sintonia/playout/libretime_playout/message_handler.py

109 lines
3.1 KiB
Python
Raw Normal View History

import json
from queue import Queue as ThreadQueue
from signal import SIGTERM, signal
from time import sleep
from typing import Any, Dict
# For RabbitMQ
from kombu.connection import Connection
from kombu.messaging import Exchange, Queue
from kombu.mixins import ConsumerMixin
feat(playout): enhance playout logging (#1495) Some initial work on modernizing the playout app. This replace any custom logger or logging based logger with the logging tools from libretime_shared.logging and loguru. Removed all the thread/function assigned logger (self.logger = ...), as this makes it part of the logic (passing logger though function args) as it should not. Of a dedicated logger is required for a specific task, it should use the create_task_logger function. - refactor: remove dead code - refactor: remove py2 specific fix - feat: remove unused test command - feat: setup shared cli and logging tools - feat: replace logging with loguru - feat: setup shared cli and logging tools for notify - fix: warn method deos not exist - feat: make cli setup the entrypoint - fix: install shared modules globally in production use extra_requires to load local packages in dev environement - feat: configure log path in systemd service - feat: default behavior is to log to console only - feat: create log dir during install - chore: add comment - fix: don't create useless dir in install - fix: move notify logs to /var/log/libretime dir - fix: update setup_logger attrs - style: linting - fix: replace verbosity flag with log-level flag - feat: use shared logging tool in liquidsoap - fix: pass logger down to api client - feat: allow custom log_filepath in liquidsoap config - chore: add pylintrc to playout - refactor: fix pylint errors - feat: set liquidsoap log filepath in systemd service - fix: missing setup entrypoint update BREAKING CHANGE: for playout and liquidsoap the default log file path changed to None and will only log to the console when developing / testing. Unless you are running the app as a systemd service (production) the default logs filepaths changed: from "/var/log/airtime/pypo/pypo.log" to "/var/log/libretime/playout.log" and from "/var/log/airtime/pypo-liquidsoap/ls_script.log" to "/var/log/libretime/liquidsoap.log" BREAKING CHANGE: for playout-notify the default log file path changed from "/var/log/airtime/pypo/notify.log" to "/var/log/libretime/playout-notify.log"
2022-01-13 16:11:37 +01:00
from loguru import logger
from .config import Config
class MessageHandler(ConsumerMixin):
def __init__(
self,
connection: Connection,
fetch_queue: ThreadQueue,
recorder_queue: ThreadQueue,
):
self.connection = connection
self.fetch_queue = fetch_queue
self.recorder_queue = recorder_queue
def get_consumers(self, Consumer, channel):
exchange = Exchange("airtime-pypo", "direct", durable=True, auto_delete=True)
queues = [Queue("pypo-fetch", exchange=exchange, key="foo")]
return [
Consumer(queues, callbacks=[self.on_message], accept=["text/plain"]),
]
def on_message(self, body, message):
logger.debug(f"received message: {body}")
try:
try:
body = body.decode()
except (UnicodeDecodeError, AttributeError):
pass
payload = json.loads(body)
command = payload["event_type"]
logger.info(f"handling command: {command}")
if command in (
"update_schedule",
"reset_liquidsoap_bootstrap",
"update_stream_format",
"update_message_offline",
"update_station_name",
"switch_source",
"update_transition_fade",
"disconnect_source",
):
self.fetch_queue.put(message.payload)
elif command in (
"update_recorder_schedule",
"cancel_recording",
):
self.recorder_queue.put(message.payload)
else:
logger.warning(f"invalid command: {command}")
except Exception as exception:
logger.exception(exception)
message.ack()
2021-05-27 16:23:02 +02:00
2022-08-14 19:55:39 +02:00
class MessageListener:
def __init__(
self,
config: Config,
fetch_queue: ThreadQueue[Dict[str, Any]],
recorder_queue: ThreadQueue[Dict[str, Any]],
) -> None:
self.config = config
self.fetch_queue = fetch_queue
self.recorder_queue = recorder_queue
def run_forever(self):
while True:
2021-05-27 16:23:02 +02:00
with Connection(
self.config.rabbitmq.url,
2021-05-27 16:23:02 +02:00
heartbeat=5,
transport_options={"client_properties": {"connection_name": "playout"}},
2021-05-27 16:23:02 +02:00
) as connection:
handler = MessageHandler(
connection=connection,
fetch_queue=self.fetch_queue,
recorder_queue=self.recorder_queue,
)
def shutdown(_signum, _frame):
raise SystemExit()
2021-05-27 16:23:02 +02:00
signal(SIGTERM, shutdown)
logger.info("starting message handler")
handler.run()
sleep(5)