示例#1
0
 def tabular(self, timezone=None):
     return {
         'id': self.get_id(short=True),
         'lastReceiveTime': DateTime.localtime(self.last_receive_time, timezone),
         'severity': self.severity,
         'status': self.status,
         'duplicateCount': self.duplicate_count,
         'customer': self.customer,
         'environment': self.environment,
         'service': ','.join(self.service),
         'resource': self.resource,
         'group': self.group,
         'event': self.event,
         'correlate': self.correlate,
         'value': self.value,
         'text': self.text,
         'tags': ','.join(self.tags),
         'attributes': self.attributes,
         'origin': self.origin,
         'type': self.event_type,
         'createTime': DateTime.localtime(self.create_time, timezone),
         'timeout': self.timeout,
         'rawData': self.raw_data,
         'repeat': self.repeat,
         'previousSeverity': self.previous_severity,
         'trendIndication': self.trend_indication,
         'receiveTime': DateTime.localtime(self.receive_time, timezone),
         'lastReceiveId': self.last_receive_id,
         'history': self.history
     }
示例#2
0
 def tabular(self, fields='all', timezone=None):
     if fields == 'summary':
         return {
             'id': self.get_id(short=True),
             'lastReceiveTime': DateTime.localtime(self.last_receive_time, timezone),
             'severity': self.severity,
             'status': self.status,
             'duplicateCount': self.duplicate_count,
             'customer': self.customer,
             'environment': self.environment,
             'service': ','.join(self.service),
             'resource': self.resource,
             'group': self.group,
             'event': self.event,
             'value': self.value,
             'text': self.text
         }
     elif fields == 'details':
         return {
             'severity': '{} -> {}'.format(self.previous_severity, self.severity),
             'trend': self.trend_indication,
             'status': self.status,
             'resource': self.resource,
             'group': self.group,
             'event': self.event,
             'value': self.value,
             'tags': ','.join(self.tags)
         }
     else:
         return {
             'id': self.id,
             'resource': self.resource,
             'event': self.event,
             'environment': self.environment,
             'severity': self.severity,
             'correlate': self.correlate,
             'status': self.status,
             'service': ','.join(self.service),
             'group': self.group,
             'value': self.value,
             'text': self.text,
             'tags': ','.join(self.tags),
             'attributes': self.attributes,
             'origin': self.origin,
             'type': self.event_type,
             'createTime': DateTime.localtime(self.create_time, timezone),
             'timeout': self.timeout,
             'rawData': self.raw_data,
             'customer': self.customer,
             'duplicateCount': self.duplicate_count,
             'repeat': self.repeat,
             'previousSeverity': self.previous_severity,
             'trendIndication': self.trend_indication,
             'receiveTime': DateTime.localtime(self.receive_time, timezone),
             'lastReceiveId': self.last_receive_id,
             'lastReceiveTime': DateTime.localtime(self.last_receive_time, timezone),
             'history': self.history
         }
示例#3
0
 def parse(cls, json):
     return Note(
         id=json.get('id', None),
         text=json.get('text', None),
         user=json.get('user', None),
         attributes=json.get('attributes', dict()),
         note_type=json.get('type', None),
         create_time=DateTime.parse(json['createTime']) if 'createTime' in json else None,
         update_time=DateTime.parse(json['updateTime']) if 'updateTime' in json else None,
         alert=json.get('related', {}).get('alert'),
         customer=json.get('customer', None)
     )
示例#4
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'key': self.key,
         'user': self.user,
         'scopes': ','.join(self.scopes),
         'text': self.text,
         'expireTime': DateTime.localtime(self.expire_time, timezone),
         'count': self.count,
         'lastUsedTime': DateTime.localtime(self.last_used_time, timezone),
         'customer': self.customer
     }
示例#5
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'key': self.key,
         'user': self.user,
         'scopes': ','.join(self.scopes),
         'text': self.text,
         'expireTime': DateTime.localtime(self.expire_time, timezone),
         'count': self.count,
         'lastUsedTime': DateTime.localtime(self.last_used_time, timezone),
         'customer': self.customer
     }
示例#6
0
文件: user.py 项目: cloud-guru/alerta
 def parse(cls, json):
     return User(id=json.get('id'),
                 name=json.get('name'),
                 email=json.get('email', None) or json.get('login'),
                 status=json.get('status'),
                 roles=json.get('roles', None)
                 or ([json['role']] if 'role' in json else list()),
                 attributes=json.get('attributes', dict()),
                 create_time=DateTime.parse(json.get('createTime')),
                 last_login=DateTime.parse(json.get('lastLogin')),
                 text=json.get('text', None),
                 update_time=DateTime.parse(json.get('updateTime')),
                 email_verified=json.get('email_verified', None))
