Esempio n. 1
0
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()
Esempio n. 2
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()
Esempio n. 3
0
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()
Esempio n. 4
0
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)
Esempio n. 5
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()
Esempio n. 6
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()
Esempio n. 7
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
Esempio n. 8
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()
Esempio n. 9
0
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)
Esempio n. 10
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
Esempio n. 11
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)
Esempio n. 12
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.")
Esempio n. 13
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()
Esempio n. 14
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 ({} 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()
Esempio n. 15
0
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()
Esempio n. 16
0
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()
Esempio n. 17
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()
Esempio n. 18
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()
Esempio n. 19
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()
Esempio n. 20
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 ({} 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()
Esempio n. 21
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.")