guard-service/src/app.py

99 lines
3.4 KiB
Python

#!/usr/bin/env python3
import sys
import json
import logging
import sentry_sdk
import pika
import requests
from sentry_sdk.integrations.logging import LoggingIntegration
import config
import uuid
from mqtt_helper import MQTT
"""
Main entry point
"""
__author__ = "@tormakris"
__copyright__ = "Copyright 2020, Birbnetes Team"
__module_name__ = "app"
__version__text__ = "1"
if config.SENTRY_DSN:
sentry_logging = LoggingIntegration(
level=logging.DEBUG, # Capture info and above as breadcrumbs
event_level=logging.ERROR # Send errors as events
)
sentry_sdk.init(
dsn=config.SENTRY_DSN,
send_default_pii=True,
integrations=[sentry_logging],
traces_sample_rate=1.0,
release=config.RELEASE_ID,
environment=config.RELEASEMODE,
_experiments={"auto_enabling_integrations": True}
)
def setup_rabbit(mqtt_: MQTT) -> None:
logging.info("Connecting to RabbitMQ...")
credentials = pika.PlainCredentials(config.RABBIT_USERNAME, config.RABBIT_PASSWORD)
connection = pika.BlockingConnection(pika.ConnectionParameters(host=config.RABBIT_HOSTNAME,
credentials=credentials,
heartbeat=30,
socket_timeout=45))
channel = connection.channel()
channel.exchange_declare(exchange=config.RABBIT_EXCHANGE, exchange_type='fanout')
queue = channel.queue_declare(durable=True, auto_delete=True, queue=uuid.uuid4().urn.split(':')[2],
exclusive=True).method.queue
channel.queue_bind(exchange=config.RABBIT_EXCHANGE, queue=queue)
channel.basic_consume(queue=queue, on_message_callback=on_message_creator(mqtt_), auto_ack=True)
logging.debug("Starting consumption...")
channel.start_consuming()
def on_message_creator(mqtt_: MQTT):
"""
This generator is used, so that the mqtt object can be injected just when the callback is registered
"""
def on_message(channel, method_frame, header_frame, body):
msg_json = json.loads(body)
if 'probability' not in msg_json:
logging.error("Malformed message from classifier")
return
if 'class' not in msg_json:
logging.error("Malformed message from classifier")
return
# TODO: strurnus should not be hardcoded here
if (msg_json['class'] == 'sturnus') and (msg_json['probability'] > config.TRIGGER_LEVEL):
r = requests.get(f"http://{config.INPUT_HOSTNAME}/sample/{msg_json['tag']}")
r.raise_for_status()
if 'device_id' not in r.json():
logging.error("Input-service response invalid")
return
logging.info(f"Sending alert command to device {r.json()['device_id']}")
mqtt_.publish(subtopic=r.json()['device_id'],
message=json.dumps({"command": "doAlert"}))
return on_message
if __name__ == "__main__":
logging.basicConfig(
stream=sys.stdout,
format="%(asctime)s - %(name)s [%(levelname)s]: %(message)s",
level=logging.DEBUG if '--debug' in sys.argv else logging.INFO
)
logging.info("Guard service starting...")
mqtt = MQTT()
mqtt.topic = config.MQTT_TOPIC
mqtt.connect()
mqtt.client.loop_start() # Start MQTT event loop on a different thread
setup_rabbit(mqtt)