Compare commits
22 Commits
prod
...
e02646a1a2
| Author | SHA1 | Date | |
|---|---|---|---|
| e02646a1a2 | |||
| 1b7e8686e4 | |||
| cf12a0dca8 | |||
| 0a97e56539 | |||
| a5d3bd08c1 | |||
| ad74b8de7a | |||
| 05d9cdc7b1 | |||
| a209246513 | |||
| 0922b5a4a4 | |||
| 2ee74e70ac | |||
| da93092232 | |||
| 60b933496f | |||
| 82b99ae803 | |||
| c8f65a0ebb | |||
| 6401a40f11 | |||
| 32197fd699 | |||
| e69ee8767a | |||
| 54f7581657 | |||
| c6a2710087 | |||
| 42fc5552ab | |||
| 499eed49e0 | |||
| 349df7eb17 |
@@ -22,6 +22,7 @@ services:
|
||||
networks:
|
||||
- configurator
|
||||
- queues-development
|
||||
- locks-development
|
||||
environment:
|
||||
STAGE: "development"
|
||||
command: mailbox
|
||||
@@ -38,3 +39,5 @@ networks:
|
||||
external: true
|
||||
queues-development:
|
||||
external: true
|
||||
locks-development:
|
||||
external: true
|
||||
|
||||
@@ -22,6 +22,7 @@ services:
|
||||
networks:
|
||||
- configurator
|
||||
- queues
|
||||
- locks
|
||||
environment:
|
||||
STAGE: "production"
|
||||
command: mailbox
|
||||
@@ -38,3 +39,5 @@ networks:
|
||||
external: true
|
||||
queues:
|
||||
external: true
|
||||
locks:
|
||||
external: true
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -119,6 +119,3 @@ GitHub.sublime-settings
|
||||
.history
|
||||
|
||||
local_platform.json
|
||||
|
||||
*pb2*
|
||||
schemas
|
||||
|
||||
@@ -5,6 +5,7 @@ from telebot import apihelper
|
||||
from daemons import base
|
||||
from utils import platform
|
||||
from utils import queues
|
||||
from utils import locks
|
||||
|
||||
|
||||
class Message(pydantic.BaseModel):
|
||||
@@ -22,6 +23,12 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
|
||||
def queue_name(self):
|
||||
return 'botalka_mailbox'
|
||||
|
||||
def before_execute(self, task: dict):
|
||||
locks.acquire(task['id'])
|
||||
|
||||
def after_execute(self, task: dict):
|
||||
locks.release(task['id'])
|
||||
|
||||
def process(self, payload: dict):
|
||||
message = Message.model_validate(payload)
|
||||
bot = platform.platform_client.get_config('bots')[message.project][message.name]
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import telebot
|
||||
import multiprocessing
|
||||
import threading
|
||||
import time
|
||||
import json
|
||||
|
||||
from daemons import base
|
||||
from utils import platform
|
||||
@@ -10,37 +9,45 @@ from utils import queues
|
||||
|
||||
class Daemon(base.Daemon):
|
||||
def __init__(self):
|
||||
self.processes: dict[str, multiprocessing.Process|None] = {}
|
||||
self.telegram_bots: dict[str, dict[str, telebot.TeleBot|None]] = {}
|
||||
self.threads: dict[str, dict[str, threading.Thread|None]] = {}
|
||||
|
||||
def execute(self):
|
||||
while True:
|
||||
bots = platform.platform_client.get_config('bots')
|
||||
for project_name, project in bots.items():
|
||||
if project_name not in self.telegram_bots:
|
||||
self.telegram_bots[project_name] = {}
|
||||
self.threads[project_name] = {}
|
||||
for bot_name, bot_info in project.items():
|
||||
key = f'{project_name}_{bot_name}'
|
||||
proc = self.processes.get(key)
|
||||
if bot_name not in self.telegram_bots[project_name]:
|
||||
self.telegram_bots[project_name][bot_name] = None
|
||||
self.threads[project_name][bot_name] = None
|
||||
bot = self.telegram_bots[project_name][bot_name]
|
||||
if bot_info.get('poll_enabled'):
|
||||
if proc and proc.is_alive():
|
||||
if bot is not None and self.threads[project_name][bot_name].is_alive():
|
||||
print(f'process for {project_name} {bot_name} is alive')
|
||||
continue
|
||||
print(f'starting process for {project_name} {bot_name}')
|
||||
process = multiprocessing.Process(target=self.start_polling, args=(bot_info['secrets']['telegram_token'], bot_info['queue']))
|
||||
process.start()
|
||||
self.processes[key] = process
|
||||
bot = telebot.TeleBot(bot_info['secrets']['telegram_token'])
|
||||
thread = self.start_polling(bot, bot_info['queue'])
|
||||
self.telegram_bots[project_name][bot_name] = bot
|
||||
self.threads[project_name][bot_name] = thread
|
||||
print(f'started process for {project_name} {bot_name}')
|
||||
else:
|
||||
if proc is None:
|
||||
if bot is None:
|
||||
print(f'process for {project_name} {bot_name} is not alive')
|
||||
continue
|
||||
print(f'terminating process for {project_name} {bot_name}')
|
||||
proc.terminate()
|
||||
self.processes[key] = None
|
||||
bot.stop_bot()
|
||||
self.telegram_bots[project_name][bot_name] = None
|
||||
print(f'terminated process for {project_name} {bot_name}')
|
||||
time.sleep(10)
|
||||
|
||||
def start_polling(self, token: str, queue: str):
|
||||
bot = telebot.TeleBot(token)
|
||||
def start_polling(self, bot: telebot.TeleBot, queue: str) -> threading.Thread:
|
||||
@bot.message_handler(content_types=['audio', 'photo', 'voice', 'video', 'document', 'animation', 'text', 'location', 'contact', 'sticker', 'video_note'])
|
||||
def do_action(message: telebot.types.Message):
|
||||
queues.set_task(queue, message.json, 1)
|
||||
bot.polling()
|
||||
thread = threading.Thread(target=bot.polling)
|
||||
thread.start()
|
||||
return thread
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
annotated-types==0.7.0
|
||||
certifi==2024.12.14
|
||||
certifi==2024.8.30
|
||||
charset-normalizer==3.4.0
|
||||
idna==3.10
|
||||
pydantic==2.10.4
|
||||
pydantic_core==2.27.2
|
||||
pydantic==2.10.2
|
||||
pydantic_core==2.27.1
|
||||
pyTelegramBotAPI==4.1.1
|
||||
requests==2.32.3
|
||||
typing_extensions==4.12.2
|
||||
urllib3==2.3.0
|
||||
urllib3==2.2.3
|
||||
|
||||
27
utils/locks.py
Normal file
27
utils/locks.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import requests
|
||||
|
||||
|
||||
LOCKS_URL = 'http://locks'
|
||||
|
||||
|
||||
class Conflict(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def acquire(name: str, ttl: int = 1):
|
||||
resp = requests.post(f'{LOCKS_URL}/api/v1/acquire', json={
|
||||
'name': name,
|
||||
'ttl': ttl,
|
||||
})
|
||||
if resp.status_code == 409:
|
||||
raise Conflict
|
||||
if resp.status_code != 202:
|
||||
raise Exception
|
||||
|
||||
|
||||
def release(name: str):
|
||||
resp = requests.post(f'{LOCKS_URL}/api/v1/release', json={
|
||||
'name': name,
|
||||
})
|
||||
if resp.status_code != 202:
|
||||
raise Exception
|
||||
@@ -1,10 +1,4 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import traceback
|
||||
import uuid
|
||||
import zoneinfo
|
||||
import requests
|
||||
import time
|
||||
|
||||
@@ -21,55 +15,32 @@ class QueuesException(Exception):
|
||||
|
||||
|
||||
class TasksHandlerMixin:
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.executor = ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
def _send_metric(self, start: datetime.datetime, end: datetime.datetime, success: bool):
|
||||
def send():
|
||||
requests.post(f'{QUEUES_URL}/api/v1/metric', json={
|
||||
'service': 'botalka',
|
||||
'queue': self.queue_name,
|
||||
'success': success,
|
||||
'timestamp': start.strftime("%Y-%m-%dT%H:%M:%S") + "Z",
|
||||
"success": success,
|
||||
"execution_time_ms": (end - start).microseconds // 1000,
|
||||
"environment": stage,
|
||||
})
|
||||
|
||||
self.executor.submit(send)
|
||||
|
||||
def poll(self):
|
||||
while True:
|
||||
try:
|
||||
response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name}).json()
|
||||
except requests.JSONDecodeError:
|
||||
print('Unable to decode json')
|
||||
time.sleep(3)
|
||||
continue
|
||||
response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name}).json()
|
||||
task = response.get('task')
|
||||
if not task:
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
start = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
|
||||
try:
|
||||
print(f'process task with id {task["id"]}, attempt {task["attempt"]}')
|
||||
self.before_execute(task)
|
||||
self.process(task['payload'])
|
||||
success = True
|
||||
except Exception as exc:
|
||||
print(f'Error processing message id={task["id"]}, payload={task["payload"]}, exc={exc}')
|
||||
traceback.print_stack()
|
||||
success = False
|
||||
end = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
|
||||
if success:
|
||||
try:
|
||||
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': task['id']})
|
||||
if resp.status_code != 202:
|
||||
raise QueuesException
|
||||
print(f'finish task with id {task["id"]}')
|
||||
except:
|
||||
print(f'Failed to finish task id={task["id"]}')
|
||||
self._send_metric(start, end, success)
|
||||
continue
|
||||
try:
|
||||
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': task['id']})
|
||||
if resp.status_code != 202:
|
||||
raise QueuesException
|
||||
self.after_execute(task)
|
||||
except:
|
||||
print(f'Failed to finish task id={task["id"]}')
|
||||
|
||||
def before_execute(self, task: dict):
|
||||
pass
|
||||
|
||||
def after_execute(self, task: dict):
|
||||
pass
|
||||
|
||||
@property
|
||||
def queue_name(self):
|
||||
|
||||
Reference in New Issue
Block a user