예제 #1
0
def push_entity(obj, entity):
    """Push one or more entities"""
    client = get_client(obj.config)

    if (entity.endswith('.json')
            or entity.endswith('.yaml')) and os.path.exists(entity):
        with open(entity, 'rb') as fd:
            data = yaml.safe_load(fd)
    else:
        data = json.loads(entity)

    if not isinstance(data, list):
        data = [data]

    with Action('Creating new entities ...', nl=True) as act:
        for e in data:
            action('Creating entity {} ...'.format(e['id']))
            try:
                client.add_entity(e)
                ok()
            except ZmonArgumentError as e:
                act.error(str(e))
            except requests.HTTPError as e:
                log_http_exception(e, act)
            except Exception as e:
                act.error('Failed: {}'.format(str(e)))
예제 #2
0
파일: token.py 프로젝트: vetinari/zmon-cli
def get_tv_token(obj):
    """Retrieve a new token"""
    client = get_client(obj.config)

    with Action('Retrieving new one-time token ...', nl=True):
        token = client.get_onetime_token()
        ok(client.token_login_url(token.strip('"')))
예제 #3
0
파일: search.py 프로젝트: vetinari/zmon-cli
def search(obj, search_query, team, limit, output, pretty):
    """
    Search dashboards, alerts, checks and grafana dashboards.

    Example:

        $ zmon search "search query" -t team-1 -t team-2
    """
    client = get_client(obj.config)

    with Output('Searching ...',
                nl=True,
                output=output,
                pretty_json=pretty,
                printer=render_search) as act:
        try:
            data = client.search(search_query, limit=limit, teams=team)

            for check in data['checks']:
                check['link'] = client.check_definition_url(check)

            for alert in data['alerts']:
                alert['link'] = client.alert_details_url(alert)

            for dashboard in data['dashboards']:
                dashboard['link'] = client.dashboard_url(dashboard['id'])

            for dashboard in data['grafana_dashboards']:
                dashboard['link'] = client.grafana_dashboard_url(dashboard)

            act.echo(data)
        except ZmonArgumentError as e:
            act.error(str(e))
예제 #4
0
def delete_entity(obj, entity_id):
    """Delete a single entity by ID"""
    client = get_client(obj.config)

    with Action('Deleting entity {} ...'.format(entity_id)) as act:
        deleted = client.delete_entity(entity_id)
        if not deleted:
            act.error('Failed')
예제 #5
0
def dashboard_get(obj, dashboard_id, output, pretty):
    """Get ZMON dashboard"""
    client = get_client(obj.config)
    with Output('Retrieving dashboard ...',
                nl=True,
                output=output,
                pretty_json=pretty) as act:
        dashboard = client.get_dashboard(dashboard_id)
        act.echo(dashboard)
예제 #6
0
def delete_check_definition(obj, check_id):
    """Delete an orphan check definition"""
    client = get_client(obj.config)

    with Action('Deleting check {} ...'.format(check_id)) as act:
        resp = client.delete_check_definition(check_id)

        if not resp.ok:
            act.error(resp.text)
예제 #7
0
def get_entity(obj, entity_id, output, pretty):
    """Get a single entity by ID"""
    client = get_client(obj.config)

    with Output('Retrieving entity {} ...'.format(entity_id),
                nl=True,
                output=output,
                pretty_json=pretty) as act:
        entity = client.get_entity(entity_id)
        act.echo(entity)
예제 #8
0
def filter_entities(obj, key, value, output, pretty):
    """List entities filtered by a certain key"""
    client = get_client(obj.config)
    with Output('Retrieving and filtering entities ...',
                nl=True,
                output=output,
                printer=render_entities,
                pretty_json=pretty) as act:
        entities = client.get_entities(query={key: value})
        entities = sorted(entities, key=entity_last_modified)
        act.echo(entities)
예제 #9
0
def entities(ctx, output, pretty):
    """Manage entities"""
    if not ctx.invoked_subcommand:
        client = get_client(ctx.obj.config)

        with Output('Retrieving all entities ...',
                    output=output,
                    printer=render_entities,
                    pretty_json=pretty) as act:
            entities = client.get_entities()
            act.echo(entities)
