/
cli.py
4309 lines (3831 loc) · 152 KB
/
cli.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 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 print_function
import errno
import hashlib
import importlib
import itertools
import locale
import logging
import os
import platform
import subprocess
import textwrap
import random
import string
import yaml
from collections import OrderedDict, namedtuple
from importlib import import_module
import getpass
import reprlib
import argparse
import requests
import tenacity
from builtins import input
from tempfile import NamedTemporaryFile
import json
from tabulate import tabulate
import daemon
from daemon.pidfile import TimeoutPIDLockFile
import io
import psutil
import re
import signal
import sys
import threading
import time
import traceback
from typing import Any, cast
import airflow
from airflow import api
from airflow import jobs, settings
from airflow.configuration import conf, get_airflow_home
from airflow.exceptions import AirflowException, AirflowWebServerTimeout
from airflow.executors import get_default_executor
from airflow.models import (
Connection, DagModel, DagBag, DagPickle, TaskInstance, DagRun, Variable, DAG
)
from airflow.ti_deps.dep_context import (DepContext, SCHEDULER_QUEUED_DEPS)
from airflow.typing_compat import Protocol
from airflow.utils import cli as cli_utils, db
from airflow.utils.dot_renderer import render_dag
from airflow.utils.net import get_hostname
from airflow.utils.timezone import parse as parsedate
from airflow.utils.log.logging_mixin import (LoggingMixin, redirect_stderr,
redirect_stdout)
from airflow.www.app import (cached_app, create_app)
from airflow.www_rbac.app import cached_app as cached_app_rbac
from airflow.www_rbac.app import create_app as create_app_rbac
from airflow.www_rbac.app import cached_appbuilder
from airflow.version import version as airflow_version
import pygments
from pygments.formatters.terminal import TerminalFormatter
from pygments.lexers.configs import IniLexer
from sqlalchemy.orm import exc
import six
from six.moves.urllib_parse import urlunparse, urlsplit, urlunsplit
api.load_auth()
api_module = import_module(conf.get('cli', 'api_client')) # type: Any
api_client = api_module.Client(api_base_url=conf.get('cli', 'endpoint_url'),
auth=api.API_AUTH.api_auth.CLIENT_AUTH)
log = logging.getLogger(__name__)
DAGS_FOLDER = settings.DAGS_FOLDER
BUILD_DOCS = "BUILDING_AIRFLOW_DOCS" in os.environ
if BUILD_DOCS:
DAGS_FOLDER = '[AIRFLOW_HOME]/dags'
def sigint_handler(sig, frame):
sys.exit(0)
def sigquit_handler(sig, frame):
"""Helps debug deadlocks by printing stacktraces when this gets a SIGQUIT
e.g. kill -s QUIT <PID> or CTRL+\
"""
print("Dumping stack traces for all threads in PID {}".format(os.getpid()))
id_to_name = dict([(th.ident, th.name) for th in threading.enumerate()])
code = []
for thread_id, stack in sys._current_frames().items():
code.append("\n# Thread: {}({})"
.format(id_to_name.get(thread_id, ""), thread_id))
for filename, line_number, name, line in traceback.extract_stack(stack):
code.append('File: "{}", line {}, in {}'
.format(filename, line_number, name))
if line:
code.append(" {}".format(line.strip()))
print("\n".join(code))
def setup_logging(filename):
root = logging.getLogger()
handler = logging.FileHandler(filename)
formatter = logging.Formatter(settings.SIMPLE_LOG_FORMAT)
handler.setFormatter(formatter)
root.addHandler(handler)
root.setLevel(settings.LOGGING_LEVEL)
return handler.stream
def setup_locations(process, pid=None, stdout=None, stderr=None, log=None):
if not stderr:
stderr = os.path.join(settings.AIRFLOW_HOME, 'airflow-{}.err'.format(process))
if not stdout:
stdout = os.path.join(settings.AIRFLOW_HOME, 'airflow-{}.out'.format(process))
if not log:
log = os.path.join(settings.AIRFLOW_HOME, 'airflow-{}.log'.format(process))
if not pid:
pid = os.path.join(settings.AIRFLOW_HOME, 'airflow-{}.pid'.format(process))
return pid, stdout, stderr, log
def process_subdir(subdir):
if subdir:
subdir = subdir.replace('DAGS_FOLDER', DAGS_FOLDER)
subdir = os.path.abspath(os.path.expanduser(subdir))
return subdir
def get_dag(args):
dagbag = DagBag(process_subdir(args.subdir))
if args.dag_id not in dagbag.dags:
raise AirflowException(
'dag_id could not be found: {}. Either the dag did not exist or it failed to '
'parse.'.format(args.dag_id))
return dagbag.dags[args.dag_id]
def get_dags(args):
if not args.dag_regex:
return [get_dag(args)]
dagbag = DagBag(process_subdir(args.subdir))
matched_dags = [dag for dag in dagbag.dags.values() if re.search(
args.dag_id, dag.dag_id)]
if not matched_dags:
raise AirflowException(
'dag_id could not be found with regex: {}. Either the dag did not exist '
'or it failed to parse.'.format(args.dag_id))
return matched_dags
@cli_utils.action_logging
def backfill(args, dag=None):
logging.basicConfig(
level=settings.LOGGING_LEVEL,
format=settings.SIMPLE_LOG_FORMAT)
dag = dag or get_dag(args)
if not args.start_date and not args.end_date:
raise AirflowException("Provide a start_date and/or end_date")
# If only one date is passed, using same as start and end
args.end_date = args.end_date or args.start_date
args.start_date = args.start_date or args.end_date
if args.task_regex:
dag = dag.sub_dag(
task_regex=args.task_regex,
include_upstream=not args.ignore_dependencies)
run_conf = None
if args.conf:
run_conf = json.loads(args.conf)
if args.dry_run:
print("Dry run of DAG {0} on {1}".format(args.dag_id,
args.start_date))
for task in dag.tasks:
print("Task {0}".format(task.task_id))
ti = TaskInstance(task, args.start_date)
ti.dry_run()
else:
if args.reset_dagruns:
DAG.clear_dags(
[dag],
start_date=args.start_date,
end_date=args.end_date,
confirm_prompt=not args.yes,
include_subdags=False,
)
dag.run(
start_date=args.start_date,
end_date=args.end_date,
mark_success=args.mark_success,
local=args.local,
donot_pickle=(args.donot_pickle or
conf.getboolean('core', 'donot_pickle')),
ignore_first_depends_on_past=args.ignore_first_depends_on_past,
ignore_task_deps=args.ignore_dependencies,
pool=args.pool,
delay_on_limit_secs=args.delay_on_limit,
verbose=args.verbose,
conf=run_conf,
rerun_failed_tasks=args.rerun_failed_tasks,
run_backwards=args.run_backwards
)
@cli_utils.deprecated_action(new_name='dags trigger')
@cli_utils.action_logging
def trigger_dag(args):
"""
Creates a dag run for the specified dag
:param args:
:return:
"""
try:
message = api_client.trigger_dag(dag_id=args.dag_id,
run_id=args.run_id,
conf=args.conf,
execution_date=args.exec_date)
print(message)
except IOError as err:
raise AirflowException(err)
@cli_utils.deprecated_action(new_name='dags delete')
@cli_utils.action_logging
def delete_dag(args):
"""
Deletes all DB records related to the specified dag
:param args:
:return:
"""
if args.yes or input(
"This will drop all existing records related to the specified DAG. "
"Proceed? (y/n)").upper() == "Y":
try:
message = api_client.delete_dag(dag_id=args.dag_id)
print(message)
except IOError as err:
raise AirflowException(err)
else:
print("Bail.")
def _pool_wrapper(args, get=None, set=None, delete=None, export=None, imp=None):
args.get = get
args.set = set
args.delete = delete
args.export = export
setattr(args, 'import', imp)
pool(args)
def pool_list(args):
_pool_wrapper(args)
def pool_get(args):
_pool_wrapper(args, get=args.pool)
def pool_set(args):
_pool_wrapper(args, set=(args.name, args.slots, args.description))
def pool_delete(args):
_pool_wrapper(args, delete=pool.name)
def pool_import(args):
_pool_wrapper(args, imp=args.file)
def pool_export(args):
_pool_wrapper(args, export=args.file)
@cli_utils.deprecated_action(new_name=['pools list', 'pools get', 'pools set', 'pools delete', 'pools import',
'pools export'])
@cli_utils.action_logging
def pool(args):
def _tabulate(pools):
return "\n%s" % tabulate(pools, ['Pool', 'Slots', 'Description'],
tablefmt="fancy_grid")
try:
imp = getattr(args, 'import')
if args.get is not None:
pools = [api_client.get_pool(name=args.get)]
elif args.set:
pools = [api_client.create_pool(name=args.set[0],
slots=args.set[1],
description=args.set[2])]
elif args.delete:
pools = [api_client.delete_pool(name=args.delete)]
elif imp:
if os.path.exists(imp):
pools = pool_import_helper(imp)
else:
print("Missing pools file.")
pools = api_client.get_pools()
elif args.export:
pools = pool_export_helper(args.export)
else:
pools = api_client.get_pools()
except (AirflowException, IOError) as err:
print(err)
else:
print(_tabulate(pools=pools))
def pool_import_helper(filepath):
with open(filepath, 'r') as poolfile:
pl = poolfile.read()
try:
d = json.loads(pl)
except Exception as e:
print("Please check the validity of the json file: " + str(e))
else:
try:
pools = []
n = 0
for k, v in d.items():
if isinstance(v, dict) and len(v) == 2:
pools.append(api_client.create_pool(name=k,
slots=v["slots"],
description=v["description"]))
n += 1
else:
pass
except Exception:
pass
finally:
print("{} of {} pool(s) successfully updated.".format(n, len(d)))
return pools
def pool_export_helper(filepath):
pool_dict = {}
pools = api_client.get_pools()
for pool in pools:
pool_dict[pool[0]] = {"slots": pool[1], "description": pool[2]}
with open(filepath, 'w') as poolfile:
poolfile.write(json.dumps(pool_dict, sort_keys=True, indent=4))
print("{} pools successfully exported to {}".format(len(pool_dict), filepath))
return pools
def _vars_wrapper(args, get=None, set=None, delete=None, export=None, imp=None):
args.get = get
args.set = set
args.delete = delete
args.export = export
setattr(args, 'import', imp)
variables(args)
def variables_get(args):
_vars_wrapper(args, get=args.key)
def variables_delete(args):
_vars_wrapper(args, delete=args.key)
def variables_set(args):
_vars_wrapper(args, set=args.key)
def variables_import(args):
_vars_wrapper(args, imp=args.file)
def variables_export(args):
_vars_wrapper(args, export=args.file)
@cli_utils.deprecated_action(new_name='variables')
@cli_utils.action_logging
def variables(args):
if args.get:
try:
var = Variable.get(args.get,
deserialize_json=args.json,
default_var=args.default)
print(var)
except ValueError as e:
print(e)
if args.delete:
Variable.delete(args.delete)
if args.set:
Variable.set(args.set[0], args.set[1])
# Work around 'import' as a reserved keyword
imp = getattr(args, 'import')
if imp:
if os.path.exists(imp):
import_helper(imp)
else:
print("Missing variables file.")
if args.export:
export_helper(args.export)
if not (args.set or args.get or imp or args.export or args.delete):
# list all variables
with db.create_session() as session:
vars = session.query(Variable)
msg = "\n".join(var.key for var in vars)
print(msg)
def import_helper(filepath):
with open(filepath, 'r') as varfile:
var = varfile.read()
try:
d = json.loads(var)
except Exception:
print("Invalid variables file.")
else:
suc_count = fail_count = 0
for k, v in d.items():
try:
Variable.set(k, v, serialize_json=not isinstance(v, six.string_types))
except Exception as e:
print('Variable import failed: {}'.format(repr(e)))
fail_count += 1
else:
suc_count += 1
print("{} of {} variables successfully updated.".format(suc_count, len(d)))
if fail_count:
print("{} variable(s) failed to be updated.".format(fail_count))
def export_helper(filepath):
var_dict = {}
with db.create_session() as session:
qry = session.query(Variable).all()
d = json.JSONDecoder()
for var in qry:
try:
val = d.decode(var.val)
except Exception:
val = var.val
var_dict[var.key] = val
with open(filepath, 'w') as varfile:
varfile.write(json.dumps(var_dict, sort_keys=True, indent=4))
print("{} variables successfully exported to {}".format(len(var_dict), filepath))
@cli_utils.deprecated_action(new_name='dags pause')
@cli_utils.action_logging
def pause(args):
set_is_paused(True, args)
@cli_utils.deprecated_action(new_name='dags unpause')
@cli_utils.action_logging
def unpause(args):
set_is_paused(False, args)
def set_is_paused(is_paused, args):
DagModel.get_dagmodel(args.dag_id).set_is_paused(
is_paused=is_paused,
)
print("Dag: {}, paused: {}".format(args.dag_id, str(is_paused)))
@cli_utils.deprecated_action(new_name='dags show')
def show_dag(args):
dag = get_dag(args)
dot = render_dag(dag)
if args.save:
filename, _, fileformat = args.save.rpartition('.')
dot.render(filename=filename, format=fileformat, cleanup=True)
print("File {} saved".format(args.save))
elif args.imgcat:
data = dot.pipe(format='png')
try:
proc = subprocess.Popen("imgcat", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
except OSError as e:
if e.errno == errno.ENOENT:
raise AirflowException(
"Failed to execute. Make sure the imgcat executables are on your systems \'PATH\'"
)
else:
raise
out, err = proc.communicate(data)
if out:
print(out.decode('utf-8'))
if err:
print(err.decode('utf-8'))
else:
print(dot.source)
def _run(args, dag, ti):
if args.local:
run_job = jobs.LocalTaskJob(
task_instance=ti,
mark_success=args.mark_success,
pickle_id=args.pickle,
ignore_all_deps=args.ignore_all_dependencies,
ignore_depends_on_past=args.ignore_depends_on_past,
ignore_task_deps=args.ignore_dependencies,
ignore_ti_state=args.force,
pool=args.pool)
run_job.run()
elif args.raw:
ti._run_raw_task(
mark_success=args.mark_success,
job_id=args.job_id,
pool=args.pool,
)
else:
pickle_id = None
if args.ship_dag:
try:
# Running remotely, so pickling the DAG
with db.create_session() as session:
pickle = DagPickle(dag)
session.add(pickle)
pickle_id = pickle.id
# TODO: This should be written to a log
print('Pickled dag {dag} as pickle_id: {pickle_id}'.format(
dag=dag, pickle_id=pickle_id))
except Exception as e:
print('Could not pickle the DAG')
print(e)
raise e
executor = get_default_executor()
executor.start()
print("Sending to executor.")
executor.queue_task_instance(
ti,
mark_success=args.mark_success,
pickle_id=pickle_id,
ignore_all_deps=args.ignore_all_dependencies,
ignore_depends_on_past=args.ignore_depends_on_past,
ignore_task_deps=args.ignore_dependencies,
ignore_ti_state=args.force,
pool=args.pool)
executor.heartbeat()
executor.end()
# Don't warn on deprecation on this one. It is deprecated, but it is used almost exclusively internally, and
# by not warning we have to make a smaller code change.
@cli_utils.action_logging
def run(args, dag=None):
if dag:
args.dag_id = dag.dag_id
# Load custom airflow config
if args.cfg_path:
with open(args.cfg_path, 'r') as conf_file:
conf_dict = json.load(conf_file)
if os.path.exists(args.cfg_path):
os.remove(args.cfg_path)
conf.read_dict(conf_dict, source=args.cfg_path)
settings.configure_vars()
# IMPORTANT, have to use the NullPool, otherwise, each "run" command may leave
# behind multiple open sleeping connections while heartbeating, which could
# easily exceed the database connection limit when
# processing hundreds of simultaneous tasks.
settings.configure_orm(disable_connection_pool=True)
if not args.pickle and not dag:
dag = get_dag(args)
elif not dag:
with db.create_session() as session:
print('Loading pickle id ', args.pickle)
dag_pickle = session.query(DagPickle).filter(DagPickle.id == args.pickle).first()
if not dag_pickle:
raise AirflowException("Who hid the pickle!? [missing pickle]")
dag = dag_pickle.pickle
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
ti.refresh_from_db()
ti.init_run_context(raw=args.raw)
hostname = get_hostname()
print("Running {} on host {}".format(ti, hostname))
if args.interactive:
_run(args, dag, ti)
else:
if settings.DONOT_MODIFY_HANDLERS:
with redirect_stdout(ti.log, logging.INFO), redirect_stderr(ti.log, logging.WARN):
_run(args, dag, ti)
else:
# Get all the Handlers from 'airflow.task' logger
# Add these handlers to the root logger so that we can get logs from
# any custom loggers defined in the DAG
airflow_logger_handlers = logging.getLogger('airflow.task').handlers
root_logger = logging.getLogger()
root_logger_handlers = root_logger.handlers
# Remove all handlers from Root Logger to avoid duplicate logs
for handler in root_logger_handlers:
root_logger.removeHandler(handler)
for handler in airflow_logger_handlers:
root_logger.addHandler(handler)
root_logger.setLevel(logging.getLogger('airflow.task').level)
with redirect_stdout(ti.log, logging.INFO), redirect_stderr(ti.log, logging.WARN):
_run(args, dag, ti)
# We need to restore the handlers to the loggers as celery worker process
# can call this command multiple times,
# so if we don't reset this then logs from next task would go to the wrong place
for handler in airflow_logger_handlers:
root_logger.removeHandler(handler)
for handler in root_logger_handlers:
root_logger.addHandler(handler)
logging.shutdown()
@cli_utils.deprecated_action(new_name='tasks failed-deps')
@cli_utils.action_logging
def task_failed_deps(args):
"""
Returns the unmet dependencies for a task instance from the perspective of the
scheduler (i.e. why a task instance doesn't get scheduled and then queued by the
scheduler, and then run by an executor).
>>> airflow task_failed_deps tutorial sleep 2015-01-01
Task instance dependencies not met:
Dagrun Running: Task instance's dagrun did not exist: Unknown reason
Trigger Rule: Task's trigger rule 'all_success' requires all upstream tasks
to have succeeded, but found 1 non-success(es).
"""
dag = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
dep_context = DepContext(deps=SCHEDULER_QUEUED_DEPS)
failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context))
# TODO, Do we want to print or log this
if failed_deps:
print("Task instance dependencies not met:")
for dep in failed_deps:
print("{}: {}".format(dep.dep_name, dep.reason))
else:
print("Task instance dependencies are all met.")
@cli_utils.deprecated_action(new_name='tasks state')
@cli_utils.action_logging
def task_state(args):
"""
Returns the state of a TaskInstance at the command line.
>>> airflow task_state tutorial sleep 2015-01-01
success
"""
dag = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
print(ti.current_state())
@cli_utils.deprecated_action(new_name='dags state')
@cli_utils.action_logging
def dag_state(args):
"""
Returns the state of a DagRun at the command line.
>>> airflow dag_state tutorial 2015-01-01T00:00:00.000000
running
"""
dag = get_dag(args)
dr = DagRun.find(dag.dag_id, execution_date=args.execution_date)
print(dr[0].state if len(dr) > 0 else None)
@cli_utils.deprecated_action(new_name='dags next-execution')
@cli_utils.action_logging
def next_execution(args):
"""
Returns the next execution datetime of a DAG at the command line.
>>> airflow next_execution tutorial
2018-08-31 10:38:00
"""
dag = get_dag(args)
if dag.is_paused:
print("[INFO] Please be reminded this DAG is PAUSED now.")
if dag.latest_execution_date:
next_execution_dttm = dag.following_schedule(dag.latest_execution_date)
if next_execution_dttm is None:
print("[WARN] No following schedule can be found. " +
"This DAG may have schedule interval '@once' or `None`.")
print(next_execution_dttm)
else:
print("[WARN] Only applicable when there is execution record found for the DAG.")
print(None)
@cli_utils.deprecated_action(new_name='rotate-fernet-key')
@cli_utils.action_logging
def rotate_fernet_key(args):
session = settings.Session()
for conn in session.query(Connection).filter(
Connection.is_encrypted | Connection.is_extra_encrypted):
conn.rotate_fernet_key()
for var in session.query(Variable).filter(Variable.is_encrypted):
var.rotate_fernet_key()
session.commit()
@cli_utils.deprecated_action(new_name=['dags list', 'dags report'])
@cli_utils.action_logging
def list_dags(args):
dagbag = DagBag(process_subdir(args.subdir))
s = textwrap.dedent("""\n
-------------------------------------------------------------------
DAGS
-------------------------------------------------------------------
{dag_list}
""")
dag_list = "\n".join(sorted(dagbag.dags))
print(s.format(dag_list=dag_list))
if getattr(args, 'report', False):
print(dagbag.dagbag_report())
def list_dags_report(args):
args.report = True
args.deprecation_warning = False
list_dags(args)
@cli_utils.deprecated_action(new_name='tasks list')
@cli_utils.action_logging
def list_tasks(args, dag=None):
dag = dag or get_dag(args)
if args.tree:
dag.tree_view()
else:
tasks = sorted([t.task_id for t in dag.tasks])
print("\n".join(sorted(tasks)))
@cli_utils.deprecated_action(new_name='tasks test')
@cli_utils.action_logging
def test(args, dag=None):
# We want log outout from operators etc to show up here. Normally
# airflow.task would redirect to a file, but here we want it to propagate
# up to the normal airflow handler.
dag = dag or get_dag(args)
task = dag.get_task(task_id=args.task_id)
# Add CLI provided task_params to task.params
if args.task_params:
passed_in_params = json.loads(args.task_params)
task.params.update(passed_in_params)
ti = TaskInstance(task, args.execution_date)
try:
logging.getLogger('airflow.task').propagate = True
if args.dry_run:
ti.dry_run()
else:
ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True)
except Exception:
if args.post_mortem:
try:
debugger = importlib.import_module("ipdb")
except ImportError:
debugger = importlib.import_module("pdb")
debugger.post_mortem()
else:
raise
finally:
# Make sure to reset back to normal. When run for CLI this doesn't
# matter, but it does for test suite
logging.getLogger('airflow.task').propagate = False
@cli_utils.deprecated_action(new_name='tasks render')
@cli_utils.action_logging
def render(args):
dag = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
ti.render_templates()
for attr in task.__class__.template_fields:
print(textwrap.dedent("""\
# ----------------------------------------------------------
# property: {}
# ----------------------------------------------------------
{}
""".format(attr, getattr(task, attr))))
@cli_utils.deprecated_action(new_name='tasks clear')
@cli_utils.action_logging
def clear(args):
logging.basicConfig(
level=settings.LOGGING_LEVEL,
format=settings.SIMPLE_LOG_FORMAT)
dags = get_dags(args)
if args.task_regex:
for idx, dag in enumerate(dags):
dags[idx] = dag.sub_dag(
task_regex=args.task_regex,
include_downstream=args.downstream,
include_upstream=args.upstream)
DAG.clear_dags(
dags,
start_date=args.start_date,
end_date=args.end_date,
only_failed=args.only_failed,
only_running=args.only_running,
confirm_prompt=not args.no_confirm,
include_subdags=not args.exclude_subdags,
include_parentdag=not args.exclude_parentdag,
)
class GunicornMonitor(LoggingMixin):
"""
Runs forever, monitoring the child processes of @gunicorn_master_proc and
restarting workers occasionally or when files in the plug-in directory
has been modified.
Each iteration of the loop traverses one edge of this state transition
diagram, where each state (node) represents
[ num_ready_workers_running / num_workers_running ]. We expect most time to
be spent in [n / n]. `bs` is the setting webserver.worker_refresh_batch_size.
The horizontal transition at ? happens after the new worker parses all the
dags (so it could take a while!)
V ────────────────────────────────────────────────────────────────────────┐
[n / n] ──TTIN──> [ [n, n+bs) / n + bs ] ────?───> [n + bs / n + bs] ──TTOU─┘
^ ^───────────────┘
│
│ ┌────────────────v
└──────┴────── [ [0, n) / n ] <─── start
We change the number of workers by sending TTIN and TTOU to the gunicorn
master process, which increases and decreases the number of child workers
respectively. Gunicorn guarantees that on TTOU workers are terminated
gracefully and that the oldest worker is terminated.
:param gunicorn_master_pid: pid of the main Gunicorn process
:param num_workers_expected: Number of workers to run the Gunicorn web server
:param master_timeout: Number of seconds the webserver waits before killing gunicorn master that
doesn't respond
:param worker_refresh_interval: Number of seconds to wait before refreshing a batch of workers.
:param worker_refresh_batch_size: Number of workers to refresh at a time. When set to 0, worker
refresh is disabled. When nonzero, airflow periodically refreshes webserver workers by
bringing up new ones and killing old ones.
:param reload_on_plugin_change: If set to True, Airflow will track files in plugins_follder directory.
When it detects changes, then reload the gunicorn.
"""
def __init__(
self,
gunicorn_master_pid,
num_workers_expected,
master_timeout,
worker_refresh_interval,
worker_refresh_batch_size,
reload_on_plugin_change
):
super(GunicornMonitor, self).__init__()
self.gunicorn_master_proc = psutil.Process(gunicorn_master_pid)
self.num_workers_expected = num_workers_expected
self.master_timeout = master_timeout
self.worker_refresh_interval = worker_refresh_interval
self.worker_refresh_batch_size = worker_refresh_batch_size
self.reload_on_plugin_change = reload_on_plugin_change
self._num_workers_running = 0
self._num_ready_workers_running = 0
self._last_refresh_time = time.time() if worker_refresh_interval > 0 else None
self._last_plugin_state = self._generate_plugin_state() if reload_on_plugin_change else None
self._restart_on_next_plugin_check = False
def _generate_plugin_state(self):
"""
Generate dict of filenames and last modification time of all files in settings.PLUGINS_FOLDER
directory.
"""
if not settings.PLUGINS_FOLDER:
return {}
all_filenames = []
for (root, _, filenames) in os.walk(settings.PLUGINS_FOLDER):
all_filenames.extend(os.path.join(root, f) for f in filenames)
plugin_state = {f: self._get_file_hash(f) for f in sorted(all_filenames)}
return plugin_state
@staticmethod
def _get_file_hash(fname):
"""Calculate MD5 hash for file"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def _get_num_ready_workers_running(self):
"""Returns number of ready Gunicorn workers by looking for READY_PREFIX in process name"""
workers = psutil.Process(self.gunicorn_master_proc.pid).children()
def ready_prefix_on_cmdline(proc):
try:
cmdline = proc.cmdline()
if len(cmdline) > 0: # pylint: disable=len-as-condition
return settings.GUNICORN_WORKER_READY_PREFIX in cmdline[0]
except psutil.NoSuchProcess:
pass
return False
ready_workers = [proc for proc in workers if ready_prefix_on_cmdline(proc)]
return len(ready_workers)
def _get_num_workers_running(self):
"""Returns number of running Gunicorn workers processes"""
workers = psutil.Process(self.gunicorn_master_proc.pid).children()
return len(workers)
def _wait_until_true(self, fn, timeout=0):
"""
Sleeps until fn is true
"""
start_time = time.time()
while not fn():
if 0 < timeout <= time.time() - start_time:
raise AirflowWebServerTimeout(
"No response from gunicorn master within {0} seconds".format(timeout)
)
time.sleep(0.1)
def _spawn_new_workers(self, count):
"""
Send signal to kill the worker.
:param count: The number of workers to spawn
"""
excess = 0
for _ in range(count):
# TTIN: Increment the number of processes by one
self.gunicorn_master_proc.send_signal(signal.SIGTTIN)
excess += 1
self._wait_until_true(
lambda: self.num_workers_expected + excess == self._get_num_workers_running(),
timeout=self.master_timeout
)
def _kill_old_workers(self, count):