Debian Codegraph @

bin/ci/ci_run_n_monitor.py

raw
1 #!/usr/bin/env python3
2 # Copyright © 2020 - 2022 Collabora Ltd.
3 # Authors:
4 # Tomeu Vizoso <[email protected]>
5 # David Heidelberg <[email protected]>
6 #
7 # For the dependencies, see the requirements.txt
8 # SPDX-License-Identifier: MIT
9
10 """
11 Helper script to restrict running only required CI jobs
12 and show the job(s) logs.
13 """
14
15 import argparse
16 import re
17 import sys
18 import time
19 from collections import defaultdict, Counter
20 from concurrent.futures import ThreadPoolExecutor
21 from functools import partial
22 from itertools import chain
23 from subprocess import check_output, CalledProcessError
24 from typing import Callable, Dict, TYPE_CHECKING, Iterable, Literal, Optional, Tuple, cast
25
26 import gitlab
27 import gitlab.v4.objects
28 from gitlab_common import (
29 GITLAB_URL,
30 TOKEN_DIR,
31 get_gitlab_pipeline_from_url,
32 get_gitlab_project,
33 get_token_from_default_dir,
34 is_gitlab_job,
35 pretty_duration,
36 read_token,
37 wait_for_pipeline,
38 )
39 from gitlab_gql import GitlabGQL, create_job_needs_dag, filter_dag, print_dag, print_formatted_list
40 from rich.console import Console
41
42 if TYPE_CHECKING:
43 from gitlab_gql import Dag
44
45 REFRESH_WAIT_LOG = 10
46 REFRESH_WAIT_JOBS = 6
47 MAX_ENABLE_JOB_ATTEMPTS = 3
48
49 STATUS_COLORS = defaultdict(lambda: "", {
50 "running": "[blue]",
51 "success": "[green]",
52 "failed": "[red]",
53 "canceled": "[magenta]",
54 "canceling": "[magenta]",
55 })
56
57 COMPLETED_STATUSES = frozenset({"success", "failed"})
58 RUNNING_STATUSES = frozenset({"created", "pending", "running"})
59
60 if is_gitlab_job():
61 console = Console(highlight=False, no_color=False, color_system="truecolor", width=120)
62 else:
63 console = Console(highlight=False)
64 print = console.print
65
66
67 def print_job_status(
68 job: gitlab.v4.objects.ProjectPipelineJob,
69 new_status: bool = False,
70 ) -> None:
71 """It prints a nice, colored job status with a link to the job."""
72 if job.status in {"canceled", "canceling"}:
73 return
74
75 if new_status and job.status == "created":
76 return
77
78 global type_field_pad
79 global name_field_pad
80 jtype = "🞋 job"
81 job_name = job.name
82 type_field_pad = len(jtype) if len(jtype) > type_field_pad else type_field_pad
83 name_field_pad = len(job_name) if len(job_name) > name_field_pad else name_field_pad
84
85 duration = job_duration(job)
86
87 print(
88 f"{STATUS_COLORS[job.status]}"
89 f"{jtype:{type_field_pad}} " # U+1F78B Round target
90 f"{link2print(job.web_url, job.name, name_field_pad)} " +
91 (f" has new status: {job.status}" if new_status else f" {job.status}") +
92 (f" ({pretty_duration(duration)})" if job.started_at else "")
93 )
94
95
96 def job_duration(job: gitlab.v4.objects.ProjectPipelineJob) -> float:
97 """
98 Given a job, report the time lapsed in execution.
99 :param job: Pipeline job
100 :return: Current time in execution
101 """
102 if job.duration:
103 return job.duration
104 elif job.started_at:
105 # Convert both times to UTC timestamps for consistent comparison
106 current_time = time.time()
107 start_time = job.started_at.timestamp()
108 return current_time - start_time
109 return 0.0
110
111
112 def pretty_wait(sec: int) -> None:
113 """shows progressbar in dots"""
114 if is_gitlab_job():
115 time.sleep(sec)
116 return
117 for val in range(sec, 0, -1):
118 print(f"⏲ {val:2d} seconds", end="\r") # U+23F2 Timer clock
119 time.sleep(1)
120
121
122 def run_target_job(
123 job: gitlab.v4.objects.ProjectPipelineJob,
124 enable_job_fn: Callable,
125 stress: int,
126 execution_times: dict,
127 target_statuses: dict,
128 ) -> None:
129 execution_times[job.name][job.id] = (job_duration(job), job.status, job.web_url)
130 if stress and job.status in COMPLETED_STATUSES:
131 if (
132 stress < 0
133 or len(execution_times[job.name]) < stress
134 ):
135 enable_job_fn(job=job, action_type="retry")
136 # Wait for the next loop to get the updated job object
137 return
138 else:
139 enable_job_fn(job=job, action_type="target")
140
141 print_job_status(job, job.status not in target_statuses[job.name])
142 target_statuses[job.name] = job.status
143
144
145 def monitor_pipeline(
146 project: gitlab.v4.objects.Project,
147 pipeline: gitlab.v4.objects.ProjectPipeline,
148 job_filter: callable,
149 dependencies: set[str],
150 stress: int,
151 inhibit_single_target_trace: int = False,
152 polling_period: int = REFRESH_WAIT_JOBS,
153 ) -> tuple[Optional[int], Optional[int], Dict[str, Dict[int, Tuple[float, str, str]]]]:
154 """Monitors pipeline and delegate canceling jobs"""
155 statuses: dict[str, str] = defaultdict(str)
156 target_statuses: dict[str, str] = defaultdict(str)
157 execution_times: dict[str, dict[str, tuple[float, str, str]]] = defaultdict(lambda: defaultdict(tuple))
158 target_id: int = -1
159 global type_field_pad
160 type_field_pad = 0
161 global name_field_pad
162 name_field_pad = len(max(dependencies, key=len))+2
163 # In a running pipeline, we can skip following job traces that are in these statuses.
164 skip_follow_statuses: frozenset[str] = (COMPLETED_STATUSES)
165
166 # Pre-populate the stress status counter for already completed target jobs.
167 if stress:
168 # When stress test, it is necessary to collect this information before start.
169 for job in pipeline.jobs.list(all=True, include_retried=True):
170 if job_filter(
171 job_name=job.name,
172 job_stage=job.stage,
173 job_tags=job.tag_list,
174 ) and job.status in COMPLETED_STATUSES:
175 execution_times[job.name][job.id] = (job_duration(job), job.status, job.web_url)
176
177 # jobs_waiting is a list of job names that are waiting for status update.
178 # It occurs when a job that we want to run depends on another job that is not yet finished.
179 jobs_waiting = []
180 # Dictionary to track the number of attempts made for each job for a given status
181 enable_attempts: dict[tuple[int, str], int] = {}
182 # FIXME: This function has too many parameters, consider refactoring.
183 enable_job_fn = partial(
184 enable_job,
185 project=project,
186 enable_attempts=enable_attempts,
187 jobs_waiting=jobs_waiting,
188 )
189 while True:
190 deps_failed = []
191 to_cancel = []
192 jobs_waiting.clear()
193 for job in sorted(pipeline.jobs.list(all=True), key=lambda j: j.name):
194 job = cast(gitlab.v4.objects.ProjectPipelineJob, job)
195 if job_filter(
196 job_name=job.name,
197 job_stage=job.stage,
198 job_tags=job.tag_list,
199 ):
200 run_target_job(
201 job,
202 enable_job_fn,
203 stress,
204 execution_times,
205 target_statuses
206 )
207 target_id = job.id
208 continue
209 # all other non-target jobs
210 if job.status != statuses[job.name]:
211 print_job_status(job, True)
212 statuses[job.name] = job.status
213
214 # run dependencies and cancel the rest
215 if job.name in dependencies:
216 if not enable_job_fn(job=job, action_type="dep"):
217 # Wait for the next loop to get the updated job object
218 continue
219 if job.status == "failed":
220 deps_failed.append(job.name)
221 else:
222 to_cancel.append(job)
223
224 cancel_jobs(project, to_cancel)
225
226 if stress:
227 enough = True
228 status_counters = {
229 name: Counter(info[1] for info in runs.values())
230 for name, runs in execution_times.items()
231 }
232 for job_name, counter in sorted(status_counters.items()):
233 n_succeed = counter.get("success", 0)
234 n_failed = counter.get("failed", 0)
235 n_total_completed = n_succeed + n_failed
236 n_total_seen = len(execution_times[job_name])
237 print(
238 f"* {job_name:{name_field_pad}} succ: {n_succeed}; "
239 f"fail: {n_failed}; "
240 f"total: {n_total_seen} of {stress}",
241 )
242 if stress < 0 or n_total_completed < stress:
243 enough = False
244
245 if not enough:
246 pretty_wait(polling_period)
247 continue
248
249 if jobs_waiting:
250 print(f"[yellow]Waiting for jobs to update status:")
251 print_formatted_list(jobs_waiting, indentation=8, color="[yellow]")
252 pretty_wait(polling_period)
253 continue
254
255 if (
256 not inhibit_single_target_trace
257 and stress in [0, 1]
258 and len(target_statuses) == 1
259 and RUNNING_STATUSES.intersection(target_statuses.values())
260 ):
261 return target_id, None, execution_times
262
263 if (
264 {"failed"}.intersection(target_statuses.values())
265 and not RUNNING_STATUSES.intersection(target_statuses.values())
266 ):
267 return None, 1, execution_times
268
269 if (
270 {"skipped"}.intersection(target_statuses.values())
271 and not RUNNING_STATUSES.intersection(target_statuses.values())
272 ):
273 print(
274 f"[red]Target in skipped state, aborting. Failed dependencies:{deps_failed}"
275 )
276 return None, 1, execution_times
277
278 if skip_follow_statuses.issuperset(target_statuses.values()):
279 return None, 0, execution_times
280
281 pretty_wait(polling_period)
282
283
284 def enable_job(
285 project: gitlab.v4.objects.Project,
286 job: gitlab.v4.objects.ProjectPipelineJob,
287 enable_attempts: dict[tuple[int, str], int],
288 action_type: Literal["target", "dep", "retry"],
289 jobs_waiting: list[str] = list,
290 ) -> bool:
291 """
292 Enable a job to run.
293 :param project: The GitLab project.
294 :param job: The job to enable.
295 :param enable_attempts: A dictionary to track the number of attempts made for each job for a give status.
296 :param action_type: The type of action to perform.
297 :param jobs_waiting:
298 :return: True if the job was enabled, False otherwise.
299 """
300 # We want to run this job, but it is not ready to run yet, so let's try again in the next
301 # iteration.
302 if job.status == "created":
303 jobs_waiting.append(job.name)
304 return False
305
306 if (
307 (job.status in COMPLETED_STATUSES and action_type != "retry")
308 or job.status in {"skipped"} | RUNNING_STATUSES
309 ):
310 return False
311
312 # Get current attempt number
313 attempt_count = enable_attempts.get((job.id, job.status), 0)
314 # Check if we've exceeded max attempts to avoid infinite loop
315 if attempt_count == MAX_ENABLE_JOB_ATTEMPTS:
316 print(
317 f"[yellow]WARNING: "
318 f"Maximum enabling attempts ({MAX_ENABLE_JOB_ATTEMPTS}) reached for job {job.name} in {job.status} status"
319 f"({link2print(job.web_url, job.id)})."
320 )
321 enable_attempts[(job.id, job.status)] = attempt_count + 1
322 return False
323 elif attempt_count > MAX_ENABLE_JOB_ATTEMPTS:
324 return False
325
326 enable_attempts[(job.id, job.status)] = attempt_count + 1
327
328 pjob = project.jobs.get(job.id, lazy=True)
329
330 if job.status in {"success", "failed", "canceled", "canceling"}:
331 try:
332 pjob.retry()
333 except Exception as e:
334 print(f"Error retrying job {job.name}: {e}")
335 return False
336 else:
337 try:
338 pjob.play()
339 except Exception as e:
340 print(f"Error playing job {job.name}: {e}")
341 return False
342
343 if action_type == "target":
344 jtype = "🞋 target" # U+1F78B Round target
345 elif action_type == "retry":
346 jtype = "↻ retrying" # U+21BB Clockwise open circle arrow
347 else:
348 jtype = "↪ dependency" # U+21AA Left Arrow Curving Right
349
350 global type_field_pad
351 global name_field_pad
352 job_name = job.name
353 type_field_pad = len(jtype) if len(jtype) > type_field_pad else type_field_pad
354 name_field_pad = len(job_name) if len(job_name) > name_field_pad else name_field_pad
355 print(
356 f"[magenta]{jtype:{type_field_pad}} {job.name:{name_field_pad}} manually enabled"
357 )
358
359 return True
360
361
362 def cancel_job(
363 project: gitlab.v4.objects.Project,
364 pipeline_job: gitlab.v4.objects.ProjectPipelineJob
365 ) -> Optional[gitlab.v4.objects.ProjectPipelineJob]:
366 """
367 Cancel GitLab job
368 :param project: project from the pipeline job comes from
369 :param pipeline_job: job made from the pipeline list
370 :return the job object when cancel was called
371 """
372 if pipeline_job.status not in RUNNING_STATUSES:
373 return
374 try:
375 project_job = project.jobs.get(pipeline_job.id, lazy=True)
376 project_job.cancel()
377 except (gitlab.GitlabCancelError, gitlab.GitlabGetError):
378 # If the job failed to cancel, it will be retried in the monitor_pipeline() next iteration
379 return
380 return pipeline_job
381
382
383 def cancel_jobs(
384 project: gitlab.v4.objects.Project,
385 to_cancel: list[gitlab.v4.objects.ProjectPipelineJob]
386 ) -> None:
387 """
388 Cancel unwanted GitLab jobs
389 :param project: project from where the pipeline comes
390 :param to_cancel: list of jobs to be cancelled
391 """
392 if not to_cancel:
393 return
394
395 with ThreadPoolExecutor(max_workers=6) as exe:
396 part = partial(cancel_job, project)
397 maybe_cancelled_job = exe.map(part, to_cancel)
398 cancelled_jobs = [f"🗙 {job.name}" for job in maybe_cancelled_job if job] # U+1F5D9 Cancellation X
399
400 # The cancelled jobs are printed without a newline
401 if len(cancelled_jobs):
402 print(f"Cancelled {len(cancelled_jobs)} jobs:")
403 print_formatted_list(cancelled_jobs, indentation=8)
404
405
406 def print_log(
407 project: gitlab.v4.objects.Project,
408 job_id: int
409 ) -> None:
410 """Print job log into output"""
411 printed_lines = 0
412 while True:
413 job = project.jobs.get(job_id)
414
415 # GitLab's REST API doesn't offer pagination for logs, so we have to refetch it all
416 lines = job.trace().decode().splitlines()
417 for line in lines[printed_lines:]:
418 print(line, markup=False)
419 printed_lines = len(lines)
420
421 if job.status in COMPLETED_STATUSES:
422 print(f"[green]Job finished: {job.web_url}")
423 return
424 pretty_wait(REFRESH_WAIT_LOG)
425
426
427 def parse_args() -> argparse.Namespace:
428 """Parse args"""
429 parser = argparse.ArgumentParser(
430 description="Tool to trigger a subset of container jobs "
431 + "and monitor the progress of a test job",
432 epilog="Example: %(prog)s --rev $(git rev-parse HEAD) "
433 + '--target ".*traces" ',
434 )
435 parser.add_argument(
436 "--server",
437 metavar="gitlab-server",
438 type=str,
439 default=GITLAB_URL,
440 help=f"Specify the GitLab server work with (Default: {GITLAB_URL})",
441 )
442 parser.add_argument(
443 "--target",
444 metavar="target-job",
445 help="Target job regex. For multiple targets, pass multiple values, "
446 "eg. `--target foo bar`. Only jobs in the target stage(s) "
447 "supplied, and their dependencies, will be considered.",
448 required=True,
449 nargs=argparse.ONE_OR_MORE,
450 )
451 parser.add_argument(
452 "--include-stage",
453 metavar="include-stage",
454 help="Job stages to include when searching for target jobs. "
455 "For multiple targets, pass multiple values, eg. "
456 "`--include-stage foo bar`.",
457 default=[".*"],
458 nargs=argparse.ONE_OR_MORE,
459 )
460 parser.add_argument(
461 "--exclude-stage",
462 metavar="exclude-stage",
463 help="Job stages to exclude when searching for target jobs. "
464 "For multiple targets, pass multiple values, eg. "
465 "`--exclude-stage foo bar`. By default, performance and "
466 "nightly jobs are excluded; pass --exclude-stage '' to "
467 "include them for consideration.",
468 default=["performance", ".*-postmerge", ".*-nightly"],
469 nargs=argparse.ONE_OR_MORE,
470 )
471 parser.add_argument(
472 "--job-tags",
473 metavar="job-tags",
474 help="Job tags to require when searching for target jobs. If multiple "
475 "values are passed, eg. `--job-tags 'foo.*' 'bar'`, the job will "
476 "need to have a tag matching `foo.*` *and* a tag matching `bar` "
477 "to qualify. Passing `--job-tags '.*'` makes sure the job has "
478 "a tag defined, while not passing `--job-tags` also allows "
479 "untagged jobs.",
480 default=[],
481 nargs=argparse.ONE_OR_MORE,
482 )
483 parser.add_argument(
484 "--token",
485 metavar="token",
486 type=str,
487 default=get_token_from_default_dir(),
488 help="Use the provided GitLab token (with `api` scope) or token file, "
489 f"otherwise it's read from {TOKEN_DIR / 'gitlab-token'}",
490 )
491 parser.add_argument(
492 "--force-manual", action="store_true",
493 help="Deprecated argument; manual jobs are always force-enabled"
494 )
495 parser.add_argument(
496 "--stress",
497 metavar="n",
498 type=int,
499 default=0,
500 help="Stresstest job(s). Specify the number of times to rerun the selected jobs, "
501 "or use -1 for indefinite. Defaults to 0. If jobs have already been executed, "
502 "this will ensure the total run count respects the specified number.",
503 )
504 parser.add_argument(
505 "--project",
506 metavar="name",
507 type=str,
508 default="mesa",
509 help="GitLab project in the format <user>/<project> or just <project>",
510 )
511 parser.add_argument(
512 "--dry-run",
513 action="store_true",
514 help="Exit after printing target jobs and dependencies",
515 )
516 parser.add_argument(
517 "--no-job-log",
518 action="store_true",
519 help="When there is only one target job, inhibit the job trace output in the console.",
520 )
521 parser.add_argument(
522 "--polling-period",
523 type=int,
524 default=REFRESH_WAIT_JOBS,
525 help=f"Specify the waiting seconds between monitor loops. (Default: {REFRESH_WAIT_JOBS})",
526 )
527
528
529 mutex_group1 = parser.add_mutually_exclusive_group()
530 mutex_group1.add_argument(
531 "--rev",
532 metavar="id",
533 type=str,
534 default="HEAD",
535 help="Repository git commit-ish, tag or branch name (default: HEAD)",
536 )
537 mutex_group1.add_argument(
538 "--pipeline-url",
539 metavar="url",
540 type=str,
541 help="URL of the pipeline to use, instead of auto-detecting it.",
542 )
543 mutex_group1.add_argument(
544 "--mr",
545 metavar="id",
546 type=int,
547 help="ID of a merge request; the latest pipeline in that MR will be used.",
548 )
549
550 args = parser.parse_args()
551
552 # argparse doesn't support groups inside add_mutually_exclusive_group(),
553 # which means we can't just put `--project` and `--rev` in a group together,
554 # we have to do this by heand instead.
555 if args.pipeline_url and args.project != parser.get_default("project"):
556 # weird phrasing but it's the error add_mutually_exclusive_group() gives
557 parser.error("argument --project: not allowed with argument --pipeline-url")
558
559 return args
560
561
562 def print_detected_jobs(
563 target_dep_dag: "Dag",
564 dependency_jobs: Iterable[str],
565 target_jobs: Iterable[str],
566 ) -> None:
567 def print_job_set(color: str, kind: str, job_set: Iterable[str]):
568 job_list = list(job_set)
569 print(f"{color}Running {len(job_list)} {kind} jobs:")
570 print_formatted_list(job_list, indentation=8, color=color)
571
572 print("[yellow]Detected target job and its dependencies:")
573 print_dag(target_dep_dag, indentation=8, color="[yellow]")
574 print_job_set("[magenta]", "dependency", dependency_jobs)
575 print_job_set("[blue]", "target", target_jobs)
576
577
578 def find_dependencies(
579 server: str,
580 token: str | None,
581 job_filter: callable,
582 project_path: str,
583 iid: int
584 ) -> set[str]:
585 """
586 Find the dependencies of the target jobs in a GitLab pipeline.
587
588 This function uses the GitLab GraphQL API to fetch the job dependency graph
589 of a pipeline, filters the graph to only include the target jobs and their
590 dependencies, and returns the names of these jobs.
591
592 Args:
593 server (str): The url to the GitLab server.
594 token (str | None): The GitLab API token. If None, the API is accessed without
595 authentication.
596 target_jobs_regex (re.Pattern): A regex pattern to match the names of the target jobs.
597 project_path (str): The path of the GitLab project.
598 iid (int): The internal ID of the pipeline.
599
600 Returns:
601 set[str]: A set of the names of the target jobs and their dependencies.
602
603 Raises:
604 SystemExit: If no target jobs are found in the pipeline.
605 """
606 gql_instance = GitlabGQL(
607 url=f"{server}/api/graphql",
608 token=token
609 )
610 dag = create_job_needs_dag(
611 gql_instance, {"projectPath": project_path.path_with_namespace, "iid": iid}
612 )
613
614 target_dep_dag = filter_dag(dag, job_filter)
615 if not target_dep_dag:
616 print("[red]The job(s) were not found in the pipeline.")
617 sys.exit(1)
618
619 dependency_jobs = set(chain.from_iterable(d["needs"] for d in target_dep_dag.values()))
620 target_jobs = set(target_dep_dag.keys())
621 print_detected_jobs(target_dep_dag, dependency_jobs, target_jobs)
622 return target_jobs.union(dependency_jobs)
623
624
625 def print_monitor_summary(
626 execution_collection: Dict[str, Dict[int, Tuple[float, str, str]]],
627 t_start: float,
628 ) -> None:
629 """Summary of the test execution"""
630 t_end = time.perf_counter()
631 spend_minutes = (t_end - t_start) / 60
632 print(f"⏲ Duration of script execution: {spend_minutes:0.1f} minutes") # U+23F2 Timer clock
633 if len(execution_collection) == 0:
634 return
635 print(f"⏲ Jobs execution times:") # U+23F2 Timer clock
636 job_names = list(execution_collection.keys())
637 job_names.sort()
638 name_field_pad = len(max(job_names, key=len)) + 2
639 for name in job_names:
640 job_executions = execution_collection[name]
641 job_times = ', '.join([__job_duration_record(job_execution)
642 for job_execution in sorted(job_executions.items())])
643 print(f"* {name:{name_field_pad}}: ({len(job_executions)}) {job_times}")
644
645
646 def __job_duration_record(dict_item: tuple) -> str:
647 """
648 Format each pair of job and its duration.
649 :param job_execution: item of execution_collection[name][idn]: Dict[int, Tuple[float, str, str]]
650 """
651 job_id = f"{dict_item[0]}" # dictionary key
652 job_duration, job_status, job_url = dict_item[1] # dictionary value, the tuple
653 return (
654 f"{STATUS_COLORS[job_status]}"
655 f"{link2print(job_url, job_id)}: {pretty_duration(job_duration):>8}"
656 )
657
658
659 def link2print(url: str, text: str, text_pad: int = 0) -> str:
660 text = str(text)
661 text_pad = len(text) if text_pad < 1 else text_pad
662 if console.is_terminal:
663 return f"[link={url}]{text:{text_pad}}[/link]"
664 else:
665 return f"{text:{text_pad}}"
666
667
668 def main() -> None:
669 try:
670 t_start = time.perf_counter()
671
672 args = parse_args()
673
674 token = read_token(args.token)
675
676 gl = gitlab.Gitlab(url=args.server,
677 private_token=token,
678 retry_transient_errors=True)
679
680 REV: str = args.rev
681
682 if args.pipeline_url:
683 pipe, cur_project = get_gitlab_pipeline_from_url(gl, args.pipeline_url)
684 REV = pipe.sha
685 else:
686 mesa_project = gl.projects.get("mesa/mesa")
687 projects = [mesa_project]
688 if args.mr:
689 REV = mesa_project.mergerequests.get(args.mr).sha
690 else:
691 REV = check_output(['git', 'rev-parse', REV]).decode('ascii').strip()
692
693 if args.rev == 'HEAD':
694 try:
695 branch_name = check_output([
696 'git', 'symbolic-ref', '-q', 'HEAD',
697 ]).decode('ascii').strip()
698 except CalledProcessError:
699 branch_name = ""
700
701 # Ignore detached heads
702 if branch_name:
703 tracked_remote = check_output([
704 'git', 'for-each-ref', '--format=%(upstream)',
705 branch_name,
706 ]).decode('ascii').strip()
707
708 # Ignore local branches that do not track any remote
709 if tracked_remote:
710 remote_rev = check_output([
711 'git', 'rev-parse', tracked_remote,
712 ]).decode('ascii').strip()
713
714 if REV != remote_rev:
715 print(
716 f"Local HEAD commit {REV[:10]} is different than "
717 f"tracked remote HEAD commit {remote_rev[:10]}"
718 )
719 print("Did you forget to `git push` ?")
720
721 projects.append(get_gitlab_project(gl, args.project))
722 (pipe, cur_project) = wait_for_pipeline(projects, REV)
723
724 print(f"Revision: {REV}")
725 print(f"Pipeline: {pipe.web_url}")
726
727 target = '|'.join(args.target)
728 target = target.strip()
729
730 print(f"🞋 target job: [blue]{target}") # U+1F78B Round target
731
732 # Implicitly include `parallel:` jobs
733 target = f'({target})' + r'( \d+/\d+)?'
734
735 target_jobs_regex = re.compile(target)
736
737 include_stage = '|'.join(args.include_stage)
738 include_stage = include_stage.strip()
739
740 print(f"🞋 target from stages: [blue]{include_stage}") # U+1F78B Round target
741
742 include_stage_regex = re.compile(include_stage)
743
744 exclude_stage = '|'.join(args.exclude_stage)
745 exclude_stage = exclude_stage.strip()
746
747 print(f"🞋 target excluding stages: [blue]{exclude_stage}") # U+1F78B Round target
748
749 exclude_stage_regex = re.compile(exclude_stage)
750
751 print(f"🞋 target jobs with tags: [blue]{str(args.job_tags)}") # U+1F78B Round target
752 job_tags_regexes = [re.compile(job_tag) for job_tag in args.job_tags]
753
754 def job_filter(
755 job_name: str,
756 job_stage: str,
757 job_tags: set[str],
758 ) -> bool:
759 """
760 Apply user-specified filters to a job, and return whether the
761 filters allow that job (True) or not (False).
762 """
763 if not target_jobs_regex.fullmatch(job_name):
764 return False
765 if not include_stage_regex.fullmatch(job_stage):
766 return False
767 if exclude_stage_regex.fullmatch(job_stage):
768 return False
769 if not all(
770 any(job_tags_regex.fullmatch(tag) for tag in job_tags)
771 for job_tags_regex in job_tags_regexes
772 ):
773 return False
774 return True
775
776 deps = find_dependencies(
777 server=args.server,
778 token=token,
779 job_filter=job_filter,
780 iid=pipe.iid,
781 project_path=cur_project
782 )
783
784 if args.dry_run:
785 sys.exit(0)
786
787 target_job_id, ret, exec_t = monitor_pipeline(
788 cur_project,
789 pipe,
790 job_filter,
791 deps,
792 args.stress,
793 args.no_job_log,
794 args.polling_period,
795 )
796
797 if target_job_id:
798 print_log(cur_project, target_job_id)
799
800 print_monitor_summary(exec_t, t_start)
801
802 sys.exit(ret)
803 except KeyboardInterrupt:
804 sys.exit(1)
805
806
807 if __name__ == "__main__":
808 main()