forked from CCExtractor/sample-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controllers.py
executable file
·1431 lines (1222 loc) · 56 KB
/
controllers.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
"""maintains all functionality related running virtual machines, starting and tracking tests."""
import datetime
import hashlib
import json
import os
import shutil
import sys
from multiprocessing import Process
from typing import Any
import requests
from flask import (Blueprint, abort, flash, g, jsonify, redirect, request,
url_for)
from git import GitCommandError, InvalidGitRepositoryError, Repo
from github import ApiError, GitHub
from lxml import etree
from lxml.etree import Element
from markdown2 import markdown
from pymysql.err import IntegrityError
from sqlalchemy import and_, func, or_
from sqlalchemy.sql import label
from sqlalchemy.sql.functions import count
from werkzeug.utils import secure_filename
from decorators import get_menu_entries, template_renderer
from mailer import Mailer
from mod_auth.controllers import check_access_rights, login_required
from mod_auth.models import Role
from mod_ci.forms import AddUsersToBlacklist, DeleteUserForm
from mod_ci.models import BlockedUsers, Kvm, MaintenanceMode, PrCommentInfo
from mod_customized.models import CustomizedTest
from mod_deploy.controllers import is_valid_signature, request_from_github
from mod_home.models import CCExtractorVersion, GeneralData
from mod_regression.models import (Category, RegressionTest,
RegressionTestOutput,
RegressionTestOutputFiles,
regressionTestLinkTable)
from mod_sample.models import Issue
from mod_test.models import (Fork, Test, TestPlatform, TestProgress,
TestResult, TestResultFile, TestStatus, TestType)
if sys.platform.startswith("linux"):
import libvirt
mod_ci = Blueprint('ci', __name__)
class Status:
"""Define different states for the tests."""
PENDING = "pending"
SUCCESS = "success"
ERROR = "error"
FAILURE = "failure"
@mod_ci.before_app_request
def before_app_request() -> None:
"""Organize menu content such as Platform management before request."""
config_entries = get_menu_entries(
g.user, 'Platform mgmt', 'cog', [], '', [
{'title': 'Maintenance', 'icon': 'wrench',
'route': 'ci.show_maintenance', 'access': [Role.admin]}, # type: ignore
{'title': 'Blocked Users', 'icon': 'ban',
'route': 'ci.blocked_users', 'access': [Role.admin]} # type: ignore
]
)
if 'config' in g.menu_entries and 'entries' in config_entries:
g.menu_entries['config']['entries'] = config_entries['entries'] + g.menu_entries['config']['entries']
else:
g.menu_entries['config'] = config_entries
def start_platforms(db, repository, delay=None, platform=None) -> None:
"""
Start new test on both platforms in parallel.
We use multiprocessing module which bypasses Python GIL to make use of multiple cores of the processor.
"""
from run import app, config, log
with app.app_context():
from flask import current_app
if platform is None or platform == TestPlatform.linux:
linux_kvm_name = config.get('KVM_LINUX_NAME', '')
log.info('Define process to run Linux VM')
linux_process = Process(target=kvm_processor, args=(current_app._get_current_object(), db, linux_kvm_name,
TestPlatform.linux, repository, delay,))
linux_process.start()
log.info('Linux VM process kicked off')
if platform is None or platform == TestPlatform.windows:
win_kvm_name = config.get('KVM_WINDOWS_NAME', '')
log.info('Define process to run Windows VM')
windows_process = Process(target=kvm_processor, args=(current_app._get_current_object(), db, win_kvm_name,
TestPlatform.windows, repository, delay,))
windows_process.start()
log.info('Windows VM process kicked off')
def kvm_processor(app, db, kvm_name, platform, repository, delay) -> None:
"""
Check whether there is no already running same kvm.
Checks whether machine is in maintenance mode or not
Launch kvm if not used by any other test
Creates testing xml files to test the change in main repo.
Creates clone with separate branch and merge pr into it.
:param app: The Flask app
:type app: Flask
:param db: database connection
:type db: sqlalchemy.orm.scoped_session
:param kvm_name: name for the kvm
:type kvm_name: str
:param platform: operating system
:type platform: str
:param repository: repository to run tests on
:type repository: str
:param delay: time delay after which to start kvm processor
:type delay: int
"""
from run import config, get_github_config, log
github_config = get_github_config(config)
log.info(f"[{platform}] Running kvm_processor")
if kvm_name == "":
log.critical(f'[{platform}] KVM name is empty!')
return
if delay is not None:
import time
log.debug(f'[{platform}] Sleeping for {delay} seconds')
time.sleep(delay)
maintenance_mode = MaintenanceMode.query.filter(MaintenanceMode.platform == platform).first()
if maintenance_mode is not None and maintenance_mode.disabled:
log.debug(f'[{platform}] In maintenance mode! Waiting...')
return
conn = libvirt.open("qemu:///system")
if conn is None:
log.critical(f"[{platform}] Connection to libvirt failed!")
return
try:
vm = conn.lookupByName(kvm_name)
except libvirt.libvirtError:
log.critical(f"[{platform}] No VM named {kvm_name} found!")
return
vm_info = vm.info()
if vm_info[0] != libvirt.VIR_DOMAIN_SHUTOFF:
# Running, check expiry and compare to runtime
status = Kvm.query.filter(Kvm.name == kvm_name).first()
max_runtime = config.get("KVM_MAX_RUNTIME", 120)
if status is not None:
if datetime.datetime.now() - status.timestamp >= datetime.timedelta(minutes=max_runtime):
test_progress = TestProgress(status.test.id, TestStatus.canceled, 'Runtime exceeded')
db.add(test_progress)
db.delete(status)
db.commit()
if vm.destroy() == -1:
log.critical(f"[{platform}] Failed to shut down {kvm_name}")
return
else:
log.info(f"[{platform}] Current job not expired yet.")
return
else:
log.warn(f"[{platform}] No task, but VM is running! Hard reset necessary")
if vm.destroy() == -1:
log.critical(f"[{platform}] Failed to shut down {kvm_name}")
return
# Check if there's no KVM status left
status = Kvm.query.filter(Kvm.name == kvm_name).first()
if status is not None:
log.warn(f"[{platform}] KVM is powered off, but test {status.test.id} still present, deleting entry")
db.delete(status)
db.commit()
# Get oldest test for this platform
finished_tests = db.query(TestProgress.test_id).filter(
TestProgress.status.in_([TestStatus.canceled, TestStatus.completed])
).subquery()
fork_location = f"%/{github_config['repository_owner']}/{github_config['repository']}.git"
fork = Fork.query.filter(Fork.github.like(fork_location)).first()
test = Test.query.filter(
Test.id.notin_(finished_tests), Test.platform == platform, Test.fork_id == fork.id
).order_by(Test.id.asc()).first()
if test is None:
test = Test.query.filter(Test.id.notin_(finished_tests), Test.platform == platform).order_by(
Test.id.asc()).first()
if test is None:
log.info(f'[{platform}] No more tests to run, returning')
return
if test.test_type == TestType.pull_request and test.pr_nr == 0:
log.warn(f'[{platform}] Test {test.id} is invalid, deleting')
db.delete(test)
db.commit()
return
# Reset to snapshot
if vm.hasCurrentSnapshot() != 1:
log.critical(f"[{platform}] VM {kvm_name} has no current snapshot set!")
return
snapshot = vm.snapshotCurrent()
if vm.revertToSnapshot(snapshot) == -1:
log.critical(f"[{platform}] Failed to revert to {snapshot.getName()} for {kvm_name}")
return
log.info(f"[{platform}] Reverted to {snapshot.getName()} for {kvm_name}")
log.debug(f'[{platform}] Starting test {test.id}')
status = Kvm(kvm_name, test.id)
# Prepare data
# 0) Write url to file
with app.app_context():
full_url = url_for('ci.progress_reporter', test_id=test.id, token=test.token, _external=True, _scheme="https")
file_path = os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'vm_data', kvm_name, 'reportURL')
with open(file_path, 'w') as f:
f.write(full_url)
# 1) Generate test files
base_folder = os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'vm_data', kvm_name, 'ci-tests')
categories = Category.query.order_by(Category.id.desc()).all()
commit_name = 'fetch_commit_' + platform.value
commit_hash = GeneralData.query.filter(GeneralData.key == commit_name).first().value
last_commit = Test.query.filter(and_(Test.commit == commit_hash, Test.platform == platform)).first()
log.debug(f"[{platform}] We will compare against the results of test {last_commit.id}")
regression_ids = test.get_customized_regressiontests()
# Init collection file
multi_test = etree.Element('multitest')
for category in categories:
# Skip categories without tests
if len(category.regression_tests) == 0:
continue
# Create XML file for test
file_name = f'{category.name}.xml'
single_test = etree.Element('tests')
should_write_xml = False
for regression_test in category.regression_tests:
if regression_test.id not in regression_ids:
log.debug(f'Skipping RT #{regression_test.id} ({category.name}) as not in scope')
continue
should_write_xml = True
entry = etree.SubElement(single_test, 'entry', id=str(regression_test.id))
command = etree.SubElement(entry, 'command')
command.text = regression_test.command
input_node = etree.SubElement(entry, 'input', type=regression_test.input_type.value)
# Need a path that is relative to the folder we provide inside the CI environment.
input_node.text = regression_test.sample.filename
output_node = etree.SubElement(entry, 'output')
output_node.text = regression_test.output_type.value
compare = etree.SubElement(entry, 'compare')
last_files = TestResultFile.query.filter(and_(
TestResultFile.test_id == last_commit.id,
TestResultFile.regression_test_id == regression_test.id
)).subquery()
for output_file in regression_test.output_files:
ignore_file = str(output_file.ignore).lower()
file_node = etree.SubElement(compare, 'file', ignore=ignore_file, id=str(output_file.id))
last_commit_files = db.query(last_files.c.got).filter(and_(
last_files.c.regression_test_output_id == output_file.id,
last_files.c.got.isnot(None)
)).first()
correct = etree.SubElement(file_node, 'correct')
# Need a path that is relative to the folder we provide inside the CI environment.
if last_commit_files is None:
log.debug(f"Selecting original file for RT #{regression_test.id} ({category.name})")
correct.text = output_file.filename_correct
else:
correct.text = output_file.create_correct_filename(last_commit_files[0])
expected = etree.SubElement(file_node, 'expected')
expected.text = output_file.filename_expected(regression_test.sample.sha)
if not should_write_xml:
continue
save_xml_to_file(single_test, base_folder, file_name)
# Append to collection file
test_file = etree.SubElement(multi_test, 'testfile')
location = etree.SubElement(test_file, 'location')
location.text = file_name
save_xml_to_file(multi_test, base_folder, 'TestAll.xml')
# 2) Create git repo clone and merge PR into it (if necessary)
try:
repo = Repo(os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'vm_data', kvm_name, 'unsafe-ccextractor'))
except InvalidGitRepositoryError:
log.critical(f"[{platform}] Could not open CCExtractor's repository copy!")
return
# Return to master
repo.heads.master.checkout(True)
# Update repository from upstream
try:
github_url = test.fork.github
if is_main_repo(github_url):
origin = repo.remote('origin')
else:
fork_id = test.fork.id
remote = f'fork_{fork_id}'
if remote in [remote.name for remote in repo.remotes]:
origin = repo.remote(remote)
else:
origin = repo.create_remote(remote, url=github_url)
except ValueError:
log.critical(f"[{platform}] Origin remote doesn't exist!")
return
fetch_info = origin.fetch()
if len(fetch_info) == 0:
log.info(f'[{platform}] Fetch from remote returned no new data...')
# Checkout to Remote Master
repo.git.checkout(origin.refs.master)
# Pull code (finally)
pull_info = origin.pull('master')
if len(pull_info) == 0:
log.info(f"[{platform}] Pull from remote returned no new data...")
elif pull_info[0].flags > 128:
log.critical(f"[{platform}] Did not pull any information from remote: {pull_info[0].flags}!")
return
ci_branch = 'CI_Branch'
# Delete the test branch if it exists, and recreate
try:
repo.delete_head(ci_branch, force=True)
except GitCommandError:
log.info(f"[{platform}] Could not delete CI_Branch head")
# Remove possible left rebase-apply directory
try:
shutil.rmtree(os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'unsafe-ccextractor', '.git', 'rebase-apply'))
except OSError:
log.info(f"[{platform}] Could not delete rebase-apply")
# If PR, merge, otherwise reset to commit
if test.test_type == TestType.pull_request:
# Fetch PR (stored under origin/pull/<id>/head)
pull_info = origin.fetch(f'pull/{test.pr_nr}/head:{ci_branch}')
if len(pull_info) == 0:
log.warn(f"[{platform}] Did not pull any information from remote PR!")
elif pull_info[0].flags > 128:
log.critical(f"[{platform}] Did not pull any information from remote PR: {pull_info[0].flags}!")
return
try:
test_branch = repo.heads[ci_branch]
except IndexError:
log.critical(f'{ci_branch} does not exist')
return
test_branch.checkout(True)
try:
pull = repository.pulls(f'{test.pr_nr}').get()
except ApiError as a:
log.error(f'Got an exception while fetching the PR payload! Message: {a.message}')
return
if pull['mergeable'] is False:
progress = TestProgress(test.id, TestStatus.canceled, "Commit could not be merged", datetime.datetime.now())
db.add(progress)
db.commit()
try:
with app.app_context():
repository.statuses(test.commit).post(
state=Status.FAILURE,
description="Tests canceled due to merge conflict",
context=f"CI - {test.platform.value}",
target_url=url_for('test.by_id', test_id=test.id, _external=True)
)
except ApiError as a:
log.error(f'Got an exception while posting to GitHub! Message: {a.message}')
return
# Merge on master if no conflict
repo.git.merge('master')
else:
test_branch = repo.create_head(ci_branch, origin.refs.master)
test_branch.checkout(True)
try:
repo.head.reset(test.commit, working_tree=True)
except GitCommandError:
log.warn(f"[{platform}] Commit {test.commit} for test {test.id} does not exist!")
return
# Power on machine
try:
vm.create()
db.add(status)
db.commit()
except libvirt.libvirtError as e:
log.critical(f"[{platform}] Failed to launch VM {kvm_name}")
log.critical(f"Information about failure: code: {e.get_error_code()}, domain: {e.get_error_domain()}, "
f"level: {e.get_error_level()}, message: {e.get_error_message()}")
except IntegrityError:
log.warn(f"[{platform}] Duplicate entry for {test.id}")
# Close connection to libvirt
conn.close()
def save_xml_to_file(xml_node, folder_name, file_name) -> None:
"""
Save the given XML node to a file in a certain folder.
:param xml_node: The XML content element to write to the file.
:type xml_node: Element
:param folder_name: The folder name.
:type folder_name: str
:param file_name: The name of the file
:type file_name: str
:return: Nothing
:rtype: None
"""
xml_node.getroottree().write(
os.path.join(folder_name, file_name), encoding='utf-8', xml_declaration=True, pretty_print=True
)
def queue_test(db, gh_commit, commit, test_type, branch="master", pr_nr=0) -> None:
"""
Store test details into Test model for each platform, and post the status to GitHub.
:param db: Database connection.
:type db: sqlalchemy.orm.scoped_session
:param gh_commit: The GitHub API call for the commit. Can be None
:type gh_commit: Any
:param commit: The commit hash.
:type commit: str
:param test_type: The type of test
:type test_type: TestType
:param branch: Branch name
:type branch: str
:param pr_nr: Pull Request number, if applicable.
:type pr_nr: int
:return: Nothing
:rtype: None
"""
from run import log
fork_url = f"%/{g.github['repository_owner']}/{g.github['repository']}.git"
fork = Fork.query.filter(Fork.github.like(fork_url)).first()
if test_type == TestType.pull_request:
log.debug('pull request test type detected')
branch = "pull_request"
linux_test = Test(TestPlatform.linux, test_type, fork.id, branch, commit, pr_nr)
db.add(linux_test)
windows_test = Test(TestPlatform.windows, test_type, fork.id, branch, commit, pr_nr)
db.add(windows_test)
db.commit()
add_customized_regression_tests(linux_test.id)
add_customized_regression_tests(windows_test.id)
if gh_commit is not None:
status_entries = {
linux_test.platform.value: linux_test.id,
windows_test.platform.value: windows_test.id
}
for platform_name, test_id in status_entries.items():
try:
gh_commit.post(
state=Status.PENDING,
description="Tests queued",
context=f"CI - {platform_name}",
target_url=url_for('test.by_id', test_id=test_id, _external=True)
)
except ApiError as a:
log.critical(f'Could not post to GitHub! Response: {a.response}')
log.debug("Created tests, waiting for cron...")
def inform_mailing_list(mailer, id, title, author, body) -> None:
"""
Send mail to subscribed users when a issue is opened via the Webhook.
:param mailer: The mailer instance
:type mailer: Mailer
:param id: ID of the Issue Opened
:type id: int
:param title: Title of the Created Issue
:type title: str
:param author: The Authors Username of the Issue
:type author: str
:param body: The Content of the Issue
:type body: str
"""
from run import get_github_issue_link
subject = f"GitHub Issue #{id}"
url = get_github_issue_link(id)
if not mailer.send_simple_message({
"to": "ccextractor-dev@googlegroups.com",
"subject": subject,
"html": get_html_issue_body(title=title, author=author, body=body, issue_number=id, url=url)
}):
g.log.error('failed to send issue to mailing list')
def get_html_issue_body(title, author, body, issue_number, url) -> Any:
"""
Curate a HTML formatted body for the issue mail.
:param title: title of the issue
:type title: str
:param author: author of the issue
:type author: str
:param body: content of the issue
:type body: str
:param issue_number: issue number
:type issue_number: int
:param url: link to the issue
:type url: str
:return: email body in html format
:rtype: str
"""
from run import app
html_issue_body = markdown(body, extras=["target-blank-links", "task_list", "code-friendly"])
template = app.jinja_env.get_or_select_template("email/new_issue.txt")
html_email_body = template.render(title=title, author=author, body=html_issue_body, url=url)
return html_email_body
@mod_ci.route('/start-ci', methods=['GET', 'POST'])
@request_from_github()
def start_ci():
"""
Perform various actions when the GitHub webhook is triggered.
Reaction to the next events need to be processed
(after verification):
- Ping (for fun)
- Push
- Pull Request
- Issues
"""
if request.method != 'POST':
return 'OK'
else:
abort_code = 418
event = request.headers.get('X-GitHub-Event')
if event == "ping":
g.log.debug('server ping successful')
return json.dumps({'msg': 'Hi!'})
x_hub_signature = request.headers.get('X-Hub-Signature')
if not is_valid_signature(x_hub_signature, request.data, g.github['ci_key']):
g.log.warning(f'CI signature failed: {x_hub_signature}')
abort(abort_code)
payload = request.get_json()
if payload is None:
g.log.warning(f'CI payload is empty')
abort(abort_code)
gh = GitHub(access_token=g.github['bot_token'])
repository = gh.repos(g.github['repository_owner'])(g.github['repository'])
if event == "push":
g.log.debug('push event detected')
if 'after' in payload:
commit_hash = payload['after']
github_status = repository.statuses(commit_hash)
# Update the db to the new last commit
ref = repository.git().refs('heads/master').get()
last_commit = GeneralData.query.filter(GeneralData.key == 'last_commit').first()
for platform in TestPlatform.values():
commit_name = 'fetch_commit_' + platform
fetch_commit = GeneralData.query.filter(GeneralData.key == commit_name).first()
if fetch_commit is None:
prev_commit = GeneralData(commit_name, last_commit.value)
g.db.add(prev_commit)
last_commit.value = ref['object']['sha']
g.db.commit()
queue_test(g.db, github_status, commit_hash, TestType.commit)
else:
g.log.warning('Unknown push type! Dumping payload for analysis')
g.log.warning(payload)
elif event == "pull_request":
g.log.debug('Pull Request event detected')
# If it's a valid PR, run the tests
pr_nr = payload['pull_request']['number']
if payload['action'] in ['opened', 'synchronize', 'reopened']:
try:
commit_hash = payload['pull_request']['head']['sha']
github_status = repository.statuses(commit_hash)
except KeyError:
g.log.error("Didn't find a SHA value for a newly opened PR!")
g.log.error(payload)
return 'ERROR'
# Check if user blacklisted
user_id = payload['pull_request']['user']['id']
if BlockedUsers.query.filter(BlockedUsers.user_id == user_id).first() is not None:
g.log.warning("User Blacklisted")
github_status.post(
state=Status.ERROR,
description="CI start aborted. You may be blocked from accessing this functionality",
target_url=url_for('home.index', _external=True)
)
return 'ERROR'
queue_test(g.db, github_status, commit_hash, TestType.pull_request, pr_nr=pr_nr)
elif payload['action'] == 'closed':
g.log.debug('PR was closed, no after hash available')
# Cancel running queue
tests = Test.query.filter(Test.pr_nr == pr_nr).all()
for test in tests:
# Add cancelled status only if the test hasn't started yet
if len(test.progress) > 0:
continue
progress = TestProgress(test.id, TestStatus.canceled, "PR closed", datetime.datetime.now())
g.db.add(progress)
repository.statuses(test.commit).post(
state=Status.FAILURE,
description="Tests canceled",
context=f"CI - {test.platform.value}",
target_url=url_for('test.by_id', test_id=test.id, _external=True)
)
elif event == "issues":
g.log.debug('issues event detected')
issue_data = payload['issue']
issue_action = payload['action']
issue = Issue.query.filter(Issue.issue_id == issue_data['number']).first()
issue_title = issue_data['title']
issue_id = issue_data['number']
issue_author = issue_data['user']['login']
issue_body = issue_data['body']
if issue_action == "opened":
inform_mailing_list(g.mailer, issue_id, issue_title, issue_author, issue_body)
if issue is not None:
issue.title = issue_title
issue.status = issue_data['state']
g.db.commit()
elif event == "release":
g.log.debug("Release webhook triggered")
release_data = payload['release']
action = payload['action']
release_version = release_data['tag_name']
if release_version[0] == 'v':
release_version = release_version[1:]
if action == "prereleased":
g.log.debug("Ignoring event meant for pre-release")
elif action in ["deleted", "unpublished"]:
g.log.debug("Received delete/unpublished action")
CCExtractorVersion.query.filter_by(version=release_version).delete()
g.db.commit()
g.log.info(f"Successfully deleted release {release_version} on {action} action")
elif action in ["edited", "published"]:
g.log.debug(f"Latest release version is {release_version}")
release_commit = GeneralData.query.filter(GeneralData.key == 'last_commit').first().value
release_date = release_data['published_at']
if action == "edited":
release = CCExtractorVersion.query.filter(CCExtractorVersion.version == release_version).one()
release.released = datetime.datetime.strptime(release_date, '%Y-%m-%dT%H:%M:%SZ').date()
release.commit = release_commit
else:
release = CCExtractorVersion(release_version, release_date, release_commit)
g.db.add(release)
g.db.commit()
g.log.info(f"Successfully updated release version with webhook action '{action}'")
# adding test corresponding to last commit to the baseline regression results
# this is not altered when a release is deleted or unpublished since it's based on commit
test = Test.query.filter(and_(Test.commit == release_commit,
Test.platform == TestPlatform.linux)).first()
test_result_file = g.db.query(TestResultFile).filter(TestResultFile.test_id == test.id).subquery()
test_result = g.db.query(TestResult).filter(TestResult.test_id == test.id).subquery()
g.db.query(RegressionTestOutput.correct).filter(
and_(RegressionTestOutput.regression_id == test_result_file.c.regression_test_id,
test_result_file.c.got is not None)).values(test_result_file.c.got)
g.db.query(RegressionTest.expected_rc).filter(
RegressionTest.id == test_result.c.regression_test_id
).values(test_result.c.expected_rc)
g.db.commit()
g.log.info("Successfully added tests for latest release!")
else:
g.log.warning(f"Unsupported release action: {action}")
else:
g.log.warning(f'CI unrecognized event: {event}')
return json.dumps({'msg': 'EOL'})
def update_build_badge(status, test) -> None:
"""
Build status badge for current test to be displayed on sample-platform.
:param status: current testing status
:type status: str
:param test: current commit that is tested
:type test: Test
:return: null
:rtype: null
"""
if test.test_type == TestType.commit and is_main_repo(test.fork.github):
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
original_location = os.path.join(parent_dir, 'static', 'svg', f'{status.upper()}-{test.platform.value}.svg')
build_status_location = os.path.join(parent_dir, 'static', 'img', 'status', f'build-{test.platform.value}.svg')
shutil.copyfile(original_location, build_status_location)
g.log.info('Build badge updated successfully!')
@mod_ci.route('/progress-reporter/<test_id>/<token>', methods=['POST'])
def progress_reporter(test_id, token):
"""
Handle the progress of a certain test after validating the token. If necessary, update the status on GitHub.
:param test_id: The id of the test to update.
:type test_id: int
:param token: The token to check the validity of the request.
:type token: str
:return: Nothing.
:rtype: None
"""
from run import config, log
test = Test.query.filter(Test.id == test_id).first()
if test is not None and test.token == token:
repo_folder = config.get('SAMPLE_REPOSITORY', '')
if 'type' in request.form:
if request.form['type'] == 'progress':
log.info('[PROGRESS_REPORTER] Progress reported')
if not progress_type_request(log, test, test_id, request):
return "FAIL"
elif request.form['type'] == 'equality':
log.info('[PROGRESS_REPORTER] Equality reported')
equality_type_request(log, test_id, test, request)
elif request.form['type'] == 'logupload':
log.info('[PROGRESS_REPORTER] Log upload')
if not upload_log_type_request(log, test_id, repo_folder, test, request):
return "EMPTY"
elif request.form['type'] == 'upload':
log.info('[PROGRESS_REPORTER] File upload')
if not upload_type_request(log, test_id, repo_folder, test, request):
return "EMPTY"
elif request.form['type'] == 'finish':
log.info('[PROGRESS_REPORTER] Test finished')
finish_type_request(log, test_id, test, request)
else:
return "FAIL"
return "OK"
return "FAIL"
def progress_type_request(log, test, test_id, request) -> bool:
"""
Handle progress updates for progress reporter.
:param log: logger
:type log: Logger
:param test: concerned test
:type test: Test
:param test_id: The id of the test to update.
:type test_id: int
:param request: Request parameters
:type request: Request
"""
status = TestStatus.from_string(request.form['status'])
current_status = TestStatus.progress_step(status)
message = request.form['message']
if len(test.progress) != 0:
last_status = TestStatus.progress_step(test.progress[-1].status)
if last_status in [TestStatus.completed, TestStatus.canceled]:
return False
if last_status > current_status:
status = TestStatus.canceled # type: ignore
message = "Duplicate Entries"
if last_status < current_status:
# get KVM start time for finding KVM preparation time
kvm_entry = Kvm.query.filter(Kvm.test_id == test_id).first()
if status == TestStatus.building:
log.info('test preparation finished')
prep_finish_time = datetime.datetime.now()
# save preparation finish time
kvm_entry.timestamp_prep_finished = prep_finish_time
g.db.commit()
# set time taken in seconds to do preparation
time_diff = (prep_finish_time - kvm_entry.timestamp).total_seconds()
set_avg_time(test.platform, "prep", time_diff)
elif status == TestStatus.testing:
log.info('test build procedure finished')
build_finish_time = datetime.datetime.now()
# save build finish time
kvm_entry.timestamp_build_finished = build_finish_time
g.db.commit()
# set time taken in seconds to do preparation
time_diff = (build_finish_time - kvm_entry.timestamp_prep_finished).total_seconds()
set_avg_time(test.platform, "build", time_diff)
progress = TestProgress(test.id, status, message)
g.db.add(progress)
g.db.commit()
gh = GitHub(access_token=g.github['bot_token'])
repository = gh.repos(g.github['repository_owner'])(g.github['repository'])
# Store the test commit for testing in case of commit
if status == TestStatus.completed and is_main_repo(test.fork.github):
commit_name = 'fetch_commit_' + test.platform.value
commit = GeneralData.query.filter(GeneralData.key == commit_name).first()
fetch_commit = Test.query.filter(
and_(Test.commit == commit.value, Test.platform == test.platform)
).first()
if test.test_type == TestType.commit and test.id > fetch_commit.id:
commit.value = test.commit
g.db.commit()
# If status is complete, remove the Kvm entry
if status in [TestStatus.completed, TestStatus.canceled]:
log.debug(f"Test {test_id} has been {status}")
var_average = 'average_time_' + test.platform.value
current_average = GeneralData.query.filter(GeneralData.key == var_average).first()
average_time = 0
total_time = 0
if current_average is None:
platform_tests = g.db.query(Test.id).filter(Test.platform == test.platform).subquery()
finished_tests = g.db.query(TestProgress.test_id).filter(
and_(
TestProgress.status.in_([TestStatus.canceled, TestStatus.completed]),
TestProgress.test_id.in_(platform_tests)
)
).subquery()
in_progress_statuses = [TestStatus.preparation, TestStatus.completed, TestStatus.canceled]
finished_tests_progress = g.db.query(TestProgress).filter(
and_(
TestProgress.test_id.in_(finished_tests),
TestProgress.status.in_(in_progress_statuses)
)
).subquery()
times = g.db.query(
finished_tests_progress.c.test_id,
label('time', func.group_concat(finished_tests_progress.c.timestamp))
).group_by(finished_tests_progress.c.test_id).all()
for p in times:
parts = p.time.split(',')
start = datetime.datetime.strptime(parts[0], '%Y-%m-%d %H:%M:%S')
end = datetime.datetime.strptime(parts[-1], '%Y-%m-%d %H:%M:%S')
total_time += int((end - start).total_seconds())
if len(times) != 0:
average_time = total_time // len(times)
new_avg = GeneralData(var_average, average_time)
log.info(f'new average time {str(average_time)} set successfully')
g.db.add(new_avg)
g.db.commit()
else:
all_results = TestResult.query.count()
regression_test_count = RegressionTest.query.count()
number_test = all_results / regression_test_count
updated_average = float(current_average.value) * (number_test - 1)
pr = test.progress_data()
end_time = pr['end']
start_time = pr['start']
if end_time.tzinfo is not None:
end_time = end_time.replace(tzinfo=None)
if start_time.tzinfo is not None:
start_time = start_time.replace(tzinfo=None)
last_running_test = end_time - start_time
updated_average = updated_average + last_running_test.total_seconds()
current_average.value = updated_average // number_test
g.db.commit()
log.info(f'average time updated to {str(current_average.value)}')
kvm = Kvm.query.filter(Kvm.test_id == test_id).first()
if kvm is not None:
log.debug("Removing KVM entry")
g.db.delete(kvm)
g.db.commit()
# Post status update
state = Status.PENDING
target_url = url_for('test.by_id', test_id=test.id, _external=True)
context = f"CI - {test.platform.value}"
if status == TestStatus.canceled:
state = Status.ERROR
message = 'Tests aborted due to an error; please check'
elif status == TestStatus.completed:
# Determine if success or failure
# It fails if any of these happen:
# - A crash (unexpected exit code)
# - A not None value on the "got" of a TestResultFile (
# meaning the hashes do not match)
crashes = g.db.query(count(TestResult.exit_code)).filter(
and_(
TestResult.test_id == test.id,
TestResult.exit_code != TestResult.expected_rc
)).scalar()
results_zero_rc = g.db.query(RegressionTest.id).filter(
RegressionTest.expected_rc == 0
).subquery()
results = g.db.query(count(TestResultFile.got)).filter(
and_(
TestResultFile.test_id == test.id,
TestResultFile.regression_test_id.in_(results_zero_rc),
TestResultFile.got.isnot(None)
)
).scalar()
log.debug(f'Test {test.id} completed: {crashes} crashes, {results} results')
if crashes > 0 or results > 0:
state = Status.FAILURE
message = 'Not all tests completed successfully, please check'
else:
state = Status.SUCCESS
message = 'Tests completed'
if test.test_type == TestType.pull_request:
comment_pr(test.id, state, test.pr_nr, test.platform.name)
update_build_badge(state, test)
else:
message = progress.message
gh_commit = repository.statuses(test.commit)
try:
gh_commit.post(state=state, description=message, context=context, target_url=target_url)
except ApiError as a:
log.error(f'Got an exception while posting to GitHub! Message: {a.message}')
if status in [TestStatus.completed, TestStatus.canceled]:
# Start next test if necessary, on the same platform
start_platforms(g.db, repository, 60, test.platform)
return True
def equality_type_request(log, test_id, test, request):
"""
Handle equality request type for progress reporter.
:param log: logger
:type log: Logger
:param test_id: The id of the test to update.
:type test_id: int
:param test: concerned test
:type test: Test
:param request: Request parameters
:type request: Request
"""
log.debug(f'Equality for {test_id}/{request.form["test_id"]}/{request.form["test_file_id"]}')
rto = RegressionTestOutput.query.filter(RegressionTestOutput.id == request.form['test_file_id']).first()
if rto is None:
# Equality posted on a file that's ignored presumably
log.info(f'No rto for {test_id}: {request.form["test_id"]}')
else: