Compare commits
29 Commits
prod
...
0f58ed101e
| Author | SHA1 | Date | |
|---|---|---|---|
| 0f58ed101e | |||
| aebaa7e546 | |||
| 80462d2a61 | |||
| f0399196b5 | |||
| 7b806075c7 | |||
| 2eb13d9443 | |||
| 49634845a1 | |||
| 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
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -121,4 +121,3 @@ GitHub.sublime-settings
|
||||
local_platform.json
|
||||
|
||||
*pb2*
|
||||
schemas
|
||||
|
||||
@@ -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"]
|
||||
|
||||
2
Makefile
Normal file
2
Makefile
Normal file
@@ -0,0 +1,2 @@
|
||||
gen:
|
||||
python -m grpc_tools.protoc --proto_path schemas --python_out=. --pyi_out=. --grpc_python_out=. ./schemas/tasks.proto
|
||||
@@ -1,3 +1,18 @@
|
||||
import os
|
||||
import grpc
|
||||
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
|
||||
|
||||
@@ -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()
|
||||
queues.set_task(self.stub, queue, message.json, 1)
|
||||
thread = threading.Thread(target=bot.polling)
|
||||
thread.start()
|
||||
return thread
|
||||
|
||||
@@ -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
|
||||
|
||||
40
schemas/tasks.proto
Normal file
40
schemas/tasks.proto
Normal file
@@ -0,0 +1,40 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package queues;
|
||||
|
||||
import "google/protobuf/struct.proto";
|
||||
|
||||
service Tasks {
|
||||
rpc Put (PutRequest) returns (EmptyResponse) {}
|
||||
|
||||
rpc Take (TakeRequest) returns (TakeResponse) {}
|
||||
|
||||
rpc Finish (FinishRequest) returns (EmptyResponse) {}
|
||||
}
|
||||
|
||||
message Task {
|
||||
string id = 1;
|
||||
int64 attempt = 2;
|
||||
google.protobuf.Struct payload = 3;
|
||||
}
|
||||
|
||||
message PutRequest {
|
||||
string queue = 1;
|
||||
int64 seconds_to_execute = 2;
|
||||
optional int64 delay = 3;
|
||||
google.protobuf.Struct payload = 4;
|
||||
}
|
||||
|
||||
message TakeRequest {
|
||||
string queue = 1;
|
||||
}
|
||||
|
||||
message FinishRequest {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
message EmptyResponse {}
|
||||
|
||||
message TakeResponse {
|
||||
optional Task task = 1;
|
||||
}
|
||||
@@ -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
|
||||
import tasks_pb2_grpc
|
||||
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')
|
||||
if not task:
|
||||
response: tasks_pb2.TakeResponse = self.stub.Take(tasks_pb2.TakeRequest(queue=self.queue_name))
|
||||
task = response.task
|
||||
if not task.id:
|
||||
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
|
||||
)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user