/
controllers.py
executable file
·1830 lines (1547 loc) · 73.1 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 re
import shutil
import time
import zipfile
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict
import googleapiclient.discovery
import requests
from flask import (Blueprint, abort, flash, g, jsonify, redirect, request,
url_for)
from github import Commit, Github, GithubException, GithubObject, Repository
from google.oauth2 import service_account
from lxml import etree
from markdown2 import markdown
from pymysql.err import IntegrityError
from sqlalchemy import and_, func
from sqlalchemy.sql import label
from sqlalchemy.sql.functions import count
from werkzeug.utils import secure_filename
from database import DeclEnum, create_session
from decorators import get_menu_entries, template_renderer
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, CategoryTestInfo, GcpInstance,
MaintenanceMode, PrCommentInfo, Status)
from mod_customized.models import CustomizedTest
from mod_home.models import CCExtractorVersion, GeneralData
from mod_regression.models import (Category, RegressionTest,
RegressionTestOutput)
from mod_sample.models import Issue
from mod_test.controllers import get_test_results
from mod_test.models import (Fork, Test, TestPlatform, TestProgress,
TestResult, TestResultFile, TestStatus, TestType)
from utility import is_valid_signature, request_from_github
mod_ci = Blueprint('ci', __name__)
class Workflow_builds(DeclEnum):
"""Define GitHub Action workflow build names."""
LINUX = "Build CCExtractor on Linux"
WINDOWS = "Build CCExtractor on Windows"
class Artifact_names(DeclEnum):
"""Define CCExtractor GitHub Artifacts names."""
linux = "CCExtractor Linux build"
windows = "CCExtractor Windows Release build"
@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(repository, delay=None, platform=None) -> None:
"""
Start new test on both platforms.
:param repository: repository to run tests on
:type repository: str
:param delay: time delay after which to start gcp_instance function
:type delay: int
:param platform: operating system
:type platform: str
"""
from run import app, config, log
vm_max_runtime = config.get("GCP_INSTANCE_MAX_RUNTIME", 120)
zone = config.get('ZONE', '')
project = config.get('PROJECT_NAME', '')
# Check if zone and project both are provided
if zone == "":
log.critical('GCP zone name is empty!')
return
if project == "":
log.critical('GCP project name is empty!')
return
compute = get_compute_service_object()
delete_expired_instances(compute, vm_max_runtime, project, zone)
with app.app_context():
from flask import current_app
app = current_app._get_current_object()
# Create a database session
db = create_session(config.get('DATABASE_URI', ''))
if platform is None or platform == TestPlatform.linux:
log.info('Define process to run Linux GCP instances')
gcp_instance(app, db, TestPlatform.linux, repository, delay)
log.info('Linux GCP instances process kicked off')
if platform is None or platform == TestPlatform.windows:
log.info('Define process to run Windows GCP instances')
gcp_instance(app, db, TestPlatform.windows, repository, delay)
log.info('Windows GCP instances process kicked off')
def get_running_instances(compute, project, zone) -> list:
"""
Get details of all the running GCP VM instances.
:param compute: The cloud compute engine service object
:type compute: googleapiclient.discovery.Resource
:param project: The GCP project name
:type project: str
:param zone: Configured zone for the VM instances
:type zone: str
:return: List of VM instances
:rtype: list
"""
result = compute.instances().list(project=project, zone=zone).execute()
return result['items'] if 'items' in result else []
def is_instance_testing(vm_name) -> bool:
"""
Check if VM name is of the correct format and return if it is used for testing or not.
:param vm_name: Name of the VM machine to be identified
:type vm_name: str
:return: Boolean whether instance is used for testing or not
:rtype: bool
"""
for platform in TestPlatform:
if re.fullmatch(f"{platform.value}-[0-9]+", vm_name):
return True
return False
def delete_expired_instances(compute, max_runtime, project, zone) -> None:
"""
Get all running instances and delete instances whose maximum runtime limit is reached.
:param compute: The cloud compute engine service object
:type compute: googleapiclient.discovery.Resource
:param max_runtime: The maximum runtime limit for VM instances
:type max_runtime: int
:param project: The GCP project name
:type project: str
:param zone: Zone for the new VM instance
:type zone: str
"""
for instance in get_running_instances(compute, project, zone):
vm_name = instance['name']
if is_instance_testing(vm_name):
creationTimestamp = datetime.datetime.strptime(instance['creationTimestamp'], '%Y-%m-%dT%H:%M:%S.%f%z')
currentTimestamp = datetime.datetime.now(datetime.timezone.utc)
if currentTimestamp - creationTimestamp >= datetime.timedelta(minutes=max_runtime):
# Update test status in database and on GitHub
platform_name, test_id = vm_name.split('-')
test = Test.query.filter(Test.id == test_id).first()
message = "Could not complete test, time limit exceeded"
progress = TestProgress(test_id, TestStatus.canceled, message)
g.db.add(progress)
g.db.commit()
gh = Github(g.github['bot_token'])
repository = gh.get_repo(f"{g.github['repository_owner']}/{g.github['repository']}")
gh_commit = repository.get_commit(test.commit)
if gh_commit is not None:
update_status_on_github(gh_commit, Status.ERROR, message, f"CI - {platform_name}")
# Delete VM instance
operation = delete_instance(compute, project, zone, vm_name)
wait_for_operation(compute, project, zone, operation['name'])
def gcp_instance(app, db, platform, repository, delay) -> None:
"""
Find all the pending tests and start running them in new GCP instances.
:param app: The Flask app
:type app: Flask
:param db: database connection
:type db: sqlalchemy.orm.scoping.scoped_session
: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 gcp_instance function
:type delay: int
"""
from run import config, get_github_config, log
github_config = get_github_config(config)
log.info(f"[{platform}] Running gcp_instance")
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
finished_tests = db.query(TestProgress.test_id).filter(
TestProgress.status.in_([TestStatus.canceled, TestStatus.completed])
).subquery()
running_tests = db.query(GcpInstance.test_id).subquery()
pending_tests = Test.query.filter(
Test.id.notin_(finished_tests), Test.id.notin_(running_tests), Test.platform == platform
).order_by(Test.id.asc())
compute = get_compute_service_object()
for test in pending_tests:
if test.test_type == TestType.pull_request:
gh_commit = repository.get_commit(test.commit)
if test.pr_nr == 0:
log.warn(f'[{platform}] Test {test.id} is invalid')
deschedule_test(gh_commit, message="Invalid PR number", test=test, db=db)
continue
test_pr = repository.get_pull(test.pr_nr)
if test.commit != test_pr.head.sha:
log.warn(f'[{platform}] Test {test.id} is invalid')
deschedule_test(gh_commit, message="PR closed or updated", test=test, db=db)
continue
if test_pr.state != 'open':
log.debug(f"PR {test.pr_nr} not in open state, skipping test {test.id}")
continue
start_test(compute, app, db, repository, test, github_config['bot_token'])
def get_compute_service_object() -> googleapiclient.discovery.Resource:
"""Get a Cloud Compute Engine service object."""
from run import config
scopes = config.get('SCOPES', '')
sa_file = os.path.join(config.get('INSTALL_FOLDER', ''), config.get('SERVICE_ACCOUNT_FILE', ''))
credentials = service_account.Credentials.from_service_account_file(sa_file, scopes=scopes)
return googleapiclient.discovery.build('compute', 'v1', credentials=credentials)
def start_test(compute, app, db, repository: Repository.Repository, test, bot_token) -> None:
"""
Start a VM instance and run the tests.
Creates testing xml files to test the changes.
Downloads the build artifacts generated during GitHub Action workflows.
Create a GCP instance and start the test.
:param compute: The cloud compute engine service object
:type compute: googleapiclient.discovery.Resource
:param app: The Flask app
:type app: Flask
:param db: database connection
:type db: sqlalchemy.orm.scoping.scoped_session
:param platform: operating system
:type platform: str
:param repository: repository to run tests on
:type repository: str
:param test: The test which is to be started
:type test: mod_test.models.Test
:param bot_token: The GitHub bot token
:type bot_token: str
:return: Nothing
:rtype: None
"""
from run import config, log
gcp_instance_name = f"{test.platform.value}-{test.id}"
log.debug(f'[{gcp_instance_name}] Starting test {test.id}')
test_folder = os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'vm_data', gcp_instance_name)
Path(test_folder).mkdir(parents=True, exist_ok=True)
status = GcpInstance(gcp_instance_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")
# 1) Generate test files
base_folder = os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'vm_data', gcp_instance_name, 'ci-tests')
Path(base_folder).mkdir(parents=True, exist_ok=True)
categories = Category.query.order_by(Category.id.desc()).all()
commit_name = 'fetch_commit_' + test.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 == test.platform)).first()
if last_commit is not None:
log.debug(f"[{gcp_instance_name}] We will compare against the results of test {last_commit.id}")
regression_ids = test.get_customized_regressiontests()
# BREAKS REGULAR TESTS
# if len(regression_ids) == 0:
# log.debug(f"[{gcp_instance_name}] No regression tests, skipping test {test.id}")
# return
# 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) Download the artifact for the current build from GitHub Actions
artifact_saved = False
base_folder = os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'vm_data', gcp_instance_name, 'unsafe-ccextractor')
Path(base_folder).mkdir(parents=True, exist_ok=True)
artifacts = repository.get_artifacts()
if test.platform == TestPlatform.linux:
artifact_name = Artifact_names.linux
else:
artifact_name = Artifact_names.windows
for index, artifact in enumerate(artifacts):
if artifact.name == artifact_name and artifact.workflow_run.head_sha == test.commit:
artifact_url = artifact.archive_download_url
try:
auth_header = f"token {bot_token}"
r = requests.get(artifact_url, headers={"Authorization": auth_header})
except Exception as e:
log.critical("Could not fetch artifact, request timed out")
return
if r.status_code != 200:
log.critical(f"Could not fetch artifact, response code: {r.status_code}")
return
open(os.path.join(base_folder, 'ccextractor.zip'), 'wb').write(r.content)
with zipfile.ZipFile(os.path.join(base_folder, 'ccextractor.zip'), 'r') as artifact_zip:
artifact_zip.extractall(base_folder)
artifact_saved = True
break
if not artifact_saved:
log.critical("Could not find an artifact for this commit")
return
zone = config.get('ZONE', '')
project_id = config.get('PROJECT_NAME', '')
operation = create_instance(compute, project_id, zone, test, full_url)
result = wait_for_operation(compute, project_id, zone, operation['name'])
if 'error' not in result:
db.add(status)
db.commit()
else:
log.error(f"Error creating test instance for test {test.id}, result: {result}")
def create_instance(compute, project, zone, test, reportURL) -> Dict:
"""
Start an instance and pass the VM metadata.
:param compute: The cloud compute engine service object
:type compute: googleapiclient.discovery.Resource
:param project: The GCP project name
:type project: str
:param zone: Zone for the new VM instance
:type zone: str
:param test: The test for which VM is to be started
:type test: mod_test.models.Test
:param reportURL: Test-specific URL link for reporting progress to server
:type reportURL: str
:return: Create operation details after VM creation
:rtype: Dict
"""
from run import config
if test.platform == TestPlatform.linux:
image_response = compute.images().getFromFamily(project=config.get('LINUX_INSTANCE_PROJECT_NAME', ''),
family=config.get('LINUX_INSTANCE_FAMILY_NAME', '')).execute()
startup_script = open(os.path.join(config.get('INSTALL_FOLDER', ''), 'install', 'ci-vm',
'ci-linux', 'startup-script.sh'), 'r').read()
metadata_items = [
{'key': 'startup-script', 'value': startup_script},
{'key': 'reportURL', 'value': reportURL},
{'key': 'bucket', 'value': config.get('GCS_BUCKET_NAME', '')}
]
elif test.platform == TestPlatform.windows:
image_response = compute.images().getFromFamily(project=config.get('WINDOWS_INSTANCE_PROJECT_NAME', ''),
family=config.get('WINDOWS_INSTANCE_FAMILY_NAME', '')).execute()
startup_script = open(os.path.join(config.get('INSTALL_FOLDER', ''), 'install', 'ci-vm',
'ci-windows', 'startup-script.ps1'), 'r').read()
service_account = open(os.path.join(config.get('INSTALL_FOLDER', ''),
config.get('SERVICE_ACCOUNT_FILE', '')), 'r').read()
rclone_conf = open(os.path.join(config.get('INSTALL_FOLDER', ''), 'install', 'ci-vm',
'ci-windows', 'rclone.conf'), 'r').read()
metadata_items = [
{'key': 'windows-startup-script-ps1', 'value': startup_script},
{'key': 'service_account', 'value': service_account},
{'key': 'rclone_conf', 'value': rclone_conf},
{'key': 'reportURL', 'value': reportURL},
{'key': 'bucket', 'value': config.get('GCS_BUCKET_NAME', '')}
]
source_disk_image = image_response['selfLink']
vm_name = f"{test.platform.value}-{test.id}"
vm_config = get_config_for_gcp_instance(vm_name, source_disk_image, metadata_items)
return compute.instances().insert(
project=project,
zone=zone,
body=vm_config).execute()
def delete_instance(compute, project, zone, vm_name) -> Dict:
"""
Delete the GCP instance with given name.
:param compute: The cloud compute engine service object
:type compute: googleapiclient.discovery.Resource
:param project: The GCP project name
:type project: str
:param zone: Zone for the new VM instance
:type zone: str
:param vm_name: Name of the instance to be deleted
:type vm_name: str
:return: Delete operation details after VM deletion
:rtype: Dict
"""
return compute.instances().delete(
project=project,
zone=zone,
instance=vm_name).execute()
def get_config_for_gcp_instance(vm_name, source_disk_image, metadata_items) -> Dict:
"""
Get VM config for new VM instance.
:param vm_name: The name of the instance to be created
:type vm_name: str
:param source_disk_image: Source disk image for new instance
:type source_disk_image: str
:param metadata_items: VM Metadata for new instance
:type metadata_items: list
:return: Config for new instance
:rtype: Dict
"""
from run import config
# Configure the machine
machine_type = config.get('MACHINE_TYPE', '')
return {
'name': vm_name,
'machineType': machine_type,
# Specify the boot disk and the image to use as a source.
'disks': [
{
'boot': True,
'autoDelete': True,
'initializeParams': {
'sourceImage': source_disk_image,
}
}
],
# Specify a network interface with NAT to access the public
# internet.
'networkInterfaces': [{
'network': 'global/networks/default',
'accessConfigs': [
{'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}
]
}],
# Allow the instance to access cloud storage and logging.
'serviceAccounts': [{
'email': 'default',
'scopes': [
'https://www.googleapis.com/auth/devstorage.read_write',
'https://www.googleapis.com/auth/logging.write'
]
}],
# Metadata is readable from the instance and allows you to
# pass configuration from deployment scripts to instances.
'metadata': {
'items': metadata_items
}
}
def wait_for_operation(compute, project, zone, operation) -> Dict:
"""
Wait for an operation to get completed.
:param compute: The cloud compute engine service object
:type compute: googleapiclient.discovery.Resource
:param project: The GCP project name
:type project: str
:param zone: Zone for the new VM instance
:type zone: str
:param operation: Operation name for which server is waiting
:type operation: str
:return: Response received after operation completion
:rtype: Dict
"""
from run import log
log.info("Waiting for an operation to finish")
while True:
result = compute.zoneOperations().get(
project=project,
zone=zone,
operation=operation).execute()
if result['status'] == 'DONE':
log.info("Operation Completed")
return result
time.sleep(1)
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 add_test_entry(db, commit, test_type, branch="master", pr_nr=0) -> None:
"""
Add test details entry into Test model for each platform.
:param db: Database connection.
:type db: sqlalchemy.orm.scoping.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()
def schedule_test(gh_commit: Commit.Commit) -> None:
"""
Post status to GitHub as waiting for GitHub Actions completion.
:param gh_commit: The GitHub API call for the commit. Can be None
:type gh_commit: Any
:return: Nothing
:rtype: None
"""
if gh_commit is not None:
for platform in TestPlatform:
status_description = "Waiting for actions to complete"
update_status_on_github(gh_commit, Status.PENDING, status_description, f"CI - {platform.value}")
def update_status_on_github(gh_commit: Commit.Commit, state, description, context,
target_url=GithubObject.NotSet): # type: ignore
"""
Update status on GitHub.
:param gh_commit: The GitHub API call for the commit. Can be None
:type gh_commit: Any
:param state: The test status.
:type state: Status
:param description: Description of test status.
:type description: str
:param context: Context for Github status.
:type context: str
:param target_url: Platform url for test status
:type target_url: _NotSetType() | str
"""
from run import log
try:
gh_commit.create_status(
state=state,
description=description,
context=context,
target_url=target_url
)
except GithubException as a:
log.critical(f'Could not post to GitHub! Response: {a.data}')
def deschedule_test(gh_commit: Commit.Commit, commit=None, test_type=None, platform=None, branch="master",
message="Tests have been cancelled", state=Status.FAILURE, test=None, db=None) -> None:
"""
Post status to GitHub (default: as failure due to GitHub Actions incompletion).
: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 platform: The platform name
:type platform: TestPlatform
:param branch: Branch name
:type branch: str
:param message: The message to be posted to GitHub
:type message: str
:param state: The status badge of the test
:type state: Status
:param test: The test which is to be canceled (optional)
:type state: Test
:param db: db session
:type db: sqlalchemy.orm.scoping.scoped_session
:return: Nothing
:rtype: None
"""
from run import log
if test_type == TestType.pull_request:
log.debug('pull request test type detected')
branch = "pull_request"
if test is None:
fork_url = f"%/{g.github['repository_owner']}/{g.github['repository']}.git"
fork = Fork.query.filter(Fork.github.like(fork_url)).first()
test = Test.query.filter(and_(Test.platform == platform,
Test.commit == commit,
Test.fork_id == fork.id,
Test.test_type == test_type,
Test.branch == branch,
)).first()
if test is not None:
progress = TestProgress(test.id, TestStatus.canceled, message, datetime.datetime.now())
db = db or g.db
db.add(progress)
db.commit()
if gh_commit is not None:
update_status_on_github(gh_commit, state, message, f"CI - {test.platform.value}")
def queue_test(gh_commit: Commit.Commit, commit, test_type, platform, branch="master", pr_nr=0) -> None:
"""
Store test details into Test model for each platform, and post the status to GitHub.
: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 platform: The platform name
:type platform: TestPlatform
: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"
platform_test = Test.query.filter(and_(Test.platform == platform,
Test.commit == commit,
Test.fork_id == fork.id,
Test.test_type == test_type,
Test.branch == branch,
Test.pr_nr == pr_nr
)).first()
add_customized_regression_tests(platform_test.id)
if gh_commit is not None:
target_url = url_for('test.by_id', test_id=platform_test.id, _external=True)
status_context = f"CI - {platform_test.platform.value}"
update_status_on_github(gh_commit, Status.PENDING, "Tests queued", status_context, target_url)
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(g.github['bot_token'])
repository = gh.get_repo(f"{g.github['repository_owner']}/{g.github['repository']}")
if event == "push":
g.log.debug('push event detected')
if 'after' in payload and payload["ref"] == "refs/heads/master":
commit_hash = payload['after']
# Update the db to the new last commit
ref = repository.get_git_ref("heads/master")
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()
add_test_entry(g.db, 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']
action = payload['action']
is_active = action in ['opened', 'synchronize', 'reopened']
is_inactive = action in ['closed']
if is_active:
try:
commit_hash = payload['pull_request']['head']['sha']
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")
return 'ERROR'
if repository.get_pull(number=pr_nr).mergeable is not False:
add_test_entry(g.db, commit_hash, TestType.pull_request, pr_nr=pr_nr)
elif is_inactive:
pr_action = 'closed' if action == 'closed' else 'converted to draft'
g.log.debug(f'PR was {pr_action}, 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, f"PR {pr_action}", datetime.datetime.now())
g.db.add(progress)
g.db.commit()
gh_commit = repository.get_commit(test.commit)
# If test run status exists, mark them as cancelled
for status in gh_commit.get_statuses():
if status["context"] == f"CI - {test.platform.value}":
target_url = url_for('test.by_id', test_id=test.id, _external=True)
update_status_on_github(gh_commit, Status.FAILURE, "Tests canceled",
status["context"], target_url=target_url)
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()