-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
1530 lines (1208 loc) · 54 KB
/
main.cpp
File metadata and controls
1530 lines (1208 loc) · 54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sqlite3
import queue
import threading
import time
import uuid
import requests
import paramiko
import hmac
import hashlib
import json
import logging
from datetime import datetime, timezone, timedelta
from flask import Flask, request, jsonify, send_file
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import flask
from dotenv import load_dotenv
import sqlite3
from datetime import datetime
import jwt
import time
sqlite3.register_adapter(datetime, lambda val: val.isoformat())
load_dotenv('/opt/pr-tester/.env')
app = Flask(__name__)
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
GITHUB_WEBHOOK_SECRET = os.environ.get('GITHUB_WEBHOOK_SECRET')
TELEGRAM_BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
TELEGRAM_CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID')
DB_DIR = '/opt/pr-tester'
DB_PATH = os.path.join(DB_DIR, 'pr_tests.db')
FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
FONT_SIZE_TITLE = 36
FONT_SIZE_TEXT = 24
GOLD_COLOR = (255, 215, 0)
AVATAR_SIZE = 40
GITHUB_AVATAR_URL = "https://github.com/"
YC_OAUTH_TOKEN = os.environ.get('YC_OAUTH_TOKEN')
YC_FOLDER_ID = os.environ.get('YC_FOLDER_ID')
WORKER_VM_ID = os.environ.get('WORKER_VM_ID')
YC_API_URL = "https://compute.api.cloud.yandex.net/compute/v1/"
WORKER_USER = os.environ.get('WORKER_USER', 'ubuntu')
WORKER_PASSWORD = os.environ.get('WORKER_PASSWORD')
GPU_WORKER_IP = os.environ.get('GPU_WORKER_IP')
YC_SERVICE_ACCOUNT_KEY_PATH = os.environ.get('YC_SERVICE_ACCOUNT_KEY_PATH', '/opt/pr-tester/key.json')
YC_SERVICE_ACCOUNT_KEY = None
# Конфигурация таймаутов для перезапуска задач
TASK_PROCESSING_TIMEOUT = 1200 # 20 минут в секундах (нормальное время 10 минут + запас)
TASK_PENDING_TIMEOUT = 1800 # 30 минут в секундах
STUCK_TASK_CHECK_INTERVAL = 300 # 5 минут
MAX_RESTART_ATTEMPTS = 3 # Максимальное количество перезапусков
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
task_queue = queue.Queue()
worker_lock = threading.Lock()
worker_active = False
worker_last_heartbeat = time.time()
worker_current_ip = None
USE_YC_CLOUD = os.environ.get('USE_YC_CLOUD', 'false').lower() == 'true'
def load_service_account_key():
global YC_SERVICE_ACCOUNT_KEY
try:
with open(YC_SERVICE_ACCOUNT_KEY_PATH, 'r') as f:
YC_SERVICE_ACCOUNT_KEY = json.load(f)
logger.info("✅ Сервисный ключ Яндекс.Облака успешно загружен")
return True
except Exception as e:
logger.error(f"❌ Ошибка загрузки сервисного ключа: {e}")
return False
def get_iam_token():
if not YC_SERVICE_ACCOUNT_KEY:
if not load_service_account_key():
return None
try:
service_account_id = YC_SERVICE_ACCOUNT_KEY["service_account_id"]
key_id = YC_SERVICE_ACCOUNT_KEY["id"]
private_key = YC_SERVICE_ACCOUNT_KEY["private_key"]
now = int(time.time())
payload = {
"aud": "https://iam.api.cloud.yandex.net/iam/v1/tokens",
"iss": service_account_id,
"iat": now,
"exp": now + 3600,
}
encoded_jwt = jwt.encode(payload, private_key, algorithm="PS256", headers={"kid": key_id})
response = requests.post(
"https://iam.api.cloud.yandex.net/iam/v1/tokens",
json={"jwt": encoded_jwt},
timeout=15,
)
if response.status_code == 200:
token = response.json()["iamToken"]
logger.info("✅ IAM токен успешно создан через JWT")
return token
else:
logger.error(f"❌ Ошибка получения IAM токена: {response.status_code} {response.text}")
except Exception as e:
logger.error(f"❌ Ошибка при генерации IAM токена: {e}")
return None
def ensure_db_dir():
if not os.path.exists(DB_DIR):
logger.error(f"Database directory does not exist: {DB_DIR}")
raise Exception(f"Database directory does not exist: {DB_DIR}")
def init_db():
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS tests
(id TEXT PRIMARY KEY,
pr_id INTEGER,
repo TEXT,
status TEXT,
result_json TEXT,
logs TEXT,
created_at TIMESTAMP,
updated_at TIMESTAMP,
commit_sha TEXT,
comment_id INTEGER)''')
c.execute('''CREATE TABLE IF NOT EXISTS tasks
(id TEXT PRIMARY KEY,
pr_id INTEGER,
repo TEXT,
clone_url TEXT,
commit_sha TEXT,
branch TEXT,
status TEXT CHECK(status IN ('pending', 'processing', 'completed', 'failed')),
created_at TIMESTAMP,
started_at TIMESTAMP,
completed_at TIMESTAMP,
comment_id INTEGER,
restart_count INTEGER DEFAULT 0,
max_restarts INTEGER DEFAULT 3)''')
c.execute('''CREATE TABLE IF NOT EXISTS worker_status
(id INTEGER PRIMARY KEY AUTOINCREMENT,
status TEXT,
last_heartbeat TIMESTAMP,
current_task TEXT,
created_at TIMESTAMP)''')
c.execute('''CREATE TABLE IF NOT EXISTS processed_events
(event_id TEXT PRIMARY KEY,
event_type TEXT,
repo TEXT,
pr_id INTEGER,
created_at TIMESTAMP)''')
conn.commit()
conn.close()
def migrate_db():
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
try:
c.execute("PRAGMA table_info(tasks)")
columns = [column[1] for column in c.fetchall()]
if 'comment_id' not in columns:
c.execute("ALTER TABLE tasks ADD COLUMN comment_id INTEGER")
logger.info("Added comment_id column to tasks table")
if 'restart_count' not in columns:
c.execute("ALTER TABLE tasks ADD COLUMN restart_count INTEGER DEFAULT 0")
logger.info("Added restart_count column to tasks table")
if 'max_restarts' not in columns:
c.execute("ALTER TABLE tasks ADD COLUMN max_restarts INTEGER DEFAULT 3")
logger.info("Added max_restarts column to tasks table")
c.execute("PRAGMA table_info(tests)")
columns = [column[1] for column in c.fetchall()]
if 'comment_id' not in columns:
c.execute("ALTER TABLE tests ADD COLUMN comment_id INTEGER")
logger.info("Added comment_id column to tests table")
conn.commit()
except Exception as e:
logger.error(f"Database migration failed: {e}")
finally:
conn.close()
def get_worker_ip():
global worker_current_ip
if not USE_YC_CLOUD:
return worker_current_ip
token = get_iam_token()
if not token:
logger.error("Не удалось получить IAM токен")
return None
headers = {
"Authorization": f"Bearer {token}",
}
try:
response = requests.get(f"{YC_API_URL}instances/{WORKER_VM_ID}",
headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
network_interfaces = data.get('networkInterfaces', [])
if network_interfaces:
primary_interface = network_interfaces[0]
ip_address = primary_interface.get('primaryV4Address', {}).get('address')
worker_current_ip = ip_address
return ip_address
else:
logger.error(f"❌ Ошибка получения информации о ВМ: {response.status_code}")
return None
except Exception as e:
logger.error(f"❌ Ошибка получения IP ВМ: {e}")
return None
def cleanup_old_tasks(pr_id, repo, current_task_id=None):
"""Удаляет старые задачи для PR при создании нового перезапуска"""
try:
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
# Удаляем все pending и processing задачи для этого PR, кроме текущей (если указана)
if current_task_id:
c.execute("""
DELETE FROM tasks
WHERE pr_id = ? AND repo = ? AND status IN ('pending', 'processing') AND id != ?
""", (pr_id, repo, current_task_id))
else:
c.execute("""
DELETE FROM tasks
WHERE pr_id = ? AND repo = ? AND status IN ('pending', 'processing')
""", (pr_id, repo))
deleted_count = c.rowcount
conn.commit()
conn.close()
if deleted_count > 0:
logger.info(f"🧹 Удалено {deleted_count} старых задач для PR #{pr_id} в {repo}")
return deleted_count
except Exception as e:
logger.error(f"❌ Ошибка при удалении старых задач для PR #{pr_id}: {e}")
return 0
def can_restart_task(task_id, pr_id, repo):
"""Проверяет, можно ли перезапустить задачу"""
try:
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("""
SELECT restart_count, max_restarts, status
FROM tasks
WHERE id = ? AND pr_id = ? AND repo = ?
""", (task_id, pr_id, repo))
task = c.fetchone()
conn.close()
if not task:
logger.warning(f"Задача {task_id} не найдена")
return False
restart_count, max_restarts, status = task
if restart_count >= max_restarts:
logger.info(f"❌ Достигнут лимит перезапусков для задачи {task_id} ({restart_count}/{max_restarts})")
return False
return True
except Exception as e:
logger.error(f"❌ Ошибка при проверке возможности перезапуска: {e}")
return False
def check_and_restart_stuck_tasks():
"""Проверяет и перезапускает зависшие задачи с учетом ограничений"""
try:
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
current_time = datetime.now(timezone.utc)
# Находим задачи в статусе processing, которые висят слишком долго (больше 20 минут)
processing_timeout = current_time - timedelta(seconds=TASK_PROCESSING_TIMEOUT)
c.execute("""
SELECT id, pr_id, repo, clone_url, commit_sha, branch, comment_id, restart_count, max_restarts
FROM tasks
WHERE status = 'processing' AND started_at < ?
""", (processing_timeout,))
stuck_processing_tasks = c.fetchall()
# Находим задачи в статусе pending, которые висят слишком долго (больше 30 минут)
pending_timeout = current_time - timedelta(seconds=TASK_PENDING_TIMEOUT)
c.execute("""
SELECT id, pr_id, repo, clone_url, commit_sha, branch, comment_id, restart_count, max_restarts
FROM tasks
WHERE status = 'pending' AND created_at < ?
""", (pending_timeout,))
stuck_pending_tasks = c.fetchall()
all_stuck_tasks = stuck_processing_tasks + stuck_pending_tasks
restarted_count = 0
for task in all_stuck_tasks:
task_id, pr_id, repo, clone_url, commit_sha, branch, comment_id, restart_count, max_restarts = task
# Проверяем возможность перезапуска
if restart_count >= max_restarts:
logger.warning(f"❌ Достигнут лимит перезапусков для зависшей задачи {task_id}, пропускаем")
continue
logger.warning(f"🔄 Найдена зависшая задача {task_id} для PR #{pr_id} в {repo}, перезапускаем... (попытка {restart_count + 1}/{max_restarts})")
# Удаляем старые задачи перед перезапуском
cleanup_old_tasks(pr_id, repo, task_id)
# Обновляем статус задачи, сбрасываем время начала и увеличиваем счетчик перезапусков
c.execute("""
UPDATE tasks
SET status = 'pending', started_at = NULL, completed_at = NULL, restart_count = restart_count + 1
WHERE id = ?
""", (task_id,))
# Возвращаем задачу в очередь
task_data = {
'id': task_id,
'pr_id': pr_id,
'repo': repo,
'clone_url': clone_url,
'commit_sha': commit_sha,
'branch': branch,
'comment_id': comment_id
}
task_queue.put(task_data)
restarted_count += 1
# Логируем событие
send_telegram_message(f"🔄 Перезапуск зависшей задачи для PR #{pr_id} в {repo} (попытка {restart_count + 1}/{max_restarts})")
conn.commit()
conn.close()
if restarted_count > 0:
logger.info(f"✅ Перезапущено {restarted_count} зависших задач")
except Exception as e:
logger.error(f"❌ Ошибка при проверке зависших задач: {e}")
def stuck_task_monitor():
"""Монитор для периодической проверки зависших задач"""
while True:
try:
check_and_restart_stuck_tasks()
time.sleep(STUCK_TASK_CHECK_INTERVAL)
except Exception as e:
logger.error(f"❌ Ошибка в мониторе зависших задач: {e}")
time.sleep(60) # Пауза при ошибке
def worker_monitor():
global worker_active, worker_last_heartbeat, worker_current_ip
while True:
try:
if USE_YC_CLOUD:
current_ip = get_worker_ip()
if current_ip:
logger.info(f"Worker VM IP: {current_ip}")
with worker_lock:
is_active = worker_active
last_hb = worker_last_heartbeat
if is_active and time.time() - last_hb > 300:
logger.warning("Worker appears to be dead. Marking as inactive.")
with worker_lock:
worker_active = False
if not task_queue.empty() and not is_active:
logger.info("Tasks in queue but worker is inactive. Starting worker...")
if USE_YC_CLOUD:
if start_worker_vm():
with worker_lock:
worker_active = True
worker_last_heartbeat = time.time()
else:
with worker_lock:
worker_active = True
worker_last_heartbeat = time.time()
logger.info("Worker marked as active (YC Cloud disabled)")
if task_queue.empty() and is_active and time.time() - last_hb > 600 and USE_YC_CLOUD:
logger.info("No tasks and worker idle. Stopping worker...")
if stop_worker_vm():
with worker_lock:
worker_active = False
time.sleep(30)
except Exception as e:
logger.error(f"Error in worker monitor: {e}")
time.sleep(60)
def start_worker_vm():
if not USE_YC_CLOUD:
logger.info("Yandex Cloud disabled, skipping VM start")
return True
token = get_iam_token()
if not token:
logger.error("❌ Не удалось получить IAM токен для запуска ВМ")
return False
headers = {
"Authorization": f"Bearer {token}",
}
try:
logger.info(f"🟡 Отправка команды на запуск ВМ {WORKER_VM_ID}")
response = requests.post(f"{YC_API_URL}instances/{WORKER_VM_ID}:start",
headers=headers, timeout=30)
if response.status_code == 200:
logger.info("✅ Команда на запуск ВМ успешно отправлена")
logger.info("⏳ Ожидание запуска ВМ...")
for i in range(30):
time.sleep(10)
ip_address = get_worker_ip()
if ip_address:
logger.info(f"✅ ВМ запущена с IP: {ip_address}")
logger.info("⏳ Ожидание инициализации ВМ...")
time.sleep(30)
return True
logger.info(f"⏳ Попытка {i+1}/30: ВМ еще не готова...")
logger.error("❌ Таймаут запуска ВМ")
return False
else:
logger.error(f"❌ Ошибка запуска ВМ: {response.status_code} {response.text}")
return False
except Exception as e:
logger.error(f"❌ Ошибка при запуске ВМ: {e}")
return False
def generate_comment(result, pr_id, repo, status, logs):
if status == 'completed':
emoji = '✅'
elif status == 'failure':
emoji = '❌'
elif status == 'timeout':
emoji = '⏰'
else:
emoji = '⚠️'
comment = f"""{emoji} **Результаты тестирования PR #{pr_id}**
<details><summary>Логи тестирования (нажмите чтобы развернуть)</summary>
<pre>
{logs}
</pre>
</details>
[Посмотреть полные логи](http://{os.environ.get('MAIN_SERVER_IP', 'localhost')}:5000/logs/{pr_id})"""
return comment
def post_github_comment(repo, pr_id, comment):
if not GITHUB_TOKEN:
logger.warning("No GITHUB_TOKEN, skipping comment")
return
url = f'https://api.github.com/repos/{repo}/issues/{pr_id}/comments'
headers = {
'Authorization': f'token {GITHUB_TOKEN}',
'Accept': 'application/vnd.github.v3+json'
}
data = {'body': comment}
try:
response = requests.post(url, headers=headers, json=data)
if response.status_code == 201:
logger.info(f"Comment successfully posted to PR #{pr_id} in {repo}")
return response.json().get('id')
else:
logger.error(f"Failed to post comment to PR #{pr_id} in {repo}: {response.status_code}")
return None
except Exception as e:
logger.error(f"Error posting GitHub comment: {e}")
return None
def stop_worker_vm():
if not USE_YC_CLOUD:
logger.info("Yandex Cloud disabled, skipping VM stop")
return True
token = get_iam_token()
if not token:
logger.error("❌ Не удалось получить IAM токен для остановки ВМ")
return False
headers = {
"Authorization": f"Bearer {token}",
}
try:
logger.info(f"🟡 Отправка команды на остановку ВМ {WORKER_VM_ID}")
response = requests.post(f"{YC_API_URL}instances/{WORKER_VM_ID}:stop",
headers=headers, timeout=30)
if response.status_code == 200:
logger.info("✅ Команда на остановку ВМ успешно отправлена")
logger.info("⏳ Ожидание остановки ВМ...")
for i in range(30):
time.sleep(10)
status = get_vm_status()
if status == "STOPPED":
logger.info("✅ ВМ успешно остановлена")
return True
elif status == "STOPPING":
logger.info(f"⏳ Попытка {i+1}/30: ВМ останавливается...")
continue
else:
logger.error(f"❌ Неожиданный статус ВМ при остановке: {status}")
return False
logger.error("❌ Таймаут остановки ВМ")
return False
else:
logger.error(f"❌ Ошибка остановки ВМ: {response.status_code} {response.text}")
return False
except Exception as e:
logger.error(f"❌ Ошибка при остановке ВМ: {e}")
return False
def get_vm_status(vm_id=None):
if not USE_YC_CLOUD:
return "RUNNING"
if vm_id is None:
vm_id = WORKER_VM_ID
token = get_iam_token()
if not token:
return None
headers = {
"Authorization": f"Bearer {token}",
}
try:
response = requests.get(f"{YC_API_URL}instances/{vm_id}",
headers=headers, timeout=10)
if response.status_code == 200:
return response.json().get('status')
else:
logger.error(f"❌ Ошибка получения статуса ВМ: {response.status_code}")
return None
except Exception as e:
logger.error(f"❌ Ошибка получения статуса ВМ: {e}")
return None
def send_telegram_message(text):
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
return None
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
data = {
"chat_id": TELEGRAM_CHAT_ID,
"text": text,
"parse_mode": "Markdown"
}
try:
response = requests.post(url, json=data)
return response.json()
except Exception as e:
logger.error(f"Ошибка отправки в Telegram: {e}")
return None
def check_ssh_connection(ip_address):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip_address, username=WORKER_USER, password=WORKER_PASSWORD, timeout=10)
ssh.close()
return True, "SSH connection successful"
except paramiko.AuthenticationException:
return False, "SSH authentication failed"
except Exception as e:
return False, f"SSH connection error: {str(e)}"
def generate_telegram_message(result, pr_id, repo, status, logs):
if status == 'completed':
emoji = '✅'
status_text = 'Тесты пройдены успешно!'
elif status == 'failure':
emoji = '❌'
status_text = 'Тесты не пройдены.'
elif status == 'timeout':
emoji = '⏰'
status_text = 'Превышено время выполнения.'
else:
emoji = '⚠️'
status_text = 'Произошла ошибка.'
full_logs = logs
if len(full_logs) > 1000:
full_logs = full_logs[:1000] + "\n... (логи обрезаны)"
bandwidth_info = ""
if result.get('timings'):
for key, value in result['timings'].items():
if value and value > 0 and 'bandwidth' in key.lower():
bandwidth_info = f"\n🏎️ Пропускная способность: {value:.2f} GB/s"
break
message = f"""
{emoji} **Результаты тестирования PR #{pr_id}**
📊 **Репозиторий:** {repo}
🔄 **Статус:** {status_text}
{bandwidth_info}
**Логи тестирования:**
📋 Полные логи доступны по ссылке:
http://{os.environ.get('MAIN_SERVER_IP', 'localhost')}:5000/logs/{pr_id}
"""
return message.strip()
def create_task_from_pr(pr_data, repo, event_type="pull_request", comment_id=None):
global worker_active, worker_last_heartbeat
pr_id = pr_data['number']
clone_url = pr_data['head']['repo']['clone_url']
commit_sha = pr_data['head']['sha']
branch = pr_data['head']['ref']
logger.info(f"Processing {event_type} for PR #{pr_id} from {repo}, branch: {branch}")
# Очищаем старые задачи для этого PR перед созданием новой
cleanup_old_tasks(pr_id, repo)
# Создаем новую задачу
task_id = str(uuid.uuid4())
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(
"INSERT INTO tasks (id, pr_id, repo, clone_url, commit_sha, branch, status, created_at, comment_id, restart_count, max_restarts) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(task_id, pr_id, repo, clone_url, commit_sha, branch, 'pending', datetime.now(timezone.utc), comment_id, 0, MAX_RESTART_ATTEMPTS))
conn.commit()
conn.close()
task = {
'id': task_id,
'pr_id': pr_id,
'repo': repo,
'clone_url': clone_url,
'commit_sha': commit_sha,
'branch': branch,
'comment_id': comment_id
}
task_queue.put(task)
with worker_lock:
if not worker_active:
logger.info("Starting worker for new task")
if start_worker_vm():
worker_active = True
worker_last_heartbeat = time.time()
logger.info(f"✅ Добавлена задача {task_id} для PR #{pr_id} в очередь")
send_telegram_message(f"🚀 Новый PR #{pr_id} в {repo} добавлен в очередь")
def check_missed_prs():
if not GITHUB_TOKEN:
logger.warning("No GITHUB_TOKEN, cannot check missed PRs")
return
logger.info("Checking for missed PRs and comments...")
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT DISTINCT repo FROM tasks")
repos = [row[0] for row in c.fetchall()]
conn.close()
headers = {
'Authorization': f'token {GITHUB_TOKEN}',
'Accept': 'application/vnd.github.v3+json'
}
for repo in repos:
try:
prs_url = f'https://api.github.com/repos/{repo}/pulls?state=open'
response = requests.get(prs_url, headers=headers, timeout=30)
if response.status_code != 200:
logger.error(f"Failed to get PRs for {repo}: {response.status_code}")
continue
pr_list = response.json()
for pr in pr_list:
pr_id = pr['number']
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT id, status, restart_count, max_restarts FROM tasks WHERE pr_id = ? AND repo = ? ORDER BY created_at DESC LIMIT 1",
(pr_id, repo))
task = c.fetchone()
conn.close()
# Создаем новую задачу только если предыдущая завершена и не превышен лимит перезапусков
if not task or (task[1] in ('failed', 'timeout') and task[2] < task[3]):
logger.info(f"Found missed PR #{pr_id} in {repo}, creating task")
create_task_from_pr(pr, repo, "missed_pr_check")
comments_url = f'https://api.github.com/repos/{repo}/issues/{pr_id}/comments'
comments_response = requests.get(comments_url, headers=headers, timeout=30)
if comments_response.status_code == 200:
comments = comments_response.json()
for comment in comments:
comment_id = comment['id']
comment_body = comment['body']
created_at = comment['created_at']
if '/run-tests' in comment_body:
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT id FROM processed_events WHERE event_id = ?", (f"comment_{comment_id}",))
processed = c.fetchone()
conn.close()
if not processed:
logger.info(f"Found test command in comment {comment_id} for PR #{pr_id} in {repo}")
create_task_from_pr(pr, repo, "comment", comment_id)
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(
"INSERT INTO processed_events (event_id, event_type, repo, pr_id, created_at) VALUES (?, ?, ?, ?, ?)",
(f"comment_{comment_id}", "comment", repo, pr_id, datetime.now(timezone.utc)))
conn.commit()
conn.close()
except Exception as e:
logger.error(f"Error checking missed PRs for {repo}: {e}")
def periodic_check():
while True:
try:
check_missed_prs()
except Exception as e:
logger.error(f"Error in periodic check: {e}")
time.sleep(3600)
@app.route('/webhook', methods=['POST'])
def handle_webhook():
global worker_active, worker_last_heartbeat
if GITHUB_WEBHOOK_SECRET:
signature = flask.request.headers.get('X-Hub-Signature-256', '')
payload = flask.request.get_data()
computed_signature = 'sha256=' + hmac.new(GITHUB_WEBHOOK_SECRET.encode(), payload, hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, computed_signature):
logger.warning(f"Invalid webhook signature: {signature}")
return 'Invalid signature', 403
event = flask.request.headers.get('X-GitHub-Event')
payload = flask.request.json
logger.info(f"Received GitHub event: {event}")
if event == 'pull_request':
action = payload['action']
if action in ['opened', 'synchronize']:
pr_data = payload['pull_request']
repo = pr_data['base']['repo']['full_name']
create_task_from_pr(pr_data, repo, event)
elif event == 'issue_comment':
action = payload['action']
if action == 'created':
comment = payload['comment']
comment_id = comment['id']
comment_body = comment['body']
if '/run-tests' in comment_body:
issue = payload['issue']
if 'pull_request' in issue:
pr_url = issue['pull_request']['url']
headers = {
'Authorization': f'token {GITHUB_TOKEN}',
'Accept': 'application/vnd.github.v3+json'
}
pr_response = requests.get(pr_url, headers=headers, timeout=30)
if pr_response.status_code == 200:
pr_data = pr_response.json()
repo = pr_data['base']['repo']['full_name']
create_task_from_pr(pr_data, repo, "comment", comment_id)
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(
"INSERT INTO processed_events (event_id, event_type, repo, pr_id, created_at) VALUES (?, ?, ?, ?, ?)",
(f"comment_{comment_id}", "comment", repo, pr_data['number'], datetime.now(timezone.utc)))
conn.commit()
conn.close()
return 'OK', 200
@app.route('/api/worker/get_task', methods=['GET'])
def worker_get_task():
try:
task = task_queue.get_nowait()
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
# Проверяем, не взял ли уже другой воркер эту задачу
c.execute("SELECT status FROM tasks WHERE id=?", (task['id'],))
current_status = c.fetchone()
if current_status and current_status[0] == 'processing':
# Задача уже в обработке другим воркером, возвращаем её в очередь
logger.warning(f"⚠️ Задача {task['id']} уже в обработке, возвращаем в очередь")
task_queue.put(task)
conn.close()
return jsonify({'message': 'Task already being processed'}), 409
# Обновляем статус задачи
c.execute("UPDATE tasks SET status=?, started_at=? WHERE id=?",
('processing', datetime.now(timezone.utc), task['id']))
conn.commit()
conn.close()
logger.info(f"✅ Задача {task['id']} назначена воркеру")
return jsonify(task)
except queue.Empty:
return jsonify({'message': 'No tasks available'}), 404
@app.route('/api/worker/task_result', methods=['POST'])
def worker_task_result():
global worker_active
data = request.json
logger.info(f"Received task result: {json.dumps(data, ensure_ascii=False)}")
task_id = data.get('id')
status = data.get('status')
result_json = data.get('result_json')
logs = data.get('logs')
if not task_id or not status:
return jsonify({'error': 'Missing task id or status'}), 400
status_mapping = {
'success': 'completed',
'failure': 'failed',
'error': 'failed',
'timeout': 'failed'
}
task_status = status_mapping.get(status, 'failed')
result_data = {}
if result_json:
try:
result_data = json.loads(result_json)
if task_status == 'completed' and (
not result_data.get('timings') or not any(result_data['timings'].values())):
result_data['timings'] = {'device_info_bandwidth': 0.0}
logger.info(f"Added default zero bandwidth for task {task_id}")
except json.JSONDecodeError:
logger.error(f"Failed to parse result_json for task {task_id}")
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("UPDATE tasks SET status=?, completed_at=? WHERE id=?",
(task_status, datetime.now(timezone.utc), task_id))
c.execute("SELECT pr_id, repo, commit_sha, comment_id FROM tasks WHERE id=?", (task_id,))
task_data = c.fetchone()
if task_data:
pr_id, repo, commit_sha, comment_id = task_data
c.execute(
"INSERT OR REPLACE INTO tests (id, pr_id, repo, status, result_json, logs, created_at, updated_at, commit_sha, comment_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(task_id, pr_id, repo, task_status, json.dumps(result_data), logs, datetime.now(timezone.utc),
datetime.now(timezone.utc), commit_sha, comment_id))
conn.commit()
conn.close()
comment = generate_comment(result_data, pr_id, repo, task_status, logs)
post_github_comment(repo, pr_id, comment)
logger.info(f"Task {task_id} completed with status: {task_status}")
telegram_message = generate_telegram_message(result_data, pr_id, repo, task_status, logs)
send_telegram_message(telegram_message)
return jsonify({'message': 'Result received'})
@app.route('/api/worker/heartbeat', methods=['POST'])
def worker_heartbeat():
global worker_last_heartbeat
with worker_lock:
worker_last_heartbeat = time.time()
logger.debug("Worker heartbeat received")
return jsonify({'message': 'Heartbeat received'})
@app.route('/logs/<int:pr_id>')
def view_logs(pr_id):
ensure_db_dir()
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT logs, created_at FROM tests WHERE pr_id = ? ORDER BY created_at DESC LIMIT 1", (pr_id,))
row = c.fetchone()
conn.close()