| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
import hashlib |
| 17 |
import json |
| 18 |
import os |
| 19 |
import tempfile |
| 20 |
from collections import defaultdict |
| 21 |
from functools import partial |
| 22 |
|
| 23 |
import kubernetes.dynamic |
| 24 |
import kubernetes.dynamic.discovery |
| 25 |
from ansible_collections.kubernetes.core.plugins.module_utils.client.resource import ( |
| 26 |
ResourceList, |
| 27 |
) |
| 28 |
from kubernetes import __version__ |
| 29 |
from kubernetes.dynamic.exceptions import ( |
| 30 |
ResourceNotFoundError, |
| 31 |
ResourceNotUniqueError, |
| 32 |
ServiceUnavailableError, |
| 33 |
) |
| 34 |
|
| 35 |
|
| 36 |
class Discoverer(kubernetes.dynamic.discovery.Discoverer): |
| 37 |
def __init__(self, client, cache_file): |
| 38 |
self.client = client |
| 39 |
default_cache_file_name = "k8srcp-{0}.json".format( |
| 40 |
hashlib.sha256(self.__get_default_cache_id()).hexdigest() |
| 41 |
) |
| 42 |
self.__cache_file = cache_file or os.path.join( |
| 43 |
tempfile.gettempdir(), default_cache_file_name |
| 44 |
) |
| 45 |
self.__init_cache() |
| 46 |
|
| 47 |
def __get_default_cache_id(self): |
| 48 |
user = self.__get_user() |
| 49 |
if user: |
| 50 |
cache_id = "{0}-{1}".format(self.client.configuration.host, user) |
| 51 |
else: |
| 52 |
cache_id = self.client.configuration.host |
| 53 |
return cache_id.encode("utf-8") |
| 54 |
|
| 55 |
def __get_user(self): |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
if hasattr(os, "getlogin"): |
| 61 |
try: |
| 62 |
user = os.getlogin() |
| 63 |
if user: |
| 64 |
return str(user) |
| 65 |
except OSError: |
| 66 |
pass |
| 67 |
if hasattr(os, "getuid"): |
| 68 |
try: |
| 69 |
user = os.getuid() |
| 70 |
if user: |
| 71 |
return str(user) |
| 72 |
except OSError: |
| 73 |
pass |
| 74 |
user = os.environ.get("USERNAME") |
| 75 |
if user: |
| 76 |
return str(user) |
| 77 |
return None |
| 78 |
|
| 79 |
def __init_cache(self, refresh=False): |
| 80 |
if refresh or not os.path.exists(self.__cache_file): |
| 81 |
self._cache = {"library_version": __version__} |
| 82 |
refresh = True |
| 83 |
else: |
| 84 |
try: |
| 85 |
with open(self.__cache_file, "r") as f: |
| 86 |
self._cache = json.load(f, cls=partial(CacheDecoder, self.client)) |
| 87 |
if self._cache.get("library_version") != __version__: |
| 88 |
|
| 89 |
self.invalidate_cache() |
| 90 |
except Exception: |
| 91 |
self.invalidate_cache() |
| 92 |
self._load_server_info() |
| 93 |
self.discover() |
| 94 |
if refresh: |
| 95 |
self._write_cache() |
| 96 |
|
| 97 |
def get_resources_for_api_version(self, prefix, group, version, preferred): |
| 98 |
"""returns a dictionary of resources associated with provided (prefix, group, version)""" |
| 99 |
|
| 100 |
resources = defaultdict(list) |
| 101 |
subresources = defaultdict(dict) |
| 102 |
|
| 103 |
path = "/".join(filter(None, [prefix, group, version])) |
| 104 |
try: |
| 105 |
resources_response = self.client.request("GET", path).resources or [] |
| 106 |
except ServiceUnavailableError: |
| 107 |
resources_response = [] |
| 108 |
|
| 109 |
resources_raw = list( |
| 110 |
filter(lambda resource: "/" not in resource["name"], resources_response) |
| 111 |
) |
| 112 |
subresources_raw = list( |
| 113 |
filter(lambda resource: "/" in resource["name"], resources_response) |
| 114 |
) |
| 115 |
for subresource in subresources_raw: |
| 116 |
resource, name = subresource["name"].split("/", 1) |
| 117 |
subresources[resource][name] = subresource |
| 118 |
|
| 119 |
for resource in resources_raw: |
| 120 |
|
| 121 |
for key in ("prefix", "group", "api_version", "client", "preferred"): |
| 122 |
resource.pop(key, None) |
| 123 |
|
| 124 |
resourceobj = kubernetes.dynamic.Resource( |
| 125 |
prefix=prefix, |
| 126 |
group=group, |
| 127 |
api_version=version, |
| 128 |
client=self.client, |
| 129 |
preferred=preferred, |
| 130 |
subresources=subresources.get(resource["name"]), |
| 131 |
**resource |
| 132 |
) |
| 133 |
resources[resource["kind"]].append(resourceobj) |
| 134 |
|
| 135 |
resource_lookup = { |
| 136 |
"prefix": prefix, |
| 137 |
"group": group, |
| 138 |
"api_version": version, |
| 139 |
"kind": resourceobj.kind, |
| 140 |
"name": resourceobj.name, |
| 141 |
} |
| 142 |
resource_list = ResourceList( |
| 143 |
self.client, |
| 144 |
group=group, |
| 145 |
api_version=version, |
| 146 |
base_kind=resource["kind"], |
| 147 |
base_resource_lookup=resource_lookup, |
| 148 |
) |
| 149 |
resources[resource_list.kind].append(resource_list) |
| 150 |
return resources |
| 151 |
|
| 152 |
def get(self, **kwargs): |
| 153 |
""" |
| 154 |
Same as search, but will throw an error if there are multiple or no |
| 155 |
results. If there are multiple results and only one is an exact match |
| 156 |
on api_version, that resource will be returned. |
| 157 |
""" |
| 158 |
results = self.search(**kwargs) |
| 159 |
|
| 160 |
if len(results) > 1 and kwargs.get("api_version"): |
| 161 |
results = [ |
| 162 |
result |
| 163 |
for result in results |
| 164 |
if result.group_version == kwargs["api_version"] |
| 165 |
] |
| 166 |
|
| 167 |
if len(results) > 1 and not all(isinstance(x, ResourceList) for x in results): |
| 168 |
results = [ |
| 169 |
result for result in results if not isinstance(result, ResourceList) |
| 170 |
] |
| 171 |
|
| 172 |
if ( |
| 173 |
len(results) > 1 |
| 174 |
and len(set((x.group_version, x.kind) for x in results)) == 1 |
| 175 |
): |
| 176 |
if len(set(len(x.verbs) for x in results)) != 1: |
| 177 |
results = [max(results, key=lambda x: len(x.verbs))] |
| 178 |
if len(results) == 1: |
| 179 |
return results[0] |
| 180 |
elif not results: |
| 181 |
raise ResourceNotFoundError("No matches found for {0}".format(kwargs)) |
| 182 |
else: |
| 183 |
raise ResourceNotUniqueError( |
| 184 |
"Multiple matches found for {0}: {1}".format(kwargs, results) |
| 185 |
) |
| 186 |
|
| 187 |
|
| 188 |
class LazyDiscoverer(Discoverer, kubernetes.dynamic.LazyDiscoverer): |
| 189 |
def __init__(self, client, cache_file): |
| 190 |
Discoverer.__init__(self, client, cache_file) |
| 191 |
self.__update_cache = False |
| 192 |
|
| 193 |
@property |
| 194 |
def update_cache(self): |
| 195 |
self.__update_cache |
| 196 |
|
| 197 |
|
| 198 |
class CacheDecoder(json.JSONDecoder): |
| 199 |
def __init__(self, client, *args, **kwargs): |
| 200 |
self.client = client |
| 201 |
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) |
| 202 |
|
| 203 |
def object_hook(self, obj): |
| 204 |
if "_type" not in obj: |
| 205 |
return obj |
| 206 |
_type = obj.pop("_type") |
| 207 |
if _type == "Resource": |
| 208 |
return kubernetes.dynamic.Resource(client=self.client, **obj) |
| 209 |
elif _type == "ResourceList": |
| 210 |
return ResourceList(self.client, **obj) |
| 211 |
elif _type == "ResourceGroup": |
| 212 |
return kubernetes.dynamic.discovery.ResourceGroup( |
| 213 |
obj["preferred"], resources=self.object_hook(obj["resources"]) |
| 214 |
) |
| 215 |
return obj |