示例#7
0
文件: key.py 项目: cloud-guru/alerta
    def parse(cls, json):
        if not isinstance(json.get('scopes', []), list):
            raise ValueError('scopes must be a list')

        return ApiKey(id=json.get('id', None),
                      key=json.get('key', None),
                      user=json.get('user', None),
                      scopes=json.get('scopes', None) or list(),
                      text=json.get('text', None),
                      expire_time=DateTime.parse(json.get('expireTime')),
                      count=json.get('count', None),
                      last_used_time=DateTime.parse(json.get('lastUsedTime')),
                      customer=json.get('customer', None))
示例#8
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'origin': self.origin,
         'customer': self.customer,
         'tags': ','.join(self.tags),
         'createTime': DateTime.localtime(self.create_time, timezone),
         'receiveTime': DateTime.localtime(self.receive_time, timezone),
         'latency': '{:.0f}ms'.format(self.latency),
         'timeout': '{}s'.format(self.timeout),
         'since': self.since,
         'status': self.status
     }
示例#9
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'origin': self.origin,
         'customer': self.customer,
         'tags': ','.join(self.tags),
         'createTime': DateTime.localtime(self.create_time, timezone),
         'receiveTime': DateTime.localtime(self.receive_time, timezone),
         'latency': '{:.0f}ms'.format(self.latency),
         'timeout': '{}s'.format(self.timeout),
         'since': self.since,
         'status': self.status
     }
示例#10
0
 def tabular(self, timezone=None):
     note = {
         'id': self.id,
         'text': self.text,
         'createTime': DateTime.localtime(self.create_time, timezone),
         'user': self.user,
         # 'attributes': self.attributes,
         'type': self.note_type,
         'related': self.alert,
         'updateTime': DateTime.localtime(self.update_time, timezone),
         'customer': self.customer
     }
     return note
示例#11
0
文件: user.py 项目: cloud-guru/alerta
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'name': self.name,
         'email': self.email,
         'status': self.status,
         'roles': ','.join(self.roles),
         # 'attributes': self.attributes,  # reserved for future use
         'createTime': DateTime.localtime(self.create_time, timezone),
         'lastLogin': DateTime.localtime(self.last_login, timezone),
         'text': self.text,
         'updateTime': DateTime.localtime(self.update_time, timezone),
         'email_verified': 'yes' if self.email_verified else 'no'
     }
示例#12
0
 def parse(cls, json):
     return User(
         id=json.get('id'),
         name=json.get('name'),
         email=json.get('email', None) or json.get('login'),
         status=json.get('status'),
         roles=json.get('roles', None) or ([json['role']] if 'role' in json else list()),
         attributes=json.get('attributes', dict()),
         create_time=DateTime.parse(json.get('createTime')),
         last_login=DateTime.parse(json.get('lastLogin')),
         text=json.get('text', None),
         update_time=DateTime.parse(json.get('updateTime')),
         email_verified=json.get('email_verified', None)
     )
示例#13
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'name': self.name,
         'email': self.email,
         'status': self.status,
         'roles': ','.join(self.roles),
         # 'attributes': self.attributes,  # reserved for future use
         'createTime': DateTime.localtime(self.create_time, timezone),
         'lastLogin': DateTime.localtime(self.last_login, timezone),
         'text': self.text,
         'updateTime': DateTime.localtime(self.update_time, timezone),
         'email_verified': 'yes' if self.email_verified else 'no'
     }
示例#14
0
    def parse(cls, json):
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')
        if not isinstance(json.get('timeout', 0), int):
            raise ValueError('timeout must be an integer')

        return Heartbeat(id=json.get('id', None),
                         origin=json.get('origin', None),
                         tags=json.get('tags', list()),
                         event_type=json.get('type', None),
                         create_time=DateTime.parse(json.get('createTime')),
                         timeout=json.get('timeout', None),
                         receive_time=DateTime.parse(json.get('receiveTime')),
                         customer=json.get('customer', None))
示例#15
0
    def parse(cls, json):
        if not isinstance(json.get('scopes', []), list):
            raise ValueError('scopes must be a list')

        return ApiKey(
            id=json.get('id', None),
            key=json.get('key', None),
            user=json.get('user', None),
            scopes=json.get('scopes', None) or list(),
            text=json.get('text', None),
            expire_time=DateTime.parse(json.get('expireTime')),
            count=json.get('count', None),
            last_used_time=DateTime.parse(json.get('lastUsedTime')),
            customer=json.get('customer', None)
        )
示例#16
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'origin': self.origin,
         'customer': self.customer,
         'tags': ','.join(self.tags),
         'attributes': self.attributes,
         'createTime': DateTime.localtime(self.create_time, timezone),
         'receiveTime': DateTime.localtime(self.receive_time, timezone),
         'since': self.since,
         'timeout': f'{self.timeout}s',
         'latency': f'{self.latency:.0f}ms',
         'maxLatency': f'{self.max_latency}ms',
         'status': self.status
     }
