-
Notifications
You must be signed in to change notification settings - Fork 6
/
run.py
1891 lines (1528 loc) · 56.7 KB
/
run.py
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
#!/usr/bin/env python3
import os
import sys
import argh
import random
import logging
import asyncio
import traceback
import itertools
import tracemalloc
import string
import shutil
import hmac
import hashlib
from datetime import datetime, date
from collections import defaultdict
from functools import wraps
from concurrent.futures._base import CancelledError
from asyncio import Task
import json
import aiohttp
import aiofiles
from websockets.exceptions import ConnectionClosed
from websockets import WebSocketCommonProtocol
from sanic import Sanic, response
from sanic.exceptions import NotFound, WebsocketClosed
from sanic.log import LOGGING_CONFIG_DEFAULTS
from jinja2 import FileSystemLoader
from sanic_jinja2 import SanicJinja2
from peewee import fn
from playhouse.shortcuts import model_to_dict
from models import Repo, Job, db, Worker
from schedule import always_relaunch, once_per_day
# This is used by ciclic
admin_token = "".join(random.choices(string.ascii_lowercase + string.digits, k=32))
open(".admin_token", "w").write(admin_token)
try:
asyncio_all_tasks = asyncio.all_tasks
except AttributeError as e:
asyncio_all_tasks = asyncio.Task.all_tasks
LOGGING_CONFIG_DEFAULTS["loggers"] = {
"task": {
"level": "INFO",
"handlers": ["task_console"],
},
"api": {
"level": "INFO",
"handlers": ["api_console"],
},
}
LOGGING_CONFIG_DEFAULTS["handlers"] = {
"api_console": {
"class": "logging.StreamHandler",
"formatter": "api",
"stream": sys.stdout,
},
"task_console": {
"class": "logging.StreamHandler",
"formatter": "background",
"stream": sys.stdout,
},
}
LOGGING_CONFIG_DEFAULTS["formatters"] = {
"background": {
"format": "%(asctime)s [%(process)d] [BACKGROUND] [%(funcName)s] %(message)s",
"datefmt": "[%Y-%m-%d %H:%M:%S %z]",
"class": "logging.Formatter",
},
"api": {
"format": "%(asctime)s [%(process)d] [API] [%(funcName)s] %(message)s",
"datefmt": "[%Y-%m-%d %H:%M:%S %z]",
"class": "logging.Formatter",
},
}
def datetime_to_epoch_json_converter(o):
if isinstance(o, datetime):
return o.strftime("%s")
# define a custom json dumps to convert datetime
def my_json_dumps(o):
return json.dumps(o, default=datetime_to_epoch_json_converter)
task_logger = logging.getLogger("task")
api_logger = logging.getLogger("api")
app = Sanic(__name__, dumps=my_json_dumps)
app.static("/static", "./static/")
yunorunner_dir = os.path.abspath(os.path.dirname(__file__))
loader = FileSystemLoader(yunorunner_dir + "/templates", encoding="utf8")
jinja = SanicJinja2(app, loader=loader)
# to avoid conflict with vue.js
jinja.env.block_start_string = "<%"
jinja.env.block_end_string = "%>"
jinja.env.variable_start_string = "<{"
jinja.env.variable_end_string = "}>"
jinja.env.comment_start_string = "<#"
jinja.env.comment_end_string = "#>"
APPS_LIST = "https://app.yunohost.org/default/v3/apps.json"
subscriptions = defaultdict(list)
# this will have the form:
# jobs_in_memory_state = {
# some_job_id: {"worker": some_worker_id, "task": some_aio_task},
# }
jobs_in_memory_state = {}
async def wait_closed(self):
"""
Wait until the connection is closed.
This is identical to :attr:`closed`, except it can be awaited.
This can make it easier to handle connection termination, regardless
of its cause, in tasks that interact with the WebSocket connection.
"""
await asyncio.shield(self.connection_lost_waiter)
# this is a backport of websockets 7.0 which sanic doesn't support yet
WebSocketCommonProtocol.wait_closed = wait_closed
def reset_pending_jobs():
Job.update(state="scheduled", log="").where(Job.state == "running").execute()
def reset_busy_workers():
# XXX when we'll have distant workers that might break those
Worker.update(state="available").execute()
def merge_jobs_on_startup():
task_logger.info(f"looks for jobs to merge on startup")
query = Job.select().where(Job.state == "scheduled").order_by(Job.name, -Job.id)
name_to_jobs = defaultdict(list)
for job in query:
name_to_jobs[job.name].append(job)
for jobs in name_to_jobs.values():
# keep oldest job
if jobs[:-1]:
task_logger.info(f"Merging {jobs[0].name} jobs...")
for to_delete in jobs[:-1]:
to_delete.delete_instance()
task_logger.info(f"* delete {to_delete.name} [{to_delete.id}]")
def set_random_day_for_monthy_job():
for repo in Repo.select().where((Repo.random_job_day == None)):
repo.random_job_day = random.randint(1, 28)
task_logger.info(
f"set random day for monthly job of repo '{repo.name}' at '{repo.random_job_day}'"
)
repo.save()
async def create_job(app_id, repo_url, job_comment=""):
job_name = app_id
if job_comment:
job_name += f" ({job_comment})"
# avoid scheduling twice
if Job.select().where(Job.name == job_name, Job.state == "scheduled").count() > 0:
task_logger.info(
f"a job for '{job_name} is already scheduled, not adding another one"
)
return
job = Job.create(
name=job_name,
url_or_path=repo_url,
state="scheduled",
)
await broadcast(
{
"action": "new_job",
"data": model_to_dict(job),
},
"jobs",
)
return job
@always_relaunch(sleep=60 * 5)
async def monitor_apps_lists(monitor_git=False, monitor_only_good_quality_apps=False):
"parse apps lists every hour or so to detect new apps"
# only support github for now :(
async def get_master_commit_sha(url):
command = await asyncio.create_subprocess_shell(
f"git ls-remote {url} master",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
data = await command.stdout.read()
commit_sha = data.decode().strip().replace("\t", " ").split(" ")[0]
return commit_sha
async with aiohttp.ClientSession() as session:
task_logger.info(f"Downloading applist...")
async with session.get(APPS_LIST) as resp:
data = await resp.json()
data = data["apps"]
repos = {x.name: x for x in Repo.select()}
for app_id, app_data in data.items():
commit_sha = await get_master_commit_sha(app_data["git"]["url"])
if app_data["state"] != "working":
task_logger.debug(f"skip {app_id} because state is {app_data['state']}")
continue
if monitor_only_good_quality_apps:
if app_data.get("level") in [None, "?"] or app_data["level"] <= 4:
task_logger.debug(f"skip {app_id} because app is not good quality")
continue
# already know, look to see if there is new commits
if app_id in repos:
repo = repos[app_id]
# but first check if the URL has changed
if repo.url != app_data["git"]["url"]:
task_logger.info(
f"Application {app_id} has changed of url from {repo.url} to {app_data['git']['url']}"
)
repo.url = app_data["git"]["url"]
repo.save()
await broadcast(
{
"action": "update_app",
"data": model_to_dict(repo),
},
"apps",
)
# change the url of all jobs that used to have this URL I
# guess :/
# this isn't perfect because that could overwrite added by
# hand jobs but well...
for job in Job.select().where(
Job.url_or_path == repo.url, Job.state == "scheduled"
):
job.url_or_path = repo.url
job.save()
task_logger.info(
f"Updating job {job.name} #{job.id} for {app_id} to {repo.url} since the app has changed of url"
)
await broadcast(
{
"action": "update_job",
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
# we don't want to do anything else
if not monitor_git:
continue
repo_is_updated = False
if repo.revision != commit_sha:
task_logger.info(
f"Application {app_id} has new commits on github "
f"({repo.revision} → {commit_sha}), schedule new job"
)
repo.revision = commit_sha
repo.save()
repo_is_updated = True
await create_job(app_id, repo.url)
repo_state = (
"working" if app_data["state"] == "working" else "other_than_working"
)
if repo.state != repo_state:
repo.state = repo_state
repo.save()
repo_is_updated = True
if repo.random_job_day is None:
repo.random_job_day = random.randint(1, 28)
repo.save()
repo_is_updated = True
if repo_is_updated:
await broadcast(
{
"action": "update_app",
"data": model_to_dict(repo),
},
"apps",
)
# new app
elif app_id not in repos:
task_logger.info(
f"New application detected: {app_id} "
+ (", scheduling a new job" if monitor_git else "")
)
repo = Repo.create(
name=app_id,
url=app_data["git"]["url"],
revision=commit_sha,
state=(
"working"
if app_data["state"] == "working"
else "other_than_working"
),
random_job_day=random.randint(1, 28),
)
await broadcast(
{
"action": "new_app",
"data": model_to_dict(repo),
},
"apps",
)
if monitor_git:
await create_job(app_id, repo.url)
await asyncio.sleep(1)
# delete apps removed from the list
unseen_repos = set(repos.keys()) - set(data.keys())
for repo_name in unseen_repos:
repo = repos[repo_name]
# delete scheduled jobs first
task_logger.info(
f"Application {repo_name} has been removed from the app list, start by removing its scheduled job if there are any..."
)
for job in Job.select().where(
Job.url_or_path == repo.url, Job.state == "scheduled"
):
await api_stop_job(None, job.id) # not sure this is going to work
job_id = job.id
task_logger.info(
f"Delete scheduled job {job.name} #{job.id} for application {repo_name} because the application is being deleted."
)
data = model_to_dict(job)
job.delete_instance()
await broadcast(
{
"action": "delete_job",
"data": data,
},
["jobs", f"job-{job_id}", f"app-jobs-{job.url_or_path}"],
)
task_logger.info(
f"Delete application {repo_name} because it has been removed from the apps list."
)
data = model_to_dict(repo)
repo.delete_instance()
await broadcast(
{
"action": "delete_app",
"data": data,
},
"apps",
)
@once_per_day
async def launch_monthly_job():
today = date.today().day
for repo in Repo.select().where(Repo.random_job_day == today):
task_logger.info(
f"Launch monthly job for {repo.name} on day {today} of the month "
)
await create_job(repo.name, repo.url)
async def ensure_workers_count():
if Worker.select().count() < app.config.WORKER_COUNT:
for _ in range(app.config.WORKER_COUNT - Worker.select().count()):
Worker.create(state="available")
elif Worker.select().count() > app.config.WORKER_COUNT:
workers_to_remove = Worker.select().count() - app.config.WORKER_COUNT
workers = Worker.select().where(Worker.state == "available")
for worker in workers:
if workers_to_remove == 0:
break
worker.delete_instance()
workers_to_remove -= 1
jobs_to_stop = workers_to_remove
for job_id in jobs_in_memory_state:
if jobs_to_stop == 0:
break
await stop_job(job_id)
jobs_to_stop -= 1
job = Job.select().where(Job.id == job_id)[0]
job.state = "scheduled"
job.log = ""
job.save()
workers = Worker.select().where(Worker.state == "available")
for worker in workers:
if workers_to_remove == 0:
break
worker.delete_instance()
workers_to_remove -= 1
@always_relaunch(sleep=3)
async def jobs_dispatcher():
await ensure_workers_count()
workers = Worker.select().where(Worker.state == "available")
# no available workers, wait
if workers.count() == 0:
return
with db.atomic("IMMEDIATE"):
jobs = Job.select().where(Job.state == "scheduled")
# no jobs to process, wait
if jobs.count() == 0:
await asyncio.sleep(3)
return
for i in range(min(workers.count(), jobs.count())):
job = jobs[i]
worker = workers[i]
job.state = "running"
job.started_time = datetime.now()
job.end_time = None
job.save()
worker.state = "busy"
worker.save()
jobs_in_memory_state[job.id] = {
"worker": worker.id,
"task": asyncio.ensure_future(run_job(worker, job)),
}
async def cleanup_old_package_check_if_lock_exists(worker, job, ignore_error=False):
await asyncio.sleep(1)
if not os.path.exists(
app.config.PACKAGE_CHECK_LOCK_PER_WORKER.format(worker_id=worker.id)
):
return
job.log += f"Lock for worker {worker.id} still exist ... trying to cleanup the old package check still running ...\n"
job.save()
await broadcast(
{
"action": "update_job",
"id": job.id,
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
task_logger.info(
f"Lock for worker {worker.id} still exist ... trying to cleanup old check process ..."
)
cwd = os.path.split(app.config.PACKAGE_CHECK_PATH)[0]
env = {
"IN_YUNORUNNER": "1",
"WORKER_ID": str(worker.id),
"ARCH": app.config.ARCH,
"DIST": app.config.DIST,
"YNH_BRANCH": app.config.YNH_BRANCH,
"YNHDEV_BACKEND": os.environ.get("YNHDEV_BACKEND", ""),
"PATH": os.environ["PATH"]
+ ":/usr/local/bin", # This is because lxc/lxd is in /usr/local/bin
}
cmd = f"script -qefc '{app.config.PACKAGE_CHECK_PATH} --force-stop 2>&1'"
try:
command = await asyncio.create_subprocess_shell(
cmd,
cwd=cwd,
env=env,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
while not command.stdout.at_eof():
data = await command.stdout.readline()
await asyncio.sleep(1)
except Exception:
traceback.print_exc()
task_logger.exception(f"ERROR in job '{job.name} #{job.id}'")
job.log += "\n"
job.log += "Exception:\n"
job.log += traceback.format_exc()
if not ignore_error:
job.state = "error"
return False
except (CancelledError, asyncio.exceptions.CancelledError):
command.terminate()
if not ignore_error:
job.log += "\nFailed to kill old check process?"
job.state = "canceled"
task_logger.info(f"Job '{job.name} #{job.id}' has been canceled")
return False
else:
job.log += "Cleaning done\n"
return True
finally:
job.save()
await broadcast(
{
"action": "update_job",
"id": job.id,
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
# Dirty hack to kill ~zombi processes adopted by init doing funky stuff -_-
os.system(
"for PID in $(ps -ef --forest | grep 'lxc exec' | grep ' 1 ' | awk '{print $2}'); do kill -9 $PID; done"
)
os.system(
"for PID in $(ps -ef --forest | grep 'incus exec' | grep ' 1 ' | awk '{print $2}'); do kill -9 $PID; done"
)
os.system(
"for PID in $(ps -ef --forest | grep 'script -qefc' | grep ' 1 ' | awk '{print $2}' ); do kill $PID; done"
)
async def run_job(worker, job):
async def update_github_commit_status(
app_url, job_url, commit_sha, state, level=None
):
token = app.config.GITHUB_COMMIT_STATUS_TOKEN
if token is None:
return
if state == "canceled":
state = "error"
if state == "done":
state = "success"
org = app_url.lower().strip("/").replace("https://", "").split("/")[1]
repo = app_url.lower().strip("/").replace("https://", "").split("/")[2]
ci_name = app.config.BASE_URL.lower().replace("https://", "").split(".")[0]
message = f"{ci_name}: "
if level:
message += f"level {level}"
else:
message += state
api_url = f"https://api.github.com/repos/{org}/{repo}/statuses/{commit_sha}"
async with aiohttp.ClientSession(
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
) as session:
async with session.post(
api_url,
data=my_json_dumps(
{
"state": state,
"target_url": job_url,
"description": f"{ci_name}: level {level}",
"context": ci_name,
}
),
) as resp:
respjson = await resp.json()
if "url" in respjson:
api_logger.info(
f"Updated commit status for {org}/{repo}/{commit_sha}"
)
else:
api_logger.error(
f"Failed to update commit status for {org}/{repo}/{commit_sha}"
)
api_logger.error(respjson)
await broadcast(
{
"action": "update_job",
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
await asyncio.sleep(5)
cleanup_ret = await cleanup_old_package_check_if_lock_exists(worker, job)
if cleanup_ret is False:
return
job_app = job.name.split()[0]
task_logger.info(f"Starting job '{job.name}' #{job.id}...")
cwd = os.path.split(app.config.PACKAGE_CHECK_PATH)[0]
env = {
"IN_YUNORUNNER": "1",
"WORKER_ID": str(worker.id),
"ARCH": app.config.ARCH,
"DIST": app.config.DIST,
"YNH_BRANCH": app.config.YNH_BRANCH,
"YNHDEV_BACKEND": os.environ.get("YNHDEV_BACKEND", ""),
"PATH": os.environ["PATH"]
+ ":/usr/local/bin", # This is because lxc/lxd is in /usr/local/bin
}
if hasattr(app.config, "STORAGE_PATH"):
env["YNH_PACKAGE_CHECK_STORAGE_DIR"] = app.config.STORAGE_PATH
begin = datetime.now()
begin_human = begin.strftime("%d/%m/%Y - %H:%M:%S")
msg = (
begin_human
+ f" - Starting test for {job.name} on arch {app.config.ARCH}, distrib {app.config.DIST}, with YunoHost {app.config.YNH_BRANCH}"
)
job.log += "=" * len(msg) + "\n"
job.log += msg + "\n"
job.log += "=" * len(msg) + "\n"
job.save()
await broadcast(
{
"action": "update_job",
"id": job.id,
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
result_json = app.config.PACKAGE_CHECK_RESULT_JSON_PER_WORKER.format(
worker_id=worker.id
)
full_log = app.config.PACKAGE_CHECK_FULL_LOG_PER_WORKER.format(worker_id=worker.id)
summary_png = app.config.PACKAGE_CHECK_SUMMARY_PNG_PER_WORKER.format(
worker_id=worker.id
)
if os.path.exists(result_json):
os.remove(result_json)
if os.path.exists(full_log):
os.remove(full_log)
if os.path.exists(summary_png):
os.remove(summary_png)
cmd = f"nice --adjustment=10 script -qefc '/bin/bash {app.config.PACKAGE_CHECK_PATH} {job.url_or_path} 2>&1'"
task_logger.info(f"Launching command: {cmd}")
try:
command = await asyncio.create_subprocess_shell(
cmd,
cwd=cwd,
env=env,
# default limit is not enough in some situations
limit=(2**16) ** 10,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
while not command.stdout.at_eof():
try:
data = await asyncio.wait_for(command.stdout.readline(), 60)
except asyncio.TimeoutError:
if (datetime.now() - begin).total_seconds() > app.config.TIMEOUT:
raise Exception(f"Job timed out ({app.config.TIMEOUT / 60} min.)")
else:
try:
job.log += data.decode("utf-8", "replace")
except UnicodeDecodeError as e:
job.log += "Uhoh ?! UnicodeDecodeError in yunorunner !?"
job.log += str(e)
job.save()
await broadcast(
{
"action": "update_job",
"id": job.id,
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
except (CancelledError, asyncio.exceptions.CancelledError):
command.terminate()
job.log += "\n"
job.state = "canceled"
task_logger.info(f"Job '{job.name} #{job.id}' has been canceled")
except Exception:
traceback.print_exc()
task_logger.exception(f"ERROR in job '{job.name} #{job.id}'")
job.log += "\n"
job.log += "Job error on:\n"
job.log += traceback.format_exc()
job.state = "error"
else:
task_logger.info(f"Finished job '{job.name}'")
if command.returncode == 124:
job.log += f"\nJob timed out ({app.config.TIMEOUT / 60} min.)\n"
job.state = "error"
else:
if command.returncode != 0 or not os.path.exists(result_json):
job.log += f"\nJob failed ? Return code is {command.returncode} / Or maybe the json result doesnt exist...\n"
job.state = "error"
else:
job.log += f"\nPackage check completed\n"
results = json.load(open(result_json))
level = results["level"]
job.state = "done" if level > 4 else "failure"
job.log += f"\nThe full log is available at {app.config.BASE_URL}/logs/{job.id}.log\n"
shutil.copy(full_log, yunorunner_dir + f"/results/logs/{job.id}.log")
shutil.copy(
result_json,
yunorunner_dir
+ f"/results/logs/{job_app}_{app.config.ARCH}_{app.config.YNH_BRANCH}_results.json",
)
shutil.copy(
summary_png, yunorunner_dir + f"/results/summary/{job.id}.png"
)
finally:
job.end_time = datetime.now()
job_url = app.config.BASE_URL + "/job/" + str(job.id)
now = datetime.now().strftime("%d/%m/%Y - %H:%M:%S")
msg = now + f" - Finished job for {job.name} ({job.state})"
job.log += "=" * len(msg) + "\n"
job.log += msg + "\n"
job.log += "=" * len(msg) + "\n"
job.save()
await broadcast(
{
"action": "update_job",
"id": job.id,
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
if "ci-apps.yunohost.org" in app.config.BASE_URL:
try:
async with aiohttp.ClientSession() as session:
async with session.get(APPS_LIST) as resp:
data = await resp.json()
data = data["apps"]
public_level = data.get(job_app, {}).get("level")
job_id_with_url = f"[#{job.id}]({job_url})"
if job.state == "error":
msg = f"Job {job_id_with_url} for {job_app} failed miserably :("
elif level == 0:
msg = f"App {job_app} failed all tests in job {job_id_with_url} :("
elif public_level is None:
msg = f"App {job_app} rises from level (unknown) to {level} in job {job_id_with_url} !"
elif level > public_level:
msg = f"App {job_app} rises from level {public_level} to {level} in job {job_id_with_url} !"
elif level < public_level:
msg = f"App {job_app} goes down from level {public_level} to {level} in job {job_id_with_url}"
elif level < 6:
msg = (
f"App {job_app} stays at level {level} in job {job_id_with_url}"
)
else:
# Dont notify anything, reduce CI flood on app chatroom if app is already level 6+
msg = ""
if msg:
cmd = f"{yunorunner_dir}/maintenance/chat_notify.sh '{msg}'"
try:
command = await asyncio.create_subprocess_shell(cmd)
while not command.stdout.at_eof():
await asyncio.sleep(1)
except:
pass
except:
traceback.print_exc()
task_logger.exception(f"ERROR in job '{job.name} #{job.id}'")
job.log += "\n"
job.log += "Exception:\n"
job.log += traceback.format_exc()
try:
if os.path.exists(result_json):
results = json.load(open(result_json))
level = results["level"]
commit = results["commit"]
await update_github_commit_status(
job.url_or_path, job_url, commit, job.state, level
)
except Exception as e:
task_logger.error(
f"Failed to push commit status for '{job.name}' #{job.id}... : {e}"
)
# if job.state != "canceled":
# await cleanup_old_package_check_if_lock_exists(worker, job, ignore_error=True)
# remove ourself from the state
del jobs_in_memory_state[job.id]
worker.state = "available"
worker.save()
await broadcast(
{
"action": "update_job",
"id": job.id,
"data": model_to_dict(job),
},
["jobs", f"job-{job.id}", f"app-jobs-{job.url_or_path}"],
)
async def broadcast(message, channels):
if not isinstance(channels, (list, tuple)):
channels = [channels]
for channel in channels:
ws_list = subscriptions[channel]
dead_ws = []
for ws in ws_list:
try:
await ws.send(my_json_dumps(message))
except (ConnectionClosed, WebsocketClosed):
dead_ws.append(ws)
except asyncio.exceptions.CancelledError as err:
api_logger.info(f"broadcast ws.send() received cancellederror {err}")
for to_remove in dead_ws:
try:
ws_list.remove(to_remove)
except ValueError:
pass
def subscribe(ws, channel):
subscriptions[channel].append(ws)
def unsubscribe_all(ws):
for channel in subscriptions:
if ws in subscriptions[channel]:
if ws in subscriptions[channel]:
print(f"\033[1;36mUnsubscribe ws {ws} from {channel}\033[0m")
subscriptions[channel].remove(ws)
def clean_websocket(function):
@wraps(function)
async def _wrap(request, websocket, *args, **kwargs):
try:
to_return = await function(request, websocket, *args, **kwargs)
return to_return
except Exception:
print(function.__name__)
unsubscribe_all(websocket)
raise
return _wrap
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
chunk = []
a = 0
for i in l:
if a < n:
a += 1
chunk.append(i)
else:
yield chunk
chunk = []
a = 0
yield chunk
@app.websocket("/index-ws")
@clean_websocket
async def ws_index(request, websocket):
subscribe(websocket, "jobs")
# avoid fetch "log" field from the db to reduce memory usage
selected_fields = (
Job.id,
Job.name,
Job.url_or_path,
Job.state,
Job.created_time,
Job.started_time,
Job.end_time,
)
JobAlias = Job.alias()
subquery = (
JobAlias.select(*selected_fields)
.where(JobAlias.state << ("done", "failure", "canceled", "error"))
.group_by(JobAlias.url_or_path)
.select(fn.Max(JobAlias.id).alias("max_id"))
)
latest_done_jobs = (
Job.select(*selected_fields)
.join(subquery, on=(Job.id == subquery.c.max_id))
.order_by(-Job.id)
.limit(500)
)
subquery = (
JobAlias.select(*selected_fields)
.where(JobAlias.state == "scheduled")
.group_by(JobAlias.url_or_path)
.select(fn.Min(JobAlias.id).alias("min_id"))
)
next_scheduled_jobs = (
Job.select(*selected_fields)
.join(subquery, on=(Job.id == subquery.c.min_id))
.order_by(-Job.id)
)
# chunks initial data by batch of 30 to avoid killing firefox
data = chunks(
itertools.chain(
map(model_to_dict, next_scheduled_jobs.iterator()),
map(model_to_dict, Job.select().where(Job.state == "running").iterator()),
map(model_to_dict, latest_done_jobs.iterator()),