File: objects.py

package info (click to toggle)
python-pykube-ng 22.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 424 kB
  • sloc: python: 2,336; makefile: 44
file content (610 lines) | stat: -rw-r--r-- 19,446 bytes parent folder | download
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
import copy
import json
from inspect import getmro
from typing import Any
from typing import Optional
from typing import Type
from urllib.parse import urlencode

from requests import Response

from .exceptions import ObjectDoesNotExist
from .http import HTTPClient
from .mixins import ReplicatedMixin
from .mixins import ScalableMixin
from .query import Query
from .utils import join_url_path
from .utils import obj_merge


class ObjectManager:
    def __call__(self, api: HTTPClient, namespace: str = None):
        if namespace is None and NamespacedAPIObject in getmro(self.api_obj_class):
            namespace = api.config.namespace
        return Query(api, self.api_obj_class, namespace=namespace)

    def __get__(self, obj, api_obj_class: Type):
        assert obj is None, "cannot invoke objects on resource object."
        self.api_obj_class = api_obj_class
        return self


class APIObject:
    """
    Baseclass for all Kubernetes API objects
    """

    objects = ObjectManager()
    base = None

    def __init__(self, api: HTTPClient, obj: dict):
        self.api = api
        self.set_obj(obj)

    def set_obj(self, obj: dict):
        self.obj = obj
        self._original_obj = copy.deepcopy(obj)

    def __repr__(self):
        return f"<{self.kind} {self.name}>"

    def __str__(self):
        return self.name

    @property
    def name(self) -> str:
        """
        Name of the Kubernetes resource (metadata.name)

        Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation
        of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition.
        Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names
        """
        return self.obj["metadata"]["name"]

    @property
    def namespace(self) -> Optional[str]:
        return None

    @property
    def metadata(self):
        return self.obj["metadata"]

    @property
    def labels(self) -> dict:
        """
        Labels of the Kubernetes resource (metadata.labels)

        Map of string keys and values that can be used to organize and categorize (scope and select) objects.
        May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels
        """
        return self.obj["metadata"].setdefault("labels", {})

    @property
    def annotations(self) -> dict:
        """
        Annotations of the Kubernetes resource (metadata.annotations)

        Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata.
        They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations
        """
        return self.obj["metadata"].setdefault("annotations", {})

    def api_kwargs(self, **kwargs):
        kw = {}
        # Construct url for api request
        obj_list = kwargs.pop("obj_list", False)
        if obj_list:
            kw["url"] = self.endpoint
        else:
            subresource = kwargs.pop("subresource", None) or ""
            operation = kwargs.pop("operation", "")
            kw["url"] = join_url_path(self.endpoint, self.name, subresource, operation)

        params = kwargs.pop("params", None)
        if params is not None:
            query_string = urlencode(params)
            kw["url"] = "{}{}".format(
                kw["url"], f"?{query_string}" if query_string else ""
            )
        if self.base:
            kw["base"] = self.base
        kw["version"] = self.version
        if self.namespace is not None:
            kw["namespace"] = self.namespace
        kw.update(kwargs)
        return kw

    def exists(self, ensure=False):
        r = self.api.get(**self.api_kwargs())
        if r.status_code not in {200, 404}:
            self.api.raise_for_status(r)
        if not r.ok:
            if ensure:
                raise ObjectDoesNotExist(f"{self.name} does not exist.")
            else:
                return False
        return True

    def create(self):
        r = self.api.post(**self.api_kwargs(data=json.dumps(self.obj), obj_list=True))
        self.api.raise_for_status(r)
        self.set_obj(r.json())

    def reload(self):
        r = self.api.get(**self.api_kwargs())
        self.api.raise_for_status(r)
        self.set_obj(r.json())

    def watch(self):
        return (
            self.__class__.objects(self.api, namespace=self.namespace)
            .filter(field_selector={"metadata.name": self.name})
            .watch()
        )

    def patch(self, strategic_merge_patch, *, subresource=None):
        """
        Patch the Kubernetes resource by calling the API with a "strategic merge" patch.
        """
        r = self.api.patch(
            **self.api_kwargs(
                subresource=subresource,
                headers={"Content-Type": "application/merge-patch+json"},
                data=json.dumps(strategic_merge_patch),
            )
        )
        self.api.raise_for_status(r)
        self.set_obj(r.json())

    def update(self, is_strategic=True, *, subresource=None):
        """
        Update the Kubernetes resource by calling the API (patch)
        """
        self.obj = obj_merge(self.obj, self._original_obj, is_strategic)
        self.patch(self.obj, subresource=subresource)

    def delete(self, propagation_policy: str = None):
        """
        Delete the Kubernetes resource by calling the API.

        The parameter propagation_policy defines whether to cascade the delete. It can be "Foreground", "Background" or "Orphan".
        See https://kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/#setting-the-cascading-deletion-policy
        """
        if propagation_policy:
            options = {"propagationPolicy": propagation_policy}
        else:
            options = {}
        r = self.api.delete(**self.api_kwargs(data=json.dumps(options)))
        if r.status_code != 404:
            self.api.raise_for_status(r)