예제 #10
0
def dashboard_update(obj, yaml_file):
    """Create/Update a single ZMON dashboard"""
    client = get_client(obj.config)
    dashboard = {}
    with open(yaml_file, 'rb') as f:
        dashboard = yaml.safe_load(f)

    msg = 'Creating new dashboard ...'
    if 'id' in dashboard:
        msg = 'Updating dashboard {} ...'.format(dashboard.get('id'))

    with Action(msg, nl=True):
        dash_id = client.update_dashboard(dashboard)
        ok(client.dashboard_url(dash_id))
예제 #11
0
파일: alert.py 프로젝트: vetinari/zmon-cli
def create_alert_definition(obj, yaml_file):
    """Create a single alert definition"""
    client = get_client(obj.config)

    alert = yaml.safe_load(yaml_file)

    alert['last_modified_by'] = obj.config.get('user', 'unknown')

    with Action('Creating alert definition ...', nl=True) as act:
        try:
            new_alert = client.create_alert_definition(alert)
            ok(client.alert_details_url(new_alert))
        except ZmonArgumentError as e:
            act.error(str(e))
예제 #12
0
def grafana_update(obj, yaml_file):
    """Create/Update a single ZMON dashboard"""
    dashboard = yaml.safe_load(yaml_file)

    title = dashboard.get('dashboard', {}).get('title', '')

    client = get_client(obj.config)

    with Action('Updating dashboard {} ...'.format(title), nl=True) as act:
        try:
            client.update_grafana_dashboard(dashboard)
            ok(client.grafana_dashboard_url(dashboard))
        except ZmonArgumentError as e:
            act.error(e)
예제 #13
0
def update(obj, yaml_file, skip_validation):
    """Update a single check definition"""
    check = yaml.safe_load(yaml_file)

    check['last_modified_by'] = obj.get('user', 'unknown')

    client = get_client(obj.config)

    with Action('Updating check definition ...', nl=True) as act:
        try:
            check = client.update_check_definition(
                check, skip_validation=skip_validation)
            ok(client.check_definition_url(check))
        except ZmonArgumentError as e:
            act.error(str(e))
예제 #14
0
파일: alert.py 프로젝트: vetinari/zmon-cli
def list_alert_definitions(obj, output, pretty):
    """List all active alert definitions"""
    client = get_client(obj.config)

    with Output('Retrieving active alert definitions ...',
                nl=True,
                output=output,
                pretty_json=pretty,
                printer=render_alerts) as act:
        alerts = client.get_alert_definitions()

        for alert in alerts:
            alert['link'] = client.alert_details_url(alert)

        act.echo(alerts)
예제 #15
0
def list_check_definitions(obj, output, pretty):
    """List all active check definitions"""
    client = get_client(obj.config)

    with Output('Retrieving active check definitions ...',
                nl=True,
                output=output,
                pretty_json=pretty,
                printer=render_checks) as act:
        checks = client.get_check_definitions()

        for check in checks:
            check['link'] = client.check_definition_url(check)

        act.echo(checks)
예제 #16
0
파일: alert.py 프로젝트: vetinari/zmon-cli
def get_alert_definition(obj, alert_id, output, pretty):
    """Get a single alert definition"""
    client = get_client(obj.config)

    with Output('Retrieving alert definition ...',
                nl=True,
                output=output,
                pretty_json=pretty) as act:
        alert = client.get_alert_definition(alert_id)

        keys = list(alert.keys())
        for k in keys:
            if alert[k] is None:
                del alert[k]

        act.echo(alert)
예제 #17
0
def get_check_definition(obj, check_id, output, pretty):
    """Get a single check definition"""
    client = get_client(obj.config)

    with Output('Retrieving check definition ...',
                nl=True,
                output=output,
                pretty_json=pretty) as act:
        check = client.get_check_definition(check_id)

        keys = list(check.keys())
        for k in keys:
            if check[k] is None:
                del check[k]

        act.echo(check)
예제 #18
0
파일: token.py 프로젝트: vetinari/zmon-cli
def list_tv_token(obj, output, pretty):
    """List onetime tokens for your user"""
    client = get_client(obj.config)

    with Output('Retrieving onetime tokens ...',
                nl=True,
                output=output,
                pretty_json=pretty) as act:
        tokens = client.list_onetime_tokens()

        for t in tokens:
            t['created'] = datetime.fromtimestamp(t['created'] / 1000)
            if t['bound_at'] is not None:
                t['bound_at'] = datetime.fromtimestamp(t['bound_at'] / 1000)

        act.echo(tokens)
