Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import json
import logging
import os
import threading
import traceback
from enum import Enum
from ipaddress import IPv4Address
from typing import List, Optional, Callable
import pika
import pika.exceptions
from pydantic import BaseModel
logger = logging.getLogger(__name__)
logging.getLogger("pika").setLevel(logging.WARNING)
BROKER_ADDRESS = os.getenv('BROKER_ADDRESS') or 'localhost'
BROKER_USER = os.getenv('BROKER_USER') or None
BROKER_PASSWORD = os.getenv('BROKER_PASSWORD') or None
custom_callback: Callable
class EventType(str, Enum):
CREATE = 'create'
UPDATE = 'update'
DELETE = 'delete'
class Host(BaseModel):
"""
representation of host object with id
"""
id: int
mac: str
ipv4_address: IPv4Address
hostname: str
class Pi(Host):
"""
representation of pi object with host id
"""
serial: bytes
display: bool
position: int
ssh_host_ed25519_key: Optional[str]
pass
class Cube(BaseModel):
"""
representation of cube object with host ids
"""
id: int
controller: Host
switch: Host
head: Pi
workers: List[Pi]
pass
class Event(BaseModel):
type: EventType
timestamp: float
payload: Cube
pass
def test_connection():
try:
# Create a connection to the broker
connection = get_connection()
# Declare a channel and a queue
channel = connection.channel()
# Close the connection
connection.close()
except Exception as e:
logger.error(f"Failed to connect to broker; message: {e}")
raise
def get_connection():
if BROKER_USER is not None:
credentials = pika.PlainCredentials(username=BROKER_USER, password=BROKER_PASSWORD)
parameters = pika.ConnectionParameters(host=BROKER_ADDRESS, credentials=credentials)
return pika.BlockingConnection(parameters)
else:
parameters = pika.ConnectionParameters(host=BROKER_ADDRESS)
return pika.BlockingConnection(parameters)
class EventListener(threading.Thread):
def __init__(self, exchange: str, queue: str, callback: Callable):
super(EventListener, self).__init__()
self._is_interrupted = False
self.exchange: str = exchange
self.queue: str = queue
self.callback: Callable = callback
self.channel = None
self.connection = None
def default_callback(self, ch, method, properties, body):
try:
event = Event.parse_obj(json.loads(body.decode('utf-8')))
self.callback(event)
ch.basic_ack(delivery_tag=method.delivery_tag)
logger.info(f"Event processed succesful")
except Exception as e:
traceback.print_exc()
logger.error(f"Failed to process Event; message {e}")
def run(self):
while True:
try:
self.connection = get_connection()
self.channel = self.connection.channel()
self.channel.exchange_declare(exchange=self.exchange, exchange_type='fanout')
self.channel.queue_declare(queue=self.queue, durable=True, exclusive=False, auto_delete=False)
self.channel.queue_bind(exchange=self.exchange, queue=self.queue)
self.channel.basic_consume(queue=self.queue, on_message_callback=self.default_callback, auto_ack=False)
try:
self.channel.start_consuming()
except SystemExit:
logger.info(f"System exit. Close Broker Connection...")
self.channel.stop_consuming()
self.connection.close()
break
except pika.exceptions.ConnectionClosedByBroker:
continue
# Do not recover on channel errors
except pika.exceptions.AMQPChannelError as err:
logger.error(f"Caught a channel error: {err}, stopping...")
break
# Recover on all other connection errors
except pika.exceptions.AMQPConnectionError:
logger.error(f"Connection was closed, retrying...")
continue