示例#17
0
    def tabular(self, timezone=None):
        data = {
            'id': self.id,
            'resource': self.resource,
            'event': self.event,
            'environment': self.environment,
            'service': ','.join(self.service),
            'group': self.group,
            'text': self.text,
            # 'tags': ','.join(self.tags),  # not displayed
            # 'attributes': self.attributes,
            # 'origin': self.origin,
            'type': self.event_type,
            'updateTime': DateTime.localtime(self.update_time, timezone),
            'customer': self.customer
        }

        if self.severity:
            data['severity'] = self.severity
            data['value'] = self.value

        if self.status:
            data['status'] = self.status

        return data
示例#18
0
    def tabular(self, timezone=None):
        data = {
            'id': self.id,
            'resource': self.resource,
            'event': self.event,
            'environment': self.environment,
            'service': ','.join(self.service),
            'group': self.group,
            'text': self.text,
            # 'tags': ','.join(self.tags),  # not displayed
            # 'attributes': self.attributes,
            # 'origin': self.origin,
            'type': self.change_type,
            'updateTime': DateTime.localtime(self.update_time, timezone),
            'customer': self.customer
        }

        if self.severity:
            data['severity'] = self.severity
            data['value'] = self.value

        if self.status:
            data['status'] = self.status

        return data
示例#19
0
    def parse(cls, json):
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')
        if not isinstance(json.get('timeout', 0), int):
            raise ValueError('timeout must be an integer')

        return Heartbeat(
            id=json.get('id', None),
            origin=json.get('origin', None),
            tags=json.get('tags', list()),
            event_type=json.get('type', None),
            create_time=DateTime.parse(json.get('createTime')),
            timeout=json.get('timeout', None),
            receive_time=DateTime.parse(json.get('receiveTime')),
            customer=json.get('customer', None)
        )
示例#20
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'priority': self.priority,
         'environment': self.environment,
         'service': ','.join(self.service),
         'resource': self.resource,
         'event': self.event,
         'group': self.group,
         'tags': ','.join(self.tags),
         'customer': self.customer,
         'startTime': DateTime.localtime(self.start_time, timezone),
         'endTime': DateTime.localtime(self.end_time, timezone),
         'duration': '{}s'.format(self.duration),
         'status': self.status,
         'remaining': '{}s'.format(self.remaining)
     }
示例#21
0
    def parse(cls, json):
        if not isinstance(json.get('service', []), list):
            raise ValueError('service must be a list')
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')

        return Blackout(id=json.get('id'),
                        environment=json.get('environment'),
                        service=json.get('service', list()),
                        resource=json.get('resource', None),
                        event=json.get('event', None),
                        group=json.get('group', None),
                        tags=json.get('tags', list()),
                        customer=json.get('customer', None),
                        start_time=DateTime.parse(json.get('startTime')),
                        end_time=DateTime.parse(json.get('endTime')),
                        duration=json.get('duration', None))
示例#22
0
    def parse(cls, json):
        if not isinstance(json.get('correlate', []), list):
            raise ValueError('correlate must be a list')
        if not isinstance(json.get('service', []), list):
            raise ValueError('service must be a list')
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')
        if not isinstance(json.get('attributes', {}), dict):
            raise ValueError('attributes must be a JSON object')
        if not isinstance(json.get('timeout') if json.get('timeout', None) is not None else 0, int):
            raise ValueError('timeout must be an integer')

        return Alert(
            id=json.get('id', None),
            resource=json.get('resource', None),
            event=json.get('event', None),
            environment=json.get('environment', None),
            severity=json.get('severity', None),
            correlate=json.get('correlate', list()),
            status=json.get('status', None),
            service=json.get('service', list()),
            group=json.get('group', None),
            value=json.get('value', None),
            text=json.get('text', None),
            tags=json.get('tags', list()),
            attributes=json.get('attributes', dict()),
            origin=json.get('origin', None),
            event_type=json.get('type', None),
            create_time=DateTime.parse(json.get('createTime')),
            timeout=json.get('timeout', None),
            raw_data=json.get('rawData', None),
            customer=json.get('customer', None),

            duplicate_count=json.get('duplicateCount', None),
            repeat=json.get('repeat', None),
            previous_severity=json.get('previousSeverity', None),
            trend_indication=json.get('trendIndication', None),
            receive_time=DateTime.parse(json.get('receiveTime')),
            last_receive_id=json.get('lastReceiveId', None),
            last_receive_time=DateTime.parse(json.get('lastReceiveTime')),
            history=json.get('history', None)
        )
