def _trace_loop(server, snapshot):
    """Server trace loop."""

    trace_printer = printer.ServerTracePrinter()

    if not snapshot:
        click.echo('# No trace information yet, waiting...\r',
                   nl=False,
                   err=True)

    def on_message(result):
        """Callback to process trace message."""
        _LOGGER.debug('result: %r', result)
        event = events.ServerTraceEvent.from_dict(result['event'])
        if event is None:
            return False

        trace_printer.process(event)

        return True

    def on_error(result):
        """Callback to process errors."""
        click.echo('Error: %s' % result['_error'], err=True)

    try:
        ws_client.ws_loop(context.GLOBAL.ws_api(), {
            'topic': '/server-trace',
            'filter': server
        }, snapshot, on_message, on_error)
    except ws_client.WSConnectionError:
        click.echo('Could not connect to any Websocket APIs', err=True)
        sys.exit(-1)
Example #2
0
def _get_instance_trace(instance, uniq, ws_api):
    """Get the history of the given instance/uniq."""
    rv = []
    message = {'topic': '/trace', 'filter': instance, 'snapshot': True}
    on_message = functools.partial(_filter_by_uniq, out_=rv, uniq=uniq)

    wsc.ws_loop(ws_api, message, True, on_message)

    return rv
Example #3
0
def _find_uniq_instance(instance, uniq, ws_api=None):
    """Find out where the given instance/uniq is/has been running."""
    rv = {}
    message = {'topic': '/trace', 'filter': instance, 'snapshot': True}
    on_message = functools.partial(_instance_to_host_uniq, out_=rv, uniq=uniq)

    wsc.ws_loop(ws_api, message, True, on_message)

    return rv
Example #4
0
def _trace_loop(ctx, app, snapshot):
    """Instance trace loop."""

    trace_printer = printer.AppTracePrinter()

    rc = {'rc': _RC_DEFAULT_EXIT}

    if not snapshot:
        click.echo('# No trace information yet, waiting...\r',
                   nl=False,
                   err=True)

    def on_message(result):
        """Callback to process trace message."""
        _LOGGER.debug('result: %r', result)
        event = events.AppTraceEvent.from_dict(result['event'])
        if event is None:
            return False

        trace_printer.process(event)

        if isinstance(event, events.FinishedTraceEvent):
            rc['rc'] = event.rc

        if isinstance(event, events.KilledTraceEvent):
            rc['rc'] = _RC_KILLED

        if isinstance(event, events.AbortedTraceEvent):
            rc['rc'] = _RC_ABORTED

        if isinstance(event, events.DeletedTraceEvent):
            return False

        return True

    def on_error(result):
        """Callback to process errors."""
        click.echo('Error: %s' % result['_error'], err=True)

    try:
        ws_client.ws_loop(ctx['wsapi'], {
            'topic': '/trace',
            'filter': app
        }, snapshot, on_message, on_error)

        sys.exit(rc['rc'])

    except ws_client.WSConnectionError:
        click.echo('Could not connect to any Websocket APIs', err=True)
        sys.exit(-1)
Example #5
0
def _find_running_instance(app, ws_api=None):
    """Find the instance name(s) and host(s) corresponding to the application.
    """
    rv = {}
    message = {'topic': '/endpoints',
               'filter': app,
               'proto': 'tcp',
               'endpoint': 'ssh',
               'snapshot': True}

    on_message = functools.partial(_instance_to_host, out_=rv)

    wsc.ws_loop(ws_api, message, True, on_message)

    return rv
Example #6
0
def _wait_for_app(wsapi, ssh, app, command):
    """Use websockets to wait for the app to start"""
    def on_message(result):
        """Callback to process trace message."""
        host = result['host']
        port = result['port']
        run_ssh(host, port, ssh, list(command))
        return False

    def on_error(result):
        """Callback to process errors."""
        click.echo('Error: %s' % result['_error'], err=True)

    try:
        return ws_client.ws_loop(
            wsapi,
            {'topic': '/endpoints',
             'filter': app,
             'proto': 'tcp',
             'endpoint': 'ssh'},
            False,
            on_message,
            on_error
        )
    except ws_client.ConnectionError:
        cli.bad_exit('Could not connect to any Websocket APIs')
Example #7
0
def _trace_loop(ctx, app, snapshot):
    """Instance trace loop."""
    trace_printer = printer.AppTracePrinter()

    def on_message(result):
        """Callback to process trace message."""
        event = events.AppTraceEvent.from_dict(result['event'])
        if event is None:
            return False

        trace_printer.process(event)
        if isinstance(event, events.DeletedTraceEvent):
            return False

        return True

    def on_error(result):
        """Callback to process errors."""
        click.echo('Error: %s' % result['_error'], err=True)

    try:
        return ws_client.ws_loop(ctx['wsapi'], {
            'topic': '/trace',
            'filter': app
        }, snapshot, on_message, on_error)
    except ws_client.ConnectionError:
        click.echo('Could not connect to any Websocket APIs', err=True)
        sys.exit(-1)
