rdeploy 0.5.2__tar.gz → 0.5.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {rdeploy-0.5.2/rdeploy.egg-info → rdeploy-0.5.3}/PKG-INFO +15 -5
  2. {rdeploy-0.5.2 → rdeploy-0.5.3}/README.md +14 -4
  3. rdeploy-0.5.3/VERSION +1 -0
  4. rdeploy-0.5.3/rdeploy/helm_chart.py +147 -0
  5. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy/tasks.py +37 -22
  6. {rdeploy-0.5.2 → rdeploy-0.5.3/rdeploy.egg-info}/PKG-INFO +15 -5
  7. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy.egg-info/SOURCES.txt +2 -0
  8. rdeploy-0.5.3/tests/test_helm_chart.py +242 -0
  9. rdeploy-0.5.2/VERSION +0 -1
  10. {rdeploy-0.5.2 → rdeploy-0.5.3}/LICENSE +0 -0
  11. {rdeploy-0.5.2 → rdeploy-0.5.3}/pyproject.toml +0 -0
  12. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy/__init__.py +0 -0
  13. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy/exceptions.py +0 -0
  14. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy/gke_auth.py +0 -0
  15. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy/main.py +0 -0
  16. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy/utils.py +0 -0
  17. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy.egg-info/dependency_links.txt +0 -0
  18. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy.egg-info/entry_points.txt +0 -0
  19. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy.egg-info/requires.txt +0 -0
  20. {rdeploy-0.5.2 → rdeploy-0.5.3}/rdeploy.egg-info/top_level.txt +0 -0
  21. {rdeploy-0.5.2 → rdeploy-0.5.3}/setup.cfg +0 -0
  22. {rdeploy-0.5.2 → rdeploy-0.5.3}/tests/test_exceptions.py +0 -0
  23. {rdeploy-0.5.2 → rdeploy-0.5.3}/tests/test_gke_auth.py +0 -0
  24. {rdeploy-0.5.2 → rdeploy-0.5.3}/tests/test_main.py +0 -0
  25. {rdeploy-0.5.2 → rdeploy-0.5.3}/tests/test_tasks.py +0 -0
  26. {rdeploy-0.5.2 → rdeploy-0.5.3}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rdeploy
3
- Version: 0.5.2
3
+ Version: 0.5.3
4
4
  Summary: CLI that makes it easy to build and deploy an application to k8s.
5
5
  Author-email: Rehive <info@rehive.com>
6
6
  License: MIT
@@ -220,7 +220,7 @@ configs:
220
220
  region: us-central1
221
221
  helm_registry: us-central1-docker.pkg.dev
222
222
  helm_values_path: ./etc/helm/staging/values.yaml
223
- helm_chart: rehive-service
223
+ helm_chart: helm-charts/rehive-service
224
224
  helm_chart_version: 0.2.0
225
225
  helm_version: 3.14.0
226
226
  use_system_helm: true
@@ -237,7 +237,7 @@ configs:
237
237
  region: us-central1
238
238
  helm_registry: us-central1-docker.pkg.dev
239
239
  helm_values_path: ./etc/helm/production/values.yaml
240
- helm_chart: rehive-service
240
+ helm_chart: helm-charts/rehive-service
241
241
  helm_chart_version: 0.2.0
242
242
  helm_version: 3.14.0
243
243
  use_system_helm: true
@@ -279,13 +279,23 @@ configs:
279
279
  | `cloud_provider.kube_cluster` | Kubernetes cluster name |
280
280
  | `cloud_provider.region` | GCP region |
281
281
  | `cloud_provider.zone` | GCP zone (alternative to region) |
282
- | `cloud_provider.helm_registry` | OCI Helm registry (GCP Artifact Registry) |
282
+ | `cloud_provider.helm_registry` | Artifact Registry host for Helm charts, e.g. `us-central1-docker.pkg.dev`. When set, the chart is downloaded with gcloud (see below) |
283
283
  | `helm_values_path` | Path to Helm values file |
284
- | `helm_chart` | Helm chart name or OCI reference |
284
+ | `helm_chart` | Helm chart name; `REPOSITORY/CHART` when `helm_registry` is set |
285
285
  | `helm_chart_version` | Helm chart version |
286
286
  | `helm_version` | Helm binary version (for local installs) |
287
287
  | `use_system_helm` | Use system Helm binary (default: `true`) |
288
288
 
289
+ #### Charts in Artifact Registry
290
+
291
+ With `helm_registry` set, `install` and `upgrade` download the chart with
292
+ gcloud instead of logging Helm in to the registry: they resolve
293
+ `helm_chart_version` to a digest, download the chart, check it against the
294
+ digest, and pass Helm the local archive. This also works when the
295
+ organization requires certificate-based access, where Artifact Registry
296
+ rejects Helm's own login. You need read access to the repository
297
+ (`roles/artifactregistry.reader`).
298
+
289
299
  ## Versioning
