-
Notifications
You must be signed in to change notification settings - Fork 4
/
components.py
1557 lines (1366 loc) · 52 KB
/
components.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections.abc
import dataclasses
import datetime
import dataclasses_json
import enum
import http
import io
import logging
import re
import tarfile
import aiohttp.web
import dacite.exceptions
import dateutil.parser
import sqlalchemy as sa
import sqlalchemy.ext.asyncio as sqlasync
import sqlalchemy.orm.query as sq
import yaml
import ci.util
import cnudie.iter
import cnudie.iter_async
import cnudie.retrieve
import cnudie.retrieve_async
import cnudie.util
import dso.model
import github.util
import oci.client_async
import oci.model as om
import ocm
import ocm.oci
import version as versionutil
import compliance_summary as cs
import consts
import deliverydb.cache
import deliverydb.model as dm
import deliverydb.util
import features
import lookups
import responsibles
import responsibles.github_statistics
import responsibles.labels
import util
import yp
logger = logging.getLogger(__name__)
@dataclasses.dataclass(frozen=True)
class ComponentVector:
'''
Holds two component objects of the same Component, but different Versions.
Represents a change in the component version from old_component to new_component.
'''
start: ocm.Component
end: ocm.Component
cache_existing_components = []
async def check_if_component_exists(
component_name: str,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent,
raise_http_error: bool=False,
):
if component_name in cache_existing_components:
return True
for _ in await version_lookup(component_name, None):
cache_existing_components.append(component_name)
return True
if raise_http_error:
raise aiohttp.web.HTTPNotFound(text=f'{component_name=} not found')
return False
def get_creation_date(component: ocm.Component) -> datetime.datetime:
'''
Trys to extract creation date from creationTime attribute and if not set from label with name
"cloud.gardener/ocm/creation-date".
Raises KeyError, if both is not successful.
'''
if (creationTime := component.creationTime):
return dateutil.parser.isoparse(creationTime)
creation_label: ocm.Label | None = component.find_label('cloud.gardener/ocm/creation-date')
if not creation_label:
raise KeyError(
'The attribute creation time, as well as the',
'label named "cloud.gardener/ocm/creation-date", were not set.',
)
else:
return dateutil.parser.isoparse(creation_label.value)
async def greatest_version_if_none(
component_name: str,
version: str,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent=None,
ocm_repo: ocm.OcmRepository=None,
oci_client: oci.client_async.Client=None,
version_filter: features.VersionFilter=features.VersionFilter.RELEASES_ONLY,
invalid_semver_ok: bool=False,
db_session: sqlasync.session.AsyncSession=None,
):
if version is None:
version = await greatest_component_version(
component_name=component_name,
version_lookup=version_lookup,
ocm_repo=ocm_repo,
oci_client=oci_client,
version_filter=version_filter,
invalid_semver_ok=invalid_semver_ok,
db_session=db_session,
)
if not version:
raise aiohttp.web.HTTPNotFound(
reason='No greatest version found',
text=f'No greatest version found for {component_name=}; {version_filter=}',
)
return version
async def _component_descriptor(
params: dict,
component_descriptor_lookup: cnudie.retrieve_async.ComponentDescriptorLookupById,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent,
version_filter: features.VersionFilter,
invalid_semver_ok: bool=False,
db_session: sqlasync.session.AsyncSession=None,
) -> ocm.ComponentDescriptor:
component_name = util.param(params, 'component_name', required=True)
ocm_repo_url = util.param(params, 'ocm_repo_url')
ocm_repo = ocm.OciOcmRepository(baseUrl=ocm_repo_url) if ocm_repo_url else None
version = util.param(params, 'version', default='greatest')
raw = util.param_as_bool(params, 'raw')
ignore_cache = util.param_as_bool(params, 'ignore_cache')
version_filter = util.param(params, 'version_filter', default=version_filter)
util.get_enum_value_or_raise(version_filter, features.VersionFilter)
if version == 'greatest':
version = await greatest_version_if_none(
component_name=component_name,
version=None,
version_lookup=version_lookup,
ocm_repo=ocm_repo,
version_filter=version_filter,
invalid_semver_ok=invalid_semver_ok,
db_session=db_session,
)
component_id = ocm.ComponentIdentity(
name=component_name,
version=version,
)
if ocm_repo_url:
ocm_repos = (ocm_repo_url,)
else:
if not (lookup := lookups.init_ocm_repository_lookup()):
raise ValueError('either ocm_repo_url, or ocm_repository_lookup must be passed')
ocm_repos = cnudie.retrieve.iter_ocm_repositories(
component_id,
lookup,
)
if raw or ignore_cache:
# in both cases fetch directly from oci-registry
try:
raw = await cnudie.retrieve_async.raw_component_descriptor_from_oci(
component_id=component_id,
ocm_repos=ocm_repos,
oci_client=lookups.semver_sanitising_oci_client_async(),
)
except om.OciImageNotFoundException:
raise aiohttp.web.HTTPNotFound(
reason='Component descriptor not found',
text=(
f'Component descriptor "{component_id.name}" in version '
f'"{component_id.version}" not found in {ocm_repo=}'
),
)
# wrap in fobj
blob_fobj = io.BytesIO(raw)
with tarfile.open(fileobj=blob_fobj, mode='r') as tf:
component_descriptor_info = tf.getmember(ocm.oci.component_descriptor_fname)
component_descriptor_bytes = tf.extractfile(component_descriptor_info).read()
if raw:
component_descriptor = component_descriptor_bytes.decode()
else:
try:
component_descriptor = ocm.ComponentDescriptor.from_dict(
yaml.safe_load(component_descriptor_bytes),
)
except dacite.exceptions.MissingValueError as e:
raise aiohttp.web.HTTPFailedDependency(
reason=str(e),
)
return component_descriptor
try:
descriptor = await util.retrieve_component_descriptor(
component_id,
component_descriptor_lookup=component_descriptor_lookup,
ocm_repo=ocm_repo,
)
except dacite.exceptions.MissingValueError as e:
raise aiohttp.web.HTTPFailedDependency(
reason=str(e),
)
return descriptor
class Component(aiohttp.web.View):
async def get(self):
'''
---
tags:
- Components
produces:
- application/json
parameters:
- in: query
name: component_name
type: string
required: true
- in: query
name: version
type: string
required: false
default: greatest
- in: query
name: ocm_repo_url
type: string
required: false
- in: query
name: raw
type: boolean
required: false
default: false
- in: query
name: ignore_cache
type: boolean
required: false
default: false
- in: query
name: version_filter
type: string
enum:
- all
- releases_only
required: false
'''
params = self.request.rel_url.query
component_descriptor = await _component_descriptor(
params=params,
component_descriptor_lookup=self.request.app[consts.APP_COMPONENT_DESCRIPTOR_LOOKUP],
version_lookup=self.request.app[consts.APP_VERSION_LOOKUP],
version_filter=self.request.app[consts.APP_VERSION_FILTER_CALLBACK](),
invalid_semver_ok=self.request.app[consts.APP_INVALID_SEMVER_OK],
db_session=self.request[consts.REQUEST_DB_SESSION],
)
return aiohttp.web.json_response(
data=component_descriptor,
dumps=util.dict_to_json_factory,
)
class ComponentDependencies(aiohttp.web.View):
async def get(self):
'''
---
tags:
- Components
produces:
- application/json
parameters:
- in: query
name: component_name
type: string
required: true
- in: query
name: version
type: string
required: false
default: greatest
- in: query
name: ocm_repo_url
type: string
required: false
- in: query
name: populate
type: string
enum:
- all
- componentReferences
required: false
default: all
- in: query
name: version_filter
type: string
enum:
- all
- releases_only
required: false
'''
params = self.request.rel_url.query
component_name = util.param(params, 'component_name', required=True)
populate = util.param(params, 'populate', default='all')
ocm_repo_url = util.param(params, 'ocm_repo_url')
ocm_repo = ocm.OciOcmRepository(baseUrl=ocm_repo_url) if ocm_repo_url else None
version = util.param(params, 'version', default='greatest')
version_filter = util.param(
params=params,
name='version_filter',
default=self.request.app[consts.APP_VERSION_FILTER_CALLBACK](),
)
util.get_enum_value_or_raise(version_filter, features.VersionFilter)
if version == 'greatest':
version = await greatest_version_if_none(
component_name=component_name,
version=None,
version_lookup=self.request.app[consts.APP_VERSION_LOOKUP],
ocm_repo=ocm_repo,
version_filter=version_filter,
invalid_semver_ok=self.request.app[consts.APP_INVALID_SEMVER_OK],
db_session=self.request[consts.REQUEST_DB_SESSION],
)
component_dependencies = resolve_component_dependencies(
component_name=component_name,
component_version=version,
component_descriptor_lookup=self.request.app[consts.APP_COMPONENT_DESCRIPTOR_LOOKUP],
ocm_repo=ocm_repo,
)
filtered_component_dependencies = []
async for component_node in component_dependencies:
if populate == 'componentReferences':
component_dependency = {
'name': component_node.component.name,
'version': component_node.component.version,
'repositoryContexts': component_node.component.repositoryContexts,
}
elif populate == 'all':
component_dependency = dataclasses.asdict(component_node.component)
else:
raise aiohttp.web.HTTPBadRequest(text=f'{populate} not implemented')
component_dependency['comp_ref'] = [
{
'name': ref.component.name,
'version': ref.component.version,
'repositoryContexts': ref.component.repositoryContexts,
}
for ref in component_node.path
]
filtered_component_dependencies.append(component_dependency)
return aiohttp.web.json_response(
data={
'componentDependencies': filtered_component_dependencies,
},
dumps=util.dict_to_json_factory,
)
class ComponentResponsibles(aiohttp.web.View):
@deliverydb.cache.dbcached_route(
skip_http_status=(http.HTTPStatus.ACCEPTED,)
)
async def get(self):
'''
---
description:
Returns a list of user-identities responsible for the given component or resource.
tags:
- Components
produces:
- application/json
parameters:
- in: query
name: component_name
type: string
required: true
- in: query
name: version
type: string
required: false
default: greatest
- in: query
name: artifact_name
type: string
required: false
description:
If given and specific responsibles are configured for the given artefact, (using label
`cloud.gardener.cnudie/responsibles`), then those take precedence over component-wide
responsibles.
- in: query
name: ocm_repo_url
type: string
required: false
- in: query
name: raw
type: boolean
required: false
default: false
- in: query
name: ignore_cache
type: boolean
required: false
default: false
- in: query
name: version_filter
type: string
enum:
- all
- releases_only
required: false
responses:
"200":
description: Successful operation.
schema:
$ref: '#/definitions/ComponentResponsibles'
"202":
description: GitHub statistics pending, client should retry.
'''
params = self.request.rel_url.query
statuses: list[responsibles.Status] = []
component_descriptor = await _component_descriptor(
params=params,
component_descriptor_lookup=self.request.app[consts.APP_COMPONENT_DESCRIPTOR_LOOKUP],
version_lookup=self.request.app[consts.APP_VERSION_LOOKUP],
version_filter=self.request.app[consts.APP_VERSION_FILTER_CALLBACK](),
invalid_semver_ok=self.request.app[consts.APP_INVALID_SEMVER_OK],
db_session=self.request[consts.REQUEST_DB_SESSION],
)
component = component_descriptor.component
main_source = cnudie.util.main_source(component_descriptor.component)
artifact_name = util.param(params, 'artifact_name')
def _responsibles_label(
component: ocm.Component,
artifact_name: str | None=None,
owners_label: str='cloud.gardener.cnudie/responsibles',
) -> responsibles.labels.ResponsiblesLabel | None:
'''
Returns the most specific ResponsiblesLabel for the given component and artifact name,
or `None` if no label is found.
If `artifact_name` is given, a fitting artifact with an owner label is looked up and
the attached label is returned. Otherwise, a fallback to component-level owner-label
happens.
'''
if artifact_name:
matching_artifacts = [
a for a in component.resources + component.sources
if a.name == artifact_name
]
if not matching_artifacts:
raise aiohttp.web.HTTPNotFound(
text=f'{component.name}:{component.version} has no {artifact_name=}'
)
for artifact in matching_artifacts:
artifact: ocm.Artifact
# hack: hard-code to using first matching artifact with label for now
if responsibles_label := artifact.find_label(name=owners_label):
return responsibles.labels.ResponsiblesLabel.from_dict(
data_dict=dataclasses.asdict(responsibles_label),
)
if responsibles_label := component.find_label(name=owners_label):
return responsibles.labels.ResponsiblesLabel.from_dict(
data_dict=dataclasses.asdict(responsibles_label),
)
return None
try:
responsibles_label = _responsibles_label(
component=component,
artifact_name=artifact_name,
)
except (
dacite.exceptions.UnionMatchError,
dacite.exceptions.WrongTypeError,
dacite.exceptions.UnexpectedDataError,
):
responsibles_label = None # fallback to heuristic
statuses.append(responsibles.Status(
type='error',
msg='responsibles-label malformed, falling back to responsibles-heuristic',
))
logger.warning(
'encountered errors while processing responsibles-label for '
f'{component.identity()=}, {artifact_name=}'
)
if responsibles_label:
user_identities = tuple(responsibles.user_identities_from_responsibles_label(
responsibles_label=responsibles_label,
source=main_source,
component_identity=component_descriptor.component.identity(),
github_api_lookup=self.request.app[consts.APP_GITHUB_API_LOOKUP],
))
else:
try:
user_identities = responsibles.user_identities_from_source(
source=main_source,
github_api_lookup=self.request.app[consts.APP_GITHUB_API_LOOKUP],
)
except ValueError:
user_identities = []
statuses.append(responsibles.Status(
type='error',
msg='responsibles-heuristic was not able to determine responsibles as '
'(github) statistics are incomplete',
))
if user_identities is None: # can be falsy
# github statistics pending, client should retry
return aiohttp.web.Response(
status=http.HTTPStatus.ACCEPTED,
)
user_identities = [
yp.inject(
addressbook_source=self.request.app[consts.APP_ADDRESSBOOK_SOURCE],
addressbook_entries=self.request.app[consts.APP_ADDRESSBOOK_ENTRIES],
addressbook_github_mappings=self.request.app[consts.APP_ADDRESSBOOK_GITHUB_MAPPINGS],
user_id=user_id,
).identifiers
for user_id in user_identities
]
return aiohttp.web.json_response(
data={
'responsibles': user_identities,
'statuses': [dataclasses.asdict(s) for s in statuses],
},
dumps=util.dict_to_json_factory,
)
# Note: The cache manager expects this function to use the persistent db-cache annotator. If this
# would be removed in a future change, the cache manager also had to be adjusted to prevent
# unnecessary load.
@deliverydb.cache.dbcached_function(
ttl_seconds=60,
exclude_kwargs=('version_lookup', 'oci_client'),
)
async def component_versions(
component_name: str,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent=None,
ocm_repo: ocm.OcmRepository=None,
oci_client: oci.client_async.Client=None,
db_session: sqlasync.session.AsyncSession=None, # required for db-cache
) -> list[str]:
if not ocm_repo and not version_lookup:
raise ValueError('At least one of `ocm_repo` and `version_lookup` must be specified')
if ocm_repo:
if not isinstance(ocm_repo, ocm.OciOcmRepository):
raise NotImplementedError(ocm_repo)
if not oci_client:
oci_client = lookups.semver_sanitising_oci_client_async()
try:
return await cnudie.retrieve_async.component_versions(
component_name=component_name,
ocm_repo=ocm_repo,
oci_client=oci_client,
)
except aiohttp.ClientResponseError:
return []
return await version_lookup(
component_id=ocm.ComponentIdentity(
name=component_name,
version=None
),
)
async def greatest_component_version(
component_name: str,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent=None,
ocm_repo: ocm.OcmRepository=None,
oci_client: oci.client_async.Client=None,
version_filter: features.VersionFilter=features.VersionFilter.RELEASES_ONLY,
invalid_semver_ok: bool=False,
db_session: sqlasync.session.AsyncSession=None,
) -> str | None:
versions = await component_versions(
component_name=component_name,
version_lookup=version_lookup,
ocm_repo=ocm_repo,
oci_client=oci_client,
db_session=db_session,
)
greatest_candidate = None
greatest_candidate_semver = None
for candidate in versions:
if isinstance(candidate, str):
candidate_semver = versionutil.parse_to_semver(
version=candidate,
invalid_semver_ok=invalid_semver_ok,
)
if not candidate_semver:
continue
else:
candidate_semver = candidate
if (
version_filter == features.VersionFilter.RELEASES_ONLY
and (candidate_semver.prerelease or candidate_semver.build)
):
continue
if not greatest_candidate_semver:
greatest_candidate_semver = candidate_semver
greatest_candidate = candidate
continue
if candidate_semver > greatest_candidate_semver:
greatest_candidate_semver = candidate_semver
greatest_candidate = candidate
return greatest_candidate
async def greatest_component_versions(
component_name: str,
component_descriptor_lookup: cnudie.retrieve_async.ComponentDescriptorLookupById,
ocm_repo: ocm.OcmRepository=None,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent=None,
max_versions: int=5,
greatest_version: str=None,
oci_client: oci.client_async.Client=None,
version_filter: features.VersionFilter=features.VersionFilter.RELEASES_ONLY,
invalid_semver_ok: bool=False,
start_date: datetime.date=None,
end_date: datetime.date=None,
db_session: sqlasync.session.AsyncSession=None,
) -> list[str]:
versions = await component_versions(
component_name=component_name,
version_lookup=version_lookup,
ocm_repo=ocm_repo,
oci_client=oci_client,
db_session=db_session,
)
if not versions:
return []
versions = [
v for v in versions
if versionutil.parse_to_semver(
version=v,
invalid_semver_ok=invalid_semver_ok,
)
]
if version_filter == features.VersionFilter.RELEASES_ONLY:
versions = [
v for v in versions
if not (pv := versionutil.parse_to_semver(
version=v,
invalid_semver_ok=invalid_semver_ok,
)).prerelease and not pv.build
]
versions = sorted(versions, key=lambda v: versionutil.parse_to_semver(
version=v,
invalid_semver_ok=invalid_semver_ok,
))
# If no end_date is provided, default to now
if not end_date:
end_date = datetime.date.today().isoformat()
# Handle date range filtering only if start_date is provided
if start_date:
async def filter_by_date_range(versions):
for version in reversed(versions):
component_descriptor = await util.retrieve_component_descriptor(
ocm.ComponentIdentity(
name=component_name,
version=version,
),
component_descriptor_lookup
)
creation_date = get_creation_date(
component_descriptor.component
).strftime('%Y-%m-%d')
if creation_date > end_date:
continue
if creation_date < start_date:
break
yield version
versions = [
version async for version
in filter_by_date_range(versions)
]
if greatest_version:
versions = versions[:versions.index(greatest_version) + 1]
if not start_date:
return versions[-max_versions:]
return versions
class GreatestComponentVersions(aiohttp.web.View):
async def get(self):
'''
---
tags:
- Components
produces:
- application/json
parameters:
- in: query
name: component_name
type: string
required: true
- in: query
name: version
type: string
required: false
- in: query
name: ocm_repo_url
type: string
required: false
- in: query
name: max
type: integer
required: false
default: 5
- in: query
name: start_date
type: string
required: false
- in: query
name: end_date
type: string
required: false
- in: query
name: version_filter
type: string
enum:
- all
- releases_only
required: false
responses:
"200":
description: Successful operation.
schema:
type: array
items:
type: string
'''
params = self.request.rel_url.query
component_name = util.param(params, 'component_name', required=True)
max_version = util.param(params, 'max', default=5)
start_date = util.param(params, 'start_date')
end_date = util.param(params, 'end_date')
version = util.param(params, 'version')
ocm_repo_url = util.param(params, 'ocm_repo_url')
ocm_repo = ocm.OciOcmRepository(baseUrl=ocm_repo_url) if ocm_repo_url else None
version_filter = util.param(
params=params,
name='version_filter',
default=self.request.app[consts.APP_VERSION_FILTER_CALLBACK](),
)
util.get_enum_value_or_raise(version_filter, features.VersionFilter)
try:
versions = await greatest_component_versions(
component_name=component_name,
component_descriptor_lookup=self.request.app[consts.APP_COMPONENT_DESCRIPTOR_LOOKUP],
ocm_repo=ocm_repo,
version_lookup=self.request.app[consts.APP_VERSION_LOOKUP],
max_versions=int(max_version),
greatest_version=version,
version_filter=version_filter,
invalid_semver_ok=self.request.app[consts.APP_INVALID_SEMVER_OK],
start_date=start_date,
end_date=end_date,
db_session=self.request[consts.REQUEST_DB_SESSION],
)
except ValueError:
raise aiohttp.web.HTTPNotFound(text=f'Version {version} not found')
return aiohttp.web.json_response(
data=versions,
dumps=util.dict_to_json_factory,
)
async def resolve_component_dependencies(
component_name: str,
component_version: str,
component_descriptor_lookup: cnudie.retrieve_async.ComponentDescriptorLookupById,
ocm_repo: ocm.OcmRepository=None,
recursion_depth: int=-1,
) -> collections.abc.AsyncGenerator[cnudie.iter.ComponentNode, None, None]:
descriptor = await util.retrieve_component_descriptor(
ocm.ComponentIdentity(
name=component_name,
version=component_version,
),
component_descriptor_lookup=component_descriptor_lookup,
ocm_repo=ocm_repo,
)
component = descriptor.component
try:
component_nodes = await _components(
component_name=component.name,
component_version=component.version,
component_descriptor_lookup=component_descriptor_lookup,
ocm_repo=ocm_repo,
recursion_depth=recursion_depth,
)
except dacite.exceptions.MissingValueError as e:
raise aiohttp.web.HTTPFailedDependency(text=str(e))
# add repo classification label if not present in component labels
async for component_node in component_nodes:
label_present = False
# if no sources present we cannot add the source
if not len(component_node.component.sources) > 0:
yield component_node
continue
for source in component_node.component.sources:
if 'cloud.gardener/cicd/source' in [label.name for label in source.labels]:
label_present = True
break
if not label_present:
component_node.component.sources[0].labels.append(ocm.Label(
name='cloud.gardener/cicd/source',
value={'repository-classification': 'main'},
))
yield component_node
class UpgradePRs(aiohttp.web.View):
required_features = (features.FeatureUpgradePRs,)
async def get(self):
'''
---
tags:
- Components
produces:
- application/json
parameters:
- in: query
name: componentName
type: string
required: false
- in: query
name: componentVersion
type: string
required: false
- in: query
name: repoUrl
type: string
required: false
- in: query
name: state
type: string
enum:
- all
- open
- closed
required: false
default: open
- in: query
name: ocmRepo
type: string
required: false
- in: query
name: version_filter
type: string
enum:
- all
- releases_only
required: false
'''
params = self.request.rel_url.query
component_name = util.param(params, 'componentName')
component_version = util.param(params, 'componentVersion')
repo_url = util.param(params, 'repoUrl')
pr_state = util.param(params, 'state', default='open')
ocm_repo_url = util.param(params, 'ocmRepo')
ocm_repo = ocm.OciOcmRepository(baseUrl=ocm_repo_url) if ocm_repo_url else None
version_filter = util.param(
params=params,
name='version_filter',
default=self.request.app[consts.APP_VERSION_FILTER_CALLBACK](),
)
util.get_enum_value_or_raise(version_filter, features.VersionFilter)
if not (bool(component_name) ^ bool(repo_url)):
raise aiohttp.web.HTTPBadRequest(
text='Exactly one of componentName and repoUrl must be passed',
)
if component_name:
component_version = await greatest_version_if_none(
component_name=component_name,
version=component_version,
version_lookup=self.request.app[consts.APP_VERSION_LOOKUP],
ocm_repo=ocm_repo,
version_filter=version_filter,
invalid_semver_ok=self.request.app[consts.APP_INVALID_SEMVER_OK],
db_session=self.request[consts.REQUEST_DB_SESSION],
)
component_descriptor = await util.retrieve_component_descriptor(
ocm.ComponentIdentity(
name=component_name,
version=component_version,
),
component_descriptor_lookup=self.request.app[consts.APP_COMPONENT_DESCRIPTOR_LOOKUP],
ocm_repo=ocm_repo,
)
component = component_descriptor.component
source = cnudie.util.main_source(
component=component,
absent_ok=True,
)
repo_url = source.access.repoUrl if source else component_name
def upgrade_pr_to_dict(
upgrade_pr: github.util.UpgradePullRequest,
) -> dict:
from_ref: ocm.ComponentReference = upgrade_pr.from_ref
to_ref: ocm.ComponentReference = upgrade_pr.to_ref
pr = upgrade_pr.pull_request
return {
'from': {
'name': from_ref.name,
'version': from_ref.version,
},
'to': {
'name': to_ref.name,
'version': to_ref.version,
},
'pr': {