-
Notifications
You must be signed in to change notification settings - Fork 48
/
parser.py
1294 lines (1112 loc) · 47.3 KB
/
parser.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
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
"""
Parser is transforming github JSONs into `events` objects
"""
import logging
from datetime import datetime, timezone
from os import getenv
from typing import Optional, Type, Union, Dict, Any, Tuple
from ogr.parsing import parse_git_repo
from packit.constants import PROD_DISTGIT_URL
from packit.utils import nested_get
from packit_service.config import ServiceConfig, Deployment
from packit_service.constants import (
KojiBuildState,
KojiTaskState,
TESTING_FARM_INSTALLABILITY_TEST_URL,
)
from packit_service.models import (
TFTTestRunTargetModel,
TestingFarmResult,
ProjectReleaseModel,
GitBranchModel,
PullRequestModel,
JobTriggerModel,
)
from packit_service.worker.events import (
AbstractCoprBuildEvent,
KojiTaskEvent,
CoprBuildStartEvent,
CoprBuildEndEvent,
PushPagureEvent,
IssueCommentGitlabEvent,
MergeRequestCommentGitlabEvent,
MergeRequestGitlabEvent,
PushGitlabEvent,
InstallationEvent,
IssueCommentEvent,
PullRequestCommentGithubEvent,
PullRequestGithubEvent,
PushGitHubEvent,
ReleaseEvent,
TestingFarmResultsEvent,
PullRequestCommentPagureEvent,
PipelineGitlabEvent,
CheckRerunCommitEvent,
CheckRerunPullRequestEvent,
CheckRerunReleaseEvent,
)
from packit_service.worker.events.enums import (
GitlabEventAction,
IssueCommentAction,
PullRequestAction,
PullRequestCommentAction,
)
from packit_service.worker.events.koji import KojiBuildEvent
from packit_service.worker.events.pagure import PullRequestFlagPagureEvent
from packit_service.worker.handlers.abstract import MAP_CHECK_PREFIX_TO_HANDLER
from packit_service.worker.helpers.testing_farm import TestingFarmJobHelper
logger = logging.getLogger(__name__)
class Parser:
"""
Once we receive a new event (GitHub/GitLab webhook) for every event
we need to have method inside the `Parser` class to create objects defined in `event.py`.
"""
@staticmethod
def parse_event(
event: dict,
) -> Optional[
Union[
PullRequestGithubEvent,
InstallationEvent,
ReleaseEvent,
TestingFarmResultsEvent,
PullRequestCommentGithubEvent,
IssueCommentEvent,
AbstractCoprBuildEvent,
PushGitHubEvent,
MergeRequestGitlabEvent,
KojiTaskEvent,
KojiBuildEvent,
MergeRequestCommentGitlabEvent,
IssueCommentGitlabEvent,
PushGitlabEvent,
PipelineGitlabEvent,
PullRequestFlagPagureEvent,
PullRequestCommentPagureEvent,
PushPagureEvent,
CheckRerunCommitEvent,
CheckRerunPullRequestEvent,
CheckRerunReleaseEvent,
]
]:
"""
Try to parse all JSONs that we process.
When reacting to fedmsg events, be aware that we are squashing the structure
so we take only `body` with the `topic` key included.
See: https://github.com/packit/packit-service-fedmsg/blob/
e53586bf7ace0c46fd6812fe8dc11491e5e6cf41/packit_service_fedmsg/consumer.py#L137
:param event: JSON from GitHub/GitLab
:return: event object
"""
if not event:
logger.warning("No event to process!")
return None
for response in map(
lambda parser: parser(event),
(
Parser.parse_pr_event,
Parser.parse_pull_request_comment_event,
Parser.parse_issue_comment_event,
Parser.parse_release_event,
Parser.parse_github_push_event,
Parser.parse_check_rerun_event,
Parser.parse_installation_event,
Parser.parse_push_pagure_event,
Parser.parse_testing_farm_results_event,
Parser.parse_copr_event,
Parser.parse_mr_event,
Parser.parse_koji_task_event,
Parser.parse_koji_build_event,
Parser.parse_merge_request_comment_event,
Parser.parse_gitlab_issue_comment_event,
Parser.parse_gitlab_push_event,
Parser.parse_pipeline_event,
Parser.parse_pagure_pr_flag_event,
Parser.parse_pagure_pull_request_comment_event,
),
):
if response:
return response
logger.debug("We don't process this event.")
return None
@staticmethod
def parse_mr_event(event) -> Optional[MergeRequestGitlabEvent]:
"""Look into the provided event and see if it's one for a new gitlab MR."""
if event.get("object_kind") != "merge_request":
return None
state = event["object_attributes"]["state"]
if state not in {"opened", "closed"}:
return None
action = nested_get(event, "object_attributes", "action")
if action not in {"reopen", "update"}:
action = state
actor = event["user"]["username"]
if not actor:
logger.warning("No Gitlab username from event.")
return None
object_id = event["object_attributes"]["id"]
if not object_id:
logger.warning("No object id from the event.")
return None
object_iid = event["object_attributes"]["iid"]
if not object_iid:
logger.warning("No object iid from the event.")
return None
source_project_url = nested_get(event, "object_attributes", "source", "web_url")
if not source_project_url:
logger.warning("Source project url not found in the event.")
return None
parsed_source_url = parse_git_repo(potential_url=source_project_url)
source_repo_branch = nested_get(event, "object_attributes", "source_branch")
logger.info(
f"Source: "
f"url={source_project_url} "
f"namespace={parsed_source_url.namespace} "
f"repo={parsed_source_url.repo} "
f"branch={source_repo_branch}."
)
target_project_url = nested_get(event, "project", "web_url")
if not target_project_url:
logger.warning("Target project url not found in the event.")
return None
parsed_target_url = parse_git_repo(potential_url=target_project_url)
target_repo_branch = nested_get(event, "object_attributes", "target_branch")
logger.info(
f"Target: "
f"url={target_project_url} "
f"namespace={parsed_target_url.namespace} "
f"repo={parsed_target_url.repo} "
f"branch={target_repo_branch}."
)
commit_sha = nested_get(event, "object_attributes", "last_commit", "id")
oldrev = nested_get(event, "object_attributes", "oldrev")
title = nested_get(event, "object_attributes", "title")
description = nested_get(event, "object_attributes", "description")
url = nested_get(event, "object_attributes", "url")
return MergeRequestGitlabEvent(
action=GitlabEventAction[action],
actor=actor,
object_id=object_id,
object_iid=object_iid,
source_repo_namespace=parsed_source_url.namespace,
source_repo_name=parsed_source_url.repo,
source_repo_branch=source_repo_branch,
source_project_url=source_project_url,
target_repo_namespace=parsed_target_url.namespace,
target_repo_name=parsed_target_url.repo,
target_repo_branch=target_repo_branch,
project_url=target_project_url,
commit_sha=commit_sha,
oldrev=oldrev,
title=title,
description=description,
url=url,
)
@staticmethod
def parse_pr_event(event) -> Optional[PullRequestGithubEvent]:
"""Look into the provided event and see if it's one for a new github PR."""
if not event.get("pull_request"):
return None
pr_id = event.get("number")
action = event.get("action")
if action not in {"opened", "reopened", "synchronize"} or not pr_id:
return None
logger.info(f"GitHub PR#{pr_id} {action!r} event.")
# we can't use head repo here b/c the app is set up against the upstream repo
# and not the fork, on the other hand, we don't process packit.yaml from
# the PR but what's in the upstream
base_repo_namespace = nested_get(
event, "pull_request", "head", "repo", "owner", "login"
)
base_repo_name = nested_get(event, "pull_request", "head", "repo", "name")
if not (base_repo_name and base_repo_namespace):
logger.warning("No full name of the repository.")
return None
base_ref = nested_get(event, "pull_request", "head", "sha")
if not base_ref:
logger.warning("Ref where the PR is coming from is not set.")
return None
user_login = nested_get(event, "pull_request", "user", "login")
if not user_login:
logger.warning("No GitHub login name from event.")
return None
target_repo_namespace = nested_get(
event, "pull_request", "base", "repo", "owner", "login"
)
target_repo_name = nested_get(event, "pull_request", "base", "repo", "name")
logger.info(f"Target repo: {target_repo_namespace}/{target_repo_name}.")
commit_sha = nested_get(event, "pull_request", "head", "sha")
https_url = event["repository"]["html_url"]
return PullRequestGithubEvent(
action=PullRequestAction[action],
pr_id=pr_id,
base_repo_namespace=base_repo_namespace,
base_repo_name=base_repo_name,
base_ref=base_ref,
target_repo_namespace=target_repo_namespace,
target_repo_name=target_repo_name,
project_url=https_url,
commit_sha=commit_sha,
actor=user_login,
)
@staticmethod
def parse_gitlab_push_event(event) -> Optional[PushGitlabEvent]:
"""
Look into the provided event and see if it's one for a new push to the gitlab branch.
https://docs.gitlab.com/ee/user/project/integrations/webhooks.html#push-events
"""
if event.get("object_kind") != "push":
return None
raw_ref = event.get("ref")
before = event.get("before")
pusher = event.get("user_username")
commits = event.get("commits")
if not (raw_ref and commits and before and pusher):
return None
elif event.get("after").startswith("0000000"):
logger.info(
f"GitLab push event on '{raw_ref}' by {pusher} to delete branch"
)
return None
number_of_commits = event.get("total_commits_count")
if not number_of_commits:
logger.warning("No number of commits info from event.")
raw_ref = raw_ref.split("/", maxsplit=2)
if not raw_ref:
logger.warning("No ref info from event.")
ref = raw_ref[-1]
head_commit = commits[-1]["id"]
if not raw_ref:
logger.warning("No commit_id info from event.")
logger.info(
f"Gitlab push event on '{raw_ref}': {before[:8]} -> {head_commit[:8]} "
f"by {pusher} "
f"({number_of_commits} {'commit' if number_of_commits == 1 else 'commits'})"
)
project_url = nested_get(event, "project", "web_url")
if not project_url:
logger.warning("Target project url not found in the event.")
return None
parsed_url = parse_git_repo(potential_url=project_url)
logger.info(
f"Project: "
f"repo={parsed_url.repo} "
f"namespace={parsed_url.namespace} "
f"url={project_url}."
)
return PushGitlabEvent(
repo_namespace=parsed_url.namespace,
repo_name=parsed_url.repo,
git_ref=ref,
project_url=project_url,
commit_sha=head_commit,
)
@staticmethod
def parse_github_push_event(event) -> Optional[PushGitHubEvent]:
"""
Look into the provided event and see if it's one for a new push to the github branch.
"""
raw_ref = event.get("ref")
before = event.get("before")
pusher = nested_get(event, "pusher", "name")
# https://developer.github.com/v3/activity/events/types/#pushevent
# > Note: The webhook payload example following the table differs
# > significantly from the Events API payload described in the table.
head_commit = (
event.get("head") or event.get("after") or event.get("head_commit")
)
if not (raw_ref and head_commit and before and pusher):
return None
elif event.get("deleted"):
logger.info(
f"GitHub push event on '{raw_ref}' by {pusher} to delete branch"
)
return None
number_of_commits = event.get("size")
if number_of_commits is None and "commits" in event:
number_of_commits = len(event.get("commits"))
ref = raw_ref.split("/", maxsplit=2)[-1]
logger.info(
f"GitHub push event on '{raw_ref}': {before[:8]} -> {head_commit[:8]} "
f"by {pusher} "
f"({number_of_commits} {'commit' if number_of_commits == 1 else 'commits'})"
)
repo_namespace = nested_get(event, "repository", "owner", "login")
repo_name = nested_get(event, "repository", "name")
if not (repo_namespace and repo_name):
logger.warning("No full name of the repository.")
return None
repo_url = nested_get(event, "repository", "html_url")
return PushGitHubEvent(
repo_namespace=repo_namespace,
repo_name=repo_name,
git_ref=ref,
project_url=repo_url,
commit_sha=head_commit,
)
@staticmethod
def parse_issue_comment_event(event) -> Optional[IssueCommentEvent]:
"""Look into the provided event and see if it is Github issue comment event."""
if nested_get(event, "issue", "pull_request"):
return None
issue_id = nested_get(event, "issue", "number")
action = event.get("action")
if action != "created" or not issue_id:
return None
comment = nested_get(event, "comment", "body")
comment_id = nested_get(event, "comment", "id")
if not (comment and comment_id):
logger.warning("No comment or comment id from the event.")
return None
logger.info(f"Github issue#{issue_id} comment: {comment!r} {action!r} event.")
base_repo_namespace = nested_get(event, "repository", "owner", "login")
base_repo_name = nested_get(event, "repository", "name")
if not (base_repo_namespace and base_repo_name):
logger.warning("No full name of the repository.")
user_login = nested_get(event, "comment", "user", "login")
if not user_login:
logger.warning("No Github login name from event.")
return None
target_repo = nested_get(event, "repository", "full_name")
logger.info(f"Target repo: {target_repo}.")
https_url = nested_get(event, "repository", "html_url")
return IssueCommentEvent(
IssueCommentAction[action],
issue_id,
base_repo_namespace,
base_repo_name,
target_repo,
https_url,
user_login,
comment,
comment_id,
)
@staticmethod
def parse_gitlab_issue_comment_event(event) -> Optional[IssueCommentGitlabEvent]:
"""Look into the provided event and see if it is Gitlab Issue comment event."""
if event.get("object_kind") != "note":
return None
issue = event.get("issue")
if not issue:
return None
issue_id = nested_get(event, "issue", "iid")
if not issue_id:
logger.warning("No issue id from the event.")
return None
comment = nested_get(event, "object_attributes", "note")
comment_id = nested_get(event, "object_attributes", "id")
if not (comment and comment_id):
logger.warning("No note or note id from the event.")
return None
state = nested_get(event, "issue", "state")
if not state:
logger.warning("No state from the event.")
return None
if state != "opened":
return None
action = nested_get(event, "object_attributes", "action")
if action not in {"reopen", "update"}:
action = state
logger.info(
f"Gitlab issue ID: {issue_id} comment: {comment!r} {action!r} event."
)
project_url = nested_get(event, "project", "web_url")
if not project_url:
logger.warning("Target project url not found in the event.")
return None
parsed_url = parse_git_repo(potential_url=project_url)
logger.info(
f"Project: "
f"repo={parsed_url.repo} "
f"namespace={parsed_url.namespace} "
f"url={project_url}."
)
actor = nested_get(event, "user", "username")
if not actor:
logger.warning("No Gitlab username from event.")
return None
return IssueCommentGitlabEvent(
action=GitlabEventAction[action],
issue_id=issue_id,
repo_namespace=parsed_url.namespace,
repo_name=parsed_url.repo,
project_url=project_url,
actor=actor,
comment=comment,
comment_id=comment_id,
)
@staticmethod
def parse_merge_request_comment_event(
event,
) -> Optional[MergeRequestCommentGitlabEvent]:
"""Look into the provided event and see if it is Gitlab MR comment event."""
if event.get("object_kind") != "note":
return None
merge_request = event.get("merge_request")
if not merge_request:
return None
state = nested_get(event, "merge_request", "state")
if state != "opened":
return None
action = nested_get(event, "merge_request", "action")
if action not in {"reopen", "update"}:
action = state
object_iid = nested_get(event, "merge_request", "iid")
if not object_iid:
logger.warning("No object iid from the event.")
object_id = nested_get(event, "merge_request", "id")
if not object_id:
logger.warning("No object id from the event.")
comment = nested_get(event, "object_attributes", "note")
comment_id = nested_get(event, "object_attributes", "id")
logger.info(
f"Gitlab MR id#{object_id} iid#{object_iid} comment: {comment!r} id#{comment_id} "
f"{action!r} event."
)
source_project_url = nested_get(event, "merge_request", "source", "web_url")
if not source_project_url:
logger.warning("Source project url not found in the event.")
return None
parsed_source_url = parse_git_repo(potential_url=source_project_url)
logger.info(
f"Source: "
f"repo={parsed_source_url.repo} "
f"namespace={parsed_source_url.namespace} "
f"url={source_project_url}."
)
target_project_url = nested_get(event, "project", "web_url")
if not target_project_url:
logger.warning("Target project url not found in the event.")
return None
parsed_target_url = parse_git_repo(potential_url=target_project_url)
logger.info(
f"Target: "
f"repo={parsed_target_url.repo} "
f"namespace={parsed_target_url.namespace} "
f"url={target_project_url}."
)
actor = nested_get(event, "user", "username")
if not actor:
logger.warning("No Gitlab username from event.")
return None
commit_sha = nested_get(event, "merge_request", "last_commit", "id")
if not commit_sha:
logger.warning("No commit_sha from the event.")
return None
return MergeRequestCommentGitlabEvent(
action=GitlabEventAction[action],
object_id=object_id,
object_iid=object_iid,
source_repo_namespace=parsed_source_url.namespace,
source_repo_name=parsed_source_url.repo,
target_repo_namespace=parsed_target_url.namespace,
target_repo_name=parsed_target_url.repo,
project_url=target_project_url,
actor=actor,
comment=comment,
commit_sha=commit_sha,
comment_id=comment_id,
)
@staticmethod
def parse_pull_request_comment_event(
event,
) -> Optional[PullRequestCommentGithubEvent]:
"""Look into the provided event and see if it is Github PR comment event."""
if not nested_get(event, "issue", "pull_request"):
return None
pr_id = nested_get(event, "issue", "number")
action = event.get("action")
if action not in {"created", "edited"} or not pr_id:
return None
comment = nested_get(event, "comment", "body")
comment_id = nested_get(event, "comment", "id")
logger.info(
f"Github PR#{pr_id} comment: {comment!r} id#{comment_id} {action!r} event."
)
base_repo_namespace = nested_get(event, "issue", "user", "login")
base_repo_name = nested_get(event, "repository", "name")
if not (base_repo_name and base_repo_namespace):
logger.warning("No full name of the repository.")
return None
user_login = nested_get(event, "comment", "user", "login")
if not user_login:
logger.warning("No GitHub login name from event.")
return None
if user_login in {"packit-as-a-service[bot]", "packit-as-a-service-stg[bot]"}:
logger.debug("Our own comment.")
return None
target_repo_namespace = nested_get(event, "repository", "owner", "login")
target_repo_name = nested_get(event, "repository", "name")
logger.info(f"Target repo: {target_repo_namespace}/{target_repo_name}.")
https_url = event["repository"]["html_url"]
return PullRequestCommentGithubEvent(
action=PullRequestCommentAction[action],
pr_id=pr_id,
base_repo_namespace=base_repo_namespace,
base_repo_name=None,
base_ref=None, # the payload does not include this info
target_repo_namespace=target_repo_namespace,
target_repo_name=target_repo_name,
project_url=https_url,
actor=user_login,
comment=comment,
comment_id=comment_id,
)
@staticmethod
def parse_check_rerun_event(
event,
) -> Optional[
Union[CheckRerunCommitEvent, CheckRerunPullRequestEvent, CheckRerunReleaseEvent]
]:
"""Look into the provided event and see if it is Github check rerun event."""
if not (
nested_get(event, "check_run")
and nested_get(event, "action") == "rerequested"
):
return None
check_name = nested_get(event, "check_run", "name")
logger.info(f"Github check run {check_name} rerun event.")
deployment = ServiceConfig.get_service_config().deployment
app = nested_get(event, "check_run", "app", "slug")
if (deployment == Deployment.prod and app != "packit-as-a-service") or (
deployment == Deployment.stg and app != "packit-as-a-service-stg"
):
logger.warning(f"Check run created by {app} and not us.")
return None
check_name_job, check_name_target = None, None
if ":" in check_name:
# e.g. "rpm-build:fedora-34-x86_64"
# or "rpm-build:fedora-34-x86_64:identifier"
# or "propose-downstream:f35
check_name_parts = check_name.split(":", maxsplit=2)
if len(check_name_parts) == 2:
check_name_job, check_name_target = check_name_parts
check_name_identifier = None
elif len(check_name_parts) == 3:
(
check_name_job,
check_name_target,
check_name_identifier,
) = check_name_parts
else:
logger.warning(f"{check_name_job} cannot be parsed")
check_name_job = None
if check_name_job not in MAP_CHECK_PREFIX_TO_HANDLER:
logger.warning(
f"{check_name_job} not in {list(MAP_CHECK_PREFIX_TO_HANDLER.keys())}"
)
check_name_job = None
elif "/" in check_name:
# for backward compatibility, e.g. packit/rpm-build-fedora-34-x86_64
# TODO: remove this (whole elif) after some time
_, _, check_name_job_info = check_name.partition("/")
for job_name in MAP_CHECK_PREFIX_TO_HANDLER.keys():
if check_name_job_info.startswith(job_name):
check_name_job = job_name
# e.g. [rpm-build-]fedora-34-x86_64
check_name_target = check_name_job_info[
(len(job_name) + 1) : # noqa
]
break
if not (check_name_job and check_name_target):
logger.warning(
f"We were not able to parse the job and target "
f"from the check run name {check_name}."
)
return None
repo_namespace = nested_get(event, "repository", "owner", "login")
repo_name = nested_get(event, "repository", "name")
actor = nested_get(event, "sender", "login")
if not (repo_namespace and repo_name):
logger.warning("No full name of the repository.")
return None
https_url = event["repository"]["html_url"]
commit_sha = nested_get(event, "check_run", "head_sha")
external_id = nested_get(event, "check_run", "external_id")
if not external_id:
logger.warning("No external_id to identify the original trigger provided.")
return None
job_trigger = JobTriggerModel.get_by_id(int(external_id))
if not job_trigger:
logger.warning(f"Job trigger with ID {external_id} not found.")
return None
db_trigger = job_trigger.get_trigger_object()
logger.info(f"Original trigger: {db_trigger}")
event = None
if isinstance(db_trigger, PullRequestModel):
event = CheckRerunPullRequestEvent(
repo_namespace=repo_namespace,
repo_name=repo_name,
project_url=https_url,
commit_sha=commit_sha,
pr_id=db_trigger.pr_id,
check_name_job=check_name_job,
check_name_target=check_name_target,
db_trigger=db_trigger,
actor=actor,
job_identifier=check_name_identifier,
)
elif isinstance(db_trigger, ProjectReleaseModel):
event = CheckRerunReleaseEvent(
repo_namespace=repo_namespace,
repo_name=repo_name,
project_url=https_url,
commit_sha=commit_sha,
tag_name=db_trigger.tag_name,
check_name_job=check_name_job,
check_name_target=check_name_target,
db_trigger=db_trigger,
actor=actor,
job_identifier=check_name_identifier,
)
elif isinstance(db_trigger, GitBranchModel):
event = CheckRerunCommitEvent(
repo_namespace=repo_namespace,
repo_name=repo_name,
project_url=https_url,
commit_sha=commit_sha,
git_ref=db_trigger.name,
check_name_job=check_name_job,
check_name_target=check_name_target,
db_trigger=db_trigger,
actor=actor,
job_identifier=check_name_identifier,
)
return event
@staticmethod
def parse_installation_event(event) -> Optional[InstallationEvent]:
"""Look into the provided event and see if it is Github App installation details."""
# Check if installation key in JSON isn't enough, we have to check the account as well
if not nested_get(event, "installation", "account"):
return None
action = event["action"]
if action != "created":
# We're currently not interested in removed/deleted/updated event.
return None
installation_id = event["installation"]["id"]
# if action == 'created' then repos are in repositories
repositories = event.get("repositories", [])
repo_names = [repo["full_name"] for repo in repositories]
logger.info(f"Github App installation {action!r} event. id: {installation_id}")
logger.debug(
f"account: {event['installation']['account']}, "
f"repositories: {repo_names}, sender: {event['sender']}"
)
# namespace (user/organization) into which the app has been installed
account_login = event["installation"]["account"]["login"]
account_id = event["installation"]["account"]["id"]
account_url = event["installation"]["account"]["url"]
account_type = event["installation"]["account"]["type"] # User or Organization
created_at = event["installation"]["created_at"]
# user who installed the app into 'account'
sender_id = event["sender"]["id"]
sender_login = event["sender"]["login"]
return InstallationEvent(
installation_id,
account_login,
account_id,
account_url,
account_type,
created_at,
repo_names,
sender_id,
sender_login,
)
@staticmethod
def parse_release_event(event) -> Optional[ReleaseEvent]:
"""
https://developer.github.com/v3/activity/events/types/#releaseevent
https://developer.github.com/v3/repos/releases/#get-a-single-release
look into the provided event and see if it's one for a published github release;
if it is, process it and return input for the job handler
"""
action = event.get("action")
release = event.get("release")
if action != "published" or not release:
return None
logger.info(f"GitHub release {release} {action!r} event.")
repo_namespace = nested_get(event, "repository", "owner", "login")
repo_name = nested_get(event, "repository", "name")
if not (repo_namespace and repo_name):
logger.warning("No full name of the repository.")
return None
release_ref = nested_get(event, "release", "tag_name")
if not release_ref:
logger.warning("Release tag name is not set.")
return None
logger.info(
f"New release event {release_ref!r} for repo {repo_namespace}/{repo_name}."
)
https_url = event["repository"]["html_url"]
return ReleaseEvent(repo_namespace, repo_name, release_ref, https_url)
@staticmethod
def parse_push_pagure_event(event) -> Optional[PushPagureEvent]:
"""this corresponds to dist-git event when someone pushes new commits"""
topic = event.get("topic")
if topic != "org.fedoraproject.prod.git.receive":
return None
logger.info(f"Dist-git commit event, topic: {topic}")
dg_repo_namespace = nested_get(event, "commit", "namespace")
dg_repo_name = nested_get(event, "commit", "repo")
if not (dg_repo_namespace and dg_repo_name):
logger.warning("No full name of the repository.")
return None
dg_branch = nested_get(event, "commit", "branch")
dg_commit = nested_get(event, "commit", "rev")
if not (dg_branch and dg_commit):
logger.warning("Target branch/rev for the new commits is not set.")
return None
username = nested_get(event, "commit", "username")
logger.info(
f"New commits added to dist-git repo {dg_repo_namespace}/{dg_repo_name},"
f"rev: {dg_commit}, branch: {dg_branch}"
)
dg_base_url = getenv("DISTGIT_URL", PROD_DISTGIT_URL)
dg_project_url = f"{dg_base_url}{dg_repo_namespace}/{dg_repo_name}"
return PushPagureEvent(
repo_namespace=dg_repo_namespace,
repo_name=dg_repo_name,
git_ref=dg_branch,
project_url=dg_project_url,
commit_sha=dg_commit,
committer=username,
)
@staticmethod
def parse_data_from_testing_farm(
tft_test_run: TFTTestRunTargetModel, event: Dict[Any, Any]
) -> Tuple[
str, str, TestingFarmResult, str, str, str, str, str, datetime, Optional[str]
]:
"""Parses common data from testing farm response.
Such common data is environment, os, summary and others.
Args:
tft_test_run (TFTTestRunTargetModel): Entry of the related test run in DB.
event (dict): Response from testing farm converted to a dict.
Returns:
tuple: project_url, ref, result, summary, copr_build_id,
copr_chroot, compose, log_url, identifier
"""
result: TestingFarmResult = TestingFarmResult(
nested_get(event, "result", "overall") or event.get("state") or "unknown"
)
summary: str = nested_get(event, "result", "summary") or ""
env: dict = nested_get(event, "environments_requested", 0, default={})
compose: str = nested_get(env, "os", "compose")
created: str = event.get("created")
identifier: Optional[str] = None
created_dt: Optional[datetime] = None
if created:
created_dt = datetime.fromisoformat(created)
created_dt = created_dt.replace(tzinfo=timezone.utc)
ref: str = nested_get(event, "test", "fmf", "ref")
fmf_url: str = nested_get(event, "test", "fmf", "url")
# ["test"]["fmf"]["ref"] contains ref to the TF test, i.e. "master",
# but we need the original commit_sha to be able to continue
if tft_test_run:
ref = tft_test_run.commit_sha
identifier = tft_test_run.identifier
if fmf_url == TESTING_FARM_INSTALLABILITY_TEST_URL:
# There are no artifacts in install-test results
copr_build_id = copr_chroot = ""
summary = {
TestingFarmResult.passed: "Installation passed",
TestingFarmResult.failed: "Installation failed",
}.get(result, summary)
else:
artifact: dict = nested_get(env, "artifacts", 0, default={})
a_type: str = artifact.get("type")
if a_type == "fedora-copr-build":
copr_build_id = artifact["id"].split(":")[0]
copr_chroot = artifact["id"].split(":")[1]
else:
logger.debug(f"{a_type} != fedora-copr-build")
copr_build_id = copr_chroot = ""
if not copr_chroot and tft_test_run:
copr_chroot = tft_test_run.target
# ["test"]["fmf"]["url"] contains PR's source/fork url or TF's install test url.
# We need the original/base project url stored in db.
if (
tft_test_run
and tft_test_run.data
and "base_project_url" in tft_test_run.data
):
project_url = tft_test_run.data["base_project_url"]
else:
project_url = (
fmf_url if fmf_url != TESTING_FARM_INSTALLABILITY_TEST_URL else None
)
log_url: str = nested_get(event, "run", "artifacts")
return (
project_url,
ref,
result,
summary,
copr_build_id,
copr_chroot,
compose,
log_url,
created_dt,
identifier,
)
@staticmethod
def parse_testing_farm_results_event(
event: dict,
) -> Optional[TestingFarmResultsEvent]:
"""this corresponds to testing farm results event"""
if event.get("source") != "testing-farm" or not event.get("request_id"):
return None