rdeploy 0.5.2__tar.gz → 0.5.4__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.4}/PKG-INFO +19 -5
  2. {rdeploy-0.5.2 → rdeploy-0.5.4}/README.md +18 -4
  3. rdeploy-0.5.4/VERSION +1 -0
  4. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy/gke_auth.py +30 -3
  5. rdeploy-0.5.4/rdeploy/helm_chart.py +158 -0
  6. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy/tasks.py +37 -22
  7. {rdeploy-0.5.2 → rdeploy-0.5.4/rdeploy.egg-info}/PKG-INFO +19 -5
  8. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy.egg-info/SOURCES.txt +2 -0
  9. {rdeploy-0.5.2 → rdeploy-0.5.4}/tests/test_gke_auth.py +63 -0
  10. rdeploy-0.5.4/tests/test_helm_chart.py +270 -0
  11. rdeploy-0.5.2/VERSION +0 -1
  12. {rdeploy-0.5.2 → rdeploy-0.5.4}/LICENSE +0 -0
  13. {rdeploy-0.5.2 → rdeploy-0.5.4}/pyproject.toml +0 -0
  14. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy/__init__.py +0 -0
  15. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy/exceptions.py +0 -0
  16. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy/main.py +0 -0
  17. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy/utils.py +0 -0
  18. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy.egg-info/dependency_links.txt +0 -0
  19. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy.egg-info/entry_points.txt +0 -0
  20. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy.egg-info/requires.txt +0 -0
  21. {rdeploy-0.5.2 → rdeploy-0.5.4}/rdeploy.egg-info/top_level.txt +0 -0
  22. {rdeploy-0.5.2 → rdeploy-0.5.4}/setup.cfg +0 -0
  23. {rdeploy-0.5.2 → rdeploy-0.5.4}/tests/test_exceptions.py +0 -0
  24. {rdeploy-0.5.2 → rdeploy-0.5.4}/tests/test_main.py +0 -0
  25. {rdeploy-0.5.2 → rdeploy-0.5.4}/tests/test_tasks.py +0 -0
  26. {rdeploy-0.5.2 → rdeploy-0.5.4}/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.4
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,27 @@ 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
+
299
+ If gcloud's login has expired, rdeploy asks before running `gcloud auth
300
+ login`. Without a terminal, such as in a script, it stops and tells you to
301
+ run it.
302
+
289
303
  ## Versioning
290
304
 
291
305
  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,27 @@ 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
+
262
+ If gcloud's login has expired, rdeploy asks before running `gcloud auth
263
+ login`. Without a terminal, such as in a script, it stops and tells you to
264
+ run it.
265
+
252
266
  ## Versioning
253
267
 
254
268
  rdeploy uses semantic versioning for releases. The `git-release` command automates tagging:
rdeploy-0.5.4/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.5.4
@@ -58,6 +58,10 @@ class KubectlLoginError(Exception):
58
58
  pass
59
59
 
60
60
 
61
+ class GcloudLoginError(KubectlLoginError):
62
+ """gcloud is not signed in and rdeploy did not sign it in."""
63
+
64
+
61
65
  # Paths and saved settings
62
66
  ##########################
63
67
 
@@ -179,7 +183,16 @@ def run_gcloud(cmd):
179
183
  return subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
180
184
 
181
185
 
182
- def ensure_gcloud_login(account=None):
186
+ def ask_yes_no(question):
187
+ """Ask in the terminal; only an explicit yes counts, so Enter means no."""
188
+ try:
189
+ answer = input(question + ' [y/N] ')
190
+ except EOFError:
191
+ return False
192
+ return answer.strip().lower() in ('y', 'yes')
193
+
194
+
195
+ def ensure_gcloud_login(account=None, ask=False):
183
196
  """
184
197
  Make sure gcloud can get a token for `account` (default: the active
185
198
  account) before rdeploy uses it, signing gcloud in again if needed.
@@ -187,6 +200,10 @@ def ensure_gcloud_login(account=None):
187
200
  A password or security-key reauthentication is left to gcloud, which
188
201
  prompts for it in the terminal. When gcloud's login has expired, or there
189
202
  is none, run `gcloud auth login`, which signs in through the browser.
203
+
204
+ With `ask`, rdeploy asks before opening the browser, and without a
205
+ terminal to ask in it stops instead. Commands that are not themselves a
206
+ sign-in, such as a deploy, use this.
190
207
  """
191
208
  account_flag = [f'--account={account}'] if account else []
192
209
  # The token itself is never needed: it goes to /dev/null, so rdeploy never
@@ -199,10 +216,20 @@ def ensure_gcloud_login(account=None):
199
216
  if ('reauth' in check.stderr.lower()
200
217
  and subprocess.run(token_cmd, stdout=subprocess.DEVNULL).returncode == 0):
201
218
  return
202
- print('gcloud needs you to sign in again. Opening your browser for gcloud first.', flush=True)
203
219
  login_cmd = ['gcloud', 'auth', 'login'] + ([account] if account else [])
220
+ if ask:
221
+ who = account or gcloud_account()
222
+ expired = 'Your gcloud login{who} has expired or is missing.'.format(
223
+ who=' for {0}'.format(who) if who else '')
224
+ if not (sys.stdin.isatty() and ask_yes_no(
225
+ expired + ' Sign in again now with `gcloud auth login`?')):
226
+ raise GcloudLoginError(
227
+ '{expired} Run `{cmd}`, then run this command again.'.format(
228
+ expired=expired, cmd=' '.join(login_cmd)))
229
+ else:
230
+ print('gcloud needs you to sign in again. Opening your browser for gcloud first.', flush=True)
204
231
  if subprocess.run(login_cmd).returncode != 0:
205
- raise KubectlLoginError('gcloud sign-in failed; gcloud\'s error is above.')
232
+ raise GcloudLoginError('gcloud sign-in failed; gcloud\'s error is above.')
206
233
 
207
234
 
208
235
  def load_client(project, secret, account=None, client_json=None):
@@ -0,0 +1,158 @@
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
+ from rdeploy.gke_auth import GcloudLoginError, ensure_gcloud_login
23
+
24
+ CHART_LAYER_MEDIA_TYPE = 'application/vnd.cncf.helm.chart.content.v1.tar+gzip'
25
+ REGISTRY_HOST = re.compile(r'^(?:https?://)?(?P<location>[a-z0-9-]+)-docker\.pkg\.dev/?$')
26
+
27
+
28
+ class ChartFetchError(Exception):
29
+ pass
30
+
31
+
32
+ def registry_location(helm_registry):
33
+ """`europe-west4-docker.pkg.dev` -> `europe-west4`."""
34
+ match = REGISTRY_HOST.match(helm_registry.strip())
35
+ if not match:
36
+ raise ChartFetchError(
37
+ 'helm_registry {registry!r} is not an Artifact Registry Docker host'
38
+ ' (LOCATION-docker.pkg.dev).'.format(registry=helm_registry))
39
+ return match.group('location')
40
+
41
+
42
+ def split_chart(helm_chart):
43
+ """`my-repo/my-chart` -> (`my-repo`, `my-chart`)."""
44
+ repository, _, package = helm_chart.strip('/').partition('/')
45
+ if not repository or not package:
46
+ raise ChartFetchError(
47
+ 'helm_chart {chart!r} must be REPOSITORY/CHART when helm_registry'
48
+ ' is set.'.format(chart=helm_chart))
49
+ return repository, package
50
+
51
+
52
+ def run_gcloud(cmd):
53
+ """
54
+ Run gcloud, capturing only its output. Prompts and errors go to the
55
+ terminal, so gcloud can ask for reauthentication.
56
+ """
57
+ result = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
58
+ if result.returncode != 0:
59
+ raise ChartFetchError('gcloud failed: {cmd}'.format(cmd=' '.join(cmd)))
60
+ return result.stdout
61
+
62
+
63
+ def sha256_file(path):
64
+ digest = hashlib.sha256()
65
+ with open(path, 'rb') as f:
66
+ for block in iter(lambda: f.read(1 << 16), b''):
67
+ digest.update(block)
68
+ return 'sha256:' + digest.hexdigest()
69
+
70
+
71
+ def resolve_digest(host, project, repository, package, chart_version):
72
+ image = '{host}/{project}/{repository}/{package}:{version}'.format(
73
+ host=host, project=project, repository=repository, package=package,
74
+ version=chart_version)
75
+ digest = run_gcloud([
76
+ 'gcloud', 'artifacts', 'docker', 'images', 'describe', image,
77
+ '--format=value(image_summary.digest)',
78
+ ]).strip()
79
+ if not digest.startswith('sha256:'):
80
+ raise ChartFetchError('Could not resolve {image} to a digest.'.format(image=image))
81
+ return digest
82
+
83
+
84
+ def download_file(project, location, repository, name, destination, filename):
85
+ run_gcloud([
86
+ 'gcloud', 'artifacts', 'files', 'download', name,
87
+ '--project={0}'.format(project),
88
+ '--location={0}'.format(location),
89
+ '--repository={0}'.format(repository),
90
+ '--destination={0}'.format(destination),
91
+ '--local-filename={0}'.format(filename),
92
+ '--allow-overwrite',
93
+ # No progress boxes; gcloud's errors still print.
94
+ '--no-user-output-enabled',
95
+ ])
96
+ return os.path.join(destination, filename)
97
+
98
+
99
+ def verified(path, digest, what):
100
+ actual = sha256_file(path)
101
+ if actual != digest:
102
+ raise ChartFetchError(
103
+ '{what} digest mismatch: expected {expected}, got {actual}.'
104
+ .format(what=what, expected=digest, actual=actual))
105
+ return path
106
+
107
+
108
+ def chart_layer_digest(manifest_path):
109
+ with open(manifest_path) as f:
110
+ manifest = json.load(f)
111
+ layers = [layer for layer in manifest.get('layers', [])
112
+ if layer.get('mediaType') == CHART_LAYER_MEDIA_TYPE]
113
+ if len(layers) != 1:
114
+ raise ChartFetchError(
115
+ 'Expected one Helm chart layer in the manifest, found {count}.'
116
+ .format(count=len(layers)))
117
+ return layers[0]['digest']
118
+
119
+
120
+ def fetch_chart(helm_registry, project, helm_chart, chart_version, destination=None):
121
+ """
122
+ Download `helm_chart` at `chart_version` from Artifact Registry with
123
+ gcloud and return the path of the verified chart archive.
124
+
125
+ Without `destination`, the archive goes to a temporary directory that is
126
+ removed when rdeploy exits.
127
+ """
128
+ location = registry_location(helm_registry)
129
+ host = '{location}-docker.pkg.dev'.format(location=location)
130
+ repository, package = split_chart(helm_chart)
131
+
132
+ if destination is None:
133
+ destination = tempfile.mkdtemp(prefix='rdeploy-chart-')
134
+ atexit.register(shutil.rmtree, destination, True)
135
+
136
+ # Before anything else, so an expired login is caught while nothing has
137
+ # happened yet, and the user is asked before a browser opens.
138
+ try:
139
+ ensure_gcloud_login(ask=True)
140
+ except GcloudLoginError as err:
141
+ raise ChartFetchError(str(err))
142
+
143
+ print('Downloading chart {chart} {version} with gcloud'.format(
144
+ chart=helm_chart, version=chart_version), flush=True)
145
+
146
+ manifest_digest = resolve_digest(host, project, repository, package, chart_version)
147
+ manifest = verified(
148
+ download_file(project, location, repository,
149
+ '{package}/manifests/{digest}'.format(package=package, digest=manifest_digest),
150
+ destination, 'manifest.json'),
151
+ manifest_digest, 'Manifest')
152
+
153
+ layer_digest = chart_layer_digest(manifest)
154
+ filename = '{name}-{version}.tgz'.format(name=package.rsplit('/', 1)[-1],
155
+ version=chart_version)
156
+ return verified(
157
+ download_file(project, location, repository, layer_digest, destination, filename),
158
+ 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.4
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,27 @@ 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
+
299
+ If gcloud's login has expired, rdeploy asks before running `gcloud auth
300
+ login`. Without a terminal, such as in a script, it stops and tells you to
301
+ run it.
302
+
289
303
  ## Versioning
290
304
 
291
305
  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
@@ -470,6 +470,69 @@ class TestEnsureGcloudLogin:
470
470
  assert mock_run.call_args_list[0][0][0] == ['gcloud', 'auth', 'print-access-token']
471
471
  assert mock_run.call_args_list[2][0][0] == ['gcloud', 'auth', 'login']
472
472
 
473
+ EXPIRED = 'There was a problem refreshing your current auth tokens. Please run: gcloud auth login'
474
+
475
+ @patch('rdeploy.gke_auth.sys.stdin')
476
+ @patch('rdeploy.gke_auth.input', create=True, return_value='y')
477
+ @patch('rdeploy.gke_auth.subprocess.run')
478
+ def test_ask_yes_runs_login(self, mock_run, mock_input, mock_stdin):
479
+ mock_stdin.isatty.return_value = True
480
+ mock_run.side_effect = [completed(returncode=1, stderr=self.EXPIRED), completed()]
481
+ gke_auth.ensure_gcloud_login('me@example.test', ask=True)
482
+ assert 'me@example.test' in mock_input.call_args[0][0]
483
+ assert '[y/N]' in mock_input.call_args[0][0]
484
+ assert mock_run.call_args_list[1][0][0] == ['gcloud', 'auth', 'login', 'me@example.test']
485
+
486
+ @pytest.mark.parametrize('answer', ['', 'n', 'no', 'maybe'])
487
+ @patch('rdeploy.gke_auth.sys.stdin')
488
+ @patch('rdeploy.gke_auth.subprocess.run')
489
+ def test_ask_anything_but_yes_stops(self, mock_run, mock_stdin, answer):
490
+ mock_stdin.isatty.return_value = True
491
+ mock_run.side_effect = [completed(returncode=1, stderr=self.EXPIRED)]
492
+ with patch('rdeploy.gke_auth.input', create=True, return_value=answer):
493
+ with pytest.raises(gke_auth.GcloudLoginError,
494
+ match='Run `gcloud auth login me@example.test`, then run this command again'):
495
+ gke_auth.ensure_gcloud_login('me@example.test', ask=True)
496
+ assert mock_run.call_count == 1 # no browser
497
+
498
+ @patch('rdeploy.gke_auth.gcloud_account', return_value='')
499
+ @patch('rdeploy.gke_auth.sys.stdin')
500
+ @patch('rdeploy.gke_auth.subprocess.run')
501
+ def test_ask_without_terminal_stops_without_asking(self, mock_run, mock_stdin, _account):
502
+ mock_stdin.isatty.return_value = False
503
+ mock_run.side_effect = [completed(returncode=1, stderr=self.EXPIRED)]
504
+ with patch('rdeploy.gke_auth.input', create=True) as mock_input:
505
+ with pytest.raises(gke_auth.GcloudLoginError, match='expired'):
506
+ gke_auth.ensure_gcloud_login(ask=True)
507
+ mock_input.assert_not_called()
508
+ assert mock_run.call_count == 1
509
+
510
+ @patch('rdeploy.gke_auth.gcloud_account', return_value='active@example.test')
511
+ @patch('rdeploy.gke_auth.sys.stdin')
512
+ @patch('rdeploy.gke_auth.subprocess.run')
513
+ def test_ask_names_the_active_account(self, mock_run, mock_stdin, _account):
514
+ mock_stdin.isatty.return_value = True
515
+ mock_run.side_effect = [completed(returncode=1, stderr=self.EXPIRED)]
516
+ with patch('rdeploy.gke_auth.input', create=True, return_value='') as mock_input:
517
+ with pytest.raises(gke_auth.GcloudLoginError):
518
+ gke_auth.ensure_gcloud_login(ask=True)
519
+ assert 'active@example.test' in mock_input.call_args[0][0]
520
+
521
+ @patch('rdeploy.gke_auth.sys.stdin')
522
+ @patch('rdeploy.gke_auth.subprocess.run')
523
+ def test_ask_signed_in_asks_nothing(self, mock_run, mock_stdin):
524
+ mock_run.return_value = completed('token')
525
+ with patch('rdeploy.gke_auth.input', create=True) as mock_input:
526
+ gke_auth.ensure_gcloud_login(ask=True)
527
+ mock_input.assert_not_called()
528
+
529
+ def test_ask_yes_no_eof_is_no(self):
530
+ with patch('rdeploy.gke_auth.input', create=True, side_effect=EOFError):
531
+ assert gke_auth.ask_yes_no('?') is False
532
+
533
+ def test_login_error_is_a_kubectl_login_error(self):
534
+ assert issubclass(gke_auth.GcloudLoginError, KubectlLoginError)
535
+
473
536
  @patch('rdeploy.gke_auth.subprocess.run')
474
537
  def test_login_fails(self, mock_run):
475
538
  mock_run.side_effect = [completed(returncode=1, stderr='no credentialed accounts'), completed(returncode=1)]
@@ -0,0 +1,270 @@
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.gke_auth import GcloudLoginError
19
+ from rdeploy.tasks import install, resolve_helm_chart, upgrade
20
+
21
+ CHART = b'fake chart archive'
22
+ CHART_DIGEST = 'sha256:' + hashlib.sha256(CHART).hexdigest()
23
+ MANIFEST = json.dumps({
24
+ 'schemaVersion': 2,
25
+ 'config': {'mediaType': 'application/vnd.cncf.helm.config.v1+json',
26
+ 'digest': 'sha256:' + 'c' * 64, 'size': 10},
27
+ 'layers': [{'mediaType': CHART_LAYER_MEDIA_TYPE,
28
+ 'digest': CHART_DIGEST, 'size': len(CHART)}],
29
+ }).encode()
30
+ MANIFEST_DIGEST = 'sha256:' + hashlib.sha256(MANIFEST).hexdigest()
31
+
32
+
33
+ class FakeGcloud:
34
+ """Stands in for gcloud: resolves the tag and serves the stored files."""
35
+
36
+ def __init__(self, files=None, digest=MANIFEST_DIGEST, fail=False):
37
+ self.files = files if files is not None else {
38
+ 'rehive-service/manifests/' + MANIFEST_DIGEST: MANIFEST,
39
+ CHART_DIGEST: CHART,
40
+ }
41
+ self.digest = digest
42
+ self.fail = fail
43
+ self.calls = []
44
+
45
+ def __call__(self, cmd, **kwargs):
46
+ self.calls.append(cmd)
47
+ if self.fail:
48
+ return MagicMock(returncode=1, stdout='')
49
+ if cmd[1:5] == ['artifacts', 'docker', 'images', 'describe']:
50
+ return MagicMock(returncode=0, stdout=self.digest + '\n')
51
+ if cmd[1:4] == ['artifacts', 'files', 'download']:
52
+ name = cmd[4]
53
+ flags = dict(arg[2:].split('=', 1) for arg in cmd[5:] if '=' in arg)
54
+ if name not in self.files:
55
+ return MagicMock(returncode=1, stdout='')
56
+ with open(os.path.join(flags['destination'], flags['local-filename']), 'wb') as f:
57
+ f.write(self.files[name])
58
+ return MagicMock(returncode=0, stdout='')
59
+ raise AssertionError('unexpected gcloud call: {}'.format(cmd))
60
+
61
+
62
+ def fetch(tmp_path, gcloud):
63
+ with patch('rdeploy.helm_chart.subprocess.run', side_effect=gcloud):
64
+ return fetch_chart('europe-west4-docker.pkg.dev', 'my-project',
65
+ 'my-charts/rehive-service', '1.2.0',
66
+ destination=str(tmp_path))
67
+
68
+
69
+ class TestParsing:
70
+ @pytest.mark.parametrize('registry', [
71
+ 'europe-west4-docker.pkg.dev',
72
+ 'https://europe-west4-docker.pkg.dev',
73
+ 'europe-west4-docker.pkg.dev/',
74
+ ])
75
+ def test_registry_location(self, registry):
76
+ assert registry_location(registry) == 'europe-west4'
77
+
78
+ def test_multi_region_location(self):
79
+ assert registry_location('us-docker.pkg.dev') == 'us'
80
+
81
+ @pytest.mark.parametrize('registry', ['gcr.io', 'ghcr.io', 'europe-west4-npm.pkg.dev'])
82
+ def test_rejects_other_registries(self, registry):
83
+ with pytest.raises(ChartFetchError):
84
+ registry_location(registry)
85
+
86
+ def test_split_chart(self):
87
+ assert split_chart('my-charts/rehive-service') == ('my-charts', 'rehive-service')
88
+
89
+ def test_split_chart_needs_repository(self):
90
+ with pytest.raises(ChartFetchError):
91
+ split_chart('rehive-service')
92
+
93
+ def test_chart_layer_digest(self, tmp_path):
94
+ path = tmp_path / 'manifest.json'
95
+ path.write_bytes(MANIFEST)
96
+ assert chart_layer_digest(str(path)) == CHART_DIGEST
97
+
98
+ def test_manifest_without_chart_layer(self, tmp_path):
99
+ path = tmp_path / 'manifest.json'
100
+ path.write_text(json.dumps({'layers': [{'mediaType': 'other', 'digest': 'x'}]}))
101
+ with pytest.raises(ChartFetchError, match='found 0'):
102
+ chart_layer_digest(str(path))
103
+
104
+
105
+ @pytest.fixture
106
+ def gcloud_signed_in():
107
+ with patch('rdeploy.helm_chart.ensure_gcloud_login') as ensure:
108
+ yield ensure
109
+
110
+
111
+ @pytest.mark.usefixtures('gcloud_signed_in')
112
+ class TestFetchChart:
113
+ def test_downloads_and_verifies_chart(self, tmp_path):
114
+ gcloud = FakeGcloud()
115
+ path = fetch(tmp_path, gcloud)
116
+ assert path == str(tmp_path / 'rehive-service-1.2.0.tgz')
117
+ with open(path, 'rb') as f:
118
+ assert f.read() == CHART
119
+
120
+ def test_gcloud_calls(self, tmp_path):
121
+ gcloud = FakeGcloud()
122
+ fetch(tmp_path, gcloud)
123
+ describe, manifest, chart = gcloud.calls
124
+ assert describe[5] == 'europe-west4-docker.pkg.dev/my-project/my-charts/rehive-service:1.2.0'
125
+ assert manifest[4] == 'rehive-service/manifests/' + MANIFEST_DIGEST
126
+ assert chart[4] == CHART_DIGEST
127
+ for call in (manifest, chart):
128
+ assert '--project=my-project' in call
129
+ assert '--location=europe-west4' in call
130
+ assert '--repository=my-charts' in call
131
+
132
+ def test_never_asks_gcloud_for_a_token(self, tmp_path):
133
+ gcloud = FakeGcloud()
134
+ fetch(tmp_path, gcloud)
135
+ assert not any('print-access-token' in call for call in gcloud.calls)
136
+
137
+ def test_gcloud_prompts_reach_the_terminal(self, tmp_path):
138
+ with patch('rdeploy.helm_chart.subprocess.run', side_effect=FakeGcloud()) as run:
139
+ fetch_chart('europe-west4-docker.pkg.dev', 'my-project',
140
+ 'my-charts/rehive-service', '1.2.0', destination=str(tmp_path))
141
+ for call in run.call_args_list:
142
+ assert 'stderr' not in call.kwargs
143
+ assert 'stdin' not in call.kwargs
144
+
145
+ def test_downloads_are_quiet(self, tmp_path):
146
+ gcloud = FakeGcloud()
147
+ fetch(tmp_path, gcloud)
148
+ for call in gcloud.calls[1:]:
149
+ assert '--no-user-output-enabled' in call
150
+
151
+ def test_checks_gcloud_login_first_and_asks(self, tmp_path, gcloud_signed_in):
152
+ gcloud = FakeGcloud()
153
+ gcloud_signed_in.side_effect = lambda **kwargs: gcloud.calls.append('login check')
154
+ fetch(tmp_path, gcloud)
155
+ gcloud_signed_in.assert_called_once_with(ask=True)
156
+ assert gcloud.calls[0] == 'login check'
157
+
158
+ def test_declined_login_stops_before_downloading(self, tmp_path, gcloud_signed_in):
159
+ gcloud = FakeGcloud()
160
+ gcloud_signed_in.side_effect = GcloudLoginError('Run `gcloud auth login`, then run this command again.')
161
+ with pytest.raises(ChartFetchError, match='gcloud auth login'):
162
+ fetch(tmp_path, gcloud)
163
+ assert gcloud.calls == []
164
+
165
+ def test_rejects_tampered_chart(self, tmp_path):
166
+ gcloud = FakeGcloud()
167
+ gcloud.files[CHART_DIGEST] = b'something else'
168
+ with pytest.raises(ChartFetchError, match='Chart digest mismatch'):
169
+ fetch(tmp_path, gcloud)
170
+
171
+ def test_rejects_tampered_manifest(self, tmp_path):
172
+ gcloud = FakeGcloud()
173
+ gcloud.files['rehive-service/manifests/' + MANIFEST_DIGEST] = MANIFEST + b' '
174
+ with pytest.raises(ChartFetchError, match='Manifest digest mismatch'):
175
+ fetch(tmp_path, gcloud)
176
+
177
+ def test_unresolved_tag(self, tmp_path):
178
+ with pytest.raises(ChartFetchError, match='digest'):
179
+ fetch(tmp_path, FakeGcloud(digest=''))
180
+
181
+ def test_gcloud_failure(self, tmp_path):
182
+ with pytest.raises(ChartFetchError, match='gcloud failed'):
183
+ fetch(tmp_path, FakeGcloud(fail=True))
184
+
185
+ def test_temporary_destination_is_cleaned_up(self):
186
+ registered = []
187
+ with patch('rdeploy.helm_chart.subprocess.run', side_effect=FakeGcloud()), \
188
+ patch('rdeploy.helm_chart.atexit.register',
189
+ side_effect=lambda *args: registered.append(args)):
190
+ path = fetch_chart('europe-west4-docker.pkg.dev', 'my-project',
191
+ 'my-charts/rehive-service', '1.2.0')
192
+ cleanup, directory, _ = registered[0]
193
+ assert os.path.dirname(path) == directory
194
+ cleanup(directory, True)
195
+ assert not os.path.exists(directory)
196
+
197
+
198
+ def registry_config(helm_registry='europe-west4-docker.pkg.dev'):
199
+ return {
200
+ 'namespace': 'staging-ns',
201
+ 'project_name': 'my-service',
202
+ 'helm_chart': 'my-charts/rehive-service',
203
+ 'helm_chart_version': '1.2.0',
204
+ 'helm_values_path': 'etc/helm/staging.yaml',
205
+ 'cloud_provider': {'name': 'gcp', 'project': 'my-project',
206
+ 'kube_cluster': 'cluster-1', 'region': 'europe-west4',
207
+ 'helm_registry': helm_registry},
208
+ }
209
+
210
+
211
+ class TestResolveHelmChart:
212
+ def test_repository_chart_keeps_version_flag(self):
213
+ config = registry_config(helm_registry=None)
214
+ config['helm_chart'] = 'rehive/service'
215
+ assert resolve_helm_chart(config) == ('rehive/service', ' --version 1.2.0')
216
+
217
+ def test_registry_chart_is_downloaded(self):
218
+ with patch('rdeploy.tasks.fetch_chart', return_value='/tmp/x/rehive-service-1.2.0.tgz') as fetch_mock:
219
+ assert resolve_helm_chart(registry_config()) == ('/tmp/x/rehive-service-1.2.0.tgz', '')
220
+ fetch_mock.assert_called_once_with('europe-west4-docker.pkg.dev', 'my-project',
221
+ 'my-charts/rehive-service', '1.2.0')
222
+
223
+ def test_path_is_quoted(self):
224
+ with patch('rdeploy.tasks.fetch_chart', return_value='/tmp/a b/chart.tgz'):
225
+ assert resolve_helm_chart(registry_config())[0] == "'/tmp/a b/chart.tgz'"
226
+
227
+ def test_windows_path_is_double_quoted(self):
228
+ path = r'C:\Users\a b\AppData\Local\Temp\rdeploy-chart-x\chart.tgz'
229
+ with patch('rdeploy.tasks.fetch_chart', return_value=path), \
230
+ patch('rdeploy.tasks.sys.platform', 'win32'):
231
+ assert resolve_helm_chart(registry_config())[0] == '"{}"'.format(path)
232
+
233
+ def test_windows_path_without_spaces_is_unquoted(self):
234
+ path = r'C:\Temp\rdeploy-chart-x\chart.tgz'
235
+ with patch('rdeploy.tasks.fetch_chart', return_value=path), \
236
+ patch('rdeploy.tasks.sys.platform', 'win32'):
237
+ assert resolve_helm_chart(registry_config())[0] == path
238
+
239
+ def test_download_failure_exits(self):
240
+ with patch('rdeploy.tasks.fetch_chart', side_effect=ChartFetchError('boom')):
241
+ with pytest.raises(SystemExit, match='Could not download the Helm chart: boom'):
242
+ resolve_helm_chart(registry_config())
243
+
244
+
245
+ class TestTasksUseDownloadedChart:
246
+ def settings(self):
247
+ return {'version': '3', 'configs': {'staging': registry_config()}}
248
+
249
+ def run_task(self, task, **kwargs):
250
+ ctx = MagicMock(spec=Context)
251
+ ctx.run.return_value = MagicMock(failed=False)
252
+ with patch('rdeploy.tasks.get_settings', return_value=self.settings()), \
253
+ patch('rdeploy.tasks.set_context'), \
254
+ patch('rdeploy.tasks._watch_rollout'), \
255
+ patch('rdeploy.tasks.fetch_chart', return_value='/tmp/x/rehive-service-1.2.0.tgz'):
256
+ task(ctx, 'staging', **kwargs)
257
+ return [call.args[0] for call in ctx.run.call_args_list]
258
+
259
+ @pytest.mark.parametrize('task,kwargs', [(upgrade, {'tag': '1.0.0'}), (install, {})])
260
+ def test_helm_gets_local_chart(self, task, kwargs):
261
+ commands = self.run_task(task, **kwargs)
262
+ helm_command = commands[-1]
263
+ assert helm_command.endswith(' /tmp/x/rehive-service-1.2.0.tgz')
264
+ assert '--version' not in helm_command
265
+ assert 'oci://' not in helm_command
266
+ assert not any('registry login' in c or 'print-access-token' in c for c in commands)
267
+
268
+ def test_upgrade_flags_intact(self):
269
+ helm_command = self.run_task(upgrade, tag='1.0.0')[-1]
270
+ 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