/
component-cli
executable file
·371 lines (300 loc) · 10.8 KB
/
component-cli
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#!/usr/bin/env python3
import argparse
import copy
import dataclasses
import os
import sys
import yaml
import gci.componentmodel as cm
import oci.model as om
import ci.util
own_dir = os.path.dirname(__file__)
def component_archive_resource_add(argv):
if not argv:
fail_and_notify_about_unsupported_command(
f'Usage: {" ".join(sys.argv[:1])} resources'
)
subcmd = argv[0]
if not subcmd in ('resources', 'resource', 'res'):
fail_and_notify_about_unsupported_command(
'only sub-commands `resources`, `resource`, `res` are supported',
)
# the only supported subcmd is `add` (also the case in original component-cli)
if not len(argv) > 1:
fail_and_notify_about_unsupported_command(
f'Usage: {" ".join(sys.argv[:1])} resources add'
)
if not argv[1] == 'add':
fail_and_notify_about_unsupported_command(
'expected subcommand `add`',
)
if not len(argv) >= 3:
fail_and_notify_about_unsupported_command(
'expected two positional arguments after `add` subcommand',
)
component_descriptor_dir = argv[2]
try:
resources_file = argv[3]
if not os.path.isfile(resources_file):
resources_file = None
except IndexError:
resources_file = None
component_descriptor_file = os.path.join(component_descriptor_dir, 'component-descriptor.yaml')
if not os.path.isfile(component_descriptor_file):
print(f'ERROR: not an existing file: {component_descriptor_file=}')
exit(1)
template_vars = {}
saw_ddash = False
for v in argv[3:]:
if v == '--':
saw_ddash = True
continue
if not saw_ddash:
continue
k,v = v.split('=')
template_vars[k] = v
def iter_resources():
if resources_file:
with open(resources_file) as f:
raw = f.read()
for k,v in template_vars.items():
raw = raw.replace('${' + k + '}', v)
for parsed in yaml.safe_load_all(raw):
if 'resources' in parsed:
yield from parsed['resources']
continue
yield parsed
if not sys.stdin.isatty():
raw = sys.stdin.read()
for k,v in template_vars.items():
raw = raw.replace('${' + k + '}', v)
for parsed in yaml.safe_load_all(raw):
if 'resources' in parsed:
yield from parsed['resources']
continue
yield parsed
with open(component_descriptor_file) as f:
component_descriptor = cm.ComponentDescriptor.from_dict(yaml.safe_load(f))
component = component_descriptor.component
print(f'adding resources from {resources_file=} to {component_descriptor_file=}')
resources_len = len(component.resources)
def resource_id(resource: dict):
if dataclasses.is_dataclass(resource):
resource = dataclasses.asdict(resource, dict_factory=ci.util.dict_factory_enum_serialisiation)
return resource.get('name'), resource.get('version'), resource.get('type')
for resource in iter_resources():
rid = resource_id(resource)
# existing resources w/ same id are merged with newly added ones
# more specifically: in case of OCI-Images, access.imageReference is kept; everything else
# is overwritten by data from imagevector
for existing_resource in component.resources:
if not resource_id(existing_resource) == rid:
continue
component.resources.remove(existing_resource)
if existing_resource.type is cm.OCI_IMAGE:
resource.access.imageReference = existing_resource.access.imageReference
component.resources.append(resource)
added_resources_count = len(component.resources) - resources_len
with open(component_descriptor_file, 'w') as f:
yaml.dump(
data=dataclasses.asdict(component_descriptor),
stream=f,
Dumper=cm.EnumValueYamlDumper,
)
print(f'added {added_resources_count} resource(s)')
log_argv(delegated=False)
def image_vector(argv):
subcmd = argv[0]
if not subcmd in ('add',):
fail_and_notify_about_unsupported_command(
'only `add` subcommand is allowed',
)
# command `image-vector add`
parser = argparse.ArgumentParser()
parser.add_argument('--comp-desc', required=True, dest='component_descriptor_path')
parser.add_argument('--image-vector', required=True, dest='images_yaml_path')
parser.add_argument(
'--component-prefixes',
default='',
help='comma-separated image-prefixes (calculate component-names by stripping off)',
)
# todo: --generic-dependencies seems to have no effect in original component-cli
parser.add_argument(
'--generic-dependencies',
action='append',
required=False,
default=[],
)
parsed = parser.parse_args(argv[1:]) # strip subcommand (`add`)
with open(parsed.component_descriptor_path) as f:
component_descriptor = cm.ComponentDescriptor.from_dict(yaml.safe_load(f))
component = component_descriptor.component
# images_yaml_path, as found e.g. at github.com/gardener/gardener charts/images.yaml
def iter_images():
images_yaml_path = parsed.images_yaml_path
with open(images_yaml_path) as f:
for part in yaml.safe_load_all(f):
yield from part['images']
imagevector_label_name = 'imagevector.gardener.cloud/images'
imagevector_label = component.find_label(imagevector_label_name)
if not imagevector_label:
component.labels.append(
imagevector_label := cm.Label(
name=imagevector_label_name,
value={'images': []}
)
)
component_prefixes = parsed.component_prefixes.split(',')
for image_dict in iter_images():
name = image_dict['name']
resource_id = image_dict.get('resourceId', {'name': name})
source_repo = image_dict.get('sourceRepository', None)
img_repo = image_dict['repository']
extra_identity = image_dict.get('extraIdentity', {})
labels = copy.copy(image_dict.get('labels', []))
tag = image_dict.get('tag', None)
target_version = image_dict.get('targetVersion', None)
for prefix in (component_prefixes or ()):
if img_repo.startswith(prefix):
relation = 'local'
is_local = True
break
else:
relation = 'external'
is_local = False
resource_name = None
resource = None
if not tag:
if resource_id:
resource_name = resource_id['name']
image_dict['name'] = resource_name
else:
resource_name = name
for resource in component.resources:
if resource.name != resource_name:
continue
tag = resource.version
# image-references from pipeline (base_component_descriptor) has precedence
img_repo = om.OciImageReference(resource.access.imageReference).ref_without_tag
component.resources.remove(resource)
if not 'relation' in image_dict:
relation = resource.relation.value
pass
break
if not tag: # and not resource:
# special-case: if there is no tag, the image is only added to `images`-label on
# component-level
imagevector_label.value['images'].append(image_dict)
continue
is_current_component = source_repo == component.name
if not is_current_component and is_local:
# if we have a tag, and repository is "local" (as passed-in via --component-prefixes),
# then we add a component-reference, and add the image to a label of this reference
for component_reference in component.componentReferences:
if component_reference.name == name and component_reference.version == tag:
break
else:
component_reference = cm.ComponentReference(
name=name,
componentName=source_repo,
version=tag,
extraIdentity=extra_identity,
labels=[cm.Label(
name='imagevector.gardener.cloud/images',
value={'images': []},
)],
)
component.componentReferences.append(component_reference)
cref_images_label = component_reference.find_label(name='imagevector.gardener.cloud/images')
cref_images_label.value['images'].append(
image_dict | {'resourceId': resource_id}
)
continue
labels.append({
'name': 'imagevector.gardener.cloud/name',
'value': name,
})
labels.append({
'name': 'imagevector.gardener.cloud/repository',
'value': img_repo,
})
if source_repo:
labels.append({
'name': 'imagevector.gardener.cloud/source-repository',
'value': source_repo,
})
if target_version:
labels.append({
'name': 'imagevector.gardener.cloud/target-version',
'value': target_version,
})
img_resource = cm.Resource(
name=resource_name or name,
version=tag,
extraIdentity=extra_identity,
labels=labels,
relation=relation,
type=cm.ArtefactType.OCI_IMAGE,
access=cm.OciAccess(
type=cm.AccessType.OCI_REGISTRY,
imageReference=f'{img_repo}:{tag}',
)
)
component.resources.append(img_resource)
if not imagevector_label.value['images']:
component.labels.remove(imagevector_label)
# "normalise" (match component-cli's behaviour)
# this could (and should) be removed
component_descriptor_dict = dataclasses.asdict(component_descriptor)
component_dict = component_descriptor_dict['component']
component_dict.pop('creationTime', None)
if not component_dict.get('labels'):
del component_dict['labels']
for r in component_dict['resources']:
r.pop('digest', None)
r.pop('srcRefs', None)
if not r.get('extraIdentity'):
r.pop('extraIdentity', None)
if not r.get('labels'):
r.pop('labels', None)
for r in component_dict['sources']:
if not r.get('extraIdentity'):
r.pop('extraIdentity', None)
for cr in component_dict['componentReferences']:
cr.pop('digest', None)
with open(parsed.component_descriptor_path, 'w') as f:
yaml.dump(
data=component_descriptor_dict,
stream=f,
Dumper=cm.EnumValueYamlDumper,
)
f.write('\n#generated by cc-utils\n')
def fail_and_notify_about_unsupported_command(message: str):
print(f'ERROR: {message}')
print(f'{sys.argv=}')
print('')
print('component-cli (github.com/gardener/component-cli) is deprecated and no longer available')
exit(1)
def log_argv(delegated=False):
if not (logfile := os.environ.get('commands_log')):
return
with open(logfile, 'a') as f:
entry = ''
if delegated:
entry = 'delegated: '
entry += ' '.join(sys.argv) + '\n'
f.write(entry)
def main():
if not len(sys.argv) > 1:
print(f'Usage: {sys.argv[0]} component-archive | image-vector')
exit(1)
cmd = sys.argv[1]
if cmd in ('component-archive', 'componentarchive', 'archive', 'ca'):
return component_archive_resource_add(sys.argv[2:])
elif cmd in ('image-vector', 'imagevector', 'iv'):
return image_vector(sys.argv[2:])
fail_and_notify_about_unsupported_command(
'only commands `component-archive` and `imagevector` are allowed',
)
if __name__ == '__main__':
main()