-
Notifications
You must be signed in to change notification settings - Fork 2
/
cleanup.py
476 lines (390 loc) · 15.5 KB
/
cleanup.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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#!/usr/bin/env python3
import logging
import functools
import dataclasses
import os
import concurrent.futures
import datetime
import itertools
import typing
import glci.aws
import glci.gcp
import glci.openstack_image
import glci.az
import glci.model as gm
import glci.util
import ccc.aws
import ccc.gcp
import ci.util
logger = logging.getLogger(__name__)
def cleanup_image(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
dry_run: bool,
) -> gm.OnlineReleaseManifest:
logger.info(f'cleaning up release for {release.platform=}')
if dry_run:
logger.warning(f"Running in DRY RUN mode {dry_run=}")
if release.platform == 'ali':
cleanup_function = None # clean_alicloud_images
elif release.platform == 'aws':
cleanup_function = cleanup_aws_images_by_id
elif release.platform == 'gcp':
cleanup_function = cleanup_gcp_images
elif release.platform == 'azure':
cleanup_function = cleanup_azure_community_gallery_images
elif release.platform == 'openstack':
cleanup_function = cleanup_openstack_images_by_id
elif release.platform == 'openstackbaremetal':
cleanup_function = cleanup_openstack_images_by_id
elif release.platform == 'oci':
cleanup_function = None
else:
logger.warning(f'do not know how to clean up {release.platform=}, yet')
return release
try:
cleanup_function(release, publishing_cfg, dry_run)
if dry_run:
return release
else:
return dataclasses.replace(release, published_image_metadata=None)
except:
import traceback
traceback.print_exc()
def cleanup_aws_images(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
dry_run: bool = False
):
target_image_name = glci.aws.target_image_name_for_release(release=release)
aws_publishing_cfg: gm.PublishingTargetAWS = publishing_cfg.target(platform=release.platform)
for aws_cfg in aws_publishing_cfg.aws_cfgs:
aws_cfg_name = aws_cfg.aws_cfg_name
mk_session = functools.partial(ccc.aws.session, aws_cfg=aws_cfg_name)
glci.aws.unregister_images_by_name(
mk_session=mk_session,
image_name=target_image_name,
dry_run=dry_run
)
def cleanup_aws_images_by_id(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
dry_run: bool
):
aws_publishing_cfg: gm.PublishingTargetAWS = publishing_cfg.target(platform=release.platform)
for aws_cfg in aws_publishing_cfg.aws_cfgs:
aws_cfg_name = aws_cfg.aws_cfg_name
mk_session = functools.partial(ccc.aws.session, aws_cfg=aws_cfg_name)
glci.aws.unregister_images_by_id(
mk_session=mk_session,
images=release.published_image_metadata.published_aws_images,
dry_run=dry_run
)
def clean_alicloud_images(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
) -> gm.OnlineReleaseManifest:
import ccc.alicloud
import glci.alicloud
aliyun_cfg = publishing_cfg.target(release.platform)
alicloud_cfg_name = aliyun_cfg.aliyun_cfg_name
oss_auth = ccc.alicloud.oss_auth(alicloud_cfg=alicloud_cfg_name)
acs_client = ccc.alicloud.acs_client(alicloud_cfg=alicloud_cfg_name)
maker = glci.alicloud.AlicloudImageMaker(
oss_auth,
acs_client,
release,
aliyun_cfg,
)
return maker.delete_images()
def cleanup_gcp_images(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
dry_run: bool = False
) -> gm.OnlineReleaseManifest:
gcp_publishing_cfg: gm.PublishingTargetGCP = publishing_cfg.target(release.platform)
cfg_factory = ci.util.ctx().cfg_factory()
gcp_cfg = cfg_factory.gcp(gcp_publishing_cfg.gcp_cfg_name)
storage_client = ccc.gcp.cloud_storage_client(gcp_cfg)
compute_client = ccc.gcp.authenticated_build_func(gcp_cfg)('compute', 'v1')
return glci.gcp.cleanup_image(
storage_client=storage_client,
compute_client=compute_client,
gcp_project_name=gcp_cfg.project(),
release=release,
publishing_cfg=gcp_publishing_cfg,
dry_run=dry_run
)
def cleanup_openstack_images_by_id(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
dry_run: bool = False
):
openstack_publishing_cfg: gm.PublishingTargetOpenstack = publishing_cfg.target(
platform=release.platform,
)
cfg_factory = ci.util.ctx().cfg_factory()
openstack_environments_cfg = cfg_factory.ccee(
openstack_publishing_cfg.environment_cfg_name,
)
username = openstack_environments_cfg.credentials().username()
password = openstack_environments_cfg.credentials().passwd()
openstack_env_cfgs = {
project.region(): gm.OpenstackEnvironment(
project_name=project.name(),
domain=project.domain(),
region=project.region(),
auth_url=project.auth_url(),
username=username,
password=password,
) for project in openstack_environments_cfg.projects()
}
published_images = release.published_image_metadata.published_openstack_images
for image in published_images:
openstack_env = openstack_env_cfgs.get(image.region_name, None)
if not openstack_env:
logger.error(f"Cannot remove image {image.image_id} because of missing OpenStack config for region {image.region_name}")
continue
glci.openstack_image.delete_single_image(
openstack_environment_cfg=openstack_env,
image_id=image.image_id,
dry_run=dry_run
)
def cleanup_openstack_images(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
dry_run: bool = False
):
openstack_publishing_cfg: gm.PublishingTargetOpenstack = publishing_cfg.target(
platform=release.platform,
)
cfg_factory = ci.util.ctx().cfg_factory()
openstack_environments_cfg = cfg_factory.ccee(
openstack_publishing_cfg.environment_cfg_name,
)
username = openstack_environments_cfg.credentials().username()
password = openstack_environments_cfg.credentials().passwd()
openstack_env_cfgs = tuple((
gm.OpenstackEnvironment(
project_name=project.name(),
domain=project.domain(),
region=project.region(),
auth_url=project.auth_url(),
username=username,
password=password,
) for project in openstack_environments_cfg.projects()
))
glci.openstack_image.delete_images_for_release(
openstack_environments_cfgs=openstack_env_cfgs,
release=release,
suffix=openstack_publishing_cfg.suffix,
dry_run=dry_run
)
def cleanup_azure_community_gallery_images(
release: gm.OnlineReleaseManifest,
publishing_cfg: gm.PublishingCfg,
dry_run: bool = False
):
cfg_factory = ci.util.ctx().cfg_factory()
azure_publishing_cfgs: list[gm.PublishingTargetAzure] = publishing_cfg.target_multi(platform=release.platform)
for azure_publishing_cfg in azure_publishing_cfgs:
logger.info(f"targetting {azure_publishing_cfg.cloud}")
azure_principal = cfg_factory.azure_service_principal(
cfg_name=azure_publishing_cfg.service_principal_cfg_name,
)
azure_principal_serialized = gm.AzureServicePrincipalCfg(
tenant_id=azure_principal.tenant_id(),
client_id=azure_principal.client_id(),
client_secret=azure_principal.client_secret(),
subscription_id=azure_principal.subscription_id(),
)
shared_gallery_cfg = cfg_factory.azure_shared_gallery(
cfg_name=azure_publishing_cfg.gallery_cfg_name,
)
shared_gallery_cfg_serialized = gm.AzureSharedGalleryCfg(
resource_group_name=shared_gallery_cfg.resource_group_name(),
gallery_name=shared_gallery_cfg.gallery_name(),
location=shared_gallery_cfg.location(),
published_name=shared_gallery_cfg.published_name(),
description=shared_gallery_cfg.description(),
eula=shared_gallery_cfg.eula(),
release_note_uri=shared_gallery_cfg.release_note_uri(),
identifier_publisher=shared_gallery_cfg.identifier_publisher(),
identifier_offer=shared_gallery_cfg.identifier_offer(),
identifier_sku=shared_gallery_cfg.identifier_sku(),
regions=azure_publishing_cfg.gallery_regions,
)
published_gallery_images = release.published_image_metadata.published_gallery_images
for gallery_image in published_gallery_images:
if gallery_image.azure_cloud != azure_publishing_cfg.cloud.value:
continue
glci.az.delete_from_azure_community_gallery(
community_gallery_image_id=gallery_image.community_gallery_image_id,
service_principal_cfg=azure_principal_serialized,
shared_gallery_cfg=shared_gallery_cfg_serialized,
azure_cloud=azure_publishing_cfg.cloud,
dry_run=dry_run
)
def clean_release_manifest_sets(
max_age_days: int=14,
cicd_cfg=None,
prefix: str=os.path.join(
gm.ReleaseManifestSet.release_manifest_set_prefix,
gm.PipelineFlavour.SNAPSHOT.value,
),
dry_run: bool=False,
):
if not cicd_cfg:
cicd_cfg = gm.CicdCfg=glci.util.cicd_cfg()
enumerate_release_sets = glci.util.preconfigured(
glci.util.enumerate_release_sets,
cicd_cfg=cicd_cfg,
)
executor = concurrent.futures.ThreadPoolExecutor(max_workers=64)
now = datetime.datetime.now()
oldest_allowed_date = now - datetime.timedelta(days=max_age_days)
logger.debug(f'{oldest_allowed_date=}')
s3_client = glci.s3.s3_client(cicd_cfg=cicd_cfg)
def purge_if_outdated(release_manifest_set: gm.ReleaseManifestSet):
if len(release_manifest_set.manifests) < 1:
logger.warning(f'{release_manifest_set.s3_key=} did not contain any manifests')
return (False, release_manifest_set)
first_manifest = release_manifest_set.manifests[0]
# all timestamps should usually be pretty close to each other
if first_manifest.build_ts_as_date() > oldest_allowed_date:
return (False, release_manifest_set)
# XXX also purge published images (if any)!
if dry_run:
logger.info(
f'Would delete {release_manifest_set.s3_bucket}/{release_manifest_set.s3_key}'
)
return (False, release_manifest_set)
else:
s3_client.delete_object(
Bucket=release_manifest_set.s3_bucket,
Key=release_manifest_set.s3_key,
)
logger.info(f'purged {release_manifest_set.s3_key=}')
return (True, release_manifest_set)
for purged, manifest in executor.map(
purge_if_outdated,
enumerate_release_sets(prefix=prefix)
):
pass
def clean_single_release_manifests(
max_age_days: int=14,
cicd_cfg=None,
prefix: str=gm.ReleaseManifest.manifest_key_prefix,
dry_run: bool=False,
):
if not cicd_cfg:
cicd_cfg = gm.CicdCfg=glci.util.cicd_cfg()
enumerate_releases = glci.util.preconfigured(
glci.util.enumerate_releases,
cicd_cfg=cicd_cfg,
)
executor = concurrent.futures.ThreadPoolExecutor(max_workers=64)
now = datetime.datetime.now()
oldest_allowed_date = now - datetime.timedelta(days=max_age_days)
logger.debug(f'{oldest_allowed_date=}')
s3_client = glci.s3.s3_client(cicd_cfg=cicd_cfg)
def purge_if_outdated(release_manifest: gm.ReleaseManifest):
if release_manifest.build_ts_as_date() < oldest_allowed_date:
# XXX also purge published images (if any)!
if dry_run:
logger.info(f'would delete {release_manifest.s3_bucket}/{release_manifest.s3_key}')
return (False, release_manifest)
else:
s3_client.delete_object(
Bucket=release_manifest.s3_bucket,
Key=release_manifest.s3_key,
)
logger.info(f'purged {release_manifest.s3_key=}')
return (True, release_manifest)
return (False, release_manifest)
for purged, manifest in executor.map(purge_if_outdated, enumerate_releases()):
pass
def _enumerate_objects_from_single_release_manifests(
cicd_cfg=None,
prefix: str=gm.ReleaseManifest.manifest_key_prefix,
) -> typing.Generator[gm.S3_ReleaseFile, None, None]:
if not cicd_cfg:
cicd_cfg = gm.CicdCfg=glci.util.cicd_cfg()
enumerate_releases = glci.util.preconfigured(
glci.util.enumerate_releases,
cicd_cfg=cicd_cfg,
)
for release_manifest in enumerate_releases(prefix=prefix):
yield from release_manifest.paths
def _enumerate_objects_from_release_manifest_sets(
cicd_cfg=None,
prefix: str=gm.ReleaseManifestSet.release_manifest_set_prefix,
) -> typing.Generator[gm.S3_ReleaseFile, None, None]:
if not cicd_cfg:
cicd_cfg = gm.CicdCfg=glci.util.cicd_cfg()
enumerate_release_sets = glci.util.preconfigured(
glci.util.enumerate_release_sets,
cicd_cfg=cicd_cfg,
)
for release_manifest_set in enumerate_release_sets(prefix=prefix):
for release_manifest in release_manifest_set.manifests:
yield from release_manifest.paths
if release_manifest_set.logs:
yield from release_manifest_set.logs
def clean_orphaned_objects(
cicd_cfg=None,
prefix='objects',
dry_run: bool=False,
):
if not cicd_cfg:
cicd_cfg = gm.CicdCfg=glci.util.cicd_cfg()
all_objects = {
object_descriptor for object_descriptor in
itertools.chain(
_enumerate_objects_from_release_manifest_sets(
cicd_cfg=cicd_cfg,
),
_enumerate_objects_from_single_release_manifests(
cicd_cfg=cicd_cfg,
)
)
}
# XXX assume for now that we only use one bucket
s3_bucket_name = cicd_cfg.build.s3_bucket_name
all_object_keys = {
o.s3_key for o in all_objects if o.s3_bucket_name == s3_bucket_name
}
logger.debug(f'{len(all_objects)=}')
logger.debug(f'{len(all_object_keys)=}')
s3_client = glci.s3.s3_client(cicd_cfg=cicd_cfg)
continuation_token = None
while True:
ctoken_args = {'ContinuationToken': continuation_token} \
if continuation_token \
else {}
res = s3_client.list_objects_v2(
Bucket=s3_bucket_name,
Prefix=prefix,
**ctoken_args,
)
if res['KeyCount'] == 0:
break
continuation_token = res.get('NextContinuationToken')
object_keys = {obj_dict['Key'] for obj_dict in res['Contents']}
# determine those keys that are no longer referenced by any manifest
loose_object_keys = object_keys - all_object_keys
if dry_run:
logger.info(f'would delete {len(loose_object_keys)=} unreferenced objs:')
else:
if loose_object_keys:
s3_client.delete_objects(
Bucket=s3_bucket_name,
Delete={
'Objects': [
{'Key': key} for key in loose_object_keys
],
},
)
logger.info(f'purged {len(loose_object_keys)=} unreferenced objs')
if not continuation_token:
break