Example #8
0
    def identity_group_cmd(pattern, identity_group):
        """Manage /etc/hosts file inside the container.
        """
        alias_dir = ctx['aliases_dir']
        cell = context.GLOBAL.cell

        def on_message(result):
            """Callback to process trace essage."""
            host = result.get('host')
            app = result.get('app')
            identity_group = result['identity-group']
            identity = result['identity']

            _LOGGER.info('group: %s, identity: %s, host: %s, app: %s',
                         identity_group, identity, host, app)

            alias_name = pattern.format(identity_group=identity_group,
                                        identity=identity,
                                        cell=cell)
            link_name = os.path.join(alias_dir, alias_name)
            if host:
                temp_name = tempfile.mktemp(dir=alias_dir, prefix='^')
                _LOGGER.info('Creating tempname: %s - %s', temp_name, host)
                os.symlink(host, temp_name)
                _LOGGER.info('Renaming: %s', link_name)
                os.rename(temp_name, link_name)
            else:
                os.unlink(link_name)

            return True

        def on_error(result):
            """Callback to process errors."""
            click.echo('Error: %s' % result['_error'], err=True)

        glob_pattern = os.path.join(
            alias_dir,
            pattern.format(identity_group=identity_group,
                           identity='*',
                           cell=cell)
        )

        for path in glob.glob(glob_pattern):
            os.unlink(path)

        try:
            return ws_client.ws_loop(
                ctx['wsapi'],
                {'topic': '/identity-groups',
                 'identity-group': identity_group},
                False,
                on_message,
                on_error
            )
        except ws_client.ConnectionError:
            click.echo('Could not connect to any Websocket APIs', err=True)
            sys.exit(-1)
Example #9
0
    def trace(api, wsapi, snapshot, identity_group):
        """Trace identity group events.

        Invoking treadmill_trace with non existing application instance will
        cause the utility to wait for the specified instance to be started.

        Specifying already finished instance of the application will display
        historical trace information and exit status.

        Specifying only an application name will list all the instance IDs with
        trace information available.
        """
        # Disable too many branches.
        #
        # pylint: disable=R0912

        ctx['api'] = api
        ctx['wsapi'] = wsapi

        def on_message(result):
            """Callback to process trace message."""
            host = result.get('host')
            if host is None:
                host = ''
            app = result.get('app')
            if app is None:
                app = ''

            identity_group = result['identity-group']
            identity = result['identity']

            print('{identity_group}/{identity} {app} {host}'.format(
                identity_group=identity_group,
                identity=identity,
                app=app,
                host=host
            ))

            return True

        def on_error(result):
            """Callback to process errors."""
            click.echo('Error: %s' % result['_error'], err=True)

        try:
            return ws_client.ws_loop(
                ctx['wsapi'],
                {'topic': '/identity-groups',
                 'identity-group': identity_group},
                snapshot,
                on_message,
                on_error
            )
        except ws_client.ConnectionError:
            click.echo('Could not connect to any Websocket APIs', err=True)
            sys.exit(-1)
Example #10
0
    def discovery(wsapi, check_state, watch, separator, app, endpoint):
        """Show state of scheduled applications."""
        ctx['wsapi'] = wsapi

        if ':' not in endpoint:
            endpoint = '*:' + endpoint

        proto, endpoint_name = endpoint.split(':')

        def on_message(result):
            """Callback to process trace message."""
            instance = ':'.join(
                [result['name'], result['proto'], result['endpoint']])
            host = result['host']
            port = result['port']
            hostport = '%s:%s' % (host, port)
            if host is not None:
                record = [instance, hostport.decode()]
                if check_state:
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.settimeout(1)

                    try:
                        sock.connect((host, int(port)))
                        sock.close()
                        state = 'up'
                    except socket.error:
                        state = 'down'

                    record.append(state)

                output = separator.join(record)
            else:
                output = instance

            print(output)
            return True

        def on_error(result):
            """Callback to process errors."""
            click.echo('Error: %s' % result['_error'], err=True)

        try:
            return ws_client.ws_loop(
                ctx['wsapi'], {
                    'topic': '/endpoints',
                    'filter': app,
                    'proto': proto,
                    'endpoint': endpoint_name
                }, not watch, on_message, on_error)
        except ws_client.ConnectionError:
            click.echo('Could not connect to any Websocket APIs', err=True)
            sys.exit(-1)