Archived
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82785b6823 | ||
|
|
583774e32a | ||
|
|
f91329eef0 | ||
|
|
7f0b82b9a9 | ||
|
|
64b395f15a | ||
|
|
240db3ca4c | ||
|
|
d09fbc3ac4 | ||
|
|
3c7ff76a83 | ||
|
|
53b29ff69b | ||
|
|
4ec0e38b77 | ||
|
|
14ee4da1fc | ||
|
|
e81c95a920 | ||
|
|
cc541ac20f | ||
|
|
10e2311a8b | ||
|
|
f32bbf9e48 | ||
|
|
0302153162 | ||
|
|
01e4437b62 | ||
|
|
64cec163b3 |
@@ -0,0 +1,9 @@
|
||||
# Fetching pre-built container images
|
||||
When Stack Orchestrator deploys a stack containing a suite of one or more containers it expects images for those containers to be on the local machine with a tag of the form `<image-name>:local` Images for these containers can be built from source (and optionally base container images from public registries) with the `build-containers` subcommand.
|
||||
|
||||
However, the task of building a large number of containers from source may consume considerable time and machine resources. This is where the `fetch-containers` subcommand steps in. It is designed to work exactly like `build-containers` but instead the images, pre-built, are fetched from an image registry then re-tagged for deployment. It can be used in place of `build-containers` for any stack provided the necessary containers, built for the local machine architecture (e.g. arm64 or x86-64) have already been published in an image registry.
|
||||
## Usage
|
||||
To use `fetch-containers`, provide an image registry path, a username and token/password with read access to the registry, and optionally specify `--force-local-overwrite`. If this argument is not specified, if there is already a locally built or previously fetched image for a stack container on the machine, it will not be overwritten and a warning issued.
|
||||
```
|
||||
$ laconic-so --stack mobymask-v3-demo fetch-containers --image-registry git.vdb.to/cerc-io --registry-username <registry-user> --registry-token <registry-token> --force-local-overwrite
|
||||
```
|
||||
@@ -27,7 +27,7 @@ from decouple import config
|
||||
import click
|
||||
from pathlib import Path
|
||||
from stack_orchestrator.build import build_containers
|
||||
from stack_orchestrator.deploy.webapp.util import determine_base_container
|
||||
from stack_orchestrator.deploy.webapp.util import determine_base_container, TimedLogger
|
||||
from stack_orchestrator.build.build_types import BuildContext
|
||||
|
||||
|
||||
@@ -40,9 +40,11 @@ from stack_orchestrator.build.build_types import BuildContext
|
||||
@click.pass_context
|
||||
def command(ctx, base_container, source_repo, force_rebuild, extra_build_args, tag):
|
||||
'''build the specified webapp container'''
|
||||
logger = TimedLogger()
|
||||
|
||||
quiet = ctx.obj.quiet
|
||||
debug = ctx.obj.debug
|
||||
verbose = ctx.obj.verbose
|
||||
local_stack = ctx.obj.local_stack
|
||||
stack = ctx.obj.stack
|
||||
|
||||
@@ -51,12 +53,12 @@ def command(ctx, base_container, source_repo, force_rebuild, extra_build_args, t
|
||||
|
||||
if local_stack:
|
||||
dev_root_path = os.getcwd()[0:os.getcwd().rindex("stack-orchestrator")]
|
||||
print(f'Local stack dev_root_path (CERC_REPO_BASE_DIR) overridden to: {dev_root_path}')
|
||||
logger.log(f'Local stack dev_root_path (CERC_REPO_BASE_DIR) overridden to: {dev_root_path}')
|
||||
else:
|
||||
dev_root_path = os.path.expanduser(config("CERC_REPO_BASE_DIR", default="~/cerc"))
|
||||
|
||||
if not quiet:
|
||||
print(f'Dev Root is: {dev_root_path}')
|
||||
if verbose:
|
||||
logger.log(f'Dev Root is: {dev_root_path}')
|
||||
|
||||
if not base_container:
|
||||
base_container = determine_base_container(source_repo)
|
||||
@@ -65,6 +67,9 @@ def command(ctx, base_container, source_repo, force_rebuild, extra_build_args, t
|
||||
container_build_env = build_containers.make_container_build_env(dev_root_path, container_build_dir, debug,
|
||||
force_rebuild, extra_build_args)
|
||||
|
||||
if verbose:
|
||||
logger.log(f"Building base container: {base_container}")
|
||||
|
||||
build_context_1 = BuildContext(
|
||||
stack,
|
||||
base_container,
|
||||
@@ -74,9 +79,12 @@ def command(ctx, base_container, source_repo, force_rebuild, extra_build_args, t
|
||||
)
|
||||
ok = build_containers.process_container(build_context_1)
|
||||
if not ok:
|
||||
print("ERROR: Build failed.", file=sys.stderr)
|
||||
logger.log("ERROR: Build failed.")
|
||||
sys.exit(1)
|
||||
|
||||
if verbose:
|
||||
logger.log(f"Base container {base_container} build finished.")
|
||||
|
||||
# Now build the target webapp. We use the same build script, but with a different Dockerfile and work dir.
|
||||
container_build_env["CERC_WEBAPP_BUILD_RUNNING"] = "true"
|
||||
container_build_env["CERC_CONTAINER_BUILD_WORK_DIR"] = os.path.abspath(source_repo)
|
||||
@@ -85,9 +93,12 @@ def command(ctx, base_container, source_repo, force_rebuild, extra_build_args, t
|
||||
"Dockerfile.webapp")
|
||||
if not tag:
|
||||
webapp_name = os.path.abspath(source_repo).split(os.path.sep)[-1]
|
||||
container_build_env["CERC_CONTAINER_BUILD_TAG"] = f"cerc/{webapp_name}:local"
|
||||
else:
|
||||
container_build_env["CERC_CONTAINER_BUILD_TAG"] = tag
|
||||
tag = f"cerc/{webapp_name}:local"
|
||||
|
||||
container_build_env["CERC_CONTAINER_BUILD_TAG"] = tag
|
||||
|
||||
if verbose:
|
||||
logger.log(f"Building app container: {tag}")
|
||||
|
||||
build_context_2 = BuildContext(
|
||||
stack,
|
||||
@@ -98,5 +109,9 @@ def command(ctx, base_container, source_repo, force_rebuild, extra_build_args, t
|
||||
)
|
||||
ok = build_containers.process_container(build_context_2)
|
||||
if not ok:
|
||||
print("ERROR: Build failed.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
logger.log("ERROR: Build failed.")
|
||||
sys.exit(1)
|
||||
|
||||
if verbose:
|
||||
logger.log(f"App container {base_container} build finished.")
|
||||
logger.log("build-webapp complete", show_step_time=False, show_total_time=True)
|
||||
|
||||
@@ -76,7 +76,7 @@ def _find_latest(candidate_tags: List[str]):
|
||||
sorted_candidates = sorted(candidate_tags)
|
||||
if opts.o.debug:
|
||||
print(f"sorted candidates: {sorted_candidates}")
|
||||
return sorted_candidates[0]
|
||||
return sorted_candidates[-1]
|
||||
|
||||
|
||||
def _filter_for_platform(container: str,
|
||||
|
||||
@@ -115,7 +115,7 @@ if [ "$CERC_NEXT_VERSION" != "keep" ] && [ "$CUR_NEXT_VERSION" != "$CERC_NEXT_VE
|
||||
mv package.json.$$ package.json
|
||||
fi
|
||||
|
||||
$CERC_BUILD_TOOL install || exit 1
|
||||
time $CERC_BUILD_TOOL install || exit 1
|
||||
|
||||
CUR_NEXT_VERSION=`jq -r '.version' node_modules/next/package.json`
|
||||
|
||||
@@ -138,9 +138,9 @@ to use for the build with:
|
||||
EOF
|
||||
cat package.json | jq ".dependencies.next = \"^$CERC_MIN_NEXTVER\"" > package.json.$$
|
||||
mv package.json.$$ package.json
|
||||
$CERC_BUILD_TOOL install || exit 1
|
||||
time $CERC_BUILD_TOOL install || exit 1
|
||||
fi
|
||||
|
||||
$CERC_BUILD_TOOL run cerc_compile || exit 1
|
||||
time $CERC_BUILD_TOOL run cerc_compile || exit 1
|
||||
|
||||
exit 0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Originally from: https://github.com/devcontainers/images/blob/main/src/javascript-node/.devcontainer/Dockerfile
|
||||
# [Choice] Node.js version (use -bullseye variants on local arm64/Apple Silicon): 18, 16, 14, 18-bullseye, 16-bullseye, 14-bullseye, 18-buster, 16-buster, 14-buster
|
||||
ARG VARIANT=20-bullseye
|
||||
ARG VARIANT=20-bullseye-slim
|
||||
FROM node:${VARIANT}
|
||||
|
||||
ARG USERNAME=node
|
||||
|
||||
@@ -32,8 +32,8 @@ elif [ -f "${WORK_DIR}/package.json" ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
$CERC_BUILD_TOOL install || exit 1
|
||||
$CERC_BUILD_TOOL build || exit 1
|
||||
time $CERC_BUILD_TOOL install || exit 1
|
||||
time $CERC_BUILD_TOOL build || exit 1
|
||||
|
||||
rm -rf "${DEST_DIR}"
|
||||
if [ -z "${CERC_BUILD_OUTPUT_DIR}" ]; then
|
||||
|
||||
@@ -110,13 +110,32 @@ class ClusterInfo:
|
||||
http_proxy_info = http_proxy_info_list[0]
|
||||
if opts.o.debug:
|
||||
print(f"http-proxy: {http_proxy_info}")
|
||||
# TODO: good enough parsing for webapp deployment for now
|
||||
|
||||
host_name = http_proxy_info["host-name"]
|
||||
|
||||
tls = None
|
||||
tls_issuer = None
|
||||
|
||||
if use_tls:
|
||||
tls_info = http_proxy_info.get("tls", {})
|
||||
tls_hosts = tls_info.get("hosts", [host_name])
|
||||
tls_issuer = tls_info.get("issuer", "letsencrypt-prod")
|
||||
tls_secret_name = f"{self.app_name}-tls"
|
||||
if "secret" in tls_info:
|
||||
# If an existing secret is specified, unset the issuer so that we don't try to re-request it.
|
||||
tls_secret_name = tls_info["secret"]
|
||||
tls_issuer = None
|
||||
|
||||
if opts.o.debug:
|
||||
print(f"TLS hosts/secret: {tls_hosts}/{tls_secret_name}")
|
||||
|
||||
tls = [client.V1IngressTLS(
|
||||
hosts=tls_hosts,
|
||||
secret_name=tls_secret_name
|
||||
)]
|
||||
|
||||
# TODO: good enough parsing for webapp deployment for now
|
||||
rules = []
|
||||
tls = [client.V1IngressTLS(
|
||||
hosts=[host_name],
|
||||
secret_name=f"{self.app_name}-tls"
|
||||
)] if use_tls else None
|
||||
paths = []
|
||||
for route in http_proxy_info["routes"]:
|
||||
path = route["path"]
|
||||
@@ -147,13 +166,15 @@ class ClusterInfo:
|
||||
tls=tls,
|
||||
rules=rules
|
||||
)
|
||||
annotations = {
|
||||
"kubernetes.io/ingress.class": "nginx",
|
||||
}
|
||||
if tls_issuer:
|
||||
annotations["cert-manager.io/cluster-issuer"] = tls_issuer
|
||||
ingress = client.V1Ingress(
|
||||
metadata=client.V1ObjectMeta(
|
||||
name=f"{self.app_name}-ingress",
|
||||
annotations={
|
||||
"kubernetes.io/ingress.class": "nginx",
|
||||
"cert-manager.io/cluster-issuer": "letsencrypt-prod"
|
||||
}
|
||||
annotations=annotations
|
||||
),
|
||||
spec=spec
|
||||
)
|
||||
|
||||
@@ -350,9 +350,10 @@ class K8sDeployer(Deployer):
|
||||
name=ingress.spec.tls[0].secret_name
|
||||
)
|
||||
|
||||
hostname = ingress.spec.tls[0].hosts[0]
|
||||
hostname = ingress.spec.rules[0].host
|
||||
ip = ingress.status.load_balancer.ingress[0].ip
|
||||
tls = "notBefore: %s, notAfter: %s" % (cert["status"]["notBefore"], cert["status"]["notAfter"])
|
||||
tls = "notBefore: %s; notAfter: %s; names: %s" % (
|
||||
cert["status"]["notBefore"], cert["status"]["notAfter"], ", ".join(ingress.spec.tls[0].hosts))
|
||||
except: # noqa: E722
|
||||
pass
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@ class ResourceLimits:
|
||||
memory: int = None
|
||||
storage: int = None
|
||||
|
||||
def __init__(self, obj={}):
|
||||
def __init__(self, obj=None):
|
||||
if obj is None:
|
||||
obj = {}
|
||||
if "cpus" in obj:
|
||||
self.cpus = float(obj["cpus"])
|
||||
if "memory" in obj:
|
||||
@@ -50,7 +52,9 @@ class Resources:
|
||||
limits: ResourceLimits = None
|
||||
reservations: ResourceLimits = None
|
||||
|
||||
def __init__(self, obj={}):
|
||||
def __init__(self, obj=None):
|
||||
if obj is None:
|
||||
obj = {}
|
||||
if "reservations" in obj:
|
||||
self.reservations = ResourceLimits(obj["reservations"])
|
||||
if "limits" in obj:
|
||||
@@ -72,7 +76,9 @@ class Spec:
|
||||
obj: typing.Any
|
||||
file_path: Path
|
||||
|
||||
def __init__(self, file_path: Path = None, obj={}) -> None:
|
||||
def __init__(self, file_path: Path = None, obj=None) -> None:
|
||||
if obj is None:
|
||||
obj = {}
|
||||
self.file_path = file_path
|
||||
self.obj = obj
|
||||
|
||||
@@ -91,49 +97,41 @@ class Spec:
|
||||
self.file_path = file_path
|
||||
|
||||
def get_image_registry(self):
|
||||
return (self.obj[constants.image_registry_key]
|
||||
if self.obj and constants.image_registry_key in self.obj
|
||||
else None)
|
||||
return self.obj.get(constants.image_registry_key)
|
||||
|
||||
def get_volumes(self):
|
||||
return (self.obj["volumes"]
|
||||
if self.obj and "volumes" in self.obj
|
||||
else {})
|
||||
return self.obj.get(constants.volumes_key, {})
|
||||
|
||||
def get_configmaps(self):
|
||||
return (self.obj["configmaps"]
|
||||
if self.obj and "configmaps" in self.obj
|
||||
else {})
|
||||
return self.obj.get(constants.configmaps_key, {})
|
||||
|
||||
def get_container_resources(self):
|
||||
return Resources(self.obj.get("resources", {}).get("containers", {}))
|
||||
return Resources(self.obj.get(constants.resources_key, {}).get("containers", {}))
|
||||
|
||||
def get_volume_resources(self):
|
||||
return Resources(self.obj.get("resources", {}).get("volumes", {}))
|
||||
return Resources(self.obj.get(constants.resources_key, {}).get(constants.volumes_key, {}))
|
||||
|
||||
def get_http_proxy(self):
|
||||
return (self.obj[constants.network_key][constants.http_proxy_key]
|
||||
if self.obj and constants.network_key in self.obj
|
||||
and constants.http_proxy_key in self.obj[constants.network_key]
|
||||
else None)
|
||||
return self.obj.get(constants.network_key, {}).get(constants.http_proxy_key, [])
|
||||
|
||||
def get_annotations(self):
|
||||
return self.obj.get("annotations", {})
|
||||
return self.obj.get(constants.annotations_key, {})
|
||||
|
||||
def get_labels(self):
|
||||
return self.obj.get("labels", {})
|
||||
return self.obj.get(constants.labels_key, {})
|
||||
|
||||
def get_privileged(self):
|
||||
return "true" == str(self.obj.get("security", {}).get("privileged", "false")).lower()
|
||||
return "true" == str(self.obj.get(constants.security_key, {}).get("privileged", "false")).lower()
|
||||
|
||||
def get_capabilities(self):
|
||||
return self.obj.get("security", {}).get("capabilities", [])
|
||||
return self.obj.get(constants.security_key, {}).get("capabilities", [])
|
||||
|
||||
def get_deployment_type(self):
|
||||
return self.obj[constants.deploy_to_key]
|
||||
return self.obj.get(constants.deploy_to_key)
|
||||
|
||||
def is_kubernetes_deployment(self):
|
||||
return self.get_deployment_type() in [constants.k8s_kind_deploy_type, constants.k8s_deploy_type]
|
||||
return self.get_deployment_type() in [constants.k8s_kind_deploy_type,
|
||||
constants.k8s_deploy_type]
|
||||
|
||||
def is_kind_deployment(self):
|
||||
return self.get_deployment_type() in [constants.k8s_kind_deploy_type]
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
import click
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from tempfile import NamedTemporaryFile
|
||||
@@ -23,6 +24,7 @@ from stack_orchestrator.util import error_exit, global_options2
|
||||
from stack_orchestrator.deploy.deployment_create import init_operation, create_operation
|
||||
from stack_orchestrator.deploy.deploy import create_deploy_context
|
||||
from stack_orchestrator.deploy.deploy_types import DeployCommandContext
|
||||
from stack_orchestrator.deploy.webapp.util import TlsDetails
|
||||
|
||||
|
||||
def _fixup_container_tag(deployment_dir: str, image: str):
|
||||
@@ -36,16 +38,16 @@ def _fixup_container_tag(deployment_dir: str, image: str):
|
||||
wfile.write(contents)
|
||||
|
||||
|
||||
def _fixup_url_spec(spec_file_name: str, url: str):
|
||||
def _fixup_url_spec(spec_file_name: str, url: str, tls_details: TlsDetails = TlsDetails()):
|
||||
# url is like: https://example.com/path
|
||||
parsed_url = urlparse(url)
|
||||
http_proxy_spec = f'''
|
||||
http-proxy:
|
||||
http_proxy_spec = f''' http-proxy:
|
||||
- host-name: {parsed_url.hostname}
|
||||
routes:
|
||||
- path: '{parsed_url.path if parsed_url.path else "/"}'
|
||||
proxy-to: webapp:80
|
||||
'''
|
||||
{tls_details.to_yaml(indent=6)}
|
||||
'''
|
||||
spec_file_path = Path(spec_file_name)
|
||||
with open(spec_file_path) as rfile:
|
||||
contents = rfile.read()
|
||||
@@ -54,7 +56,8 @@ def _fixup_url_spec(spec_file_name: str, url: str):
|
||||
wfile.write(contents)
|
||||
|
||||
|
||||
def create_deployment(ctx, deployment_dir, image, url, kube_config, image_registry, env_file):
|
||||
def create_deployment(ctx, deployment_dir, image, url, kube_config, image_registry, env_file,
|
||||
tls_details: TlsDetails = None):
|
||||
# Do the equivalent of:
|
||||
# 1. laconic-so --stack webapp-template deploy --deploy-to k8s init --output webapp-spec.yml
|
||||
# --config (eqivalent of the contents of my-config.env)
|
||||
@@ -86,7 +89,7 @@ def create_deployment(ctx, deployment_dir, image, url, kube_config, image_regist
|
||||
None
|
||||
)
|
||||
# Add the TLS and DNS spec
|
||||
_fixup_url_spec(spec_file_name, url)
|
||||
_fixup_url_spec(spec_file_name, url, tls_details)
|
||||
create_operation(
|
||||
deploy_command_context,
|
||||
spec_file_name,
|
||||
@@ -116,8 +119,16 @@ def command(ctx):
|
||||
@click.option("--image", help="image to deploy", required=True)
|
||||
@click.option("--url", help="url to serve", required=True)
|
||||
@click.option("--env-file", help="environment file for webapp")
|
||||
@click.option("--tls-host", help="Override TLS hostname (eg, '*.mydomain.com')")
|
||||
@click.option("--tls-secret", help="Override TLS secret name")
|
||||
@click.option("--tls-issuer", help="TLS issuer to use (default: letsencrypt-prod)")
|
||||
@click.pass_context
|
||||
def create(ctx, deployment_dir, image, url, kube_config, image_registry, env_file):
|
||||
def create(ctx, deployment_dir, image, url, kube_config, image_registry, env_file, tls_host, tls_secret, tls_issuer):
|
||||
'''create a deployment for the specified webapp container'''
|
||||
|
||||
return create_deployment(ctx, deployment_dir, image, url, kube_config, image_registry, env_file)
|
||||
if (tls_secret and not tls_host) or (tls_host and not tls_secret):
|
||||
print("Cannot specify --tls-host without --tls-secret", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
return create_deployment(ctx, deployment_dir, image, url, kube_config, image_registry, env_file,
|
||||
TlsDetails(tls_host, tls_secret, tls_issuer))
|
||||
|
||||
@@ -26,7 +26,7 @@ import click
|
||||
|
||||
from stack_orchestrator.deploy.images import remote_image_exists, add_tags_to_image
|
||||
from stack_orchestrator.deploy.webapp import deploy_webapp
|
||||
from stack_orchestrator.deploy.webapp.util import (LaconicRegistryClient,
|
||||
from stack_orchestrator.deploy.webapp.util import (LaconicRegistryClient, TimedLogger, TlsDetails,
|
||||
build_container_image, push_container_image,
|
||||
file_hash, deploy_to_k8s, publish_deployment,
|
||||
hostname_for_deployment_request, generate_hostname_for_app,
|
||||
@@ -34,7 +34,6 @@ from stack_orchestrator.deploy.webapp.util import (LaconicRegistryClient,
|
||||
|
||||
|
||||
def process_app_deployment_request(
|
||||
run_id,
|
||||
ctx,
|
||||
laconic: LaconicRegistryClient,
|
||||
app_deployment_request,
|
||||
@@ -44,14 +43,19 @@ def process_app_deployment_request(
|
||||
deployment_parent_dir,
|
||||
kube_config,
|
||||
image_registry,
|
||||
force_rebuild=False,
|
||||
log_file=None
|
||||
force_rebuild,
|
||||
tls_details,
|
||||
logger,
|
||||
):
|
||||
logger.log("BEGIN - process_app_deployment_request")
|
||||
|
||||
# 1. look up application
|
||||
app = laconic.get_record(app_deployment_request.attributes.application, require=True)
|
||||
logger.log(f"Retrieved app record {app_deployment_request.attributes.application}")
|
||||
|
||||
# 2. determine dns
|
||||
requested_name = hostname_for_deployment_request(app_deployment_request, laconic)
|
||||
logger.log(f"Determined requested name: {requested_name}")
|
||||
|
||||
# HACK
|
||||
if "." in requested_name:
|
||||
@@ -69,7 +73,7 @@ def process_app_deployment_request(
|
||||
matched_owner = match_owner(app_deployment_request, laconic.get_record(dns_record.attributes.request, require=True))
|
||||
|
||||
if matched_owner:
|
||||
print("Matched DnsRecord ownership:", matched_owner)
|
||||
logger.log(f"Matched DnsRecord ownership: {matched_owner}")
|
||||
else:
|
||||
raise Exception("Unable to confirm ownership of DnsRecord %s for request %s" %
|
||||
(dns_record.id, app_deployment_request.id))
|
||||
@@ -103,7 +107,7 @@ def process_app_deployment_request(
|
||||
(app_deployment_crn, deployment_dir))
|
||||
print("deploy_webapp", deployment_dir)
|
||||
deploy_webapp.create_deployment(ctx, deployment_dir, deployment_container_tag,
|
||||
f"https://{fqdn}", kube_config, image_registry, env_filename)
|
||||
f"https://{fqdn}", kube_config, image_registry, env_filename, tls_details)
|
||||
elif env_filename:
|
||||
shutil.copyfile(env_filename, deployment_config_file)
|
||||
|
||||
@@ -115,15 +119,21 @@ def process_app_deployment_request(
|
||||
shared_tag_exists = remote_image_exists(image_registry, app_image_shared_tag)
|
||||
if shared_tag_exists and not force_rebuild:
|
||||
# simply add our unique tag to the existing image and we are done
|
||||
print(f"Using existing app image {app_image_shared_tag} for {deployment_container_tag}", file=log_file)
|
||||
logger.log(f"Using existing app image {app_image_shared_tag} for {deployment_container_tag}")
|
||||
add_tags_to_image(image_registry, app_image_shared_tag, deployment_container_tag)
|
||||
logger.log("Tag complete")
|
||||
else:
|
||||
extra_build_args = [] # TODO: pull from request
|
||||
build_container_image(app, deployment_container_tag, extra_build_args, log_file)
|
||||
push_container_image(deployment_dir, log_file)
|
||||
logger.log(f"Building container image {deployment_container_tag}")
|
||||
build_container_image(app, deployment_container_tag, extra_build_args, logger)
|
||||
logger.log("Build complete")
|
||||
logger.log(f"Pushing container image {deployment_container_tag}")
|
||||
push_container_image(deployment_dir, logger)
|
||||
logger.log("Push complete")
|
||||
# The build/push commands above will use the unique deployment tag, so now we need to add the shared tag.
|
||||
print(f"Updating app image tag {app_image_shared_tag} from build of {deployment_container_tag}", file=log_file)
|
||||
logger.log(f"Updating app image tag {app_image_shared_tag} from build of {deployment_container_tag}")
|
||||
add_tags_to_image(image_registry, deployment_container_tag, app_image_shared_tag)
|
||||
logger.log("Tag complete")
|
||||
|
||||
# 7. update config (if needed)
|
||||
if not deployment_record or file_hash(deployment_config_file) != deployment_record.attributes.meta.config:
|
||||
@@ -131,13 +141,13 @@ def process_app_deployment_request(
|
||||
|
||||
# 8. update k8s deployment
|
||||
if needs_k8s_deploy:
|
||||
print("Deploying to k8s")
|
||||
deploy_to_k8s(
|
||||
deployment_record,
|
||||
deployment_dir,
|
||||
log_file
|
||||
logger
|
||||
)
|
||||
|
||||
logger.log("Publishing deployment to registry.")
|
||||
publish_deployment(
|
||||
laconic,
|
||||
app,
|
||||
@@ -146,8 +156,11 @@ def process_app_deployment_request(
|
||||
dns_record,
|
||||
dns_crn,
|
||||
deployment_dir,
|
||||
app_deployment_request
|
||||
app_deployment_request,
|
||||
logger
|
||||
)
|
||||
logger.log("Publication complete.")
|
||||
logger.log("END - process_app_deployment_request")
|
||||
|
||||
|
||||
def load_known_requests(filename):
|
||||
@@ -186,11 +199,14 @@ def dump_known_requests(filename, requests, status="SEEN"):
|
||||
@click.option("--exclude-tags", help="Exclude requests with matching tags (comma-separated).", default="")
|
||||
@click.option("--force-rebuild", help="Rebuild even if the image already exists.", is_flag=True)
|
||||
@click.option("--log-dir", help="Output build/deployment logs to directory.", default=None)
|
||||
@click.option("--tls-host", help="Override TLS hostname (eg, '*.mydomain.com')")
|
||||
@click.option("--tls-secret", help="Override TLS secret name")
|
||||
@click.option("--tls-issuer", help="TLS issuer to use (default: letsencrypt-prod)")
|
||||
@click.pass_context
|
||||
def command(ctx, kube_config, laconic_config, image_registry, deployment_parent_dir, # noqa: C901
|
||||
request_id, discover, state_file, only_update_state,
|
||||
dns_suffix, record_namespace_dns, record_namespace_deployments, dry_run,
|
||||
include_tags, exclude_tags, force_rebuild, log_dir):
|
||||
include_tags, exclude_tags, force_rebuild, log_dir, tls_host, tls_secret, tls_issuer):
|
||||
if request_id and discover:
|
||||
print("Cannot specify both --request-id and --discover", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
@@ -208,6 +224,10 @@ def command(ctx, kube_config, laconic_config, image_registry, deployment_parent_
|
||||
print("--dns-suffix, --record-namespace-dns, and --record-namespace-deployments are all required", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
if (tls_secret and not tls_host) or (tls_host and not tls_secret):
|
||||
print("Cannot specify --tls-host without --tls-secret", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
# Split CSV and clean up values.
|
||||
include_tags = [tag.strip() for tag in include_tags.split(",") if tag]
|
||||
exclude_tags = [tag.strip() for tag in exclude_tags.split(",") if tag]
|
||||
@@ -293,6 +313,7 @@ def command(ctx, kube_config, laconic_config, image_registry, deployment_parent_
|
||||
print("Found %d unsatisfied request(s) to process." % len(requests_to_execute))
|
||||
|
||||
if not dry_run:
|
||||
tls_details = TlsDetails(tls_host, tls_secret, tls_issuer)
|
||||
for r in requests_to_execute:
|
||||
dump_known_requests(state_file, [r], "DEPLOYING")
|
||||
status = "ERROR"
|
||||
@@ -309,8 +330,9 @@ def command(ctx, kube_config, laconic_config, image_registry, deployment_parent_
|
||||
run_log_file = open(run_log_file_path, "wt")
|
||||
run_reg_client = LaconicRegistryClient(laconic_config, log_file=run_log_file)
|
||||
|
||||
logger = TimedLogger(run_id, run_log_file)
|
||||
logger.log("Processing ...")
|
||||
process_app_deployment_request(
|
||||
run_id,
|
||||
ctx,
|
||||
run_reg_client,
|
||||
r,
|
||||
@@ -321,12 +343,15 @@ def command(ctx, kube_config, laconic_config, image_registry, deployment_parent_
|
||||
kube_config,
|
||||
image_registry,
|
||||
force_rebuild,
|
||||
run_log_file
|
||||
tls_details,
|
||||
logger
|
||||
)
|
||||
status = "DEPLOYED"
|
||||
except Exception as e:
|
||||
print("ERROR: " + str(e), file=run_log_file)
|
||||
logger.log("ERROR: " + str(e))
|
||||
finally:
|
||||
if logger:
|
||||
logger.log(f"DONE with status {status}", show_step_time=False, show_total_time=True)
|
||||
dump_known_requests(state_file, [r], status)
|
||||
if run_log_file:
|
||||
run_log_file.close()
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http:#www.gnu.org/licenses/>.
|
||||
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -25,6 +26,40 @@ import uuid
|
||||
import yaml
|
||||
|
||||
|
||||
class TlsDetails:
|
||||
def __init__(self, host_or_hosts=None, secret_name: str = None, issuer_name: str = None):
|
||||
if host_or_hosts:
|
||||
if isinstance(host_or_hosts, list):
|
||||
self.hosts = host_or_hosts
|
||||
else:
|
||||
self.hosts = [host_or_hosts]
|
||||
else:
|
||||
self.hosts = None
|
||||
self.secret_name = secret_name
|
||||
self.issuer_name = issuer_name
|
||||
|
||||
def to_yaml(self, indent=6):
|
||||
if not self.hosts and not self.secret_name and not self.issuer_name:
|
||||
return ""
|
||||
|
||||
ret = " " * indent + "tls:\n"
|
||||
indent += 2
|
||||
|
||||
if self.issuer_name:
|
||||
ret += " " * indent + "issuer: '%s'\n" % self.issuer_name
|
||||
|
||||
if self.secret_name:
|
||||
ret += " " * indent + "secret: '%s'\n" % self.secret_name
|
||||
|
||||
if self.hosts:
|
||||
ret += " " * indent + "hosts:"
|
||||
indent += 2
|
||||
for h in self.hosts:
|
||||
ret += "\n" + " " * indent + "- '%s'" % h
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
class AttrDict(dict):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(AttrDict, self).__init__(*args, **kwargs)
|
||||
@@ -39,6 +74,25 @@ class AttrDict(dict):
|
||||
return v
|
||||
|
||||
|
||||
class TimedLogger:
|
||||
def __init__(self, id="", file=None):
|
||||
self.start = datetime.datetime.now()
|
||||
self.last = self.start
|
||||
self.id = id
|
||||
self.file = file
|
||||
|
||||
def log(self, msg, show_step_time=True, show_total_time=False):
|
||||
prefix = f"{datetime.datetime.utcnow()} - {self.id}"
|
||||
if show_step_time:
|
||||
prefix += f" - {datetime.datetime.now() - self.last} (step)"
|
||||
if show_total_time:
|
||||
prefix += f" - {datetime.datetime.now() - self.start} (total)"
|
||||
print(f"{prefix}: {msg}", file=self.file)
|
||||
if self.file:
|
||||
self.file.flush()
|
||||
self.last = datetime.datetime.now()
|
||||
|
||||
|
||||
def logged_cmd(log_file, *vargs):
|
||||
result = None
|
||||
try:
|
||||
@@ -219,7 +273,7 @@ def determine_base_container(clone_dir, app_type="webapp"):
|
||||
return base_container
|
||||
|
||||
|
||||
def build_container_image(app_record, tag, extra_build_args=[], log_file=None):
|
||||
def build_container_image(app_record, tag, extra_build_args=[], logger=None):
|
||||
tmpdir = tempfile.mkdtemp()
|
||||
|
||||
try:
|
||||
@@ -228,31 +282,33 @@ def build_container_image(app_record, tag, extra_build_args=[], log_file=None):
|
||||
repo = random.choice(app_record.attributes.repository)
|
||||
clone_dir = os.path.join(tmpdir, record_id)
|
||||
|
||||
print(f"Cloning repository {repo} to {clone_dir} ...")
|
||||
logger.log(f"Cloning repository {repo} to {clone_dir} ...")
|
||||
if ref:
|
||||
# TODO: Determing branch or hash, and use depth 1 if we can.
|
||||
git_env = dict(os.environ.copy())
|
||||
# Never prompt
|
||||
git_env["GIT_TERMINAL_PROMPT"] = "0"
|
||||
try:
|
||||
subprocess.check_call(["git", "clone", repo, clone_dir], env=git_env, stdout=log_file, stderr=log_file)
|
||||
subprocess.check_call(["git", "clone", repo, clone_dir], env=git_env, stdout=logger.file, stderr=logger.file)
|
||||
except Exception as e:
|
||||
print(f"git clone failed. Is the repository {repo} private?", file=log_file)
|
||||
logger.log(f"git clone failed. Is the repository {repo} private?")
|
||||
raise e
|
||||
try:
|
||||
subprocess.check_call(["git", "checkout", ref], cwd=clone_dir, env=git_env, stdout=log_file, stderr=log_file)
|
||||
subprocess.check_call(["git", "checkout", ref], cwd=clone_dir, env=git_env, stdout=logger.file, stderr=logger.file)
|
||||
except Exception as e:
|
||||
print(f"git checkout failed. Does ref {ref} exist?", file=log_file)
|
||||
logger.log(f"git checkout failed. Does ref {ref} exist?")
|
||||
raise e
|
||||
else:
|
||||
result = subprocess.run(["git", "clone", "--depth", "1", repo, clone_dir], stdout=log_file, stderr=log_file)
|
||||
result = subprocess.run(["git", "clone", "--depth", "1", repo, clone_dir], stdout=logger.file, stderr=logger.file)
|
||||
result.check_returncode()
|
||||
|
||||
base_container = determine_base_container(clone_dir, app_record.attributes.app_type)
|
||||
|
||||
print("Building webapp ...")
|
||||
logger.log("Building webapp ...")
|
||||
build_command = [
|
||||
sys.argv[0], "build-webapp",
|
||||
sys.argv[0],
|
||||
"--verbose",
|
||||
"build-webapp",
|
||||
"--source-repo", clone_dir,
|
||||
"--tag", tag,
|
||||
"--base-container", base_container
|
||||
@@ -261,28 +317,31 @@ def build_container_image(app_record, tag, extra_build_args=[], log_file=None):
|
||||
build_command.append("--extra-build-args")
|
||||
build_command.append(" ".join(extra_build_args))
|
||||
|
||||
result = subprocess.run(build_command, stdout=log_file, stderr=log_file)
|
||||
result = subprocess.run(build_command, stdout=logger.file, stderr=logger.file)
|
||||
result.check_returncode()
|
||||
finally:
|
||||
logged_cmd(log_file, "rm", "-rf", tmpdir)
|
||||
logged_cmd(logger.file, "rm", "-rf", tmpdir)
|
||||
|
||||
|
||||
def push_container_image(deployment_dir, log_file=None):
|
||||
print("Pushing image ...")
|
||||
def push_container_image(deployment_dir, logger):
|
||||
logger.log("Pushing images ...")
|
||||
result = subprocess.run([sys.argv[0], "deployment", "--dir", deployment_dir, "push-images"],
|
||||
stdout=log_file, stderr=log_file)
|
||||
stdout=logger.file, stderr=logger.file)
|
||||
result.check_returncode()
|
||||
logger.log("Finished pushing images.")
|
||||
|
||||
|
||||
def deploy_to_k8s(deploy_record, deployment_dir, log_file=None):
|
||||
def deploy_to_k8s(deploy_record, deployment_dir, logger):
|
||||
if not deploy_record:
|
||||
command = "up"
|
||||
else:
|
||||
command = "update"
|
||||
|
||||
logger.log("Deploying to k8s ...")
|
||||
result = subprocess.run([sys.argv[0], "deployment", "--dir", deployment_dir, command],
|
||||
stdout=log_file, stderr=log_file)
|
||||
stdout=logger.file, stderr=logger.file)
|
||||
result.check_returncode()
|
||||
logger.log("Finished deploying to k8s.")
|
||||
|
||||
|
||||
def publish_deployment(laconic: LaconicRegistryClient,
|
||||
@@ -292,7 +351,8 @@ def publish_deployment(laconic: LaconicRegistryClient,
|
||||
dns_record,
|
||||
dns_crn,
|
||||
deployment_dir,
|
||||
app_deployment_request=None):
|
||||
app_deployment_request=None,
|
||||
logger=None):
|
||||
if not deploy_record:
|
||||
deploy_ver = "0.0.1"
|
||||
else:
|
||||
@@ -322,6 +382,8 @@ def publish_deployment(laconic: LaconicRegistryClient,
|
||||
if app_deployment_request:
|
||||
new_dns_record["record"]["request"] = app_deployment_request.id
|
||||
|
||||
if logger:
|
||||
logger.log("Publishing DnsRecord.")
|
||||
dns_id = laconic.publish(new_dns_record, [dns_crn])
|
||||
|
||||
new_deployment_record = {
|
||||
@@ -341,6 +403,8 @@ def publish_deployment(laconic: LaconicRegistryClient,
|
||||
if app_deployment_request:
|
||||
new_deployment_record["record"]["request"] = app_deployment_request.id
|
||||
|
||||
if logger:
|
||||
logger.log("Publishing ApplicationDeploymentRecord.")
|
||||
deployment_id = laconic.publish(new_deployment_record, [deployment_crn])
|
||||
return {"dns": dns_id, "deployment": deployment_id}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user