Compare commits
36 Commits
aebaa7e546
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c135352ab | |||
|
|
33901b0a82 | ||
| bea73c9322 | |||
|
|
7b9d264ef9 | ||
| 0112b5c0e4 | |||
|
|
a707a8b93e | ||
| 57669cf6bd | |||
|
|
df3354a536 | ||
| 9a55a4f822 | |||
|
|
6a8f18300b | ||
|
|
b575ba5717 | ||
|
|
24b1d39e10 | ||
| 8bd6dc2701 | |||
|
|
d61c665b6c | ||
|
|
4f0114e99a | ||
|
|
0cab3e52cb | ||
|
|
2d292dfc46 | ||
|
|
72c5823ccd | ||
|
|
e0e7564fcc | ||
|
|
2bff8983b5 | ||
|
|
4af857e2f3 | ||
|
|
ef1d60e368 | ||
|
|
8828bfd05b | ||
|
|
5a8d6c6488 | ||
|
|
f27122ce56 | ||
|
|
c509cb0b32 | ||
|
|
0785997e6e | ||
|
|
7742138ec8 | ||
|
|
4d03af75d8 | ||
|
|
5a00dad803 | ||
| 7ed7afbef4 | |||
| 73cc7b2c03 | |||
| 5dbacec1b0 | |||
| 0b6dc3af1a | |||
| 98d69fff70 | |||
| 0dbae621ab |
@@ -22,7 +22,6 @@ services:
|
||||
networks:
|
||||
- configurator
|
||||
- queues-development
|
||||
- locks-development
|
||||
environment:
|
||||
STAGE: "development"
|
||||
command: mailbox
|
||||
@@ -39,5 +38,3 @@ networks:
|
||||
external: true
|
||||
queues-development:
|
||||
external: true
|
||||
locks-development:
|
||||
external: true
|
||||
|
||||
@@ -22,7 +22,7 @@ services:
|
||||
networks:
|
||||
- configurator
|
||||
- queues
|
||||
- locks
|
||||
- monitoring
|
||||
environment:
|
||||
STAGE: "production"
|
||||
command: mailbox
|
||||
@@ -39,5 +39,5 @@ networks:
|
||||
external: true
|
||||
queues:
|
||||
external: true
|
||||
locks:
|
||||
monitoring:
|
||||
external: true
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -120,4 +120,5 @@ GitHub.sublime-settings
|
||||
|
||||
local_platform.json
|
||||
|
||||
*pb2*
|
||||
*pb2*
|
||||
schemas
|
||||
|
||||
@@ -4,6 +4,5 @@ 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
2
Makefile
@@ -1,2 +0,0 @@
|
||||
gen:
|
||||
python -m grpc_tools.protoc --proto_path schemas --python_out=. --pyi_out=. --grpc_python_out=. ./schemas/tasks.proto
|
||||
@@ -1,18 +1,3 @@
|
||||
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,6 +1,7 @@
|
||||
import telebot
|
||||
import threading
|
||||
import multiprocessing
|
||||
import time
|
||||
import json
|
||||
|
||||
from daemons import base
|
||||
from utils import platform
|
||||
@@ -9,45 +10,37 @@ from utils import queues
|
||||
|
||||
class Daemon(base.Daemon):
|
||||
def __init__(self):
|
||||
self.telegram_bots: dict[str, dict[str, telebot.TeleBot|None]] = {}
|
||||
self.threads: dict[str, dict[str, threading.Thread|None]] = {}
|
||||
self.processes: dict[str, multiprocessing.Process|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():
|
||||
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]
|
||||
key = f'{project_name}_{bot_name}'
|
||||
proc = self.processes.get(key)
|
||||
if bot_info.get('poll_enabled'):
|
||||
if bot is not None and self.threads[project_name][bot_name].is_alive():
|
||||
if proc and proc.is_alive():
|
||||
print(f'process for {project_name} {bot_name} is alive')
|
||||
continue
|
||||
print(f'starting process for {project_name} {bot_name}')
|
||||
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
|
||||
process = multiprocessing.Process(target=self.start_polling, args=(bot_info['secrets']['telegram_token'], bot_info['queue']))
|
||||
process.start()
|
||||
self.processes[key] = process
|
||||
print(f'started process for {project_name} {bot_name}')
|
||||
else:
|
||||
if bot is None:
|
||||
if proc is None:
|
||||
print(f'process for {project_name} {bot_name} is not alive')
|
||||
continue
|
||||
print(f'terminating process for {project_name} {bot_name}')
|
||||
bot.stop_bot()
|
||||
self.telegram_bots[project_name][bot_name] = None
|
||||
proc.terminate()
|
||||
self.processes[key] = None
|
||||
print(f'terminated process for {project_name} {bot_name}')
|
||||
time.sleep(10)
|
||||
|
||||
def start_polling(self, bot: telebot.TeleBot, queue: str) -> threading.Thread:
|
||||
def start_polling(self, token: str, queue: str):
|
||||
bot = telebot.TeleBot(token)
|
||||
@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(self.stub, queue, message.json, 1)
|
||||
thread = threading.Thread(target=bot.polling)
|
||||
thread.start()
|
||||
return thread
|
||||
queues.set_task(queue, message.json, 1)
|
||||
bot.polling()
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
annotated-types==0.7.0
|
||||
certifi==2024.8.30
|
||||
certifi==2024.12.14
|
||||
charset-normalizer==3.4.0
|
||||
grpcio==1.68.1
|
||||
grpcio-tools==1.68.1
|
||||
idna==3.10
|
||||
protobuf==5.29.1
|
||||
pydantic==2.10.2
|
||||
pydantic_core==2.27.1
|
||||
pydantic==2.10.4
|
||||
pydantic_core==2.27.2
|
||||
pyTelegramBotAPI==4.1.1
|
||||
requests==2.32.3
|
||||
setuptools==75.6.0
|
||||
typing_extensions==4.12.2
|
||||
urllib3==2.2.3
|
||||
urllib3==2.3.0
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
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,8 +1,18 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
import zoneinfo
|
||||
import requests
|
||||
import time
|
||||
import tasks_pb2_grpc
|
||||
import tasks_pb2
|
||||
|
||||
from google.protobuf import json_format
|
||||
|
||||
stage = os.getenv("STAGE", 'local')
|
||||
if stage == 'local':
|
||||
QUEUES_URL = 'http://localhost:1239'
|
||||
else:
|
||||
QUEUES_URL = 'http://queues:1239'
|
||||
|
||||
|
||||
class QueuesException(Exception):
|
||||
@@ -10,24 +20,54 @@ 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:
|
||||
response: tasks_pb2.TakeResponse = self.stub.Take(tasks_pb2.TakeRequest(queue=self.queue_name))
|
||||
task: tasks_pb2.Task = response.task
|
||||
print(task)
|
||||
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:
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
start = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
|
||||
try:
|
||||
payload = json_format.MessageToDict(task.payload)
|
||||
self.process(payload)
|
||||
print(f'process task with id {task["id"]}, attempt {task["attempt"]}')
|
||||
self.process(task['payload'])
|
||||
success = True
|
||||
except Exception as exc:
|
||||
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}')
|
||||
print(f'Error processing message id={task["id"]}, payload={task["payload"]}, exc={exc}')
|
||||
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)
|
||||
|
||||
@property
|
||||
def queue_name(self):
|
||||
@@ -36,12 +76,12 @@ class TasksHandlerMixin:
|
||||
def process(self, payload):
|
||||
raise NotImplemented
|
||||
|
||||
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
|
||||
)
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user