예제 #1
0
    def _render_latest_data(self):
        """Render the latest data with sparkline for each timeseries."""
        date = tslib.date_from_utc_ts(self._computation.last_logical_ts)
        print('\033[K\rAt {date} (@{resolution}, Δ: {lag}):'.format(
            date=white(self._render_date(date), bold=True),
            resolution=tslib.render_delta(self._computation.resolution)
            if self._computation.resolution else '-',
            lag=tslib.render_delta_from_now(date)))

        if not len(self._sparks):
            print('(no data)')
            return 2

        for tsid, spark in self._sparks.items():
            metadata = self._computation.get_metadata(tsid)
            print(u'\033[K\r{repr:<60}: [{spark:10s}] '.format(
                repr=utils.timeseries_repr(metadata) or '',
                spark=self._render_spark_line(spark)),
                  end='')
            value = spark[-1]
            if type(value) == int:
                print('\033[;1m{0:>10d}\033[;0m'.format(value))
            elif type(value) == float:
                print('\033[;1m{0:>10.2f}\033[;0m'.format(value))
            else:
                print('{:>10s}'.format('-'))

        return len(self._sparks) + 1
예제 #2
0
    def _render_latest_data(self):
        """Render the latest data with sparkline for each timeseries."""
        date = tslib.date_from_utc_ts(self._computation.last_logical_ts)
        print('\033[K\rAt {date} (@{resolution}, Δ: {lag}):'.format(
            date=white(self._render_date(date), bold=True),
            resolution=tslib.render_delta(self._computation.resolution)
            if self._computation.resolution else '-',
            lag=tslib.render_delta_from_now(date)))

        if not len(self._sparks):
            print('(no data)')
            return 2

        for tsid, spark in self._sparks.items():
            metadata = self._computation.get_metadata(tsid)
            print(u'\033[K\r{repr:<60}: [{spark:10s}] '
                  .format(repr=utils.timeseries_repr(metadata) or '',
                          spark=self._render_spark_line(spark)),
                  end='')
            value = spark[-1]
            if type(value) == int:
                print('\033[;1m{0:>10d}\033[;0m'.format(value))
            elif type(value) == float:
                print('\033[;1m{0:>10.2f}\033[;0m'.format(value))
            else:
                print('{:>10s}'.format('-'))

        return len(self._sparks) + 1
예제 #3
0
    def _render_latest_events(self):
        """Render the latest events emitted by the computation.

        TODO(mpetazzoni): render custom events/alert events differently and
        support alert event schema v3.
        """
        print('\nEvents:')

        def maybe_json(v):
            if isinstance(v, six.string_types):
                return json.loads(v)
            return v

        for event in self._events:
            ets = self._computation.get_metadata(event.tsid)
            contexts = json.loads(ets.get('sf_detectInputContexts', '{}'))

            values = maybe_json(event.properties.get('inputs', '{}'))
            values = ' | '.join([
                u'{name} ({key}): {value}'.format(
                    name=white(contexts[k].get('identifier', k)),
                    key=','.join([
                        u'{0}:{1}'.format(dim_name, dim_value)
                        for dim_name, dim_value in v.get('key', {}).items()
                    ]),
                    value=v['value']) for k, v in values.items()
            ])

            date = tslib.date_from_utc_ts(event.timestamp_ms)
            is_now = event.properties['is']

            print(u' {mark} {date} [{incident}]: {values}'.format(
                mark=green(u'✓') if is_now == 'ok' else red(u'✗'),
                date=white(self._render_date(date), bold=True),
                incident=event.properties['incidentId'],
                values=values))

        return 2 + len(self._events)
예제 #4
0
    def _render_latest_events(self):
        """Render the latest events emitted by the computation.

        TODO(mpetazzoni): render custom events/alert events differently and
        support alert event schema v3.
        """
        print('\nEvents:')

        def maybe_json(v):
            if isinstance(v, six.string_types):
                return json.loads(v)
            return v

        for event in self._events:
            ets = self._computation.get_metadata(event.tsid)
            contexts = json.loads(ets.get('sf_detectInputContexts', '{}'))

            values = maybe_json(event.properties.get('inputs', '{}'))
            values = ' | '.join([
                u'{name} ({key}): {value}'.format(
                    name=white(contexts[k].get('identifier', k)),
                    key=','.join([u'{0}:{1}'.format(dim_name, dim_value)
                                  for dim_name, dim_value
                                  in v.get('key', {}).items()]),
                    value=v['value'])
                for k, v in values.items()])

            date = tslib.date_from_utc_ts(event.timestamp_ms)
            is_now = event.properties['is']

            print(u' {mark} {date} [{incident}]: {values}'
                  .format(mark=green(u'✓') if is_now == 'ok' else red(u'✗'),
                          date=white(self._render_date(date), bold=True),
                          incident=event.properties['incidentId'],
                          values=values))

        return 2 + len(self._events)