示例#23
0
    def parse(cls, json):
        if not isinstance(json.get('correlate', []), list):
            raise ValueError('correlate must be a list')
        if not isinstance(json.get('service', []), list):
            raise ValueError('service must be a list')
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')
        if not isinstance(json.get('attributes', {}), dict):
            raise ValueError('attributes must be a JSON object')
        if not isinstance(json.get('timeout') if json.get('timeout', None) is not None else 0, int):
            raise ValueError('timeout must be an integer')

        return Alert(
            id=json.get('id', None),
            resource=json.get('resource', None),
            event=json.get('event', None),
            environment=json.get('environment', None),
            severity=json.get('severity', None),
            correlate=json.get('correlate', list()),
            status=json.get('status', None),
            service=json.get('service', list()),
            group=json.get('group', None),
            value=json.get('value', None),
            text=json.get('text', None),
            tags=json.get('tags', list()),
            attributes=json.get('attributes', dict()),
            origin=json.get('origin', None),
            event_type=json.get('type', None),
            create_time=DateTime.parse(json.get('createTime')),
            timeout=json.get('timeout', None),
            raw_data=json.get('rawData', None),
            customer=json.get('customer', None),

            duplicate_count=json.get('duplicateCount', None),
            repeat=json.get('repeat', None),
            previous_severity=json.get('previousSeverity', None),
            trend_indication=json.get('trendIndication', None),
            receive_time=DateTime.parse(json.get('receiveTime')),
            last_receive_id=json.get('lastReceiveId', None),
            last_receive_time=DateTime.parse(json.get('lastReceiveTime')),
            history=json.get('history', None)
        )
示例#24
0
 def create_key(self, username, scopes=None, expires=None, text='', customer=None):
     data = {
         'user': username,
         'scopes': scopes or list(),
         'text': text,
         'customer': customer
     }
     if expires:
         data['expireTime'] = DateTime.iso8601(expires)
     r = self.http.post('/key', data)
     return ApiKey.parse(r['data'])
示例#25
0
 def create_key(self, username, scopes=None, expires=None, text='', customer=None):
     data = {
         'user': username,
         'scopes': scopes or list(),
         'text': text,
         'customer': customer
     }
     if expires:
         data['expireTime'] = DateTime.iso8601(expires)
     r = self.http.post('/key', data)
     return ApiKey.parse(r['data'])
示例#26
0
 def tabular(self, timezone=None):
     return {
         'id': self.id,
         'priority': self.priority,
         'environment': self.environment,
         'service': ','.join(self.service),
         'resource': self.resource,
         'event': self.event,
         'group': self.group,
         'tags': ','.join(self.tags),
         'customer': self.customer,
         'startTime': DateTime.localtime(self.start_time, timezone),
         'endTime': DateTime.localtime(self.end_time, timezone),
         'duration': '{}s'.format(self.duration),
         'status': self.status,
         'remaining': '{}s'.format(self.remaining),
         'user': self.user,
         'createTime': DateTime.localtime(self.create_time, timezone),
         'text': self.text
     }
示例#27
0
    def parse(cls, json):
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')
        if not isinstance(json.get('attributes', {}), dict):
            raise ValueError('attributes must be a JSON object')
        if not isinstance(json.get('timeout', 0), int):
            raise ValueError('timeout must be an integer')

        return Heartbeat(
            id=json.get('id', None),
            origin=json.get('origin', None),
            status=json.get('status', None),
            tags=json.get('tags', list()),
            attributes=json.get('attributes', dict()),
            event_type=json.get('type', None),
            create_time=DateTime.parse(json.get('createTime')),
            timeout=json.get('timeout', None),
            max_latency=json.get('maxLatency', None) or DEFAULT_MAX_LATENCY,
            receive_time=DateTime.parse(json.get('receiveTime')),
            customer=json.get('customer', None)
        )
示例#28
0
    def parse(cls, json):
        if not isinstance(json.get('service', []), list):
            raise ValueError('service must be a list')
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')

        return Blackout(
            id=json.get('id'),
            environment=json.get('environment'),
            service=json.get('service', list()),
            resource=json.get('resource', None),
            event=json.get('event', None),
            group=json.get('group', None),
            tags=json.get('tags', list()),
            customer=json.get('customer', None),
            start_time=DateTime.parse(json.get('startTime')),
            end_time=DateTime.parse(json.get('endTime')),
            duration=json.get('duration', None),
            user=json.get('user', None),
            create_time=DateTime.parse(json.get('createTime')),
            text=json.get('text', None)
        )
示例#29
0
    def parse(cls, json):
        if not isinstance(json.get('service', []), list):
            raise ValueError('service must be a list')
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')

        return RichHistory(id=json.get('id', None),
                           resource=json.get('resource', None),
                           event=json.get('event', None),
                           environment=json.get('environment', None),
                           severity=json.get('severity', None),
                           status=json.get('status', None),
                           service=json.get('service', list()),
                           group=json.get('group', None),
                           value=json.get('value', None),
                           text=json.get('text', None),
                           tags=json.get('tags', list()),
                           attributes=json.get('attributes', dict()),
                           origin=json.get('origin', None),
                           change_type=json.get('type', None),
                           update_time=DateTime.parse(json.get('updateTime')),
                           customer=json.get('customer', None))
