forked from apache/airflow
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathserialized_objects.py
More file actions
2320 lines (1976 loc) · 95.7 KB
/
Copy pathserialized_objects.py
File metadata and controls
2320 lines (1976 loc) · 95.7 KB
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Serialized Dag and BaseOperator."""
# TODO: update test_recursive_serialize_calls_must_forward_kwargs and re-enable RET505
# ruff: noqa: RET505
from __future__ import annotations
import collections.abc
import contextlib
import datetime
import enum
import itertools
import logging
import math
import sys
import weakref
from collections.abc import Collection, Iterable, Mapping
from functools import cache, cached_property, lru_cache
from inspect import signature
from textwrap import dedent
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, TypeVar, cast, overload
import attrs
import lazy_object_proxy
import pydantic
from dateutil import relativedelta
from pendulum.tz.timezone import FixedTimezone, Timezone
from airflow._shared.module_loading import import_string, qualname
from airflow._shared.timezones.timezone import from_timestamp, parse_timezone, utcnow
from airflow.callbacks.callback_requests import DagCallbackRequest, TaskCallbackRequest
from airflow.exceptions import AirflowException, DeserializationError, SerializationError
from airflow.models.connection import Connection
from airflow.models.expandinput import SchedulerMappedArgument, create_expand_input
from airflow.models.taskinstancekey import TaskInstanceKey
from airflow.sdk import DAG, Asset, AssetAlias, BaseOperator, XComArg
from airflow.sdk.bases.operator import OPERATOR_DEFAULTS # TODO: Copy this into the scheduler?
from airflow.sdk.definitions._internal.expandinput import MappedArgument
from airflow.sdk.definitions.asset import (
AssetAliasEvent,
AssetAliasUniqueKey,
AssetUniqueKey,
BaseAsset,
)
from airflow.sdk.definitions.deadline import DeadlineAlert
from airflow.sdk.definitions.mappedoperator import MappedOperator
from airflow.sdk.definitions.operator_resources import Resources
from airflow.sdk.definitions.param import Param, ParamsDict
from airflow.sdk.definitions.taskgroup import MappedTaskGroup, TaskGroup
from airflow.sdk.definitions.xcom_arg import serialize_xcom_arg
from airflow.sdk.execution_time.context import OutletEventAccessor, OutletEventAccessors
from airflow.serialization.dag_dependency import DagDependency
from airflow.serialization.decoders import (
decode_asset_like,
decode_deadline_alert,
decode_relativedelta,
decode_timetable,
)
from airflow.serialization.definitions.assets import (
SerializedAsset,
SerializedAssetAlias,
SerializedAssetBase,
SerializedAssetUniqueKey,
)
from airflow.serialization.definitions.baseoperator import SerializedBaseOperator
from airflow.serialization.definitions.dag import SerializedDAG
from airflow.serialization.definitions.deadline import SerializedDeadlineAlert
from airflow.serialization.definitions.node import DAGNode
from airflow.serialization.definitions.operatorlink import XComOperatorLink
from airflow.serialization.definitions.param import SerializedParam, SerializedParamsDict
from airflow.serialization.definitions.taskgroup import SerializedMappedTaskGroup, SerializedTaskGroup
from airflow.serialization.definitions.xcom_arg import SchedulerXComArg, deserialize_xcom_arg
from airflow.serialization.encoders import (
coerce_to_core_timetable,
encode_asset_like,
encode_deadline_alert,
encode_expand_input,
encode_relativedelta,
encode_timetable,
encode_timezone,
ensure_serialized_asset,
)
from airflow.serialization.enums import DagAttributeTypes as DAT, Encoding
from airflow.serialization.helpers import TimetableNotRegistered, serialize_template_field
from airflow.serialization.json_schema import load_dag_schema
from airflow.settings import DAGS_FOLDER, json
from airflow.task.priority_strategy import (
PriorityWeightStrategy,
get_airflow_priority_weight_strategies,
get_weight_rule_from_priority_weight_strategy,
validate_and_load_priority_weight_strategy,
)
from airflow.timetables.base import DagRunInfo, Timetable
from airflow.triggers.base import BaseTrigger, StartTriggerArgs
from airflow.utils.code_utils import get_python_source
from airflow.utils.db import LazySelectSequence
if TYPE_CHECKING:
from inspect import Parameter
from kubernetes.client import models as k8s # noqa: TC004
from kubernetes.client.api_client import ApiClient # noqa: TC004
from airflow.models.expandinput import SchedulerExpandInput
from airflow.sdk import BaseOperatorLink
from airflow.sdk.definitions._internal.node import DAGNode as SDKDAGNode
from airflow.sdk.types import Operator as SdkOperator
from airflow.serialization.definitions.mappedoperator import (
Operator as SerializedOperator,
SerializedMappedOperator,
)
from airflow.serialization.json_schema import Validator
from airflow.timetables.base import DagRunInfo, Timetable
log = logging.getLogger(__name__)
_CALLBACK_TYPES = ("execute", "failure", "success", "retry", "skipped")
_OPERATOR_CALLBACK_FIELDS = frozenset(f"on_{x}_callback" for x in _CALLBACK_TYPES)
_HAS_CALLBACK_FIELDS = frozenset(f"has_on_{x}_callback" for x in _CALLBACK_TYPES)
def _get_registered_priority_weight_strategy(
importable_string: str,
) -> type[PriorityWeightStrategy] | None:
from airflow import plugins_manager
with contextlib.suppress(KeyError):
return get_airflow_priority_weight_strategies()[importable_string]
return plugins_manager.get_priority_weight_strategy_plugins().get(importable_string)
class _PriorityWeightStrategyNotRegistered(AirflowException):
def __init__(self, type_string: str) -> None:
self.type_string = type_string
def __str__(self) -> str:
return (
f"Priority weight strategy class {self.type_string!r} is not registered or "
"you have a top level database access that disrupted the session. "
"Please check the airflow best practices documentation."
)
def _encode_outlet_event_accessor(var: OutletEventAccessor) -> dict[str, Any]:
key = var.key
return {
"key": BaseSerialization.serialize(key),
"extra": var.extra,
"asset_alias_events": [attrs.asdict(cast("attrs.AttrsInstance", e)) for e in var.asset_alias_events],
}
def _decode_outlet_event_accessor(var: dict[str, Any]) -> OutletEventAccessor:
asset_alias_events = var.get("asset_alias_events", [])
outlet_event_accessor = OutletEventAccessor(
key=BaseSerialization.deserialize(var["key"]),
extra=var["extra"],
asset_alias_events=[
AssetAliasEvent(
source_alias_name=e["source_alias_name"],
dest_asset_key=AssetUniqueKey(
name=e["dest_asset_key"]["name"], uri=e["dest_asset_key"]["uri"]
),
# fallback for backward compatibility
dest_asset_extra=e.get("dest_asset_extra", {}),
extra=e["extra"],
)
for e in asset_alias_events
],
)
return outlet_event_accessor
def _encode_outlet_event_accessors(var: OutletEventAccessors) -> dict[str, Any]:
return {
"__type": DAT.ASSET_EVENT_ACCESSORS,
"_dict": [
{"key": BaseSerialization.serialize(k), "value": _encode_outlet_event_accessor(v)}
for k, v in var._dict.items()
],
}
def _decode_outlet_event_accessors(var: dict[str, Any]) -> OutletEventAccessors:
d = OutletEventAccessors()
d._dict = {
BaseSerialization.deserialize(row["key"]): _decode_outlet_event_accessor(row["value"])
for row in var["_dict"]
}
return d
def _encode_priority_weight_strategy(var: PriorityWeightStrategy | str) -> str:
"""
Encode a priority weight strategy instance.
In this version, we only store the importable string, so the class should not wait
for any parameters to be passed to it. If you need to store the parameters, you
should store them in the class itself.
"""
priority_weight_strategy_class = type(validate_and_load_priority_weight_strategy(var))
with contextlib.suppress(KeyError):
return get_weight_rule_from_priority_weight_strategy(priority_weight_strategy_class)
importable_string = qualname(priority_weight_strategy_class)
if _get_registered_priority_weight_strategy(importable_string) is None:
raise _PriorityWeightStrategyNotRegistered(importable_string)
return importable_string
def _decode_priority_weight_strategy(var: str) -> PriorityWeightStrategy:
"""
Decode a previously serialized priority weight strategy.
In this version, we only store the importable string, so we just need to get the class
from the dictionary of registered classes and instantiate it with no parameters.
"""
priority_weight_strategy_class = _get_registered_priority_weight_strategy(var)
if priority_weight_strategy_class is None:
raise _PriorityWeightStrategyNotRegistered(var)
return priority_weight_strategy_class()
def _encode_start_trigger_args(var: StartTriggerArgs) -> dict[str, Any]:
"""Encode a StartTriggerArgs."""
def serialize_kwargs(key: str) -> Any:
if (val := getattr(var, key)) is None:
return None
return BaseSerialization.serialize(val)
return {
"__type": "START_TRIGGER_ARGS",
"trigger_cls": var.trigger_cls,
"trigger_kwargs": serialize_kwargs("trigger_kwargs"),
"next_method": var.next_method,
"next_kwargs": serialize_kwargs("next_kwargs"),
"timeout": var.timeout.total_seconds() if var.timeout else None,
}
def _decode_start_trigger_args(var: dict[str, Any]) -> StartTriggerArgs:
"""Decode a StartTriggerArgs."""
return StartTriggerArgs(
trigger_cls=var["trigger_cls"],
trigger_kwargs=var["trigger_kwargs"],
next_method=var["next_method"],
next_kwargs=var["next_kwargs"],
timeout=datetime.timedelta(seconds=var["timeout"]) if var["timeout"] else None,
)
class _XComRef(NamedTuple):
"""
Store info needed to create XComArg.
We can't turn it in to a XComArg until we've loaded _all_ the tasks, so when
deserializing an operator, we need to create something in its place, and
post-process it in ``deserialize_dag``.
"""
data: dict
def deref(self, dag: SerializedDAG) -> SchedulerXComArg:
return deserialize_xcom_arg(self.data, dag)
# These two should be kept in sync. Note that these are intentionally not using
# the type declarations in expandinput.py so we always remember to update
# serialization logic when adding new ExpandInput variants. If you add things to
# the unions, be sure to update _ExpandInputRef to match.
# Mapping[str, Any], For .expand(**kwargs).
# XComArg # For expand_kwargs(arg).
_ExpandInputOriginalValue = Mapping[str, Any] | XComArg | Collection[XComArg | Mapping[str, Any]]
# Mapping[str, Any], For .expand(**kwargs).
# _XComRef For expand_kwargs(arg).
_ExpandInputSerializedValue = Mapping[str, Any] | _XComRef | Collection[_XComRef | Mapping[str, Any]]
class _ExpandInputRef(NamedTuple):
"""
Store info needed to create a mapped operator's expand input.
This references a ``ExpandInput`` type, but replaces ``XComArg`` objects
with ``_XComRef`` (see documentation on the latter type for reasoning).
"""
key: str
value: _ExpandInputSerializedValue
@classmethod
def validate_expand_input_value(cls, value: _ExpandInputOriginalValue) -> None:
"""
Validate we've covered all ``ExpandInput.value`` types.
This function does not actually do anything, but is called during
serialization so Mypy will *statically* check we have handled all
possible ExpandInput cases.
"""
def deref(self, dag: SerializedDAG) -> SchedulerExpandInput:
"""
De-reference into a concrete ExpandInput object.
If you add more cases here, be sure to update _ExpandInputOriginalValue
and _ExpandInputSerializedValue to match the logic.
"""
if isinstance(self.value, _XComRef):
value: Any = self.value.deref(dag)
elif isinstance(self.value, collections.abc.Mapping):
value = {k: v.deref(dag) if isinstance(v, _XComRef) else v for k, v in self.value.items()}
else:
value = [v.deref(dag) if isinstance(v, _XComRef) else v for v in self.value]
return create_expand_input(self.key, value)
class BaseSerialization:
"""BaseSerialization provides utils for serialization."""
# JSON primitive types.
_primitive_types = (int, bool, float, str)
# Time types.
# datetime.date and datetime.time are converted to strings.
_datetime_types = (datetime.datetime,)
# Object types that are always excluded in serialization.
_excluded_types = (logging.Logger, Connection, type, property)
_json_schema: ClassVar[Validator | None] = None
# Should the extra operator link be loaded via plugins when
# de-serializing the DAG? This flag is set to False in Scheduler so that Extra Operator links
# are not loaded to not run User code in Scheduler.
_load_operator_extra_links = True
_CONSTRUCTOR_PARAMS: dict[str, Parameter] = {}
SERIALIZER_VERSION = 3
@classmethod
def to_json(cls, var: Any) -> str:
"""Stringify DAGs and operators contained by var and returns a JSON string of var."""
return json.dumps(cls.to_dict(var), ensure_ascii=True)
@classmethod
def to_dict(cls, var: Any) -> dict:
"""Stringify DAGs and operators contained by var and returns a dict of var."""
# Don't call on this class directly - only SerializedDAG or
# SerializedBaseOperator should be used as the "entrypoint"
raise NotImplementedError()
@classmethod
def from_json(cls, serialized_obj: str) -> BaseSerialization | dict | list | set | tuple:
"""Deserialize json_str and reconstructs all DAGs and operators it contains."""
return cls.from_dict(json.loads(serialized_obj))
@classmethod
def from_dict(cls, serialized_obj: dict[Encoding, Any]) -> Any:
"""Deserialize a dict of type decorators and reconstructs all DAGs and operators it contains."""
return cls.deserialize(serialized_obj)
@classmethod
def validate_schema(cls, serialized_obj: str | dict) -> None:
"""Validate serialized_obj satisfies JSON schema."""
if cls._json_schema is None:
raise AirflowException(f"JSON schema of {cls.__name__:s} is not set.")
if isinstance(serialized_obj, dict):
cls._json_schema.validate(serialized_obj)
elif isinstance(serialized_obj, str):
cls._json_schema.validate(json.loads(serialized_obj))
else:
raise TypeError("Invalid type: Only dict and str are supported.")
@staticmethod
def _encode(x: Any, type_: Any) -> dict[Encoding, Any]:
"""Encode data by a JSON dict."""
return {Encoding.VAR: x, Encoding.TYPE: type_}
@classmethod
def _is_primitive(cls, var: Any) -> bool:
"""Primitive types."""
return var is None or isinstance(var, cls._primitive_types)
@classmethod
def _is_excluded(cls, var: Any, attrname: str, instance: Any) -> bool:
"""Check if type is excluded from serialization."""
if var is None:
if not cls._is_constructor_param(attrname, instance):
# Any instance attribute, that is not a constructor argument, we exclude None as the default
return True
return cls._value_is_hardcoded_default(attrname, var, instance)
return isinstance(var, cls._excluded_types) or cls._value_is_hardcoded_default(
attrname, var, instance
)
@classmethod
def serialize_to_json(
cls,
# TODO (GH-52141): When can we remove scheduler constructs here?
object_to_serialize: SdkOperator | SerializedOperator | DAG | SerializedDAG,
decorated_fields: set,
) -> dict[str, Any]:
"""Serialize an object to JSON."""
serialized_object: dict[str, Any] = {}
keys_to_serialize = object_to_serialize.get_serialized_fields()
for key in keys_to_serialize:
# None is ignored in serialized form and is added back in deserialization.
value = getattr(object_to_serialize, key, None)
if cls._is_excluded(value, key, object_to_serialize):
continue
if key == "_operator_name":
# when operator_name matches task_type, we can remove
# it to reduce the JSON payload
task_type = getattr(object_to_serialize, "task_type", None)
if value != task_type:
serialized_object[key] = cls.serialize(value)
elif key in decorated_fields:
serialized_object[key] = cls.serialize(value)
elif key == "timetable" and value is not None:
serialized_object[key] = encode_timetable(value)
elif key == "weight_rule" and value is not None:
encoded_priority_weight_strategy = _encode_priority_weight_strategy(value)
# Exclude if it is just default
default_pri_weight_stra = cls.get_schema_defaults("operator").get(key, None)
if default_pri_weight_stra != encoded_priority_weight_strategy:
serialized_object[key] = encoded_priority_weight_strategy
else:
value = cls.serialize(value)
if isinstance(value, dict) and Encoding.TYPE in value:
value = value[Encoding.VAR]
serialized_object[key] = value
return serialized_object
@classmethod
def serialize(
cls, var: Any, *, strict: bool = False
) -> Any: # Unfortunately there is no support for recursive types in mypy
"""
Serialize an object; helper function of depth first search for serialization.
The serialization protocol is:
(1) keeping JSON supported types: primitives, dict, list;
(2) encoding other types as ``{TYPE: 'foo', VAR: 'bar'}``, the deserialization
step decode VAR according to TYPE;
(3) Operator has a special field CLASS to record the original class
name for displaying in UI.
:meta private:
"""
from airflow.sdk.definitions._internal.types import is_arg_set
from airflow.sdk.exceptions import TaskDeferred
if not is_arg_set(var):
return cls._encode(None, type_=DAT.ARG_NOT_SET)
elif cls._is_primitive(var):
# enum.IntEnum is an int instance, it causes json dumps error so we use its value.
if isinstance(var, enum.Enum):
return var.value
# These are not allowed in JSON. https://datatracker.ietf.org/doc/html/rfc8259#section-6
if isinstance(var, float) and (math.isnan(var) or math.isinf(var)):
return str(var)
return var
elif isinstance(var, dict):
return cls._encode(
{str(k): cls.serialize(v, strict=strict) for k, v in var.items()},
type_=DAT.DICT,
)
elif isinstance(var, list):
return [cls.serialize(v, strict=strict) for v in var]
elif (
var.__class__.__name__ == "V1Pod"
and _has_kubernetes(attempt_import=True)
and isinstance(var, k8s.V1Pod)
):
json_pod = ApiClient().sanitize_for_serialization(var)
return cls._encode(json_pod, type_=DAT.POD)
elif isinstance(var, OutletEventAccessors):
return cls._encode(
_encode_outlet_event_accessors(var),
type_=DAT.ASSET_EVENT_ACCESSORS,
)
elif isinstance(var, AssetUniqueKey):
return cls._encode(
attrs.asdict(var),
type_=DAT.ASSET_UNIQUE_KEY,
)
elif isinstance(var, AssetAliasUniqueKey):
return cls._encode(
attrs.asdict(var),
type_=DAT.ASSET_ALIAS_UNIQUE_KEY,
)
elif isinstance(var, DAG):
return cls._encode(DagSerialization.serialize_dag(var), type_=DAT.DAG)
elif isinstance(var, (DeadlineAlert, SerializedDeadlineAlert)):
return cls._encode(encode_deadline_alert(var), type_=DAT.DEADLINE_ALERT)
elif isinstance(var, Resources):
return var.to_dict()
elif isinstance(var, MappedOperator):
return cls._encode(OperatorSerialization.serialize_mapped_operator(var), type_=DAT.OP)
elif isinstance(var, BaseOperator):
var._needs_expansion = var.get_needs_expansion()
return cls._encode(OperatorSerialization.serialize_operator(var), type_=DAT.OP)
elif isinstance(var, cls._datetime_types):
return cls._encode(var.timestamp(), type_=DAT.DATETIME)
elif isinstance(var, datetime.timedelta):
return cls._encode(var.total_seconds(), type_=DAT.TIMEDELTA)
elif isinstance(var, (Timezone, FixedTimezone)):
return cls._encode(encode_timezone(var), type_=DAT.TIMEZONE)
elif isinstance(var, relativedelta.relativedelta):
return cls._encode(encode_relativedelta(var), type_=DAT.RELATIVEDELTA)
elif isinstance(var, TaskInstanceKey):
return cls._encode(
var._asdict(),
type_=DAT.TASK_INSTANCE_KEY,
)
elif isinstance(var, (AirflowException, TaskDeferred)) and hasattr(var, "serialize"):
exc_cls_name, args, kwargs = var.serialize()
return cls._encode(
cls.serialize(
{"exc_cls_name": exc_cls_name, "args": args, "kwargs": kwargs},
strict=strict,
),
type_=DAT.AIRFLOW_EXC_SER,
)
elif isinstance(var, (KeyError, AttributeError)):
return cls._encode(
cls.serialize(
{
"exc_cls_name": var.__class__.__name__,
"args": [var.args],
"kwargs": {},
},
strict=strict,
),
type_=DAT.BASE_EXC_SER,
)
elif isinstance(var, BaseTrigger):
return cls._encode(
cls.serialize(
var.serialize(),
strict=strict,
),
type_=DAT.BASE_TRIGGER,
)
elif callable(var):
return str(get_python_source(var))
elif isinstance(var, set):
# FIXME: casts set to list in customized serialization in future.
try:
return cls._encode(
sorted(cls.serialize(v, strict=strict) for v in var),
type_=DAT.SET,
)
except TypeError:
return cls._encode(
[cls.serialize(v, strict=strict) for v in var],
type_=DAT.SET,
)
elif isinstance(var, tuple):
# FIXME: casts tuple to list in customized serialization in future.
return cls._encode(
[cls.serialize(v, strict=strict) for v in var],
type_=DAT.TUPLE,
)
elif isinstance(var, TaskGroup):
return TaskGroupSerialization.serialize_task_group(var)
elif isinstance(var, Param):
return cls._encode(cls._serialize_param(var), type_=DAT.PARAM)
elif isinstance(var, XComArg):
return cls._encode(serialize_xcom_arg(var), type_=DAT.XCOM_REF)
elif isinstance(var, LazySelectSequence):
return cls.serialize(list(var))
elif isinstance(var, (BaseAsset, SerializedAssetBase)):
serialized_asset = encode_asset_like(var)
return cls._encode(serialized_asset, type_=serialized_asset.pop("__type"))
elif isinstance(var, Connection):
return cls._encode(var.to_dict(validate=True), type_=DAT.CONNECTION)
elif isinstance(var, TaskCallbackRequest):
return cls._encode(var.to_json(), type_=DAT.TASK_CALLBACK_REQUEST)
elif isinstance(var, DagCallbackRequest):
return cls._encode(var.to_json(), type_=DAT.DAG_CALLBACK_REQUEST)
elif isinstance(var, MappedArgument):
data = {"input": encode_expand_input(var._input), "key": var._key}
return cls._encode(data, type_=DAT.MAPPED_ARGUMENT)
else:
return cls.default_serialization(strict, var)
@classmethod
def default_serialization(cls, strict, var) -> str:
log.debug("Cast type %s to str in serialization.", type(var))
if strict:
raise SerializationError("Encountered unexpected type")
return str(var)
@classmethod
def deserialize(cls, encoded_var: Any) -> Any:
"""
Deserialize an object; helper function of depth first search for deserialization.
:meta private:
"""
if cls._is_primitive(encoded_var):
return encoded_var
elif isinstance(encoded_var, list):
return [cls.deserialize(v) for v in encoded_var]
if not isinstance(encoded_var, dict):
raise ValueError(f"The encoded_var should be dict and is {type(encoded_var)}")
var = encoded_var[Encoding.VAR]
type_ = encoded_var[Encoding.TYPE]
if type_ == DAT.DICT:
return {k: cls.deserialize(v) for k, v in var.items()}
elif type_ == DAT.ASSET_EVENT_ACCESSORS:
return _decode_outlet_event_accessors(var)
elif type_ == DAT.ASSET_UNIQUE_KEY:
return AssetUniqueKey(name=var["name"], uri=var["uri"])
elif type_ == DAT.ASSET_ALIAS_UNIQUE_KEY:
return AssetAliasUniqueKey(name=var["name"])
elif type_ == DAT.DAG:
return DagSerialization.deserialize_dag(var)
elif type_ == DAT.OP:
return OperatorSerialization.deserialize_operator(var)
elif type_ == DAT.DATETIME:
return from_timestamp(var)
elif type_ == DAT.POD:
# Attempt to import kubernetes for deserialization. Using attempt_import=True allows
# lazy loading of kubernetes libraries only when actually needed for POD deserialization.
if not _has_kubernetes(attempt_import=True):
raise RuntimeError(
"Cannot deserialize POD objects without kubernetes libraries. "
"Please install the `kubernetes` package."
)
pod = ApiClient()._ApiClient__deserialize_model(var, k8s.V1Pod)
return pod
elif type_ == DAT.TIMEDELTA:
return datetime.timedelta(seconds=var)
elif type_ == DAT.TIMEZONE:
return parse_timezone(var)
elif type_ == DAT.RELATIVEDELTA:
return decode_relativedelta(var)
elif type_ == DAT.AIRFLOW_EXC_SER or type_ == DAT.BASE_EXC_SER:
deser = cls.deserialize(var)
exc_cls_name = deser["exc_cls_name"]
args = deser["args"]
kwargs = deser["kwargs"]
del deser
if type_ == DAT.AIRFLOW_EXC_SER:
exc_cls = import_string(exc_cls_name)
else:
exc_cls = import_string(f"builtins.{exc_cls_name}")
return exc_cls(*args, **kwargs)
elif type_ == DAT.BASE_TRIGGER:
tr_cls_name, kwargs = cls.deserialize(var)
tr_cls = import_string(tr_cls_name)
return tr_cls(**kwargs)
elif type_ == DAT.SET:
return {cls.deserialize(v) for v in var}
elif type_ == DAT.TUPLE:
return tuple(cls.deserialize(v) for v in var)
elif type_ == DAT.PARAM:
return cls._deserialize_param(var)
elif type_ == DAT.XCOM_REF:
return _XComRef(var) # Delay deserializing XComArg objects until we have the entire DAG.
elif type_ in (DAT.ASSET, DAT.ASSET_ALIAS, DAT.ASSET_ALL, DAT.ASSET_ANY, DAT.ASSET_REF):
return decode_asset_like(encoded_var)
elif type_ == DAT.CONNECTION:
return Connection(**var)
elif type_ == DAT.TASK_CALLBACK_REQUEST:
return TaskCallbackRequest.from_json(var)
elif type_ == DAT.DAG_CALLBACK_REQUEST:
return DagCallbackRequest.from_json(var)
elif type_ == DAT.TASK_INSTANCE_KEY:
return TaskInstanceKey(**var)
elif type_ == DAT.MAPPED_ARGUMENT:
expand_input = create_expand_input(var["input"]["type"], var["input"]["value"])
return SchedulerMappedArgument(input=expand_input, key=var["key"])
elif type_ == DAT.ARG_NOT_SET:
from airflow.serialization.definitions.notset import NOTSET
return NOTSET
elif type_ == DAT.DEADLINE_ALERT:
return decode_deadline_alert(var)
else:
raise TypeError(f"Invalid type {type_!s} in deserialization.")
@classmethod
def _deserialize_datetime(cls, arg):
if isinstance(arg, str):
return arg
return from_timestamp(arg)
_deserialize_timezone = parse_timezone
@classmethod
def _deserialize_timedelta(cls, seconds: int) -> datetime.timedelta:
return datetime.timedelta(seconds=seconds)
@classmethod
def _is_constructor_param(cls, attrname: str, instance: Any) -> bool:
return attrname in cls._CONSTRUCTOR_PARAMS
@classmethod
def _value_is_hardcoded_default(cls, attrname: str, value: Any, instance: Any) -> bool:
"""
Return true if ``value`` is the hard-coded default for the given attribute.
This takes in to account cases where the ``max_active_tasks`` parameter is
stored in the ``_max_active_tasks`` attribute.
And by using `is` here only and not `==` this copes with the case a
user explicitly specifies an attribute with the same "value" as the
default. (This is because ``"default" is "default"`` will be False as
they are different strings with the same characters.)
Also returns True if the value is an empty list or empty dict. This is done
to account for the case where the default value of the field is None but has the
``field = field or {}`` set.
"""
if attrname in cls._CONSTRUCTOR_PARAMS:
if cls._CONSTRUCTOR_PARAMS[attrname] is value or (value in [{}, []]):
return True
if cls._CONSTRUCTOR_PARAMS[attrname] is attrs.NOTHING and value is None:
return True
if attrs.has(type(instance)):
return any(fld.default is value for fld in attrs.fields(type(instance)) if fld.name == attrname)
return False
@classmethod
def _serialize_param(cls, param: Param):
return {
"__class": f"{param.__module__}.{param.__class__.__name__}",
"default": cls.serialize(param.value),
"description": cls.serialize(param.description),
"schema": cls.serialize(param.schema),
"source": cls.serialize(getattr(param, "source", None)),
}
@classmethod
def _deserialize_param(cls, param_dict: dict) -> SerializedParam:
"""
Deserialize an encoded Param to a server-side SerializedParam.
In 2.2.0, Param attrs were assumed to be json-serializable and were not run through
this class's ``serialize`` method. So before running through ``deserialize``,
we first verify that it's necessary to do.
"""
attrs = ("default", "description", "schema", "source")
kwargs = {}
def is_serialized(val):
if isinstance(val, dict):
return Encoding.TYPE in val
if isinstance(val, list):
return all(isinstance(item, dict) and Encoding.TYPE in item for item in val)
return False
for attr in attrs:
if attr in param_dict:
val = param_dict[attr]
if is_serialized(val):
val = cls.deserialize(val)
kwargs[attr] = val
return SerializedParam(
default=kwargs.get("default"),
description=kwargs.get("description"),
source=kwargs.get("source", None),
**(kwargs.get("schema") or {}),
)
@classmethod
def _serialize_params_dict(cls, params: ParamsDict | dict) -> list[tuple[str, dict]]:
"""Serialize Params dict for a DAG or task as a list of tuples to ensure ordering."""
serialized_params = []
for k, raw_v in params.items():
# Use native param object, not resolved value if possible
v = params.get_param(k) if isinstance(params, ParamsDict) else raw_v
try:
class_identity = f"{v.__module__}.{v.__class__.__name__}"
except AttributeError:
class_identity = ""
if class_identity == "airflow.sdk.definitions.param.Param":
serialized_params.append((k, cls._serialize_param(v)))
else:
# Auto-box other values into Params object like it is done by DAG parsing as well
serialized_params.append((k, cls._serialize_param(Param(v))))
return serialized_params
@classmethod
def _deserialize_params_dict(cls, encoded_params: list[tuple[str, dict]]) -> SerializedParamsDict:
"""Deserialize an encoded ParamsDict to a server-side SerializedParamsDict."""
if isinstance(encoded_params, collections.abc.Mapping):
# in 2.9.2 or earlier params were serialized as JSON objects
encoded_param_pairs: Iterable[tuple[str, dict]] = encoded_params.items()
else:
encoded_param_pairs = encoded_params
def deserialized_param(v):
if not isinstance(v, dict) or "__class" not in v:
return SerializedParam(v) # Old style param serialization format.
return cls._deserialize_param(v)
op_params = {k: deserialized_param(v) for k, v in encoded_param_pairs}
return SerializedParamsDict(op_params)
@classmethod
@lru_cache(maxsize=4) # Cache for "operator", "dag", and a few others
def get_schema_defaults(cls, object_type: str) -> dict[str, Any]:
"""
Extract default values from JSON schema for any object type.
:param object_type: The object type to get defaults for (e.g., "operator", "dag")
:return: Dictionary of field name -> default value
"""
# Load schema if needed (handles lazy loading)
schema_loader = cls._json_schema
if schema_loader is None:
return {}
# Access the schema definitions (trigger lazy loading)
schema_data = schema_loader.schema
object_def = schema_data.get("definitions", {}).get(object_type, {})
properties = object_def.get("properties", {})
defaults = {}
for field_name, field_def in properties.items():
if isinstance(field_def, dict) and "default" in field_def:
defaults[field_name] = field_def["default"]
return defaults
class _DependencyDetector:
"""
Detects dependencies between DAGs.
:meta private:
"""
@staticmethod
def detect_task_dependencies(task: SdkOperator) -> list[DagDependency]:
"""Detect dependencies caused by tasks."""
from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.providers.standard.sensors.external_task import ExternalTaskSensor
deps = []
if isinstance(task, TriggerDagRunOperator):
deps.append(
DagDependency(
source=task.dag_id,
target=getattr(task, "trigger_dag_id"),
label=task.task_display_name,
dependency_type="trigger",
dependency_id=task.task_id,
)
)
elif (
isinstance(task, MappedOperator)
and issubclass(task.operator_class, TriggerDagRunOperator)
and "trigger_dag_id" in task.partial_kwargs
):
deps.append(
DagDependency(
source=task.dag_id,
target=task.partial_kwargs["trigger_dag_id"],
label=task.task_display_name,
dependency_type="trigger",
dependency_id=task.task_id,
)
)
elif isinstance(task, ExternalTaskSensor):
deps.append(
DagDependency(
source=getattr(task, "external_dag_id"),
target=task.dag_id,
label=task.task_display_name,
dependency_type="sensor",
dependency_id=task.task_id,
)
)
elif (
isinstance(task, MappedOperator)
and issubclass(task.operator_class, ExternalTaskSensor)
and "external_dag_id" in task.partial_kwargs
):
deps.append(
DagDependency(
source=task.partial_kwargs["external_dag_id"],
target=task.dag_id,
label=task.task_display_name,
dependency_type="sensor",
dependency_id=task.task_id,
)
)
for obj in task.outlets or []:
if isinstance(obj, (Asset, SerializedAsset)):
serialized_asset = ensure_serialized_asset(obj)
deps.append(
DagDependency(
source=task.dag_id,
target="asset",
label=obj.name,
dependency_type="asset",
dependency_id=SerializedAssetUniqueKey.from_asset(serialized_asset).to_str(),
)
)
elif isinstance(obj, (AssetAlias, SerializedAssetAlias)):
serialized_alias = ensure_serialized_asset(obj)
deps.extend(serialized_alias.iter_dag_dependencies(source=task.dag_id, target=""))
return deps
@staticmethod
def detect_dag_dependencies(dag: DAG | None) -> Iterable[DagDependency]:
"""Detect dependencies set directly on the DAG object."""
if not dag:
return
tt = coerce_to_core_timetable(dag.timetable)
yield from tt.asset_condition.iter_dag_dependencies(source="", target=dag.dag_id)
class OperatorSerialization(DAGNode, BaseSerialization):
"""
Logic to encode an operator and decode the data.
This covers serialization of both BaseOperator and MappedOperator. Creating
a serializaed operator is a three-step process:
1. Instantiate a :class:`SerializedBaseOperator` or :class:`MappedOperator` object.
2. Populate attributes with :func:`OperatorSerialization.populated_operator`.
3. When the task's containing DAG is available, fix references to the DAG
with :func:`OperatorSerialization.set_task_dag_references`.
"""
_decorated_fields = {"executor_config"}
_CONSTRUCTOR_PARAMS = {}
_json_schema: ClassVar[Validator] = lazy_object_proxy.Proxy(load_dag_schema)
_const_fields: ClassVar[set[str] | None] = None
# Parameters of BaseOperator.__init__ that must not appear in template_fields.
# Computed once at class-load time: the signature never changes during a process.
_FORBIDDEN_TEMPLATE_FIELDS: ClassVar[frozenset[str]] = frozenset(
signature(BaseOperator.__init__).parameters
) - {"email"}
@classmethod
def serialize_mapped_operator(cls, op: MappedOperator) -> dict[str, Any]:
serialized_op = cls._serialize_node(op)
# Handle expand_input and op_kwargs_expand_input.
expansion_kwargs = op._get_specified_expand_input()
if TYPE_CHECKING: # Let Mypy check the input type for us!
_ExpandInputRef.validate_expand_input_value(expansion_kwargs.value)
serialized_op[op._expand_input_attr] = encode_expand_input(expansion_kwargs)
if op.partial_kwargs:
serialized_op["partial_kwargs"] = {}
for k, v in op.partial_kwargs.items():
if cls._is_excluded(v, k, op):
continue
if k in _OPERATOR_CALLBACK_FIELDS:
if bool(v):
serialized_op["partial_kwargs"][f"has_{k}"] = True
continue
serialized_op["partial_kwargs"].update({k: cls.serialize(v)})
# Store python_callable_name instead of python_callable.
# exclude_module=True ensures stable names across bundle version changes.
python_callable = op.partial_kwargs.get("python_callable", None)
if python_callable:
serialized_op["partial_kwargs"]["python_callable_name"] = qualname(
python_callable, exclude_module=True
)