Exemplo n.º 1
0
 def from_zookeeper_host(cls, zookeeper_host):
     config = {
         'container': {
             'registry': zookeeper_host,
         }
     }
     return cls(Client.from_config(config))
Exemplo n.º 2
0
Arquivo: tail.py Projeto: lnenov/lymph
    def run(self):
        client = Client.from_config(self.config)
        tail = RemoteTail()

        for address in self.args['<address>']:
            connected = tail.subscribe_service(client.container.lookup(address))
            if not connected:
                print("Couldn't connect to log endpoint of '%s'" % address)

        if not tail.instances:
            return 1

        level = get_loglevel(self.args['--level'])
        logger = logging.getLogger('lymph-tail-cli')
        logger.setLevel(level)

        console = logging.StreamHandler()
        console.setLevel(level)
        console.setFormatter(logging.Formatter('[%(service_type)s][%(identity)s] [%(levelname)s] %(message)s'))

        logger.addHandler(console)

        try:
            for topic, instance, msg in tail:
                level = getattr(logging, topic)
                extra = {
                    'identity': instance.identity[:10],
                    'service_type': instance.endpoint,
                }
                logger.log(level, msg, extra=extra)
        except KeyboardInterrupt:
            pass
Exemplo n.º 3
0
    def run(self):
        params = self.args.get('<params>')
        if params == '-':
            params = sys.stdin.read()
        body = json.loads(params)
        try:
            timeout = float(self.args.get('--timeout'))
        except ValueError:
            print("--timeout requires a number (e.g. --timeout=0.42)")
            return 1
        subject = self.args['<subject>']
        address = self.args.get('--address')
        if not address:
            address = subject.split('.', 1)[0]

        client = Client.from_config(self.config)

        def request():
            trace.set_id(self.args.get('--trace-id'))
            return client.request(address, subject, body, timeout=timeout)

        N, C = int(self.args['-N']), int(self.args['-C'])

        if N == 1:
            return self._run_one_request(request)
        else:
            return self._run_many_requests(request, N, C)
Exemplo n.º 4
0
 def change_loglevel(self, address, logger, level, period):
     client = Client.from_config(self.config)
     body = {"qualname": logger, "loglevel": level, "period": period}
     service = client.container.lookup(address)
     print("Changing logger '%s' of '%s' to '%s' for a period of %s seconds" % (logger, address, level, period))
     for instance in service:
         client.request(instance.endpoint, "lymph.change_loglevel", body)
Exemplo n.º 5
0
Arquivo: emit.py Projeto: torte/lymph
    def run(self):
        event_type = self.args.get('<event-type>')
        body = json.loads(self.args.get('<body>'))

        trace.set_id(self.args.get('--trace-id'))
        client = Client.from_config(self.config)
        client.emit(event_type, body)
Exemplo n.º 6
0
    def run(self):
        if self.args.get('--only-running'):
            sys.stderr.write("\n--only-running is deprecated (it's now the default)\n\n")
        client = Client.from_config(self.config)

        name = self.args.get('<name>')
        if name:
            services = {name}
            self.args['--instances'] = True
        else:
            services = client.container.discover()

        instances = {}
        for interface_name in services:
            service = client.container.lookup(interface_name)
            if not service and not self.args.get('--all'):
                continue
            instances[interface_name] = service

        if self.args.get('--json'):
            print(json.dumps({
                name: [instance.serialize() for instance in service] for name, service in instances.items()
            }))
        else:
            self.print_human_readable_output(instances)
Exemplo n.º 7
0
Arquivo: emit.py Projeto: 1-Hash/lymph
    def run(self):
        event_type = self.args.get("<event-type>")
        body = json.loads(self.args.get("<body>"))

        trace.set_id(self.args.get("--trace-id"))
        client = Client.from_config(self.config)
        client.emit(event_type, body)
