Skip to content
Draft
Show file tree
Hide file tree
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
26 changes: 25 additions & 1 deletion openserverless/common/kube_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,30 @@ def get_jobs(self, name_filter: str | None = None, namespace="nuvolaris"):
except Exception as ex:
logging.error(f"get_jobs {ex}")
return None

def get_job(self, job_name: str, namespace="nuvolaris"):
"""Get a Kubernetes Job by its exact name.

A missing Job is a normal condition for the idempotent image builder,
so HTTP 404 is returned as ``None`` without being treated as an API
failure.
"""
url = f"{self.host}/apis/batch/v1/namespaces/{namespace}/jobs/{job_name}"
headers = {"Authorization": self.token}
try:
logging.info(f"GET request to {url}")
response = req.get(url, headers=headers, verify=self.ssl_ca_cert)
if response.status_code == 200:
return json.loads(response.text)
if response.status_code == 404:
return None
logging.error(
f"GET to {url} failed with {response.status_code}. Body {response.text}"
)
return None
except Exception as ex:
logging.error(f"get_job {ex}")
return None

def delete_job(self, job_name: str, namespace="nuvolaris"):
"""
Expand Down Expand Up @@ -702,4 +726,4 @@ def wait_for_init_container_completion(self, job_name: str, init_container_name:
time.sleep(2)

logging.error(f"Timeout waiting for init container '{init_container_name}' to complete")
return False
return False
90 changes: 90 additions & 0 deletions openserverless/impl/builder/build_catalog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import json
import os
import re


BUILDER_ID = re.compile(r"^[a-z0-9][a-z0-9._:-]{0,62}$")
IMAGE_REFERENCE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@-]{0,511}$")
SUPPORTED_KINDS = {"python", "nodejs", "php", "java", "go", "ruby", "dotnet"}


class BuildCatalogError(ValueError):
pass


class BuildCatalog:
"""Validated allowlist of images that may be extended by BuildKit."""

def __init__(self, builders=None, environ=None):
self.environ = environ if environ is not None else os.environ
self.builders = self._validate(builders if builders is not None else self._load())

def _load(self):
raw = self.environ.get("BUILDER_CATALOG_JSON", "").strip()
if raw:
try:
return json.loads(raw)
except json.JSONDecodeError as exc:
raise BuildCatalogError(f"BUILDER_CATALOG_JSON is invalid: {exc.msg}") from exc

path = self.environ.get(
"BUILDER_CATALOG_FILE", "/etc/openserverless/builders.json"
)
try:
with open(path, encoding="utf-8") as catalog_file:
return json.load(catalog_file)
except FileNotFoundError:
return {}
except (OSError, json.JSONDecodeError) as exc:
raise BuildCatalogError(f"Cannot load builder catalog {path}: {exc}") from exc

def _validate(self, document):
if not isinstance(document, dict):
raise BuildCatalogError("Builder catalog must be a JSON object")
builders = document.get("builders", document)
if not isinstance(builders, dict):
raise BuildCatalogError("Builder catalog 'builders' must be an object")

validated = {}
for builder_id, entry in builders.items():
if not isinstance(builder_id, str) or not BUILDER_ID.fullmatch(builder_id):
raise BuildCatalogError(f"Invalid builder id: {builder_id!r}")
if not isinstance(entry, dict):
raise BuildCatalogError(f"Builder {builder_id} must be an object")
kind = entry.get("kind")
source = entry.get("source")
if kind not in SUPPORTED_KINDS:
raise BuildCatalogError(f"Builder {builder_id} has unsupported kind {kind!r}")
if not isinstance(source, str) or not IMAGE_REFERENCE.fullmatch(source):
raise BuildCatalogError(f"Builder {builder_id} has invalid source image")
validated[builder_id] = {"kind": kind, "source": source}
return validated

def get(self, builder_id):
try:
return self.builders[builder_id]
except KeyError as exc:
raise BuildCatalogError(f"Unknown builder: {builder_id}") from exc

def capabilities(self):
return [
{"id": builder_id, "kind": entry["kind"]}
for builder_id, entry in sorted(self.builders.items())
]
Loading
Loading