class NamespacedAPIObject(APIObject):
    @property
    def namespace(self) -> str:
        """
        Namespace scope of the Kubernetes resource (metadata.namespace)

        Namespace defines the space within each name must be unique.
        Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces
        """
        if self.obj["metadata"].get("namespace"):
            return self.obj["metadata"]["namespace"]
        else:
            return self.api.config.namespace


def object_factory(api, api_version, kind) -> Type[APIObject]:
    """
    Dynamically builds a Python class for the given Kubernetes object in an API.

    For example:

        api = pykube.HTTPClient(...)
        NetworkPolicy = pykube.object_factory(api, "networking.k8s.io/v1", "NetworkPolicy")

    This enables construction of any Kubernetes object kind without explicit support
    from pykube.

    Currently, the HTTPClient passed to this function will not be bound to the returned type.
    It is planned to fix this, but in the mean time pass it as you would normally.
    """
    resource_list = api.resource_list(api_version)
    try:
        resource = next(
            resource
            for resource in resource_list["resources"]
            if resource["kind"] == kind
        )
    except StopIteration:
        raise ValueError("unknown resource kind {!r}".format(kind)) from None
    base = NamespacedAPIObject if resource["namespaced"] else APIObject
    return type(
        kind,
        (base,),
        {"version": api_version, "endpoint": resource["name"], "kind": kind},
    )


class ConfigMap(NamespacedAPIObject):
    version = "v1"
    endpoint = "configmaps"
    kind = "ConfigMap"


class CronJob(NamespacedAPIObject):
    version = "batch/v1beta1"
    endpoint = "cronjobs"
    kind = "CronJob"


class DaemonSet(NamespacedAPIObject):
    version = "apps/v1"
    endpoint = "daemonsets"
    kind = "DaemonSet"


class Deployment(NamespacedAPIObject, ReplicatedMixin, ScalableMixin):
    version = "apps/v1"
    endpoint = "deployments"
    kind = "Deployment"

    @property
    def ready(self):
        return (
            self.obj["status"]["observedGeneration"]
            >= self.obj["metadata"]["generation"]
            and self.obj["status"]["updatedReplicas"] == self.replicas
        )

    def rollout_undo(self, target_revision=None):
        """Produces same action as kubectl rollout undo deployment command.
        Input variable is revision to rollback to (in kubectl, --to-revision)
        """
        if target_revision is None:
            revision = {}
        else:
            revision = {"revision": target_revision}

        params = {
            "kind": "DeploymentRollback",
            "apiVersion": self.version,
            "name": self.name,
            "rollbackTo": revision,
        }

        kwargs = {
            "version": self.version,
            "namespace": self.namespace,
            "operation": "rollback",
        }
        r = self.api.post(**self.api_kwargs(data=json.dumps(params), **kwargs))
        r.raise_for_status()
        return r.text


class Endpoint(NamespacedAPIObject):
    version = "v1"
    endpoint = "endpoints"
    kind = "Endpoint"


class Event(NamespacedAPIObject):
    version = "v1"
    endpoint = "events"
    kind = "Event"


class LimitRange(NamespacedAPIObject):
    version = "v1"
    endpoint = "limitranges"
    kind = "LimitRange"


class ResourceQuota(NamespacedAPIObject):
    version = "v1"
    endpoint = "resourcequotas"
    kind = "ResourceQuota"


class ServiceAccount(NamespacedAPIObject):
    version = "v1"
    endpoint = "serviceaccounts"
    kind = "ServiceAccount"


class Ingress(NamespacedAPIObject):
    version = "networking.k8s.io/v1"
    endpoint = "ingresses"
    kind = "Ingress"


