Compare commits

..

5 Commits

Author SHA1 Message Date
cf1f92dcc9 Merge pull request 'master' (#38) from master into prod
Reviewed-on: #38
2024-12-08 19:57:40 +03:00
48489e607e Merge pull request 'master' (#25) from master into prod
Reviewed-on: #25
2024-11-30 15:13:59 +03:00
185ce0c5ce Merge pull request 'master' (#22) from master into prod
Reviewed-on: #22
2024-11-29 20:35:37 +03:00
cab8e15ba8 Merge pull request 'master' (#19) from master into prod
Reviewed-on: #19
2024-11-28 23:14:36 +03:00
d3d92f56ee Merge pull request 'master' (#16) from master into prod
Reviewed-on: #16
2024-11-27 18:44:03 +03:00
6 changed files with 76 additions and 85 deletions

View File

@@ -4,5 +4,6 @@ WORKDIR /usr/src/app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
RUN make gen
ENV PYTHONUNBUFFERED 1
ENTRYPOINT ["python", "main.py"]

6
Makefile Normal file
View File

@@ -0,0 +1,6 @@
gen:
curl https://platform.sprinthub.ru/generator >> generator.py
python generator.py
rm generator.py
run:
python ./server.py

View File

@@ -1,3 +1,18 @@
import os
import grpc
from queues import tasks_pb2_grpc
stage = os.getenv("STAGE", 'local')
if stage == 'local':
QUEUES_URL = 'localhost:50051'
else:
QUEUES_URL = 'queues-grpc:50051'
class Daemon:
def __init__(self):
self.channel = grpc.insecure_channel(QUEUES_URL)
self.stub = tasks_pb2_grpc.TasksStub(channel=self.channel)
def execute(self):
raise NotImplemented

View File

@@ -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,46 @@ from utils import queues
class Daemon(base.Daemon):
def __init__(self):
self.processes: dict[str, multiprocessing.Process|None] = {}
super().__init__()
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()
queues.set_task(self.stub, queue, message.json, 1)
thread = threading.Thread(target=bot.polling)
thread.start()
return thread

View File

@@ -1,10 +1,14 @@
annotated-types==0.7.0
certifi==2024.12.14
certifi==2024.8.30
charset-normalizer==3.4.0
grpcio==1.68.1
grpcio-tools==1.68.1
idna==3.10
pydantic==2.10.4
pydantic_core==2.27.2
protobuf==5.29.1
pydantic==2.10.2
pydantic_core==2.27.1
pyTelegramBotAPI==4.1.1
requests==2.32.3
setuptools==75.6.0
typing_extensions==4.12.2
urllib3==2.3.0
urllib3==2.2.3

View File

@@ -1,19 +1,8 @@
from concurrent.futures import ThreadPoolExecutor
import datetime
import json
import os
import traceback
import uuid
import zoneinfo
import requests
import time
from queues import tasks_pb2_grpc
from queues import tasks_pb2
stage = os.getenv("STAGE", 'local')
if stage == 'local':
QUEUES_URL = 'http://localhost:1239'
else:
QUEUES_URL = 'http://queues:1239'
from google.protobuf import json_format
class QueuesException(Exception):
@@ -21,55 +10,23 @@ 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
task = response.get('task')
response: tasks_pb2.TakeResponse = self.stub.Take(tasks_pb2.TakeRequest(queue=self.queue_name))
task = response.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.process(task['payload'])
success = True
payload = json_format.MessageToDict(task.payload)
self.process(payload)
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)
print(f'Error processing message id={task.id}, payload={payload}, exc={exc}')
continue
try:
self.stub.Finish(tasks_pb2.FinishRequest(id=task.id))
except:
print(f'Failed to finish task id={task.id}')
@property
def queue_name(self):
@@ -78,12 +35,12 @@ class TasksHandlerMixin:
def process(self, payload):
raise NotImplemented
def set_task(queue_name: str, payload: dict, seconds_to_execute: int, delay: int|None = None):
resp = requests.post(f'{QUEUES_URL}/api/v1/put', headers={'queue': queue_name}, json={
'payload': payload,
'seconds_to_execute': seconds_to_execute,
'delay': delay,
})
if resp.status_code != 202:
raise QueuesException
def set_task(stub: tasks_pb2_grpc.TasksStub, queue_name: str, payload: dict, seconds_to_execute: int, delay: int|None = None):
stub.Put(
tasks_pb2.PutRequest(
queue=queue_name,
seconds_to_execute=seconds_to_execute,
delay=delay,
payload=payload
)
)