Compare commits

...
7 Commits
Author SHA1 Message Date
ashish b63a13caa1 Adjustment to stop script 2026-01-24 10:42:50 -06:00
ashish 9ed37905c8 Another bugfix 2023-11-22 19:36:40 -06:00
ashish a3b2e0e22c Fixed AttributeError in NtfyRouter #5
Squashed commit of the following:

commit 49daddff83a18e0eba4ab04899937f8962df2379
Author: Ashish D'Souza <[email protected]>
Date:   Wed Nov 22 18:55:58 2023 -0600

    Fixed wrong variable name
2023-11-22 18:56:31 -06:00
ashish a14ae8581a Added ntfy router #2
Squashed commit of the following:

commit 3ba0c9b4c6
Author: Ashish D'Souza <[email protected]>
Date:   Sun Nov 19 05:21:27 2023 -0600

    Another bugfix

commit 8a76bddbf1
Author: Ashish D'Souza <[email protected]>
Date:   Sun Nov 19 05:12:40 2023 -0600

    Added ntfy router to ansible scripts

commit 7b51846e1b
Author: Ashish D'Souza <[email protected]>
Date:   Sun Nov 19 05:12:14 2023 -0600

    Fixed inconsistent variable names bug

commit a96a14e261
Author: Ashish D'Souza <[email protected]>
Date:   Sun Nov 19 04:53:09 2023 -0600

    Added ntfy router to docker compose

commit d2f30faa5e
Author: Ashish D'Souza <[email protected]>
Date:   Sun Nov 19 04:52:07 2023 -0600

    Added ntfy routing
2023-11-19 06:17:01 -06:00
ashish 1640a7a590 Updated Docker Compose configuration 2023-11-11 03:45:54 -06:00
ashish 2ca06e8cc6 Added Ansible playbooks 2023-11-10 01:01:19 -06:00
ashish b1c16a00ff Enabled NACK on exception 2023-11-10 00:18:57 -06:00
12 changed files with 428 additions and 12 deletions

No files matched your search

