1#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18from __future__ import annotations
19
20import logging
21from typing import TYPE_CHECKING
22
23from airflow.utils.module_loading import qualname
24
25# lazy loading for performance reasons
26serializers = [
27 "kubernetes.client.models.v1_resource_requirements.V1ResourceRequirements",
28 "kubernetes.client.models.v1_pod.V1Pod",
29]
30
31if TYPE_CHECKING:
32 from airflow.serialization.serde import U
33
34__version__ = 1
35
36deserializers: list[type[object]] = []
37log = logging.getLogger(__name__)
38
39
40def serialize(o: object) -> tuple[U, str, int, bool]:
41 from kubernetes.client import models as k8s
42
43 if not k8s:
44 return "", "", 0, False
45
46 if isinstance(o, (k8s.V1Pod, k8s.V1ResourceRequirements)):
47 try:
48 from airflow.providers.cncf.kubernetes.pod_generator import PodGenerator
49 except ImportError:
50 from airflow.kubernetes.pre_7_4_0_compatibility.pod_generator import ( # type: ignore[assignment]
51 PodGenerator,
52 )
53
54 # We're running this in an except block, so we don't want it to fail
55 # under any circumstances, e.g. accessing a non-existing attribute.
56 def safe_get_name(pod):
57 try:
58 return pod.metadata.name
59 except Exception:
60 return None
61
62 try:
63 return PodGenerator.serialize_pod(o), qualname(o), __version__, True
64 except Exception:
65 log.warning("Serialization failed for pod %s", safe_get_name(o))
66 log.debug("traceback for serialization error", exc_info=True)
67 return "", "", 0, False
68
69 return "", "", 0, False