Skip to content

spark_on_k8s.diagnostics

See the reference overview for supported entry points and task guides. A module may also contain helpers outside the documented public API.

Diagnosis dataclass

Source code in spark_on_k8s/diagnostics.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@dataclass
class Diagnosis:
    namespace: str
    app_id: str
    driver_pod: str
    findings: list[DiagnosticFinding] = field(default_factory=list)
    inspected_pods: int = 0
    inspected_events: int = 0
    incomplete: bool = False
    schema_version: int = 1
    collected_at: str = field(default_factory=lambda: datetime.now(UTC).isoformat())

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

app_id instance-attribute

collected_at = field(default_factory=lambda: datetime.now(UTC).isoformat()) class-attribute instance-attribute

driver_pod instance-attribute

findings = field(default_factory=list) class-attribute instance-attribute

incomplete = False class-attribute instance-attribute

inspected_events = 0 class-attribute instance-attribute

inspected_pods = 0 class-attribute instance-attribute

namespace instance-attribute

schema_version = 1 class-attribute instance-attribute

__init__(namespace, app_id, driver_pod, findings=list(), inspected_pods=0, inspected_events=0, incomplete=False, schema_version=1, collected_at=(lambda: datetime.now(UTC).isoformat())())

to_dict()

Source code in spark_on_k8s/diagnostics.py
38
39
def to_dict(self) -> dict[str, Any]:
    return asdict(self)

DiagnosticFinding dataclass

Source code in spark_on_k8s/diagnostics.py
15
16
17
18
19
20
21
22
23
@dataclass(frozen=True)
class DiagnosticFinding:
    code: str
    severity: Literal["info", "warning", "error"]
    resource: str
    summary: str
    evidence: str
    remediation: str
    container: str | None = None

code instance-attribute

container = None class-attribute instance-attribute

evidence instance-attribute

remediation instance-attribute

resource instance-attribute

severity instance-attribute

summary instance-attribute

__init__(code, severity, resource, summary, evidence, remediation, container=None)

classify_pod(pod, events)

Classify observed pod/container states and events; never inspect logs or secrets.

Source code in spark_on_k8s/diagnostics.py
 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
def classify_pod(pod: dict, events: list[dict]) -> list[DiagnosticFinding]:
    """Classify observed pod/container states and events; never inspect logs or secrets."""
    name = pod["metadata"]["name"]
    status = pod.get("status") or {}
    findings: dict[tuple[str, str | None], DiagnosticFinding] = {}

    def add(code, summary, evidence, remediation, container=None, severity="error"):
        findings.setdefault(
            (code, container),
            DiagnosticFinding(
                code,
                severity,
                name,
                summary,
                _evidence(evidence),
                remediation,
                container,
            ),
        )

    # The kubelet reports an elapsed activeDeadlineSeconds (max_runtime) on the pod, not on a container.
    if status.get("reason") == "DeadlineExceeded":
        add(
            "deadline_exceeded",
            "Pod exceeded its maximum runtime and was stopped by Kubernetes",
            status.get("message") or "DeadlineExceeded",
            "The pod's activeDeadlineSeconds (max_runtime) elapsed. Check driver logs for stalled or "
            "slow work before raising max_runtime; outputs written before the stop may be partial.",
        )
    waiting_containers = []
    for container in (status.get("init_container_statuses") or []) + (status.get("container_statuses") or []):
        container_name = container.get("name")
        current = container.get("state") or {}
        waiting = current.get("waiting") or {}
        reason = waiting.get("reason")
        if reason and reason != "ContainerCreating":
            waiting_containers.append(
                f"container {container_name} waiting: {reason}"
                + (f" ({waiting['message']})" if waiting.get("message") else "")
            )
        if reason in {"ImagePullBackOff", "ErrImagePull", "InvalidImageName"}:
            add(
                "image_pull_failed",
                "Container image is unavailable",
                waiting.get("message") or reason,
                "Check the image reference, registry reachability and imagePullSecrets in this namespace.",
                container_name,
            )
        if reason == "CrashLoopBackOff":
            add(
                "crash_loop",
                "Container repeatedly exits",
                waiting.get("message") or reason,
                "Inspect current and previous container logs and its exit code before changing "
                "restart or resource settings.",
                container_name,
            )
        for previous, state in ((False, current), (True, container.get("last_state") or {})):
            terminated = state.get("terminated") or {}
            if terminated.get("reason") == "OOMKilled":
                add(
                    "oom_killed",
                    "A container attempt was killed for exceeding memory",
                    f"{'Previous' if previous else 'Current'} attempt: OOMKilled; "
                    f"exit code {terminated.get('exit_code')}",
                    "Compare memory usage with the container limit and Spark memory/overhead "
                    "settings; investigate before increasing limits.",
                    container_name,
                    "warning" if previous else "error",
                )
            elif not previous and terminated.get("exit_code") not in (None, 0):
                add(
                    "container_failed",
                    "Container exited unsuccessfully",
                    f"{terminated.get('reason') or 'Terminated'}; exit code {terminated['exit_code']}",
                    "Inspect this container's logs for the application error. The exit code alone "
                    "does not identify the cause.",
                    container_name,
                )
    messages = [(event.get("reason", ""), event.get("message", "")) for event in events]
    messages.extend(
        (condition.get("reason", ""), condition.get("message", ""))
        for condition in status.get("conditions") or []
        if condition.get("type") == "PodScheduled" and condition.get("status") == "False"
    )
    for reason, message in messages:
        message = message or ""
        lower = message.lower()
        if reason in {"FailedScheduling", "Unschedulable"}:
            add(
                "unschedulable",
                "Kubernetes could not schedule the pod",
                message or reason,
                "Review the scheduler's stated constraints, resource requests, node selectors and affinity.",
            )
            if "insufficient " in lower:
                add(
                    "insufficient_resources",
                    "Scheduler reports insufficient resources",
                    message,
                    "Compare requested resources with eligible node capacity; adjust requests or "
                    "add capacity.",
                )
            if "taint" in lower:
                add(
                    "taint_mismatch",
                    "Scheduler reports a taint constraint",
                    message,
                    "Check whether the workload belongs on these nodes before adding a matching toleration.",
                )
        if "persistentvolumeclaim" in lower and ("not found" in lower or "unbound" in lower):
            add(
                "pvc_missing",
                "A required persistent volume claim is unavailable",
                message,
                "Check the named PVC in this namespace, its binding state and storage class. Do "
                "not create an empty replacement for required data.",
            )
        if "forbidden" in lower or reason == "Forbidden":
            add(
                "permission_denied",
                "Kubernetes reported a denied operation",
                message or reason,
                "Identify the denied verb/resource and acting service account in the evidence; "
                "ask an administrator for a namespace-scoped permission.",
            )
        if reason in {"FailedToRetrieveImagePullSecret"} or "failed to pull image" in lower:
            add(
                "image_pull_failed",
                "Kubernetes could not access the container image",
                message or reason,
                "Check the image reference, registry reachability and imagePullSecrets in this namespace.",
            )
    if not findings and status.get("phase") in {"Pending", "Failed"}:
        add(
            "cause_unknown",
            f"Pod is {status['phase']} without a specific observed cause",
            # A waiting reason without a dedicated rule (CreateContainerConfigError for a missing
            # Secret, ErrImageNeverPull) is still the most useful evidence available.
            "; ".join(waiting_containers)
            or status.get("message")
            or status.get("reason")
            or f"Pod phase: {status['phase']}",
            "Inspect container logs and newer Kubernetes events. Absence of diagnostic evidence "
            "does not establish a cause.",
            severity="warning",
        )
    return list(findings.values())