class Job(NamespacedAPIObject, ScalableMixin):
    version = "batch/v1"
    endpoint = "jobs"
    kind = "Job"
    scalable_attr = "parallelism"

    @property
    def parallelism(self):
        return self.obj["spec"]["parallelism"]

    @parallelism.setter
    def parallelism(self, value):
        self.obj["spec"]["parallelism"] = value


class Namespace(APIObject):
    version = "v1"
    endpoint = "namespaces"
    kind = "Namespace"


class Node(APIObject):
    version = "v1"
    endpoint = "nodes"
    kind = "Node"

    @property
    def unschedulable(self):
        if "unschedulable" in self.obj["spec"]:
            return self.obj["spec"]["unschedulable"]
        return False

    @unschedulable.setter
    def unschedulable(self, value):
        self.obj["spec"]["unschedulable"] = value
        self.update()

    def cordon(self):
        self.unschedulable = True

    def uncordon(self):
        self.unschedulable = False


class Pod(NamespacedAPIObject):
    version = "v1"
    endpoint = "pods"
    kind = "Pod"

    @property
    def ready(self):
        cs = self.obj["status"].get("conditions", [])
        condition = next((c for c in cs if c["type"] == "Ready"), None)
        return condition is not None and condition["status"] == "True"

    def logs(
        self,
        container=None,
        pretty=None,
        previous=False,
        since_seconds=None,
        since_time=None,
        timestamps=False,
        tail_lines=None,
        limit_bytes=None,
    ):
        """
        Produces the same result as calling kubectl logs pod/<pod-name>.
        Check parameters meaning at
        http://kubernetes.io/docs/api-reference/v1/operations/,
        part 'read log of the specified Pod'. The result is plain text.
        """
        log_call = "log"
        params = {}
        if container is not None:
            params["container"] = container
        if pretty is not None:
            params["pretty"] = pretty
        if previous:
            params["previous"] = "true"
        if since_seconds is not None and since_time is None:
            params["sinceSeconds"] = int(since_seconds)
        elif since_time is not None and since_seconds is None:
            params["sinceTime"] = since_time
        if timestamps:
            params["timestamps"] = "true"
        if tail_lines is not None:
            params["tailLines"] = int(tail_lines)
        if limit_bytes is not None:
            params["limitBytes"] = int(limit_bytes)

        query_string = urlencode(params)
        log_call += f"?{query_string}" if query_string else ""
        kwargs = {
            "version": self.version,
            "namespace": self.namespace,
            "operation": log_call,
        }
        r = self.api.get(**self.api_kwargs(**kwargs))
        r.raise_for_status()
        return r.text


class ReplicationController(NamespacedAPIObject, ReplicatedMixin, ScalableMixin):
    version = "v1"
    endpoint = "replicationcontrollers"
    kind = "ReplicationController"

    @property
    def ready(self):
        return (
            self.obj["status"]["observedGeneration"]
            >= self.obj["metadata"]["generation"]
            and self.obj["status"]["readyReplicas"] == self.replicas
        )


class ReplicaSet(NamespacedAPIObject, ReplicatedMixin, ScalableMixin):
    version = "apps/v1"
    endpoint = "replicasets"
    kind = "ReplicaSet"


class Secret(NamespacedAPIObject):
    version = "v1"
    endpoint = "secrets"
    kind = "Secret"


