Skip to content

Commit 6822e73

Browse files
committed
WIP: OCI tagging
1 parent 6a7f814 commit 6822e73

File tree

13 files changed

+619
-295
lines changed

13 files changed

+619
-295
lines changed

Makefile

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ install-test: install-dev
4646
test: install-test
4747
$(POETRY) run pytest -k "not kms"
4848

49+
test-debug: install-test
50+
$(POETRY) run pytest -k "not kms" -vvv -s
51+
52+
test-trace: install-test
53+
$(POETRY) run pytest -k "not kms" -vvv --log-cli-level=DEBUG
54+
4955
format: install-dev
5056
$(POETRY) run black --extend-exclude test-data/gardenlinux .
5157

poetry.lock

Lines changed: 94 additions & 24 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ oras = { git = "https://github.com/oras-project/oras-py.git", rev="caf8db5b2793
1919
python-dotenv = "^1.0.1"
2020
cryptography = "^44.0.0"
2121
boto3 = "*"
22+
click = "^8.2.0"
23+
pygments = "^2.19.1"
24+
opencontainers = "^0.0.14"
2225

2326
[tool.poetry.group.dev.dependencies]
2427
bandit = "^1.8.3"

src/gardenlinux/constants.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,5 @@
164164

165165
OCI_ANNOTATION_SIGNATURE_KEY = "io.gardenlinux.oci.signature"
166166
OCI_ANNOTATION_SIGNED_STRING_KEY = "io.gardenlinux.oci.signed-string"
167+
168+
GL_USER_AGENT_REGISTRY = "gardenlinux.oci.registry/1.0"

src/gardenlinux/features/__main__.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -226,14 +226,27 @@ def get_flavor_from_cname(cname: str, get_arch: bool = True) -> str:
226226
# transform to flavor:
227227
# azure-gardener_prod_tpm2_trustedboot-amd64
228228

229-
platform = cname.split("-")[0]
230-
features = cname.split("-")[1:-1]
231-
arch = cname.split("-")[-1]
229+
parts = cname.split("-")
232230

231+
# Extract platform, features, and architecture
232+
platform = parts[0]
233+
234+
# If there's more than two parts (beyond platform and arch), those are features
235+
if len(parts) > 2:
236+
features = "-".join(parts[1:-1]) # Join all middle parts with hyphens
237+
else:
238+
features = ""
239+
240+
arch = parts[-1]
241+
242+
# Create the flavor string
233243
if get_arch:
234-
return f"{platform}-{features}-{arch}"
244+
flavor = f"{platform}-{features}-{arch}" if features else f"{platform}-{arch}"
235245
else:
236-
return f"{platform}-{features}"
246+
flavor = f"{platform}-{features}" if features else platform
247+
248+
print(f"Extracted flavor: {flavor}")
249+
return flavor
237250

238251

239252
if __name__ == "__main__":

src/gardenlinux/oci/__main__.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,6 @@ def cli():
2626
type=click.Path(),
2727
help="Version of image",
2828
)
29-
@click.option(
30-
"--commit",
31-
required=False,
32-
type=click.Path(),
33-
default=None,
34-
help="Commit of image",
35-
)
3629
@click.option(
3730
"--arch",
3831
required=True,
@@ -58,16 +51,22 @@ def cli():
5851
default=False,
5952
help="Use HTTP to communicate with the registry",
6053
)
54+
@click.option(
55+
"--additional_tag",
56+
required=False,
57+
multiple=True,
58+
help="Additional tag to push the manifest with",
59+
)
6160
def push_manifest(
6261
container,
6362
version,
64-
commit,
6563
arch,
6664
cname,
6765
directory,
6866
cosign_file,
6967
manifest_file,
7068
insecure,
69+
additional_tag,
7170
):
7271
"""push artifacts from a dir to a registry, get the index-entry for the manifest in return"""
7372
container_name = f"{container}:{version}"
@@ -77,7 +76,7 @@ def push_manifest(
7776
insecure=insecure,
7877
)
7978
digest = registry.push_from_dir(
80-
arch, version, cname, directory, manifest_file, commit=commit
79+
arch, version, cname, directory, manifest_file, additional_tag
8180
)
8281
if cosign_file:
8382
print(digest, file=open(cosign_file, "w"))

src/gardenlinux/oci/registry.py

Lines changed: 158 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@
2929
from oras.schemas import manifest as oras_manifest_schema
3030

