Debian Codegraph @

bin/ci/gitlab_gql.py

raw
1 #!/usr/bin/env python3
2 # For the dependencies, see the requirements.txt
3
4 import logging
5 import re
6 import sys
7 import traceback
8 from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, Namespace
9 from collections import OrderedDict
10 from copy import deepcopy
11 from dataclasses import dataclass, field
12 from itertools import accumulate
13 from os import get_terminal_size, getenv
14 from pathlib import Path
15 from subprocess import check_output
16 from textwrap import dedent
17 from typing import Any, Iterable, Optional, TypedDict, Union
18
19 import yaml
20 from filecache import DAY, filecache
21 from gitlab_common import get_token_from_default_dir, is_gitlab_job
22 from gql import Client, gql
23 from gql.transport.requests import RequestsHTTPTransport
24 from graphql import DocumentNode
25 from rich.console import Console
26
27 DEFAULT_TERMINAL_SIZE: int = 80 # columns
28
29
30 class DagNode(TypedDict):
31 needs: set[str]
32 stage: str
33 tags: set[str]
34 # `name` is redundant but is here for retro-compatibility
35 name: str
36
37
38 # see create_job_needs_dag function for more details
39 Dag = dict[str, DagNode]
40
41
42 StageSeq = OrderedDict[str, set[str]]
43
44 if is_gitlab_job():
45 console = Console(highlight=False, no_color=False, color_system="truecolor", width=120)
46 else:
47 console = Console(highlight=False)
48 print = console.print
49
50
51 def get_project_root_dir():
52 root_path = Path(__file__).parent.parent.parent.resolve()
53 gitlab_file = root_path / ".gitlab-ci.yml"
54 assert gitlab_file.exists()
55
56 return root_path
57
58
59 @dataclass
60 class GitlabGQL:
61 _transport: Any = field(init=False)
62 client: Client = field(init=False)
63 url: str = "https://gitlab.freedesktop.org/api/graphql"
64 token: Optional[str] = None
65
66 def __post_init__(self) -> None:
67 self._setup_gitlab_gql_client()
68
69 def _setup_gitlab_gql_client(self) -> None:
70 # Select your transport with a defined url endpoint
71 headers = {}
72 if self.token:
73 headers["Authorization"] = f"Bearer {self.token}"
74 self._transport = RequestsHTTPTransport(url=self.url, headers=headers)
75
76 # Create a GraphQL client using the defined transport
77 self.client = Client(transport=self._transport, fetch_schema_from_transport=True)
78
79 def query(
80 self,
81 gql_file: Union[Path, str],
82 params: dict[str, Any] = {},
83 operation_name: Optional[str] = None,
84 paginated_key_loc: Iterable[str] = [],
85 disable_cache: bool = False,
86 ) -> dict[str, Any]:
87 def run_uncached() -> dict[str, Any]:
88 if paginated_key_loc:
89 return self._sweep_pages(gql_file, params, operation_name, paginated_key_loc)
90 return self._query(gql_file, params, operation_name)
91
92 if disable_cache:
93 return run_uncached()
94
95 try:
96 # Create an auxiliary variable to deliver a cached result and enable catching exceptions
97 # Decorate the query to be cached
98 if paginated_key_loc:
99 result = self._sweep_pages_cached(
100 gql_file, params, operation_name, paginated_key_loc
101 )
102 else:
103 result = self._query_cached(gql_file, params, operation_name)
104 return result # type: ignore
105 except Exception as ex:
106 logging.error(f"Cached query failed with {ex}")
107 # print exception traceback
108 traceback_str = "".join(traceback.format_exception(ex))
109 logging.error(traceback_str)
110 self.invalidate_query_cache()
111 logging.error("Cache invalidated, retrying without cache")
112 return run_uncached()
113
114 def _query(
115 self,
116 gql_file: Union[Path, str],
117 params: dict[str, Any] = {},
118 operation_name: Optional[str] = None,
119 ) -> dict[str, Any]:
120 # Provide a GraphQL query
121 source_path: Path = Path(__file__).parent
122 pipeline_query_file: Path = source_path / gql_file
123
124 query: DocumentNode
125 with open(pipeline_query_file, "r") as f:
126 pipeline_query = f.read()
127 query = gql(pipeline_query)
128
129 # Execute the query on the transport
130 return self.client.execute_sync(
131 query, variable_values=params, operation_name=operation_name
132 )
133
134 @filecache(DAY)
135 def _sweep_pages_cached(self, *args, **kwargs):
136 return self._sweep_pages(*args, **kwargs)
137
138 @filecache(DAY)
139 def _query_cached(self, *args, **kwargs):
140 return self._query(*args, **kwargs)
141
142 def _sweep_pages(
143 self, query, params, operation_name=None, paginated_key_loc: Iterable[str] = []
144 ) -> dict[str, Any]:
145 """
146 Retrieve paginated data from a GraphQL API and concatenate the results into a single
147 response.
148
149 Args:
150 query: represents a filepath with the GraphQL query to be executed.
151 params: a dictionary that contains the parameters to be passed to the query. These
152 parameters can be used to filter or modify the results of the query.
153 operation_name: The `operation_name` parameter is an optional parameter that specifies
154 the name of the GraphQL operation to be executed. It is used when making a GraphQL
155 query to specify which operation to execute if there are multiple operations defined
156 in the GraphQL schema. If not provided, the default operation will be executed.
157 paginated_key_loc (Iterable[str]): The `paginated_key_loc` parameter is an iterable of
158 strings that represents the location of the paginated field within the response. It
159 is used to extract the paginated field from the response and append it to the final
160 result. The node has to be a list of objects with a `pageInfo` field that contains
161 at least the `hasNextPage` and `endCursor` fields.
162
163 Returns:
164 a dictionary containing the response from the query with the paginated field
165 concatenated.
166 """
167
168 def fetch_page(cursor: str | None = None) -> dict[str, Any]:
169 if cursor:
170 params["cursor"] = cursor
171 logging.info(
172 f"Found more than 100 elements, paginating. "
173 f"Current cursor at {cursor}"
174 )
175
176 return self._query(query, params, operation_name)
177
178 # Execute the initial query
179 response: dict[str, Any] = fetch_page()
180
181 # Initialize an empty list to store the final result
182 final_partial_field: list[dict[str, Any]] = []
183
184 # Loop until all pages have been retrieved
185 while True:
186 # Get the partial field to be appended to the final result
187 partial_field = response
188 for key in paginated_key_loc:
189 partial_field = partial_field[key]
190
191 # Append the partial field to the final result
192 final_partial_field += partial_field["nodes"]
193
194 # Check if there are more pages to retrieve
195 page_info = partial_field["pageInfo"]
196 if not page_info["hasNextPage"]:
197 break
198
199 # Execute the query with the updated cursor parameter
200 response = fetch_page(page_info["endCursor"])
201
202 # Replace the "nodes" field in the original response with the final result
203 partial_field["nodes"] = final_partial_field
204 return response
205
206 def invalidate_query_cache(self) -> None:
207 logging.warning("Invalidating query cache")
208 try:
209 self._sweep_pages._db.clear()
210 self._query._db.clear()
211 except AttributeError as ex:
212 logging.warning(f"Could not invalidate cache, maybe it was not used in {ex.args}?")
213
214
215 def insert_early_stage_jobs(stage_sequence: StageSeq, jobs_metadata: Dag) -> Dag:
216 pre_processed_dag: dict[str, set[str]] = {}
217 jobs_from_early_stages = list(accumulate(stage_sequence.values(), set.union))
218 for job_name, metadata in jobs_metadata.items():
219 final_needs: set[str] = deepcopy(metadata["needs"])
220 # Pre-process jobs that are not based on needs field
221 # e.g. sanity job in mesa MR pipelines
222 if not final_needs:
223 job_stage: str = jobs_metadata[job_name]["stage"]
224 stage_index: int = list(stage_sequence.keys()).index(job_stage)
225 if stage_index > 0:
226 final_needs |= jobs_from_early_stages[stage_index - 1]
227 pre_processed_dag[job_name] = final_needs
228
229 for job_name, needs in pre_processed_dag.items():
230 jobs_metadata[job_name]["needs"] = needs
231
232 return jobs_metadata
233
234
235 def traverse_dag_needs(jobs_metadata: Dag) -> None:
236 created_jobs = set(jobs_metadata.keys())
237 for job, metadata in jobs_metadata.items():
238 final_needs: set = deepcopy(metadata["needs"]) & created_jobs
239 # Post process jobs that are based on needs field
240 partial = True
241
242 while partial:
243 next_depth: set[str] = {n for dn in final_needs if dn in jobs_metadata for n in jobs_metadata[dn]["needs"]}
244 partial: bool = not final_needs.issuperset(next_depth)
245 final_needs = final_needs.union(next_depth)
246
247 jobs_metadata[job]["needs"] = final_needs
248
249
250 def extract_stages_and_job_needs(
251 pipeline_jobs: dict[str, Any], pipeline_stages: dict[str, Any]
252 ) -> tuple[StageSeq, Dag]:
253 jobs_metadata = Dag()
254 # Record the stage sequence to post process deps that are not based on needs
255 # field, for example: sanity job
256 stage_sequence: OrderedDict[str, set[str]] = OrderedDict()
257 for stage in pipeline_stages["nodes"]:
258 stage_sequence[stage["name"]] = set()
259
260 for job in pipeline_jobs["nodes"]:
261 stage_sequence[job["stage"]["name"]].add(job["name"])
262 dag_job: DagNode = {
263 "name": job["name"],
264 "tags": set(job["tags"] or []), # jobs with no tags defined return None here
265 "stage": job["stage"]["name"],
266 "needs": set([j["node"]["name"] for j in job["needs"]["edges"]]),
267 }
268 jobs_metadata[job["name"]] = dag_job
269
270 return stage_sequence, jobs_metadata
271
272
273 def create_job_needs_dag(gl_gql: GitlabGQL, params, disable_cache: bool = True) -> Dag:
274 """
275 This function creates a Directed Acyclic Graph (DAG) to represent a sequence of jobs, where each
276 job has a set of jobs that it depends on (its "needs") and belongs to a certain "stage".
277 The "name" of the job is used as the key in the dictionary.
278
279 For example, consider the following DAG:
280
281 1. build stage: job1 -> job2 -> job3
282 2. test stage: job2 -> job4
283
284 - The job needs for job3 are: job1, job2
285 - The job needs for job4 are: job2
286 - The job2 needs to wait all jobs from build stage to finish.
287
288 The resulting DAG would look like this:
289
290 dag = {
291 "job1": {"needs": set(), "stage": "build", "name": "job1"},
292 "job2": {"needs": {"job1", "job2", job3"}, "stage": "test", "name": "job2"},
293 "job3": {"needs": {"job1", "job2"}, "stage": "build", "name": "job3"},
294 "job4": {"needs": {"job2"}, "stage": "test", "name": "job4"},
295 }
296
297 To access the job needs, one can do:
298
299 dag["job3"]["needs"]
300
301 This will return the set of jobs that job3 needs: {"job1", "job2"}
302
303 Args:
304 gl_gql (GitlabGQL): The `gl_gql` parameter is an instance of the `GitlabGQL` class, which is
305 used to make GraphQL queries to the GitLab API.
306 params (dict): The `params` parameter is a dictionary that contains the necessary parameters
307 for the GraphQL query. It is used to specify the details of the pipeline for which the
308 job needs DAG is being created.
309 The specific keys and values in the `params` dictionary will depend on
310 the requirements of the GraphQL query being executed
311 disable_cache (bool): The `disable_cache` parameter is a boolean that specifies whether the
312
313 Returns:
314 The final DAG (Directed Acyclic Graph) representing the job dependencies sourced from needs
315 or stages rule.
316 """
317 stages_jobs_gql = gl_gql.query(
318 "pipeline_details.gql",
319 params=params,
320 paginated_key_loc=["project", "pipeline", "jobs"],
321 disable_cache=disable_cache,
322 )
323 pipeline_data = stages_jobs_gql["project"]["pipeline"]
324 if not pipeline_data:
325 raise RuntimeError(f"Could not find any pipelines for {params}")
326
327 stage_sequence, jobs_metadata = extract_stages_and_job_needs(
328 pipeline_data["jobs"], pipeline_data["stages"]
329 )
330 # Fill the DAG with the job needs from stages that don't have any needs but still need to wait
331 # for previous stages
332 final_dag = insert_early_stage_jobs(stage_sequence, jobs_metadata)
333 # Now that each job has its direct needs filled correctly, update the "needs" field for each job
334 # in the DAG by performing a topological traversal
335 traverse_dag_needs(final_dag)
336
337 return final_dag
338
339
340 def filter_dag(dag: Dag, job_filter: callable) -> Dag:
341 return Dag({
342 job: data
343 for job, data in dag.items()
344 if job_filter(
345 job_name=job,
346 job_stage=data["stage"],
347 job_tags=data["tags"],
348 )
349 })
350
351
352 def print_dag(dag: Dag, indentation: int = 0, color: str = "") -> None:
353 for job, data in sorted(dag.items()):
354 print(f"{color}{' '*indentation}{job}:")
355 print_formatted_list(list(data['needs']), indentation=indentation+8, color=color)
356
357
358 def print_formatted_list(elements: list[str], indentation: int = 0, color: str = "") -> None:
359 """
360 When a list of elements is going to be printed, if it is longer than one line, reformat it to be multiple
361 lines with a 'ls' command style.
362 :param elements: list of elements to be printed
363 :param indentation: number of spaces to be injected in front of each line
364 """
365 if len(elements) == 0:
366 return
367 elements.sort()
368 try:
369 h_size = get_terminal_size().columns if sys.stdin.isatty() else DEFAULT_TERMINAL_SIZE
370 except OSError:
371 h_size = DEFAULT_TERMINAL_SIZE
372 if indentation + sum(len(element) for element in elements) + (len(elements)*2) < h_size: # fits in one line
373 print(f"{color}{' '*indentation}{', '.join([element for element in elements])}")
374 return
375 column_separator_size = 2
376 column_width: int = len(max(elements, key=len)) + column_separator_size
377 n_columns: int = max((h_size - indentation) // column_width, 1)
378 step = (len(elements) // n_columns) + 1
379 rows = [elements[i::step] for i in range(step)]
380 for line in rows:
381 print(' '*indentation, end='')
382 for column in range(len(line)):
383 if line[column] is not None:
384 print(f"{color}{line[column]:<{column_width}}", end='')
385 print()
386
387
388 def fetch_merged_yaml(gl_gql: GitlabGQL, params) -> dict[str, Any]:
389 params["content"] = dedent("""\
390 include:
391 - local: .gitlab-ci.yml
392 """)
393 raw_response = gl_gql.query("job_details.gql", params)
394 ci_config = raw_response["ciConfig"]
395 if merged_yaml := ci_config["mergedYaml"]:
396 return yaml.safe_load(merged_yaml)
397 if "errors" in ci_config:
398 for error in ci_config["errors"]:
399 print(error)
400
401 gl_gql.invalidate_query_cache()
402 raise ValueError(
403 """
404 Could not fetch any content for merged YAML,
405 please verify if the git SHA exists in remote.
406 Maybe you forgot to `git push`? """
407 )
408
409
410 def recursive_fill(job, relationship_field, target_data, acc_data: dict, merged_yaml):
411 if relatives := job.get(relationship_field):
412 if isinstance(relatives, str):
413 relatives = [relatives]
414
415 for relative in relatives:
416 parent_job = merged_yaml[relative]
417 acc_data = recursive_fill(parent_job, acc_data, merged_yaml) # type: ignore
418
419 acc_data |= job.get(target_data, {})
420
421 return acc_data
422
423
424 def get_variables(job, merged_yaml, project_path, sha) -> dict[str, str]:
425 p = get_project_root_dir() / ".gitlab-ci" / "image-tags.yml"
426 image_tags = yaml.safe_load(p.read_text())
427
428 variables = image_tags["variables"]
429 variables |= merged_yaml["variables"]
430 variables |= job["variables"]
431 variables["CI_PROJECT_PATH"] = project_path
432 variables["CI_PROJECT_NAME"] = project_path.split("/")[1]
433 variables["CI_REGISTRY_IMAGE"] = "registry.freedesktop.org/${CI_PROJECT_PATH}"
434 variables["CI_COMMIT_SHA"] = sha
435
436 while recurse_among_variables_space(variables):
437 pass
438
439 return variables
440
441
442 # Based on: https://stackoverflow.com/a/2158532/1079223
443 def flatten(xs):
444 for x in xs:
445 if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
446 yield from flatten(x)
447 else:
448 yield x
449
450
451 def get_full_script(job) -> list[str]:
452 script = []
453 for script_part in ("before_script", "script", "after_script"):
454 script.append(f"# {script_part}")
455 lines = flatten(job.get(script_part, []))
456 script.extend(lines)
457 script.append("")
458
459 return script
460
461
462 def recurse_among_variables_space(var_graph) -> bool:
463 updated = False
464 for var, value in var_graph.items():
465 value = str(value)
466 dep_vars = []
467 if match := re.findall(r"(\$[{]?[\w\d_]*[}]?)", value):
468 all_dep_vars = [v.lstrip("${").rstrip("}") for v in match]
469 # print(value, match, all_dep_vars)
470 dep_vars = [v for v in all_dep_vars if v in var_graph]
471
472 for dep_var in dep_vars:
473 dep_value = str(var_graph[dep_var])
474 new_value = var_graph[var]
475 new_value = new_value.replace(f"${{{dep_var}}}", dep_value)
476 new_value = new_value.replace(f"${dep_var}", dep_value)
477 var_graph[var] = new_value
478 updated |= dep_value != new_value
479
480 return updated
481
482
483 def print_job_final_definition(job_name, merged_yaml, project_path, sha):
484 job = merged_yaml[job_name]
485 variables = get_variables(job, merged_yaml, project_path, sha)
486
487 print("# --------- variables ---------------")
488 for var, value in sorted(variables.items()):
489 print(f"export {var}={value!r}")
490
491 # TODO: Recurse into needs to get full script
492 # TODO: maybe create a extra yaml file to avoid too much rework
493 script = get_full_script(job)
494 print()
495 print()
496 print("# --------- full script ---------------")
497 print("\n".join(script))
498
499 if image := variables.get("MESA_IMAGE"):
500 print()
501 print()
502 print("# --------- container image ---------------")
503 print(image)
504
505
506 def from_sha_to_pipeline_iid(gl_gql: GitlabGQL, params) -> str:
507 result = gl_gql.query("pipeline_utils.gql", params)
508
509 return result["project"]["pipelines"]["nodes"][0]["iid"]
510
511
512 def parse_args() -> Namespace:
513 parser = ArgumentParser(
514 formatter_class=ArgumentDefaultsHelpFormatter,
515 description="CLI and library with utility functions to debug jobs via Gitlab GraphQL",
516 epilog=f"""Example:
517 {Path(__file__).name} --print-dag""",
518 )
519 parser.add_argument("-pp", "--project-path", type=str, default="mesa/mesa")
520 parser.add_argument("--sha", "--rev", type=str, default='HEAD')
521 parser.add_argument(
522 "--regex",
523 type=str,
524 required=False,
525 default=".*",
526 help="Regex pattern for the job name to be considered",
527 )
528 parser.add_argument(
529 "--include-stage",
530 type=str,
531 required=False,
532 default=".*",
533 help="Regex pattern for the stage name to be considered",
534 )
535 parser.add_argument(
536 "--exclude-stage",
537 type=str,
538 required=False,
539 default="^$",
540 help="Regex pattern for the stage name to be excluded",
541 )
542 parser.add_argument(
543 "--job-tags",
544 metavar="job-tags",
545 help="Job tags to require when searching for target jobs. If multiple "
546 "values are passed, eg. `--job-tags 'foo.*' 'bar'`, the job will "
547 "need to have a tag matching `foo.*` *and* a tag matching `bar` "
548 "to qualify. Passing `--job-tags '.*'` makes sure the job has "
549 "a tag defined, while not passing `--job-tags` also allows "
550 "untagged jobs.",
551 default=[],
552 nargs='+',
553 )
554 mutex_group_print = parser.add_mutually_exclusive_group()
555 mutex_group_print.add_argument(
556 "--print-dag",
557 action="store_true",
558 help="Print job needs DAG",
559 )
560 mutex_group_print.add_argument(
561 "--print-merged-yaml",
562 action="store_true",
563 help="Print the resulting YAML for the specific SHA",
564 )
565 mutex_group_print.add_argument(
566 "--print-job-manifest",
567 metavar='JOB_NAME',
568 type=str,
569 help="Print the resulting job data"
570 )
571 parser.add_argument(
572 "--gitlab-token-file",
573 type=str,
574 default=get_token_from_default_dir(),
575 help="force GitLab token, otherwise it's read from $XDG_CONFIG_HOME/gitlab-token",
576 )
577
578 args = parser.parse_args()
579 args.gitlab_token = Path(args.gitlab_token_file).read_text().strip()
580 return args
581
582
583 def main():
584 args = parse_args()
585 gl_gql = GitlabGQL(token=args.gitlab_token)
586
587 sha = check_output(['git', 'rev-parse', args.sha]).decode('ascii').strip()
588
589 if args.print_dag:
590 iid = from_sha_to_pipeline_iid(gl_gql, {"projectPath": args.project_path, "sha": sha})
591 dag = create_job_needs_dag(
592 gl_gql, {"projectPath": args.project_path, "iid": iid}, disable_cache=True
593 )
594
595 job_name_regex = re.compile(args.regex)
596 include_stage_regex = re.compile(args.include_stage)
597 exclude_stage_regex = re.compile(args.exclude_stage)
598 job_tags_regexes = [re.compile(job_tag) for job_tag in args.job_tags]
599
600 def job_filter(
601 job_name: str,
602 job_stage: str,
603 job_tags: set[str],
604 ) -> bool:
605 """
606 Apply user-specified filters to a job, and return whether the
607 filters allow that job (True) or not (False).
608 """
609 if not job_name_regex.fullmatch(job_name):
610 return False
611 if not include_stage_regex.fullmatch(job_stage):
612 return False
613 if exclude_stage_regex.fullmatch(job_stage):
614 return False
615 if not all(
616 any(job_tags_regex.fullmatch(tag) for tag in job_tags)
617 for job_tags_regex in job_tags_regexes
618 ):
619 return False
620 return True
621
622 dag = filter_dag(dag, job_filter)
623
624 print_dag(dag)
625
626 if args.print_merged_yaml or args.print_job_manifest:
627 merged_yaml = fetch_merged_yaml(
628 gl_gql, {"projectPath": args.project_path, "sha": sha}
629 )
630
631 if args.print_merged_yaml:
632 print(yaml.dump(merged_yaml, indent=2))
633
634 if args.print_job_manifest:
635 print_job_final_definition(
636 args.print_job_manifest, merged_yaml, args.project_path, sha
637 )
638
639
640 if __name__ == "__main__":
641 main()