290
300
 
291
301
  rdeploy uses semantic versioning for releases. The `git-release` command automates tagging:
@@ -183,7 +183,7 @@ configs:
183
183
  region: us-central1
184
184
  helm_registry: us-central1-docker.pkg.dev
185
185
  helm_values_path: ./etc/helm/staging/values.yaml
186
- helm_chart: rehive-service
186
+ helm_chart: helm-charts/rehive-service
187
187
  helm_chart_version: 0.2.0
188
188
  helm_version: 3.14.0
189
189
  use_system_helm: true
@@ -200,7 +200,7 @@ configs:
200
200
  region: us-central1
201
201
  helm_registry: us-central1-docker.pkg.dev
202
202
  helm_values_path: ./etc/helm/production/values.yaml
203
- helm_chart: rehive-service
203
+ helm_chart: helm-charts/rehive-service
204
204
  helm_chart_version: 0.2.0
205
205
  helm_version: 3.14.0
206
206
  use_system_helm: true
@@ -242,13 +242,23 @@ configs:
242
242
  | `cloud_provider.kube_cluster` | Kubernetes cluster name |
243
243
  | `cloud_provider.region` | GCP region |
244
244
  | `cloud_provider.zone` | GCP zone (alternative to region) |
245
- | `cloud_provider.helm_registry` | OCI Helm registry (GCP Artifact Registry) |
245
+ | `cloud_provider.helm_registry` | Artifact Registry host for Helm charts, e.g. `us-central1-docker.pkg.dev`. When set, the chart is downloaded with gcloud (see below) |
246
246
  | `helm_values_path` | Path to Helm values file |
247
- | `helm_chart` | Helm chart name or OCI reference |
247
+ | `helm_chart` | Helm chart name; `REPOSITORY/CHART` when `helm_registry` is set |
248
248
  | `helm_chart_version` | Helm chart version |
249
249
  | `helm_version` | Helm binary version (for local installs) |
250
250
  | `use_system_helm` | Use system Helm binary (default: `true`) |
251
251
 
252
+ #### Charts in Artifact Registry
253
+
254
+ With `helm_registry` set, `install` and `upgrade` download the chart with
255
+ gcloud instead of logging Helm in to the registry: they resolve
256
+ `helm_chart_version` to a digest, download the chart, check it against the
257
+ digest, and pass Helm the local archive. This also works when the
258
+ organization requires certificate-based access, where Artifact Registry
259
+ rejects Helm's own login. You need read access to the repository
260
+ (`roles/artifactregistry.reader`).
261
+
252
262
  ## Versioning
253
263
 
254
264
  rdeploy uses semantic versioning for releases. The `git-release` command automates tagging:
rdeploy-0.5.3/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.5.3
@@ -0,0 +1,147 @@
1
+ """
2
+ Download Helm charts from Google Artifact Registry through gcloud.
3
+
4
+ Helm logs in to an OCI registry with a bearer token. When the organization
5
+ enforces certificate-based access, Artifact Registry rejects that token,
6
+ because Helm cannot present the device certificate. gcloud can, so rdeploy
7
+ downloads the chart with gcloud and hands Helm the local archive.
8
+
9
+ A chart in Artifact Registry is an OCI artifact: the tag points to a manifest,
10
+ and the manifest names one layer, the chart's .tgz. Both are checked against
11
+ their sha256 digests before Helm sees them.
12
+ """
13
+ import atexit
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import tempfile
21
+
22
+ CHART_LAYER_MEDIA_TYPE = 'application/vnd.cncf.helm.chart.content.v1.tar+gzip'
23
+ REGISTRY_HOST = re.compile(r'^(?:https?://)?(?P<location>[a-z0-9-]+)-docker\.pkg\.dev/?$')
24
+
25
+
26
+ class ChartFetchError(Exception):
27
+ pass
28
+
29
+
30
+ def registry_location(helm_registry):
31
+ """`europe-west4-docker.pkg.dev` -> `europe-west4`."""
32
+ match = REGISTRY_HOST.match(helm_registry.strip())
33
+ if not match:
34
+ raise ChartFetchError(
35
+ 'helm_registry {registry!r} is not an Artifact Registry Docker host'
36
+ ' (LOCATION-docker.pkg.dev).'.format(registry=helm_registry))
37
+ return match.group('location')
38
+
39
+
40
+ def split_chart(helm_chart):
41
+ """`my-repo/my-chart` -> (`my-repo`, `my-chart`)."""
42
+ repository, _, package = helm_chart.strip('/').partition('/')
43
+ if not repository or not package:
44
+ raise ChartFetchError(
45
+ 'helm_chart {chart!r} must be REPOSITORY/CHART when helm_registry'
46
+ ' is set.'.format(chart=helm_chart))
47
+ return repository, package
48
+
49
+
50
+ def run_gcloud(cmd):
51
+ """
52
+ Run gcloud, capturing only its output. Prompts and errors go to the
53
+ terminal, so gcloud can ask for reauthentication.
54
+ """
55
+ result = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
56
+ if result.returncode != 0:
57
+ raise ChartFetchError('gcloud failed: {cmd}'.format(cmd=' '.join(cmd)))
58
+ return result.stdout
59
+
60
+
61
+ def sha256_file(path):
62
+ digest = hashlib.sha256()
63
+ with open(path, 'rb') as f:
64
+ for block in iter(lambda: f.read(1 << 16), b''):
65
+ digest.update(block)
66
+ return 'sha256:' + digest.hexdigest()
67
+
68
+
69
+ def resolve_digest(host, project, repository, package, chart_version):
70
+ image = '{host}/{project}/{repository}/{package}:{version}'.format(
71
+ host=host, project=project, repository=repository, package=package,
72
+ version=chart_version)
73
+ digest = run_gcloud([
74
+ 'gcloud', 'artifacts', 'docker', 'images', 'describe', image,
75
+ '--format=value(image_summary.digest)',
76
+ ]).strip()
77
+ if not digest.startswith('sha256:'):
78
+ raise ChartFetchError('Could not resolve {image} to a digest.'.format(image=image))
79
+ return digest
80
+
81
+
82
+ def download_file(project, location, repository, name, destination, filename):
83
+ run_gcloud([
84
+ 'gcloud', 'artifacts', 'files', 'download', name,
85
+ '--project={0}'.format(project),
86
+ '--location={0}'.format(location),
87
+ '--repository={0}'.format(repository),
88
+ '--destination={0}'.format(destination),
89
+ '--local-filename={0}'.format(filename),
90
+ '--allow-overwrite',
91
+ ])
92
+ return os.path.join(destination, filename)
93
+
94
+
95
+ def verified(path, digest, what):
96
+ actual = sha256_file(path)
97
+ if actual != digest:
98
+ raise ChartFetchError(
99
+ '{what} digest mismatch: expected {expected}, got {actual}.'
100
+ .format(what=what, expected=digest, actual=actual))
101
+ return path
102
+
103
+
104
+ def chart_layer_digest(manifest_path):
105
+ with open(manifest_path) as f:
106
+ manifest = json.load(f)
107
+ layers = [layer for layer in manifest.get('layers', [])
108
+ if layer.get('mediaType') == CHART_LAYER_MEDIA_TYPE]
109
+ if len(layers) != 1:
110
+ raise ChartFetchError(
111
+ 'Expected one Helm chart layer in the manifest, found {count}.'
112
+ .format(count=len(layers)))
113
+ return layers[0]['digest']
114
+
115
+
116
+ def fetch_chart(helm_registry, project, helm_chart, chart_version, destination=None):
117
+ """
118
+ Download `helm_chart` at `chart_version` from Artifact Registry with
119
+ gcloud and return the path of the verified chart archive.
120
+
121
+ Without `destination`, the archive goes to a temporary directory that is
122
+ removed when rdeploy exits.
123
+ """
124
+ location = registry_location(helm_registry)
125
+ host = '{location}-docker.pkg.dev'.format(location=location)
126
+ repository, package = split_chart(helm_chart)
127
+
128
+ if destination is None:
129
+ destination = tempfile.mkdtemp(prefix='rdeploy-chart-')
130
+ atexit.register(shutil.rmtree, destination, True)
131
+
132
+ print('Downloading chart {chart} {version} with gcloud'.format(
133
+ chart=helm_chart, version=chart_version), flush=True)
134
+
135
+ manifest_digest = resolve_digest(host, project, repository, package, chart_version)
136
+ manifest = verified(
137
+ download_file(project, location, repository,
138
+ '{package}/manifests/{digest}'.format(package=package, digest=manifest_digest),
139
+ destination, 'manifest.json'),
140
+ manifest_digest, 'Manifest')
141
+
142
+ layer_digest = chart_layer_digest(manifest)
143
+ filename = '{name}-{version}.tgz'.format(name=package.rsplit('/', 1)[-1],
144
+ version=chart_version)
145
+ return verified(
146
+ download_file(project, location, repository, layer_digest, destination, filename),
147
+ layer_digest, 'Chart')
@@ -17,6 +17,7 @@ import re
17
17
  from packaging import version