示例#30
0
    def parse(cls, json):
        if not isinstance(json.get('service', []), list):
            raise ValueError('service must be a list')
        if not isinstance(json.get('tags', []), list):
            raise ValueError('tags must be a list')

        return RichHistory(
            id=json.get('id', None),
            resource=json.get('resource', None),
            event=json.get('event', None),
            environment=json.get('environment', None),
            severity=json.get('severity', None),
            status=json.get('status', None),
            service=json.get('service', list()),
            group=json.get('group', None),
            value=json.get('value', None),
            text=json.get('text', None),
            tags=json.get('tags', list()),
            attributes=json.get('attributes', dict()),
            origin=json.get('origin', None),
            change_type=json.get('type', None),
            update_time=DateTime.parse(json.get('updateTime')),
            customer=json.get('customer', None)
        )
示例#31
0
def cli(obj, ids, filters, display, from_date=None):
    """Query for alerts based on search filter criteria."""
    client = obj['client']
    timezone = obj['timezone']
    if ids:
        query = [('id', x) for x in ids]
    else:
        query = build_query(filters)
    if from_date:
        query.append(('from-date', from_date))

    r = client.http.get('/alerts', query)

    if obj['output'] == 'json':
        click.echo(
            json.dumps(r['alerts'],
                       sort_keys=True,
                       indent=4,
                       ensure_ascii=False))
    elif obj['output'] in ['json_lines', 'jsonl', 'ndjson']:
        for alert in r['alerts']:
            click.echo(json.dumps(alert, ensure_ascii=False))
    else:
        alerts = [Alert.parse(a) for a in r['alerts']]
        last_time = r['lastTime']
        auto_refresh = r['autoRefresh']

        if display == 'tabular':
            headers = {
                'id': 'ID',
                'lastReceiveTime': 'LAST RECEIVED',
                'severity': 'SEVERITY',
                'status': 'STATUS',
                'duplicateCount': 'DUPL',
                'customer': 'CUSTOMER',
                'environment': 'ENVIRONMENT',
                'service': 'SERVICE',
                'resource': 'RESOURCE',
                'group': 'GROUP',
                'event': 'EVENT',
                'value': 'VALUE',
                'text': 'TEXT'
            }
            click.echo(
                tabulate([a.tabular('summary', timezone) for a in alerts],
                         headers=headers,
                         tablefmt=obj['output']))
        elif display in ['compact', 'details']:
            for alert in reversed(alerts):
                color = COLOR_MAP.get(alert.severity, {'fg': 'white'})
                click.secho(
                    '{0}|{1}|{2}|{3:5d}|{4}|{5:<5s}|{6:<10s}|{7:<18s}|{8:12s}|{9:16s}|{10:12s}'
                    .format(
                        alert.id[0:8],
                        DateTime.localtime(alert.last_receive_time, timezone),
                        alert.severity, alert.duplicate_count, alert.customer
                        or "-", alert.environment, ','.join(alert.service),
                        alert.resource, alert.group, alert.event, alert.value
                        or "n/a"),
                    fg=color['fg'])
                click.secho('   |{}'.format(alert.text), fg=color['fg'])

                if display == 'details':
                    click.secho('    severity   | {} -> {}'.format(
                        alert.previous_severity, alert.severity),
                                fg=color['fg'])
                    click.secho('    trend      | {}'.format(
                        alert.trend_indication),
                                fg=color['fg'])
                    click.secho('    status     | {}'.format(alert.status),
                                fg=color['fg'])
                    click.secho('    resource   | {}'.format(alert.resource),
                                fg=color['fg'])
                    click.secho('    group      | {}'.format(alert.group),
                                fg=color['fg'])
                    click.secho('    event      | {}'.format(alert.event),
                                fg=color['fg'])
                    click.secho('    value      | {}'.format(alert.value),
                                fg=color['fg'])
                    click.secho('    tags       | {}'.format(' '.join(
                        alert.tags)),
                                fg=color['fg'])

                    for key, value in alert.attributes.items():
                        click.secho('    {} | {}'.format(key.ljust(10), value),
                                    fg=color['fg'])

                    latency = alert.receive_time - alert.create_time

                    click.secho('        time created  | {}'.format(
                        DateTime.localtime(alert.create_time, timezone)),
                                fg=color['fg'])
                    click.secho('        time received | {}'.format(
                        DateTime.localtime(alert.receive_time, timezone)),
                                fg=color['fg'])
                    click.secho('        last received | {}'.format(
                        DateTime.localtime(alert.last_receive_time, timezone)),
                                fg=color['fg'])
                    click.secho('        latency       | {}ms'.format(
                        (latency.microseconds / 1000)),
                                fg=color['fg'])
                    click.secho('        timeout       | {}s'.format(
                        alert.timeout),
                                fg=color['fg'])

                    click.secho('            alert id     | {}'.format(
                        alert.id),
                                fg=color['fg'])
                    click.secho('            last recv id | {}'.format(
                        alert.last_receive_id),
                                fg=color['fg'])
                    click.secho('            customer     | {}'.format(
                        alert.customer),
                                fg=color['fg'])
                    click.secho('            environment  | {}'.format(
                        alert.environment),
                                fg=color['fg'])
                    click.secho('            service      | {}'.format(
                        ','.join(alert.service)),
                                fg=color['fg'])
                    click.secho('            resource     | {}'.format(
                        alert.resource),
                                fg=color['fg'])
                    click.secho('            type         | {}'.format(
                        alert.event_type),
                                fg=color['fg'])
                    click.secho('            repeat       | {}'.format(
                        alert.repeat),
                                fg=color['fg'])
                    click.secho('            origin       | {}'.format(
                        alert.origin),
                                fg=color['fg'])
                    click.secho('            correlate    | {}'.format(
                        ','.join(alert.correlate)),
                                fg=color['fg'])

        return auto_refresh, last_time
