response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Set a state of task instances.
def post_set_task_instances_state(*, dag_id: str, session: Session = NEW_SESSION) -> APIResponse: """Set a state of task instances.""" body = get_json_request_dict() try: data = set_task_instance_state_form.load(body) except ValidationError as err: raise BadRequest(detail=str(err.message...
Set the note for a Mapped Task instance.
def set_mapped_task_instance_note( *, dag_id: str, dag_run_id: str, task_id: str, map_index: int ) -> APIResponse: """Set the note for a Mapped Task instance.""" return set_task_instance_note(dag_id=dag_id, dag_run_id=dag_run_id, task_id=task_id, map_index=map_index)
Update the state of a task instance.
def patch_task_instance( *, dag_id: str, dag_run_id: str, task_id: str, map_index: int = -1, session: Session = NEW_SESSION ) -> APIResponse: """Update the state of a task instance.""" body = get_json_request_dict() try: data = set_single_task_instance_state_form.load(body) except Validation...
Update the state of a mapped task instance.
def patch_mapped_task_instance( *, dag_id: str, dag_run_id: str, task_id: str, map_index: int, session: Session = NEW_SESSION ) -> APIResponse: """Update the state of a mapped task instance.""" return patch_task_instance( dag_id=dag_id, dag_run_id=dag_run_id, task_id=task_id, map_index=map_index, se...
Set the note for a Task instance. This supports both Mapped and non-Mapped Task instances.
def set_task_instance_note( *, dag_id: str, dag_run_id: str, task_id: str, map_index: int = -1, session: Session = NEW_SESSION ) -> APIResponse: """Set the note for a Task instance. This supports both Mapped and non-Mapped Task instances.""" try: post_body = set_task_instance_note_form_schema.load(g...
Delete variable.
def delete_variable(*, variable_key: str) -> Response: """Delete variable.""" if Variable.delete(variable_key) == 0: raise NotFound("Variable not found") return Response(status=HTTPStatus.NO_CONTENT)
Get a variable by key.
def get_variable(*, variable_key: str, session: Session = NEW_SESSION) -> Response: """Get a variable by key.""" var = session.scalar(select(Variable).where(Variable.key == variable_key).limit(1)) if not var: raise NotFound("Variable not found", detail="Variable does not exist") return variable_...
Get all variable values.
def get_variables( *, limit: int | None, order_by: str = "id", offset: int | None = None, session: Session = NEW_SESSION, ) -> Response: """Get all variable values.""" total_entries = session.execute(select(func.count(Variable.id))).scalar() to_replace = {"value": "val"} allowed_sort...
Update a variable by key.
def patch_variable( *, variable_key: str, update_mask: UpdateMask = None, session: Session = NEW_SESSION, ) -> Response: """Update a variable by key.""" try: data = variable_schema.load(get_json_request_dict()) except ValidationError as err: raise BadRequest("Invalid Variable...
Create a variable.
def post_variables() -> Response: """Create a variable.""" try: data = variable_schema.load(get_json_request_dict()) except ValidationError as err: raise BadRequest("Invalid Variable schema", detail=str(err.messages)) Variable.set(data["key"], data["val"], description=data.get("descripti...
Get version information.
def get_version() -> APIResponse: """Get version information.""" airflow_version = airflow.__version__ git_version = get_airflow_git_version() version_info = VersionInfo(version=airflow_version, git_version=git_version) return version_info_schema.dump(version_info)
Get all XCom values.
def get_xcom_entries( *, dag_id: str, dag_run_id: str, task_id: str, map_index: int | None = None, xcom_key: str | None = None, limit: int | None, offset: int | None = None, session: Session = NEW_SESSION, ) -> APIResponse: """Get all XCom values.""" query = select(XCom) ...
Get an XCom entry.
def get_xcom_entry( *, dag_id: str, task_id: str, dag_run_id: str, xcom_key: str, map_index: int = -1, deserialize: bool = False, session: Session = NEW_SESSION, ) -> APIResponse: """Get an XCom entry.""" if deserialize: if not conf.getboolean("api", "enable_xcom_deseria...
Set process title. This is used by airflow.cli.commands.internal_api_command to track the status of the worker.
def post_worker_init(_): """ Set process title. This is used by airflow.cli.commands.internal_api_command to track the status of the worker. """ old_title = setproctitle.getproctitle() setproctitle.setproctitle(settings.GUNICORN_WORKER_READY_PREFIX + old_title)
Allow methods to be executed in database isolation mode. If [core]database_access_isolation is true then such method are not executed locally, but instead RPC call is made to Database API (aka Internal API). This makes some components decouple from direct Airflow database access. Each decorated method must be present ...
def internal_api_call(func: Callable[PS, RT]) -> Callable[PS, RT]: """ Allow methods to be executed in database isolation mode. If [core]database_access_isolation is true then such method are not executed locally, but instead RPC call is made to Database API (aka Internal API). This makes some componen...
Handle Internal API /internal_api/v1/rpcapi endpoint.
def internal_airflow_api(body: dict[str, Any]) -> APIResponse: """Handle Internal API /internal_api/v1/rpcapi endpoint.""" log.debug("Got request") json_rpc = body.get("jsonrpc") if json_rpc != "2.0": return log_and_build_error_response(message="Expected jsonrpc 2.0 request.", status=400) m...
Return the map associating a method to a FAB action.
def get_fab_action_from_method_map(): """Return the map associating a method to a FAB action.""" return _MAP_METHOD_NAME_TO_FAB_ACTION_NAME
Return the map associating a FAB action to a method.
def get_method_from_fab_action_map(): """Return the map associating a FAB action to a method.""" return { **{v: k for k, v in _MAP_METHOD_NAME_TO_FAB_ACTION_NAME.items()}, }
Create a lazy loader for command.
def lazy_load_command(import_path: str) -> Callable: """Create a lazy loader for command.""" _, _, name = import_path.rpartition(".") def command(*args, **kwargs): func = import_string(import_path) return func(*args, **kwargs) command.__name__ = name return command
Define a positive int type for an argument.
def positive_int(*, allow_zero): """Define a positive int type for an argument.""" def _check(value): try: value = int(value) if allow_zero and value == 0: return value if value > 0: return value except ValueError: ...
Parse comma-separated list and returns list of string (strips whitespace).
def string_list_type(val): """Parse comma-separated list and returns list of string (strips whitespace).""" return [x.strip() for x in val.split(",")]
Lower arg.
def string_lower_type(val): """Lower arg.""" if not val: return return val.strip().lower()
Create and returns command line argument parser.
def get_parser(dag_parser: bool = False) -> argparse.ArgumentParser: """Create and returns command line argument parser.""" parser = DefaultHelpParser(prog="airflow", formatter_class=AirflowHelpFormatter) subparsers = parser.add_subparsers(dest="subcommand", metavar="GROUP_OR_COMMAND") subparsers.requir...
Sort subcommand optional args, keep positional args.
def _sort_args(args: Iterable[Arg]) -> Iterable[Arg]: """Sort subcommand optional args, keep positional args.""" def get_long_option(arg: Arg): """Get long option from Arg.flags.""" return arg.flags[0] if len(arg.flags) == 1 else arg.flags[1] positional, optional = partition(lambda x: x.fl...
Check whether a file IO is stdout. The intended use case for this helper is to check whether an argument parsed with argparse.FileType points to stdout (by setting the path to ``-``). This is why there is no equivalent for stderr; argparse does not allow using it. .. warning:: *fileio* must be open for this check to ...
def is_stdout(fileio: IOBase) -> bool: """Check whether a file IO is stdout. The intended use case for this helper is to check whether an argument parsed with argparse.FileType points to stdout (by setting the path to ``-``). This is why there is no equivalent for stderr; argparse does not allow using ...
Start Flower, Celery monitoring tool.
def flower(args): """Start Flower, Celery monitoring tool.""" # This needs to be imported locally to not trigger Providers Manager initialization from airflow.providers.celery.executors.celery_executor import app as celery_app options = [ "flower", conf.get("celery", "BROKER_URL"), ...
Start serve_logs sub-process.
def _serve_logs(skip_serve_logs: bool = False): """Start serve_logs sub-process.""" sub_proc = None if skip_serve_logs is False: sub_proc = Process(target=serve_logs) sub_proc.start() try: yield finally: if sub_proc: sub_proc.terminate()
Reconfigure the logger. * remove any previously configured handlers * logs of severity error, and above goes to stderr, * logs of severity lower than error goes to stdout.
def logger_setup_handler(logger, **kwargs): """ Reconfigure the logger. * remove any previously configured handlers * logs of severity error, and above goes to stderr, * logs of severity lower than error goes to stdout. """ if conf.getboolean("logging", "celery_stdout_stderr_separation", fa...
Start Airflow Celery worker.
def worker(args): """Start Airflow Celery worker.""" # This needs to be imported locally to not trigger Providers Manager initialization from airflow.providers.celery.executors.celery_executor import app as celery_app # Disable connection pool so that celery worker does not hold an unnecessary db conne...
Send SIGTERM to Celery worker.
def stop_worker(args): """Send SIGTERM to Celery worker.""" # Read PID from file if args.pid: pid_file_path = args.pid else: pid_file_path, _, _, _ = setup_locations(process=WORKER_PROCESS_NAME) pid = read_pid_from_pidfile(pid_file_path) # Send SIGTERM if pid: wor...
Display cheat-sheet.
def cheat_sheet(args): """Display cheat-sheet.""" display_commands_index()
Display list of all commands.
def display_commands_index(): """Display list of all commands.""" def display_recursive( prefix: list[str], commands: Iterable[GroupCommand | ActionCommand], help_msg: str | None = None, ): actions: list[ActionCommand] = [] groups: list[GroupCommand] = [] for...
Show current application configuration.
def show_config(args): """Show current application configuration.""" with StringIO() as output: conf.write( output, section=args.section, include_examples=args.include_examples or args.defaults, include_descriptions=args.include_descriptions or args.defaul...
Get one value from configuration.
def get_value(args): """Get one value from configuration.""" # while this will make get_value quite a bit slower we must initialize configuration # for providers because we do not know what sections and options will be available after # providers are initialized. Theoretically Providers might add new se...
Get a connection.
def connections_get(args): """Get a connection.""" try: conn = BaseHook.get_connection(args.conn_id) except AirflowNotFoundException: raise SystemExit("Connection not found.") AirflowConsole().print_as( data=[conn], output=args.output, mapper=_connection_mapper, ...
List all connections at the command line.
def connections_list(args): """List all connections at the command line.""" with create_session() as session: query = select(Connection) if args.conn_id: query = query.where(Connection.conn_id == args.conn_id) query = session.scalars(query) conns = query.all() ...
Check if a URI is valid, by checking if scheme (conn_type) provided.
def _valid_uri(uri: str) -> bool: """Check if a URI is valid, by checking if scheme (conn_type) provided.""" return urlsplit(uri).scheme != ""
Return connection types available.
def _get_connection_types() -> list[str]: """Return connection types available.""" _connection_types = [] providers_manager = ProvidersManager() for connection_type, provider_info in providers_manager.hooks.items(): if provider_info: _connection_types.append(connection_type) ret...
Export all connections to a file.
def connections_export(args): """Export all connections to a file.""" file_formats = [".yaml", ".json", ".env"] if args.format: warnings.warn( "Option `--format` is deprecated. Use `--file-format` instead.", DeprecationWarning, stacklevel=3 ) if args.format and args.file_for...
Add new connection.
def connections_add(args): """Add new connection.""" has_uri = bool(args.conn_uri) has_json = bool(args.conn_json) has_type = bool(args.conn_type) # Validate connection-id try: helpers.validate_key(args.conn_id, max_length=200) except Exception as e: raise SystemExit(f"Could...
Delete connection from DB.
def connections_delete(args): """Delete connection from DB.""" with create_session() as session: try: to_delete = session.scalars(select(Connection).where(Connection.conn_id == args.conn_id)).one() except exc.NoResultFound: raise SystemExit(f"Did not find a connection wit...
Import connections from a file.
def connections_import(args): """Import connections from a file.""" if os.path.exists(args.file): _import_helper(args.file, args.overwrite) else: raise SystemExit("Missing connections file.")
Load connections from a file and save them to the DB. :param overwrite: Whether to skip or overwrite on collision.
def _import_helper(file_path: str, overwrite: bool) -> None: """Load connections from a file and save them to the DB. :param overwrite: Whether to skip or overwrite on collision. """ connections_dict = load_connections_dict(file_path) with create_session() as session: for conn_id, conn in c...
Test an Airflow connection.
def connections_test(args) -> None: """Test an Airflow connection.""" console = AirflowConsole() if conf.get("core", "test_connection", fallback="Disabled").lower().strip() != "enabled": console.print( "[bold yellow]\nTesting connections is disabled in Airflow configuration. " ...
Run the command in a daemon process if daemon mode enabled or within this process if not. :param args: the set of arguments passed to the original CLI command :param process_name: process name used in naming log and PID files for the daemon :param callback: the actual command to run with or without daemon context :par...
def run_command_with_daemon_option( *, args: Namespace, process_name: str, callback: Callable, should_setup_logging: bool = False, umask: str = settings.DAEMON_UMASK, pid_file: str | None = None, ): """Run the command in a daemon process if daemon mode enabled or within this process if n...
Create backfill job or dry run for a DAG or list of DAGs using regex.
def dag_backfill(args, dag: list[DAG] | DAG | None = None) -> None: """Create backfill job or dry run for a DAG or list of DAGs using regex.""" logging.basicConfig(level=settings.LOGGING_LEVEL, format=settings.SIMPLE_LOG_FORMAT) signal.signal(signal.SIGTERM, sigint_handler) if args.ignore_first_depends_...
Create a dag run for the specified dag.
def dag_trigger(args) -> None: """Create a dag run for the specified dag.""" api_client = get_current_api_client() try: message = api_client.trigger_dag( dag_id=args.dag_id, run_id=args.run_id, conf=args.conf, execution_date=args.exec_date, ...
Delete all DB records related to the specified dag.
def dag_delete(args) -> None: """Delete all DB records related to the specified dag.""" api_client = get_current_api_client() if ( args.yes or input("This will drop all existing records related to the specified DAG. Proceed? (y/n)").upper() == "Y" ): try: mess...
Pauses a DAG.
def dag_pause(args) -> None: """Pauses a DAG.""" set_is_paused(True, args)
Unpauses a DAG.
def dag_unpause(args) -> None: """Unpauses a DAG.""" set_is_paused(False, args)
Set is_paused for DAG by a given dag_id.
def set_is_paused(is_paused: bool, args) -> None: """Set is_paused for DAG by a given dag_id.""" should_apply = True dags = [ dag for dag in get_dags(args.subdir, dag_id=args.dag_id, use_regex=args.treat_dag_id_as_regex) if is_paused != dag.get_is_paused() ] if not dags: ...
Display DAG dependencies, save to file or show as imgcat image.
def dag_dependencies_show(args) -> None: """Display DAG dependencies, save to file or show as imgcat image.""" dot = render_dag_dependencies(SerializedDagModel.get_dag_dependencies()) filename = args.save imgcat = args.imgcat if filename and imgcat: raise SystemExit( "Option --s...
Display DAG or saves its graphic representation to the file.
def dag_show(args) -> None: """Display DAG or saves its graphic representation to the file.""" dag = get_dag(args.subdir, args.dag_id) dot = render_dag(dag) filename = args.save imgcat = args.imgcat if filename and imgcat: raise SystemExit( "Option --save and --imgcat are mu...
Return a dagbag dag details dict.
def _get_dagbag_dag_details(dag: DAG) -> dict: """Return a dagbag dag details dict.""" return { "dag_id": dag.dag_id, "dag_display_name": dag.dag_display_name, "root_dag_id": dag.parent_dag.dag_id if dag.parent_dag else None, "is_paused": dag.get_is_paused(), "is_active":...
Return the state (and conf if exists) of a DagRun at the command line. >>> airflow dags state tutorial 2015-01-01T00:00:00.000000 running >>> airflow dags state a_dag_with_conf_passed 2015-01-01T00:00:00.000000 failed, {"name": "bob", "age": "42"}
def dag_state(args, session: Session = NEW_SESSION) -> None: """ Return the state (and conf if exists) of a DagRun at the command line. >>> airflow dags state tutorial 2015-01-01T00:00:00.000000 running >>> airflow dags state a_dag_with_conf_passed 2015-01-01T00:00:00.000000 failed, {"name": "b...
Return the next execution datetime of a DAG at the command line. >>> airflow dags next-execution tutorial 2018-08-31 10:38:00
def dag_next_execution(args) -> None: """ Return the next execution datetime of a DAG at the command line. >>> airflow dags next-execution tutorial 2018-08-31 10:38:00 """ dag = get_dag(args.subdir, args.dag_id) with create_session() as session: last_parsed_dag: DagModel = session....
Display dags with or without stats at the command line.
def dag_list_dags(args, session=NEW_SESSION) -> None: """Display dags with or without stats at the command line.""" cols = args.columns if args.columns else [] invalid_cols = [c for c in cols if c not in dag_schema.fields] valid_cols = [c for c in cols if c in dag_schema.fields] if invalid_cols: ...
Get DAG details given a DAG id.
def dag_details(args, session=NEW_SESSION): """Get DAG details given a DAG id.""" dag = DagModel.get_dagmodel(args.dag_id, session=session) if not dag: raise SystemExit(f"DAG: {args.dag_id} does not exist in 'dag' table") dag_detail = dag_schema.dump(dag) if args.output in ["table", "plain...
Display dags with import errors on the command line.
def dag_list_import_errors(args) -> None: """Display dags with import errors on the command line.""" dagbag = DagBag(process_subdir(args.subdir)) data = [] for filename, errors in dagbag.import_errors.items(): data.append({"filepath": filename, "error": errors}) AirflowConsole().print_as( ...
Display dagbag stats at the command line.
def dag_report(args) -> None: """Display dagbag stats at the command line.""" dagbag = DagBag(process_subdir(args.subdir)) AirflowConsole().print_as( data=dagbag.dagbag_stats, output=args.output, mapper=lambda x: { "file": x.file, "duration": x.duration, ...
List latest n jobs.
def dag_list_jobs(args, dag: DAG | None = None, session: Session = NEW_SESSION) -> None: """List latest n jobs.""" queries = [] if dag: args.dag_id = dag.dag_id if args.dag_id: dag = DagModel.get_dagmodel(args.dag_id, session=session) if not dag: raise SystemExit(...
List dag runs for a given DAG.
def dag_list_dag_runs(args, dag: DAG | None = None, session: Session = NEW_SESSION) -> None: """List dag runs for a given DAG.""" if dag: args.dag_id = dag.dag_id else: dag = DagModel.get_dagmodel(args.dag_id, session=session) if not dag: raise SystemExit(f"DAG: {args...
Execute one single DagRun for a given DAG and execution date.
def dag_test(args, dag: DAG | None = None, session: Session = NEW_SESSION) -> None: """Execute one single DagRun for a given DAG and execution date.""" run_conf = None if args.conf: try: run_conf = json.loads(args.conf) except ValueError as e: raise SystemExit(f"Confi...
Serialize a DAG instance.
def dag_reserialize(args, session: Session = NEW_SESSION) -> None: """Serialize a DAG instance.""" session.execute(delete(SerializedDagModel).execution_options(synchronize_session=False)) if not args.clear_only: dagbag = DagBag(process_subdir(args.subdir)) dagbag.sync_to_db(session=session)
Create DagFileProcessorProcess instance.
def _create_dag_processor_job_runner(args: Any) -> DagProcessorJobRunner: """Create DagFileProcessorProcess instance.""" processor_timeout_seconds: int = conf.getint("core", "dag_file_processor_timeout") processor_timeout = timedelta(seconds=processor_timeout_seconds) return DagProcessorJobRunner( ...
Start Airflow Dag Processor Job.
def dag_processor(args): """Start Airflow Dag Processor Job.""" if not conf.getboolean("scheduler", "standalone_dag_processor"): raise SystemExit("The option [scheduler/standalone_dag_processor] must be True.") sql_conn: str = conf.get("database", "sql_alchemy_conn").lower() if sql_conn.starts...
Initialize the metadata database.
def initdb(args): """Initialize the metadata database.""" warnings.warn( "`db init` is deprecated. Use `db migrate` instead to migrate the db and/or " "airflow connections create-default-connections to create the default connections", DeprecationWarning, stacklevel=2, ) ...
Reset the metadata database.
def resetdb(args): """Reset the metadata database.""" print(f"DB: {settings.engine.url!r}") if not (args.yes or input("This will drop existing tables if they exist. Proceed? (y/n)").upper() == "Y"): raise SystemExit("Cancelled") db.resetdb(skip_init=args.skip_init)
Upgrades the metadata database.
def upgradedb(args): """Upgrades the metadata database.""" warnings.warn("`db upgrade` is deprecated. Use `db migrate` instead.", DeprecationWarning, stacklevel=2) migratedb(args)
Recursively search for the revision of the given version. This searches REVISION_HEADS_MAP for the revision of the given version, recursively searching for the previous version if the given version is not found.
def get_version_revision(version: str, recursion_limit=10) -> str | None: """ Recursively search for the revision of the given version. This searches REVISION_HEADS_MAP for the revision of the given version, recursively searching for the previous version if the given version is not found. """ i...
Migrates the metadata database.
def migratedb(args): """Migrates the metadata database.""" print(f"DB: {settings.engine.url!r}") if args.to_revision and args.to_version: raise SystemExit("Cannot supply both `--to-revision` and `--to-version`.") if args.from_version and args.from_revision: raise SystemExit("Cannot supp...
Downgrades the metadata database.
def downgrade(args): """Downgrades the metadata database.""" if args.to_revision and args.to_version: raise SystemExit("Cannot supply both `--to-revision` and `--to-version`.") if args.from_version and args.from_revision: raise SystemExit("`--from-revision` may not be combined with `--from-...
Wait for all airflow migrations to complete. Used for launching airflow in k8s.
def check_migrations(args): """Wait for all airflow migrations to complete. Used for launching airflow in k8s.""" db.check_migrations(timeout=args.migration_wait_timeout)
Run a shell that allows to access metadata database.
def shell(args): """Run a shell that allows to access metadata database.""" url = settings.engine.url print(f"DB: {url!r}") if url.get_backend_name() == "mysql": with NamedTemporaryFile(suffix="my.cnf") as f: content = textwrap.dedent( f""" [client] ...
Run a check command that checks if db is available.
def check(args): """Run a check command that checks if db is available.""" if InternalApiConfig.get_use_internal_api(): return retries: int = args.retry retry_delay: int = args.retry_delay def _warn_remaining_retries(retrystate: RetryCallState): remain = retries - retrystate.attempt...
Purges old records in metadata database.
def cleanup_tables(args): """Purges old records in metadata database.""" run_cleanup( table_names=args.tables, dry_run=args.dry_run, clean_before_timestamp=args.clean_before_timestamp, verbose=args.verbose, confirm=not args.yes, skip_archive=args.skip_archive, ...
Export archived records from metadata database.
def export_archived(args): """Export archived records from metadata database.""" export_archived_records( export_format=args.export_format, output_path=args.output_path, table_names=args.tables, drop_archives=args.drop_archives, needs_confirm=not args.yes, )
Drop archived tables from metadata database.
def drop_archived(args): """Drop archived tables from metadata database.""" drop_archived_tables( table_names=args.tables, needs_confirm=not args.yes, )
Upload text file to File.io service and return link.
def _upload_text_to_fileio(content): """Upload text file to File.io service and return link.""" resp = httpx.post("https://file.io", content=content) if resp.status_code not in [200, 201]: print(resp.json()) raise FileIoException("Failed to send report to file.io service.") try: ...
Show information related to Airflow, system and other.
def show_info(args): """Show information related to Airflow, system and other.""" # Enforce anonymization, when file_io upload is tuned on. anonymizer = PiiAnonymizer() if args.anonymize or args.file_io else NullAnonymizer() info = AirflowInfo(anonymizer) if args.file_io: _send_report_to_fil...
Start Airflow Internal API.
def internal_api(args): """Start Airflow Internal API.""" print(settings.HEADER) access_logfile = args.access_logfile or "-" error_logfile = args.error_logfile or "-" access_logformat = args.access_logformat num_workers = args.workers worker_timeout = args.worker_timeout if args.debug:...
Create a new instance of Airflow Internal API app.
def create_app(config=None, testing=False): """Create a new instance of Airflow Internal API app.""" flask_app = Flask(__name__) flask_app.config["APP_NAME"] = "Airflow Internal API" flask_app.config["TESTING"] = testing flask_app.config["SQLALCHEMY_DATABASE_URI"] = conf.get("database", "SQL_ALCHEM...
Return cached instance of Airflow Internal API app.
def cached_app(config=None, testing=False): """Return cached instance of Airflow Internal API app.""" global app if not app: app = create_app(config=config, testing=testing) return app
Check if job(s) are still alive.
def check(args, session: Session = NEW_SESSION) -> None: """Check if job(s) are still alive.""" if args.allow_multiple and args.limit <= 1: raise SystemExit("To use option --allow-multiple, you must set the limit to a value greater than 1.") if args.hostname and args.local: raise SystemExit...
Start a kerberos ticket renewer.
def kerberos(args): """Start a kerberos ticket renewer.""" print(settings.HEADER) mode = KerberosMode.STANDARD if args.one_time: mode = KerberosMode.ONE_TIME run_command_with_daemon_option( args=args, process_name="kerberos", callback=lambda: krb.run(principal=args....
Generate yaml files for each task in the DAG. Used for testing output of KubernetesExecutor.
def generate_pod_yaml(args): """Generate yaml files for each task in the DAG. Used for testing output of KubernetesExecutor.""" execution_date = args.execution_date dag = get_dag(subdir=args.subdir, dag_id=args.dag_id) yaml_output_path = args.output_path dr = DagRun(dag.dag_id, execution_date=execut...
Clean up k8s pods in evicted/failed/succeeded/pending states.
def cleanup_pods(args): """Clean up k8s pods in evicted/failed/succeeded/pending states.""" namespace = args.namespace min_pending_minutes = args.min_pending_minutes # protect newly created pods from deletion if min_pending_minutes < 5: min_pending_minutes = 5 # https://kubernetes.io/d...
Delete a namespaced pod. Helper Function for cleanup_pods.
def _delete_pod(name, namespace): """ Delete a namespaced pod. Helper Function for cleanup_pods. """ kube_client = get_kube_client() delete_options = client.V1DeleteOptions() print(f'Deleting POD "{name}" from "{namespace}" namespace') api_response = kube_client.delete_namespaced_pod(na...
Check command value and raise error if value is in removed command.
def check_legacy_command(action, value): """Check command value and raise error if value is in removed command.""" new_command = COMMAND_MAP.get(value) if new_command is not None: msg = f"`airflow {value}` command, has been removed, please use `airflow {new_command}`" raise ArgumentError(act...
Dump plugins information.
def dump_plugins(args): """Dump plugins information.""" plugins_info: list[dict[str, str]] = get_plugin_info() if not plugins_manager.plugins: print("No plugins loaded") return # Remove empty info if args.output == "table": # We can do plugins_info[0] as the element it will ...
Display info of all the pools.
def pool_list(args): """Display info of all the pools.""" api_client = get_current_api_client() pools = api_client.get_pools() _show_pools(pools=pools, output=args.output)
Display pool info by a given name.
def pool_get(args): """Display pool info by a given name.""" api_client = get_current_api_client() try: pools = [api_client.get_pool(name=args.pool)] _show_pools(pools=pools, output=args.output) except PoolNotFound: raise SystemExit(f"Pool {args.pool} does not exist")
Create new pool with a given name and slots.
def pool_set(args): """Create new pool with a given name and slots.""" api_client = get_current_api_client() api_client.create_pool( name=args.pool, slots=args.slots, description=args.description, include_deferred=args.include_deferred ) print(f"Pool {args.pool} created")
Delete pool by a given name.
def pool_delete(args): """Delete pool by a given name.""" api_client = get_current_api_client() try: api_client.delete_pool(name=args.pool) print(f"Pool {args.pool} deleted") except PoolNotFound: raise SystemExit(f"Pool {args.pool} does not exist")
Import pools from the file.
def pool_import(args): """Import pools from the file.""" if not os.path.exists(args.file): raise SystemExit(f"Missing pools file {args.file}") pools, failed = pool_import_helper(args.file) if failed: raise SystemExit(f"Failed to update pool(s): {', '.join(failed)}") print(f"Uploaded...
Export all the pools to the file.
def pool_export(args): """Export all the pools to the file.""" pools = pool_export_helper(args.file) print(f"Exported {len(pools)} pools to {args.file}")
Help import pools from the json file.
def pool_import_helper(filepath): """Help import pools from the json file.""" api_client = get_current_api_client() with open(filepath) as poolfile: data = poolfile.read() try: pools_json = json.loads(data) except JSONDecodeError as e: raise SystemExit(f"Invalid json file: {...
Help export all the pools to the json file.
def pool_export_helper(filepath): """Help export all the pools to the json file.""" api_client = get_current_api_client() pool_dict = {} pools = api_client.get_pools() for pool in pools: pool_dict[pool[0]] = {"slots": pool[1], "description": pool[2], "include_deferred": pool[3]} with ope...
Get a provider info.
def provider_get(args): """Get a provider info.""" providers = ProvidersManager().providers if args.provider_name in providers: provider_version = providers[args.provider_name].version provider_info = providers[args.provider_name].data if args.full: provider_info["descri...
List all providers at the command line.
def providers_list(args): """List all providers at the command line.""" AirflowConsole().print_as( data=list(ProvidersManager().providers.values()), output=args.output, mapper=lambda x: { "package_name": x.data["package-name"], "description": _remove_rst_syntax(x....