| 1 |
#!/usr/bin/env python3 |
| 2 |
import logging |
| 3 |
import os |
| 4 |
import re |
| 5 |
import sys |
| 6 |
import argparse |
| 7 |
import subprocess |
| 8 |
import yaml |
| 9 |
from typing import Optional, Set, Any |
| 10 |
from dataclasses import dataclass, field |
| 11 |
|
| 12 |
from datetime import datetime, timezone |
| 13 |
from pathlib import Path |
| 14 |
|
| 15 |
|
| 16 |
# Very simple type alias for GitLab YAML data structure |
| 17 |
# It is composed by a dictionary of job names, each with a dictionary of fields |
| 18 |
# (e.g., script, stage, rules, etc.) |
| 19 |
YamlData = dict[str, dict[str, Any]] |
| 20 |
|
| 21 |
# Dummy environment vars to make build scripts happy |
| 22 |
# To avoid set -u errors in build scripts |
| 23 |
DUMMY_ENV_VARS: dict[str, str] = { |
| 24 |
# setup-test-env.sh |
| 25 |
"CI_JOB_STARTED_AT": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S%z"), |
| 26 |
# build-deqp.sh |
| 27 |
"DEQP_API": "dummy", |
| 28 |
"DEQP_TARGET": "dummy", |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
@dataclass |
| 33 |
class ProjectPaths: |
| 34 |
"""Manages all project-related paths""" |
| 35 |
|
| 36 |
root: Path = field(default_factory=lambda: Path(), init=False) |
| 37 |
setup_test_env: Path = field(default_factory=lambda: Path(), init=False) |
| 38 |
conditional_tags: Path = field(default_factory=lambda: Path(), init=False) |
| 39 |
container_dir: Path = field(default_factory=lambda: Path(), init=False) |
| 40 |
container_ci: Path = field(default_factory=lambda: Path(), init=False) |
| 41 |
|
| 42 |
def __post_init__(self): |
| 43 |
self.root = self.find_root() |
| 44 |
self.setup_test_env = self.root / ".gitlab-ci" / "setup-test-env.sh" |
| 45 |
self.conditional_tags = self.root / ".gitlab-ci" / "conditional-build-image-tags.yml" |
| 46 |
self.container_dir = self.root / ".gitlab-ci" / "container" |
| 47 |
self.container_ci = self.container_dir / "gitlab-ci-inc.yml" |
| 48 |
|
| 49 |
def find_root(self) -> Path: |
| 50 |
"""Find git repository root or fallback to other methods""" |
| 51 |
try: |
| 52 |
logging.debug("Getting git repo root using git rev-parse") |
| 53 |
return Path( |
| 54 |
subprocess.check_output( |
| 55 |
["git", "rev-parse", "--show-toplevel"], |
| 56 |
text=True, |
| 57 |
stderr=subprocess.PIPE, |
| 58 |
).strip() |
| 59 |
) |
| 60 |
# FileNotFoundError is raised if git is not installed |
| 61 |
except (subprocess.CalledProcessError, FileNotFoundError): |
| 62 |
# Fallback to CI_PROJECT_DIR or path-based method |
| 63 |
if ci_dir := os.environ.get("CI_PROJECT_DIR"): |
| 64 |
logging.debug(f"Getting git repo root using CI_PROJECT_DIR: {ci_dir}") |
| 65 |
return Path(ci_dir) |
| 66 |
|
| 67 |
# Last resort, use the path to this script |
| 68 |
logging.debug("Getting git repo root using path to this script") |
| 69 |
return Path(__file__).resolve().parent.parent.parent |
| 70 |
|
| 71 |
|
| 72 |
PATHS: ProjectPaths = ProjectPaths() |
| 73 |
|
| 74 |
|
| 75 |
def from_component_to_build_tag(component: str) -> str: |
| 76 |
# e.g., "angle" -> "CONDITIONAL_BUILD_ANGLE_TAG" |
| 77 |
return "CONDITIONAL_BUILD_" + re.sub(r"-", "_", component.upper()) + "_TAG" |
| 78 |
|
| 79 |
|
| 80 |
def from_component_to_tag_var(component: str) -> str: |
| 81 |
# e.g., "angle" -> "ANGLE_TAG" |
| 82 |
return re.sub(r"-", "_", component.upper()) + "_TAG" |
| 83 |
|
| 84 |
|
| 85 |
def from_script_name_to_component(script_name: str) -> str: |
| 86 |
# e.g., "build-angle.sh" -> "angle" |
| 87 |
return re.sub(r"^build-([a-z0-9_-]+)\.sh$", r"\1", script_name) |
| 88 |
|
| 89 |
|
| 90 |
def from_script_name_to_tag_var(script_name: str) -> str: |
| 91 |
# e.g., "build-angle.sh" -> "ANGLE_TAG" |
| 92 |
return re.sub(r"^build-([a-z0-9_-]+)\.sh$", r"\1_TAG", script_name).replace("-", "_").upper() |
| 93 |
|
| 94 |
|
| 95 |
def prepare_setup_env_script() -> Path: |
| 96 |
""" |
| 97 |
Sets up dummy environment variables to mimic the script in the CI repo. |
| 98 |
Returns the path to the setup-test-env.sh script. |
| 99 |
""" |
| 100 |
if not PATHS.setup_test_env.exists(): |
| 101 |
logging.error(".gitlab-ci/setup-test-env.sh not found. Exiting.") |
| 102 |
sys.exit(1) |
| 103 |
|
| 104 |
# Dummy environment vars to mimic the script |
| 105 |
for key, value in DUMMY_ENV_VARS.items(): |
| 106 |
os.environ[key] = value |
| 107 |
|
| 108 |
os.environ["CI_PROJECT_DIR"] = str(PATHS.root) |
| 109 |
|
| 110 |
return PATHS.setup_test_env |
| 111 |
|
| 112 |
|
| 113 |
def validate_build_script(script_filename: str) -> bool: |
| 114 |
""" |
| 115 |
Returns True if the build script for the given component uses the structured tag variable. |
| 116 |
""" |
| 117 |
build_script = PATHS.container_dir / script_filename |
| 118 |
with open(build_script, "r", encoding="utf-8") as f: |
| 119 |
script_content = f.read() |
| 120 |
|
| 121 |
tag_var = from_script_name_to_tag_var(script_filename) |
| 122 |
if not re.search(tag_var, script_content, re.IGNORECASE): |
| 123 |
logging.debug( |
| 124 |
f"Skipping {build_script} because it doesn't use {tag_var}", |
| 125 |
) |
| 126 |
return False |
| 127 |
return True |
| 128 |
|
| 129 |
|
| 130 |
def load_container_yaml() -> YamlData: |
| 131 |
if not PATHS.container_ci.is_file(): |
| 132 |
logging.error(f"File not found: {PATHS.container_ci}") |
| 133 |
sys.exit(1) |
| 134 |
|
| 135 |
# Ignore !reference and other custom GitLab tags, we just want to know the |
| 136 |
# job names and fields |
| 137 |
yaml.SafeLoader.add_multi_constructor("", lambda loader, suffix, node: None) |
| 138 |
with open(str(PATHS.container_ci), "r", encoding="utf-8") as f: |
| 139 |
data = yaml.load(f, Loader=yaml.SafeLoader) |
| 140 |
if not isinstance(data, dict): |
| 141 |
return {"variables": {}} |
| 142 |
return data |
| 143 |
|
| 144 |
|
| 145 |
def find_candidate_components() -> list[str]: |
| 146 |
""" |
| 147 |
1) Reads .gitlab-ci/container/gitlab-ci.yml to find component links: |
| 148 |
lines matching '.*.container-builds-<component>' |
| 149 |
2) Looks for matching build-<component>.sh in .gitlab-ci/container/ |
| 150 |
3) Returns a sorted list of components in the intersection of these sets. |
| 151 |
""" |
| 152 |
container_yaml = load_container_yaml() |
| 153 |
# Extract patterns like `container-builds-foo` from job names |
| 154 |
candidates: Set[str] = set() |
| 155 |
for job_name in container_yaml: |
| 156 |
if match := re.search(r"\.container-builds-([a-z0-9_-]+)$", str(job_name)): |
| 157 |
candidates.add(match.group(1)) |
| 158 |
|
| 159 |
if not candidates: |
| 160 |
logging.error( |
| 161 |
f"No viable build components found in {PATHS.container_ci}. " |
| 162 |
"Please check the file for valid component names. " |
| 163 |
"They should be named like '.container-builds-<component>'." |
| 164 |
) |
| 165 |
return [] |
| 166 |
|
| 167 |
# Find build scripts named build-<component>.sh |
| 168 |
build_scripts: list[str] = [] |
| 169 |
for path in PATHS.container_dir.glob("build-*.sh"): |
| 170 |
if validate_build_script(path.name): |
| 171 |
logging.info(f"Found build script: {path.name}") |
| 172 |
component = from_script_name_to_component(path.name) |
| 173 |
build_scripts.append(component) |
| 174 |
|
| 175 |
# Return sorted intersection of components found in build scripts and candidates |
| 176 |
return sorted(candidates.intersection(build_scripts)) |
| 177 |
|
| 178 |
|
| 179 |
def filter_components(components: list[str], includes: list[str], excludes: list[str]) -> list[str]: |
| 180 |
""" |
| 181 |
Returns components that match at least one `includes` regex and none of the `excludes` regex. |
| 182 |
If includes is empty, returns an empty list (unless user explicitly does --all or --include). |
| 183 |
""" |
| 184 |
if not includes: |
| 185 |
return [] |
| 186 |
|
| 187 |
filtered = [] |
| 188 |
for comp in components: |
| 189 |
# Must match at least one "include" |
| 190 |
if not any(re.fullmatch(inc, comp) for inc in includes): |
| 191 |
logging.debug(f"Excluding {comp}, no matches in includes.") |
| 192 |
continue |
| 193 |
# Must not match any "exclude" |
| 194 |
if any(re.fullmatch(exc, comp) for exc in excludes): |
| 195 |
logging.debug(f"Excluding {comp}, matched exclude pattern.") |
| 196 |
continue |
| 197 |
filtered.append(comp) |
| 198 |
return filtered |
| 199 |
|
| 200 |
|
| 201 |
def run_build_script(component: str, check_only: bool = False) -> Optional[str]: |
| 202 |
""" |
| 203 |
Runs .gitlab-ci/container/build-<component>.sh to produce a new tag (last line of stdout). |
| 204 |
If check_only=True, we skip updates to the YAML (but do the build to see if it passes). |
| 205 |
Returns the extracted tag (string) on success, or None on failure. |
| 206 |
""" |
| 207 |
# 1) Set up environment |
| 208 |
setup_env_script = prepare_setup_env_script() |
| 209 |
|
| 210 |
build_script = PATHS.container_dir / f"build-{component}.sh" |
| 211 |
if not build_script.is_file(): |
| 212 |
logging.error(f"Build script not found for {component}: {build_script}") |
| 213 |
return None |
| 214 |
|
| 215 |
# Tag var should appear in the script, e.g., ANGLE_TAG for 'angle' |
| 216 |
tag_var = from_component_to_tag_var(component) |
| 217 |
|
| 218 |
# We set up environment for the child process |
| 219 |
child_env: dict[str, str] = {} |
| 220 |
child_env["NEW_TAG_DRY_RUN"] = "1" |
| 221 |
if check_only: |
| 222 |
# For checking only |
| 223 |
child_env.pop("NEW_TAG_DRY_RUN", None) |
| 224 |
child_env["CI_NOT_BUILDING_ANYTHING"] = "1" |
| 225 |
if tag_value := get_current_tag_value(component): |
| 226 |
child_env[tag_var] = tag_value |
| 227 |
else: |
| 228 |
logging.error(f"No current tag value for {component}") |
| 229 |
return None |
| 230 |
|
| 231 |
logging.debug( |
| 232 |
f"Running build for {component} with " |
| 233 |
f"{tag_var}={child_env.get(tag_var)} " |
| 234 |
f"(check_only={check_only})" |
| 235 |
) |
| 236 |
|
| 237 |
# Run the build script |
| 238 |
result = subprocess.run( |
| 239 |
["bash", "-c", f"source {setup_env_script} && source {build_script}"], |
| 240 |
env=os.environ | child_env, |
| 241 |
capture_output=True, |
| 242 |
text=True, |
| 243 |
) |
| 244 |
logging.debug(f"{' '.join(result.args)}") |
| 245 |
|
| 246 |
# Tag check succeeded |
| 247 |
if result.returncode == 0: |
| 248 |
# Tag is assumed to be the last line of stdout |
| 249 |
lines = result.stdout.strip().splitlines() |
| 250 |
return lines[-1] if lines else "" |
| 251 |
|
| 252 |
# Tag check failed, let's dissect the error |
| 253 |
|
| 254 |
if result.returncode == 2: |
| 255 |
logging.error(f"Tag mismatch for {component}.") |
| 256 |
logging.error(result.stdout) |
| 257 |
return None |
| 258 |
|
| 259 |
# Check if there's an unbound variable error |
| 260 |
err_output = result.stderr |
| 261 |
unbound_match = re.search(r"([A-Z_]+)(?=: unbound variable)", err_output) |
| 262 |
if unbound_match: |
| 263 |
var_name = unbound_match.group(1) |
| 264 |
logging.fatal(f"Please set the variable {var_name} in {build_script}.") |
| 265 |
sys.exit(3) |
| 266 |
|
| 267 |
# Unexpected error in the build script, propagate the exit code |
| 268 |
logging.fatal(f"Build script for {component} failed with return code {result.returncode}") |
| 269 |
logging.error(result.stdout) |
| 270 |
sys.exit(result.returncode) |
| 271 |
|
| 272 |
|
| 273 |
def load_image_tags_yaml() -> YamlData: |
| 274 |
if not PATHS.conditional_tags.is_file(): |
| 275 |
raise FileNotFoundError( |
| 276 |
f"Conditional build image tags file not found: {PATHS.conditional_tags}" |
| 277 |
) |
| 278 |
|
| 279 |
with open(str(PATHS.conditional_tags), "r", encoding="utf-8") as f: |
| 280 |
data = yaml.safe_load(f) |
| 281 |
if not isinstance(data, dict): |
| 282 |
return {"variables": {}} |
| 283 |
if "variables" not in data: |
| 284 |
data["variables"] = {} |
| 285 |
return data |
| 286 |
|
| 287 |
|
| 288 |
def get_current_tag_value(component: str) -> Optional[str]: |
| 289 |
# If the CI job already set the tag, use it |
| 290 |
tag_var = from_component_to_tag_var(component) |
| 291 |
if os.getenv(tag_var): |
| 292 |
logging.debug(f"Using tag from environment variable {tag_var}") |
| 293 |
return os.getenv(tag_var) |
| 294 |
|
| 295 |
# Otherwise, look in the YAML file, which normally occurs when updating tags locally |
| 296 |
full_tag_var = from_component_to_build_tag(component) |
| 297 |
data = load_image_tags_yaml() |
| 298 |
variables = data.get("variables", {}) |
| 299 |
if not isinstance(variables, dict): |
| 300 |
return None |
| 301 |
logging.debug(f"Using tag from YAML file {full_tag_var}") |
| 302 |
return variables.get(full_tag_var) |
| 303 |
|
| 304 |
|
| 305 |
def update_image_tag_in_yaml(component: str, tag_value: str) -> None: |
| 306 |
""" |
| 307 |
Uses PyYAML to edit the YAML file at IMAGE_TAGS_FILE, setting the environment variable |
| 308 |
for the given component. Maintains sorted keys. |
| 309 |
""" |
| 310 |
full_tag_var = from_component_to_build_tag(component) |
| 311 |
data = load_image_tags_yaml() |
| 312 |
|
| 313 |
# Ensure we have a variables dictionary |
| 314 |
if "variables" not in data: |
| 315 |
data["variables"] = {} |
| 316 |
elif not isinstance(data["variables"], dict): |
| 317 |
data["variables"] = {} |
| 318 |
|
| 319 |
# Update the tag |
| 320 |
data["variables"][full_tag_var] = tag_value |
| 321 |
|
| 322 |
# Sort the variables |
| 323 |
data["variables"] = dict(sorted(data["variables"].items())) |
| 324 |
|
| 325 |
# Write back to file |
| 326 |
with open(str(PATHS.conditional_tags), "w", encoding="utf-8") as f: |
| 327 |
yaml.dump(data, f, sort_keys=False) # Don't sort top-level keys |
| 328 |
|
| 329 |
|
| 330 |
def parse_args(): |
| 331 |
parser = argparse.ArgumentParser( |
| 332 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 333 |
description="Manage container image tags for CI builds with regex-based includes/excludes.", |
| 334 |
epilog=""" |
| 335 |
Exit codes: |
| 336 |
0 - Success |
| 337 |
1 - Unhandled error in this script |
| 338 |
2 - Tag mismatch when using --check |
| 339 |
3 - Unbound variable error in build script |
| 340 |
x - Build script failed with return code x |
| 341 |
""", |
| 342 |
) |
| 343 |
|
| 344 |
parser.add_argument( |
| 345 |
"--include", |
| 346 |
"-i", |
| 347 |
action="append", |
| 348 |
default=[], |
| 349 |
help="Full match regex pattern for components to include.", |
| 350 |
) |
| 351 |
parser.add_argument( |
| 352 |
"--exclude", |
| 353 |
"-x", |
| 354 |
action="append", |
| 355 |
default=[], |
| 356 |
help="Full match regex pattern for components to exclude.", |
| 357 |
) |
| 358 |
parser.add_argument("--all", action="store_true", help="Equivalent to --include '.*'") |
| 359 |
parser.add_argument( |
| 360 |
"--check", |
| 361 |
"-c", |
| 362 |
action="append", |
| 363 |
default=[], |
| 364 |
help="Check matching components instead of updating YAML. " |
| 365 |
"If any component fails, exit with a non-zero exit code.", |
| 366 |
) |
| 367 |
parser.add_argument( |
| 368 |
"--list", |
| 369 |
"-l", |
| 370 |
action="store_true", |
| 371 |
help="List all available components and exit.", |
| 372 |
) |
| 373 |
parser.add_argument( |
| 374 |
"-v", |
| 375 |
"--verbose", |
| 376 |
action="count", |
| 377 |
default=0, |
| 378 |
help="Increase verbosity level (-v for info, -vv for debug)", |
| 379 |
) |
| 380 |
|
| 381 |
if len(sys.argv) == 1: |
| 382 |
parser.print_help() |
| 383 |
sys.exit(0) |
| 384 |
|
| 385 |
return parser.parse_args() |
| 386 |
|
| 387 |
|
| 388 |
def main(): |
| 389 |
args = parse_args() |
| 390 |
|
| 391 |
# Configure logging based on verbosity level |
| 392 |
if args.verbose == 1: |
| 393 |
log_level = logging.INFO |
| 394 |
elif args.verbose == 2: |
| 395 |
log_level = logging.DEBUG |
| 396 |
else: |
| 397 |
log_level = logging.WARNING |
| 398 |
|
| 399 |
logging.basicConfig(level=log_level, format="%(levelname)s: %(message)s") |
| 400 |
|
| 401 |
# 1) If checking, just run build scripts in check mode and propagate errors |
| 402 |
if args.check: |
| 403 |
tag_mismatch = False |
| 404 |
for comp in args.check: |
| 405 |
try: |
| 406 |
if run_build_script(comp, check_only=True) is None: |
| 407 |
# The tag is invalid |
| 408 |
tag_mismatch = True |
| 409 |
except SystemExit as e: |
| 410 |
# Let custom exit codes propagate |
| 411 |
raise e |
| 412 |
except Exception as e: |
| 413 |
logging.error(f"Internal error: {e}") |
| 414 |
sys.exit(1) |
| 415 |
# If any component failed, exit with code 1 |
| 416 |
if tag_mismatch: |
| 417 |
sys.exit(2) |
| 418 |
return |
| 419 |
|
| 420 |
# Convert --all into a wildcard include |
| 421 |
if args.all: |
| 422 |
args.include.append(".*") |
| 423 |
|
| 424 |
# 2) If --list, just show all discovered components |
| 425 |
all_components = find_candidate_components() |
| 426 |
if args.list: |
| 427 |
print("Detected components:", ", ".join(all_components)) |
| 428 |
return |
| 429 |
|
| 430 |
# 3) Filter components |
| 431 |
final_components = filter_components(all_components, args.include, args.exclude) |
| 432 |
|
| 433 |
if args.verbose: |
| 434 |
logging.debug(f"Found components: {all_components}") |
| 435 |
logging.debug(f"Filtered components: {final_components}") |
| 436 |
|
| 437 |
for comp in final_components: |
| 438 |
logging.info(f"Updating {comp}...") |
| 439 |
new_tag = run_build_script(comp, check_only=False) |
| 440 |
if new_tag is not None: |
| 441 |
update_image_tag_in_yaml(comp, new_tag) |
| 442 |
if args.verbose: |
| 443 |
logging.debug(f"Updated {comp} with tag: {new_tag}") |
| 444 |
|
| 445 |
|
| 446 |
if __name__ == "__main__": |
| 447 |
main() |