示例#32
0
def cli(obj, ids, query, filters, display, from_date=None):
    """Query for alerts based on search filter criteria."""
    client = obj['client']
    timezone = obj['timezone']
    if ids:
        query = [('id', x) for x in ids]
    elif query:
        query = [('q', query)]
    else:
        query = build_query(filters)
    if from_date:
        query.append(('from-date', from_date))

    r = client.http.get('/alerts', query, page=1, page_size=1000)

    if obj['output'] == 'json':
        click.echo(json.dumps(r['alerts'], sort_keys=True, indent=4, ensure_ascii=False))
    elif obj['output'] in ['json_lines', 'jsonl', 'ndjson']:
        for alert in r['alerts']:
            click.echo(json.dumps(alert, ensure_ascii=False))
    else:
        alerts = [Alert.parse(a) for a in r['alerts']]
        last_time = r['lastTime']
        auto_refresh = r['autoRefresh']

        if display == 'oneline':
            headers = {'id': 'ID', 'lastReceiveTime': 'LAST RECEIVED', 'severity': 'SEVERITY', 'status': 'STATUS',
                       'duplicateCount': 'DUPL', 'customer': 'CUSTOMER', 'environment': 'ENVIRONMENT', 'service': 'SERVICE',
                       'resource': 'RESOURCE', 'group': 'GROUP', 'event': 'EVENT', 'value': 'VALUE', 'text': 'DESCRIPTION'}

            data = [{k: v for k, v in a.tabular(timezone).items() if k in headers.keys()} for a in alerts]
            click.echo(tabulate(data, headers=headers, tablefmt=obj['output']))

        else:
            for alert in reversed(alerts):
                color = COLOR_MAP.get(alert.severity, {'fg': 'white'})
                click.secho('{}|{}|{}|{:5d}|{}|{:<5s}|{:<10s}|{:<18s}|{:12s}|{:16s}|{:12s}'.format(
                    alert.id[0:8],
                    DateTime.localtime(alert.last_receive_time, timezone),
                    alert.severity,
                    alert.duplicate_count,
                    alert.customer or '-',
                    alert.environment,
                    ','.join(alert.service),
                    alert.resource,
                    alert.group,
                    alert.event,
                    alert.value or 'n/a'), fg=color['fg'])
                click.secho(f'   |{alert.text}', fg=color['fg'])

                if display == 'full':
                    click.secho('    severity   | {} -> {}'.format(alert.previous_severity,
                                                                   alert.severity), fg=color['fg'])
                    click.secho(f'    trend      | {alert.trend_indication}', fg=color['fg'])
                    click.secho(f'    status     | {alert.status}', fg=color['fg'])
                    click.secho(f'    resource   | {alert.resource}', fg=color['fg'])
                    click.secho(f'    group      | {alert.group}', fg=color['fg'])
                    click.secho(f'    event      | {alert.event}', fg=color['fg'])
                    click.secho(f'    value      | {alert.value}', fg=color['fg'])
                    click.secho('    tags       | {}'.format(' '.join(alert.tags)), fg=color['fg'])

                    for key, value in alert.attributes.items():
                        click.secho(f'    {key.ljust(10)} | {value}', fg=color['fg'])

                    latency = alert.receive_time - alert.create_time

                    click.secho('        time created  | {}'.format(
                        DateTime.localtime(alert.create_time, timezone)), fg=color['fg'])
                    click.secho('        time received | {}'.format(
                        DateTime.localtime(alert.receive_time, timezone)), fg=color['fg'])
                    click.secho('        last received | {}'.format(
                        DateTime.localtime(alert.last_receive_time, timezone)), fg=color['fg'])
                    click.secho(f'        latency       | {latency.microseconds / 1000}ms', fg=color['fg'])
                    click.secho(f'        timeout       | {alert.timeout}s', fg=color['fg'])

                    click.secho(f'            alert id     | {alert.id}', fg=color['fg'])
                    click.secho(f'            last recv id | {alert.last_receive_id}', fg=color['fg'])
                    click.secho(f'            customer     | {alert.customer}', fg=color['fg'])
                    click.secho(f'            environment  | {alert.environment}', fg=color['fg'])
                    click.secho('            service      | {}'.format(','.join(alert.service)), fg=color['fg'])
                    click.secho(f'            resource     | {alert.resource}', fg=color['fg'])
                    click.secho(f'            type         | {alert.event_type}', fg=color['fg'])
                    click.secho(f'            repeat       | {alert.repeat}', fg=color['fg'])
                    click.secho(f'            origin       | {alert.origin}', fg=color['fg'])
                    click.secho('            correlate    | {}'.format(','.join(alert.correlate)), fg=color['fg'])

        return auto_refresh, last_time
