-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathcontrollers.py
More file actions
executable file
·3064 lines (2585 loc) · 128 KB
/
controllers.py
File metadata and controls
executable file
·3064 lines (2585 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""maintains all functionality related running virtual machines, starting and tracking tests."""
import base64
import datetime
import fnmatch
import hashlib
import json
import os
import re
import shutil
import time
import zipfile
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import Any, Callable, Dict, Optional, TypeVar
import googleapiclient.discovery
import requests
import yaml
from flask import (Blueprint, abort, flash, g, jsonify, redirect, request,
url_for)
from github import (Auth, 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, select
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, PendingDeletion, 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
# Timeout constants (in seconds)
GITHUB_API_TIMEOUT = 30 # Timeout for GitHub API calls
GCP_API_TIMEOUT = 60 # Timeout for GCP API calls
ARTIFACT_DOWNLOAD_TIMEOUT = 300 # 5 minutes for artifact downloads
GCP_OPERATION_MAX_WAIT = 1800 # 30 minutes max wait for GCP operations
GCP_VM_CREATE_VERIFY_TIMEOUT = 60 # 60 seconds to verify VM creation started
# Retry constants
MAX_RETRIES = 3
INITIAL_BACKOFF = 1 # seconds
MAX_BACKOFF = 30 # seconds
T = TypeVar('T')
def retry_with_backoff(
func: Callable[..., T],
max_retries: int = MAX_RETRIES,
initial_backoff: float = INITIAL_BACKOFF,
max_backoff: float = MAX_BACKOFF,
retryable_exceptions: Any = (GithubException, requests.RequestException)
) -> T:
"""
Execute a function with exponential backoff retry logic.
:param func: The function to execute (should be a callable with no arguments, use lambda for args)
:param max_retries: Maximum number of retry attempts
:param initial_backoff: Initial backoff time in seconds
:param max_backoff: Maximum backoff time in seconds
:param retryable_exceptions: Tuple of exception types that should trigger a retry
:return: The result of the function call
:raises: The last exception if all retries fail
"""
from run import log
last_exception: Optional[Exception] = None
backoff = initial_backoff
for attempt in range(max_retries + 1):
try:
return func()
except retryable_exceptions as e:
last_exception = e
if attempt < max_retries:
log.warning(f"Attempt {attempt + 1}/{max_retries + 1} failed: {e}. Retrying in {backoff}s...")
time.sleep(backoff)
backoff = min(backoff * 2, max_backoff)
else:
log.error(f"All {max_retries + 1} attempts failed. Last error: {e}")
if last_exception is not None:
raise last_exception
raise RuntimeError("retry_with_backoff: unexpected state - no exception captured")
def safe_db_commit(db, operation_description: str = "database operation") -> bool:
"""
Safely commit a database transaction with rollback on failure.
:param db: The database session
:param operation_description: Description of the operation for logging
:return: True if commit succeeded, False otherwise
"""
from run import log
try:
db.commit()
return True
except Exception as e:
log.error(f"Database commit failed during {operation_description}: {e}")
try:
db.rollback()
log.info(f"Successfully rolled back transaction for {operation_description}")
except Exception as rollback_error:
log.error(f"Rollback also failed for {operation_description}: {rollback_error}")
return False
# User-friendly messages for known GCP error codes
GCP_ERROR_MESSAGES = {
'ZONE_RESOURCE_POOL_EXHAUSTED': (
"GCP resources temporarily unavailable in the configured zone. "
"The test will be retried automatically when resources become available."
),
'QUOTA_EXCEEDED': (
"GCP quota limit reached. "
"The test will be retried automatically when resources become available."
),
'RESOURCE_NOT_FOUND': "Required GCP resource not found. Please contact the administrator.",
'RESOURCE_ALREADY_EXISTS': "A VM with this name already exists. Please contact the administrator.",
'TIMEOUT': "GCP operation timed out. The test will be retried automatically.",
}
# GCP error codes that are transient and should be retried automatically.
# Tests encountering these errors will remain pending and be picked up on the next cron run.
GCP_RETRYABLE_ERRORS = {
'ZONE_RESOURCE_POOL_EXHAUSTED',
'QUOTA_EXCEEDED',
}
def get_gcp_error_code(result: Dict) -> Optional[str]:
"""
Extract the error code from a GCP API error response.
:param result: The GCP API response dictionary
:return: The error code string, or None if not found
"""
if not isinstance(result, dict):
return None
error = result.get('error')
if not isinstance(error, dict):
return None
errors = error.get('errors', [])
if not errors or not isinstance(errors, list):
return None
first_error = errors[0] if len(errors) > 0 else {}
return first_error.get('code')
def is_retryable_gcp_error(result: Dict) -> bool:
"""
Check if a GCP error is transient and should be retried.
:param result: The GCP API response dictionary
:return: True if the error is retryable, False otherwise
"""
error_code = get_gcp_error_code(result)
return error_code in GCP_RETRYABLE_ERRORS
def parse_gcp_error(result: Dict, log=None) -> str:
"""
Parse a GCP API error response and return a user-friendly message.
GCP errors have the structure:
{
'error': {
'errors': [{'code': 'ERROR_CODE', 'message': '...'}]
}
}
For known error codes, returns a user-friendly message.
For unknown errors, logs the details server-side and returns a generic message
to avoid exposing potentially sensitive information.
:param result: The GCP API response dictionary
:param log: Optional logger instance. If not provided, uses module logger.
:return: A user-friendly error message
"""
import logging
if log is None:
log = logging.getLogger('Platform')
if not isinstance(result, dict):
log.error(f"GCP error (non-dict): {result}")
return "VM creation failed. Please contact the administrator."
error = result.get('error')
if error is None:
log.error(f"GCP error (no error key): {result}")
return "VM creation failed. Please contact the administrator."
if not isinstance(error, dict):
log.error(f"GCP error (error not dict): {error}")
return "VM creation failed. Please contact the administrator."
errors = error.get('errors', [])
if not errors:
log.error(f"GCP error (empty errors list): {error}")
return "VM creation failed. Please contact the administrator."
# Get the first error (usually the most relevant)
first_error = errors[0] if isinstance(errors, list) and len(errors) > 0 else {}
error_code = first_error.get('code', 'UNKNOWN')
error_message = first_error.get('message', 'No details provided')
# Check if we have a user-friendly message for this error code
if error_code in GCP_ERROR_MESSAGES:
return GCP_ERROR_MESSAGES[error_code]
# For unknown errors, log full details server-side but return generic message
# to avoid exposing potentially sensitive information (project names, zones, etc.)
log.error(f"GCP error ({error_code}): {error_message}")
return f"VM creation failed ({error_code}). Please contact the administrator."
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 x64 Release build"
def is_valid_commit_hash(commit: Optional[str]) -> bool:
"""
Validate that a string is a valid Git commit hash.
A valid commit hash is:
- Not None or empty
- At least 7 characters (short hash) up to 40 characters (full SHA-1)
- Contains only hexadecimal characters (0-9, a-f, A-F)
- Not the Git null SHA (all zeros)
:param commit: The commit hash to validate
:type commit: Optional[str]
:return: True if valid, False otherwise
:rtype: bool
"""
if not commit or not isinstance(commit, str):
return False
commit = commit.strip()
# Check length (7-40 characters for valid git hashes)
if len(commit) < 7 or len(commit) > 40:
return False
# Check for null SHA (all zeros)
if commit == '0' * len(commit):
return False
# Check that it's a valid hexadecimal string
try:
int(commit, 16)
return True
except ValueError:
return False
# Maximum number of artifacts to search through when looking for a specific commit
# GitHub keeps artifacts for 90 days by default, so this should be enough
MAX_ARTIFACTS_TO_SEARCH = 500
def find_artifact_for_commit(repository, commit_sha: str, platform: Any, log) -> Optional[Any]:
"""
Find a build artifact for a specific commit and platform.
This function properly handles GitHub API pagination to search through
all available artifacts. This prevents race conditions where tests
fail because artifacts are not found due to pagination issues.
:param repository: GitHub repository object
:type repository: Repository.Repository
:param commit_sha: The commit SHA to find artifact for
:type commit_sha: str
:param platform: The platform (linux or windows) - TestPlatform enum value
:type platform: TestPlatform
:param log: Logger instance
:return: The artifact object if found, None otherwise
:rtype: Optional[Artifact]
"""
if platform == TestPlatform.linux:
artifact_name = Artifact_names.linux
else:
artifact_name = Artifact_names.windows
try:
artifacts = repository.get_artifacts()
artifacts_checked = 0
for artifact in artifacts:
artifacts_checked += 1
if artifact.name == artifact_name and artifact.workflow_run.head_sha == commit_sha:
log.debug(f"Found artifact '{artifact_name}' for commit {commit_sha[:8]} "
f"(checked {artifacts_checked} artifacts)")
return artifact
# Limit search to prevent excessive API calls
if artifacts_checked >= MAX_ARTIFACTS_TO_SEARCH:
log.warning(f"Reached max artifact search limit ({MAX_ARTIFACTS_TO_SEARCH}) "
f"without finding artifact for commit {commit_sha[:8]}")
break
log.debug(f"No artifact '{artifact_name}' found for commit {commit_sha[:8]} "
f"(checked {artifacts_checked} artifacts)")
return None
except Exception as e:
log.error(f"Error searching for artifact: {type(e).__name__}: {e}")
return None
def verify_artifacts_exist(repository, commit_sha: str, log) -> Dict[str, bool]:
"""
Verify that build artifacts exist for a commit before queuing tests.
This function should be called before queue_test() to prevent the race
condition where tests are queued before artifacts are available.
:param repository: GitHub repository object
:type repository: Repository.Repository
:param commit_sha: The commit SHA to verify
:type commit_sha: str
:param log: Logger instance
:return: Dict with 'linux' and 'windows' keys indicating artifact availability
:rtype: Dict[str, bool]
"""
result = {'linux': False, 'windows': False}
linux_artifact = find_artifact_for_commit(repository, commit_sha, TestPlatform.linux, log)
if linux_artifact is not None:
result['linux'] = True
log.info(f"Linux artifact verified for commit {commit_sha[:8]}")
else:
log.warning(f"Linux artifact NOT found for commit {commit_sha[:8]}")
windows_artifact = find_artifact_for_commit(repository, commit_sha, TestPlatform.windows, log)
if windows_artifact is not None:
result['windows'] = True
log.info(f"Windows artifact verified for commit {commit_sha[:8]}")
else:
log.warning(f"Windows artifact NOT found for commit {commit_sha[:8]}")
return result
@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
with app.app_context():
from flask import current_app
app = current_app._get_current_object() # type: ignore[attr-defined]
# Create a database session
db = create_session(config.get('DATABASE_URI', ''))
compute = get_compute_service_object()
# Step 1: Verify any pending deletions from previous runs
verify_pending_deletions(compute, project, zone, db)
# Step 2: Scan for orphaned VMs that weren't properly deleted
scan_for_orphaned_vms(compute, project, zone, db)
# Step 3: Delete expired instances (tests that ran too long)
delete_expired_instances(compute, vm_max_runtime, project, zone, db, repository)
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, db, repository) -> 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)
db.add(progress)
if not safe_db_commit(db, f"canceling timed-out test {test_id}"):
continue # Skip to next instance if commit failed
gh_commit = repository.get_commit(test.commit)
if gh_commit is not None:
# Build target_url so users can see test results
from flask import url_for
try:
target_url = url_for('test.by_id', test_id=test_id, _external=True)
except RuntimeError:
# Outside of request context
target_url = f"https://sampleplatform.ccextractor.org/test/{test_id}"
update_status_on_github(gh_commit, Status.ERROR, message, f"CI - {platform_name}", target_url)
# Delete VM instance with tracking for verification
from run import log
try:
operation = delete_instance_with_tracking(
compute, project, zone, vm_name, db)
op_name = operation.get('name', 'unknown')
log.info(f"Expired instance deletion initiated for {vm_name} (op: {op_name})")
except Exception as e:
log.error(f"Failed to delete expired instance {vm_name}: {e}")
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])
)
running_tests = db.query(GcpInstance.test_id)
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:
try:
gh_commit = retry_with_backoff(lambda t=test: repository.get_commit(t.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 = retry_with_backoff(lambda t=test: repository.get_pull(t.pr_nr))
# Note: We intentionally do NOT check if test.commit != test_pr.head.sha
# If a new commit was pushed to the PR, a new test entry will be created for it.
# We should still run the test for the commit that was originally queued.
# This prevents the confusing "PR closed or updated" error when users push fixes.
if test_pr.state != 'open':
log.info(f"[{platform}] PR {test.pr_nr} is closed, descheduling test {test.id}")
deschedule_test(gh_commit, message="PR is closed", test=test, db=db)
continue
except GithubException as e:
log.error(f"GitHub API error for test {test.id} after retries: {e}")
continue # Skip this test, try next one
except Exception as e:
log.error(f"Unexpected error checking PR status for test {test.id}: {e}")
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 mark_test_failed(db, test, repository, message: str) -> bool:
"""
Mark a test as failed and update GitHub status.
This function ensures that GitHub is always notified of the failure,
even if database operations fail. The GitHub status update is critical
to prevent tests from appearing stuck in "pending" state forever.
:param db: Database session
:type db: sqlalchemy.orm.scoping.scoped_session
:param test: The test to mark as failed
:type test: mod_test.models.Test
:param repository: GitHub repository object
:type repository: Repository.Repository
:param message: Error message to display
:type message: str
:return: True if operation succeeded, False otherwise
"""
from run import log
db_success = False
github_success = False
# Step 1: Try to update the database
try:
progress = TestProgress(test.id, TestStatus.canceled, message)
db.add(progress)
db.commit()
db_success = True
log.info(f"Test {test.id}: Database updated with failure status")
except Exception as e:
log.error(f"Test {test.id}: Failed to update database: {e}")
# Continue to try GitHub update even if DB fails
# Step 2: Try to update GitHub status (CRITICAL - must not be skipped)
# Use retry logic since this is critical to prevent stuck "pending" status
try:
# Build target_url first (doesn't need retry)
from flask import url_for
try:
target_url = url_for('test.by_id', test_id=test.id, _external=True)
except RuntimeError:
# Outside of request context
target_url = f"https://sampleplatform.ccextractor.org/test/{test.id}"
# Use retry_with_backoff for GitHub API calls
def update_github_status():
gh_commit = repository.get_commit(test.commit)
update_status_on_github(gh_commit, Status.ERROR, message, f"CI - {test.platform.value}", target_url)
retry_with_backoff(update_github_status, max_retries=3, initial_backoff=2.0)
github_success = True
log.info(f"Test {test.id}: GitHub status updated to ERROR: {message}")
except GithubException as e:
log.error(f"Test {test.id}: GitHub API error while updating status (after retries): {e.status} - {e.data}")
except Exception as e:
log.error(f"Test {test.id}: Failed to update GitHub status (after retries): {type(e).__name__}: {e}")
# Log final status
if db_success and github_success:
log.info(f"Test {test.id}: Successfully marked as failed")
elif github_success:
log.warning(f"Test {test.id}: GitHub updated but database update failed - test may be retried")
elif db_success:
log.error(f"Test {test.id}: Database updated but GitHub status NOT updated - "
f"status will appear stuck as 'pending' on GitHub!")
else:
log.critical(f"Test {test.id}: BOTH database and GitHub updates failed - "
f"test is in inconsistent state!")
return db_success and github_success
# Mapping of workflow names to their YAML files in the repository
WORKFLOW_FILES = {
"Build CCExtractor on Linux": ".github/workflows/build_linux.yml",
"Build CCExtractor on Windows": ".github/workflows/build_windows.yml",
}
# Cache for workflow path filters (refreshed periodically)
_workflow_filters_cache: Dict[str, tuple] = {} # {workflow_name: (filters, timestamp)}
WORKFLOW_CACHE_TTL = 3600 # 1 hour cache TTL
def _get_workflow_path_filters(repository, workflow_name: str, log) -> Optional[list]:
"""
Fetch and parse the workflow YAML to extract path filters.
Returns a list of path patterns that trigger the workflow, or None if
the workflow has no path filters (runs on all changes).
:param repository: GitHub repository object
:param workflow_name: Name of the workflow (e.g., "Build CCExtractor on Linux")
:param log: Logger instance
:return: List of path patterns, or None if no filters
"""
import time as time_module
# Check cache first
if workflow_name in _workflow_filters_cache:
filters, cached_at = _workflow_filters_cache[workflow_name]
if time_module.time() - cached_at < WORKFLOW_CACHE_TTL:
return filters
workflow_file = WORKFLOW_FILES.get(workflow_name)
if not workflow_file:
log.warning(f"Unknown workflow: {workflow_name}")
return None
try:
# Fetch the workflow file content from the repository
contents = repository.get_contents(workflow_file)
workflow_yaml = base64.b64decode(contents.content).decode('utf-8')
# Parse the YAML
workflow_config = yaml.safe_load(workflow_yaml)
# Extract path filters from 'on.push.paths' and 'on.pull_request.paths'
on_config = workflow_config.get('on', {})
path_filters = set()
# Check push paths
push_config = on_config.get('push', {})
if isinstance(push_config, dict) and 'paths' in push_config:
path_filters.update(push_config['paths'])
# Check pull_request paths
pr_config = on_config.get('pull_request', {})
if isinstance(pr_config, dict) and 'paths' in pr_config:
path_filters.update(pr_config['paths'])
filters = list(path_filters) if path_filters else None
# Cache the result
_workflow_filters_cache[workflow_name] = (filters, time_module.time())
log.debug(f"Workflow '{workflow_name}' path filters: {filters}")
return filters
except Exception as e:
log.warning(f"Failed to fetch/parse workflow file {workflow_file}: {e}")
return None # Assume no filters on error (will retry)
def _will_workflow_run_for_commit(repository, commit_sha: str, workflow_name: str, log) -> Optional[bool]:
"""
Check if a workflow will run for a given commit based on path filters.
:param repository: GitHub repository object
:param commit_sha: The commit SHA to check
:param workflow_name: Name of the workflow
:param log: Logger instance
:return: True if workflow will run (files match), False if it won't (no match),
None if cannot determine (no path filters or error)
"""
# Get the workflow's path filters
path_filters = _get_workflow_path_filters(repository, workflow_name, log)
if path_filters is None:
# No path filters means workflow runs on all changes
return None
try:
# Get the list of files changed in this commit
commit = repository.get_commit(commit_sha)
changed_files = [f.filename for f in commit.files]
log.debug(f"Commit {commit_sha[:7]} changed {len(changed_files)} files")
# Check if any changed file matches any path filter
for changed_file in changed_files:
for pattern in path_filters:
# Handle ** patterns (match any path depth)
if '**' in pattern:
# Convert ** glob to regex-compatible pattern
regex_pattern = pattern.replace('**/', '(.*/)?').replace('**', '.*')
regex_pattern = regex_pattern.replace('*', '[^/]*')
if re.match(regex_pattern, changed_file):
log.debug(f"File '{changed_file}' matches pattern '{pattern}'")
return True
elif fnmatch.fnmatch(changed_file, pattern):
log.debug(f"File '{changed_file}' matches pattern '{pattern}'")
return True
# No files matched any pattern
log.info(f"Commit {commit_sha[:7]}: No changed files match workflow '{workflow_name}' path filters")
return False
except Exception as e:
log.warning(f"Failed to check commit files against workflow filters: {e}")
return None # Cannot determine
def _diagnose_missing_artifact(repository, commit_sha: str, platform, log) -> tuple:
"""
Diagnose why an artifact was not found for a commit.
Checks the workflow run status to provide a more helpful error message and
indicate whether this is a retryable situation (build still in progress)
or a permanent failure (build failed, artifact expired).
:param repository: GitHub repository object
:param commit_sha: The commit SHA to check
:param platform: The platform (TestPlatform.linux or TestPlatform.windows)
:param log: Logger instance
:return: Tuple of (error_message: str, is_retryable: bool)
is_retryable=True means the test should NOT be marked as failed
and should be left for the next cron cycle to retry
"""
if platform == TestPlatform.linux:
expected_workflow = Workflow_builds.LINUX
else:
expected_workflow = Workflow_builds.WINDOWS
# First, check if the workflow will even run based on path filters
will_run = _will_workflow_run_for_commit(repository, commit_sha, expected_workflow, log)
if will_run is False:
# Workflow will definitely NOT run - no matching files in commit
message = (f"No build will be created: commit {commit_sha[:7]} does not modify any files "
f"that trigger the '{expected_workflow}' workflow. "
f"Only documentation or non-code files were changed.")
log.info(f"Commit {commit_sha[:7]}: workflow '{expected_workflow}' will not run due to path filters")
return (message, False) # NOT retryable - workflow will never run
try:
# Build workflow name lookup
workflow: Dict[int, Optional[str]] = defaultdict(lambda: None)
for active_workflow in repository.get_workflows():
workflow[active_workflow.id] = active_workflow.name
# Check workflow runs for this commit
workflow_found = False
for workflow_run in repository.get_workflow_runs(head_sha=commit_sha):
workflow_run_name = workflow[workflow_run.workflow_id]
if workflow_run_name != expected_workflow:
continue
workflow_found = True
if workflow_run.status != "completed":
# Build is still running - this is RETRYABLE
# Don't mark as failed, let the next cron cycle retry
message = (f"Build still in progress: '{expected_workflow}' is {workflow_run.status}. "
f"Will retry when build completes.")
return (message, True) # Retryable
elif workflow_run.conclusion != "success":
# Build failed - this is a PERMANENT failure
message = (f"Build failed: '{expected_workflow}' finished with conclusion "
f"'{workflow_run.conclusion}'. Check the GitHub Actions logs for details.")
return (message, False) # Not retryable
else:
# Build succeeded but artifact not found
# Check if the build completed very recently - if so, this might be
# GitHub API propagation delay (artifact exists but not visible yet)
# In that case, treat as retryable
ARTIFACT_PROPAGATION_GRACE_PERIOD = 300 # 5 minutes in seconds
try:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
# workflow_run.updated_at is when the run completed
if workflow_run.updated_at:
completed_at = workflow_run.updated_at
if completed_at.tzinfo is None:
completed_at = completed_at.replace(tzinfo=timezone.utc)
seconds_since_completion = (now - completed_at).total_seconds()
if seconds_since_completion < ARTIFACT_PROPAGATION_GRACE_PERIOD:
message = (f"Build completed recently ({int(seconds_since_completion)}s ago): "
f"'{expected_workflow}' succeeded but artifact not yet visible. "
f"Will retry (GitHub API propagation delay).")
log.info(f"Artifact not found but build completed {int(seconds_since_completion)}s ago - "
f"treating as retryable (possible API propagation delay)")
return (message, True) # Retryable - API propagation delay
except Exception as e:
log.warning(f"Could not check workflow completion time: {e}")
# Fall through to permanent failure
# Build completed more than 5 minutes ago - artifact should be visible
# This is a PERMANENT failure (artifact expired or not uploaded)
message = (f"Artifact not found: '{expected_workflow}' completed successfully, "
f"but no artifact was found. The artifact may have expired (GitHub deletes "
f"artifacts after a retention period) or was not uploaded properly.")
return (message, False) # Not retryable
if not workflow_found:
# No workflow run found - could be queued, not triggered, or too old
# Check commit age to determine if we should keep waiting
MAX_WAIT_HOURS = 3
try:
from datetime import datetime, timedelta, timezone
commit_obj = repository.get_commit(commit_sha)
commit_date = commit_obj.commit.author.date
if commit_date.tzinfo is None:
commit_date = commit_date.replace(tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
commit_age = now - commit_date
if commit_age > timedelta(hours=MAX_WAIT_HOURS):
# Commit is too old - workflow was never triggered or history expired
hours_old = commit_age.total_seconds() / 3600
message = (f"No build available: '{expected_workflow}' never ran for commit "
f"{commit_sha[:7]} (commit is {hours_old:.1f} hours old). "
f"The workflow was likely not triggered due to path filters, "
f"or the commit predates the workflow configuration.")
log.info(f"Commit {commit_sha[:7]} is {hours_old:.1f} hours old with no workflow run - "
f"marking as permanent failure")
return (message, False) # NOT retryable - too old
except Exception as e:
log.warning(f"Could not check commit age: {e}")
# Fall through to retryable on error
# Commit is recent enough - workflow might still be queued
message = (f"No workflow run found: '{expected_workflow}' has not run for commit "
f"{commit_sha[:7]}. The workflow may be queued, or was not triggered "
f"due to path filters. Will retry.")
return (message, True) # Retryable
except Exception as e:
log.warning(f"Failed to diagnose missing artifact: {e}")
# On diagnostic failure, assume retryable to be safe
return (f"No build artifact found for this commit (diagnostic check failed: {e})", True)
return ("No build artifact found for this commit", True) # Default to retryable
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
# Check if test is already being processed (basic locking)
existing_instance = GcpInstance.query.filter(GcpInstance.test_id == test.id).first()
if existing_instance is not None:
log.warning(f"Test {test.id} already has a GCP instance, skipping duplicate start")
return
# Check if test already has progress (already started or finished)
existing_progress = TestProgress.query.filter(TestProgress.test_id == test.id).first()
if existing_progress is not None:
log.warning(f"Test {test.id} already has progress entries, skipping")
return
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_entry = GeneralData.query.filter(GeneralData.key == commit_name).first()
if commit_entry is None:
log.warning(f'No commit hash found for {commit_name}, skipping comparison')
commit_hash = None
else: