-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathselector.py
240 lines (208 loc) · 7.53 KB
/
selector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""Library for common selectors."""
from argparse import (
ArgumentParser,
BooleanOptionalAction,
Action,
ArgumentError,
Namespace,
)
import logging
import pathlib
import shlex
from typing import Any
from flux_local import git_repo, helm
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAMESPACE = "flux-system"
class SourceAppendAction(Action):
"""Append a key=value pair to the argument list."""
def __call__(
self,
parser: ArgumentParser,
namespace: Namespace,
values: Any,
option_string: str | None = None,
) -> None:
values = values.split(",")
if not values[0]:
return
result = getattr(namespace, self.dest) or []
for value in values:
try:
source = git_repo.Source.from_str(value)
except ValueError:
raise ArgumentError(
self, f"Expected key or key=value format from '{value}'"
)
result.append(source)
setattr(namespace, self.dest, result)
def add_selector_flags(args: ArgumentParser) -> None:
"""Add common selector flags to the arguments object."""
args.add_argument(
"--path",
help="Optional path with flux Kustomization resources (multi-cluster ok)",
type=pathlib.Path,
default=None,
nargs="?",
)
args.add_argument(
"--sources",
help="Optional GitRepository or OCIRepository sources to restrict "
"to e.g. `flux-system`. Can include optional map of repository "
"source to relative path e.g. `cluster=./k8s/`",
action=SourceAppendAction,
)
args.add_argument(
"--all-namespaces",
"-A",
type=bool,
default=False,
action=BooleanOptionalAction,
help="List the requested objects across all namespaces.",
)
args.add_argument(
"--namespace",
"-n",
type=str,
default=DEFAULT_NAMESPACE,
help="If present, the namespace scope for this request",
)
add_common_flags(args)
def add_common_flags(args: ArgumentParser) -> None:
"""Add flags that are common to selectors and other command types."""
args.add_argument(
"--skip-crds",
type=str,
default=True,
action=BooleanOptionalAction,
help="When true do not include CRDs to reduce output size",
)
args.add_argument(
"--skip-secrets",
type=str,
default=True,
action=BooleanOptionalAction,
help="When true do not include Secrets to reduce output size and randomness",
)
args.add_argument(
"--kustomize-build-flags",
type=str,
default="",
help="If present, additional flags to pass to `kustomize build`",
)
def add_ks_selector_flags(args: ArgumentParser) -> None:
"""Add common kustomization selector flags to the arguments object."""
args.add_argument(
"kustomization",
help="The name of the flux Kustomization",
type=str,
default=None,
nargs="?",
)
add_selector_flags(args)
def options( # type: ignore[no-untyped-def]
kustomize_build_flags: str | None, **kwargs
) -> git_repo.Options:
"""Create an Options object based on flags."""
options = git_repo.Options()
options.kustomize_flags = shlex.split(kustomize_build_flags or "")
return options
def build_ks_selector( # type: ignore[no-untyped-def]
**kwargs,
) -> git_repo.ResourceSelector:
"""Build a selector object form the specified flags."""
selector = git_repo.ResourceSelector()
selector.path = git_repo.PathSelector(
kwargs.get("path"), sources=kwargs.get("sources")
)
selector.kustomization.name = kwargs["kustomization"]
selector.kustomization.namespace = kwargs["namespace"]
if kwargs["all_namespaces"]:
selector.kustomization.namespace = None
selector.kustomization.skip_crds = kwargs["skip_crds"]
selector.kustomization.skip_secrets = kwargs["skip_secrets"]
selector.cluster_policy.enabled = False
return selector
def add_hr_selector_flags(args: ArgumentParser) -> None:
"""Add common HelmRelease selector flags to the arguments object."""
args.add_argument(
"helmrelease",
help="The name of the flux Kustomization",
type=str,
default=None,
nargs="?",
)
add_selector_flags(args)
def build_hr_selector( # type: ignore[no-untyped-def]
**kwargs,
) -> git_repo.ResourceSelector:
"""Build a selector object form the specified flags."""
_LOGGER.debug("Building HelmRelease selector from args: %s", kwargs)
selector = git_repo.ResourceSelector()
selector.path = git_repo.PathSelector(
kwargs.get("path"), sources=kwargs.get("sources")
)
selector.helm_release.name = kwargs.get("helmrelease")
selector.helm_release.namespace = kwargs["namespace"]
if kwargs["all_namespaces"]:
selector.helm_release.namespace = None
selector.helm_release.skip_crds = kwargs["skip_crds"]
selector.helm_release.skip_secrets = kwargs["skip_secrets"]
selector.kustomization.name = None
selector.kustomization.namespace = None
selector.cluster_policy.enabled = False
return selector
def add_helm_options_flags(args: ArgumentParser) -> None:
"""Add common helm template options flags to the arguments object."""
args.add_argument(
"--kube-version",
help="Kubernetes version used for Capabilities.KubeVersion",
)
args.add_argument(
"--api-versions",
"-a",
help="Kubernetes api versions used for helm Capabilities.APIVersions",
)
args.add_argument(
"--registry-config",
help="Path to a helm registry config file",
)
def build_helm_options(**kwargs) -> helm.Options: # type: ignore[no-untyped-def]
"""Build a helm Options object from the flags.
This assumes that the hr selector and helm options flags methods were
called to add arguments to the parser.
"""
return helm.Options(
skip_crds=kwargs["skip_crds"],
skip_secrets=kwargs["skip_secrets"],
kube_version=kwargs.get("kube_version"),
api_versions=kwargs.get("api_versions"),
registry_config=kwargs.get("registry_config"),
)
def add_cluster_selector_flags(args: ArgumentParser) -> None:
"""Add common flux cluster selector flags to the arguments object."""
add_selector_flags(args)
def build_cluster_selector( # type: ignore[no-untyped-def]
**kwargs,
) -> git_repo.ResourceSelector:
"""Build a selector object form the specified flags."""
_LOGGER.debug("Building flux cluster Kustomization selector from args: %s", kwargs)
selector = git_repo.ResourceSelector()
selector.path = git_repo.PathSelector(
kwargs.get("path"), sources=kwargs.get("sources")
)
selector.kustomization.namespace = kwargs.get("namespace")
if kwargs.get("all_namespaces"):
selector.cluster.namespace = None
selector.kustomization.namespace = None
selector.kustomization.skip_crds = kwargs["skip_crds"]
selector.kustomization.skip_secrets = kwargs["skip_secrets"]
return selector
def not_found(resource: str, mds: git_repo.MetadataSelector) -> str:
"""Return a not found error message for the given resource type and query."""
if mds.name:
return (
f"{resource} object '{mds.name}' not found in '{mds.namespace}' namespace"
)
if mds.namespace:
return f"no {resource} objects found in '{mds.namespace}' namespace"
return f"no {resource} objects found in cluster"