Exemplo n.º 8
0
    def run(self):
        if self.args.get('--only-running'):
            sys.stderr.write(
                "\n--only-running is deprecated (it's now the default)\n\n")
        client = Client.from_config(self.config)

        name = self.args.get('<name>')
        if name:
            services = {name}
            self.args['--instances'] = True
        else:
            services = client.container.discover()

        instances = {}
        for interface_name in services:
            service = client.container.lookup(interface_name)
            if not service and not self.args.get('--all'):
                continue
            instances[interface_name] = service

        if self.args.get('--json'):
            print(
                json.dumps({
                    name: [instance.serialize() for instance in service]
                    for name, service in instances.items()
                }))
        else:
            self.print_human_readable_output(instances)
Exemplo n.º 9
0
Arquivo: shell.py Projeto: torte/lymph
    def run(self, **kwargs):
        self.client = Client.from_config(self.config)

        service_fullname = self.args.get('--remote')
        if service_fullname:
            return self._open_remote_shell(service_fullname)
        else:
            return self._open_local_shell()
Exemplo n.º 10
0
    def run(self, **kwargs):
        self.client = Client.from_config(self.config)

        service_fullname = self.args.get('--remote')
        if service_fullname:
            return self._open_remote_shell(service_fullname)
        else:
            return self._open_local_shell()
Exemplo n.º 11
0
    def run(self):
        event_type = self.args.get('<event-type>')

        class Subscriber(lymph.Interface):
            @lymph.event(*event_type)
            def on_event(self, event):
                print('%s: %r' % (event.evt_type, event.body))

        client = Client.from_config(self.config, interface_cls=Subscriber)
        client.container.join()
Exemplo n.º 12
0
 def run(self):
     client = Client.from_config(self.config)
     for service_type in sorted(client.container.discover()):
         p = client.container.lookup('lymph://%s' % service_type)
         print("%s [%s]" % (self.terminal.red(service_type), len(p)))
         if self.args.get('--instances'):
             instances = sorted(p, key=lambda d: d.identity)
             for i, d in enumerate(p):
                 prefix = u'└─' if i == len(instances) - 1 else u'├─'
                 print(u'%s [%s] %s' % (prefix, d.identity[:10], d.endpoint))
Exemplo n.º 13
0
 def run(self, **kwargs):
     client = Client.from_config(self.config, **kwargs)
     body = json.loads(self.args.get('<params>', '{}'))
     try:
         timeout = float(self.args.get('--timeout'))
     except ValueError:
         print("--timeout requires a number number (e.g. --timeout=0.42)")
         return 1
     response = client.request(self.args['<address>'], self.args['<func>'], body, timeout=timeout)
     print(response.body)
Exemplo n.º 14
0
    def run(self):
        event_type = self.args.get('<event-type>')

        class Subscriber(lymph.Interface):
            @lymph.event(event_type)
            def on_event(self, event):
                print('%s: %r' % (event.evt_type, event.body))

        client = Client.from_config(self.config, interface_cls=Subscriber)
        client.container.join()
Exemplo n.º 15
0
    def run(self):
        client = Client.from_config(self.config)
        result = client.request(self.args['<address>'], 'lymph.inspect', {}, timeout=5).body
        print()

        for method in sorted(result['methods'], key=lambda m: m['name']):
            print("rpc {name}({params})\n    {help}\n".format(
                name=self.terminal.red(method['name']),
                params=', '.join(method['params']),
                help='\n    '.join(textwrap.wrap(method['help'], 70)),
            ))
Exemplo n.º 16
0
 def run(self):
     client = Client.from_config(self.config)
     for service_type in sorted(client.container.discover()):
         p = client.container.lookup('lymph://%s' % service_type)
         print("%s [%s]" % (self.terminal.red(service_type), len(p)))
         if self.args.get('--instances'):
             instances = sorted(p, key=lambda d: d.identity)
             for i, d in enumerate(p):
                 prefix = u'└─' if i == len(instances) - 1 else u'├─'
                 print(u'%s [%s] %s' %
                       (prefix, d.identity[:10], d.endpoint))
