Example #1
0
def parse_args(args=None):
    parser = argparse.ArgumentParser(
        description='Lightbus management command.')
    subparsers = parser.add_subparsers(help='Commands', dest='subcommand')
    subparsers.required = True

    parser_run = subparsers.add_parser(
        'run',
        help='Run Lightbus',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser_run_action_group = parser_run.add_mutually_exclusive_group()
    parser_run_action_group.add_argument(
        '--events-only',
        help='Run Lightbus, but only listen for and handle events',
        action='store_true')
    parser_run_action_group.add_argument(
        '--rpcs-only',
        help='Run Lightbus, but only consume and handle RPCs',
        action='store_true')
    parser_run_action_group.add_argument(
        '--import',
        dest='imprt',
        help='The Python module to import initially. If omited ')
    parser_run.set_defaults(func=command_run)

    parser_run_transport_group = parser_run.add_argument_group(
        title='Transport options')
    parser_run_transport_group.add_argument(
        '--rpc-transport',
        help='RPC transport class to use',
        default='lightbus.RedisRpcTransport')
    parser_run_transport_group.add_argument(
        '--result-transport',
        help='Result transport class to use',
        default='lightbus.RedisResultTransport')
    parser_run_transport_group.add_argument(
        '--event-transport',
        help='Event transport class to use',
        default='lightbus.RedisEventTransport')

    autoload_plugins()
    block(plugin_hook('before_parse_args',
                      parser=parser,
                      subparsers=subparsers),
          timeout=5)

    # parser_run_connection_group = parser_run.add_argument_group(title='Connection options')
    # parser_run_connection_group.add_argument(
    #     '--redis-url', help='URL to Redis server when using Redis-based transports', default='redis://localhost:6379/0'
    # )

    args = parser.parse_args(sys.argv[1:] if args is None else args)
    block(plugin_hook('after_parse_args', args=args), timeout=5)

    return args
Example #2
0
def parse_args(args=None):
    parser = argparse.ArgumentParser(
        description="Lightbus management command.")
    parser.add_argument(
        "--service-name",
        "-s",
        help="Name of service in which this process resides. YOU SHOULD "
        "LIKELY SET THIS IN PRODUCTION. Can also be set using the "
        "LIGHTBUS_SERVICE_NAME environment. Will default to a random string.",
    )
    parser.add_argument(
        "--process-name",
        "-p",
        help=
        "A unique name of this process within the service. Can also be set using the "
        "LIGHTBUS_PROCESS_NAME environment. Will default to a random string.",
    )
    parser.add_argument("--config",
                        dest="config_file",
                        help="Config file to load, JSON or YAML",
                        metavar="FILE")
    parser.add_argument(
        "--log-level",
        help="Set the log level. Overrides any value set in config. "
        "One of debug, info, warning, critical, exception.",
        metavar="LOG_LEVEL",
    )

    subparsers = parser.add_subparsers(help="Commands", dest="subcommand")
    subparsers.required = True

    lightbus.commands.run.Command().setup(parser, subparsers)
    lightbus.commands.shell.Command().setup(parser, subparsers)
    lightbus.commands.dump_schema.Command().setup(parser, subparsers)
    lightbus.commands.dump_schema.Command().setup(parser, subparsers)
    lightbus.commands.dump_config_schema.Command().setup(parser, subparsers)

    autoload_plugins(config=Config.load_dict({}))

    loop = get_event_loop()
    block(plugin_hook("before_parse_args",
                      parser=parser,
                      subparsers=subparsers),
          loop,
          timeout=5)
    args = parser.parse_args(sys.argv[1:] if args is None else args)
    # Note that we don't have an after_parse_args plugin hook. Instead we use the receive_args
    # hook which is called once we have instantiated our plugins

    return args
def test_autoload_plugins():
    assert get_plugins() == OrderedDict()
    assert autoload_plugins()
    assert [(name, p.__class__) for name, p in get_plugins().items()] == [
        ('internal_state', StatePlugin),
        ('internal_metrics', MetricsPlugin),
    ]
Example #4
0
def test_autoload_plugins():
    config = Config.load_dict({})
    assert get_plugins() is None
    assert autoload_plugins(config)
    assert [(name, p.__class__) for name, p in get_plugins().items()] == [
        ("internal_state", StatePlugin),
        ("internal_metrics", MetricsPlugin),
    ]
Example #5
0
def test_plugin_enabled():
    config = Config.load_dict({
        "plugins": {
            "internal_state": {
                "enabled": True
            },
            "internal_metrics": {
                "enabled": True
            }
        }
    })
    plugins = autoload_plugins(config)
    assert plugins
Example #6
0
    def setup(self, plugins: dict=None):
        """Setup lightbus and get it ready to consume events and/or RPCs

        You should call this manually if you are calling `consume_rpcs()` or
        `consume_events()` directly. This you be handled for you if you are
        calling `run_forever()`.
        """
        if plugins is None:
            logger.debug("Auto-loading any installed Lightbus plugins...")
            plugins = autoload_plugins()
        else:
            logger.debug("Loading explicitly specified Lightbus plugins....")
            manually_set_plugins(plugins)

        if plugins:
            logger.info(LBullets("Loaded the following plugins ({})".format(len(plugins)), items=plugins))
        else:
            logger.info("No plugins loaded")
Example #7
0
    async def setup_async(self, plugins: dict = None):
        """Setup lightbus and get it ready to consume events and/or RPCs

        You should call this manually if you are calling `consume_rpcs()`
        directly. This you be handled for you if you are
        calling `run_forever()`.
        """
        logger.info(
            LBullets(
                "Lightbus is setting up",
                items={
                    "service_name (set with -s or LIGHTBUS_SERVICE_NAME)":
                    Bold(self.config.service_name),
                    "process_name (with with -p or LIGHTBUS_PROCESS_NAME)":
                    Bold(self.config.process_name),
                },
            ))

        # Log the transport information
        rpc_transport = self.transport_registry.get_rpc_transport("default",
                                                                  default=None)
        result_transport = self.transport_registry.get_result_transport(
            "default", default=None)
        event_transport = self.transport_registry.get_event_transport(
            "default", default=None)
        log_transport_information(rpc_transport, result_transport,
                                  event_transport,
                                  self.schema.schema_transport, logger)

        # Log the plugins we have
        if plugins is None:
            logger.debug("Auto-loading any installed Lightbus plugins...")
            # Force auto-loading as many commands need to do config-less best-effort
            # plugin loading. But now we have the config loaded so we can
            # make sure we load the plugins properly.
            plugins = autoload_plugins(self.config, force=True)
        else:
            logger.debug("Loading explicitly specified Lightbus plugins....")
            manually_set_plugins(plugins)

        if plugins:
            logger.info(
                LBullets("Loaded the following plugins ({})".format(
                    len(plugins)),
                         items=plugins))
        else:
            logger.info("No plugins loaded")

        # Load schema
        logger.debug("Loading schema...")
        await self.schema.load_from_bus()

        # Share the schema of the registered APIs
        for api in registry.all():
            await self.schema.add_api(api)

        logger.info(
            LBullets(
                "Loaded the following remote schemas ({})".format(
                    len(self.schema.remote_schemas)),
                items=self.schema.remote_schemas.keys(),
            ))

        for transport in self.transport_registry.get_all_transports():
            await transport.open()