2015-12-12 22:34:08 +00:00
|
|
|
|
|
|
|
import click
|
2015-12-13 15:11:22 +00:00
|
|
|
import json
|
2016-03-21 21:42:39 +00:00
|
|
|
import logging
|
2016-02-28 20:37:56 +00:00
|
|
|
import requests
|
2016-03-21 21:42:39 +00:00
|
|
|
from datetime import datetime
|
2015-12-12 22:34:08 +00:00
|
|
|
from certidude import config
|
|
|
|
|
2015-12-13 15:11:22 +00:00
|
|
|
|
2015-12-12 22:34:08 +00:00
|
|
|
def publish(event_type, event_data):
|
|
|
|
"""
|
2017-02-07 22:07:21 +00:00
|
|
|
Publish event on nchan EventSource publisher
|
2015-12-12 22:34:08 +00:00
|
|
|
"""
|
2017-03-26 00:10:09 +00:00
|
|
|
assert event_type, "No event type specified"
|
|
|
|
assert event_data, "No event data specified"
|
2017-02-07 22:07:21 +00:00
|
|
|
if not config.EVENT_SOURCE_PUBLISH:
|
2016-09-18 11:32:39 +00:00
|
|
|
# Push server disabled
|
|
|
|
return
|
|
|
|
|
2016-03-21 21:42:39 +00:00
|
|
|
if not isinstance(event_data, basestring):
|
2015-12-13 15:11:22 +00:00
|
|
|
from certidude.decorators import MyEncoder
|
|
|
|
event_data = json.dumps(event_data, cls=MyEncoder)
|
|
|
|
|
2017-02-07 22:07:21 +00:00
|
|
|
url = config.EVENT_SOURCE_PUBLISH % config.EVENT_SOURCE_TOKEN
|
2016-04-05 12:02:05 +00:00
|
|
|
click.echo("Publishing %s event '%s' on %s" % (event_type, event_data, url))
|
2015-12-13 15:11:22 +00:00
|
|
|
|
2016-03-21 21:42:39 +00:00
|
|
|
try:
|
|
|
|
notification = requests.post(
|
|
|
|
url,
|
|
|
|
data=event_data,
|
|
|
|
headers={"X-EventSource-Event": event_type, "User-Agent": "Certidude API"})
|
2016-09-17 21:00:14 +00:00
|
|
|
if notification.status_code == requests.codes.created:
|
|
|
|
pass # Sent to client
|
|
|
|
elif notification.status_code == requests.codes.accepted:
|
|
|
|
pass # Buffered in nchan
|
|
|
|
else:
|
|
|
|
click.echo("Failed to submit event to push server, server responded %d" % (
|
|
|
|
notification.status_code))
|
2016-03-21 21:42:39 +00:00
|
|
|
except requests.exceptions.ConnectionError:
|
2016-04-05 12:02:05 +00:00
|
|
|
click.echo("Failed to submit event to push server, connection error")
|
2016-03-21 21:42:39 +00:00
|
|
|
|
2016-09-17 21:00:14 +00:00
|
|
|
|
2017-02-07 22:07:21 +00:00
|
|
|
class EventSourceLogHandler(logging.Handler):
|
2016-03-21 21:42:39 +00:00
|
|
|
"""
|
|
|
|
To be used with Python log handling framework for publishing log entries
|
|
|
|
"""
|
|
|
|
def emit(self, record):
|
|
|
|
publish("log-entry", dict(
|
2016-04-05 12:30:50 +00:00
|
|
|
created = datetime.utcfromtimestamp(record.created),
|
2016-03-21 21:42:39 +00:00
|
|
|
message = record.msg % record.args,
|
|
|
|
severity = record.levelname.lower()))
|
2015-12-12 22:34:08 +00:00
|
|
|
|