예제 #1
0
파일: main.py 프로젝트: Netcondut/ipopo
def main():
    """
    Loads Qt and the framework.
    Blocks while Qt or the framework are running.
    """
    # Import the Qt bridge as late as possible, to avoid unwanted module
    # loading
    import qt_bridge

    # Load Qt
    qt_loader = qt_bridge.QtLoader()
    qt_loader.setup()

    # Prepare the framework, with iPOPO and a shell
    framework = pelix.framework.create_framework(
        ["pelix.ipopo.core", "pelix.shell.core", "pelix.shell.console", "pelix.shell.ipopo"]
    )
    context = framework.get_bundle_context()

    # Register the Qt bridge as a service
    context.register_service("qt.ui", qt_loader, {})

    # Run the framework in a new thread
    thread = threading.Thread(target=run_framework, args=(framework, qt_loader.stop))
    thread.start()

    # Run the Qt loop (blocking)
    qt_loader.loop()

    # Stop the framework (if still there)
    framework.stop()
    thread.join(1)
예제 #2
0
파일: xmpp.py 프로젝트: gitter-badger/ipopo
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()
예제 #3
0
def run_framework(framework, 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 on_stop: Method to call once the framework has stopped
    """
    try:
        # Start the framework
        context = framework.get_bundle_context()
        framework.start()

        # [...] Install bundles, instantiate components [...]
        context.install_bundle('main_frame').start()

        # Wait for the framework to stop
        framework.wait_for_stop()

    finally:
        # Stop on errors or if the framework stopped
        if on_stop is not None:
            # Notify the given method
            on_stop()
예제 #4
0
def main(args):
    """
    Entry point
    """
    # Parse arguments
    parser = argparse.ArgumentParser(
                             description="Remote Services demonstration: Chat")
    parser.add_argument("--server", action="store_true", dest="server",
                        help="Run in server mode")
    parser.add_argument("--name", action="store", dest="name",
                        help="Set the client name")
    args = parser.parse_args(args)

    # Start the framework
    framework = pelix.framework.create_framework(("pelix.ipopo.core",
                                                  "pelix.shell.core",
                                                  "pelix.shell.ipopo",
                                                  "pelix.shell.console",
                                                  "chat.constants"))
    framework.start()
    context = framework.get_bundle_context()

    # Start remote services
    start_remote_services(context)

    # Start the server
    if args.server:
        start_server(context)

    else:
        # Start the client
        start_client(context, args.name)

    # Wait for the framework to stop
    framework.wait_for_stop()
예제 #5
0
파일: xmpp.py 프로젝트: debovis/ipopo
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()
예제 #6
0
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
예제 #7
0
def load_isolate(pelix_properties,
                 state_updater_url=None,
                 looper_name=None,
                 fail_on_pdb=False):
    """
    Starts a Pelix framework, installs iPOPO and boot modules and waits for
    the framework to stop

    :param pelix_properties: Pelix framework instance properties
    :param state_updater_url: URL to access the isolate state updater
    :param looper_name: Name of the main thread loop handler
    :param fail_on_pdb: If true, ``pdb.post_mortem()`` is called if an
                        exception occurs starting the framework
    :raise Exception: All exceptions are propagated
    """
    # Give some information
    _logger.debug("Running Python %s from %s",
                  '.'.join(str(part) for part in sys.version_info),
                  sys.executable)
    _logger.debug("Starting Pelix framework with properties:\n%s",
                  pformat(pelix_properties))

    # Update Python path (if necessary)
    for key in (cohorte.PROP_HOME, cohorte.PROP_BASE):
        repo = os.path.join(pelix_properties[key], "repo")
        if repo not in sys.path:
            _logger.debug("Adding %s to Python path", repo)
            sys.path.insert(0, repo)

    # Prepare the framework
    framework = \
        pelix.framework.FrameworkFactory.get_framework(pelix_properties)

    if not looper_name:
        # Run the framework in the main thread (nothing to do)
        _run_framework(framework, state_updater_url, fail_on_pdb)
    else:
        # Get the main thread handler
        context = framework.get_bundle_context()
        looper = _get_looper(context, looper_name)
        looper.setup(sys.argv)

        # Register the looper as a service
        context.register_service(cohorte.SERVICE_LOOPER, looper, None)

        # Run the framework in a new thread
        threading.Thread(target=_safe_run_framework,
                         args=(framework, looper, state_updater_url,
                               fail_on_pdb),
                         name="framework").start()

        # Let the main thread loop
        try:
            _logger.debug("Entering main thread loop...")
            looper.loop()
            _logger.debug("Exiting main thread loop...")
        finally:
            # Stop the framework if the looper stops
            _logger.debug("Stopping the framework...")
            framework.stop()
예제 #8
0
def main(http_port, peer_name, node_name, app_id):
    """
    Runs the framework

    :param http_port: HTTP port to listen to
    :param peer_name: Name of the peer
    :param node_name: Name (also, UID) of the node hosting the peer
    :param app_id: Application ID
    """
    # Create the framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core',
         'pelix.ipopo.waiting',
         'pelix.shell.core',
         'pelix.shell.ipopo',
         'pelix.shell.console',
         'pelix.http.basic',

         # Herald core
         'herald.core',
         'herald.directory',
         'herald.shell',

         # Herald HTTP
         'herald.transports.http.directory',
         'herald.transports.http.discovery_multicast',
         'herald.transports.http.servlet',
         'herald.transports.http.transport',

         # RPC
         'pelix.remote.dispatcher',
         'pelix.remote.registry',
         'herald.remote.discovery',
         'herald.remote.herald_xmlrpc',),
        {herald.FWPROP_NODE_UID: node_name,
         herald.FWPROP_NODE_NAME: node_name,
         herald.FWPROP_PEER_NAME: peer_name,
         herald.FWPROP_APPLICATION_ID: app_id})

    # Start everything
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate components
    with use_waiting_list(context) as ipopo:
        # ... HTTP server
        ipopo.add(pelix.http.FACTORY_HTTP_BASIC, "http-server",
                  {pelix.http.HTTP_SERVICE_PORT: http_port})

        # ... HTTP reception servlet
        ipopo.add(herald.transports.http.FACTORY_SERVLET,
                  "herald-http-servlet")

        # ... HTTP multicast discovery
        ipopo.add(herald.transports.http.FACTORY_DISCOVERY_MULTICAST,
                  "herald-http-discovery-multicast")

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
예제 #9
0
    def testUseService(self):
        """
        Tests utilies.use_service()
        """
        framework = pelix.framework.create_framework([])
        framework.start()
        context = framework.get_bundle_context()

        # Try without the service reference: TypeError
        self.assertRaises(TypeError,
                          utilities.use_service(context, None).__enter__)

        # Start the service bundle
        bundle = context.install_bundle("tests.service_bundle")
        bundle.start()

        # Get the service reference
        svc_ref = context.get_service_reference(IEchoService)

        # Use it
        with utilities.use_service(context, svc_ref) as service:
            # Test the usage information
            self.assertIn(context.get_bundle(),
                          svc_ref.get_using_bundles(),
                          "Bundles using the service not updated")

            # Get the service the Pelix way
            got_service = context.get_service(svc_ref)

            # Test the service object
            self.assertIs(service, got_service, "Found a different service.")

            # Clean up the test usage
            context.unget_service(svc_ref)
            got_service = None

            # Re-test the usage information
            self.assertIn(context.get_bundle(),
                          svc_ref.get_using_bundles(),
                          "Bundles using service not kept")

        # Test the usage information
        self.assertNotIn(context.get_bundle(),
                         svc_ref.get_using_bundles(),
                         "Bundles using service kept after block")

        # Stop the iPOPO bundle
        bundle.stop()

        # Ensure the service is not accessible anymore
        self.assertRaises(pelix.constants.BundleException,
                          utilities.use_service(context, svc_ref).__enter__)

        # Uninstall the bundle
        bundle.uninstall()

        # Ensure the service is not accessible anymore
        self.assertRaises(pelix.constants.BundleException,
                          utilities.use_service(context, svc_ref).__enter__)
예제 #10
0
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
    framework = pelix.framework.create_framework((
        # iPOPO
        "pelix.ipopo.core",
        # Shell core (engine)
        "pelix.shell.core",
        # Text console
        "pelix.shell.console"))

    # Start the framework, and the pre-installed bundles
    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()

    # Start the model bundles, which provide the ml models
    context.install_bundle("gb_clf", path=model_path).start()
    context.install_bundle("lr", path=model_path).start()
    #context.install_bundle("cat_boost", path=model_path).start()

    # Start the model_consumer bundle, which provides the model consumer service.
    context.install_bundle("model_consumer", path=model_path).start()

    # Start the model bundles, which provide the ml models
    context.install_bundle("iris", path=data_path).start()
    context.install_bundle("breast_cancer", path=data_path).start()
    context.install_bundle("kyoto", path=data_path).start()
    context.install_bundle("kyoto_595_notime", path=data_path).start()
    context.install_bundle("kyoto_all", path=data_path).start()
    context.install_bundle("kyoto_notime", path=data_path).start()

    # Start the model_consumer bundle, which provides the model consumer service.
    context.install_bundle("data_consumer", path=data_path).start()

    context.install_bundle("data_bank", path=bank_path).start()

    # Start the model bundles, which provide the ml models
    context.install_bundle("accuracy_score", path=metric_path).start()
    context.install_bundle("hamming_loss", path=metric_path).start()
    context.install_bundle("attacks_50", path=metric_path).start()
    context.install_bundle("attacks_90", path=metric_path).start()
    context.install_bundle("sev_50", path=metric_path).start()
    context.install_bundle("sev_90", path=metric_path).start()

    # Start the model_consumer bundle, which provides the model consumer service.
    context.install_bundle("metric_consumer", path=metric_path).start()


    # Start the analyzer bundle, which provides a shell command
    context.install_bundle("analyzer").start()

    # Wait for the framework to stop
    framework.wait_for_stop()
예제 #11
0
    def testUseService(self):
        """
        Tests utilities.use_service()
        """
        framework = pelix.framework.create_framework([])
        framework.start()
        context = framework.get_bundle_context()

        # Try without the service reference: TypeError
        self.assertRaises(TypeError,
                          utilities.use_service(context, None).__enter__)

        # Start the service bundle
        bundle = context.install_bundle("tests.framework.service_bundle")
        bundle.start()

        # Get the service reference
        svc_ref = context.get_service_reference(IEchoService)

        # Use it
        with utilities.use_service(context, svc_ref) as service:
            # Test the usage information
            self.assertIn(context.get_bundle(),
                          svc_ref.get_using_bundles(),
                          "Bundles using the service not updated")

            # Get the service the Pelix way
            got_service = context.get_service(svc_ref)

            # Test the service object
            self.assertIs(service, got_service, "Found a different service.")

            # Clean up the test usage
            context.unget_service(svc_ref)
            got_service = None

            # Re-test the usage information
            self.assertIn(context.get_bundle(),
                          svc_ref.get_using_bundles(),
                          "Bundles using service not kept")

        # Test the usage information
        self.assertNotIn(context.get_bundle(),
                         svc_ref.get_using_bundles(),
                         "Bundles using service kept after block")

        # Stop the iPOPO bundle
        bundle.stop()

        # Ensure the service is not accessible anymore
        self.assertRaises(pelix.constants.BundleException,
                          utilities.use_service(context, svc_ref).__enter__)

        # Uninstall the bundle
        bundle.uninstall()

        # Ensure the service is not accessible anymore
        self.assertRaises(pelix.constants.BundleException,
                          utilities.use_service(context, svc_ref).__enter__)
예제 #12
0
def load_isolate(pelix_properties, state_updater_url=None,
                 looper_name=None, fail_on_pdb=False):
    """
    Starts a Pelix framework, installs iPOPO and boot modules and waits for
    the framework to stop

    :param pelix_properties: Pelix framework instance properties
    :param state_updater_url: URL to access the isolate state updater
    :param looper_name: Name of the main thread loop handler
    :param fail_on_pdb: If true, ``pdb.post_mortem()`` is called if an
                        exception occurs starting the framework
    :raise Exception: All exceptions are propagated
    """
    # Give some information
    _logger.debug("Running Python %s from %s",
                  '.'.join(str(part) for part in sys.version_info),
                  sys.executable)
    _logger.debug("Starting Pelix framework with properties:\n%s",
                  pformat(pelix_properties))

    # Update Python path (if necessary)
    for key in (cohorte.PROP_HOME, cohorte.PROP_BASE):
        repo = os.path.join(pelix_properties[key], "repo")
        if repo not in sys.path:
            _logger.debug("Adding %s to Python path", repo)
            sys.path.insert(0, repo)

    # Prepare the framework
    framework = \
        pelix.framework.FrameworkFactory.get_framework(pelix_properties)

    if not looper_name:
        # Run the framework in the main thread (nothing to do)
        _run_framework(framework, state_updater_url, fail_on_pdb)
    else:
        # Get the main thread handler
        context = framework.get_bundle_context()
        looper = _get_looper(context, looper_name)
        looper.setup(sys.argv)

        # Register the looper as a service
        context.register_service(cohorte.SERVICE_LOOPER, looper, None)

        # Run the framework in a new thread
        threading.Thread(target=_safe_run_framework,
                         args=(framework, looper,
                               state_updater_url, fail_on_pdb),
                         name="framework").start()

        # Let the main thread loop
        try:
            _logger.debug("Entering main thread loop...")
            looper.loop()
            _logger.debug("Exiting main thread loop...")
        finally:
            # Stop the framework if the looper stops
            _logger.debug("Stopping the framework...")
            framework.stop()
예제 #13
0
def main(xmpp_server, xmpp_port, peer_name, node_name, app_id,
         xmpp_jid=None, xmpp_password=None):
    """
    Runs the framework

    :param xmpp_server: Address of the XMPP server
    :param xmpp_port: Port of the XMPP server
    :param peer_name: Name of the peer
    :param node_name: Name (also, UID) of the node hosting the peer
    :param app_id: Application ID
    :param xmpp_jid: XMPP JID, None for Anonymous login
    :param xmpp_password: XMPP account password
    """
    # Create the framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core',
         'pelix.ipopo.waiting',
         'pelix.shell.core',
         'pelix.shell.ipopo',
         'pelix.shell.console',

         # Herald core
         'herald.core',
         'herald.directory',
         'herald.shell',

         # Herald XMPP
         'herald.transports.xmpp.directory',
         'herald.transports.xmpp.transport',

         # RPC
         'pelix.remote.dispatcher',
         'pelix.remote.registry',
         'herald.remote.discovery',
         'herald.remote.herald_xmlrpc',),
        {herald.FWPROP_NODE_UID: node_name,
         herald.FWPROP_NODE_NAME: node_name,
         herald.FWPROP_PEER_NAME: peer_name,
         herald.FWPROP_APPLICATION_ID: app_id})
    context = framework.get_bundle_context()

    # Start everything
    framework.start()

    # Instantiate components
    with use_waiting_list(context) as ipopo:
        # ... XMPP Transport
        ipopo.add(herald.transports.xmpp.FACTORY_TRANSPORT,
                  "herald-xmpp-transport",
                  {herald.transports.xmpp.PROP_XMPP_SERVER: xmpp_server,
                   herald.transports.xmpp.PROP_XMPP_PORT: xmpp_port,
                   herald.transports.xmpp.PROP_XMPP_JID: xmpp_jid,
                   herald.transports.xmpp.PROP_XMPP_PASSWORD: xmpp_password})

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
예제 #14
0
def main(xmpp_server, xmpp_port, peer_name, node_name, app_id,
         xmpp_jid=None, xmpp_password=None):
    """
    Runs the framework

    :param xmpp_server: Address of the XMPP server
    :param xmpp_port: Port of the XMPP server
    :param peer_name: Name of the peer
    :param node_name: Name (also, UID) of the node hosting the peer
    :param app_id: Application ID
    :param xmpp_jid: XMPP JID, None for Anonymous login
    :param xmpp_password: XMPP account password
    """
    # Create the framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core',
         'pelix.ipopo.waiting',
         'pelix.shell.core',
         'pelix.shell.ipopo',
         'pelix.shell.console',

         # Herald core
         'herald.core',
         'herald.directory',
         'herald.shell',

         # Herald XMPP
         'herald.transports.xmpp.directory',
         'herald.transports.xmpp.transport',

         # RPC
         'pelix.remote.dispatcher',
         'pelix.remote.registry',
         'herald.remote.discovery',
         'herald.remote.herald_xmlrpc',),
        {herald.FWPROP_NODE_UID: node_name,
         herald.FWPROP_NODE_NAME: node_name,
         herald.FWPROP_PEER_NAME: peer_name,
         herald.FWPROP_APPLICATION_ID: app_id})
    context = framework.get_bundle_context()

    # Start everything
    framework.start()

    # Instantiate components
    with use_waiting_list(context) as ipopo:
        # ... XMPP Transport
        ipopo.add(herald.transports.xmpp.FACTORY_TRANSPORT,
                  "herald-xmpp-transport",
                  {herald.transports.xmpp.PROP_XMPP_SERVER: xmpp_server,
                   herald.transports.xmpp.PROP_XMPP_PORT: xmpp_port,
                   herald.transports.xmpp.PROP_XMPP_JID: xmpp_jid,
                   herald.transports.xmpp.PROP_XMPP_PASSWORD: xmpp_password})

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
예제 #15
0
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()
예제 #16
0
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()
예제 #17
0
파일: remote.py 프로젝트: guillaumedc/ipopo
def main(address="localhost", port=9000):
    """
    Starts a framework with a remote shell and starts an interactive console.

    :param address: Shell binding address
    :param port: Shell binding port
    """
    from pelix.ipopo.constants import use_ipopo
    import pelix.framework

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo',
         'pelix.shell.remote'))
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate a Remote Shell
    with use_ipopo(context) as ipopo:
        rshell = ipopo.instantiate(pelix.shell.FACTORY_REMOTE_SHELL,
                                   "remote-shell", {
                                       "pelix.shell.address": address,
                                       "pelix.shell.port": port
                                   })

    # Prepare interpreter variables
    variables = {
        '__name__': '__console__',
        '__doc__': None,
        '__package__': None,
        'framework': framework,
        'context': context,
        'use_ipopo': use_ipopo
    }

    # Prepare a banner
    host, port = rshell.get_access()
    banner = "{lines}\nPython interpreter with Pelix Remote Shell\n" \
        "Remote shell bound to: {host}:{port}\n{lines}\n" \
        "Python version: {version}\n" \
        .format(lines='-' * 80, version=sys.version,
                host=host, port=port)

    try:
        # Run an interpreter
        _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
예제 #18
0
def main(args=None):
    """
    Loads Qt and the framework.
    Blocks while Qt or the framework are running.
    """
    if args is None:
        args = sys.argv[1:]

    # Get arguments
    parser = argparse.ArgumentParser(description="Pelix-Qt demo - Fake Compass")
    parser.add_argument("-p", "--port", type=int, dest="http_port",
                        default=8081, metavar="PORT",
                        help="Port of the HTTP server")
    options = parser.parse_args(args)
    http_port = options.http_port

    # Prepare the framework + iPOPO + shell)
    framework = pelix.framework.create_framework(BUNDLES)
    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.probe').start()
    context.install_bundle('utils.fake_compass').start()

    # Wait for stop then delete the framework
    framework.wait_for_stop()
예제 #19
0
def main(args=None):
    """
    Loads Qt and the framework.
    Blocks while Qt or the framework are running.
    """
    if args is None:
        args = sys.argv[1:]

    # Get arguments
    parser = argparse.ArgumentParser(description="Pelix-Qt demo")
    parser.add_argument("-p",
                        "--port",
                        type=int,
                        dest="http_port",
                        default=8080,
                        metavar="PORT",
                        help="Port of the HTTP server")
    options = parser.parse_args(args)
    http_port = options.http_port

    # Prepare Qt (import the package as late as possible)
    import core.qt
    qt_loader = core.qt.QtLoader()
    qt_loader.setup()

    # Prepare the framework + iPOPO + shell)
    framework = pelix.framework.create_framework(BUNDLES)

    # Register QtLoader as a service
    context = framework.get_bundle_context()
    context.register_service(core.SVC_QT_LOADER, qt_loader, {})

    # Run the framework in a new thread
    thread = threading.Thread(target=run_framework,
                              args=(framework, http_port, qt_loader.stop))
    thread.start()

    # Run the Qt loop (blocking)
    qt_loader.loop()

    # Stop the framework (if still there)
    framework.stop()
    thread.join(1)

    thread = None
    framework = None
    qt_loader = None
예제 #20
0
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
    framework = pelix.framework.create_framework((
        # iPOPO
        "pelix.ipopo.core",
        # Shell core (engine)
        "pelix.shell.core",
        # Text console
        "pelix.shell.console"))

    # Start the framework, and the pre-installed bundles
    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()

    # Start the spell dictionary bundles, which provide the dictionary services
    context.install_bundle("spell_dictionary_EN").start()
    context.install_bundle("spell_dictionary_FR").start()

    # Start the spell checker bundle, which provides the spell checker service.
    context.install_bundle("spell_checker").start()

    # Sample usage of the spell checker service
    # 1. get its service reference, that describes the service itself
    ref_config = context.get_service_reference("spell_checker_service")

    # 2. the use_service method allows to grab a service and to use it inside a
    # with block. It automatically releases the service when exiting the block,
    # even if an exception was raised
    with use_service(context, ref_config) as svc_config:
        # Here, svc_config points to the spell checker service
        passage = "Welcome to our framwork iPOPO"
        print("1. Testing Spell Checker:", passage)
        misspelled_words = svc_config.check(passage)
        print(">  Misspelled_words are:", misspelled_words)

    # Start the spell client bundle, which provides a shell command
    context.install_bundle("spell_client").start()

    # Wait for the framework to stop
    framework.wait_for_stop()
예제 #21
0
def main(address="localhost", port=9000):
    """
    Starts a framework with a remote shell and starts an interactive console.

    :param address: Shell binding address
    :param port: Shell binding port
    """
    from pelix.ipopo.constants import use_ipopo
    import pelix.framework

    # Start a Pelix framework
    framework = pelix.framework.create_framework(('pelix.ipopo.core',
                                                  'pelix.shell.core',
                                                  'pelix.shell.ipopo',
                                                  'pelix.shell.remote'))
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate a Remote Shell
    with use_ipopo(context) as ipopo:
        rshell = ipopo.instantiate(pelix.shell.FACTORY_REMOTE_SHELL,
                                   "remote-shell",
                                   {"pelix.shell.address": address,
                                    "pelix.shell.port": port})

    # Prepare interpreter variables
    variables = {'__name__': '__console__',
                 '__doc__': None,
                 '__package__': None,
                 'framework': framework,
                 'context': context,
                 'use_ipopo': use_ipopo}

    # Prepare a banner
    host, port = rshell.get_access()
    banner = "{lines}\nPython interpreter with Pelix Remote Shell\n" \
        "Remote shell bound to: {host}:{port}\n{lines}\n" \
        "Python version: {version}\n" \
        .format(lines='-' * 80, version=sys.version,
                host=host, port=port)

    try:
        # Run an interpreter
        _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
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
    framework = pelix.framework.create_framework((
        # iPOPO
        "pelix.ipopo.core",
        # Shell core (engine)
        "pelix.shell.core",
        # Text console
        "pelix.shell.console"))

    # Start the framework, and the pre-installed bundles
    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()

    # Start the spell dictionary bundles, which provide the dictionary services
    context.install_bundle("spell_dictionary_EN").start()
    context.install_bundle("spell_dictionary_FR").start()

    # Start the spell checker bundle, which provides the spell checker service.
    context.install_bundle("spell_checker").start()

    # Sample usage of the spell checker service
    # 1. get its service reference, that describes the service itself
    #ref_config = context.get_service_reference("spell_checker_service")

    # 2. the use_service method allows to grab a service and to use it inside a
    # with block. It automatically releases the service when exiting the block,
    # even if an exception was raised
    #with use_service(context, ref_config) as svc_config:
        # Here, svc_config points to the spell checker service
    #    passage = "Welcome to the demo. Misspelled"
    #    print("1. Testing Spell Checker:", passage)
    #    misspelled_words = svc_config.check(passage)
    #    print(">  Misspelled_words are:", misspelled_words)

    # Start the spell client bundle, which provides a shell command
    context.install_bundle("spell_client").start()

    # Wait for the framework to stop
    framework.wait_for_stop()
예제 #23
0
파일: demo.py 프로젝트: Netcondut/ipopo
def main(http_port=8080):
    """
    Entry point
    """
    # Prepare framework properties
    fw_props = {"http.port": http_port}

    # Get the framework
    _logger.info("Starting Pelix framework...")
    pause()
    framework = pelix.framework.FrameworkFactory.get_framework(fw_props)
    framework.start()

    # Install iPOPO and demo bundles
    context = framework.get_bundle_context()
    bundles = ('pelix.ipopo.core', 'http_svc', 'hello_servlet', 'extra_info')
    for bundle in bundles:
        _logger.info("Starting bundle %s...", bundle)
        context.install_bundle(bundle).start()

    _logger.info("All bundles successfully started.")

    # Get the iPOPO service
    ipopo_ref = context.get_service_reference(IPOPO_SERVICE_SPECIFICATION)
    ipopo = context.get_service(ipopo_ref)

    # Wait for user to press a key
    _logger.info("Framework is started, the hello world servlet is here : "
          "http://localhost:%d/hello", http_port)

    _logger.info("Next step will be activating the extra information component")
    pause()

    _logger.info("Instantiating extra information...")
    ipopo.instantiate("ExtraInfoFactory", "demo.extra_info_component")
    _logger.info("Look at the servlet page.")
    pause()

    _logger.info("Removing extra information...")
    ipopo.kill("demo.extra_info_component")
    _logger.info("Look at the servlet page.")
    pause()

    _logger.info("Bye !")
    framework.stop()
    pelix.framework.FrameworkFactory.delete_framework(framework)
예제 #24
0
def main(args=None):
    """
    Loads Qt and the framework.
    Blocks while Qt or the framework are running.
    """
    if args is None:
        args = sys.argv[1:]

    # Get arguments
    parser = argparse.ArgumentParser(description="Pelix-Qt demo")
    parser.add_argument("-p", "--port", type=int, dest="http_port",
                        default=8080, metavar="PORT",
                        help="Port of the HTTP server")
    options = parser.parse_args(args)
    http_port = options.http_port

    # Prepare Qt (import the package as late as possible)
    import core.qt
    qt_loader = core.qt.QtLoader()
    qt_loader.setup()

    # Prepare the framework + iPOPO + shell)
    framework = pelix.framework.create_framework(BUNDLES)

    # Register QtLoader as a service
    context = framework.get_bundle_context()
    context.register_service(core.SVC_QT_LOADER, qt_loader, {})

    # Run the framework in a new thread
    thread = threading.Thread(target=run_framework, args=(framework,
                                                          http_port,
                                                          qt_loader.stop))
    thread.start()

    # Run the Qt loop (blocking)
    qt_loader.loop()

    # Stop the framework (if still there)
    framework.stop()
    thread.join(1)

    thread = None
    framework = None
    qt_loader = None
예제 #25
0
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")
	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")
	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': '0.0.0.0',
				'pelix.http.port': 8080 
				})

	logging.info("Installing PV bundle")
	context.install_bundle("pvPanelsServlet").start()
	logging.info("PV bundle installed")

	# Wait for the framework to stop
	framework.wait_for_stop()
예제 #26
0
def main():
    framework = pelix.framework.create_framework(
        ("pelix.ipopo.core", "pelix.shell.core", "pelix.shell.console",
         "pelix.shell.ipopo"))
    framework.start()
    context = framework.get_bundle_context()

    # Games here
    context.install_bundle('game_tictactoe', './games/').start()
    # Servlets here
    context.install_bundle('servlet_index').start()
    context.install_bundle('servlet_tictactoe', './games/').start()

    context.install_bundle('pelix.http.basic').start()
    with use_ipopo(context) as ipopo:
        ipopo.instantiate('pelix.http.service.basic.factory', 'http-server', {
            'pelix.http.address': 'localhost',
            'pelix.http.port': 9000
        })

    framework.wait_for_stop()
예제 #27
0
def main():
    """
    Loads Qt and the framework.
    Blocks while Qt or the framework are running.
    """
    # Add current dir to path, so pelix can seek for modules here
    utils.Path.add_module_dir_to_path(__file__)
    utils.Path.add_module_dir_to_path(modules__file__)

    # Import the Qt bridge as late as possible, to avoid unwanted module
    # loading
    from . import qt_bridge

    # Load Qt
    qt_loader = qt_bridge.QtLoader()
    qt_loader.setup()

    # Prepare the framework, with iPOPO and a shell
    framework = pelix.framework.create_framework(['pelix.ipopo.core',
                                                  'pelix.shell.core',
                                                  'pelix.shell.ipopo'])
    context = framework.get_bundle_context()

    # Register the Qt bridge as a service
    context.register_service("qt.ui", qt_loader, {})

    # Run the framework in a new thread
    thread = threading.Thread(target=run_framework, args=(framework,
                                                          qt_loader.stop))
    thread.start()

    # Run the Qt loop (blocking)
    qt_loader.loop()

    # Stop the framework (if still there)
    framework.stop()
    thread.join(1)
예제 #28
0
파일: remote.py 프로젝트: matthieucan/ipopo
def main(argv=None):
    """
    Script entry point

    :param argv: Script arguments (None for sys.argv)
    :return: An exit code or None
    """
    # Prepare arguments
    parser = argparse.ArgumentParser(
        prog="pelix.shell.remote", parents=[make_common_parser()],
        description="Pelix Remote Shell")

    # Remote shell options
    group = parser.add_argument_group("Remote Shell options")
    group.add_argument("-a", "--address", default="localhost",
                       help="The remote shell binding address")
    group.add_argument("-p", "--port", type=int, default=9000,
                       help="The remote shell binding port")

    # Local options
    group = parser.add_argument_group("Local options")
    group.add_argument("--no-input", action="store_true",
                       help="Run without input (for daemon mode)")

    # Parse them
    args = parser.parse_args(argv)

    # Handle arguments
    init = handle_common_arguments(args)

    # Set the initial bundles
    bundles = ['pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo',
               'pelix.shell.remote']
    bundles.extend(init.bundles)

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        utilities.remove_duplicates(bundles), init.properties)
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    # Instantiate a Remote Shell, if necessary
    with use_ipopo(context) as ipopo:
        rshell_name = "remote-shell"
        try:
            ipopo.get_instance_details(rshell_name)
        except ValueError:
            # Component doesn't exist, we can instantiate it
            rshell = ipopo.instantiate(
                pelix.shell.FACTORY_REMOTE_SHELL, rshell_name,
                {"pelix.shell.address": args.address,
                 "pelix.shell.port": args.port})
        else:
            logging.error("A remote shell component (%s) is already "
                          "configured. Abandon.", rshell_name)
            return 1

    # Prepare a banner
    host, port = rshell.get_access()
    try:
        if args.no_input:
            # No input required: just print the access to the shell
            print("Remote shell bound to:", host, "- port:", port)

            try:
                while not framework.wait_for_stop(1):
                    # Awake from wait every second to let KeyboardInterrupt
                    # exception to raise
                    pass
            except KeyboardInterrupt:
                print("Got Ctrl+C: exiting.")
                return 127
        else:
            # Prepare interpreter variables
            variables = {'__name__': '__console__',
                         '__doc__': None,
                         '__package__': None,
                         'framework': framework,
                         'context': context,
                         'use_ipopo': use_ipopo}

            banner = "{lines}\nPython interpreter with Pelix Remote Shell\n" \
                     "Remote shell bound to: {host}:{port}\n{lines}\n" \
                     "Python version: {version}\n" \
                .format(lines='-' * 80, version=sys.version,
                        host=host, port=port)

            # Run an interpreter
            _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
예제 #29
0
def main(is_server, discoveries, transports, http_port, other_arguments):
    """
    Runs the framework

    :param is_server: If True, starts the provider bundle,
                      else the consumer one
    :param discoveries: List of discovery protocols
    :param transports: List of RPC protocols
    :param http_port: Port of the HTTP server
    :param other_arguments: Other arguments
    """
    # Create the framework
    framework = pelix.framework.create_framework(
        (
            'pelix.ipopo.core',
            'pelix.ipopo.waiting',
            # Shell
            'pelix.shell.core',
            'pelix.shell.ipopo',
            'pelix.shell.console',
            # HTTP Service
            "pelix.http.basic",
            # Remote Services (core)
            'pelix.remote.dispatcher',
            'pelix.remote.registry'),
        # Framework properties
        {pelix.constants.FRAMEWORK_UID: other_arguments.fw_uid})

    # Start everything
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate components
    # Get the iPOPO service
    with use_waiting_list(context) as ipopo:
        # Instantiate remote service components
        # ... HTTP server
        ipopo.add("pelix.http.service.basic.factory", "http-server",
                  {"pelix.http.port": http_port})

        # ... servlet giving access to the registry
        ipopo.add(rs.FACTORY_REGISTRY_SERVLET,
                  "pelix-remote-dispatcher-servlet")

    # Prepare the utility object
    util = InstallUtils(context, other_arguments)

    # Install the discovery bundles
    for discovery in discoveries:
        getattr(util, "discovery_{0}".format(discovery))()

    # Install the transport bundles
    for transport in transports:
        getattr(util, "transport_{0}".format(transport))()

    # Start the service provider or consumer
    if is_server:
        # ... the provider
        context.install_bundle("remote.provider").start()

    else:
        # ... or the consumer
        context.install_bundle("remote.consumer").start()

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
예제 #30
0
파일: xmpp.py 프로젝트: elrhedda/ipopo
def main(argv=None):
    """
    Entry point

    :param argv: Script arguments (None for sys.argv)
    :return: An exit code or None
    """
    # Prepare arguments
    parser = argparse.ArgumentParser(prog="pelix.shell.xmpp",
                                     parents=[make_common_parser()],
                                     description="Pelix XMPP Shell")

    group = parser.add_argument_group("XMPP options")
    group.add_argument("-j", "--jid", dest="jid", help="Jabber ID")
    group.add_argument("--password", dest="password", help="JID password")
    group.add_argument("-s",
                       "--server",
                       dest="server",
                       help="XMPP server host")
    group.add_argument("-p",
                       "--port",
                       dest="port",
                       type=int,
                       default=5222,
                       help="XMPP server port")
    group.add_argument("--tls",
                       dest="use_tls",
                       action="store_true",
                       help="Use a STARTTLS connection")
    group.add_argument("--ssl",
                       dest="use_ssl",
                       action="store_true",
                       help="Use an SSL connection")

    # Parse them
    args = parser.parse_args(argv)

    # Handle common arguments
    init = handle_common_arguments(args)

    # Quiet down the SleekXMPP logger
    if not args.verbose:
        logging.getLogger("sleekxmpp").setLevel(logging.WARNING)

    if not args.server and not args.jid:
        _logger.error("No JID nor server given. Abandon.")
        sys.exit(1)

    # Get the password if necessary
    password = args.password
    if args.jid and args.password is None:
        try:
            import getpass
        except ImportError:
            _logger.error(
                "getpass() unavailable: give a password in command line")
        else:
            try:
                password = getpass.getpass()
            except getpass.GetPassWarning:
                pass

    # Get the server from the JID, if necessary
    server = args.server
    if not server:
        server = sleekxmpp.JID(args.jid).domain

    # Set the initial bundles
    bundles = [
        'pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo',
        'pelix.shell.console', 'pelix.shell.xmpp'
    ]
    bundles.extend(init.bundles)

    # Use the utility method to create, run and delete the framework
    framework = pelix.framework.create_framework(remove_duplicates(bundles),
                                                 init.properties)
    framework.start()

    # Instantiate a Remote Shell
    with use_ipopo(framework.get_bundle_context()) as ipopo:
        ipopo.instantiate(
            pelix.shell.FACTORY_XMPP_SHELL, "xmpp-shell", {
                "shell.xmpp.server": server,
                "shell.xmpp.port": args.port,
                "shell.xmpp.jid": args.jid,
                "shell.xmpp.password": password,
                "shell.xmpp.tls": args.use_tls,
                "shell.xmpp.ssl": args.use_ssl
            })

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    try:
        framework.wait_for_stop()
    except KeyboardInterrupt:
        framework.stop()
예제 #31
0
def main(args=None):
    """
    Standalone  monitor entry point
    """
    import argparse
    if not args:
        args = sys.argv[1:]

    # Define arguments
    parser = argparse.ArgumentParser(description="Herald XMPP Monitor Bot")

    # Server configuration
    group = parser.add_argument_group("XMPP server",
                                      "Access to the XMPP server")
    group.add_argument("-s",
                       "--server",
                       action="store",
                       default="localhost",
                       dest="xmpp_server",
                       help="Host of the XMPP server")
    group.add_argument("-p",
                       "--port",
                       action="store",
                       type=int,
                       default=5222,
                       dest="xmpp_port",
                       help="Port of the XMPP server")

    # Bot account configuration
    group = parser.add_argument_group("Monitor bot account",
                                      "Definition of the bot's credentials")
    group.add_argument("--jid",
                       action="store",
                       default=None,
                       dest="jid",
                       help="Full JID to use")
    group.add_argument("--password",
                       action="store",
                       default=None,
                       dest="password",
                       help="Password associated to the JID")
    group.add_argument("--nick",
                       action="store",
                       default="HeraldMonitorBot",
                       dest="nick",
                       help="Nickname to use in chat rooms")

    # Main Room configuration
    group = parser.add_argument_group("Herald configuration")
    group.add_argument("-r",
                       "--room",
                       action="store",
                       default="herald",
                       dest="main_room",
                       help="Main chat room (XMPP MUC) to use for Herald")

    # Parse arguments
    args = parser.parse_args(args)

    # Prepare properties
    properties = {
        PROP_XMPP_SERVER: args.xmpp_server,
        PROP_XMPP_PORT: args.xmpp_port,
        PROP_MONITOR_JID: args.jid,
        PROP_MONITOR_PASSWORD: args.password,
        PROP_MONITOR_NICK: args.nick,
        PROP_XMPP_ROOM_NAME: args.main_room
    }

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo',
         'pelix.shell.console'))
    framework.start()

    context = framework.get_bundle_context()
    with use_ipopo(context) as ipopo:
        # Register the component factory
        ipopo.register_factory(context, MonitorBotWrapper)

        # Create the component
        ipopo.instantiate(FACTORY_MONITOR, 'herald-xmpp-monitor', properties)

    try:
        framework.wait_for_stop()
    except (KeyboardInterrupt, EOFError):
        framework.stop()
예제 #32
0
파일: remote.py 프로젝트: tcalmant/ipopo
def main(argv=None):
    """
    Script entry point

    :param argv: Script arguments (None for sys.argv)
    :return: An exit code or None
    """
    # Prepare arguments
    parser = argparse.ArgumentParser(
        prog="pelix.shell.remote",
        parents=[make_common_parser()],
        description="Pelix Remote Shell ({} SSL support)".format(
            "with" if ssl is not None else "without"
        ),
    )

    # Remote shell options
    group = parser.add_argument_group("Remote Shell options")
    group.add_argument(
        "-a",
        "--address",
        default="localhost",
        help="The remote shell binding address",
    )
    group.add_argument(
        "-p",
        "--port",
        type=int,
        default=9000,
        help="The remote shell binding port",
    )

    if ssl is not None:
        # Remote Shell TLS options
        group = parser.add_argument_group("TLS Options")
        group.add_argument("--cert", help="Path to the server certificate file")
        group.add_argument(
            "--key",
            help="Path to the server key file "
            "(can be omitted if the key is in the certificate)",
        )
        group.add_argument(
            "--key-password",
            help="Password of the server key."
            "Set to '-' for a password request.",
        )
        group.add_argument(
            "--ca-chain",
            help="Path to the CA chain file to authenticate clients",
        )

    # Local options
    group = parser.add_argument_group("Local options")
    group.add_argument(
        "--no-input",
        action="store_true",
        help="Run without input (for daemon mode)",
    )

    # Parse them
    args = parser.parse_args(argv)

    # Handle arguments
    init = handle_common_arguments(args)

    # Set the initial bundles
    bundles = [
        "pelix.ipopo.core",
        "pelix.shell.core",
        "pelix.shell.ipopo",
        "pelix.shell.remote",
    ]
    bundles.extend(init.bundles)

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        utilities.remove_duplicates(bundles), init.properties
    )
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    # Instantiate a Remote Shell, if necessary
    with use_ipopo(context) as ipopo:
        rshell_name = "remote-shell"
        try:
            ipopo.get_instance_details(rshell_name)
        except ValueError:
            # Component doesn't exist, we can instantiate it.

            if ssl is not None:
                # Copy parsed arguments
                ca_chain = args.ca_chain
                cert = args.cert
                key = args.key

                # Normalize the TLS key file password argument
                if args.key_password == "-":
                    import getpass

                    key_password = getpass.getpass(
                        "Password for {}: ".format(args.key or args.cert)
                    )
                else:
                    key_password = args.key_password
            else:
                # SSL support is missing:
                # Ensure the SSL arguments are defined but set to None
                ca_chain = None
                cert = None
                key = None
                key_password = None

            # Setup the component
            rshell = ipopo.instantiate(
                pelix.shell.FACTORY_REMOTE_SHELL,
                rshell_name,
                {
                    "pelix.shell.address": args.address,
                    "pelix.shell.port": args.port,
                    "pelix.shell.ssl.ca": ca_chain,
                    "pelix.shell.ssl.cert": cert,
                    "pelix.shell.ssl.key": key,
                    "pelix.shell.ssl.key_password": key_password,
                },
            )

            # Avoid loose reference to the password
            del key_password
        else:
            logging.error(
                "A remote shell component (%s) is already "
                "configured. Abandon.",
                rshell_name,
            )
            return 1

    # Prepare a banner
    host, port = rshell.get_access()
    try:
        if args.no_input:
            # No input required: just print the access to the shell
            print("Remote shell bound to:", host, "- port:", port)

            try:
                while not framework.wait_for_stop(1):
                    # Awake from wait every second to let KeyboardInterrupt
                    # exception to raise
                    pass
            except KeyboardInterrupt:
                print("Got Ctrl+C: exiting.")
                return 127
        else:
            # Prepare interpreter variables
            variables = {
                "__name__": "__console__",
                "__doc__": None,
                "__package__": None,
                "framework": framework,
                "context": context,
                "use_ipopo": use_ipopo,
            }

            banner = (
                "{lines}\nPython interpreter with Pelix Remote Shell\n"
                "Remote shell bound to: {host}:{port}\n{lines}\n"
                "Python version: {version}\n".format(
                    lines="-" * 80, version=sys.version, host=host, port=port
                )
            )

            # Run an interpreter
            _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
예제 #33
0
def main(http_port, peer_name, node_name, app_id):
    """
    Runs the framework

    :param http_port: HTTP port to listen to
    :param peer_name: Name of the peer
    :param node_name: Name (also, UID) of the node hosting the peer
    :param app_id: Application ID
    """
    # Create the framework
    framework = pelix.framework.create_framework(
        (
            'pelix.ipopo.core',
            'pelix.ipopo.waiting',
            'pelix.shell.core',
            'pelix.shell.ipopo',
            'pelix.shell.console',
            'pelix.http.basic',

            # Herald core
            'herald.core',
            'herald.directory',
            'herald.shell',

            # Herald HTTP
            'herald.transports.http.directory',
            'herald.transports.http.discovery_multicast',
            'herald.transports.http.servlet',
            'herald.transports.http.transport',

            # RPC
            'pelix.remote.dispatcher',
            'pelix.remote.registry',
            'herald.remote.discovery',
            'herald.remote.herald_xmlrpc',
        ),
        {
            herald.FWPROP_NODE_UID: node_name,
            herald.FWPROP_NODE_NAME: node_name,
            herald.FWPROP_PEER_NAME: peer_name,
            herald.FWPROP_APPLICATION_ID: app_id
        })

    # Start everything
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate components
    with use_waiting_list(context) as ipopo:
        # ... HTTP server
        ipopo.add(pelix.http.FACTORY_HTTP_BASIC, "http-server",
                  {pelix.http.HTTP_SERVICE_PORT: http_port})

        # ... HTTP reception servlet
        ipopo.add(herald.transports.http.FACTORY_SERVLET,
                  "herald-http-servlet")

        # ... HTTP multicast discovery
        ipopo.add(herald.transports.http.FACTORY_DISCOVERY_MULTICAST,
                  "herald-http-discovery-multicast")

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
예제 #34
0
def main(argv=None):
    """
    Script entry point

    :param argv: Script arguments (None for sys.argv)
    :return: An exit code or None
    """
    # Prepare arguments
    parser = argparse.ArgumentParser(
        prog="pelix.shell.remote", parents=[make_common_parser()],
        description="Pelix Remote Shell")

    # Remote shell options
    group = parser.add_argument_group("Remote Shell options")
    group.add_argument("-a", "--address", default="localhost",
                       help="The remote shell binding address")
    group.add_argument("-p", "--port", type=int, default=9000,
                       help="The remote shell binding port")

    # Local options
    group = parser.add_argument_group("Local options")
    group.add_argument("--no-input", action="store_true",
                       help="Run without input (for daemon mode)")

    # Parse them
    args = parser.parse_args(argv)

    # Handle arguments
    init = handle_common_arguments(args)

    # Set the initial bundles
    bundles = ['pelix.ipopo.core', 'pelix.shell.core', 'pelix.shell.ipopo',
               'pelix.shell.remote']
    bundles.extend(init.bundles)

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        utilities.remove_duplicates(bundles), init.properties)
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    # Instantiate a Remote Shell, if necessary
    with use_ipopo(context) as ipopo:
        rshell_name = "remote-shell"
        try:
            ipopo.get_instance_details(rshell_name)
        except ValueError:
            # Component doesn't exist, we can instantiate it
            rshell = ipopo.instantiate(
                pelix.shell.FACTORY_REMOTE_SHELL, rshell_name,
                {"pelix.shell.address": args.address,
                 "pelix.shell.port": args.port})
        else:
            logging.error("A remote shell component (%s) is already "
                          "configured. Abandon.", rshell_name)
            return 1

    # Prepare a banner
    host, port = rshell.get_access()
    try:
        if args.no_input:
            # No input required: just print the access to the shell
            print("Remote shell bound to:", host, "- port:", port)

            try:
                while not framework.wait_for_stop(1):
                    # Awake from wait every second to let KeyboardInterrupt
                    # exception to raise
                    pass
            except KeyboardInterrupt:
                print("Got Ctrl+C: exiting.")
                return 127
        else:
            # Prepare interpreter variables
            variables = {'__name__': '__console__',
                         '__doc__': None,
                         '__package__': None,
                         'framework': framework,
                         'context': context,
                         'use_ipopo': use_ipopo}

            banner = "{lines}\nPython interpreter with Pelix Remote Shell\n" \
                     "Remote shell bound to: {host}:{port}\n{lines}\n" \
                     "Python version: {version}\n" \
                .format(lines='-' * 80, version=sys.version,
                        host=host, port=port)

            # Run an interpreter
            _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
예제 #35
0
def _run_framework(framework, state_updater_url, fail_on_pdb):
    """
    Starts the framework

    :param framework: An instance of framework
    :param state_updater_url: URL to access the isolate state updater
    :param fail_on_pdb: If true, ``pdb.post_mortem()`` is called if an
                        exception occurs starting the framework
    :raise Exception: All exceptions are propagated
    """
    try:
        context = framework.get_bundle_context()
        framework.start()

        # Install & start configuration bundles
        for name in MINIMAL_BUNDLES:
            _logger.debug('Installing bundle %s...', name)
            bundle = context.install_bundle(name)
            bundle.start()
            _logger.debug('Bundle %s (%d) started',
                          name, bundle.get_bundle_id())

        # Install the text UI if requested. It still needs the Shell Core
        # service to be usable
        if context.get_property(cohorte.PROP_SHELL_CONSOLE):
            _logger.debug("Installing the Pelix Shell UI "
                          "(requires pelix.shell.core to work)")
            context.install_bundle("pelix.shell.console").start()

        # Find the isolate loader to use
        if context.get_property(cohorte.PROP_CONFIG_BROKER):
            # If a broker has been given, use the Broker client...
            loader_bundle_name = 'cohorte.boot.loaders.broker'
        else:
            # ... else use the ForkerLoader
            loader_bundle_name = 'cohorte.boot.loaders.forker'

        # Install & start the loader bundle
        _logger.debug("Using isolate loader: %s.", loader_bundle_name)
        loader_bundle = context.install_bundle(loader_bundle_name)
        loader_bundle.start()

        # Retrieve the loader service & load the isolate
        loader = _get_loader(context, loader_bundle)
        _logger.debug("Isolate booting...")

        # Prepare the access to the state updater
        loader.prepare_state_updater(state_updater_url)
        loader.update_state(constants.STATE_LOADING)

        try:
            # Load the isolate
            loader.load(None)
        except Exception as ex:
            # Something wrong occurred
            loader.update_state(constants.STATE_FAILED, str(ex))
            raise
        else:
            # Isolate loaded
            loader.update_state(constants.STATE_LOADED)
            _logger.debug("Isolate loaded.")

        # Wait forever for the framework to stop
        _logger.debug("Waiting for the isolate to stop...")
        try:
            loader.wait()
        except KeyboardInterrupt:
            # Stop waiting on keyboard interruption
            _logger.debug("Got keyboard interruption, stopping.")

        # Ensure the framework is stopped
        framework.stop()
        _logger.debug("Framework stopped.")
    except Exception as ex:
        _logger.exception(ex)
        _logger.error('Error running the isolate: %s', ex)
        if fail_on_pdb:
            # Start PDB to debug the exception
            import pdb
            pdb.post_mortem()
        else:
            # Propagate the exception
            raise
    finally:
        # Delete the framework (clean up)
        pelix.framework.FrameworkFactory.delete_framework(framework)
        _logger.debug("Framework deleted.")
예제 #36
0
파일: remote.py 프로젝트: pisua/yblues
def main(argv=None):
    """
    Script entry point

    :param argv: Script arguments (None for sys.argv)
    :return: An exit code or None
    """
    # Prepare arguments
    parser = argparse.ArgumentParser(
        prog="pelix.shell.remote",
        parents=[make_common_parser()],
        description="Pelix Remote Shell ({} SSL support)".format(
            "with" if ssl is not None else "without"),
    )

    # Remote shell options
    group = parser.add_argument_group("Remote Shell options")
    group.add_argument(
        "-a",
        "--address",
        default="localhost",
        help="The remote shell binding address",
    )
    group.add_argument(
        "-p",
        "--port",
        type=int,
        default=9000,
        help="The remote shell binding port",
    )

    if ssl is not None:
        # Remote Shell TLS options
        group = parser.add_argument_group("TLS Options")
        group.add_argument(
            "--cert", help="Path to the ycappuccino_core certificate file")
        group.add_argument(
            "--key",
            help="Path to the ycappuccino_core key file "
            "(can be omitted if the key is in the certificate)",
        )
        group.add_argument(
            "--key-password",
            help="Password of the ycappuccino_core key."
            "Set to '-' for a password request.",
        )
        group.add_argument(
            "--ca-chain",
            help="Path to the CA chain file to authenticate clients",
        )

    # Local options
    group = parser.add_argument_group("Local options")
    group.add_argument(
        "--no-input",
        action="store_true",
        help="Run without input (for daemon mode)",
    )

    # Parse them
    args = parser.parse_args(argv)

    # Handle arguments
    init = handle_common_arguments(args)

    # Set the initial bundles
    bundles = [
        "pelix.ipopo.core",
        "pelix.shell.core",
        "pelix.shell.ipopo",
        "pelix.shell.remote",
    ]
    bundles.extend(init.bundles)

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        utilities.remove_duplicates(bundles), init.properties)
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    # Instantiate a Remote Shell, if necessary
    with use_ipopo(context) as ipopo:
        rshell_name = "remote-shell"
        try:
            ipopo.get_instance_details(rshell_name)
        except ValueError:
            # Component doesn't exist, we can instantiate it.

            if ssl is not None:
                # Copy parsed arguments
                ca_chain = args.ca_chain
                cert = args.cert
                key = args.key

                # Normalize the TLS key file password argument
                if args.key_password == "-":
                    import getpass

                    key_password = getpass.getpass("Password for {}: ".format(
                        args.key or args.cert))
                else:
                    key_password = args.key_password
            else:
                # SSL support is missing:
                # Ensure the SSL arguments are defined but set to None
                ca_chain = None
                cert = None
                key = None
                key_password = None

            # Setup the component
            rshell = ipopo.instantiate(
                pelix.shell.FACTORY_REMOTE_SHELL,
                rshell_name,
                {
                    "pelix.shell.address": args.address,
                    "pelix.shell.port": args.port,
                    "pelix.shell.ssl.ca": ca_chain,
                    "pelix.shell.ssl.cert": cert,
                    "pelix.shell.ssl.key": key,
                    "pelix.shell.ssl.key_password": key_password,
                },
            )

            # Avoid loose reference to the password
            del key_password
        else:
            logging.error(
                "A remote shell component (%s) is already "
                "configured. Abandon.",
                rshell_name,
            )
            return 1

    # Prepare a banner
    host, port = rshell.get_access()
    try:
        if args.no_input:
            # No input required: just print the access to the shell
            print("Remote shell bound to:", host, "- port:", port)

            try:
                while not framework.wait_for_stop(1):
                    # Awake from wait every second to let KeyboardInterrupt
                    # exception to raise
                    pass
            except KeyboardInterrupt:
                print("Got Ctrl+C: exiting.")
                return 127
        else:
            # Prepare interpreter variables
            variables = {
                "__name__": "__console__",
                "__doc__": None,
                "__package__": None,
                "framework": framework,
                "context": context,
                "use_ipopo": use_ipopo,
            }

            banner = ("{lines}\nPython interpreter with Pelix Remote Shell\n"
                      "Remote shell bound to: {host}:{port}\n{lines}\n"
                      "Python version: {version}\n".format(lines="-" * 80,
                                                           version=sys.version,
                                                           host=host,
                                                           port=port))

            # Run an interpreter
            _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
예제 #37
0
파일: xmpp.py 프로젝트: tcalmant/ipopo
def main(argv=None):
    """
    Entry point

    :param argv: Script arguments (None for sys.argv)
    :return: An exit code or None
    """
    # Prepare arguments
    parser = argparse.ArgumentParser(
        prog="pelix.shell.xmpp",
        parents=[make_common_parser()],
        description="Pelix XMPP Shell",
    )

    group = parser.add_argument_group("XMPP options")
    group.add_argument("-j", "--jid", dest="jid", help="Jabber ID")
    group.add_argument("--password", dest="password", help="JID password")
    group.add_argument("-s", "--server", dest="server", help="XMPP server host")
    group.add_argument(
        "-p",
        "--port",
        dest="port",
        type=int,
        default=5222,
        help="XMPP server port",
    )
    group.add_argument(
        "--tls",
        dest="use_tls",
        action="store_true",
        help="Use a STARTTLS connection",
    )
    group.add_argument(
        "--ssl",
        dest="use_ssl",
        action="store_true",
        help="Use an SSL connection",
    )

    # Parse them
    args = parser.parse_args(argv)

    # Handle common arguments
    init = handle_common_arguments(args)

    # Quiet down the SleekXMPP logger
    if not args.verbose:
        logging.getLogger("sleekxmpp").setLevel(logging.WARNING)

    if not args.server and not args.jid:
        _logger.error("No JID nor server given. Abandon.")
        sys.exit(1)

    # Get the password if necessary
    password = args.password
    if args.jid and args.password is None:
        try:
            import getpass
        except ImportError:
            _logger.error(
                "getpass() unavailable: give a password in command line"
            )
        else:
            try:
                password = getpass.getpass()
            except getpass.GetPassWarning:
                pass

    # Get the server from the JID, if necessary
    server = args.server
    if not server:
        server = sleekxmpp.JID(args.jid).domain

    # Set the initial bundles
    bundles = [
        "pelix.ipopo.core",
        "pelix.shell.core",
        "pelix.shell.ipopo",
        "pelix.shell.console",
        "pelix.shell.xmpp",
    ]
    bundles.extend(init.bundles)

    # Use the utility method to create, run and delete the framework
    framework = pelix.framework.create_framework(
        remove_duplicates(bundles), init.properties
    )
    framework.start()

    # Instantiate a Remote Shell
    with use_ipopo(framework.get_bundle_context()) as ipopo:
        ipopo.instantiate(
            pelix.shell.FACTORY_XMPP_SHELL,
            "xmpp-shell",
            {
                "shell.xmpp.server": server,
                "shell.xmpp.port": args.port,
                "shell.xmpp.jid": args.jid,
                "shell.xmpp.password": password,
                "shell.xmpp.tls": args.use_tls,
                "shell.xmpp.ssl": args.use_ssl,
            },
        )

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    try:
        framework.wait_for_stop()
    except KeyboardInterrupt:
        framework.stop()
예제 #38
0
def main(args=None):
    """
    Standalone  monitor entry point
    """
    import argparse
    if not args:
        args = sys.argv[1:]

    # Define arguments
    parser = argparse.ArgumentParser(description="Herald XMPP Monitor Bot")

    # Server configuration
    group = parser.add_argument_group("XMPP server",
                                      "Access to the XMPP server")
    group.add_argument("-s", "--server", action="store", default="localhost",
                       dest="xmpp_server", help="Host of the XMPP server")
    group.add_argument("-p", "--port", action="store", type=int, default=5222,
                       dest="xmpp_port", help="Port of the XMPP server")

    # Bot account configuration
    group = parser.add_argument_group("Monitor bot account",
                                      "Definition of the bot's credentials")
    group.add_argument("--jid", action="store", default=None,
                       dest="jid", help="Full JID to use")
    group.add_argument("--password", action="store", default=None,
                       dest="password", help="Password associated to the JID")
    group.add_argument("--nick", action="store", default="HeraldMonitorBot",
                       dest="nick", help="Nickname to use in chat rooms")

    # Main Room configuration
    group = parser.add_argument_group("Herald configuration")
    group.add_argument("-r", "--room", action="store",
                       default="herald", dest="main_room",
                       help="Main chat room (XMPP MUC) to use for Herald")

    # Parse arguments
    args = parser.parse_args(args)

    # Prepare properties
    properties = {
        PROP_XMPP_SERVER: args.xmpp_server,
        PROP_XMPP_PORT: args.xmpp_port,
        PROP_MONITOR_JID: args.jid,
        PROP_MONITOR_PASSWORD: args.password,
        PROP_MONITOR_NICK: args.nick,
        PROP_XMPP_ROOM_NAME: args.main_room
    }

    # Start a Pelix framework
    framework = pelix.framework.create_framework(('pelix.ipopo.core',
                                                  'pelix.shell.core',
                                                  'pelix.shell.ipopo',
                                                  'pelix.shell.console'))
    framework.start()

    context = framework.get_bundle_context()
    with use_ipopo(context) as ipopo:
        # Register the component factory
        ipopo.register_factory(context, MonitorBotWrapper)

        # Create the component
        ipopo.instantiate(FACTORY_MONITOR, 'herald-xmpp-monitor', properties)

    try:
        framework.wait_for_stop()
    except (KeyboardInterrupt, EOFError):
        framework.stop()
예제 #39
0
def main(is_server, discoveries, transports, http_port, other_arguments):
    """
    Runs the framework

    :param is_server: If True, starts the provider bundle,
                      else the consumer one
    :param discoveries: List of discovery protocols
    :param transports: List of RPC protocols
    :param http_port: Port of the HTTP server
    :param other_arguments: Other arguments
    """
    # Create the framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core',
         'pelix.ipopo.waiting',
         # Shell
         'pelix.shell.core',
         'pelix.shell.ipopo',
         'pelix.shell.console',
         # HTTP Service
         "pelix.http.basic",
         # Remote Services (core)
         'pelix.remote.dispatcher',
         'pelix.remote.registry'),
        # Framework properties
        {pelix.constants.FRAMEWORK_UID: other_arguments.fw_uid})

    # Start everything
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate components
    # Get the iPOPO service
    with use_waiting_list(context) as ipopo:
        # Instantiate remote service components
        # ... HTTP server
        ipopo.add("pelix.http.service.basic.factory", "http-server",
                  {"pelix.http.address": "0.0.0.0",
                   "pelix.http.port": http_port})

        # ... servlet giving access to the registry
        ipopo.add(rs.FACTORY_REGISTRY_SERVLET,
                  "pelix-remote-dispatcher-servlet")

    # Prepare the utility object
    util = InstallUtils(context, other_arguments)

    # Install the discovery bundles
    for discovery in discoveries:
        getattr(util, "discovery_{0}".format(discovery))()

    # Install the transport bundles
    for transport in transports:
        getattr(util, "transport_{0}".format(transport))()

    # Start the service provider or consumer
    if is_server:
        # ... the provider
        context.install_bundle("remote.provider").start()

    else:
        # ... or the consumer
        context.install_bundle("remote.consumer").start()

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
예제 #40
0
def _run_framework(framework, state_updater_url, fail_on_pdb):
    """
    Starts the framework

    :param framework: An instance of framework
    :param state_updater_url: URL to access the isolate state updater
    :param fail_on_pdb: If true, ``pdb.post_mortem()`` is called if an
                        exception occurs starting the framework
    :raise Exception: All exceptions are propagated
    """
    try:
        context = framework.get_bundle_context()
        framework.start()

        # Install & start configuration bundles
        for name in MINIMAL_BUNDLES:
            _logger.debug('Installing bundle %s...', name)
            bundle = context.install_bundle(name)
            bundle.start()
            _logger.debug('Bundle %s (%d) started', name,
                          bundle.get_bundle_id())

        # Install the text UI if requested. It still needs the Shell Core
        # service to be usable
        if context.get_property(cohorte.PROP_SHELL_CONSOLE):
            _logger.debug("Installing the Pelix Shell UI "
                          "(requires pelix.shell.core to work)")
            context.install_bundle("pelix.shell.console").start()

        # Find the isolate loader to use
        if context.get_property(cohorte.PROP_CONFIG_BROKER):
            # If a broker has been given, use the Broker client...
            loader_bundle_name = 'cohorte.boot.loaders.broker'
        else:
            # ... else use the ForkerLoader
            loader_bundle_name = 'cohorte.boot.loaders.forker'

        # Install & start the loader bundle
        _logger.debug("Using isolate loader: %s.", loader_bundle_name)
        loader_bundle = context.install_bundle(loader_bundle_name)
        loader_bundle.start()

        # Retrieve the loader service & load the isolate
        loader = _get_loader(context, loader_bundle)
        _logger.debug("Isolate booting...")

        # Prepare the access to the state updater
        loader.prepare_state_updater(state_updater_url)
        loader.update_state(constants.STATE_LOADING)

        try:
            # Load the isolate
            loader.load(None)
        except Exception as ex:
            # Something wrong occurred
            loader.update_state(constants.STATE_FAILED, str(ex))
            raise
        else:
            # Isolate loaded
            loader.update_state(constants.STATE_LOADED)
            _logger.debug("Isolate loaded.")

        # Wait forever for the framework to stop
        _logger.debug("Waiting for the isolate to stop...")
        try:
            loader.wait()
        except KeyboardInterrupt:
            # Stop waiting on keyboard interruption
            _logger.debug("Got keyboard interruption, stopping.")

        # Ensure the framework is stopped
        framework.stop()
        _logger.debug("Framework stopped.")
    except Exception as ex:
        _logger.exception(ex)
        _logger.error('Error running the isolate: %s', ex)
        if fail_on_pdb:
            # Start PDB to debug the exception
            import pdb
            pdb.post_mortem()
        else:
            # Propagate the exception
            raise
    finally:
        # Delete the framework (clean up)
        pelix.framework.FrameworkFactory.delete_framework(framework)
        _logger.debug("Framework deleted.")