|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from dataclasses import dataclass |
| 5 | +from typing import Any, Protocol |
| 6 | + |
| 7 | +import kubernetes |
| 8 | +from jobs.job import Job |
| 9 | + |
| 10 | +from jobs_server.models import SubmissionContext |
| 11 | +from jobs_server.utils.helpers import traverse |
| 12 | + |
| 13 | + |
| 14 | +def sanitize_rfc1123_domain_name(s: str) -> str: |
| 15 | + """Sanitize a string to be compliant with RFC 1123 domain name |
| 16 | +
|
| 17 | + Note: Any invalid characters are replaced with dashes.""" |
| 18 | + |
| 19 | + # TODO: This is obviously wildly incomplete |
| 20 | + return s.replace("_", "-") |
| 21 | + |
| 22 | + |
| 23 | +def k8s_annotations( |
| 24 | + job: Job, context: SubmissionContext | None = None |
| 25 | +) -> dict[str, str]: |
| 26 | + """Determine the Kubernetes annotations for a Job""" |
| 27 | + # Store as annotations since labels have restrictive value formats |
| 28 | + options = job.options.labels if job.options else {} |
| 29 | + context = {"x-jobby.io/submission-context": json.dumps(context)} if context else {} |
| 30 | + return options | context |
| 31 | + |
| 32 | + |
| 33 | +@dataclass |
| 34 | +class GroupVersionKind: |
| 35 | + group: str |
| 36 | + version: str |
| 37 | + kind: str |
| 38 | + |
| 39 | + |
| 40 | +class KubernetesObject(Protocol): |
| 41 | + @property |
| 42 | + def api_version(self) -> str: ... |
| 43 | + |
| 44 | + @property |
| 45 | + def kind(self) -> str: ... |
| 46 | + |
| 47 | + |
| 48 | +def gvk(obj: KubernetesObject | dict[str, Any]) -> GroupVersionKind: |
| 49 | + kind = obj.kind if hasattr(obj, "kind") else obj["kind"] |
| 50 | + if "/" in ( |
| 51 | + api_version := obj.api_version |
| 52 | + if hasattr(obj, "api_version") |
| 53 | + else obj["apiVersion"] |
| 54 | + ): |
| 55 | + group, version = api_version.split("/") |
| 56 | + else: |
| 57 | + group, version = "", api_version |
| 58 | + |
| 59 | + return GroupVersionKind(group, version, kind) |
| 60 | + |
| 61 | + |
| 62 | +class KubernetesNamespaceMixin: |
| 63 | + """Determine the desired or current Kubernetes namespace.""" |
| 64 | + |
| 65 | + def __init__(self, **kwargs): |
| 66 | + kubernetes.config.load_config() |
| 67 | + self._namespace: str | None = kwargs.get("namespace") |
| 68 | + |
| 69 | + @property |
| 70 | + def namespace(self) -> str: |
| 71 | + _, active_context = kubernetes.config.list_kube_config_contexts() |
| 72 | + current_namespace = active_context["context"].get("namespace") |
| 73 | + return self._namespace or current_namespace |
| 74 | + |
| 75 | + |
| 76 | +def filter_conditions( |
| 77 | + obj: dict[str, Any], |
| 78 | + typ: str | None = None, |
| 79 | + reason: str | None = None, |
| 80 | + message: str | None = None, |
| 81 | +): |
| 82 | + """ |
| 83 | + Filters Kubernetes object conditions based on specified attributes. |
| 84 | +
|
| 85 | + This function filters the `status.conditions` field of a Kubernetes object |
| 86 | + by matching conditions against the provided `type`, `reason`, and `message` |
| 87 | + attributes. Only conditions that match all specified attributes are included |
| 88 | + in the result. |
| 89 | +
|
| 90 | + Parameters |
| 91 | + ---------- |
| 92 | + obj : dict[str, Any] |
| 93 | + The Kubernetes object, typically a dictionary representing a Kubernetes |
| 94 | + resource, containing a `status.conditions` field. |
| 95 | + typ : str, optional |
| 96 | + The type of condition to filter by. If `None`, this filter is not applied. |
| 97 | + reason : str, optional |
| 98 | + The reason attribute to filter by. If `None`, this filter is not applied. |
| 99 | + message : str, optional |
| 100 | + The message attribute to filter by. If `None`, this filter is not applied. |
| 101 | +
|
| 102 | + Returns |
| 103 | + ------- |
| 104 | + list[dict[str, Any]] |
| 105 | + A list of conditions that match the specified filters. Each condition |
| 106 | + is represented as a dictionary. |
| 107 | +
|
| 108 | + Notes |
| 109 | + ----- |
| 110 | + - The function assumes that the `status.conditions` field exists in the |
| 111 | + provided object and that it is a list of condition dictionaries. |
| 112 | + - If no conditions match the specified filters, an empty list is returned. |
| 113 | +
|
| 114 | + Examples |
| 115 | + -------- |
| 116 | + >>> obj = { |
| 117 | + ... "status": { |
| 118 | + ... "conditions": [ |
| 119 | + ... {"type": "Ready", "reason": "DeploymentCompleted", "message": "Deployment successful."}, |
| 120 | + ... {"type": "Failed", "reason": "DeploymentFailed", "message": "Deployment failed due to timeout."} |
| 121 | + ... ] |
| 122 | + ... } |
| 123 | + ... } |
| 124 | + >>> filter_conditions(obj, typ="Ready") |
| 125 | + [{'type': 'Ready', 'reason': 'DeploymentCompleted', 'message': 'Deployment successful.'}] |
| 126 | +
|
| 127 | + >>> filter_conditions(obj, reason="DeploymentFailed") |
| 128 | + [{'type': 'Failed', 'reason': 'DeploymentFailed', 'message': 'Deployment failed due to timeout.'}] |
| 129 | + """ |
| 130 | + |
| 131 | + def _match(cond): |
| 132 | + return all([ |
| 133 | + typ is None or cond["type"] == typ, |
| 134 | + reason is None or cond["reason"] == reason, |
| 135 | + message is None or cond["message"] == message, |
| 136 | + ]) |
| 137 | + |
| 138 | + return [cond for cond in traverse(obj, "status.conditions") if _match(cond)] |
0 commit comments