3131
from gardenlinux.features import Parser
32-
from ..constants import OCI_ANNOTATION_SIGNATURE_KEY, OCI_ANNOTATION_SIGNED_STRING_KEY
32+
from ..constants import (
33+
OCI_ANNOTATION_SIGNATURE_KEY,
34+
OCI_ANNOTATION_SIGNED_STRING_KEY,
35+
GL_USER_AGENT_REGISTRY,
36+
)
3337
from .checksum import (
3438
calculate_sha256,
3539
verify_sha256,
@@ -653,40 +657,59 @@ def push_from_dir(
653657
cname: str,
654658
directory: str,
655659
manifest_file: str,
656-
commit: Optional[str] = None,
660+
additional_tags: list = None,
657661
):
658-
# Step 1 scan and extract nested artifacts:
659-
for file in os.listdir(directory):
660-
try:
661-
if file.endswith(".pxe.tar.gz"):
662-
logger.info(f"Found nested artifact {file}")
663-
nested_tar_obj = tarfile.open(f"{directory}/{file}")
664-
nested_tar_obj.extractall(filter="data", path=directory)
665-
nested_tar_obj.close()
666-
except (OSError, tarfile.FilterError, tarfile.TarError) as e:
667-
print(f"Failed to extract nested artifact {file}", e)
668-
exit(1)
662+
"""
663+
Push artifacts from a directory to a registry
664+
665+
Args:
666+
architecture: Target architecture of the image
667+
version: Version tag for the image
668+
cname: Canonical name of the image
669+
directory: Directory containing the artifacts
670+
manifest_file: File to write the manifest index entry to
671+
additional_tags: Additional tags to push the manifest with
672+
673+
Returns:
674+
The digest of the pushed manifest
675+
"""
676+
if additional_tags is None:
677+
additional_tags = []
669678

670679
try:
680+
# Step 1: scan and extract nested artifacts
681+
for file in os.listdir(directory):
682+
try:
683+
if file.endswith(".pxe.tar.gz"):
684+
logger.info(f"Found nested artifact {file}")
685+
nested_tar_obj = tarfile.open(f"{directory}/{file}")
686+
nested_tar_obj.extractall(filter="data", path=directory)
687+
nested_tar_obj.close()
688+
except (OSError, tarfile.FilterError, tarfile.TarError) as e:
689+
print(f"Failed to extract nested artifact {file}", e)
690+
exit(1)
691+
692+
# Step 2: Get metadata from files
671693
oci_metadata = get_oci_metadata_from_fileset(
672694
os.listdir(directory), architecture
673695
)
674696

675697
features = ""
698+
commit = ""
676699
for artifact in oci_metadata:
677700
if artifact["media_type"] == "application/io.gardenlinux.release":
678-
file = open(f"{directory}/{artifact["file_name"]}", "r")
679-
lines = file.readlines()
680-
for line in lines:
681-
if line.strip().startswith("GARDENLINUX_FEATURES="):
682-
features = line.strip().removeprefix(
683-
"GARDENLINUX_FEATURES="
684-
)
685-
break
686-
file.close()
687-
688-
flavor = Parser.get_flavor_from_cname(cname, get_arch=True)
689-
701+
with open(f"{directory}/{artifact["file_name"]}", "r") as file:
702+
for line in file:
703+
line = line.strip()
704+
if line.startswith("GARDENLINUX_FEATURES="):
705+
features = line.removeprefix("GARDENLINUX_FEATURES=")
706+
elif line.startswith("GARDENLINUX_COMMIT_ID="):
707+
commit = line.removeprefix("GARDENLINUX_COMMIT_ID=")
708+
if features and commit: # Break if both values are found
709+
break
710+
break # Break after processing the release file
711+
712+
# Step 3: Push the image manifest
690713
digest = self.push_image_manifest(
691714
architecture,
692715
cname,
@@ -697,7 +720,116 @@ def push_from_dir(
697720
manifest_file,
698721
commit=commit,
699722
)
723+
724+
# Step 4: Process additional tags if provided
725+
if additional_tags and len(additional_tags) > 0:
726+
print(f"DEBUG: Processing {len(additional_tags)} additional tags")
727+
logger.info(f"Processing {len(additional_tags)} additional tags")
728+
729+
# Call push_additional_tags_manifest with repository information
730+
self.push_additional_tags_manifest(
731+
architecture,
732+
cname,
733+
version,
734+
additional_tags,
735+
container=self.container,
736+
)
737+
738+
return digest
700739
except Exception as e:
701740
print("Error: ", e)
702741
exit(1)
703-
return digest
742+
743+
def push_additional_tags_manifest(
744+
self, architecture, cname, version, additional_tags, container
745+
):
746+
"""
747+
Push additional tags for an existing manifest using ORAS Registry methods
748+
749+
Args:
750+
architecture: Target architecture of the image
751+
cname: Canonical name of the image
752+
version: Version tag for the image
753+
additional_tags: List of additional tags to push
754+
container: Container object
755+
"""
756+
try:
757+
print(f"DEBUG: Processing {len(additional_tags)} additional tags for manifest")
758+
print(f"DEBUG: Container: {container}")
759+
print(f"DEBUG: Container api_prefix: {container.api_prefix}")
760+
print(f"DEBUG: Container uri: {container.uri}")
761+
print(f"DEBUG: Container tag: {container.tag}")
762+
print(f"DEBUG: Container registry: {container.registry}")
763+
print(f"DEBUG: Container repository: {container.repository}")
764+
765+
# Source tag is the tag containing the version-cname-architecture combination
766+
source_tag = f"{version}-{cname}-{architecture}"
767+
source_container = copy.deepcopy(container)
768+
source_container.tag = source_tag
769+
770+
# Authentication credentials from environment
771+
token = os.getenv("GL_CLI_REGISTRY_TOKEN")
772+
username = os.getenv("GL_CLI_REGISTRY_USERNAME")
773+
password = os.getenv("GL_CLI_REGISTRY_PASSWORD")
774+
775+
print(f"DEBUG: Token is {'set' if token else 'not set'}")
776+
print(f"DEBUG: Username is {'set' if username else 'not set'}")
777+
print(f"DEBUG: Password is {'set' if password else 'not set'}")
778+
779+
# Login to registry if credentials are provided
780+
if username and password:
781+
print(f"DEBUG: Logging in with username/password")
782+
try:
783+
self.login(username, password)
784+
except Exception as login_error:
785+
print(f"DEBUG: Login error: {str(login_error)}")
786+
elif token:
787+
# If token is provided, set it directly on the Registry instance
788+
print(f"DEBUG: Using token authentication")
789+
self.token = base64.b64encode(token.encode("utf-8")).decode("utf-8")
790+
self.auth.set_token_auth(self.token)
791+
792+
# Step 1: Get the manifest from the source container
793+
try:
794+
print(f"DEBUG: Getting manifest from {source_container}")
795+
manifest = self.get_manifest(source_container)
796+
if not manifest:
797+
print(f"DEBUG: Failed to get manifest for {source_container}")
798+
logger.error(f"Failed to get manifest for {source_container}")
799+
return
800+
print(f"DEBUG: Successfully retrieved manifest: {manifest['mediaType'] if 'mediaType' in manifest else 'unknown'}")
801+
except Exception as get_error:
802+
print(f"DEBUG: Error getting manifest: {str(get_error)}")
803+
logger.error(f"Error getting manifest: {str(get_error)}")
804+
return
805+
806+
# Step 2: For each additional tag, push the manifest using Registry.upload_manifest
807+
for tag in additional_tags:
808+
try:
809+
print(f"DEBUG: Pushing additional tag: {tag}")
810+
811+
# Create a new container for this tag
812+
tag_container = copy.deepcopy(container)
813+
tag_container.tag = tag
814+
815+
print(f"DEBUG: Pushing to container: {tag_container}")
816+
817+
# Upload the manifest to the new tag
818+
response = self.upload_manifest(manifest, tag_container)
819+
820+
if response and response.status_code in [200, 201]:
821+
print(f"DEBUG: Successfully pushed tag {tag} for manifest")
822+
logger.info(f"Successfully pushed tag {tag} for manifest")
823+
else:
824+
status_code = getattr(response, 'status_code', 'unknown')
825+
response_text = getattr(response, 'text', 'No response text')
826+
print(f"DEBUG: Failed to push tag {tag} for manifest: {status_code} - {response_text}")
827+
logger.error(f"Failed to push tag {tag} for manifest: {status_code}")
828+
829+
except Exception as tag_error:
830+
print(f"DEBUG: Error pushing tag {tag} for manifest: {str(tag_error)}")
831+
logger.error(f"Error pushing tag {tag} for manifest: {str(tag_error)}")
832+
833+
except Exception as e:
834+
print(f"DEBUG: Error in push_additional_tags_manifest: {str(e)}")
835+
logger.error(f"Error in push_additional_tags_manifest: {str(e)}")

0 commit comments

Comments
 (0)