+22 -6
View File
@@ -9,14 +9,14 @@ services:
retries: 3 retries: 3
timeout: 10s timeout: 10s
start_period: 30s start_period: 30s
start_interval: 5s #start_interval: 5s
volumes: volumes:
- type: bind - type: bind
source: /etc/localtime source: /etc/localtime
target: /etc/localtime target: /etc/localtime
read_only: true read_only: true
ports: ports:
- 5672:5672 - 10000:5672
bedroom-speaker-player: bedroom-speaker-player:
container_name: broadcast-bedroom-speaker-player container_name: broadcast-bedroom-speaker-player
image: broadcast-player:latest image: broadcast-player:latest
@@ -27,11 +27,11 @@ services:
command: ['google_home', 'bedroom_speaker'] command: ['google_home', 'bedroom_speaker']
environment: environment:
RABBITMQ_HOST: localhost RABBITMQ_HOST: localhost
RABBITMQ_PORT: 5672 RABBITMQ_PORT: 10000
RABBITMQ_TOPICS: 'notification.*.ashish.*,call.*.ashish,alarm.*.ashish' RABBITMQ_TOPICS: 'notification.*.ashish.*,call.*.ashish,alarm.*.ashish'
GOOGLE_HOME_NAME: Bedroom speaker GOOGLE_HOME_NAME: Bedroom speaker
HTTP_IP: 192.168.0.10 HTTP_IP: ${SERVER_IP}
HTTP_PORT: 24984 HTTP_PORT: 10001
volumes: volumes:
- type: volume - type: volume
source: bedroom-speaker-audio source: bedroom-speaker-audio
@@ -41,6 +41,22 @@ services:
target: /etc/localtime target: /etc/localtime
read_only: true read_only: true
network_mode: host network_mode: host
ntfy-router:
container_name: broadcast-ntfy-router
image: broadcast-ntfy-router:latest
restart: unless-stopped
depends_on:
rabbitmq:
condition: service_healthy
environment:
RABBITMQ_HOST: localhost
RABBITMQ_PORT: 10000
volumes:
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
network_mode: host
nginx: nginx:
container_name: broadcast-nginx container_name: broadcast-nginx
image: nginx:1.25.2 image: nginx:1.25.2
@@ -55,7 +71,7 @@ services:
target: /etc/localtime target: /etc/localtime
read_only: true read_only: true
ports: ports:
- 192.168.0.10:24984:80 - ${SERVER_IP}:10001:80
volumes: volumes:
bedroom-speaker-audio: bedroom-speaker-audio:
+117
View File
@@ -0,0 +1,117 @@
- name: Install Broadcast
hosts: Lothlorien
tasks:
- name: Create Broadcast bedroom speaker audio Docker volume directory
become: true
ansible.builtin.file:
path: /data/broadcast-bedroom-speaker-audio
state: directory
- name: Create Broadcast bedroom speaker audio Docker volume
community.docker.docker_volume:
volume_name: broadcast-bedroom-speaker-audio
driver: local
driver_options:
type: none
o: bind
device: /data/broadcast-bedroom-speaker-audio
- name: Create temporary Docker build directory for broadcast-player
ansible.builtin.tempfile:
state: directory
register: docker_build_dir
- name: Copy Docker build directory
ansible.builtin.copy:
src: player/
dest: '{{docker_build_dir.path}}'
mode: preserve
- name: Build broadcast-player Docker image
ansible.builtin.docker_image:
build:
path: '{{docker_build_dir.path}}'
name: broadcast-player
tag: latest
source: build
force_source: true
state: present
- name: Remove temporary Docker build directory
become: true
ansible.builtin.file:
path: '{{docker_build_dir.path}}'
state: absent
- name: Create temporary Docker build directory for broadcast-ntfy-router
ansible.builtin.tempfile:
state: directory
register: docker_build_dir
- name: Copy Docker build directory
ansible.builtin.copy:
src: ntfy_router/
dest: '{{docker_build_dir.path}}'
mode: preserve
- name: Build broadcast-ntfy-router Docker image
ansible.builtin.docker_image:
build:
path: '{{docker_build_dir.path}}'
name: broadcast-ntfy-router
tag: latest
source: build
force_source: true
state: present
- name: Remove temporary Docker build directory
become: true
ansible.builtin.file:
path: '{{docker_build_dir.path}}'
state: absent
- name: Read homelab config
ansible.builtin.slurp:
src: '{{ansible_user_dir}}/.homelab.json'
register: homelab_config_file
- name: Set homelab_config variable
ansible.builtin.set_fact:
homelab_config: '{{homelab_config_file.content|b64decode|from_json}}'
- name: Insert into Postgres table service
community.postgresql.postgresql_query:
login_host: '{{homelab_config.database.host}}'
login_user: '{{homelab_config.database.user}}'
login_password: '{{homelab_config.database.password}}'
db: '{{homelab_config.database.name}}'
query: 'INSERT INTO service (name, host, source, config) VALUES (%s, %s, %s, %s) ON CONFLICT DO NOTHING;'
positional_args:
- '{{item.name}}'
- '{{item.host}}'
- '{{item.source}}'
- '{{item.config}}'
with_items:
- {name: broadcast, host: '{{ansible_hostname}}', source: gitea/ashish/broadcast/master, config: null}
- name: Insert into Postgres table service_port
community.postgresql.postgresql_query:
login_host: '{{homelab_config.database.host}}'
login_user: '{{homelab_config.database.user}}'
login_password: '{{homelab_config.database.password}}'
db: '{{homelab_config.database.name}}'
query: 'INSERT INTO service_port (service, port, domain, reverse_proxy, reverse_proxy_port) VALUES (%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING;'
positional_args:
- '{{item.service}}'
- '{{item.port}}'
- '{{item.domain}}'
- '{{item.reverse_proxy}}'
- '{{item.reverse_proxy_port}}'
with_items:
- {service: broadcast, port: 10000, domain: null, reverse_proxy: null, reverse_proxy_port: null}
- {service: broadcast, port: 10001, domain: null, reverse_proxy: null, reverse_proxy_port: null}
- name: Insert into Postgres table service_data
community.postgresql.postgresql_query:
login_host: '{{homelab_config.database.host}}'
login_user: '{{homelab_config.database.user}}'
login_password: '{{homelab_config.database.password}}'
db: '{{homelab_config.database.name}}'
query: 'INSERT INTO service_data (service, data_name, storage_type, source) VALUES (%s, %s, %s, %s) ON CONFLICT DO NOTHING;'
positional_args:
- '{{item.service}}'
- '{{item.data_name}}'
- '{{item.storage_type}}'
- '{{item.source}}'
with_items:
- {service: broadcast, data_name: bedroom_speaker_audio, storage_type: docker, source: broadcast-bedroom-speaker-audio}
+12
View File
@@ -0,0 +1,12 @@
FROM python:3.11
LABEL author="Ashish D'Souza"
WORKDIR /code
ENTRYPOINT ["python3.11", "router.py"]
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY src .
+3
View File
@@ -0,0 +1,3 @@
aiohttp==3.8.6
pika==1.3.2
PyYAML==6.0.1
+25
View File
@@ -0,0 +1,25 @@
notification:
jenkins:
system:
title: '.*'
message:
message: '.*'
uptime_kuma:
system:
title: '(?<=\[).+(?=\])'
message:
title: '^.+(?=\s\[)'
message: '[^\n]+$'
Dsatp58_alerts:
system:
title: '(?<=\s)[\w.]+'
message:
message: '[^\n]+(?=\n---------)'
call:
call_ashish:
caller:
title: '.*'
user:
topic: '(?<=_)\w+$'
message:
message: '.*'
+21
View File
@@ -0,0 +1,21 @@
import json
import asyncio
from typing import AsyncGenerator
import aiohttp
class NtfySubscriber:
def __init__(self, topics: list[str]):
self._topics = topics
def _generate_ntfy_url(self):
return 'https://ntfy.homelab.net/' + ','.join(self._topics) + '/json'
async def subscribe(self) -> AsyncGenerator[tuple[str, str, str], None]:
async with aiohttp.ClientSession(raise_for_status=True, timeout=aiohttp.ClientTimeout()) as session:
async with session.get(self._generate_ntfy_url(), verify_ssl=False) as response:
async for line in response.content:
msg = json.loads(line.decode())
if msg['event'] == 'message':
yield msg['topic'], msg['title'], msg['message']
+50
View File
@@ -0,0 +1,50 @@
import json
import asyncio
import pika
from pika.adapters.asyncio_connection import AsyncioConnection
class RabbitMQPublisher:
def __init__(self, rabbitmq_host: str, rabbitmq_port: int):
self._connection = AsyncioConnection(
pika.ConnectionParameters(host=rabbitmq_host, port=rabbitmq_port),
on_open_callback=self._on_connection_open,
on_open_error_callback=self._on_connection_open_error,
on_close_callback=self._on_connection_closed,
)
self._channel = None
def _on_connection_open(self, connection: AsyncioConnection) -> None:
self._connection.channel(on_open_callback=self._on_channel_open)
def _on_connection_open_error(self, connection: AsyncioConnection, error: Exception) -> None:
print(f'Failed to open connection')
self._connection.ioloop.stop()
raise error
def _on_connection_closed(self, connection: AsyncioConnection, reason: Exception) -> None:
print(f'Connection closed')
raise reason
self._connection.ioloop.stop()
def _on_channel_open(self, channel: pika.channel.Channel) -> None:
self._channel = channel
def _publish(self, topic: str, data: str) -> None:
self._channel.basic_publish(exchange='broadcast', routing_key=topic, body=data)
def send_notification(self, system: str, user: str, priority: str, message: str) -> None:
self._publish(f'notification.{system}.{user}.{priority}', message)
def send_call(self, caller: str, user: str, message: str) -> None:
self._publish(f'call.{caller}.{user}', json.dumps({
'ringtone': {
'filename': 'Magic.mp3',
'trim': {
'start_time': '00:01:34.64',
'end_time': '00:01:41.53'
}
},
'message': message
}))
+66
View File
@@ -0,0 +1,66 @@
import os
import re
import asyncio
import functools
from typing import Callable
import yaml
from ntfy_subscriber import NtfySubscriber
from rabbitmq_publisher import RabbitMQPublisher
class NtfyRouter:
def __init__(self, config_filename: str):
self._formatters = None
self._ntfy_subscriber = None
self._rabbitmq_publisher = None
with open(config_filename) as config_file:
config = yaml.safe_load(config_file)
self._formatters = self._get_formatters(config)
def _get_formatters(self, config: dict) -> dict:
def parse_arg(compiled_regex: re.Pattern, text: str) -> str:
return compiled_regex.search(text).group().lower()
def format_field(parsers: dict[str, Callable], **args) -> str:
return '. '.join(parser(args[arg_name]) for arg_name, parser in parsers.items())
return {
broadcast_type: {
topic: {
field_name: functools.partial(
format_field,
{
arg: functools.partial(
parse_arg,
re.compile(regex_pattern)
) for arg, regex_pattern in config[broadcast_type][topic][field_name].items()
}
) for field_name in config[broadcast_type][topic]
} for topic in config[broadcast_type]
} for broadcast_type in config
}
def route_message(self, topic: str, title: str, message: str):
if topic in self._formatters['notification']:
notification_args = {notification_arg: self._formatters['notification'][topic][notification_arg](topic=topic, title=title, message=message) for notification_arg in self._formatters['notification'][topic]}
self._rabbitmq_publisher.send_notification(user='ashish', priority='high', **notification_args)
elif topic in self._formatters['call']:
call_args = {call_arg: self._formatters['call'][topic][call_arg](topic=topic, title=title, message=message) for call_arg in self._formatters['call'][topic]}
self._rabbitmq_publisher.send_call(**call_args)
async def start(self, rabbitmq_host: str, rabbitmq_port: int):
self._ntfy_subscriber = NtfySubscriber([topic for message_type in self._formatters for topic in self._formatters[message_type]])
self._rabbitmq_publisher = RabbitMQPublisher(rabbitmq_host, rabbitmq_port)
async for topic, title, message in self._ntfy_subscriber.subscribe():
self.route_message(topic, title, message)
if __name__ == '__main__':
ntfy_router = NtfyRouter(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.yaml'))
rabbitmq_host = os.environ.get('RABBITMQ_HOST', 'localhost')
rabbitmq_port = int(os.environ.get('RABBITMQ_PORT', '5672'))
asyncio.run(ntfy_router.start(rabbitmq_host, rabbitmq_port))
+11 -6
View File
@@ -1,8 +1,9 @@
import os import os
import json import json
import datetime import datetime
import functools
import threading import threading
import traceback
import functools
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
import pika import pika
@@ -28,6 +29,7 @@ class Player(ABC):
def subscribe(self, rabbitmq_host: str, rabbitmq_port: str, rabbitmq_topics: list[str]) -> None: def subscribe(self, rabbitmq_host: str, rabbitmq_port: str, rabbitmq_topics: list[str]) -> None:
def handle_message(connection: pika.adapters.blocking_connection.BlockingConnection, channel: pika.channel.Channel, method: pika.spec.Basic.Deliver, body: bytes): def handle_message(connection: pika.adapters.blocking_connection.BlockingConnection, channel: pika.channel.Channel, method: pika.spec.Basic.Deliver, body: bytes):
try:
topic = method.routing_key topic = method.routing_key
message_type = topic.split('.', 1)[0] message_type = topic.split('.', 1)[0]
@@ -83,18 +85,21 @@ class Player(ABC):
reminder_audio = Audio.from_tts(f'Reminder to {reminder_text}') reminder_audio = Audio.from_tts(f'Reminder to {reminder_text}')
alarm_audio.concat(reminder_audio) alarm_audio.concat(reminder_audio)
case _: case _:
# Send NACK, do not requeue raise ValueError(f'No alarm type {_}')
connection.add_callback_threadsafe(functools.partial(channel.basic_nack, delivery_tag=method.delivery_tag, requeue=False))
audio_save_path = os.path.join(os.environ['AUDIO_ROOT_PATH'], 'alarm.mp3') audio_save_path = os.path.join(os.environ['AUDIO_ROOT_PATH'], 'alarm.mp3')
ringtone_audio.save(audio_save_path) alarm_audio.save(audio_save_path)
self.play(audio_save_path) self.play(audio_save_path)
case _: case _:
# Send NACK, do not requeue raise ValueError(f'No message type {_}')
connection.add_callback_threadsafe(functools.partial(channel.basic_nack, delivery_tag=method.delivery_tag, requeue=False))
# Send ACK # Send ACK
connection.add_callback_threadsafe(functools.partial(channel.basic_ack, delivery_tag=method.delivery_tag)) connection.add_callback_threadsafe(functools.partial(channel.basic_ack, delivery_tag=method.delivery_tag))
except Exception:
traceback.print_exc()
# Send NACK, do not requeue
connection.add_callback_threadsafe(functools.partial(channel.basic_nack, delivery_tag=method.delivery_tag, requeue=False))
def on_message(connection: pika.adapters.blocking_connection.BlockingConnection, channel: pika.channel.Channel, method: pika.spec.Basic.Deliver, properties: pika.spec.BasicProperties, body: bytes) -> None: def on_message(connection: pika.adapters.blocking_connection.BlockingConnection, channel: pika.channel.Channel, method: pika.spec.Basic.Deliver, properties: pika.spec.BasicProperties, body: bytes) -> None:
thread = threading.Thread(target=handle_message, args=(connection, channel, method, body)) thread = threading.Thread(target=handle_message, args=(connection, channel, method, body))
+25
View File
@@ -0,0 +1,25 @@
- name: Start Broadcast
hosts: Lothlorien
tasks:
- name: Create temporary Docker Compose directory
ansible.builtin.tempfile:
state: directory
register: docker_compose_dir
- name: Copy docker-compose.yaml
ansible.builtin.copy:
src: conf/docker-compose.yaml
dest: '{{docker_compose_dir.path}}/docker-compose.yaml'
mode: preserve
- name: Docker Compose up Broadcast
environment:
SERVER_IP: '{{ansible_default_ipv4.address}}'
community.docker.docker_compose:
project_name: broadcast
project_src: '{{docker_compose_dir.path}}'
state: present
- name: Remove temporary Docker Compose directory
ansible.builtin.file:
path: '{{docker_compose_dir.path}}'
state: absent
+25
View File
@@ -0,0 +1,25 @@
- name: Stop Broadcast
hosts: Lothlorien
tasks:
- name: Create temporary Docker Compose directory
ansible.builtin.tempfile:
state: directory
register: docker_compose_dir
- name: Copy docker-compose.yaml
ansible.builtin.copy:
src: conf/docker-compose.yaml
dest: '{{docker_compose_dir.path}}/docker-compose.yaml'
mode: preserve
- name: Docker Compose down Broadcast
environment:
SERVER_IP: '{{ansible_default_ipv4.address}}'
community.docker.docker_compose_v2:
project_name: broadcast
project_src: '{{docker_compose_dir.path}}'
state: absent
- name: Remove temporary Docker Compose directory
ansible.builtin.file:
path: '{{docker_compose_dir.path}}'
state: absent
+51
View File
@@ -0,0 +1,51 @@
- name: Stop Broadcast
ansible.builtin.import_playbook: stop.yaml
- name: Uninstall Broadcast
hosts: Lothlorien
tasks:
- name: Remove Broadcast bedroom speaker audio Docker volume
community.docker.docker_volume:
volume_name: broadcast-bedroom-speaker-audio
state: absent
- name: Remove Broadcast bedroom speaker audio Docker volume
become: true
ansible.builtin.file:
path: /data/broadcast-bedroom-speaker-audio
state: absent
- name: Read homelab config
ansible.builtin.slurp:
src: '{{ansible_user_dir}}/.homelab.json'
register: homelab_config_file
- name: Set homelab_config variable
ansible.builtin.set_fact:
homelab_config: '{{homelab_config_file.content|b64decode|from_json}}'
- name: Delete from Postgres table service_data
community.postgresql.postgresql_query:
login_host: '{{homelab_config.database.host}}'
login_user: '{{homelab_config.database.user}}'
login_password: '{{homelab_config.database.password}}'
db: '{{homelab_config.database.name}}'
query: 'DELETE FROM service_data WHERE service = %s;'
positional_args:
- broadcast
- name: Delete from Postgres table service_port
community.postgresql.postgresql_query:
login_host: '{{homelab_config.database.host}}'
login_user: '{{homelab_config.database.user}}'
login_password: '{{homelab_config.database.password}}'
db: '{{homelab_config.database.name}}'
query: 'DELETE FROM service_port WHERE service = %s;'
positional_args:
- broadcast
- name: Delete from Postgres table service
community.postgresql.postgresql_query:
login_host: '{{homelab_config.database.host}}'
login_user: '{{homelab_config.database.user}}'
login_password: '{{homelab_config.database.password}}'
db: '{{homelab_config.database.name}}'
query: 'DELETE FROM service WHERE name = %s;'
positional_args:
- broadcast