-
Notifications
You must be signed in to change notification settings - Fork 14.6k
/
Copy pathviews.py
5657 lines (4888 loc) · 214 KB
/
views.py
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.
from __future__ import annotations
import collections.abc
import contextlib
import copy
import datetime
import itertools
import json
import logging
import math
import operator
import os
import sys
import traceback
import warnings
from bisect import insort_left
from collections import defaultdict
from functools import cached_property
from json import JSONDecodeError
from pathlib import Path
from typing import TYPE_CHECKING, Any, Collection, Iterator, Mapping, MutableMapping, Sequence
from urllib.parse import unquote, urljoin, urlsplit
import configupdater
import flask.json
import lazy_object_proxy
import re2
import sqlalchemy as sqla
from croniter import croniter
from flask import (
Response,
abort,
before_render_template,
flash,
g,
has_request_context,
make_response,
redirect,
render_template,
request,
send_from_directory,
session as flask_session,
url_for,
)
from flask_appbuilder import BaseView, ModelView, expose
from flask_appbuilder._compat import as_unicode
from flask_appbuilder.actions import action
from flask_appbuilder.const import FLAMSG_ERR_SEC_ACCESS_DENIED
from flask_appbuilder.models.sqla.filters import BaseFilter
from flask_appbuilder.urltools import get_order_args, get_page_args, get_page_size_args
from flask_appbuilder.widgets import FormWidget
from flask_babel import lazy_gettext
from jinja2.utils import htmlsafe_json_dumps, pformat # type: ignore
from markupsafe import Markup, escape
from pendulum.datetime import DateTime
from pendulum.parsing.exceptions import ParserError
from sqlalchemy import and_, case, desc, func, inspect, or_, select, union_all
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import joinedload
from wtforms import BooleanField, validators
import airflow
from airflow import models, plugins_manager, settings
from airflow.api.common.airflow_health import get_airflow_health
from airflow.api.common.mark_tasks import (
set_dag_run_state_to_failed,
set_dag_run_state_to_queued,
set_dag_run_state_to_success,
set_state,
)
from airflow.auth.managers.models.resource_details import AccessView, DagAccessEntity, DagDetails
from airflow.compat.functools import cache
from airflow.configuration import AIRFLOW_CONFIG, conf
from airflow.datasets import Dataset
from airflow.exceptions import (
AirflowConfigException,
AirflowException,
AirflowNotFoundException,
ParamValidationError,
RemovedInAirflow3Warning,
)
from airflow.executors.executor_loader import ExecutorLoader
from airflow.hooks.base import BaseHook
from airflow.jobs.job import Job
from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
from airflow.jobs.triggerer_job_runner import TriggererJobRunner
from airflow.models import Connection, DagModel, DagTag, Log, SlaMiss, Trigger, XCom
from airflow.models.dag import get_dataset_triggered_next_run_info
from airflow.models.dagrun import RUN_ID_REGEX, DagRun, DagRunType
from airflow.models.dataset import DagScheduleDatasetReference, DatasetDagRunQueue, DatasetEvent, DatasetModel
from airflow.models.errors import ParseImportError
from airflow.models.operator import needs_expansion
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.taskinstance import TaskInstance, TaskInstanceNote
from airflow.plugins_manager import PLUGINS_ATTRIBUTES_TO_DUMP
from airflow.providers_manager import ProvidersManager
from airflow.security import permissions
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.dependencies_deps import SCHEDULER_QUEUED_DEPS
from airflow.timetables._cron import CronMixin
from airflow.timetables.base import DataInterval, TimeRestriction
from airflow.timetables.simple import ContinuousTimetable
from airflow.utils import json as utils_json, timezone, yaml
from airflow.utils.airflow_flask_app import get_airflow_app
from airflow.utils.dag_edges import dag_edges
from airflow.utils.db import get_query_count
from airflow.utils.docs import get_doc_url_for_provider, get_docs_url
from airflow.utils.helpers import exactly_one
from airflow.utils.log import secrets_masker
from airflow.utils.log.log_reader import TaskLogReader
from airflow.utils.net import get_hostname
from airflow.utils.session import NEW_SESSION, create_session, provide_session
from airflow.utils.state import DagRunState, State, TaskInstanceState
from airflow.utils.strings import to_boolean
from airflow.utils.task_group import TaskGroup, task_group_to_dict
from airflow.utils.timezone import td_format, utcnow
from airflow.utils.types import NOTSET
from airflow.version import version
from airflow.www import auth, utils as wwwutils
from airflow.www.decorators import action_logging, gzipped
from airflow.www.extensions.init_auth_manager import get_auth_manager
from airflow.www.forms import (
DagRunEditForm,
DateTimeForm,
TaskInstanceEditForm,
create_connection_form_class,
)
from airflow.www.widgets import AirflowModelListWidget, AirflowVariableShowWidget
if TYPE_CHECKING:
from sqlalchemy.orm import Session
from airflow.auth.managers.models.batch_apis import IsAuthorizedDagRequest
from airflow.models.dag import DAG
from airflow.models.operator import Operator
PAGE_SIZE = conf.getint("webserver", "page_size")
FILTER_TAGS_COOKIE = "tags_filter"
FILTER_STATUS_COOKIE = "dag_status_filter"
LINECHART_X_AXIS_TICKFORMAT = (
"function (d, i) { let xLabel;"
"if (i === undefined) {xLabel = d3.time.format('%H:%M, %d %b %Y')(new Date(parseInt(d)));"
"} else {xLabel = d3.time.format('%H:%M, %d %b')(new Date(parseInt(d)));} return xLabel;}"
)
SENSITIVE_FIELD_PLACEHOLDER = "RATHER_LONG_SENSITIVE_FIELD_PLACEHOLDER"
logger = logging.getLogger(__name__)
def sanitize_args(args: dict[str, Any]) -> dict[str, Any]:
"""
Remove all parameters starting with `_`.
:param args: arguments of request
:return: copy of the dictionary passed as input with args starting with `_` removed.
"""
return {key: value for key, value in args.items() if not key.startswith("_")}
# Following the release of https://github.com/python/cpython/issues/102153 in Python 3.8.17 and 3.9.17 on
# June 6, 2023, we are adding extra sanitization of the urls passed to get_safe_url method to make it works
# the same way regardless if the user uses latest Python patchlevel versions or not. This also follows
# a recommended solution by the Python core team.
#
# From: https://github.com/python/cpython/commit/d28bafa2d3e424b6fdcfd7ae7cde8e71d7177369
#
# We recommend that users of these APIs where the values may be used anywhere
# with security implications code defensively. Do some verification within your
# code before trusting a returned component part. Does that ``scheme`` make
# sense? Is that a sensible ``path``? Is there anything strange about that
# ``hostname``? etc.
#
# C0 control and space to be stripped per WHATWG spec.
# == "".join([chr(i) for i in range(0, 0x20 + 1)])
_WHATWG_C0_CONTROL_OR_SPACE = (
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c"
"\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f "
)
def get_safe_url(url):
"""Given a user-supplied URL, ensure it points to our web server."""
if not url:
return url_for("Airflow.index")
# If the url contains semicolon, redirect it to homepage to avoid
# potential XSS. (Similar to https://github.com/python/cpython/pull/24297/files (bpo-42967))
if ";" in unquote(url):
return url_for("Airflow.index")
url = url.lstrip(_WHATWG_C0_CONTROL_OR_SPACE)
host_url = urlsplit(request.host_url)
redirect_url = urlsplit(urljoin(request.host_url, url))
if not (redirect_url.scheme in ("http", "https") and host_url.netloc == redirect_url.netloc):
return url_for("Airflow.index")
# This will ensure we only redirect to the right scheme/netloc
return redirect_url.geturl()
def get_date_time_num_runs_dag_runs_form_data(www_request, session, dag):
"""Get Execution Data, Base Date & Number of runs from a Request."""
date_time = www_request.args.get("execution_date")
run_id = www_request.args.get("run_id")
# First check run id, then check execution date, if not fall back on the latest dagrun
if run_id:
dagrun = dag.get_dagrun(run_id=run_id, session=session)
date_time = dagrun.execution_date
elif date_time:
date_time = _safe_parse_datetime(date_time)
else:
date_time = dag.get_latest_execution_date(session=session) or timezone.utcnow()
base_date = www_request.args.get("base_date")
if base_date:
base_date = _safe_parse_datetime(base_date)
else:
# The DateTimeField widget truncates milliseconds and would loose
# the first dag run. Round to next second.
base_date = (date_time + datetime.timedelta(seconds=1)).replace(microsecond=0)
default_dag_run = conf.getint("webserver", "default_dag_run_display_number")
num_runs = www_request.args.get("num_runs", default=default_dag_run, type=int)
# When base_date has been rounded up because of the DateTimeField widget, we want
# to use the execution_date as the starting point for our query just to ensure a
# link targeting a specific dag run actually loads that dag run. If there are
# more than num_runs dag runs in the "rounded period" then those dagruns would get
# loaded and the actual requested run would be excluded by the limit(). Once
# the user has changed base date to be anything else we want to use that instead.
query_date = base_date
if date_time < base_date <= date_time + datetime.timedelta(seconds=1):
query_date = date_time
drs = session.scalars(
select(DagRun)
.where(DagRun.dag_id == dag.dag_id, DagRun.execution_date <= query_date)
.order_by(desc(DagRun.execution_date))
.limit(num_runs)
).all()
dr_choices = []
dr_state = None
for dr in drs:
dr_choices.append((dr.execution_date.isoformat(), dr.run_id))
if date_time == dr.execution_date:
dr_state = dr.state
# Happens if base_date was changed and the selected dag run is not in result
if not dr_state and drs:
dr = drs[0]
date_time = dr.execution_date
dr_state = dr.state
return {
"dttm": date_time,
"base_date": base_date,
"num_runs": num_runs,
"execution_date": date_time.isoformat(),
"dr_choices": dr_choices,
"dr_state": dr_state,
}
def _safe_parse_datetime(v, *, allow_empty=False, strict=True) -> datetime.datetime | None:
"""
Parse datetime and return error message for invalid dates.
:param v: the string value to be parsed
:param allow_empty: Set True to return none if empty str or None
:param strict: if False, it will fall back on the dateutil parser if unable to parse with pendulum
"""
if allow_empty is True and not v:
return None
try:
return timezone.parse(v, strict=strict)
except (TypeError, ParserError):
abort(400, f"Invalid datetime: {v!r}")
def node_dict(node_id, label, node_class):
return {
"id": node_id,
"value": {"label": label, "rx": 5, "ry": 5, "class": node_class},
}
def dag_to_grid(dag: DagModel, dag_runs: Sequence[DagRun], session: Session) -> dict[str, Any]:
"""
Create a nested dict representation of the DAG's TaskGroup and its children.
Used to construct the Graph and Grid views.
"""
query = session.execute(
select(
TaskInstance.task_id,
TaskInstance.run_id,
TaskInstance.state,
TaskInstance._try_number,
func.min(TaskInstanceNote.content).label("note"),
func.count(func.coalesce(TaskInstance.state, sqla.literal("no_status"))).label("state_count"),
func.min(TaskInstance.queued_dttm).label("queued_dttm"),
func.min(TaskInstance.start_date).label("start_date"),
func.max(TaskInstance.end_date).label("end_date"),
)
.join(TaskInstance.task_instance_note, isouter=True)
.where(
TaskInstance.dag_id == dag.dag_id,
TaskInstance.run_id.in_([dag_run.run_id for dag_run in dag_runs]),
)
.group_by(TaskInstance.task_id, TaskInstance.run_id, TaskInstance.state, TaskInstance._try_number)
.order_by(TaskInstance.task_id, TaskInstance.run_id)
)
grouped_tis: dict[str, list[TaskInstance]] = collections.defaultdict(
list,
((task_id, list(tis)) for task_id, tis in itertools.groupby(query, key=lambda ti: ti.task_id)),
)
@cache
def get_task_group_children_getter() -> operator.methodcaller:
sort_order = conf.get("webserver", "grid_view_sorting_order", fallback="topological")
if sort_order == "topological":
return operator.methodcaller("topological_sort")
if sort_order == "hierarchical_alphabetical":
return operator.methodcaller("hierarchical_alphabetical_sort")
raise AirflowConfigException(f"Unsupported grid_view_sorting_order: {sort_order}")
def task_group_to_grid(item: Operator | TaskGroup) -> dict[str, Any]:
if not isinstance(item, TaskGroup):
def _mapped_summary(ti_summaries: list[TaskInstance]) -> Iterator[dict[str, Any]]:
run_id = ""
record: dict[str, Any] = {}
def set_overall_state(record):
for state in wwwutils.priority:
if state in record["mapped_states"]:
record["state"] = state
break
# When turning the dict into JSON we can't have None as a key,
# so use the string that the UI does.
with contextlib.suppress(KeyError):
record["mapped_states"]["no_status"] = record["mapped_states"].pop(None)
for ti_summary in ti_summaries:
if run_id != ti_summary.run_id:
run_id = ti_summary.run_id
if record:
set_overall_state(record)
yield record
record = {
"task_id": ti_summary.task_id,
"run_id": run_id,
"queued_dttm": ti_summary.queued_dttm,
"start_date": ti_summary.start_date,
"end_date": ti_summary.end_date,
"mapped_states": {ti_summary.state: ti_summary.state_count},
"state": None, # We change this before yielding
}
continue
record["queued_dttm"] = min(
filter(None, [record["queued_dttm"], ti_summary.queued_dttm]), default=None
)
record["start_date"] = min(
filter(None, [record["start_date"], ti_summary.start_date]), default=None
)
# Sometimes the start date of a group might be before the queued date of the group
if (
record["queued_dttm"]
and record["start_date"]
and record["queued_dttm"] > record["start_date"]
):
record["queued_dttm"] = None
record["end_date"] = max(
filter(None, [record["end_date"], ti_summary.end_date]), default=None
)
record["mapped_states"][ti_summary.state] = ti_summary.state_count
if record:
set_overall_state(record)
yield record
if item_is_mapped := needs_expansion(item):
instances = list(_mapped_summary(grouped_tis[item.task_id]))
else:
instances = [
{
"task_id": task_instance.task_id,
"run_id": task_instance.run_id,
"state": task_instance.state,
"queued_dttm": task_instance.queued_dttm,
"start_date": task_instance.start_date,
"end_date": task_instance.end_date,
"try_number": wwwutils.get_try_count(task_instance._try_number, task_instance.state),
"note": task_instance.note,
}
for task_instance in grouped_tis[item.task_id]
]
setup_teardown_type = {}
if item.is_setup is True:
setup_teardown_type["setupTeardownType"] = "setup"
elif item.is_teardown is True:
setup_teardown_type["setupTeardownType"] = "teardown"
return {
"id": item.task_id,
"instances": instances,
"label": item.label,
"extra_links": item.extra_links,
"is_mapped": item_is_mapped,
"has_outlet_datasets": any(isinstance(i, Dataset) for i in (item.outlets or [])),
"operator": item.operator_name,
"trigger_rule": item.trigger_rule,
**setup_teardown_type,
}
# Task Group
task_group = item
children = [task_group_to_grid(child) for child in get_task_group_children_getter()(item)]
def get_summary(dag_run: DagRun):
child_instances = [
item
for sublist in (child["instances"] for child in children if "instances" in child)
for item in sublist
if item["run_id"] == dag_run.run_id
if item
]
children_queued_dttms = (item["queued_dttm"] for item in child_instances)
children_start_dates = (item["start_date"] for item in child_instances)
children_end_dates = (item["end_date"] for item in child_instances)
children_states = {item["state"] for item in child_instances}
group_state = next((state for state in wwwutils.priority if state in children_states), None)
group_queued_dttm = min(filter(None, children_queued_dttms), default=None)
group_start_date = min(filter(None, children_start_dates), default=None)
group_end_date = max(filter(None, children_end_dates), default=None)
# Sometimes the start date of a group might be before the queued date of the group
if group_queued_dttm and group_start_date and group_queued_dttm > group_start_date:
group_queued_dttm = None
return {
"task_id": task_group.group_id,
"run_id": dag_run.run_id,
"state": group_state,
"queued_dttm": group_queued_dttm,
"start_date": group_start_date,
"end_date": group_end_date,
}
def get_mapped_group_summaries():
mapped_ti_query = session.execute(
select(TaskInstance.task_id, TaskInstance.state, TaskInstance.run_id, TaskInstance.map_index)
.where(
TaskInstance.dag_id == dag.dag_id,
TaskInstance.task_id.in_(child["id"] for child in children),
TaskInstance.run_id.in_(r.run_id for r in dag_runs),
)
.order_by(TaskInstance.task_id, TaskInstance.run_id)
)
# Group tis by run_id, and then map_index.
mapped_tis: Mapping[str, Mapping[int, list[TaskInstance]]] = defaultdict(
lambda: defaultdict(list)
)
for ti in mapped_ti_query:
mapped_tis[ti.run_id][ti.map_index].append(ti)
def get_mapped_group_summary(run_id: str, mapped_instances: Mapping[int, list[TaskInstance]]):
child_instances = [
item
for sublist in (child["instances"] for child in children if "instances" in child)
for item in sublist
if item and item["run_id"] == run_id
]
children_queued_dttms = (item["queued_dttm"] for item in child_instances)
children_start_dates = (item["start_date"] for item in child_instances)
children_end_dates = (item["end_date"] for item in child_instances)
children_states = {item["state"] for item in child_instances}
# TODO: This assumes TI map index has a one-to-one mapping to
# its parent mapped task group, which will not be true when we
# allow nested mapping in the future.
mapped_states: MutableMapping[str, int] = defaultdict(int)
for mi_values in mapped_instances.values():
child_states = {mi.state for mi in mi_values}
state = next(s for s in wwwutils.priority if s in child_states)
value = state.value if state is not None else "no_status"
mapped_states[value] += 1
group_state = next((state for state in wwwutils.priority if state in children_states), None)
group_queued_dttm = min(filter(None, children_queued_dttms), default=None)
group_start_date = min(filter(None, children_start_dates), default=None)
group_end_date = max(filter(None, children_end_dates), default=None)
return {
"task_id": task_group.group_id,
"run_id": run_id,
"state": group_state,
"queued_dttm": group_queued_dttm,
"start_date": group_start_date,
"end_date": group_end_date,
"mapped_states": mapped_states,
}
return [get_mapped_group_summary(run_id, tis) for run_id, tis in mapped_tis.items()]
# We don't need to calculate summaries for the root
if task_group.group_id is None:
return {
"id": task_group.group_id,
"label": task_group.label,
"children": children,
"instances": [],
}
if next(task_group.iter_mapped_task_groups(), None) is not None:
return {
"id": task_group.group_id,
"label": task_group.label,
"children": children,
"tooltip": task_group.tooltip,
"instances": get_mapped_group_summaries(),
"is_mapped": True,
}
group_summaries = [get_summary(dr) for dr in dag_runs]
return {
"id": task_group.group_id,
"label": task_group.label,
"children": children,
"tooltip": task_group.tooltip,
"instances": group_summaries,
}
return task_group_to_grid(dag.task_group)
def get_key_paths(input_dict):
"""Return a list of dot-separated dictionary paths."""
for key, value in input_dict.items():
if isinstance(value, dict):
for sub_key in get_key_paths(value):
yield f"{key}.{sub_key}"
else:
yield key
def get_value_from_path(key_path, content):
"""Return the value from a dictionary based on dot-separated path of keys."""
elem = content
for x in key_path.strip(".").split("."):
try:
x = int(x)
elem = elem[x]
except ValueError:
elem = elem.get(x)
return elem
def get_task_stats_from_query(qry):
"""
Return a dict of the task quantity, grouped by dag id and task status.
:param qry: The data in the format (<dag id>, <task state>, <is dag running>, <task count>),
ordered by <dag id> and <is dag running>
"""
data = {}
last_dag_id = None
has_running_dags = False
for dag_id, state, is_dag_running, count in qry:
if last_dag_id != dag_id:
last_dag_id = dag_id
has_running_dags = False
elif not is_dag_running and has_running_dags:
continue
if is_dag_running:
has_running_dags = True
if dag_id not in data:
data[dag_id] = {}
data[dag_id][state] = count
return data
def redirect_or_json(origin, msg, status="", status_code=200):
"""
Return json which allows us to more elegantly handle side effects in-page.
This is useful because some endpoints are called by javascript.
"""
if request.headers.get("Accept") == "application/json":
if status == "error" and status_code == 200:
status_code = 500
return Response(response=msg, status=status_code, mimetype="application/json")
else:
if status:
flash(msg, status)
else:
flash(msg)
return redirect(origin)
######################################################################################
# Error handlers
######################################################################################
def not_found(error):
"""Show Not Found on screen for any error in the Webserver."""
return (
render_template(
"airflow/error.html",
hostname=get_hostname() if conf.getboolean("webserver", "EXPOSE_HOSTNAME") else "",
status_code=404,
error_message="Page cannot be found.",
),
404,
)
def method_not_allowed(error):
"""Show Method Not Allowed on screen for any error in the Webserver."""
return (
render_template(
"airflow/error.html",
hostname=get_hostname() if conf.getboolean("webserver", "EXPOSE_HOSTNAME") else "",
status_code=405,
error_message="Received an invalid request.",
),
405,
)
def show_traceback(error):
"""Show Traceback for a given error."""
is_logged_in = get_auth_manager().is_logged_in()
return (
render_template(
"airflow/traceback.html",
python_version=sys.version.split(" ")[0] if is_logged_in else "redacted",
airflow_version=version if is_logged_in else "redacted",
hostname=get_hostname()
if conf.getboolean("webserver", "EXPOSE_HOSTNAME") and is_logged_in
else "redacted",
info=traceback.format_exc()
if conf.getboolean("webserver", "EXPOSE_STACKTRACE") and is_logged_in
else "Error! Please contact server admin.",
),
500,
)
######################################################################################
# BaseViews
######################################################################################
class AirflowBaseView(BaseView):
"""Base View to set Airflow related properties."""
from airflow import macros
route_base = ""
extra_args = {
# Make our macros available to our UI templates too.
"macros": macros,
"get_docs_url": get_docs_url,
}
if not conf.getboolean("core", "unit_test_mode"):
executor, _ = ExecutorLoader.import_default_executor_cls()
extra_args["sqlite_warning"] = settings.engine.dialect.name == "sqlite"
if not executor.is_production:
extra_args["production_executor_warning"] = executor.__name__
extra_args["otel_on"] = conf.getboolean("metrics", "otel_on")
line_chart_attr = {
"legend.maxKeyLength": 200,
}
def render_template(self, *args, **kwargs):
# Add triggerer_job only if we need it
if TriggererJobRunner.is_needed():
kwargs["triggerer_job"] = lazy_object_proxy.Proxy(TriggererJobRunner.most_recent_job)
if "dag" in kwargs:
kwargs["can_edit_dag"] = get_auth_manager().is_authorized_dag(
method="PUT", details=DagDetails(id=kwargs["dag"].dag_id)
)
return super().render_template(
*args,
# Cache this at most once per request, not for the lifetime of the view instance
scheduler_job=lazy_object_proxy.Proxy(SchedulerJobRunner.most_recent_job),
**kwargs,
)
class Airflow(AirflowBaseView):
"""Main Airflow application."""
@expose("/health")
def health(self):
"""
Check the health status of the Airflow instance.
Includes metadatabase, scheduler and triggerer.
"""
airflow_health_status = get_airflow_health()
return flask.json.jsonify(airflow_health_status)
@expose("/home")
@auth.has_access_view()
def index(self):
"""Home view."""
from airflow.models.dag import DagOwnerAttributes
hide_paused_dags_by_default = conf.getboolean("webserver", "hide_paused_dags_by_default")
default_dag_run = conf.getint("webserver", "default_dag_run_display_number")
num_runs = request.args.get("num_runs", default=default_dag_run, type=int)
current_page = request.args.get("page", default=0, type=int)
arg_search_query = request.args.get("search")
arg_tags_filter = request.args.getlist("tags")
arg_status_filter = request.args.get("status")
arg_sorting_key = request.args.get("sorting_key", "dag_id")
arg_sorting_direction = request.args.get("sorting_direction", default="asc")
if request.args.get("reset_tags") is not None:
flask_session[FILTER_TAGS_COOKIE] = None
# Remove the reset_tags=reset from the URL
return redirect(url_for("Airflow.index"))
cookie_val = flask_session.get(FILTER_TAGS_COOKIE)
if arg_tags_filter:
flask_session[FILTER_TAGS_COOKIE] = ",".join(arg_tags_filter)
elif cookie_val:
# If tags exist in cookie, but not URL, add them to the URL
return redirect(url_for("Airflow.index", tags=cookie_val.split(",")))
if arg_status_filter is None:
cookie_val = flask_session.get(FILTER_STATUS_COOKIE)
if cookie_val:
arg_status_filter = cookie_val
else:
arg_status_filter = "active" if hide_paused_dags_by_default else "all"
flask_session[FILTER_STATUS_COOKIE] = arg_status_filter
else:
status = arg_status_filter.strip().lower()
flask_session[FILTER_STATUS_COOKIE] = status
arg_status_filter = status
dags_per_page = PAGE_SIZE
start = current_page * dags_per_page
end = start + dags_per_page
# Get all the dag id the user could access
filter_dag_ids = get_auth_manager().get_permitted_dag_ids(user=g.user)
with create_session() as session:
# read orm_dags from the db
dags_query = select(DagModel).where(~DagModel.is_subdag, DagModel.is_active)
if arg_search_query:
escaped_arg_search_query = arg_search_query.replace("_", r"\_")
dags_query = dags_query.where(
DagModel.dag_id.ilike("%" + escaped_arg_search_query + "%", escape="\\")
| DagModel._dag_display_property_value.ilike(
"%" + escaped_arg_search_query + "%", escape="\\"
)
| DagModel.owners.ilike("%" + escaped_arg_search_query + "%", escape="\\")
)
if arg_tags_filter:
dags_query = dags_query.where(DagModel.tags.any(DagTag.name.in_(arg_tags_filter)))
dags_query = dags_query.where(DagModel.dag_id.in_(filter_dag_ids))
filtered_dag_count = get_query_count(dags_query, session=session)
if filtered_dag_count == 0 and len(arg_tags_filter):
flash(
"No matching DAG tags found.",
"warning",
)
flask_session[FILTER_TAGS_COOKIE] = None
return redirect(url_for("Airflow.index"))
all_dags = dags_query
active_dags = dags_query.where(~DagModel.is_paused)
paused_dags = dags_query.where(DagModel.is_paused)
# find DAGs which have a RUNNING DagRun
running_dags = dags_query.join(DagRun, DagModel.dag_id == DagRun.dag_id).where(
DagRun.state == DagRunState.RUNNING
)
# find DAGs for which the latest DagRun is FAILED
subq_all = (
select(DagRun.dag_id, func.max(DagRun.start_date).label("start_date"))
.group_by(DagRun.dag_id)
.subquery()
)
subq_failed = (
select(DagRun.dag_id, func.max(DagRun.start_date).label("start_date"))
.where(DagRun.state == DagRunState.FAILED)
.group_by(DagRun.dag_id)
.subquery()
)
subq_join = (
select(subq_all.c.dag_id, subq_all.c.start_date)
.join(
subq_failed,
and_(
subq_all.c.dag_id == subq_failed.c.dag_id,
subq_all.c.start_date == subq_failed.c.start_date,
),
)
.subquery()
)
failed_dags = dags_query.join(subq_join, DagModel.dag_id == subq_join.c.dag_id)
is_paused_count = dict(
session.execute(
all_dags.with_only_columns(DagModel.is_paused, func.count()).group_by(DagModel.is_paused)
).all()
)
status_count_active = is_paused_count.get(False, 0)
status_count_paused = is_paused_count.get(True, 0)
status_count_running = get_query_count(running_dags, session=session)
status_count_failed = get_query_count(failed_dags, session=session)
all_dags_count = status_count_active + status_count_paused
if arg_status_filter == "active":
current_dags = active_dags
num_of_all_dags = status_count_active
elif arg_status_filter == "paused":
current_dags = paused_dags
num_of_all_dags = status_count_paused
elif arg_status_filter == "running":
current_dags = running_dags
num_of_all_dags = status_count_running
elif arg_status_filter == "failed":
current_dags = failed_dags
num_of_all_dags = status_count_failed
else:
current_dags = all_dags
num_of_all_dags = all_dags_count
if arg_sorting_key == "dag_id":
if arg_sorting_direction == "desc":
current_dags = current_dags.order_by(
func.coalesce(DagModel.dag_display_name, DagModel.dag_id).desc()
)
else:
current_dags = current_dags.order_by(
func.coalesce(DagModel.dag_display_name, DagModel.dag_id)
)
elif arg_sorting_key == "last_dagrun":
dag_run_subquery = (
select(
DagRun.dag_id,
sqla.func.max(DagRun.execution_date).label("max_execution_date"),
)
.group_by(DagRun.dag_id)
.subquery()
)
current_dags = current_dags.outerjoin(
dag_run_subquery, and_(dag_run_subquery.c.dag_id == DagModel.dag_id)
)
null_case = case((dag_run_subquery.c.max_execution_date.is_(None), 1), else_=0)
if arg_sorting_direction == "desc":
current_dags = current_dags.order_by(
null_case, dag_run_subquery.c.max_execution_date.desc()
)
else:
current_dags = current_dags.order_by(null_case, dag_run_subquery.c.max_execution_date)
else:
sort_column = DagModel.__table__.c.get(arg_sorting_key)
if sort_column is not None:
null_case = case((sort_column.is_(None), 1), else_=0)
if arg_sorting_direction == "desc":
current_dags = current_dags.order_by(null_case, sort_column.desc())
else:
current_dags = current_dags.order_by(null_case, sort_column)
dags = (
session.scalars(
current_dags.options(joinedload(DagModel.tags)).offset(start).limit(dags_per_page)
)
.unique()
.all()
)
can_create_dag_run = get_auth_manager().is_authorized_dag(
method="POST", access_entity=DagAccessEntity.RUN, user=g.user
)
dataset_triggered_dag_ids = {dag.dag_id for dag in dags if dag.schedule_interval == "Dataset"}
if dataset_triggered_dag_ids:
dataset_triggered_next_run_info = get_dataset_triggered_next_run_info(
dataset_triggered_dag_ids, session=session
)
else:
dataset_triggered_next_run_info = {}
for dag in dags:
dag.can_edit = get_auth_manager().is_authorized_dag(
method="PUT", details=DagDetails(id=dag.dag_id), user=g.user
)
dag.can_trigger = dag.can_edit and can_create_dag_run
dag.can_delete = get_auth_manager().is_authorized_dag(
method="DELETE", details=DagDetails(id=dag.dag_id), user=g.user
)
dagtags = session.execute(select(func.distinct(DagTag.name)).order_by(DagTag.name)).all()
tags = [
{"name": name, "selected": bool(arg_tags_filter and name in arg_tags_filter)}
for (name,) in dagtags
]
owner_links_dict = DagOwnerAttributes.get_all(session)
if get_auth_manager().is_authorized_view(access_view=AccessView.IMPORT_ERRORS):
import_errors = select(ParseImportError).order_by(ParseImportError.id)
can_read_all_dags = get_auth_manager().is_authorized_dag(method="GET")
if not can_read_all_dags:
# if the user doesn't have access to all DAGs, only display errors from visible DAGs
import_errors = import_errors.where(
ParseImportError.filename.in_(
select(DagModel.fileloc).distinct().where(DagModel.dag_id.in_(filter_dag_ids))
)
)
import_errors = session.scalars(import_errors)
for import_error in import_errors:
stacktrace = import_error.stacktrace
if not can_read_all_dags:
# Check if user has read access to all the DAGs defined in the file
file_dag_ids = (
session.query(DagModel.dag_id)
.filter(DagModel.fileloc == import_error.filename)
.all()
)
requests: Sequence[IsAuthorizedDagRequest] = [
{
"method": "GET",
"details": DagDetails(id=dag_id[0]),
}
for dag_id in file_dag_ids
]
if not get_auth_manager().batch_is_authorized_dag(requests):
stacktrace = "REDACTED - you do not have read permission on all DAGs in the file"
flash(
f"Broken DAG: [{import_error.filename}]\r{stacktrace}",
"dag_import_error",
)
from airflow.plugins_manager import import_errors as plugin_import_errors
for filename, stacktrace in plugin_import_errors.items():
flash(
f"Broken plugin: [{filename}] {stacktrace}",
"error",
)
num_of_pages = math.ceil(num_of_all_dags / dags_per_page)
state_color_mapping = State.state_color.copy()
state_color_mapping["null"] = state_color_mapping.pop(None)
page_title = conf.get(section="webserver", key="instance_name", fallback="DAGs")
page_title_has_markup = conf.getboolean(
section="webserver", key="instance_name_has_markup", fallback=False