18
18
  from rdeploy.exceptions import ReleaseError, ExecuteError
19
19
  from rdeploy import gke_auth
20
+ from rdeploy.helm_chart import fetch_chart, ChartFetchError
20
21
 
21
22
  from rdeploy.utils import (get_settings, confirm, get_helm_bin, get_helm_os_string,
22
23
  yaml_decode_data_fields, build_management_cmd,
@@ -342,6 +343,33 @@ def create_public_bucket(ctx, config, bucket_name):
342
343
  .format(bucket_name=bucket_name))
343
344
 
344
345
 
346
+ def resolve_helm_chart(config_dict):
347
+ """
348
+ Return the chart for helm install/upgrade and its --version flag.
349
+
350
+ A chart in Artifact Registry (cloud_provider.helm_registry) is downloaded
351
+ with gcloud, which works under certificate-based access where Helm's own
352
+ registry login is rejected. Helm then gets the local archive, which is
353
+ already the configured version, so no --version flag is passed.
354
+ """
355
+ provider_data = config_dict.get('cloud_provider') or {}
356
+ helm_registry = provider_data.get('helm_registry')
357
+ if not helm_registry:
358
+ return (config_dict['helm_chart'],
359
+ ' --version {0}'.format(config_dict['helm_chart_version']))
360
+ try:
361
+ path = fetch_chart(helm_registry, provider_data['project'],
362
+ config_dict['helm_chart'],
363
+ config_dict['helm_chart_version'])
364
+ except ChartFetchError as err:
365
+ sys.exit('Could not download the Helm chart: {err}'.format(err=err))
366
+ # invoke runs commands through sh, or cmd.exe on Windows, which needs
367
+ # double quotes rather than single quotes around a path.
368
+ if sys.platform == 'win32':
369
+ return subprocess.list2cmdline([path]), ''
370
+ return shlex.quote(path), ''
371
+
372
+
345
373
  @task
346
374
  def install(ctx, config):