示例#33
0
 def tabular(self, fields='all', timezone=None):
     if fields == 'summary':
         return {
             'id':
             self.get_id(short=True),
             'lastReceiveTime':
             DateTime.localtime(self.last_receive_time, timezone),
             'severity':
             self.severity,
             'status':
             self.status,
             'duplicateCount':
             self.duplicate_count,
             'customer':
             self.customer,
             'environment':
             self.environment,
             'service':
             ','.join(self.service),
             'resource':
             self.resource,
             'group':
             self.group,
             'event':
             self.event,
             'value':
             self.value,
             'text':
             self.text
         }
     elif fields == 'details':
         return {
             'severity':
             '{} -> {}'.format(self.previous_severity, self.severity),
             'trend':
             self.trend_indication,
             'status':
             self.status,
             'resource':
             self.resource,
             'group':
             self.group,
             'event':
             self.event,
             'value':
             self.value,
             'tags':
             ','.join(self.tags)
         }
     else:
         return {
             'id':
             self.id,
             'resource':
             self.resource,
             'event':
             self.event,
             'environment':
             self.environment,
             'severity':
             self.severity,
             'correlate':
             self.correlate,
             'status':
             self.status,
             'service':
             ','.join(self.service),
             'group':
             self.group,
             'value':
             self.value,
             'text':
             self.text,
             'tags':
             ','.join(self.tags),
             'attributes':
             self.attributes,
             'origin':
             self.origin,
             'type':
             self.event_type,
             'createTime':
             DateTime.localtime(self.create_time, timezone),
             'timeout':
             self.timeout,
             'rawData':
             self.raw_data,
             'customer':
             self.customer,
             'duplicateCount':
             self.duplicate_count,
             'repeat':
             self.repeat,
             'previousSeverity':
             self.previous_severity,
             'trendIndication':
             self.trend_indication,
             'receiveTime':
             DateTime.localtime(self.receive_time, timezone),
             'lastReceiveId':
             self.last_receive_id,
             'lastReceiveTime':
             DateTime.localtime(self.last_receive_time, timezone),
             'history': [h.serialize(timezone) for h in self.history]
         }
示例#34
0
def cli(obj, ids, query, filters, display, from_date=None):
    """Query for alerts based on search filter criteria."""
    client = obj['client']
    timezone = obj['timezone']
    if ids:
        query = [('id', x) for x in ids]
    elif query:
        query = [('q', query)]
    else:
        query = build_query(filters)
    if from_date:
        query.append(('from-date', from_date))

    r = client.http.get('/alerts', query, page=1, page_size=1000)

    if obj['output'] == 'json':
        click.echo(json.dumps(r['alerts'], sort_keys=True, indent=4, ensure_ascii=False))
    elif obj['output'] in ['json_lines', 'jsonl', 'ndjson']:
        for alert in r['alerts']:
            click.echo(json.dumps(alert, ensure_ascii=False))
    else:
        alerts = [Alert.parse(a) for a in r['alerts']]
        last_time = r['lastTime']
        auto_refresh = r['autoRefresh']

        if display == 'tabular':
            headers = {'id': 'ID', 'lastReceiveTime': 'LAST RECEIVED', 'severity': 'SEVERITY', 'status': 'STATUS',
                       'duplicateCount': 'DUPL', 'customer': 'CUSTOMER', 'environment': 'ENVIRONMENT', 'service': 'SERVICE',
                       'resource': 'RESOURCE', 'group': 'GROUP', 'event': 'EVENT', 'value': 'VALUE', 'text': 'TEXT'}
            click.echo(tabulate([a.tabular('summary', timezone)
                                 for a in alerts], headers=headers, tablefmt=obj['output']))
        elif display in ['compact', 'details']:
            for alert in reversed(alerts):
                color = COLOR_MAP.get(alert.severity, {'fg': 'white'})
                click.secho('{}|{}|{}|{:5d}|{}|{:<5s}|{:<10s}|{:<18s}|{:12s}|{:16s}|{:12s}'.format(
                    alert.id[0:8],
                    DateTime.localtime(alert.last_receive_time, timezone),
                    alert.severity,
                    alert.duplicate_count,
                    alert.customer or '-',
                    alert.environment,
                    ','.join(alert.service),
                    alert.resource,
                    alert.group,
                    alert.event,
                    alert.value or 'n/a'), fg=color['fg'])
                click.secho('   |{}'.format(alert.text), fg=color['fg'])

                if display == 'details':
                    click.secho('    severity   | {} -> {}'.format(alert.previous_severity,
                                                                   alert.severity), fg=color['fg'])
                    click.secho('    trend      | {}'.format(alert.trend_indication), fg=color['fg'])
                    click.secho('    status     | {}'.format(alert.status), fg=color['fg'])
                    click.secho('    resource   | {}'.format(alert.resource), fg=color['fg'])
                    click.secho('    group      | {}'.format(alert.group), fg=color['fg'])
                    click.secho('    event      | {}'.format(alert.event), fg=color['fg'])
                    click.secho('    value      | {}'.format(alert.value), fg=color['fg'])
                    click.secho('    tags       | {}'.format(' '.join(alert.tags)), fg=color['fg'])

                    for key, value in alert.attributes.items():
                        click.secho('    {} | {}'.format(key.ljust(10), value), fg=color['fg'])

                    latency = alert.receive_time - alert.create_time

                    click.secho('        time created  | {}'.format(
                        DateTime.localtime(alert.create_time, timezone)), fg=color['fg'])
                    click.secho('        time received | {}'.format(
                        DateTime.localtime(alert.receive_time, timezone)), fg=color['fg'])
                    click.secho('        last received | {}'.format(
                        DateTime.localtime(alert.last_receive_time, timezone)), fg=color['fg'])
                    click.secho('        latency       | {}ms'.format((latency.microseconds / 1000)), fg=color['fg'])
                    click.secho('        timeout       | {}s'.format(alert.timeout), fg=color['fg'])

                    click.secho('            alert id     | {}'.format(alert.id), fg=color['fg'])
                    click.secho('            last recv id | {}'.format(alert.last_receive_id), fg=color['fg'])
                    click.secho('            customer     | {}'.format(alert.customer), fg=color['fg'])
                    click.secho('            environment  | {}'.format(alert.environment), fg=color['fg'])
                    click.secho('            service      | {}'.format(','.join(alert.service)), fg=color['fg'])
                    click.secho('            resource     | {}'.format(alert.resource), fg=color['fg'])
                    click.secho('            type         | {}'.format(alert.event_type), fg=color['fg'])
                    click.secho('            repeat       | {}'.format(alert.repeat), fg=color['fg'])
                    click.secho('            origin       | {}'.format(alert.origin), fg=color['fg'])
                    click.secho('            correlate    | {}'.format(','.join(alert.correlate)), fg=color['fg'])

        return auto_refresh, last_time