Exemplo n.º 17
0
    def run(self):
        address = self.args['<address>']
        client = Client.from_config(self.config)
        result = client.request(address, 'lymph.inspect', {}, timeout=5).body

        print('RPC interface of {}\n'.format(self.terminal.bold(address)))

        for method in sorted(result['methods'], key=lambda m: m['name']):
            print("rpc {name}({params})\n\t {help}\n".format(
                name=self.terminal.red(method['name']),
                params=self.terminal.yellow(', '.join(method['params'])),
                help='\n    '.join(textwrap.wrap(method['help'], 70)),
            ))
Exemplo n.º 18
0
 def change_loglevel(self, address, logger, level, period):
     client = Client.from_config(self.config)
     body = {
         'qualname': logger,
         'loglevel': level,
         'period': period,
     }
     service = client.container.lookup(address)
     print(
         "Changing logger '%s' of '%s' to '%s' for a period of %s seconds" %
         (logger, address, level, period))
     for instance in service:
         client.request(instance.endpoint, 'lymph.change_loglevel', body)
Exemplo n.º 19
0
 def __init__(self, *args, **kwargs):
     super(TopCommand, self).__init__(*args, **kwargs)
     self.terminal = blessed.Terminal()
     self.metrics_table = Table(self.default_columns, prettifier=prettifier)
     self.metrics_poller = MetricsPoller(Client.from_config(self.config))
     # TODO: Set TextOption values from command line arguments.
     self.input = UserInput({
         'o': TextOption('order', 'Set order by column e.g. +name', self._on_order),
         'f': TextOption('fqdns', 'Set comma separated fqdns to show, set to empty to disable filtering', self._on_filetring_by_fqdns),
         'n': TextOption('name', 'Set comma separated services name to show, set to empty to disable filtering', self._on_filetring_by_names),
         '?': UniqueKeyOption('', 'Show this help message', self._on_help),
         'KEY_ESCAPE': UniqueKeyOption('', 'Quit terminal or active command', self._on_escape),
     })
Exemplo n.º 20
0
 def run(self, **kwargs):
     client = Client.from_config(self.config, **kwargs)
     body = json.loads(self.args.get('<params>', '{}'))
     try:
         timeout = float(self.args.get('--timeout'))
     except ValueError:
         print("--timeout requires a number number (e.g. --timeout=0.42)")
         return 1
     response = client.request(self.args['<address>'],
                               self.args['<func>'],
                               body,
                               timeout=timeout)
     print(response.body)
Exemplo n.º 21
0
 def _request(self, address, subject, body, timeout=2.0):
     client = Client.from_config(self.config)
     try:
         response = client.request(
             address,
             subject,
             body,
             timeout=timeout
         )
     except lymph.exceptions.LookupFailure as e:
         raise RequestError("The specified service name could not be found: %s: %s" % (type(e).__name__, e))
     except lymph.exceptions.Timeout:
         raise RequestError("The request timed out. Either the service is not available or busy.")
     return response.body
Exemplo n.º 22
0
 def run(self):
     client = Client.from_config(self.config)
     services = client.container.discover()
     if services:
         for interface_name in sorted(services):
             interface_instances = client.container.lookup(interface_name)
             print(u"%s [%s]" % (self.terminal.red(interface_name), len(interface_instances)))
             if self.args.get('--instances'):
                 instances = sorted(interface_instances, key=lambda d: d.identity)
                 for i, d in enumerate(interface_instances):
                     prefix = u'└─' if i == len(instances) - 1 else u'├─'
                     print(u'%s [%s] %s' % (prefix, d.identity[:10], d.endpoint))
     else:
         print(u"No registered services found")