class Service(NamespacedAPIObject):
    version = "v1"
    endpoint = "services"
    kind = "Service"

    def proxy_http_request(
        self, method: str, path: str, port: Optional[int] = None, **kwargs: Any
    ) -> Response:
        """Issue a HTTP request with specific HTTP method to proxy of a Service.
        Args:
            :param method: The http request method e.g. 'GET', 'POST' etc.
            :param path: The URI path for the request.
            :param port: This value can be used to override the
            default (first defined) port used to connect to the Service.
            :param kwargs: Keyword arguments for the proxy_http_get function.
            They are the same as for requests.models.Request object.
        Returns:
            The requests.Response object.
        """
        if port is None:
            port = self.obj["spec"]["ports"][0]["port"]
        kwargs["url"] = f"services/{self.name}:{port}/proxy/{path}"
        kwargs["namespace"] = self.namespace
        kwargs["version"] = self.version
        return self.api.request(method, **kwargs)

    def proxy_http_get(
        self, path: str, port: Optional[int] = None, **kwargs
    ) -> Response:
        """Issue a HTTP GET request to proxy of a Service.
        Args:
            :param path: The URI path for the request.
            :param port: This value can be used to override the
            default (first defined) port used to connect to the Service.
            :param kwargs: Keyword arguments for the proxy_http_get function.
            They are the same as for requests.models.Request object
            plus the additional 'port' kwarg, which can be used to override the
            default (first defined) port used to connect to the Service.
        Returns:
            The requests.Response object.
        """
        return self.proxy_http_request("GET", path, port, **kwargs)

    def proxy_http_post(
        self, path: str, port: Optional[int] = None, **kwargs
    ) -> Response:
        """Issue a HTTP POST request to proxy of a Service.
        Args:
            :param path: The URI path for the request.
            :param port: This value can be used to override the
            default (first defined) port used to connect to the Service.
            :param kwargs: Keyword arguments for the proxy_http_get function.
            They are the same as for requests.models.Request object
            plus the additional 'port' kwarg, which can be used to override the
            default (first defined) port used to connect to the Service.
        Returns:
            The requests.Response object.
        """
        return self.proxy_http_request("POST", path, port, **kwargs)

    def proxy_http_put(
        self, path: str, port: Optional[int] = None, **kwargs
    ) -> Response:
        """Issue a HTTP PUT request to proxy of a Service.
        Args:
            :param path: The URI path for the request.
            :param port: This value can be used to override the
            default (first defined) port used to connect to the Service.
            :param kwargs: Keyword arguments for the proxy_http_get function.
            They are the same as for requests.models.Request object
            plus the additional 'port' kwarg, which can be used to override the
            default (first defined) port used to connect to the Service.
        Returns:
            The requests.Response object.
        """
        return self.proxy_http_request("PUT", path, port, **kwargs)

    def proxy_http_delete(
        self, path: str, port: Optional[int] = None, **kwargs
    ) -> Response:
        """Issue a HTTP DELETE request to proxy of a Service.
        Args:
            :param path: The URI path for the request.
            :param port: This value can be used to override the
            default (first defined) port used to connect to the Service.
            :param kwargs: Keyword arguments for the proxy_http_get function.
            They are the same as for requests.models.Request object
            plus the additional 'port' kwarg, which can be used to override the
            default (first defined) port used to connect to the Service.
        Returns:
            The requests.Response object.
        """
        return self.proxy_http_request("DELETE", path, port, **kwargs)


class PersistentVolume(APIObject):
    version = "v1"
    endpoint = "persistentvolumes"
    kind = "PersistentVolume"


class PersistentVolumeClaim(NamespacedAPIObject):
    version = "v1"
    endpoint = "persistentvolumeclaims"
    kind = "PersistentVolumeClaim"


class HorizontalPodAutoscaler(NamespacedAPIObject):
    version = "autoscaling/v1"
    endpoint = "horizontalpodautoscalers"
    kind = "HorizontalPodAutoscaler"


class StatefulSet(NamespacedAPIObject, ReplicatedMixin, ScalableMixin):
    version = "apps/v1"
    endpoint = "statefulsets"
    kind = "StatefulSet"


class Role(NamespacedAPIObject):
    version = "rbac.authorization.k8s.io/v1"
    endpoint = "roles"
    kind = "Role"


class RoleBinding(NamespacedAPIObject):
    version = "rbac.authorization.k8s.io/v1"
    endpoint = "rolebindings"
    kind = "RoleBinding"


class ClusterRole(APIObject):
    version = "rbac.authorization.k8s.io/v1"
    endpoint = "clusterroles"
    kind = "ClusterRole"


class ClusterRoleBinding(APIObject):
    version = "rbac.authorization.k8s.io/v1"
    endpoint = "clusterrolebindings"
    kind = "ClusterRoleBinding"


class PodSecurityPolicy(APIObject):
    version = "policy/v1beta1"
    endpoint = "podsecuritypolicies"
    kind = "PodSecurityPolicy"


class PodDisruptionBudget(NamespacedAPIObject):
    version = "policy/v1beta1"
    endpoint = "poddisruptionbudgets"
    kind = "PodDisruptionBudget"


class CustomResourceDefinition(APIObject):
    version = "apiextensions.k8s.io/v1"
    endpoint = "customresourcedefinitions"
    kind = "CustomResourceDefinition"