-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathresource.py
More file actions
2112 lines (1767 loc) · 79.7 KB
/
resource.py
File metadata and controls
2112 lines (1767 loc) · 79.7 KB
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 base64
import contextlib
import copy
import json
import os
import re
import sys
import threading
import warnings
from abc import ABC, abstractmethod
from collections.abc import Callable, Generator
from io import StringIO
from signal import SIGINT, signal
from types import TracebackType
from typing import Any, Self
from urllib.parse import parse_qs, urlencode, urlparse
import jsonschema
import kubernetes
import requests
import yaml
from benedict import benedict
from kubernetes.dynamic import DynamicClient, ResourceInstance
from kubernetes.dynamic.exceptions import (
ConflictError,
ForbiddenError,
MethodNotAllowedError,
NotFoundError,
ResourceNotFoundError,
)
from kubernetes.dynamic.resource import ResourceField
from packaging.version import Version
from simple_logger.logger import get_logger, logging
from timeout_sampler import (
TimeoutExpiredError,
TimeoutSampler,
TimeoutWatch,
)
from urllib3.exceptions import MaxRetryError
from fake_kubernetes_client.dynamic_client import FakeDynamicClient
from ocp_resources.event import Event
from ocp_resources.exceptions import (
ClientWithBasicAuthError,
ConditionError,
MissingRequiredArgumentError,
MissingResourceResError,
ResourceTeardownError,
ValidationError,
)
from ocp_resources.utils.client_config import DynamicClientWithKubeconfig, resolve_bearer_token, save_kubeconfig
from ocp_resources.utils.constants import (
DEFAULT_CLUSTER_RETRY_EXCEPTIONS,
NOT_FOUND_ERROR_EXCEPTION_DICT,
PROTOCOL_ERROR_EXCEPTION_DICT,
TIMEOUT_1MINUTE,
TIMEOUT_1SEC,
TIMEOUT_4MINUTES,
TIMEOUT_5SEC,
TIMEOUT_10SEC,
TIMEOUT_30SEC,
)
from ocp_resources.utils.resource_constants import ResourceConstants
from ocp_resources.utils.schema_validator import SchemaValidator
from ocp_resources.utils.utils import skip_existing_resource_creation_teardown
LOGGER = get_logger(name=__name__)
MAX_SUPPORTED_API_VERSION = "v2"
def _find_supported_resource(client: DynamicClient, api_group: str, kind: str) -> ResourceField | None:
results = client.resources.search(group=api_group, kind=kind)
sorted_results = sorted(results, key=lambda result: KubeAPIVersion(result.api_version), reverse=True)
for result in sorted_results:
if KubeAPIVersion(result.api_version) <= KubeAPIVersion(MAX_SUPPORTED_API_VERSION):
return result
return None
def _get_api_version(client: DynamicClient, api_group: str, kind: str) -> str:
# Returns api_group/api_version
res = _find_supported_resource(client=client, api_group=api_group, kind=kind)
log = f"Couldn't find {kind} in {api_group} api group"
if not res:
LOGGER.warning(log)
raise NotImplementedError(log)
if isinstance(res.group_version, str):
LOGGER.info(f"kind: {kind} api version: {res.group_version}")
return res.group_version
raise NotImplementedError(log)
def client_configuration_with_basic_auth(
username: str,
password: str,
host: str,
configuration: kubernetes.client.Configuration,
) -> kubernetes.client.ApiClient:
verify_ssl = configuration.verify_ssl
def _fetch_oauth_config(_host: str, _verify_ssl: bool) -> Any:
well_known_url = f"{_host}/.well-known/oauth-authorization-server"
config_response = requests.get(well_known_url, verify=_verify_ssl)
if config_response.status_code != 200:
raise ClientWithBasicAuthError("No well-known file found at endpoint")
return config_response.json()
def _get_authorization_code(_auth_endpoint: str, _username: str, _password: str, _verify_ssl: bool) -> str:
_code = None
auth_params = {
"client_id": "openshift-challenging-client",
"response_type": "code",
"state": "USER",
"code_challenge_method": "S256",
}
auth_url = f"{_auth_endpoint}?{urlencode(auth_params)}"
credentials = f"{_username}:{_password}"
auth_header = base64.b64encode(credentials.encode()).decode()
auth_response = requests.get(
auth_url,
headers={"Authorization": f"Basic {auth_header}", "X-CSRF-Token": "USER", "Accept": "application/json"},
verify=_verify_ssl,
allow_redirects=False,
)
if auth_response.status_code == 302:
location = auth_response.headers.get("Location", "")
parsed_url = urlparse(location)
query_params = parse_qs(parsed_url.query)
_code = query_params.get("code", [None])[0]
if _code:
return _code
raise ClientWithBasicAuthError("No authorization code found")
def _exchange_code_for_token(
_token_endpoint: str, _auth_code: str, _verify_ssl: bool
) -> kubernetes.client.ApiClient:
_client = None
token_data = {
"grant_type": "authorization_code",
"code": _auth_code,
"client_id": "openshift-challenging-client",
}
token_response = requests.post(
_token_endpoint,
data=token_data,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
# openshift-challenging-client:
"Authorization": "Basic b3BlbnNoaWZ0LWNoYWxsZW5naW5nLWNsaWVudDo=",
},
verify=_verify_ssl,
)
if token_response.status_code == 200:
token_json = token_response.json()
access_token = token_json.get("access_token")
configuration.host = host
configuration.api_key = {"authorization": f"Bearer {access_token}"}
_client = kubernetes.client.ApiClient(configuration=configuration)
if _client:
return _client
raise ClientWithBasicAuthError("Failed to authenticate with basic auth")
oauth_config = _fetch_oauth_config(_host=host, _verify_ssl=verify_ssl)
auth_endpoint = oauth_config.get("authorization_endpoint")
if not auth_endpoint:
raise ClientWithBasicAuthError("No authorization_endpoint found in well-known file")
_code = _get_authorization_code(
_auth_endpoint=auth_endpoint, _username=username, _password=password, _verify_ssl=verify_ssl
)
return _exchange_code_for_token(
_token_endpoint=oauth_config.get("token_endpoint"), _auth_code=_code, _verify_ssl=verify_ssl
)
def get_client(
config_file: str | None = None,
config_dict: dict[str, Any] | None = None,
context: str | None = None,
client_configuration: kubernetes.client.Configuration | None = None,
persist_config: bool = True,
temp_file_path: str | None = None,
try_refresh_token: bool = True,
username: str | None = None,
password: str | None = None,
host: str | None = None,
verify_ssl: bool | None = None,
token: str | None = None,
fake: bool = False,
generate_kubeconfig: bool = False,
) -> DynamicClient | FakeDynamicClient:
"""
Get a kubernetes client.
This function is a replica of `ocp_utilities.infra.get_client` which cannot be imported as ocp_utilities imports
from ocp_resources.
Pass either config_file or config_dict.
If none of them are passed, client will be created from default OS kubeconfig
(environment variable or .kube folder).
Args:
config_file (str): path to a kubeconfig file.
config_dict (dict): dict with kubeconfig configuration.
context (str): name of the context to use.
persist_config (bool): whether to persist config file.
temp_file_path (str): path to a temporary kubeconfig file.
try_refresh_token (bool): try to refresh token
username (str): username for basic auth
password (str): password for basic auth
host (str): host for the cluster
verify_ssl (bool): whether to verify ssl
token (str): Use token to login
generate_kubeconfig (bool): if True, save the kubeconfig to a temporary file and add path to client kubeconfig attribute.
Returns:
DynamicClient: a kubernetes client.
"""
if fake:
return FakeDynamicClient()
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
client_configuration = client_configuration or kubernetes.client.Configuration()
if verify_ssl is not None:
client_configuration.verify_ssl = verify_ssl
if not client_configuration.proxy and proxy:
LOGGER.info(f"Setting proxy from environment variable: {proxy}")
client_configuration.proxy = proxy
if username and password and host:
_client = client_configuration_with_basic_auth(
username=username, password=password, host=host, configuration=client_configuration
)
elif host and token:
client_configuration.host = host
client_configuration.api_key = {"authorization": f"Bearer {token}"}
_client = kubernetes.client.ApiClient(client_configuration)
# Ref: https://github.com/kubernetes-client/python/blob/v26.1.0/kubernetes/base/config/kube_config.py
elif config_dict:
_client = kubernetes.config.new_client_from_config_dict(
config_dict=config_dict,
context=context,
client_configuration=client_configuration,
persist_config=persist_config,
temp_file_path=temp_file_path,
)
else:
# Ref: https://github.com/kubernetes-client/python/blob/v26.1.0/kubernetes/base/config/__init__.py
LOGGER.info("Trying to get client via new_client_from_config")
# kubernetes.config.kube_config.load_kube_config sets KUBE_CONFIG_DEFAULT_LOCATION during module import.
# If `KUBECONFIG` environment variable is set via code, the `KUBE_CONFIG_DEFAULT_LOCATION` will be None since
# is populated during import which comes before setting the variable in code.
config_file = config_file or os.environ.get("KUBECONFIG", "~/.kube/config")
_client = kubernetes.config.new_client_from_config(
config_file=config_file,
context=context,
client_configuration=client_configuration,
persist_config=persist_config,
)
kubernetes.client.Configuration.set_default(default=client_configuration)
try:
_dynamic_client = kubernetes.dynamic.DynamicClient(client=_client)
except MaxRetryError:
# Ref: https://github.com/kubernetes-client/python/blob/v26.1.0/kubernetes/base/config/incluster_config.py
LOGGER.info("Trying to get client via incluster_config")
_dynamic_client = kubernetes.dynamic.DynamicClient(
client=kubernetes.config.incluster_config.load_incluster_config(
client_configuration=client_configuration, try_refresh_token=try_refresh_token
),
)
if generate_kubeconfig:
if config_file:
LOGGER.info(f"`generate_kubeconfig` ignored, kubeconfig already available at {config_file}")
_dynamic_client = DynamicClientWithKubeconfig(client=_dynamic_client.client, kubeconfig=config_file)
else:
_resolved_token = resolve_bearer_token(token=token, client_configuration=client_configuration)
kubeconfig_path = save_kubeconfig(
host=host or client_configuration.host,
token=_resolved_token,
config_dict=config_dict,
verify_ssl=verify_ssl,
)
_dynamic_client = DynamicClientWithKubeconfig(client=_dynamic_client.client, kubeconfig=kubeconfig_path)
return _dynamic_client
def sub_resource_level(current_class: Any, owner_class: Any, parent_class: Any) -> str | None:
# return the name of the last class in MRO list that is not one of base
# classes; otherwise return None
for class_iterator in reversed([
class_iterator
for class_iterator in current_class.mro()
if class_iterator not in owner_class.mro() and issubclass(class_iterator, parent_class)
]):
return class_iterator.__name__
return None
def replace_key_with_hashed_value(resource_dict: dict[Any, Any], key_name: str) -> dict[Any, Any]:
"""
Recursively search a nested dictionary for a given key and changes its value to "******" if found.
The function supports two key formats:
1. Regular dictionary path:
A key to be hashed can be found directly in a dictionary, e.g. "a>b>c", would hash the value associated with
key "c", where dictionary format is:
input = {
"a": {
"b": {
"c": "sensitive data"
}
}
}
output = {
"a": {
"b": {
"c": "*******"
}
}
}
2. list path:
A key to be hashed can be found in a dictionary that is in list somewhere in a dictionary, e.g. "a>b[]>c",
would hash the value associated with key "c", where dictionary format is:
input = {
"a": {
"b": [
{"d": "not sensitive data"},
{"c": "sensitive data"}
]
}
}
output = {
"a": {
"b": [
{"d": "not sensitive data"},
{"c": "*******"}
]
}
}
Args:
resource_dict: The nested dictionary to search.
key_name: The key path to find.
Returns:
dict[Any, Any]: A copy of the input dictionary with the specified key's value replaced with "*******".
"""
result = copy.deepcopy(resource_dict)
benedict_resource_dict = benedict(result, keypath_separator=">")
if "[]" not in key_name:
if benedict_resource_dict.get(key_name):
benedict_resource_dict[key_name] = "*******"
return dict(benedict_resource_dict)
key_prefix, remaining_key = key_name.split("[]>", 1)
if not benedict_resource_dict.get(key_prefix):
return dict(benedict_resource_dict)
resource_data = benedict_resource_dict[key_prefix]
if not isinstance(resource_data, list):
return dict(benedict_resource_dict)
for index, element in enumerate(resource_data):
if isinstance(element, dict):
resource_data[index] = replace_key_with_hashed_value(resource_dict=element, key_name=remaining_key)
return dict(benedict_resource_dict)
class KubeAPIVersion(Version):
"""
Implement the Kubernetes API versioning scheme from
https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-versioning
"""
component_re = re.compile(r"(\d+ | [a-z]+)", re.VERBOSE)
def __init__(self, vstring: str):
self.vstring = vstring
self.version: list[str | Any] = []
super().__init__(version=vstring)
def parse(self, vstring: str) -> None:
components = [comp for comp in self.component_re.split(vstring) if comp]
for idx, obj in enumerate(components):
with contextlib.suppress(ValueError):
components[idx] = int(obj)
errmsg = f"version '{vstring}' does not conform to kubernetes api versioning guidelines"
if len(components) not in (2, 4) or components[0] != "v" or not isinstance(components[1], int):
raise ValueError(errmsg)
if len(components) == 4 and (components[2] not in ("alpha", "beta") or not isinstance(components[3], int)):
raise ValueError(errmsg)
self.version = components
def __str__(self):
return self.vstring
def __repr__(self):
return f"KubeAPIVersion ('{str(self)}')"
def _cmp(self, other):
if isinstance(other, str):
other = KubeAPIVersion(vstring=other)
myver = self.version
otherver = other.version
for ver in myver, otherver:
if len(ver) == 2:
ver.extend(["zeta", 9999])
if myver == otherver:
return 0
if myver < otherver:
return -1
if myver > otherver:
return 1
class ClassProperty:
def __init__(self, func: Callable) -> None:
self.func = func
def __get__(self, obj: Any, owner: Any) -> Any:
return self.func(owner)
class Resource(ResourceConstants):
"""
Base class for API resources
Provides common functionality for all Kubernetes/OpenShift resources including
CRUD operations, resource management, and schema validation.
Attributes:
api_group (str): API group for the resource (e.g., "apps", "batch")
api_version (str): API version (e.g., "v1", "v1beta1")
singular_name (str): Singular resource name for API calls
timeout_seconds (int): Default timeout for API operations
schema_validation_enabled (bool): Enable automatic validation on create/update
"""
api_group: str = ""
api_version: str = ""
singular_name: str = ""
timeout_seconds: int = TIMEOUT_1MINUTE
class ApiGroup:
AAQ_KUBEVIRT_IO: str = "aaq.kubevirt.io"
ADMISSIONREGISTRATION_K8S_IO: str = "admissionregistration.k8s.io"
APIEXTENSIONS_K8S_IO: str = "apiextensions.k8s.io"
APIREGISTRATION_K8S_IO: str = "apiregistration.k8s.io"
APP_KUBERNETES_IO: str = "app.kubernetes.io"
APPS: str = "apps"
APPSTUDIO_REDHAT_COM: str = "appstudio.redhat.com"
AUTHENTICATION_K8S_IO: str = "authentication.k8s.io"
BATCH: str = "batch"
BITNAMI_COM: str = "bitnami.com"
CACHING_INTERNAL_KNATIVE_DEV: str = "caching.internal.knative.dev"
CDI_KUBEVIRT_IO: str = "cdi.kubevirt.io"
CLONE_KUBEVIRT_IO: str = "clone.kubevirt.io"
CLUSTER_OPEN_CLUSTER_MANAGEMENT_IO: str = "cluster.open-cluster-management.io"
COMPONENTS_PLATFORM_OPENDATAHUB_IO = "components.platform.opendatahub.io"
CONFIG_OPENSHIFT_IO: str = "config.openshift.io"
CONSOLE_OPENSHIFT_IO: str = "console.openshift.io"
COORDINATION_K8S_IO: str = "coordination.k8s.io"
CSIADDONS_OPENSHIFT_IO: str = "csiaddons.openshift.io"
DATA_IMPORT_CRON_TEMPLATE_KUBEVIRT_IO: str = "dataimportcrontemplate.kubevirt.io"
DATASCIENCECLUSTER_OPENDATAHUB_IO: str = "datasciencecluster.opendatahub.io"
DATASCIENCEPIPELINESAPPLICATIONS_OPENDATAHUB_IO: str = "datasciencepipelinesapplications.opendatahub.io"
DISCOVERY_K8S_IO: str = "discovery.k8s.io"
DSCINITIALIZATION_OPENDATAHUB_IO: str = "dscinitialization.opendatahub.io"
EVENTS_K8S_IO: str = "events.k8s.io"
EXPORT_KUBEVIRT_IO: str = "export.kubevirt.io"
FENCE_AGENTS_REMEDIATION_MEDIK8S_IO: str = "fence-agents-remediation.medik8s.io"
FORKLIFT_KONVEYOR_IO: str = "forklift.konveyor.io"
FRRK8S_METALLB_IO = "frrk8s.metallb.io"
GATEWAY_NETWORKING_K8S_IO: str = "gateway.networking.k8s.io"
HCO_KUBEVIRT_IO: str = "hco.kubevirt.io"
HELM_MARIADB_MMONTES_IO: str = "helm.mariadb.mmontes.io"
HIVE_OPENSHIFT_IO: str = "hive.openshift.io"
HOSTPATHPROVISIONER_KUBEVIRT_IO: str = "hostpathprovisioner.kubevirt.io"
IMAGE_OPENSHIFT_IO: str = "image.openshift.io"
IMAGE_REGISTRY: str = "registry.redhat.io"
IMAGEREGISTRY_OPERATOR_OPENSHIFT_IO: str = "imageregistry.operator.openshift.io"
INSTANCETYPE_KUBEVIRT_IO: str = "instancetype.kubevirt.io"
INTEGREATLY_ORG: str = "integreatly.org"
JAEGERTRACING_IO = "jaegertracing.io"
K8S_CNI_CNCF_IO: str = "k8s.cni.cncf.io"
K8S_MARIADB_COM: str = "k8s.mariadb.com"
K8S_OVN_ORG: str = "k8s.ovn.org"
K8S_V1_CNI_CNCF_IO: str = "k8s.v1.cni.cncf.io"
KEDA_SH: str = "keda.sh"
KUADRANT_IO = "kuadrant.io"
KUBEFLOW_ORG: str = "kubeflow.org"
KUBERNETES_IO: str = "kubernetes.io"
KUBEVIRT_IO: str = "kubevirt.io"
KUBEVIRT_KUBEVIRT_IO: str = "kubevirt.kubevirt.io"
LITMUS_IO: str = "litmuschaos.io"
LLAMASTACK_IO: str = "llamastack.io"
MAAS_OPENDATAHUB_IO: str = "maas.opendatahub.io"
MACHINE_OPENSHIFT_IO: str = "machine.openshift.io"
MACHINECONFIGURATION_OPENSHIFT_IO: str = "machineconfiguration.openshift.io"
MAISTRA_IO: str = "maistra.io"
METALLB_IO: str = "metallb.io"
METRICS_K8S_IO: str = "metrics.k8s.io"
MIGRATION_OPENSHIFT_IO: str = "migration.openshift.io"
MIGRATIONS_KUBEVIRT_IO: str = "migrations.kubevirt.io"
MODELREGISTRY_OPENDATAHUB_IO: str = "modelregistry.opendatahub.io"
MONITORING_COREOS_COM: str = "monitoring.coreos.com"
MTQ_KUBEVIRT_IO: str = "mtq.kubevirt.io"
NETWORKADDONSOPERATOR_NETWORK_KUBEVIRT_IO: str = "networkaddonsoperator.network.kubevirt.io"
NETWORKING_ISTIO_IO: str = "networking.istio.io"
NETWORKING_K8S_IO: str = "networking.k8s.io"
NMSTATE_IO: str = "nmstate.io"
NODE_LABELLER_KUBEVIRT_IO: str = "node-labeller.kubevirt.io"
NODEMAINTENANCE_KUBEVIRT_IO: str = "nodemaintenance.kubevirt.io"
NVIDIA_COM: str = "nvidia.com"
OBSERVABILITY_OPEN_CLUSTER_MANAGEMENT_IO: str = "observability.open-cluster-management.io"
OCS_OPENSHIFT_IO: str = "ocs.openshift.io"
OPENTELEMETRY_IO: str = "opentelemetry.io"
OPERATOR_AUTHORINO_KUADRANT_IO: str = "operator.authorino.kuadrant.io"
OPERATOR_OPEN_CLUSTER_MANAGEMENT_IO: str = "operator.open-cluster-management.io"
OPERATOR_OPENSHIFT_IO: str = "operator.openshift.io"
OPERATORS_COREOS_COM: str = "operators.coreos.com"
OPERATORS_OPENSHIFT_IO: str = "operators.openshift.io"
OS_TEMPLATE_KUBEVIRT_IO: str = "os.template.kubevirt.io"
PACKAGES_OPERATORS_COREOS_COM: str = "packages.operators.coreos.com"
PERFORMANCE_OPENSHIFT_IO: str = "performance.openshift.io"
POLICY: str = "policy"
POOL_KUBEVIRT_IO: str = "pool.kubevirt.io"
PROJECT_OPENSHIFT_IO: str = "project.openshift.io"
QUOTA_OPENSHIFT_IO: str = "quota.openshift.io"
RBAC_AUTHORIZATION_K8S_IO: str = "rbac.authorization.k8s.io"
REMEDIATION_MEDIK8S_IO: str = "remediation.medik8s.io"
RHTAS_REDHAT_COM: str = "rhtas.redhat.com"
RIPSAW_CLOUDBULLDOZER_IO: str = "ripsaw.cloudbulldozer.io"
ROUTE_OPENSHIFT_IO: str = "route.openshift.io"
SAMPLES_OPERATOR_OPENSHIFT_IO: str = "samples.operator.openshift.io"
SCHEDULING_K8S_IO: str = "scheduling.k8s.io"
SECURITY_ISTIO_IO: str = "security.istio.io"
SECURITY_OPENSHIFT_IO: str = "security.openshift.io"
SELF_NODE_REMEDIATION_MEDIK8S_IO: str = "self-node-remediation.medik8s.io"
SERVICES_PLATFORM_OPENDATAHUB_IO: str = "services.platform.opendatahub.io"
SERVING_KNATIVE_DEV: str = "serving.knative.dev"
SERVING_KSERVE_IO: str = "serving.kserve.io"
SNAPSHOT_KUBEVIRT_IO: str = "snapshot.kubevirt.io"
SNAPSHOT_STORAGE_K8S_IO: str = "snapshot.storage.k8s.io"
SRIOVNETWORK_OPENSHIFT_IO: str = "sriovnetwork.openshift.io"
SSP_KUBEVIRT_IO: str = "ssp.kubevirt.io"
STORAGE_K8S_IO: str = "storage.k8s.io"
STORAGECLASS_KUBERNETES_IO: str = "storageclass.kubernetes.io"
STORAGECLASS_KUBEVIRT_IO: str = "storageclass.kubevirt.io"
SUBRESOURCES_KUBEVIRT_IO: str = "subresources.kubevirt.io"
TEKTON_DEV: str = "tekton.dev"
TEKTONTASKS_KUBEVIRT_IO: str = "tektontasks.kubevirt.io"
TEMPLATE_KUBEVIRT_IO: str = "template.kubevirt.io"
TEMPLATE_OPENSHIFT_IO: str = "template.openshift.io"
TEMPO_GRAFANA_COM: str = "tempo.grafana.com"
TRUSTYAI_OPENDATAHUB_IO: str = "trustyai.opendatahub.io"
UPLOAD_CDI_KUBEVIRT_IO: str = "upload.cdi.kubevirt.io"
USER_OPENSHIFT_IO: str = "user.openshift.io"
V2V_KUBEVIRT_IO: str = "v2v.kubevirt.io"
VELERO_IO: str = "velero.io"
VM_KUBEVIRT_IO: str = "vm.kubevirt.io"
class ApiVersion:
V1: str = "v1"
V1BETA1: str = "v1beta1"
V1ALPHA1: str = "v1alpha1"
V1ALPHA3: str = "v1alpha3"
def __init__(
self,
client: DynamicClient | None = None, # TODO: make mandatory in the next major release
name: str | None = None,
teardown: bool = True,
yaml_file: str | None = None,
delete_timeout: int = TIMEOUT_4MINUTES,
dry_run: bool = False,
node_selector: dict[str, Any] | None = None,
node_selector_labels: dict[str, str] | None = None,
config_file: str | None = None,
config_dict: dict[str, Any] | None = None,
context: str | None = None,
label: dict[str, str] | None = None,
annotations: dict[str, str] | None = None,
api_group: str = "",
hash_log_data: bool = True,
ensure_exists: bool = False,
kind_dict: dict[Any, Any] | None = None,
wait_for_resource: bool = False,
schema_validation_enabled: bool = False,
):
"""
Create an API resource
If `yaml_file` or `kind_dict` are passed, logic in `to_dict` is bypassed.
Args:
name (str): Resource name
client (DynamicClient): Dynamic client for connecting to a remote cluster
teardown (bool): Indicates if this resource would need to be deleted
yaml_file (str): yaml file for the resource
delete_timeout (int): timeout associated with delete action
dry_run (bool): dry run
node_selector (dict): node selector
node_selector_labels (str): node selector labels
config_file (str): Path to config file for connecting to remote cluster.
context (str): Context name for connecting to remote cluster.
label (dict): Resource labels
annotations (dict[str, str] | None): Resource annotations
api_group (str): Resource API group; will overwrite API group definition in resource class
hash_log_data (bool): Hash resource content based on resource keys_to_hash property
(example: Secret resource)
ensure_exists (bool): Whether to check if the resource exists before when initializing the resource, raise if not.
kind_dict (dict): dict which represents the resource object
wait_for_resource (bool): Waits for the resource to be created
schema_validation_enabled (bool): Enable automatic schema validation for this instance.
Defaults to False. Set to True to validate on create/update operations.
"""
if yaml_file and kind_dict:
raise ValueError("yaml_file and resource_dict are mutually exclusive")
self.name = name
self.teardown = teardown
self.yaml_file = yaml_file
self.kind_dict = kind_dict
self.delete_timeout = delete_timeout
self.dry_run = dry_run
self.node_selector = node_selector
self.node_selector_labels = node_selector_labels
self.config_file = config_file
self.config_dict = config_dict or {}
self.context = context
self.label = label
self.annotations = annotations
if not client:
warnings.warn(
"'client' arg will be mandatory in the next major release. "
"`config_file` and `context` args will be removed.",
FutureWarning,
stacklevel=2,
)
self.client: DynamicClient = client or get_client(config_file=self.config_file, context=self.context)
self.api_group: str = api_group or self.api_group
self.hash_log_data = hash_log_data
if not self.api_group and not self.api_version:
raise NotImplementedError("Subclasses of Resource require self.api_group or self.api_version to be defined")
if not (self.name or self.yaml_file or self.kind_dict):
raise MissingRequiredArgumentError(argument="name")
self.namespace: str | None = None
self.node_selector_spec = self._prepare_node_selector_spec()
self.res: dict[Any, Any] = self.kind_dict or {}
self.yaml_file_contents: str = ""
self.initial_resource_version: str = ""
self.logger = self._set_logger()
self.wait_for_resource = wait_for_resource
if ensure_exists:
self._ensure_exists()
# Set instance-level validation flag
self.schema_validation_enabled = schema_validation_enabled
# self._set_api_version() must be last init line
self._set_api_version()
def _ensure_exists(self) -> None:
if not self.exists:
_name_for_raise = self.name if not self.namespace else f"{self.namespace}/{self.name}"
raise ResourceNotFoundError(f"Resource `{self.kind}` `{_name_for_raise}` does not exist")
def _set_logger(self) -> logging.Logger:
log_level = os.environ.get("OPENSHIFT_PYTHON_WRAPPER_LOG_LEVEL", "INFO")
log_file = os.environ.get("OPENSHIFT_PYTHON_WRAPPER_LOG_FILE", "")
return get_logger(
name=f"{__name__.rsplit('.')[0]} {self.kind}",
level=log_level,
filename=log_file,
)
def _prepare_node_selector_spec(self) -> dict[str, str]:
return self.node_selector or self.node_selector_labels or {}
@ClassProperty
def kind(cls) -> str | None:
return sub_resource_level(cls, NamespacedResource, Resource)
def _base_body(self) -> None:
"""
Generate resource dict from yaml if self.yaml_file else return base resource dict.
Returns:
dict: Resource dict.
"""
if self.kind_dict:
# If `kind_dict` is provided, no additional logic should be applied
self.name = self.kind_dict["metadata"]["name"]
elif self.yaml_file:
if not self.yaml_file_contents:
if isinstance(self.yaml_file, StringIO):
self.yaml_file_contents = self.yaml_file.read()
else:
with open(self.yaml_file) as stream:
self.yaml_file_contents = stream.read()
self.res = yaml.safe_load(stream=self.yaml_file_contents)
self.res.get("metadata", {}).pop("resourceVersion", None)
self.name = self.res["metadata"]["name"]
else:
self.res = {
"apiVersion": self.api_version,
"kind": self.kind,
"metadata": {"name": self.name},
}
if self.label:
self.res.setdefault("metadata", {}).setdefault("labels", {}).update(self.label)
if self.annotations:
self.res.setdefault("metadata", {}).setdefault("annotations", {}).update(self.annotations)
if not self.res:
raise MissingResourceResError(name=self.name or "")
def to_dict(self) -> None:
"""
Generate intended dict representation of the resource.
"""
self._base_body()
def __enter__(self) -> Any:
if threading.current_thread().native_id == threading.main_thread().native_id:
signal(SIGINT, self._sigint_handler)
return self.deploy(wait=self.wait_for_resource)
def __exit__(
self,
exc_type: type[BaseException] | None = None,
exc_val: BaseException | None = None,
exc_tb: TracebackType | None = None,
) -> None:
if self.teardown:
if not self.clean_up():
raise ResourceTeardownError(resource=self)
def _sigint_handler(self, signal_received: int, _frame: Any) -> None:
self.__exit__()
sys.exit(signal_received)
def deploy(self, wait: bool = False) -> Self:
"""
For debug, export REUSE_IF_RESOURCE_EXISTS to skip resource create.
Spaces are important in the export dict
Examples:
To skip creation of all resources by kind:
export REUSE_IF_RESOURCE_EXISTS="{Pod: {}}"
To skip creation of resource by name (on all namespaces or non-namespaced resources):
export REUSE_IF_RESOURCE_EXISTS="{Pod: {<pod-name>:}}"
To skip creation of resource by name and namespace:
export REUSE_IF_RESOURCE_EXISTS="{Pod: {<pod-name>: <pod-namespace>}}"
To skip creation of multiple resources:
export REUSE_IF_RESOURCE_EXISTS="{Namespace: {<namespace-name>:}, Pod: {<pod-name>: <pod-namespace>}}"
"""
_resource = None
_export_str = "REUSE_IF_RESOURCE_EXISTS"
skip_resource_kind_create_if_exists = os.environ.get(_export_str)
if skip_resource_kind_create_if_exists:
_resource = skip_existing_resource_creation_teardown(
resource=self,
export_str=_export_str,
user_exported_args=skip_resource_kind_create_if_exists,
)
if _resource:
return _resource
self.create(wait=wait)
return self
def clean_up(self, wait: bool = True, timeout: int | None = None) -> bool:
"""
For debug, export SKIP_RESOURCE_TEARDOWN to skip resource teardown.
Spaces are important in the export dict
Args:
wait (bool, optional): Wait for resource deletion. Defaults to True.
timeout (int, optional): Timeout in seconds to wait for resource to be deleted. Defaults to 240.
Returns:
bool: True if resource was deleted else False.
Examples:
To skip teardown of all resources by kind:
export SKIP_RESOURCE_TEARDOWN="{Pod: {}}"
To skip teardown of resource by name (on all namespaces):
export SKIP_RESOURCE_TEARDOWN="{Pod: {<pod-name>:}}"
To skip teardown of resource by name and namespace:
export SKIP_RESOURCE_TEARDOWN="{Pod: {<pod-name>: <pod-namespace>}}"
To skip teardown of multiple resources:
export SKIP_RESOURCE_TEARDOWN="{Namespace: {<namespace-name>:}, Pod: {<pod-name>: <pod-namespace>}}"
"""
_export_str = "SKIP_RESOURCE_TEARDOWN"
skip_resource_teardown = os.environ.get(_export_str)
if skip_resource_teardown and skip_existing_resource_creation_teardown(
resource=self,
export_str=_export_str,
user_exported_args=skip_resource_teardown,
check_exists=False,
):
self.logger.warning(
f"Skip resource {self.kind} {self.name} teardown. Got {_export_str}={skip_resource_teardown}"
)
return True
return self.delete(wait=wait, timeout=timeout or self.delete_timeout)
@classmethod
def _prepare_resources(
cls, client: DynamicClient, singular_name: str, *args: Any, **kwargs: Any
) -> ResourceInstance:
if not cls.api_version:
cls.api_version = _get_api_version(client=client, api_group=cls.api_group, kind=cls.kind)
get_kwargs = {"singular_name": singular_name} if singular_name else {}
return client.resources.get(
kind=cls.kind,
api_version=cls.api_version,
**get_kwargs,
).get(*args, **kwargs, timeout_seconds=cls.timeout_seconds)
def _prepare_singular_name_kwargs(self, **kwargs: Any) -> dict[str, Any]:
kwargs = kwargs if kwargs else {}
if self.singular_name:
kwargs["singular_name"] = self.singular_name
return kwargs
def _set_api_version(self) -> None:
if not self.api_version:
self.api_version = _get_api_version(client=self.client, api_group=self.api_group, kind=self.kind)
def full_api(self, **kwargs: Any) -> ResourceInstance:
"""
Get resource API
Keyword Args:
pretty
_continue
include_uninitialized
field_selector
label_selector
limit
resource_version
timeout_seconds
watch
async_req
Returns:
Resource: Resource object.
"""
self._set_api_version()
kwargs = self._prepare_singular_name_kwargs(**kwargs)
return self.client.resources.get(api_version=self.api_version, kind=self.kind, **kwargs)
@property
def api(self) -> ResourceInstance:
return self.full_api()
def wait(self, timeout: int = TIMEOUT_4MINUTES, sleep: int = 1) -> None:
"""
Wait for resource
Args:
timeout (int): Time to wait for the resource.
sleep (int): Time to wait between retries
Raises:
TimeoutExpiredError: If resource not exists.
"""
self.logger.info(f"Wait until {self.kind} {self.name} is created")
samples = TimeoutSampler(
wait_timeout=timeout,
sleep=sleep,
exceptions_dict={
**PROTOCOL_ERROR_EXCEPTION_DICT,
**NOT_FOUND_ERROR_EXCEPTION_DICT,
**DEFAULT_CLUSTER_RETRY_EXCEPTIONS,
},
func=lambda: self.exists,
)
for sample in samples:
if sample:
return
def wait_deleted(self, timeout: int = TIMEOUT_4MINUTES) -> bool:
"""
Wait until resource is deleted
Args:
timeout (int): Time to wait for the resource.
Raises:
TimeoutExpiredError: If resource still exists.
"""
self.logger.info(f"Wait until {self.kind} {self.name} is deleted")
try:
for sample in TimeoutSampler(wait_timeout=timeout, sleep=1, func=lambda: self.exists):
if not sample:
return True
except TimeoutExpiredError:
self.logger.warning(f"Timeout expired while waiting for {self.kind} {self.name} to be deleted")
return False
return False
@property
def exists(self) -> ResourceInstance | None:
"""
Whether self exists on the server
"""
try:
return self.instance
except NotFoundError:
return None
@property
def _kube_v1_api(self) -> kubernetes.client.CoreV1Api:
return kubernetes.client.CoreV1Api(api_client=self.client.client)
def wait_for_status(
self,
status: str,
timeout: int = TIMEOUT_4MINUTES,
stop_status: str | None = None,
sleep: int = 1,
exceptions_dict: dict[type[Exception], list[str]] = PROTOCOL_ERROR_EXCEPTION_DICT
| DEFAULT_CLUSTER_RETRY_EXCEPTIONS,
) -> None:
"""
Wait for resource to be in status
Args:
status (str): Expected status.