def test_hidden_instantiate(self): """ Tests the value of hidden properties given as instantiation parameters """ context = self.framework.get_bundle_context() # Prepare random values hidden_value = random.randint(0, 100) public_value = random.randint(0, 100) # Instantiate the component with use_ipopo(context) as ipopo: svc = ipopo.instantiate(self.module.FACTORY_HIDDEN_PROPS, NAME_A, { "hidden.prop": hidden_value, "public.prop": public_value }) # Check default values (and accesses) self.assertEqual(svc.hidden, hidden_value) self.assertEqual(svc.public, public_value) # Check instance details with use_ipopo(context) as ipopo: details = ipopo.get_instance_details(NAME_A) self.assertNotIn("hidden.prop", details["properties"])
def test_hidden_instantiate(self): """ Tests the value of hidden properties given as instantiation parameters """ context = self.framework.get_bundle_context() # Prepare random values hidden_value = random.randint(0, 100) public_value = random.randint(0, 100) # Instantiate the component with use_ipopo(context) as ipopo: svc = ipopo.instantiate(self.module.FACTORY_HIDDEN_PROPS, NAME_A, {"hidden.prop": hidden_value, "public.prop": public_value}) # Check default values (and accesses) self.assertEqual(svc.hidden, hidden_value) self.assertEqual(svc.public, public_value) # Check instance details with use_ipopo(context) as ipopo: details = ipopo.get_instance_details(NAME_A) self.assertNotIn("hidden.prop", details["properties"])
def testConstantContext(self): """ Tests ipopo.constants.use_ipopo() """ # Try without the bundle self.assertRaises(pelix.BundleException, constants.use_ipopo(self.context).__enter__) # Start the iPOPO bundle bundle = self.context.install_bundle("pelix.ipopo.core") bundle.start() # Get the iPOPO service reference # (the only one registered in this bundle) ipopo_ref = bundle.get_registered_services()[0] # Use it with constants.use_ipopo(self.context) as ipopo: # Test the usage information self.assertIn(self.context.get_bundle(), ipopo_ref.get_using_bundles(), "Bundles using iPOPO not updated") # Get the service the Pelix way ipopo_svc = self.context.get_service(ipopo_ref) # Test the service object self.assertIs(ipopo, ipopo_svc, "Found a different service.") # Clean up the test usage self.context.unget_service(ipopo_ref) ipopo_svc = None # Re-test the usage information self.assertIn(self.context.get_bundle(), ipopo_ref.get_using_bundles(), "Bundles using iPOPO not kept") # Test the usage information self.assertNotIn(self.context.get_bundle(), ipopo_ref.get_using_bundles(), "Bundles using iPOPO kept after block") # Stop the iPOPO bundle bundle.stop() # Ensure the service is not accessible anymore self.assertRaises(pelix.BundleException, constants.use_ipopo(self.context).__enter__) # Uninstall the bundle bundle.uninstall() # Ensure the service is not accessible anymore self.assertRaises(pelix.BundleException, constants.use_ipopo(self.context).__enter__)
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match (-1 for the trailing space) match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1) # Sort matching names matches = sorted(match for match in matches) # Print the match and the associated name session.write_line() with use_ipopo(context) as ipopo: for factory_name in matches: # Remove the spaces added for the completion factory_name = factory_name.strip() bnd = ipopo.get_factory_bundle(factory_name) session.write_line(match_pattern, factory_name, bnd.get_symbolic_name()) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
def register_factory( self, component_class: type, factory_name: str, service_names: Union[List[str], str], properties: dict = None, ) -> type: """ Registers provided class as iPOPO component factory. :param component_class: the class of the components that will be provided by the factory :param factory_name: the name of the factory :param service_names: the service(s) that will be provided by the components :param properties: the properties associated to the factory :return: the input class, amended by iPOPO :raise FastDuplicateFactoryError: """ obj = Provides(service_names)(component_class) with use_ipopo(self.context) as ipopo: if ipopo.is_registered_factory(factory_name): raise FastDuplicateFactoryError(factory_name) if properties: for key, value in properties.items(): obj = Property(field="_" + self._fieldify(key), name=key, value=value)(obj) factory = ComponentFactory(factory_name)(obj) # Now factory is registered, ensure its bundle is installed and started self.context.install_bundle(component_class.__module__).start() return factory
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of component factories with use_ipopo(context) as ipopo: return [ "{} ".format(name) for name, _, _ in ipopo.get_instances() if name.startswith(current) ]
def main(): """ Runs the framework """ # Create the framework fw = create_framework( ('pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo', 'pelix.shell.console', 'dataclass_bundle')) # Start the framework and wait for it to stop fw.start() # Register a service ctx = fw.get_bundle_context() test_svc = object() ctx.register_service("dataclass.check", test_svc, {}) # Start components with use_ipopo(ctx) as ipopo: before = ipopo.instantiate("dataclass.before", "before", {}) after = ipopo.instantiate("dataclass.after", "after", {}) print("CHECK 'before' injection:", before.requirement is test_svc) print("CHECK 'after' injection:", after.requirement is test_svc) print("before:") print(repr(before)) print() print("after:") print(repr(after)) fw.wait_for_stop()
def remove(self, component): # type: (str) -> None """ Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component """ with self.__lock: # Find its factory factory = self.__names.pop(component) components = self.__queue[factory] # Clear the queue del components[component] if not components: # No more component for this factory del self.__queue[factory] # Kill the component try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now ipopo.kill(component) except (BundleException, ValueError): # iPOPO not yet started or component not instantiated pass
def load_framework(transport, components): """ Starts a Pelix framework in the local process :param transport: Name of the transport bundle to install :param components: Tuples (factory, name) of instances to start """ all_bundles = [ 'pelix.ipopo.core', 'pelix.http.basic', 'pelix.remote.dispatcher', 'pelix.remote.registry', 'pelix.remote.discovery.multicast', transport ] # Start the framework framework = create_framework(all_bundles) framework.start() with use_ipopo(framework.get_bundle_context()) as ipopo: # Start a HTTP service on a random port ipopo.instantiate(pelix.http.FACTORY_HTTP_BASIC, "http-server", {pelix.http.HTTP_SERVICE_PORT: 0}) ipopo.instantiate(pelix.remote.FACTORY_REGISTRY_SERVLET, "dispatcher-servlet", {pelix.http.HTTP_SERVICE_PORT: 0}) # Start the multicast discovery ipopo.instantiate(pelix.remote.FACTORY_DISCOVERY_MULTICAST, "multicast-discovery") # Start other components for factory, name in components: ipopo.instantiate(factory, name) return framework
def main(server, port, jid=None, password=None, use_tls=False, use_ssl=False): """ Starts a framework with a remote shell and starts an interactive console. :param server: XMPP server host :param port: XMPP server port :param jid: Shell JID :param password: Shell JID password :param use_tls: Use STARTTLS :param use_ssl: Use an SSL connection """ # Start a Pelix framework framework = pelix.framework.create_framework(('pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo', 'pelix.shell.console', 'pelix.shell.xmpp')) framework.start() context = framework.get_bundle_context() # Instantiate a Remote Shell with use_ipopo(context) as ipopo: ipopo.instantiate(pelix.shell.FACTORY_XMPP_SHELL, "xmpp-shell", {"shell.xmpp.server": server, "shell.xmpp.port": port, "shell.xmpp.jid": jid, "shell.xmpp.password": password, "shell.xmpp.tls": use_tls, "shell.xmpp.ssl": use_ssl}) try: framework.wait_for_stop() except KeyboardInterrupt: # Stop server on interruption framework.stop()
def _setup_bridge(self, event_filter, mqtt_prefix): """ Instantiates the MQTT Event Admin bridge :param event_filter: Filter on EventAdmin topics :param mqtt_prefix: Prefix to use in MQTT topics """ context = self.framework.get_bundle_context() context.install_bundle("pelix.services.eventadmin_mqtt").start() name = "mqtt-bridge" with use_ipopo(context) as ipopo: ipopo.instantiate( pelix.services.FACTORY_EVENT_ADMIN_MQTT, "mqtt-bridge", {pelix.services.PROP_EVENT_TOPICS: event_filter, "mqtt.host": self.HOST, "mqtt.port": self.PORT, "mqtt.topic.prefix": mqtt_prefix} ) # Wait for it svc_ref = None while svc_ref is None: svc_ref = context.get_service_reference( pelix.services.SERVICE_EVENT_HANDLER, "(instance.name={})".format(name))
def main(server, port, jid=None, password=None, use_tls=False, use_ssl=False): """ Starts a framework with a remote shell and starts an interactive console. :param server: XMPP server host :param port: XMPP server port :param jid: Shell JID :param password: Shell JID password :param use_tls: Use STARTTLS :param use_ssl: Use an SSL connection """ # Start a Pelix framework framework = pelix.framework.create_framework( ('pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo', 'pelix.shell.console', 'pelix.shell.xmpp')) framework.start() context = framework.get_bundle_context() # Instantiate a Remote Shell with use_ipopo(context) as ipopo: ipopo.instantiate( pelix.shell.FACTORY_XMPP_SHELL, "xmpp-shell", { "shell.xmpp.server": server, "shell.xmpp.port": port, "shell.xmpp.jid": jid, "shell.xmpp.password": password, "shell.xmpp.tls": use_tls, "shell.xmpp.ssl": use_ssl }) try: framework.wait_for_stop() except KeyboardInterrupt: # Stop server on interruption framework.stop()
def load_framework(app_id, transport, components): """ Starts a Pelix framework in the local process :param app_id: Application ID :param transport: Name of the transport bundle to install :param components: Tuples (factory, name) of instances to start """ all_bundles = ['pelix.ipopo.core', 'pelix.remote.dispatcher', 'pelix.remote.registry', 'pelix.remote.discovery.mqtt', transport] # Start the framework framework = create_framework(all_bundles) framework.start() with use_ipopo(framework.get_bundle_context()) as ipopo: # Start the MQTT discovery ipopo.instantiate(pelix.remote.FACTORY_DISCOVERY_MQTT, "mqtt-discovery", {"mqtt.host": MQTT_SERVER, "application.id": app_id}) # Start other components for factory, name in components: ipopo.instantiate(factory, name, {"mqtt.host": MQTT_SERVER}) return framework
def testLifeCycle(self): """ Tests the instantiation of a components """ with use_ipopo(self.framework.get_bundle_context()) as ipopo: # Instantiate a dummy component (from test.ipopo.ipopo_bundle) factory = "ipopo.tests.a" name = "component-shell-test" # Check if we're clear self.assertFalse(ipopo.is_registered_instance(name)) # Instantiate the component self._run_command("instantiate {0} {1}", factory, name) # Check that the component is instantiated self.assertTrue(ipopo.is_registered_instance(name)) # Instantiate it a second time (no exception must raise) self._run_command("instantiate {0} {1}", factory, name) # Kill it self._run_command("kill {0}", name) # Check that it is dead self.assertFalse(ipopo.is_registered_instance(name)) # Kill it a second time (no exception must raise) self._run_command("kill {0}", name)
def test_bundle(self): """ Tests the detection of the calling bundle """ # Install a test bundle context = self.framework.get_bundle_context() bnd = context.install_bundle("tests.misc.log_bundle") module = bnd.get_module() bnd.start() # Instantiate a test component with use_ipopo(context) as ipopo: comp = ipopo.instantiate(module.SIMPLE_FACTORY, "test.log", {}) # Log something comp.log(logging.WARNING, "Some log") # Check the bundle latest = self.service.get_log()[-1] self.assertIs(latest.bundle, bnd, "Wrong bundle found") # Check if the bundle in the string representation self.assertIn(bnd.get_symbolic_name(), str(latest)) # Remove the name of the module comp.remove_name() # Log something comp.log(logging.WARNING, "Some log") # Check the bundle latest = self.service.get_log()[-1] self.assertIsNone(latest.bundle, "Wrong bundle found")
def testHandlerInheritance(self): """ Tests the inheritance of handlers """ # Register factories context = self.framework.get_bundle_context() with use_ipopo(context) as ipopo: for factory in (ChildAll, ChildNoProvides, ChildExtendProvides, ChildReplaceProvides): ipopo.register_factory(context, factory) # Check behavior of "child all" component = ipopo.instantiate(FACTORY_ALL, 'all', {}) self.assertProvides(SPEC_PARENT, component) self.assertNotProvides(SPEC_CHILD, component) # No service provided component = ipopo.instantiate(FACTORY_NO_PROVIDE, 'no_service', {}) self.assertNotProvides(SPEC_PARENT, component) self.assertNotProvides(SPEC_CHILD, component) # Service replaced component = ipopo.instantiate(FACTORY_REPLACE_PROVIDE, 'replacement', {}) self.assertNotProvides(SPEC_PARENT, component) self.assertProvides(SPEC_CHILD, component) # Service added component = ipopo.instantiate(FACTORY_EXTEND_PROVIDE, 'addition', {}) self.assertProvides(SPEC_PARENT, component) self.assertProvides(SPEC_CHILD, component)
def setUp(self): """ Prepares a framework and a registers a service to export """ # Create the framework self.framework = pelix.framework.create_framework( ["pelix.ipopo.core", "pelix.shell.core", "pelix.rsa.shell", "pelix.http.basic", "pelix.rsa.remoteserviceadmin", "pelix.rsa.providers.distribution.xmlrpc"], {"ecf.xmlrpc.server.hostname": "localhost"}) self.framework.start() # Start an HTTP server, required by XML-RPC context = self.framework.get_bundle_context() with use_ipopo(context) as ipopo: ipopo.instantiate( 'pelix.http.service.basic.factory', 'http-server', {'pelix.http.address': 'localhost', 'pelix.http.port': 0}) # Get the shell service svc_ref = context.get_service_reference(SERVICE_SHELL) self.shell = context.get_service(svc_ref)
def test_unsigned_client(self): """ Tests connection with an unsigned client """ # Get the path of the server certificates ca_chain = os.path.join(TMP_DIR, "ca.crt") srv_cert = os.path.join(TMP_DIR, "server.crt") srv_key = os.path.join(TMP_DIR, "server.key") client_cert = os.path.join(TMP_DIR, "client_other.crt") client_key = os.path.join(TMP_DIR, "client.key") # Start the remote shell context = self.framework.get_bundle_context() with use_ipopo(context) as ipopo: self.remote = ipopo.instantiate( FACTORY_REMOTE_SHELL, "remoteShell", {'pelix.shell.address': '127.0.0.1', 'pelix.shell.port': 9000, 'pelix.shell.ssl.ca': ca_chain, 'pelix.shell.ssl.cert': srv_cert, 'pelix.shell.ssl.key': srv_key}) # Create a client client = TLSShellClient( self.remote.get_ps1(), self.fail, client_cert, client_key) try: self.assertRaises( ssl.SSLError, client.connect, self.remote.get_access()) finally: client.close()
def add(self, factory, component, properties=None): # type: (str, str, dict) -> None """ Enqueues the instantiation of the given component :param factory: Factory name :param component: Component name :param properties: Component properties :raise ValueError: Component name already reserved in the queue :raise Exception: Error instantiating the component """ with self.__lock: if component in self.__names: raise ValueError( "Component name already queued: {0}".format(component)) # Normalize properties if properties is None: properties = {} # Store component description self.__names[component] = factory self.__queue.setdefault(factory, {})[component] = properties try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass
def handle_ipopo_event(self, event): # type: (IPopoEvent) -> None """ Handles an iPOPO event :param event: iPOPO event bean """ kind = event.get_kind() if kind == IPopoEvent.REGISTERED: # A factory has been registered try: with use_ipopo(self.__context) as ipopo: factory = event.get_factory_name() with self.__lock: # Copy the list of components names for this factory components = self.__queue[factory].copy() for component in components: self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass except KeyError: # No components for this new factory pass
def main(): """ Starts a Pelix framework and waits for it to stop """ # Prepare the framework, with iPOPO and the shell console # Warning: we only use the first argument of this method, a list of bundles logging.info("Preparing framework") print("Preparing framework") framework = pelix.framework.create_framework(( "pelix.ipopo.core", # iPOPO "pelix.shell.core", # Shell core (engine) # "pelix.shell.console",# Text console "pelix.shell.remote", "pelix.http.basic", )) # Start the framework, and the pre-installed bundles logging.info("Starting framework") print("Starting framework") framework.start() # Get the bundle context of the framework, i.e. the link between the # framework starter and its content. context = framework.get_bundle_context() context.add_framework_stop_listener(StopListener()) with use_ipopo(context) as ipopo: ipopo.instantiate(pelix.shell.FACTORY_REMOTE_SHELL, 'remote-shell', {}) ipopo.instantiate('pelix.http.service.basic.factory', 'http-server', { 'pelix.http.address': '192.168.1.101', # TODO Utiliser un fichier de conf 'pelix.http.port': 3737 # TODO Utiliser un fichier de conf }) logging.info("Installing PV bundle") print("Installing PV bundle") context.install_bundle("pvPanelsServlet").start() logging.info("PV bundle installed") print("PV bundle installed") cad = pifacecad.PiFaceCAD() while True: cad.lcd.clear() cad.lcd.cursor_off() cad.lcd.blink_off() cad.lcd.backlight_off() co2 = get_co2_value() cad.lcd.write("IP:{}\n".format(run_cmd(GET_IP_CMD)[:-1])) cad.lcd.write("CO2:" + co2 + "\n") # TODO Utiliser les interruptions pour capter l'appui if cad.switches[4].value == 1: cad.lcd.backlight_on() sleep(5) # TODO Utiliser une variable + fichier de conf
def remove(self, component): """ Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component """ with self.__lock: # Find its factory factory = self.__names.pop(component) components = self.__queue[factory] # Clear the queue del components[component] if not components: # No more component for this factory del self.__queue[factory] # Kill the component try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now ipopo.kill(component) except (BundleException, ValueError): # iPOPO not yet started or component not instantiated pass
def testInvalidConfiguration(self): """ Tests the instantiation of the remote shell with invalid port """ import logging logging.basicConfig(level=logging.DEBUG) with use_ipopo(self.framework.get_bundle_context()) as ipopo: # Check invalid ports for port in (-1, 100000, '-100', '65536', 'Abc', None): remote = ipopo.instantiate(FACTORY_REMOTE_SHELL, "remoteShell_test", {'pelix.shell.port': port}) # Check that the port is in a valid range self.assertGreater(remote.get_access()[1], 0) self.assertLess(remote.get_access()[1], 65536) ipopo.kill("remoteShell_test") # Check empty addresses for address in (None, ''): remote = ipopo.instantiate(FACTORY_REMOTE_SHELL, "remoteShell_test", {'pelix.shell.address': address, 'pelix.shell.port': 0}) # Check that the address has been selected anyway self.assertTrue(remote.get_access()[0]) ipopo.kill("remoteShell_test")
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match (-1 for the trailing space) match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1) # Sort matching names matches = sorted(match for match in matches) # Print the match and the associated name session.write_line() with use_ipopo(context) as ipopo: for factory_name in matches: # Remove the spaces added for the completion factory_name = factory_name.strip() bnd = ipopo.get_factory_bundle(factory_name) session.write_line( match_pattern, factory_name, bnd.get_symbolic_name() ) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
def testInvalidConfiguration(self): """ Tests the instantiation of the remote shell with invalid port """ import logging logging.basicConfig(level=logging.DEBUG) with use_ipopo(self.framework.get_bundle_context()) as ipopo: # Check invalid ports for port in (-1, 100000, '-100', '65536', 'Abc', None): remote = ipopo.instantiate(FACTORY_REMOTE_SHELL, "remoteShell_test", {'pelix.shell.port': port}) # Check that the port is in a valid range self.assertGreater(remote.get_access()[1], 0) self.assertLess(remote.get_access()[1], 65536) ipopo.kill("remoteShell_test") # Check empty addresses for address in (None, ''): remote = ipopo.instantiate(FACTORY_REMOTE_SHELL, "remoteShell_test", { 'pelix.shell.address': address, 'pelix.shell.port': 0 }) # Check that the address has been selected anyway self.assertTrue(remote.get_access()[0]) ipopo.kill("remoteShell_test")
def handle_ipopo_event(self, event): """ Handles an iPOPO event :param event: iPOPO event bean """ kind = event.get_kind() if kind == IPopoEvent.REGISTERED: # A factory has been registered try: with use_ipopo(self.__context) as ipopo: factory = event.get_factory_name() with self.__lock: # Copy the list of components names for this factory components = self.__queue[factory].copy() for component in components: self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass except KeyError: # No components for this new factory pass
def setUp(self): """ Prepares a framework and a registers a service to export """ # Create the framework self.framework = pelix.framework.create_framework( ["pelix.ipopo.core", "pelix.http.basic", "pelix.rsa.remoteserviceadmin", "pelix.rsa.providers.distribution.xmlrpc"], {"ecf.xmlrpc.server.hostname": "localhost"}) self.framework.start() # Get the RSA service context = self.framework.get_bundle_context() self.rsa = context.get_service( context.get_service_reference( rsa.SERVICE_REMOTE_SERVICE_ADMIN)) # type: rsa.RemoteServiceAdminImpl # Start an HTTP server, required by XML-RPC with use_ipopo(context) as ipopo: ipopo.instantiate( 'pelix.http.service.basic.factory', 'http-server', {'pelix.http.address': 'localhost', 'pelix.http.port': 0})
def testPrinter(self): """ Tests the topics filtering """ # Start the printer with use_ipopo(self.framework.get_bundle_context()) as ipopo: ipopo.instantiate(pelix.misc.FACTORY_EVENT_ADMIN_PRINTER, "evtPrinter", {pelix.services.PROP_EVENT_TOPICS: '/titi/*', 'evt.log': True, 'evt.print': True}) # Send events, with a matching topic for topic in ('/titi/toto', '/titi/', '/titi/toto/tata'): # Clear the log I/O self.log_io.truncate(0) # Send the event self.eventadmin.send(topic) # Check the log output = self.log_io.getvalue() self.assertIn(topic, output) # Send events, with a non-matching topic for topic in ('/toto/titi/42', '/titi', '/toto/42'): # Clear the log I/O self.log_io.truncate(0) # Send the event self.eventadmin.send(topic) # Check the log output = self.log_io.getvalue() self.assertNotIn(topic, output)
def register_factory( self, component_class: Type[T], factory_name: str, service_names: Union[List[str], str], properties: dict = None, ) -> Type[T]: """ Registers provided class as iPOPO component factory. :param component_class: the class of the components that will be provided by the factory :param factory_name: the name of the factory :param service_names: the service(s) that will be provided by the components :param properties: the properties associated to the factory :return: the input class, amended by iPOPO :raise FastDuplicateFactoryError: """ obj = Provides(service_names)(component_class) with use_ipopo(self.context) as ipopo: if ipopo.is_registered_factory(factory_name): raise FastBundleLoaderDuplicateFactoryError(factory_name) if properties: for key, value in properties.items(): obj = Property(field="_" + self._fieldify(key), name=key, value=value)(obj) factory = ComponentFactory(factory_name)(obj) return factory
def testDualRemoteShell(self): """ Tests with a second remote shell component """ # Start the remote shell, on a random port with use_ipopo(self.framework.get_bundle_context()) as ipopo: remote_2 = ipopo.instantiate(FACTORY_REMOTE_SHELL, "remoteShell_2", {'pelix.shell.address': '127.0.0.1', 'pelix.shell.port': 0}) # Accesses should be different self.assertNotEqual(self.remote.get_access(), remote_2.get_access()) # Create clients client_1 = ShellClient(self.remote.get_banner(), self.remote.get_ps1(), self.fail) client_2 = ShellClient(remote_2.get_banner(), remote_2.get_ps1(), self.fail) # Connect them to the remote shell client_1.connect(self.remote.get_access()) client_2.connect(remote_2.get_access()) try: for command in ('bl', 'bd 0', 'sl', 'sd 1'): # Get clients outputs client_1_output = client_1.run_command(command) client_2_output = client_2.run_command(command) # Compare them self.assertEqual(client_1_output, client_2_output) finally: # Close the client in any case client_1.close() client_2.close()
def add(self, factory, component, properties=None): """ Enqueues the instantiation of the given component :param factory: Factory name :param component: Component name :param properties: Component properties :raise ValueError: Component name already reserved in the queue :raise Exception: Error instantiating the component """ with self.__lock: if component in self.__names: raise ValueError("Component name already queued: {0}" .format(component)) # Normalize properties if properties is None: properties = {} # Store component description self.__names[component] = factory self.__queue.setdefault(factory, {})[component] = properties try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass
def service_changed(self, event): """ Handles an event about the iPOPO service """ kind = event.get_kind() if kind == ServiceEvent.REGISTERED: # iPOPO service registered: register to factory events with use_ipopo(self.__context) as ipopo: ipopo.add_listener(self)
def test_hidden_default(self): """ Tests the hidden property """ context = self.framework.get_bundle_context() # Instantiate the component with use_ipopo(context) as ipopo: svc = ipopo.instantiate(self.module.FACTORY_HIDDEN_PROPS, NAME_A) # Check default values (and accesses) self.assertEqual(svc.hidden, "hidden") self.assertEqual(svc.public, "public") # Check instance details with use_ipopo(context) as ipopo: details = ipopo.get_instance_details(NAME_A) self.assertNotIn("hidden.prop", details["properties"])
def instantiate_components(self, context): """ Instantiate the defined components :param context: A :class:`~pelix.framework.BundleContext` object :raise BundleException: Error starting a component """ with use_ipopo(context) as ipopo: for name, (factory, properties) in self.__state.components.items(): ipopo.instantiate(factory, name, properties)
def run_framework(framework, http_port, on_stop): """ Handles Pelix framework starting and main loop. Waits for the framework to stop before stopping Qt and returning. This method should be executed in a new thread. :param framework: The Pelix framework to run :param http_port: Port the HTTP server will listen on :param on_stop: Method to call once the framework has stopped """ try: # Start the framework context = framework.get_bundle_context() framework.start() # Instantiate components... with use_ipopo(context) as ipopo: # EventAdmin ipopo.instantiate("pelix-services-eventadmin-factory", "pelix-services-eventadmin", {}) # HTTP Service ipopo.instantiate("pelix.http.service.basic.factory", "pelix.http.service.basic", {"pelix.http.port": http_port}) # Remote services ipopo.instantiate("pelix-remote-dispatcher-servlet-factory", "pelix-remote-dispatcher-servlet", {}) ipopo.instantiate("pelix-jsonrpc-exporter-factory", "pelix-jsonrpc-exporter", {}) ipopo.instantiate("pelix-jsonrpc-importer-factory", "pelix-jsonrpc-importer", {}) ipopo.instantiate("pelix-remote-discovery-multicast-factory", "pelix-remote-discovery-multicast", {}) # Install other bundles context.install_bundle("core.bridges").start() context.install_bundle("core.frame").start() context.install_bundle('core.framework_info').start() context.install_bundle('core.probe').start() bundles, _ = context.install_package('./details') for bundle in bundles: bundle.start() # Wait for stop then delete the framework framework.wait_for_stop() finally: # Notify that the framework has stopped if on_stop is not None: on_stop()
def get_factory_properties(self, factory_name: str) -> dict: """ :param factory_name: :return: properties of the factory """ with use_ipopo(self.context) as ipopo: details = ipopo.get_factory_details(factory_name) properties = details["properties"] return properties
def get_factory_path(self, factory_name: str) -> str: """ :param factory_name: :return: path of the file where the factory is defined """ with use_ipopo(self.context) as ipopo: details = ipopo.get_factory_details(factory_name) bundle: Bundle = details["bundle"] return bundle.get_location()
def ipopo_factories(self): """ List of iPOPO factories """ try: with use_ipopo(self.__context) as ipopo: return {name: ipopo.get_factory_details(name) for name in ipopo.get_factories()} except BundleException: # iPOPO is not available: return None
def testInvalidInstantiate(self): """ Tests invalid parameters to instantiate and kill """ with use_ipopo(self.framework.get_bundle_context()) as ipopo: # Bad factory name self._run_command("instantiate <badfactory> good_name") self.assertFalse(ipopo.is_registered_instance('good_name')) # Bad component name self._run_command("kill <bad_component>")
def ipopo_instances(self): """ List of iPOPO instances """ try: with use_ipopo(self.__context) as ipopo: return {instance[0]: ipopo.get_instance_details(instance[0]) for instance in ipopo.get_instances()} except BundleException: # iPOPO is not available: return None
def get_factory_details(self, factory_name: str) -> Dict[str, Any]: """ :param factory_name: name of the factory :return: factory details as in iPOPO :raise FastBundleLoaderUnknownFactoryNameError: unknown factory name """ with use_ipopo(self.context) as ipopo: try: return ipopo.get_factory_details(factory_name) except ValueError as exc: raise FastBundleLoaderUnknownFactoryNameError(factory_name) from exc
def boot_load(context, boot_config): """ Utility method to do the common isolate boot operations, i.e. applies the properties, install the bundles and finally instantiate the components indicated in the given boot configuration. :param context: The bundle context to use to install bundles :param boot_config: The boot configuration :raise BundleException: Error installing a bundle :raise Exception: Unknown error while instantiating components """ logger = logging.getLogger(__name__ + "::boot_load") framework = context.get_bundle(0) # Set up framework properties, if possible for key, value in boot_config.properties.items(): if not framework.add_property(key, value): current = context.get_property(key) if current != value: logger.debug( "Couldn't set the property %r to %r (current: %r)", key, value, current) # Load Forker bundles for bundle in boot_config.bundles: try: # Install & start it context.install_bundle(bundle.name).start() except pelix.framework.BundleException as ex: if bundle.optional: logger.exception(ex) # The error can be ignored logger.info("Error installing bundle '%s': %s", bundle.name, ex) else: # Fatal error raise if boot_config.composition: # Instantiate iPOPO components, if any with constants.use_ipopo(context) as ipopo: for component in boot_config.composition: # If not indicated, tell iPOPO to restart this component after # bundle update if constants.IPOPO_AUTO_RESTART not in component.properties: component.properties[constants.IPOPO_AUTO_RESTART] = True # Instantiate the component ipopo.instantiate(component.factory, component.name, component.properties) else: logger.debug("No component to instantiate")
def _install_importer(self): """ Installs the service importer :return: The Importer component instance """ context = self.framework.get_bundle_context() with use_ipopo(context) as ipopo: # Register the factory ipopo.register_factory(context, Importer) # Instantiate the component return ipopo.instantiate(TEST_IMPORTER_FACTORY, "importer", {})