347
375
  """
@@ -358,28 +386,22 @@ def install(ctx, config):
358
386
  if config_dict.get('helm_version') and version.parse(str(config_dict['helm_version'])) <= version.parse('3'):
359
387
  install_flag = " --name"
360
388
 
361
- provider_data = config_dict.get('cloud_provider')
362
- helm_registry = provider_data.get('helm_registry')
363
- if helm_registry:
364
- # Authenticate with the GCP Artifact Registry
365
- ctx.run('gcloud auth print-access-token | {helm_bin} registry login -u oauth2accesstoken --password-stdin https://{helm_registry}'.format(helm_registry=helm_registry, helm_bin=helm_bin), echo=True)
366
- helm_chart = 'oci://{helm_registry}/{gcp_project}/{helm_chart}'.format(helm_registry=helm_registry, gcp_project=provider_data['project'], helm_chart=config_dict['helm_chart'])
367
- else:
389
+ if not (config_dict.get('cloud_provider') or {}).get('helm_registry'):
368
390
  # Add the Rehive Helm Repo
369
391
  ctx.run('{helm_bin} repo add rehive https://rehive.github.io/charts'.format(helm_bin=helm_bin), echo=True)
370
- helm_chart = config_dict['helm_chart']
392
+ helm_chart, version_flag = resolve_helm_chart(config_dict)
371
393
 
372
394
  ctx.run('{helm_bin} install{helm_install_flag} {project_name} '
373
395
  '{target} '
374
- '--values {helm_values_path} '
375
- '--version {helm_chart_version} {helm_chart}'
396
+ '--values {helm_values_path}'
397
+ '{version_flag} {helm_chart}'
376
398
  .format(helm_bin=helm_bin,
377
399
  target=helm_target_flags(settings_dict, config_dict),
378
400
  project_name=config_dict['project_name'],
379
401
  helm_install_flag=install_flag,
380
402
  helm_values_path=config_dict['helm_values_path'],
381
403
  helm_chart=helm_chart,
382
- helm_chart_version=config_dict['helm_chart_version']),
404
+ version_flag=version_flag),
383
405
  echo=True)
384
406
 
385
407
 
@@ -580,14 +602,7 @@ def upgrade(ctx, config, tag, atomic=True, timeout='15m', progress=True):
580
602
 
581
603
  helm_bin = get_helm_bin(config_dict)
582
604
 
583
- provider_data = config_dict.get('cloud_provider')
584
- helm_registry = provider_data.get('helm_registry')
585
- if helm_registry:
586
- # Authenticate with the GCP Artifact Registry
587
- ctx.run('gcloud auth print-access-token | {helm_bin} registry login -u oauth2accesstoken --password-stdin https://{helm_registry}'.format(helm_registry=helm_registry, helm_bin=helm_bin), echo=True)
588
- helm_chart = 'oci://{helm_registry}/{gcp_project}/{helm_chart}'.format(helm_registry=helm_registry, gcp_project=provider_data['project'], helm_chart=config_dict['helm_chart'])
589
- else:
590
- helm_chart = config_dict['helm_chart']
605
+ helm_chart, version_flag = resolve_helm_chart(config_dict)
591
606
 
592
607
  atomic_flags = ' --atomic --timeout {timeout}'.format(timeout=timeout) if atomic else ''
593
608
 
@@ -618,15 +633,15 @@ def upgrade(ctx, config, tag, atomic=True, timeout='15m', progress=True):
618
633
  helm_command = ('{helm_bin} upgrade {project_name} '
619
634
  '{target} '
620
635
  '--values {helm_values_path} '
621
- '--set image.tag={version} '
622
- '--version {helm_chart_version}{atomic_flags} {helm_chart}'
636
+ '--set image.tag={version}'
637
+ '{version_flag}{atomic_flags} {helm_chart}'
623
638
  .format(helm_bin=helm_bin,
624
639
  target=helm_target_flags(settings_dict, config_dict),
625
640
  project_name=config_dict['project_name'],
626
641
  helm_chart=helm_chart,
627
642
  helm_values_path=config_dict['helm_values_path'],
628
643
  version=tag,
629
- helm_chart_version=config_dict['helm_chart_version'],
644
+ version_flag=version_flag,
630
645
  atomic_flags=atomic_flags))
631
646
 
632
647
  # The helm call below is the sole source of truth for success/failure/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rdeploy
3
- Version: 0.5.2
3
+ Version: 0.5.3
4
4
  Summary: CLI that makes it easy to build and deploy an application to k8s.
5
5
  Author-email: Rehive <info@rehive.com>
6
6
  License: MIT
@@ -220,7 +220,7 @@ configs:
220
220
  region: us-central1
221
221
  helm_registry: us-central1-docker.pkg.dev
222
222
  helm_values_path: ./etc/helm/staging/values.yaml
223
- helm_chart: rehive-service
223
+ helm_chart: helm-charts/rehive-service
224
224
  helm_chart_version: 0.2.0
225
225
  helm_version: 3.14.0
226
226
  use_system_helm: true
@@ -237,7 +237,7 @@ configs:
237
237
  region: us-central1
238
238
  helm_registry: us-central1-docker.pkg.dev
239
239
  helm_values_path: ./etc/helm/production/values.yaml
240
- helm_chart: rehive-service
240
+ helm_chart: helm-charts/rehive-service
241
241
  helm_chart_version: 0.2.0
242
242
  helm_version: 3.14.0
243
243
  use_system_helm: true
@@ -279,13 +279,23 @@ configs:
279
279
  | `cloud_provider.kube_cluster` | Kubernetes cluster name |
280
280
  | `cloud_provider.region` | GCP region |
281
281
  | `cloud_provider.zone` | GCP zone (alternative to region) |
282
- | `cloud_provider.helm_registry` | OCI Helm registry (GCP Artifact Registry) |
282
+ | `cloud_provider.helm_registry` | Artifact Registry host for Helm charts, e.g. `us-central1-docker.pkg.dev`. When set, the chart is downloaded with gcloud (see below) |
283
283
  | `helm_values_path` | Path to Helm values file |
284
- | `helm_chart` | Helm chart name or OCI reference |
284
+ | `helm_chart` | Helm chart name; `REPOSITORY/CHART` when `helm_registry` is set |
285
285
  | `helm_chart_version` | Helm chart version |
286
286
  | `helm_version` | Helm binary version (for local installs) |
287
287
  | `use_system_helm` | Use system Helm binary (default: `true`) |
288
288
 
289
+ #### Charts in Artifact Registry
290
+
291
+ With `helm_registry` set, `install` and `upgrade` download the chart with
292
+ gcloud instead of logging Helm in to the registry: they resolve
293
+ `helm_chart_version` to a digest, download the chart, check it against the
294
+ digest, and pass Helm the local archive. This also works when the
295
+ organization requires certificate-based access, where Artifact Registry
296
+ rejects Helm's own login. You need read access to the repository
297
+ (`roles/artifactregistry.reader`).
298
+
289
299
  ## Versioning
290
300
 
291
301
  rdeploy uses semantic versioning for releases. The `git-release` command automates tagging:
@@ -5,6 +5,7 @@ pyproject.toml
5
5
  rdeploy/__init__.py
6
6
  rdeploy/exceptions.py
7
7
  rdeploy/gke_auth.py
8
+ rdeploy/helm_chart.py
8
9
  rdeploy/main.py
9
10
  rdeploy/tasks.py
10
11
  rdeploy/utils.py
@@ -16,6 +17,7 @@ rdeploy.egg-info/requires.txt
16
17
  rdeploy.egg-info/top_level.txt
17
18
  tests/test_exceptions.py
18
19
  tests/test_gke_auth.py
20
+ tests/test_helm_chart.py
19
21
  tests/test_main.py
20
22
  tests/test_tasks.py
21
23
  tests/test_utils.py
@@ -0,0 +1,242 @@
1
+ import hashlib
2
+ import json
3
+ import os
4
+ from unittest.mock import MagicMock, patch
5
+
6
+ import pytest
7
+ from invoke import Context
8
+
9
+ from rdeploy import helm_chart
10
+ from rdeploy.helm_chart import (
11
+ CHART_LAYER_MEDIA_TYPE,
12
+ ChartFetchError,
13
+ chart_layer_digest,
14
+ fetch_chart,
15
+ registry_location,
16
+ split_chart,
17
+ )
18
+ from rdeploy.tasks import install, resolve_helm_chart, upgrade
19
+
20
+ CHART = b'fake chart archive'
21
+ CHART_DIGEST = 'sha256:' + hashlib.sha256(CHART).hexdigest()
22
+ MANIFEST = json.dumps({
23
+ 'schemaVersion': 2,
24
+ 'config': {'mediaType': 'application/vnd.cncf.helm.config.v1+json',
25
+ 'digest': 'sha256:' + 'c' * 64, 'size': 10},
26
+ 'layers': [{'mediaType': CHART_LAYER_MEDIA_TYPE,
27
+ 'digest': CHART_DIGEST, 'size': len(CHART)}],
28
+ }).encode()
29
+ MANIFEST_DIGEST = 'sha256:' + hashlib.sha256(MANIFEST).hexdigest()
30
+
31
+
32
+ class FakeGcloud:
33
+ """Stands in for gcloud: resolves the tag and serves the stored files."""
34
+
35
+ def __init__(self, files=None, digest=MANIFEST_DIGEST, fail=False):
36
+ self.files = files if files is not None else {
37
+ 'rehive-service/manifests/' + MANIFEST_DIGEST: MANIFEST,
38
+ CHART_DIGEST: CHART,
39
+ }
40
+ self.digest = digest
41
+ self.fail = fail
42
+ self.calls = []
43
+
44
+ def __call__(self, cmd, **kwargs):
45
+ self.calls.append(cmd)
46
+ if self.fail:
47
+ return MagicMock(returncode=1, stdout='')
48
+ if cmd[1:5] == ['artifacts', 'docker', 'images', 'describe']:
49
+ return MagicMock(returncode=0, stdout=self.digest + '\n')
50
+ if cmd[1:4] == ['artifacts', 'files', 'download']:
51
+ name = cmd[4]
52
+ flags = dict(arg[2:].split('=', 1) for arg in cmd[5:] if '=' in arg)
53
+ if name not in self.files:
54
+ return MagicMock(returncode=1, stdout='')
55
+ with open(os.path.join(flags['destination'], flags['local-filename']), 'wb') as f:
56
+ f.write(self.files[name])
57
+ return MagicMock(returncode=0, stdout='')
58
+ raise AssertionError('unexpected gcloud call: {}'.format(cmd))
59
+
60
+
61
+ def fetch(tmp_path, gcloud):
62
+ with patch('rdeploy.helm_chart.subprocess.run', side_effect=gcloud):
63
+ return fetch_chart('europe-west4-docker.pkg.dev', 'my-project',
64
+ 'my-charts/rehive-service', '1.2.0',
65
+ destination=str(tmp_path))
66
+
67
+
68
+ class TestParsing:
69
+ @pytest.mark.parametrize('registry', [
70
+ 'europe-west4-docker.pkg.dev',
71
+ 'https://europe-west4-docker.pkg.dev',
72
+ 'europe-west4-docker.pkg.dev/',
73
+ ])
74
+ def test_registry_location(self, registry):
75
+ assert registry_location(registry) == 'europe-west4'
76
+
77
+ def test_multi_region_location(self):
78
+ assert registry_location('us-docker.pkg.dev') == 'us'
79
+
80
+ @pytest.mark.parametrize('registry', ['gcr.io', 'ghcr.io', 'europe-west4-npm.pkg.dev'])
81
+ def test_rejects_other_registries(self, registry):
82
+ with pytest.raises(ChartFetchError):
83
+ registry_location(registry)
84
+
85
+ def test_split_chart(self):
86
+ assert split_chart('my-charts/rehive-service') == ('my-charts', 'rehive-service')
87
+
88
+ def test_split_chart_needs_repository(self):
89
+ with pytest.raises(ChartFetchError):
90
+ split_chart('rehive-service')
91
+
92
+ def test_chart_layer_digest(self, tmp_path):
93
+ path = tmp_path / 'manifest.json'
94
+ path.write_bytes(MANIFEST)
95
+ assert chart_layer_digest(str(path)) == CHART_DIGEST
96
+
97
+ def test_manifest_without_chart_layer(self, tmp_path):
98
+ path = tmp_path / 'manifest.json'
99
+ path.write_text(json.dumps({'layers': [{'mediaType': 'other', 'digest': 'x'}]}))
100
+ with pytest.raises(ChartFetchError, match='found 0'):
101
+ chart_layer_digest(str(path))
102
+
103
+
104
+ class TestFetchChart:
105
+ def test_downloads_and_verifies_chart(self, tmp_path):
106
+ gcloud = FakeGcloud()
107
+ path = fetch(tmp_path, gcloud)
108
+ assert path == str(tmp_path / 'rehive-service-1.2.0.tgz')
109
+ with open(path, 'rb') as f:
110
+ assert f.read() == CHART
111
+
112
+ def test_gcloud_calls(self, tmp_path):
113
+ gcloud = FakeGcloud()
114
+ fetch(tmp_path, gcloud)
115
+ describe, manifest, chart = gcloud.calls
116
+ assert describe[5] == 'europe-west4-docker.pkg.dev/my-project/my-charts/rehive-service:1.2.0'
117
+ assert manifest[4] == 'rehive-service/manifests/' + MANIFEST_DIGEST
118
+ assert chart[4] == CHART_DIGEST
119
+ for call in (manifest, chart):
120
+ assert '--project=my-project' in call
121
+ assert '--location=europe-west4' in call
122
+ assert '--repository=my-charts' in call
123
+
124
+ def test_never_asks_gcloud_for_a_token(self, tmp_path):
125
+ gcloud = FakeGcloud()
126
+ fetch(tmp_path, gcloud)
127
+ assert not any('print-access-token' in call for call in gcloud.calls)
128
+
129
+ def test_gcloud_prompts_reach_the_terminal(self, tmp_path):
130
+ with patch('rdeploy.helm_chart.subprocess.run', side_effect=FakeGcloud()) as run:
131
+ fetch_chart('europe-west4-docker.pkg.dev', 'my-project',
132
+ 'my-charts/rehive-service', '1.2.0', destination=str(tmp_path))
133
+ for call in run.call_args_list:
134
+ assert 'stderr' not in call.kwargs
135
+ assert 'stdin' not in call.kwargs
136
+
137
+ def test_rejects_tampered_chart(self, tmp_path):
138
+ gcloud = FakeGcloud()
139
+ gcloud.files[CHART_DIGEST] = b'something else'
140
+ with pytest.raises(ChartFetchError, match='Chart digest mismatch'):
141
+ fetch(tmp_path, gcloud)
142
+
143
+ def test_rejects_tampered_manifest(self, tmp_path):
144
+ gcloud = FakeGcloud()
145
+ gcloud.files['rehive-service/manifests/' + MANIFEST_DIGEST] = MANIFEST + b' '
146
+ with pytest.raises(ChartFetchError, match='Manifest digest mismatch'):
147
+ fetch(tmp_path, gcloud)
148
+
149
+ def test_unresolved_tag(self, tmp_path):
150
+ with pytest.raises(ChartFetchError, match='digest'):
151
+ fetch(tmp_path, FakeGcloud(digest=''))
152
+
153
+ def test_gcloud_failure(self, tmp_path):
154
+ with pytest.raises(ChartFetchError, match='gcloud failed'):
155
+ fetch(tmp_path, FakeGcloud(fail=True))
156
+
157
+ def test_temporary_destination_is_cleaned_up(self):
158
+ registered = []
159
+ with patch('rdeploy.helm_chart.subprocess.run', side_effect=FakeGcloud()), \
160
+ patch('rdeploy.helm_chart.atexit.register',
161
+ side_effect=lambda *args: registered.append(args)):
162
+ path = fetch_chart('europe-west4-docker.pkg.dev', 'my-project',
163
+ 'my-charts/rehive-service', '1.2.0')
164
+ cleanup, directory, _ = registered[0]
165
+ assert os.path.dirname(path) == directory
166
+ cleanup(directory, True)
167
+ assert not os.path.exists(directory)
168
+
169
+
170
+ def registry_config(helm_registry='europe-west4-docker.pkg.dev'):
171
+ return {
172
+ 'namespace': 'staging-ns',
173
+ 'project_name': 'my-service',
174
+ 'helm_chart': 'my-charts/rehive-service',
175
+ 'helm_chart_version': '1.2.0',
176
+ 'helm_values_path': 'etc/helm/staging.yaml',
177
+ 'cloud_provider': {'name': 'gcp', 'project': 'my-project',
178
+ 'kube_cluster': 'cluster-1', 'region': 'europe-west4',
179
+ 'helm_registry': helm_registry},
180
+ }
181
+
182
+
183
+ class TestResolveHelmChart:
184
+ def test_repository_chart_keeps_version_flag(self):
185
+ config = registry_config(helm_registry=None)
186
+ config['helm_chart'] = 'rehive/service'
187
+ assert resolve_helm_chart(config) == ('rehive/service', ' --version 1.2.0')
188
+
189
+ def test_registry_chart_is_downloaded(self):
190
+ with patch('rdeploy.tasks.fetch_chart', return_value='/tmp/x/rehive-service-1.2.0.tgz') as fetch_mock:
191
+ assert resolve_helm_chart(registry_config()) == ('/tmp/x/rehive-service-1.2.0.tgz', '')
192
+ fetch_mock.assert_called_once_with('europe-west4-docker.pkg.dev', 'my-project',
193
+ 'my-charts/rehive-service', '1.2.0')
194
+
195
+ def test_path_is_quoted(self):
196
+ with patch('rdeploy.tasks.fetch_chart', return_value='/tmp/a b/chart.tgz'):
197
+ assert resolve_helm_chart(registry_config())[0] == "'/tmp/a b/chart.tgz'"
198
+
199
+ def test_windows_path_is_double_quoted(self):
200
+ path = r'C:\Users\a b\AppData\Local\Temp\rdeploy-chart-x\chart.tgz'
201
+ with patch('rdeploy.tasks.fetch_chart', return_value=path), \
202
+ patch('rdeploy.tasks.sys.platform', 'win32'):
203
+ assert resolve_helm_chart(registry_config())[0] == '"{}"'.format(path)
204
+
205
+ def test_windows_path_without_spaces_is_unquoted(self):
206
+ path = r'C:\Temp\rdeploy-chart-x\chart.tgz'
207
+ with patch('rdeploy.tasks.fetch_chart', return_value=path), \
208
+ patch('rdeploy.tasks.sys.platform', 'win32'):
209
+ assert resolve_helm_chart(registry_config())[0] == path
210
+
211
+ def test_download_failure_exits(self):
212
+ with patch('rdeploy.tasks.fetch_chart', side_effect=ChartFetchError('boom')):
213
+ with pytest.raises(SystemExit, match='Could not download the Helm chart: boom'):
214
+ resolve_helm_chart(registry_config())
215
+
216
+
217
+ class TestTasksUseDownloadedChart:
218
+ def settings(self):
219
+ return {'version': '3', 'configs': {'staging': registry_config()}}
220
+
221
+ def run_task(self, task, **kwargs):
222
+ ctx = MagicMock(spec=Context)
223
+ ctx.run.return_value = MagicMock(failed=False)
224
+ with patch('rdeploy.tasks.get_settings', return_value=self.settings()), \
225
+ patch('rdeploy.tasks.set_context'), \
226
+ patch('rdeploy.tasks._watch_rollout'), \
227
+ patch('rdeploy.tasks.fetch_chart', return_value='/tmp/x/rehive-service-1.2.0.tgz'):
228
+ task(ctx, 'staging', **kwargs)
229
+ return [call.args[0] for call in ctx.run.call_args_list]
230
+
231
+ @pytest.mark.parametrize('task,kwargs', [(upgrade, {'tag': '1.0.0'}), (install, {})])
232
+ def test_helm_gets_local_chart(self, task, kwargs):
233
+ commands = self.run_task(task, **kwargs)
234
+ helm_command = commands[-1]
235
+ assert helm_command.endswith(' /tmp/x/rehive-service-1.2.0.tgz')
236
+ assert '--version' not in helm_command
237
+ assert 'oci://' not in helm_command
238
+ assert not any('registry login' in c or 'print-access-token' in c for c in commands)
239
+
240
+ def test_upgrade_flags_intact(self):
241
+ helm_command = self.run_task(upgrade, tag='1.0.0')[-1]
242
+ assert '--set image.tag=1.0.0 --atomic --timeout 15m /tmp/x/' in helm_command
rdeploy-0.5.2/VERSION DELETED
@@ -1 +0,0 @@
1
- 0.5.2
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes