Skip to content

Add labels and annotations #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 42 additions & 10 deletions src/image_tools/bake.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@
python -m image_tools.bake -p opa -i 22.12.0
"""

import sys
import copy
from typing import List, Dict, Any
from argparse import Namespace
from subprocess import run
import json
import logging
import sys
from argparse import Namespace
from datetime import datetime, timezone
from functools import cache
from subprocess import CalledProcessError, run
from typing import Any, Dict, List

from .lib import Command
from .args import bake_args, load_configuration
from .lib import Command
from .version import version


Expand Down Expand Up @@ -65,7 +68,9 @@ def generate_bakefile(args: Namespace, conf) -> Dict[str, Any]:
product_name: str = product["name"]
product_targets = {}
for version_dict in product.get("versions", []):
product_targets.update(bakefile_product_version_targets(args, product_name, version_dict, product_names, build_cache))
product_targets.update(
bakefile_product_version_targets(args, product_name, version_dict, product_names, build_cache)
)
groups[product_name] = {
"targets": list(product_targets.keys()),
}
Expand Down Expand Up @@ -102,9 +107,21 @@ def bakefile_product_version_targets(
tags = build_image_tags(image_name, args.image_version, versions["product"])
build_args = build_image_args(versions, args.image_version)
target_name = bakefile_target_name_for_product_version(product_name, versions["product"])
rfc3339_date_time = datetime.now(timezone.utc).isoformat()
revision = get_git_revision()

# The build-date label is set on UBI images automatically so we want to override it to not cause confusion even though it means we have the same date in the labels multiple times
result = {
target_name: {
"annotations": [
f"org.opencontainers.image.created={rfc3339_date_time}",
f"org.opencontainers.image.revision={revision}",
],
"labels": {
"org.opencontainers.image.created": rfc3339_date_time,
"build-date": rfc3339_date_time,
"org.opencontainers.image.revision": revision,
},
"dockerfile": f"{product_name}/Dockerfile",
"tags": tags,
"args": build_args,
Expand All @@ -114,15 +131,18 @@ def bakefile_product_version_targets(
f"stackable/image/{name}": f"target:{bakefile_target_name_for_product_version(name, version)}"
for name, version in versions.items()
if name in product_names
}
},
},
}

if args.cache:
result[target_name]["cache-to"] = result[target_name]["cache-from"] = generate_cache_location(cache, target_name, args.architecture)
result[target_name]["cache-to"] = result[target_name]["cache-from"] = generate_cache_location(
cache, target_name, args.architecture
)

return result


def targets_for_selector(conf, selected_products: List[str]) -> List[str]:
targets = []
for selected_product in selected_products or (product["name"] for product in conf.products):
Expand Down Expand Up @@ -168,21 +188,23 @@ def bake_command(args: Namespace, targets: List[str], bakefile) -> Command:
stdin=json.dumps(bakefile),
)


def generate_cache_location(cache: List[Dict[str, str]], target_name: str, arch: str) -> List[str]:
cache_copy = copy.deepcopy(cache)
result = []

for backend in cache_copy:
if 'ref_prefix' in backend:
if "ref_prefix" in backend:
# Need to replace the / from values like linux/amd64 because otherwise
# the cache ref would be invalid.
arch = arch.replace('/', '_')
arch = arch.replace("/", "_")
backend["ref"] = f"{backend['ref_prefix']}:{target_name}-{arch}"
del backend["ref_prefix"]
result.append(",".join([f"{k}={v}" for k, v in backend.items()]))

return result


def main() -> int:
"""Generate a Docker bake file from conf.py and build the given args.product images."""
args = bake_args()
Expand Down Expand Up @@ -216,5 +238,15 @@ def main() -> int:
return result.returncode


@cache
def get_git_revision():
try:
result = run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True)
return result.stdout.strip()
except CalledProcessError as e:
logging.error("Failed to get git revision", e)
return None


if __name__ == "__main__":
sys.exit(main())