本文整理汇总了Python中alerta.models.alert.Alert类的典型用法代码示例。如果您正苦于以下问题:Python Alert类的具体用法?Python Alert怎么用?Python Alert使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Alert类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_body
def test_get_body(self):
from flask import g
with self.app.test_request_context('/'):
g.login = 'foo'
alert_in = Alert(
resource='test1',
event='event1',
environment='Development',
service=['svc1', 'svc2']
)
self.assertTrue(isinstance(alert_in.create_time, datetime))
self.assertEqual(alert_in.last_receive_time, None)
self.assertTrue(isinstance(alert_in.receive_time, datetime))
self.assertEqual(alert_in.update_time, None)
body = alert_in.get_body()
self.assertEqual(type(body['createTime']), str)
self.assertEqual(body['lastReceiveTime'], None)
self.assertEqual(type(body['receiveTime']), str)
self.assertEqual(body['updateTime'], None)
alert_out = process_alert(alert_in)
self.assertTrue(isinstance(alert_out.create_time, datetime))
self.assertTrue(isinstance(alert_out.last_receive_time, datetime))
self.assertTrue(isinstance(alert_out.receive_time, datetime))
self.assertTrue(isinstance(alert_out.update_time, datetime))
body = alert_out.get_body()
self.assertEqual(type(body['createTime']), str)
self.assertEqual(type(body['lastReceiveTime']), str)
self.assertEqual(type(body['receiveTime']), str)
self.assertEqual(type(body['updateTime']), str)
示例2: get_counts
def get_counts():
query = qb.from_params(request.args)
severity_count = Alert.get_counts_by_severity(query)
status_count = Alert.get_counts_by_status(query)
return jsonify(
status="ok",
total=sum(severity_count.values()),
severityCounts=severity_count,
statusCounts=status_count
)
示例3: process_alert
def process_alert(alert: Alert) -> Alert:
wanted_plugins, wanted_config = plugins.routing(alert)
skip_plugins = False
for plugin in wanted_plugins:
if alert.is_suppressed:
skip_plugins = True
break
try:
alert = plugin.pre_receive(alert, config=wanted_config)
except TypeError:
alert = plugin.pre_receive(alert) # for backward compatibility
except (RejectException, HeartbeatReceived, BlackoutPeriod, RateLimit):
raise
except Exception as e:
if current_app.config['PLUGINS_RAISE_ON_ERROR']:
raise RuntimeError("Error while running pre-receive plugin '{}': {}".format(plugin.name, str(e)))
else:
logging.error("Error while running pre-receive plugin '{}': {}".format(plugin.name, str(e)))
if not alert:
raise SyntaxError("Plugin '%s' pre-receive hook did not return modified alert" % plugin.name)
try:
is_duplicate = alert.is_duplicate()
if is_duplicate:
alert = alert.deduplicate(is_duplicate)
else:
is_correlated = alert.is_correlated()
if is_correlated:
alert = alert.update(is_correlated)
else:
alert = alert.create()
except Exception as e:
raise ApiError(str(e))
updated = None
for plugin in wanted_plugins:
if skip_plugins:
break
try:
updated = plugin.post_receive(alert, config=wanted_config)
except TypeError:
updated = plugin.post_receive(alert) # for backward compatibility
except Exception as e:
if current_app.config['PLUGINS_RAISE_ON_ERROR']:
raise ApiError("Error while running post-receive plugin '{}': {}".format(plugin.name, str(e)))
else:
logging.error("Error while running post-receive plugin '{}': {}".format(plugin.name, str(e)))
if updated:
alert = updated
if updated:
alert.tag(alert.tags)
alert.update_attributes(alert.attributes)
return alert
示例4: housekeeping
def housekeeping():
DEFAULT_EXPIRED_DELETE_HRS = 2 # hours
DEFAULT_INFO_DELETE_HRS = 12 # hours
try:
expired_threshold = int(request.args.get('expired', DEFAULT_EXPIRED_DELETE_HRS))
info_threshold = int(request.args.get('info', DEFAULT_INFO_DELETE_HRS))
except Exception as e:
raise ApiError(str(e), 400)
try:
Alert.housekeeping(expired_threshold, info_threshold)
return 'OK'
except Exception as e:
return 'HOUSEKEEPING FAILED: %s' % e, 503
示例5: process_action
def process_action(alert: Alert, action: str, text: str) -> Tuple[Alert, str, str]:
wanted_plugins, wanted_config = plugins.routing(alert)
updated = None
for plugin in wanted_plugins:
if alert.is_suppressed:
break
try:
updated = plugin.take_action(alert, action, text, config=wanted_config)
except NotImplementedError:
pass # plugin does not support action() method
except RejectException:
raise
except Exception as e:
if current_app.config['PLUGINS_RAISE_ON_ERROR']:
raise ApiError("Error while running action plugin '{}': {}".format(plugin.name, str(e)))
else:
logging.error("Error while running action plugin '{}': {}".format(plugin.name, str(e)))
if updated:
try:
alert, action, text = updated
except Exception:
alert = updated
# remove keys from attributes with None values
new_attrs = {k: v for k, v in alert.attributes.items() if v is not None}
alert.attributes = new_attrs
return alert, action, text
示例6: process_status
def process_status(alert: Alert, status: str, text: str) -> Tuple[Alert, str, str]:
wanted_plugins, wanted_config = plugins.routing(alert)
updated = None
for plugin in wanted_plugins:
if alert.is_suppressed:
break
try:
updated = plugin.status_change(alert, status, text, config=wanted_config)
except TypeError:
updated = plugin.status_change(alert, status, text) # for backward compatibility
except RejectException:
raise
except Exception as e:
if current_app.config['PLUGINS_RAISE_ON_ERROR']:
raise ApiError("Error while running status plugin '{}': {}".format(plugin.name, str(e)))
else:
logging.error("Error while running status plugin '{}': {}".format(plugin.name, str(e)))
if updated:
try:
alert, status, text = updated
except Exception:
alert = updated
# remove keys from attributes with None values
new_attrs = {k: v for k, v in alert.attributes.items() if v is not None}
alert.attributes = new_attrs
return alert, status, text
示例7: pagerduty
def pagerduty():
data = request.json
updated = False
if data and 'messages' in data:
for message in data['messages']:
try:
incident_key, status, text = parse_pagerduty(message)
except ValueError as e:
raise ApiError(str(e), 400)
if not incident_key:
raise ApiError('no incident key in PagerDuty data payload', 400)
customer = g.get('customer', None)
try:
alert = Alert.find_by_id(id=incident_key, customer=customer)
except Exception as e:
raise ApiError(str(e), 500)
if not alert:
raise ApiError("not found", 404)
try:
updated = alert.set_status(status, text)
except Exception as e:
raise ApiError(str(e), 500)
else:
raise ApiError("no messages in PagerDuty data payload", 400)
if updated:
return jsonify(status="ok"), 200
else:
raise ApiError("update PagerDuty incident status failed", 500)
示例8: action_alerts
def action_alerts(alerts: List[str], action: str, text: str, timeout: int) -> None:
updated = []
errors = []
for alert_id in alerts:
alert = Alert.find_by_id(alert_id)
try:
previous_status = alert.status
alert, action, text = process_action(alert, action, text)
alert = alert.from_action(action, text, timeout)
except RejectException as e:
errors.append(str(e))
continue
except InvalidAction as e:
errors.append(str(e))
continue
except Exception as e:
errors.append(str(e))
continue
if previous_status != alert.status:
try:
alert, status, text = process_status(alert, alert.status, text)
alert = alert.from_status(status, text, timeout)
except RejectException as e:
errors.append(str(e))
continue
except Exception as e:
errors.append(str(e))
continue
updated.append(alert.id)
示例9: incoming
def incoming(self, query_string, payload):
if 'callback_query' in payload:
author = payload['callback_query']['from']
user = '{} {}'.format(author.get('first_name'), author.get('last_name'))
command, alert_id = payload['callback_query']['data'].split(' ', 1)
customers = g.get('customers', None)
alert = Alert.find_by_id(alert_id, customers=customers)
if not alert:
jsonify(status='error', message='alert not found for Telegram message')
action = command.lstrip('/')
if action in ['open', 'ack', 'close']:
alert.set_status(status=action, text='status change via Telegram')
elif action in ['watch', 'unwatch']:
alert.untag(tags=['{}:{}'.format(action, user)])
elif action == 'blackout':
environment, resource, event = command.split('|', 2)
blackout = Blackout(environment, resource=resource, event=event)
blackout.create()
send_message_reply(alert, action, user, payload)
text = 'alert updated via telegram webhook'
write_audit_trail.send(current_app._get_current_object(), event='webhook-updated', message=text,
user=g.login, customers=g.customers, scopes=g.scopes, resource_id=alert.id,
type='alert', request=request)
return jsonify(status='ok')
else:
return jsonify(status='ok', message='no callback_query in Telegram message')
示例10: bulk_set_status
def bulk_set_status():
status = request.json.get('status', None)
text = request.json.get('text', 'bulk status update')
timeout = request.json.get('timeout', None)
if not status:
raise ApiError("must supply 'status' as json data", 400)
query = qb.from_params(request.args)
alerts = Alert.find_all(query)
if not alerts:
raise ApiError('not found', 404)
updated = []
errors = []
for alert in alerts:
try:
alert, status, text = process_status(alert, status, text)
except RejectException as e:
errors.append(str(e))
continue
except Exception as e:
errors.append(str(e))
continue
if alert.set_status(status, text, timeout):
updated.append(alert.id)
if errors:
raise ApiError('failed to bulk set alert status', 500, errors=errors)
else:
return jsonify(status='ok', updated=updated, count=len(updated))
示例11: telegram
def telegram():
data = request.json
if 'callback_query' in data:
author = data['callback_query']['from']
user = "{} {}".format(author.get('first_name'), author.get('last_name'))
command, alert_id = data['callback_query']['data'].split(' ', 1)
alert = Alert.find_by_id(alert_id)
if not alert:
jsonify(status="error", message="alert not found for Telegram message")
action = command.lstrip('/')
if action in ['open', 'ack', 'close']:
alert.set_status(status=action, text='status change via Telegram')
elif action in ['watch', 'unwatch']:
alert.untag(tags=["{}:{}".format(action, user)])
elif action == 'blackout':
environment, resource, event = alert.split('|', 2)
blackout = Blackout(environment, resource=resource, event=event)
blackout.create()
send_message_reply(alert, action, user, data)
return jsonify(status="ok")
else:
return jsonify(status="error", message="no callback_query in Telegram message"), 400
示例12: incoming
def incoming(self, query_string, payload):
if payload and payload['state'] == 'alerting':
return [parse_grafana(payload, match, query_string) for match in payload.get('evalMatches', [])]
elif payload and payload['state'] == 'ok' and payload.get('ruleId'):
try:
query = qb.from_dict({'attributes.ruleId': str(payload['ruleId'])})
existingAlerts = Alert.find_all(query)
except Exception as e:
raise ApiError(str(e), 500)
alerts = []
for updateAlert in existingAlerts:
updateAlert.severity = 'normal'
updateAlert.status = 'closed'
try:
alert = process_alert(updateAlert)
except RejectException as e:
raise ApiError(str(e), 403)
except Exception as e:
raise ApiError(str(e), 500)
alerts.append(alert)
return alerts
else:
raise ApiError('no alerts in Grafana notification payload', 400)
示例13: receive
def receive():
try:
incomingAlert = Alert.parse(request.json)
except ValueError as e:
raise ApiError(str(e), 400)
if g.get('customer', None):
incomingAlert.customer = g.get('customer')
add_remote_ip(request, incomingAlert)
try:
alert = process_alert(incomingAlert)
except RejectException as e:
raise ApiError(str(e), 403)
except RateLimit as e:
return jsonify(status="error", message=str(e), id=incomingAlert.id), 429
except BlackoutPeriod as e:
return jsonify(status="ok", message=str(e), id=incomingAlert.id), 202
except Exception as e:
raise ApiError(str(e), 500)
if alert:
return jsonify(status="ok", id=alert.id, alert=alert.serialize), 201
else:
raise ApiError("insert or update of received alert failed", 500)
示例14: incoming
def incoming(self, query_string, payload):
updated = False
if payload and 'messages' in payload:
for message in payload['messages']:
try:
incident_key, status, text = parse_pagerduty(message)
except ValueError as e:
raise ApiError(str(e), 400)
if not incident_key:
raise ApiError('no incident key in PagerDuty data payload', 400)
customers = g.get('customers', None)
try:
alert = Alert.find_by_id(id=incident_key, customers=customers)
except Exception as e:
raise ApiError(str(e), 500)
if not alert:
raise ApiError('not found', 404)
try:
updated = alert.set_status(status, text)
except Exception as e:
raise ApiError(str(e), 500)
if updated:
return jsonify(status='ok')
else:
raise ApiError('update PagerDuty incident status failed', 500)
else:
raise ApiError('no messages in PagerDuty data payload', 400)
示例15: bulk_update_attributes
def bulk_update_attributes():
if not request.json.get('attributes', None):
raise ApiError("must supply 'attributes' as json data", 400)
query = qb.from_params(request.args)
updated = Alert.update_attributes_find_all(query, request.json['attributes'])
return jsonify(status='ok', updated=updated, count=len(updated))