예제 #19
0
def filter_check_definitions(obj, field, value, output, pretty):
    """Filter active check definitions"""
    client = get_client(obj.config)

    with Output('Retrieving and filtering check definitions ...',
                nl=True,
                output=output,
                pretty_json=pretty,
                printer=render_checks) as act:
        checks = client.get_check_definitions()

        filtered = [check for check in checks if check.get(field) == value]

        for check in filtered:
            check['link'] = client.check_definition_url(check)

        act.echo(filtered)
예제 #20
0
def create_downtime(obj, entity_ids, duration, comment, output, pretty):
    """Create downtime for specified entities"""
    client = get_client(obj.config)

    start_ts = time.time()
    end_ts = time.time() + (duration * 60)

    downtime = {
        'entities': entity_ids,
        'comment': comment or 'downtime by ZMON CLI',
        'start_time': start_ts,
        'end_time': end_ts
    }

    with Output('Creating downtime ...', nl=True, output=output, pretty_json=pretty) as act:
        try:
            new_downtime = client.create_downtime(downtime)
            act.echo(new_downtime)
        except ZmonArgumentError as e:
            act.error(str(e))
예제 #21
0
파일: alert.py 프로젝트: vetinari/zmon-cli
def filter_alert_definitions(obj, field, value, output, pretty):
    """Filter active alert definitions"""
    client = get_client(obj.config)

    with Output('Retrieving and filtering alert definitions ...',
                nl=True,
                output=output,
                pretty_json=pretty,
                printer=render_alerts) as act:
        alerts = client.get_alert_definitions()

        if field == 'check_definition_id':
            value = int(value)

        filtered = [alert for alert in alerts if alert.get(field) == value]

        for alert in filtered:
            alert['link'] = client.alert_details_url(alert)

        act.echo(filtered)
예제 #22
0
파일: alert.py 프로젝트: vetinari/zmon-cli
def update_alert_definition(obj, yaml_file):
    """Update a single alert definition"""
    alert = yaml.safe_load(yaml_file)

    alert['last_modified_by'] = obj.config.get('user', 'unknown')

    client = get_client(obj.config)

    with Action('Updating alert definition ...', nl=True) as act:
        try:
            # Workaround API inconsistency!
            if alert.get('parameters'):
                for k, v in alert['parameters'].items():
                    if type(v) is str:
                        alert['parameters'][k] = json.loads(v)

            client.update_alert_definition(alert)
            ok(client.alert_details_url(alert))
        except ZmonArgumentError as e:
            act.error(str(e))
예제 #23
0
def data(obj, alert_id, entity_ids, output, pretty):
    """Get check data for alert and entities"""
    client = get_client(obj.config)

    with Output('Retrieving alert data ...',
                nl=True,
                output=output,
                pretty_json=pretty) as act:
        data = client.get_alert_data(alert_id)

        if not entity_ids:
            result = data
        else:
            result = [d for d in data if d['entity'] in entity_ids]

        values = {
            v['entity']: v['results'][0]['value']
            for v in result if len(v['results'])
        }

        act.echo(values)
예제 #24
0
def filter_entities(obj, filters, output, pretty):
    """
    List entities filtered by key values pairs

    E.g.:
        zmon entities filter type instance application_id my-app
    """
    client = get_client(obj.config)

    if len(filters) % 2:
        fatal_error('Invalid filters count: expected even number of args!')

    with Output('Retrieving and filtering entities ...',
                nl=True,
                output=output,
                printer=render_entities,
                pretty_json=pretty) as act:

        query = dict(zip(filters[0::2], filters[1::2]))

        entities = client.get_entities(query=query)
        entities = sorted(entities, key=entity_last_modified)

        act.echo(entities)
예제 #25
0
파일: alert.py 프로젝트: vetinari/zmon-cli
def delete_alert_definition(obj, alert_id):
    """Delete a single alert definition"""
    client = get_client(obj.config)

    with Action('Deleting alert definition ...'):
        client.delete_alert_definition(alert_id)