示例#35
0
    def update(self):
        self.lines, self.cols = self.screen.getmaxyx()
        self.screen.clear()

        now = datetime.utcnow()
        status = self.client.mgmt_status()
        version = status['version']

        # draw header
        self._addstr(0, 0, self.client.endpoint, curses.A_BOLD)
        self._addstr(0, 'C', 'alerta {}'.format(version), curses.A_BOLD)
        self._addstr(0, 'R', '{}'.format(now.strftime('%H:%M:%S %d/%m/%y')),
                     curses.A_BOLD)

        # TODO - draw bars

        # draw alerts
        text_width = self.cols - 95
        self._addstr(
            2, 1,
            'Sev. Time     Dupl. Customer Env.         Service      Resource     Group Event'
            + '        Value Text' + ' ' * (text_width - 4),
            curses.A_UNDERLINE)

        def short_sev(severity):
            return self.SEVERITY_MAP.get(severity,
                                         self.SEVERITY_MAP['unknown'])[0]

        def color(severity):
            return self.SEVERITY_MAP.get(severity,
                                         self.SEVERITY_MAP['unknown'])[1]

        r = self.client.http.get('/alerts')
        alerts = [Alert.parse(a) for a in r['alerts']]
        last_time = DateTime.parse(r['lastTime'])

        for i, alert in enumerate(alerts):
            row = i + 3
            if row >= self.lines - 2:  # leave room for footer
                break

            text = '{:<4} {} {:5d} {:8.8} {:<12} {:<12} {:<12.12} {:5.5} {:<12.12} {:<5.5} {:.{width}}'.format(
                short_sev(alert.severity),
                DateTime.localtime(alert.last_receive_time,
                                   self.timezone,
                                   fmt='%H:%M:%S'),
                alert.duplicate_count,
                alert.customer or '-',
                alert.environment,
                ','.join(alert.service),
                alert.resource,
                alert.group,
                alert.event,
                alert.value or 'n/a',
                alert.text,
                width=text_width)
            # XXX - needed to support python2 and python3
            if not isinstance(text, str):
                text = text.encode('ascii', errors='replace')

            self._addstr(row, 1, text, color(alert.severity))

        # draw footer
        self._addstr(self.lines - 1, 0,
                     'Last Update: {}'.format(last_time.strftime('%H:%M:%S')),
                     curses.A_BOLD)
        self._addstr(
            self.lines - 1, 'C',
            '{} - {}'.format(r['status'], r.get('message',
                                                'no errors')), curses.A_BOLD)
        self._addstr(self.lines - 1, 'R', 'Count: {}'.format(r['total']),
                     curses.A_BOLD)

        self.screen.refresh()