Debian Codegraph @

magnum_capi_helm/helm.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import functools
14 import json
15 import pathlib
16 import typing as t
17
18 from magnum.common import utils
19 from oslo_concurrency import processutils
20 from oslo_log import log as logging
21
22 from magnum_capi_helm import conf
23
24 LOG = logging.getLogger(__name__)
25 CONF = conf.CONF
26
27 # This code is loosely based on:
28 # https://github.com/azimuth-cloud/pyhelm3
29 # Ideally we can share this code in the future.
30
31
32 def mergeconcat(defaults, *overrides):
33 """Deep-merge two or more dictionaries together.
34
35 Lists are concatenated.
36 """
37
38 def mergeconcat2(defaults, overrides):
39 if isinstance(defaults, dict) and isinstance(overrides, dict):
40 merged = dict(defaults)
41 for key, value in overrides.items():
42 if key in defaults:
43 merged[key] = mergeconcat2(defaults[key], value)
44 else:
45 merged[key] = value
46 return merged
47 elif isinstance(defaults, (list, tuple)) and isinstance(
48 overrides, (list, tuple)
49 ):
50 merged = list(defaults)
51 merged.extend(overrides)
52 return merged
53 else:
54 return overrides if overrides is not None else defaults
55
56 return functools.reduce(mergeconcat2, overrides, defaults)
57
58
59 class Client:
60 """Client for interacting with Helm CLI."""
61
62 def __init__(self):
63 self._default_timeout = "5m"
64 self._executable = "helm"
65 self._history_max_revisions = 10
66 self._kubeconfig = CONF.capi_helm.kubeconfig_file
67
68 def _run(self, command, **kwargs) -> bytes:
69 command = [self._executable] + command
70 if self._kubeconfig:
71 command.extend(["--kubeconfig", self._kubeconfig])
72 stdout, stderr = utils.execute(*command, **kwargs)
73 LOG.debug(f"Ran helm {command} got out:{stdout} err:{stderr}")
74 return stdout
75
76 def install_or_upgrade(
77 self,
78 release_name: str,
79 chart_ref: t.Union[pathlib.Path, str],
80 *values: t.Dict[str, t.Any],
81 namespace: str,
82 repo: t.Optional[str] = None,
83 version: t.Optional[str] = None,
84 ) -> t.Iterable[t.Dict[str, t.Any]]:
85 """Install or upgrade specified release using chart and values."""
86 assert release_name is not None
87 command = [
88 "upgrade",
89 release_name,
90 chart_ref,
91 "--history-max",
92 self._history_max_revisions,
93 "--install",
94 "--output",
95 "json",
96 "--timeout",
97 self._default_timeout,
98 # We send the values in on stdin
99 "--values",
100 "-",
101 "--namespace",
102 namespace,
103 ]
104 if repo:
105 command += ["--repo", repo]
106 if version:
107 command += [
108 "--version",
109 version,
110 ]
111
112 process_input = json.dumps(mergeconcat({}, *values))
113 return json.loads(self._run(command, process_input=process_input))
114
115 def uninstall_release(
116 self,
117 release_name: str,
118 namespace: str,
119 ):
120 """Uninstall the named release."""
121 assert release_name is not None
122 command = [
123 "uninstall",
124 release_name,
125 "--timeout",
126 self._default_timeout,
127 "--namespace",
128 namespace,
129 ]
130 try:
131 self._run(command)
132 except processutils.ProcessExecutionError as exc:
133 # Swallow release not found errors, as that is our desired state
134 if not exc.stderr or "release: not found" not in exc.stderr:
135 raise