Exemplo n.º 23
0
 def run(self):
     client = Client.from_config(self.config)
     address = self.args['<address>']
     try:
         result = client.request(address, 'lymph.inspect', {}).body
     except LookupFailure:
         logger.error("cannot resolve %s", address)
         sys.exit(1)
     print
     for method in result['methods']:
         print("rpc {name}({params})\n    {help}\n".format(
             name=self.terminal.red(method['name']),
             params=', '.join(method['params']),
             help='\n    '.join(textwrap.wrap(method['help'], 70)),
         ))
Exemplo n.º 24
0
 def run(self):
     client = Client.from_config(self.config)
     services = client.container.discover()
     instances = {}
     for interface_name in sorted(services):
         service = client.container.lookup(interface_name)
         if not service and self.args.get('--only-running'):
             continue
         instances[interface_name] = service
     if self.args.get('--json'):
         print(json.dumps({
             name: [instance.serialize() for instance in service] for name, service in instances.items()
         }))
     else:
         self.print_human_readable_output(instances)
Exemplo n.º 25
0
 def run(self):
     client = Client.from_config(self.config)
     address = self.args['<address>']
     try:
         result = client.request(address, 'lymph.inspect', {}).body
     except LookupFailure:
         logger.error("cannot resolve %s", address)
         sys.exit(1)
     print
     for method in result['methods']:
         print("rpc {name}({params})\n    {help}\n".format(
             name=self.terminal.red(method['name']),
             params=', '.join(method['params']),
             help='\n    '.join(textwrap.wrap(method['help'], 70)),
         ))
Exemplo n.º 26
0
 def run(self):
     client = Client.from_config(self.config)
     services = client.container.discover()
     instances = {}
     for interface_name in sorted(services):
         service = client.container.lookup(interface_name)
         if not service and self.args.get('--only-running'):
             continue
         instances[interface_name] = service
     if self.args.get('--json'):
         print(
             json.dumps({
                 name: [instance.serialize() for instance in service]
                 for name, service in instances.items()
             }))
     else:
         self.print_human_readable_output(instances)
Exemplo n.º 27
0
 def run(self):
     client = Client.from_config(self.config)
     services = client.container.discover()
     if services:
         for interface_name in sorted(services):
             interface_instances = client.container.lookup(interface_name)
             if not interface_instances and self.args.get('--only-running'):
                 continue
             print(u"%s [%s]" % (self.terminal.red(interface_name), len(interface_instances)))
             if self.args.get('--instances'):
                 instances = sorted(interface_instances, key=lambda d: d.identity)
                 for i, d in enumerate(interface_instances):
                     prefix = u'└─' if i == len(instances) - 1 else u'├─'
                     print(u'%s [%s] %s' % (prefix, d.identity[:10], d.endpoint))
                     if self.args.get('--full'):
                         for k, v in sorted(d.serialize().items()):
                             if k == 'endpoint':
                                 continue
                             print(u'   %s: %r' % (k, v))
     else:
         print(u"No registered services found")
Exemplo n.º 28
0
    def run(self):
        body = json.loads(self.args.get("<params>", "{}"))
        try:
            timeout = float(self.args.get("--timeout"))
        except ValueError:
            print("--timeout requires a number (e.g. --timeout=0.42)")
            return 1
        subject = self.args["<subject>"]
        address = self.args.get("--address")
        if not address:
            address = subject.split(".", 1)[0]

        client = Client.from_config(self.config)

        def request():
            trace.set_id(self.args.get("--trace-id"))
            return client.request(address, subject, body, timeout=timeout)

        N, C = int(self.args["-N"]), int(self.args["-C"])

        if N == 1:
            return self._run_one_request(request)
        else:
            return self._run_many_requests(request, N, C)
Exemplo n.º 29
0
    def run(self):
        event_type = self.args.get('<event-type>')
        body = json.loads(self.args.get('<body>'))

        client = Client.from_config(self.config)
        client.emit(event_type, body)
Exemplo n.º 30
0
 def from_config(cls, config):
     return cls(Client.from_config(config))
Exemplo n.º 31
0
 def create_client(self, **kwargs):
     container, interface = self.create_container(**kwargs)
     return Client(container)