Compare commits

..

No commits in common. "223eeff0be12ed8e6749550bfdc9e74c37556f70" and "488f17317604eb5fb124aa46dd67aed756750dc6" have entirely different histories.

3 changed files with 21 additions and 76 deletions

View File

@ -1,7 +1,5 @@
import asyncio import asyncio
import os
import sys import sys
import time
import threading import threading
from queue import Queue from queue import Queue
from loguru import logger from loguru import logger
@ -16,10 +14,6 @@ def init_logger():
async def main(): async def main():
# LAZY HACK THIS IS BAD
# TODO: Get rid of this trash and add retries if RabbitMQ isn't ready
time.sleep(5)
config = load_config("config.json") config = load_config("config.json")
queue = Queue() queue = Queue()
monitor = EventMonitor( monitor = EventMonitor(
@ -34,20 +28,15 @@ async def main():
monitor_thread.start() monitor_thread.start()
# RabbitMQ # RabbitMQ
host = os.getenv("RABBITMQ_HOST", "localhost") host = 'localhost'
port = 5672 port = 5672
exchange = 'matrix_alerts' exchange = 'matrix_alerts'
producer = RabbitMQProducer(host=host, port=port, exchange=exchange) producer = RabbitMQProducer(host=host, port=port, exchange=exchange)
while True: while True:
alert_text = queue.get() alert_text = queue.get()
try:
producer.send_event(message={'body': alert_text}) producer.send_event(message={'body': alert_text})
queue.task_done() queue.task_done()
except Exception as e:
logger.error(f"bigtime issue here: {e}")
queue.put(alert_text)
# try: # try:
# await bot.send_markdown(event) # await bot.send_markdown(event)

View File

@ -1,4 +1,3 @@
pika
loguru loguru
web3 web3
requests requests

View File

@ -1,6 +1,5 @@
import json import json
import pika import pika
import time
from loguru import logger from loguru import logger
@ -11,39 +10,20 @@ class RabbitMQProducer:
self.exchange = exchange self.exchange = exchange
self.exchange_type = exchange_type self.exchange_type = exchange_type
self.max_retries = 5
self.initial_delay = 1 # Initial delay in seconds for exponential backoff
self.connection = None self.connection = None
self.channel = None self.channel = None
self.connect() self.connect()
def connect(self): def connect(self):
retries = 0
while retries < self.max_retries:
try: try:
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port)) self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
self.channel = self.connection.channel() self.channel = self.connection.channel()
self.channel.exchange_declare(exchange=self.exchange, exchange_type=self.exchange_type) self.channel.exchange_declare(exchange=self.exchange, exchange_type=self.exchange_type)
logger.info(f"Successfully connected to RabbitMQ at {self.host}:{self.port}")
return
except Exception as e: except Exception as e:
retries += 1 logger.warning(f"Could not connect to RabbitMQ: {e}")
wait_time = self.initial_delay * (2 ** (retries - 1))
logger.warning(f"Could not connect to RabbitMQ (attempt {retries}/{self.max_retries}): {e}")
if retries < self.max_retries:
logger.info(f"Retrying in {wait_time} seconds...")
time.sleep(wait_time)
else:
logger.error("All connection attempts failed.")
raise
def send_event(self, message: dict): def send_event(self, message: dict):
retries = 0 if self.connection.is_closed:
while retries < self.max_retries:
if self.connection is None or not self.connection.is_open:
logger.info("Connection is closed. Reconnecting...")
self.connect() self.connect()
try: try:
@ -53,32 +33,9 @@ class RabbitMQProducer:
body=json.dumps(message), body=json.dumps(message),
properties=pika.BasicProperties(content_type='application/json') properties=pika.BasicProperties(content_type='application/json')
) )
logger.info(f"Message sent: {message}")
return
except pika.exceptions.AMQPConnectionError as e:
retries += 1
wait_time = self.initial_delay * (2 ** (retries - 1))
logger.warning(f"Connection error (attempt {retries}/{self.max_retries}): {e}")
if retries < self.max_retries:
logger.info(f"Retrying in {wait_time} seconds...")
self.connect()
time.sleep(wait_time)
else:
logger.error("All retry attempts failed.")
raise
except Exception as e: except Exception as e:
logger.warning(f"Failed to send message: {e}") logger.warning(f"Failed to send message: {e}")
raise
def close_connection(self): def close_connection(self):
if self.connection and self.connection.is_open: if self.connection and not self.connection.is_closed:
self.connection.close() self.connection.close()
# Usage example:
if __name__ == "__main__":
producer = RabbitMQProducer(host='localhost', port=5672, exchange='logs')
try:
producer.send_event({"message": "Hello, RabbitMQ!"})
finally:
producer.close_connection()