예제 #5
0
def prompt(flow, tz, params):
    print(
        red('-*-', bold=True) + ' ' +
        white('SignalFx SignalFlow™ Analytics Console', bold=True) + ' ' +
        red('-*-', bold=True))
    print()
    print(white('Enter your program and press <Esc><Enter> to execute.'))
    print('SignalFlow programs may span multiple lines.')
    print('Set parameters with ".<param> <value>"; '
          'see current settings with "."')
    print('To stop streaming, or to exit, just press ^C.')
    print()

    def set_param(param, value=None):
        if param not in params:
            print('Unknown parameter {0} !'.format(param))
            return
        params[param] = value

    history = prompt_toolkit.history.FileHistory(
        os.path.expanduser('~/.signalflow.history'))
    prompt = prompt_toolkit.shortcuts.PromptSession(history=history)

    while True:
        program = []
        try:
            prompt_args = {
                'lexer':
                prompt_toolkit.lexers.PygmentsLexer(
                    pygments_signalflow.SignalFlowLexer),
                'auto_suggest':
                prompt_toolkit.auto_suggest.AutoSuggestFromHistory(),
                'prompt_continuation':
                lambda w, ln, sw: '>' * (w - 1) + ' ',
                'completer':
                PromptCompleter(),
                'multiline':
                True,
            }
            program = prompt.prompt(u'-> ', **prompt_args).strip()
        except (KeyboardInterrupt, EOFError):
            print()
            break

        if not program:
            continue

        # Parameter access and changes
        if program.startswith('.'):
            if len(program) > 1:
                set_param(*program[1:].split(' ', 1))
            pprint.pprint(params)
            continue

        # Execute from file
        if program.startswith('!'):
            filename = program[1:].strip()
            try:
                with open(filename) as f:
                    program = f.read()
            except Exception:
                print('Cannot read program from {0}!'.format(filename))
                continue
            print('Executing program from {0}:'.format(filename))
            print(program)
        exec_params = process_params(**params)
        output = params.get('output') or 'live'

        try:
            if output == 'live':
                live.stream(flow, tz, program, **exec_params)
            elif output in ['csv', 'graph']:
                data = csvflow.stream(flow, program, **exec_params)
                if output == 'csv':
                    for line in data:
                        print(line)
                elif output == 'graph':
                    graph.render(data, tz)
            else:
                print('Unknown output format {0}!'.format(output))
        except signalfx.signalflow.errors.ComputationAborted as e:
            print(e)
        except signalfx.signalflow.errors.ComputationFailed as e:
            print(e)

    return 0
예제 #6
0
def prompt(flow, tz, params):
    print(red('-*-', bold=True) + ' ' +
          white('SignalFx SignalFlow™ Analytics Console', bold=True) + ' ' +
          red('-*-', bold=True))
    print()
    print(white('Enter your program and press <Esc><Enter> to execute.'))
    print('SignalFlow programs may span multiple lines.')
    print('Set parameters with ".<param> <value>"; '
          'see current settings with "."')
    print('To stop streaming, or to exit, just press ^C.')
    print()

    def set_param(param, value=None):
        if param not in params:
            print('Unknown parameter {0} !'.format(param))
            return
        params[param] = value

    history = prompt_toolkit.history.FileHistory(
            os.path.expanduser('~/.signalflow.history'))
    prompt = prompt_toolkit.shortcuts.PromptSession(history=history)

    while True:
        program = []
        try:
            prompt_args = {
                'lexer': prompt_toolkit.lexers.PygmentsLexer(
                    pygments_signalflow.SignalFlowLexer),
                'auto_suggest':
                    prompt_toolkit.auto_suggest.AutoSuggestFromHistory(),
                'prompt_continuation': lambda w, ln, sw: '>' * (w - 1) + ' ',
                'completer': PromptCompleter(),
                'multiline': True,
            }
            program = prompt.prompt(u'-> ', **prompt_args).strip()
        except (KeyboardInterrupt, EOFError):
            print()
            break

        if not program:
            continue

        # Parameter access and changes
        if program.startswith('.'):
            if len(program) > 1:
                set_param(*program[1:].split(' ', 1))
            pprint.pprint(params)
            continue

        # Execute from file
        if program.startswith('!'):
            filename = program[1:].strip()
            try:
                with open(filename) as f:
                    program = f.read()
            except Exception:
                print('Cannot read program from {0}!'.format(filename))
                continue
            print('Executing program from {0}:'.format(filename))
            print(program)
        exec_params = process_params(**params)
        output = params.get('output') or 'live'

        try:
            if output == 'live':
                live.stream(flow, tz, program, **exec_params)
            elif output in ['csv', 'graph']:
                data = csvflow.stream(flow, program, **exec_params)
                if output == 'csv':
                    for line in data:
                        print(line)
                elif output == 'graph':
                    graph.render(data, tz)
            else:
                print('Unknown output format {0}!'.format(output))
        except signalfx.signalflow.errors.ComputationAborted as e:
            print(e)
        except signalfx.signalflow.errors.ComputationFailed as e:
            print(e)

    return 0