daemon: Improve importing custom services.

This should help avoid python module name conflicts.
This commit is contained in:
Tom Goff 2017-02-24 00:20:57 +00:00
parent 56896bddd1
commit 67117a3af3

View file

@ -15,6 +15,7 @@ services.
''' '''
import sys, os, shlex import sys, os, shlex
import imp
from itertools import repeat from itertools import repeat
from core.api import coreapi from core.api import coreapi
@ -47,9 +48,8 @@ class CoreServices(ConfigurableManager):
_name = "services" _name = "services"
_type = coreapi.CORE_TLV_REG_UTILITY _type = coreapi.CORE_TLV_REG_UTILITY
_invalid_custom_names = ('core', 'addons', 'api', 'bsd', 'emane', 'misc', service_path = set()
'netns', 'phys', 'services', 'xen')
def __init__(self, session): def __init__(self, session):
ConfigurableManager.__init__(self, session) ConfigurableManager.__init__(self, session)
# dict of default services tuples, key is node type # dict of default services tuples, key is node type
@ -65,23 +65,34 @@ class CoreServices(ConfigurableManager):
self.importcustom(path) self.importcustom(path)
self.isStartupService = startup.Startup.isStartupService self.isStartupService = startup.Startup.isStartupService
@classmethod
def add_service_path(cls, path):
cls.service_path.add(path)
def importcustom(self, path): def importcustom(self, path):
''' Import services from a myservices directory. ''' Import services from a myservices directory.
''' '''
if not path or len(path) == 0: if not path or path in self.service_path:
return return
if not os.path.isdir(path): if not os.path.isdir(path):
self.session.warn("invalid custom service directory specified" \ self.session.warn("invalid custom service directory specified" \
": %s" % path) ": %s" % path)
return return
self.add_service_path(path)
try: try:
parentdir, childdir = os.path.split(path) parentdir, childdir = os.path.split(path)
if childdir in self._invalid_custom_names: f, pathname, description = imp.find_module(childdir, [parentdir])
raise ValueError, "use a unique custom services dir name, " \ name = 'core.services.custom.' + childdir
"not '%s'" % childdir if name in sys.modules:
if not parentdir in sys.path: i = 1
sys.path.append(parentdir) while name + str(i) in sys.modules:
exec("from %s import *" % childdir) i += 1
name += str(i)
m = imp.load_module(name, f, pathname, description)
if hasattr(m, '__all__'):
for x in m.__all__:
f, pathname, description = imp.find_module(x, [path])
imp.load_module(name + '.' + x, f, pathname, description)
except Exception, e: except Exception, e:
self.session.warn("error importing custom services from " \ self.session.warn("error importing custom services from " \
"%s:\n%s" % (path, e)) "%s:\n%s" % (path, e))