collect_diagnosis(api, driver, *, namespace, pod_limit=20, event_limit=100, timeout=10)

Collect at most one executor page and one event page per inspected pod.

Source code in spark_on_k8s/diagnostics.py
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
def collect_diagnosis(api, driver, *, namespace: str, pod_limit=20, event_limit=100, timeout=10) -> Diagnosis:
    """Collect at most one executor page and one event page per inspected pod."""
    from kubernetes.client import ApiException
    from urllib3.exceptions import TimeoutError as HTTPTimeoutError

    deadline = _limits(pod_limit, event_limit, timeout)
    report = _report(driver, namespace)
    pods = [driver]
    try:
        response = api.list_namespaced_pod(
            **_executor_options(driver, report, pod_limit), **deadline.request_options()
        )
        pods.extend(_owned_executors(driver, response, report))
    except (ApiException, TimeoutError, HTTPTimeoutError) as error:
        _incomplete(
            report,
            driver.metadata.name,
            f"Executor listing failed ({getattr(error, 'status', 'timeout')}).",
            remediation=_read_remediation(error),
        )
    for pod in pods:
        response = None
        try:
            if not pod.metadata.uid:
                raise ValueError("Pod UID is unavailable")
            response = api.list_namespaced_event(
                **_event_options(pod, namespace, event_limit), **deadline.request_options()
            )
        except (ApiException, TimeoutError, HTTPTimeoutError, ValueError) as error:
            _incomplete(
                report,
                pod.metadata.name,
                f"Event listing failed ({getattr(error, 'status', 'unavailable')}).",
                remediation=_read_remediation(error),
            )
        _record(report, pod, response)
    return report

collect_diagnosis_async(api, driver, *, namespace, pod_limit=20, event_limit=100, timeout=10) async

Async transport for the same classifier and bounded collection policy.

Source code in spark_on_k8s/diagnostics.py
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
async def collect_diagnosis_async(
    api, driver, *, namespace: str, pod_limit=20, event_limit=100, timeout=10
) -> Diagnosis:
    """Async transport for the same classifier and bounded collection policy."""
    from kubernetes_asyncio.client import ApiException

    deadline = _limits(pod_limit, event_limit, timeout)
    report = _report(driver, namespace)
    pods = [driver]
    try:
        response = await api.list_namespaced_pod(
            **_executor_options(driver, report, pod_limit), **deadline.request_options()
        )
        pods.extend(_owned_executors(driver, response, report))
    except (ApiException, TimeoutError) as error:
        _incomplete(
            report,
            driver.metadata.name,
            f"Executor listing failed ({getattr(error, 'status', 'timeout')}).",
            remediation=_read_remediation(error),
        )
    for pod in pods:
        response = None
        try:
            if not pod.metadata.uid:
                raise ValueError("Pod UID is unavailable")
            response = await api.list_namespaced_event(
                **_event_options(pod, namespace, event_limit), **deadline.request_options()
            )
        except (ApiException, TimeoutError, ValueError) as error:
            _incomplete(
                report,
                pod.metadata.name,
                f"Event listing failed ({getattr(error, 'status', 'unavailable')}).",
                remediation=_read_remediation(error),
            )
        _record(report, pod, response)
    return report

validate_target(namespace, value, *, label=False)

Source code in spark_on_k8s/diagnostics.py
42
43
44
45
46
47
def validate_target(namespace: str, value: str, *, label: bool = False) -> None:
    if not isinstance(namespace, str) or len(namespace) > 63 or not _NAME.fullmatch(namespace):
        raise ValueError("Namespace must be a Kubernetes DNS label of at most 63 characters")
    pattern = _LABEL if label else _POD_NAME
    if not isinstance(value, str) or len(value) > (63 if label else 253) or not pattern.fullmatch(value):
        raise ValueError("Invalid Kubernetes application or pod identifier")