2 Runtime container for running components.
5 from Component import Component
7 from utils import logging
13 class Container(Component):
15 Runtime container for running components.
16 The Container loads and instantiates components.
19 def __init__(self, paths, whitelist = []):
21 @param paths: paths where to look for components
24 self.__components = []
26 self.__whitelist = whitelist
28 Component.__init__(self)
31 if (os.path.exists(p)):
34 for c in self.__components:
35 self.emit_message(msgs.COM_EV_COMPONENT_LOADED, c)
37 for dev in self.__devices:
38 self.emit_message(msgs.CORE_EV_DEVICE_ADDED, dev.get_device_id(), dev)
42 def __find_modules(self, path):
44 Returns a list of the modules of all components under the given path.
49 dirs = os.listdir(path)
51 # a module called "core" gets loaded first
54 dirs = ["core"] + dirs
57 comppath = os.path.join(path, f)
58 if (not os.path.isdir(comppath) or f.startswith(".")):
61 elif (self.__whitelist and not f in self.__whitelist and f != "core"):
62 logging.info("not loading component: %s", f)
65 mod = self.__load_module(comppath)
73 def __load_module(self, path):
75 Loads and returns the module from the given path. Returns None if
76 the module could not be loaded.
80 sys.path = [os.path.dirname(path)] + syspath
83 mod = __import__(os.path.basename(path))
84 mod._syspath = os.path.dirname(path)
88 logging.error("could not load component [%s]:\n%s" \
89 % (path, logging.stacktrace()))
94 def __register_messages(self, mod):
96 Registers the messages of the given module.
99 if (hasattr(mod, "messages")):
100 for msg in mod.messages:
101 logging.debug("registering message: %s", msg)
106 def __load_components(self, mod):
108 Loads the components of the given module.
111 syspath = sys.path[:]
112 sys.path = [mod._syspath] + syspath
114 logging.debug("loading module [%s]", mod.__file__)
117 classes = mod.get_classes()
118 except AttributeError:
121 logging.error(logging.stacktrace())
126 logging.debug("creating [%s]" % c.__name__)
128 #comp._attach_to_message_bus()
129 self.__components.append(comp)
132 logging.error("could not instantiate class [%s]:\n%s" %
133 (`c`, logging.stacktrace()))
137 device_classes = mod.get_devices()
138 except AttributeError:
141 logging.error(logging.stacktrace())
144 for c in device_classes:
146 logging.debug("adding device [%s]" % c.__name__)
148 #comp._attach_to_message_bus()
149 self.__devices.append(comp)
152 logging.error("could not instantiate class [%s]:\n%s" %
153 (`c`, logging.stacktrace()))
162 def load_path(self, path):
164 Loads all components from the given path.
166 @param path: path of components directory
169 #self.__components = []
172 mods = self.__find_modules(path)
174 self.__register_messages(mod)
176 self.emit_message(msgs.COM_EV_LOADING_MODULE, mod.__name__)
177 self.__load_components(mod)