Newer
Older
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
from pilab.events import utils
logger = logging.getLogger(__name__)
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
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
class EventListener(threading.Thread):
def __init__(self, exchange: str, queue: str, callback: Callable):
super(EventListener, self).__init__()
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 = utils.get_blocking_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:
logger.error(f"Connection was closed, retrying...")
time.sleep(1)
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 closed unexpected, retrying...")
time.sleep(1)