Compare commits
36 Commits
2eb13d9443
...
metric
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5581786225 | ||
|
|
66b4348957 | ||
|
|
33901b0a82 | ||
|
|
7b9d264ef9 | ||
|
|
a707a8b93e | ||
|
|
df3354a536 | ||
|
|
6a8f18300b | ||
|
|
b575ba5717 | ||
|
|
24b1d39e10 | ||
|
|
d61c665b6c | ||
|
|
4f0114e99a | ||
|
|
0cab3e52cb | ||
|
|
2d292dfc46 | ||
|
|
72c5823ccd | ||
|
|
e0e7564fcc | ||
|
|
2bff8983b5 | ||
|
|
4af857e2f3 | ||
|
|
ef1d60e368 | ||
|
|
8828bfd05b | ||
|
|
5a8d6c6488 | ||
|
|
f27122ce56 | ||
|
|
c509cb0b32 | ||
|
|
0785997e6e | ||
|
|
7742138ec8 | ||
|
|
4d03af75d8 | ||
|
|
5a00dad803 | ||
| 7ed7afbef4 | |||
| 73cc7b2c03 | |||
| 5dbacec1b0 | |||
| 0b6dc3af1a | |||
| 98d69fff70 | |||
| 0dbae621ab | |||
| b4dd0a4b7b | |||
| bb4c6d4748 | |||
| 92fe0c1999 | |||
| ec2c39ed35 |
@@ -22,7 +22,6 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- configurator
|
- configurator
|
||||||
- queues-development
|
- queues-development
|
||||||
- locks-development
|
|
||||||
environment:
|
environment:
|
||||||
STAGE: "development"
|
STAGE: "development"
|
||||||
command: mailbox
|
command: mailbox
|
||||||
@@ -39,5 +38,3 @@ networks:
|
|||||||
external: true
|
external: true
|
||||||
queues-development:
|
queues-development:
|
||||||
external: true
|
external: true
|
||||||
locks-development:
|
|
||||||
external: true
|
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- configurator
|
- configurator
|
||||||
- queues
|
- queues
|
||||||
- locks
|
|
||||||
environment:
|
environment:
|
||||||
STAGE: "production"
|
STAGE: "production"
|
||||||
command: mailbox
|
command: mailbox
|
||||||
@@ -39,5 +38,3 @@ networks:
|
|||||||
external: true
|
external: true
|
||||||
queues:
|
queues:
|
||||||
external: true
|
external: true
|
||||||
locks:
|
|
||||||
external: true
|
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -121,3 +121,4 @@ GitHub.sublime-settings
|
|||||||
local_platform.json
|
local_platform.json
|
||||||
|
|
||||||
*pb2*
|
*pb2*
|
||||||
|
schemas
|
||||||
|
|||||||
@@ -4,6 +4,5 @@ WORKDIR /usr/src/app
|
|||||||
COPY requirements.txt requirements.txt
|
COPY requirements.txt requirements.txt
|
||||||
RUN pip install -r requirements.txt
|
RUN pip install -r requirements.txt
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN make gen
|
|
||||||
ENV PYTHONUNBUFFERED 1
|
ENV PYTHONUNBUFFERED 1
|
||||||
ENTRYPOINT ["python", "main.py"]
|
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:
|
class Daemon:
|
||||||
def __init__(self):
|
|
||||||
self.channel = grpc.insecure_channel(QUEUES_URL)
|
|
||||||
self.stub = tasks_pb2_grpc.TasksStub(channel=self.channel)
|
|
||||||
def execute(self):
|
def execute(self):
|
||||||
raise NotImplemented
|
raise NotImplemented
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import telebot
|
import telebot
|
||||||
import threading
|
import multiprocessing
|
||||||
import time
|
import time
|
||||||
|
import json
|
||||||
|
|
||||||
from daemons import base
|
from daemons import base
|
||||||
from utils import platform
|
from utils import platform
|
||||||
@@ -9,45 +10,37 @@ from utils import queues
|
|||||||
|
|
||||||
class Daemon(base.Daemon):
|
class Daemon(base.Daemon):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.telegram_bots: dict[str, dict[str, telebot.TeleBot|None]] = {}
|
self.processes: dict[str, multiprocessing.Process|None] = {}
|
||||||
self.threads: dict[str, dict[str, threading.Thread|None]] = {}
|
|
||||||
|
|
||||||
def execute(self):
|
def execute(self):
|
||||||
while True:
|
while True:
|
||||||
bots = platform.platform_client.get_config('bots')
|
bots = platform.platform_client.get_config('bots')
|
||||||
for project_name, project in bots.items():
|
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():
|
for bot_name, bot_info in project.items():
|
||||||
if bot_name not in self.telegram_bots[project_name]:
|
key = f'{project_name}_{bot_name}'
|
||||||
self.telegram_bots[project_name][bot_name] = None
|
proc = self.processes.get(key)
|
||||||
self.threads[project_name][bot_name] = None
|
|
||||||
bot = self.telegram_bots[project_name][bot_name]
|
|
||||||
if bot_info.get('poll_enabled'):
|
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')
|
print(f'process for {project_name} {bot_name} is alive')
|
||||||
continue
|
continue
|
||||||
print(f'starting process for {project_name} {bot_name}')
|
print(f'starting process for {project_name} {bot_name}')
|
||||||
bot = telebot.TeleBot(bot_info['secrets']['telegram_token'])
|
process = multiprocessing.Process(target=self.start_polling, args=(bot_info['secrets']['telegram_token'], bot_info['queue']))
|
||||||
thread = self.start_polling(bot, bot_info['queue'])
|
process.start()
|
||||||
self.telegram_bots[project_name][bot_name] = bot
|
self.processes[key] = process
|
||||||
self.threads[project_name][bot_name] = thread
|
|
||||||
print(f'started process for {project_name} {bot_name}')
|
print(f'started process for {project_name} {bot_name}')
|
||||||
else:
|
else:
|
||||||
if bot is None:
|
if proc is None:
|
||||||
print(f'process for {project_name} {bot_name} is not alive')
|
print(f'process for {project_name} {bot_name} is not alive')
|
||||||
continue
|
continue
|
||||||
print(f'terminating process for {project_name} {bot_name}')
|
print(f'terminating process for {project_name} {bot_name}')
|
||||||
bot.stop_bot()
|
proc.terminate()
|
||||||
self.telegram_bots[project_name][bot_name] = None
|
self.processes[key] = None
|
||||||
print(f'terminated process for {project_name} {bot_name}')
|
print(f'terminated process for {project_name} {bot_name}')
|
||||||
time.sleep(10)
|
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'])
|
@bot.message_handler(content_types=['audio', 'photo', 'voice', 'video', 'document', 'animation', 'text', 'location', 'contact', 'sticker', 'video_note'])
|
||||||
def do_action(message: telebot.types.Message):
|
def do_action(message: telebot.types.Message):
|
||||||
queues.set_task(self.stub, queue, message.json, 1)
|
queues.set_task(queue, message.json, 1)
|
||||||
thread = threading.Thread(target=bot.polling)
|
bot.polling()
|
||||||
thread.start()
|
|
||||||
return thread
|
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
annotated-types==0.7.0
|
annotated-types==0.7.0
|
||||||
certifi==2024.8.30
|
certifi==2024.12.14
|
||||||
charset-normalizer==3.4.0
|
charset-normalizer==3.4.0
|
||||||
grpcio==1.68.1
|
|
||||||
grpcio-tools==1.68.1
|
|
||||||
idna==3.10
|
idna==3.10
|
||||||
protobuf==5.29.1
|
pydantic==2.10.4
|
||||||
pydantic==2.10.2
|
pydantic_core==2.27.2
|
||||||
pydantic_core==2.27.1
|
|
||||||
pyTelegramBotAPI==4.1.1
|
pyTelegramBotAPI==4.1.1
|
||||||
requests==2.32.3
|
requests==2.32.3
|
||||||
setuptools==75.6.0
|
|
||||||
typing_extensions==4.12.2
|
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,6 +1,19 @@
|
|||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import datetime
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import traceback
|
||||||
|
import uuid
|
||||||
|
import zoneinfo
|
||||||
|
import requests
|
||||||
import time
|
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'
|
||||||
|
|
||||||
|
|
||||||
class QueuesException(Exception):
|
class QueuesException(Exception):
|
||||||
@@ -8,22 +21,55 @@ class QueuesException(Exception):
|
|||||||
|
|
||||||
|
|
||||||
class TasksHandlerMixin:
|
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):
|
def poll(self):
|
||||||
while True:
|
while True:
|
||||||
response: tasks_pb2.TakeResponse = self.stub.Take(tasks_pb2.TakeRequest(self.queue_name))
|
try:
|
||||||
task: tasks_pb2.Task = response.task
|
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:
|
if not task:
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
continue
|
continue
|
||||||
|
start = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
|
||||||
try:
|
try:
|
||||||
self.process(task.payload)
|
print(f'process task with id {task["id"]}, attempt {task["attempt"]}')
|
||||||
|
self.process(task['payload'])
|
||||||
|
success = True
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f'Error processing message id={task["id"]}, payload={task["payload"]}, exc={exc}')
|
print(f'Error processing message id={task["id"]}, payload={task["payload"]}, exc={exc}')
|
||||||
continue
|
traceback.print_stack()
|
||||||
|
success = False
|
||||||
|
end = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
|
||||||
|
if success:
|
||||||
try:
|
try:
|
||||||
self.stub.Finish(tasks_pb2.FinishRequest(task.id))
|
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:
|
except:
|
||||||
print(f'Failed to finish task id={task.id}')
|
print(f'Failed to finish task id={task["id"]}')
|
||||||
|
self._send_metric(start, end, success)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def queue_name(self):
|
def queue_name(self):
|
||||||
@@ -32,12 +78,12 @@ class TasksHandlerMixin:
|
|||||||
def process(self, payload):
|
def process(self, payload):
|
||||||
raise NotImplemented
|
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(
|
def set_task(queue_name: str, payload: dict, seconds_to_execute: int, delay: int|None = None):
|
||||||
tasks_pb2.PutRequest(
|
resp = requests.post(f'{QUEUES_URL}/api/v1/put', headers={'queue': queue_name}, json={
|
||||||
queue=queue_name,
|
'payload': payload,
|
||||||
seconds_to_execute=seconds_to_execute,
|
'seconds_to_execute': seconds_to_execute,
|
||||||
delay=delay,
|
'delay': delay,
|
||||||
payload=payload
|
})
|
||||||
)
|
if resp.status_code != 202:
|
||||||
)
|
raise QueuesException
|
||||||
|
|||||||
Reference in New Issue
Block a user