response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Run command and returns stdout. | def run_command(command: str) -> str:
"""Run command and returns stdout."""
process = subprocess.Popen(
shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True
)
output, stderr = (stream.decode(sys.getdefaultencoding(), "ignore") for stream in process.communicate())
... |
Get Config option values from Secret Backend. | def _get_config_value_from_secret_backend(config_key: str) -> str | None:
"""Get Config option values from Secret Backend."""
try:
secrets_client = get_custom_secret_backend()
if not secrets_client:
return None
return secrets_client.get_config(config_key)
except Exception... |
Check if the config is a template.
:param configuration_description: description of configuration
:param section: section
:param key: key
:return: True if the config is a template | def _is_template(configuration_description: dict[str, dict[str, Any]], section: str, key: str) -> bool:
"""
Check if the config is a template.
:param configuration_description: description of configuration
:param section: section
:param key: key
:return: True if the config is a template
"""... |
Read Airflow configuration description from YAML file.
:param include_airflow: Include Airflow configs
:param include_providers: Include provider configs
:param selected_provider: If specified, include selected provider only
:return: Python dictionary containing configs & their info | def retrieve_configuration_description(
include_airflow: bool = True,
include_providers: bool = True,
selected_provider: str | None = None,
) -> dict[str, dict[str, Any]]:
"""
Read Airflow configuration description from YAML file.
:param include_airflow: Include Airflow configs
:param inclu... |
Get path to Airflow Home. | def get_airflow_home() -> str:
"""Get path to Airflow Home."""
return expand_env_var(os.environ.get("AIRFLOW_HOME", "~/airflow")) |
Get Path to airflow.cfg path. | def get_airflow_config(airflow_home: str) -> str:
"""Get Path to airflow.cfg path."""
airflow_config_var = os.environ.get("AIRFLOW_CONFIG")
if airflow_config_var is None:
return os.path.join(airflow_home, "airflow.cfg")
return expand_env_var(airflow_config_var) |
Create default config parser based on configuration description.
It creates ConfigParser with all default values retrieved from the configuration description and
expands all the variables from the global and local variables defined in this module.
:param configuration_description: configuration description - retrieve... | def create_default_config_parser(configuration_description: dict[str, dict[str, Any]]) -> ConfigParser:
"""
Create default config parser based on configuration description.
It creates ConfigParser with all default values retrieved from the configuration description and
expands all the variables from th... |
Create parser using the old defaults from Airflow < 2.7.0.
This is used in order to be able to fall-back to those defaults when old version of provider,
not supporting "config contribution" is installed with Airflow 2.7.0+. This "default"
configuration does not support variable expansion, those are pretty much hard-co... | def create_pre_2_7_defaults() -> ConfigParser:
"""
Create parser using the old defaults from Airflow < 2.7.0.
This is used in order to be able to fall-back to those defaults when old version of provider,
not supporting "config contribution" is installed with Airflow 2.7.0+. This "default"
configura... |
Load standard airflow configuration.
In case it finds that the configuration file is missing, it will create it and write the default
configuration values there, based on defaults passed, and will add the comments and examples
from the default configuration.
:param airflow_config_parser: parser to which the configura... | def load_standard_airflow_configuration(airflow_config_parser: AirflowConfigParser):
"""
Load standard airflow configuration.
In case it finds that the configuration file is missing, it will create it and write the default
configuration values there, based on defaults passed, and will add the comments ... |
Load the Airflow config files.
Called for you automatically as part of the Airflow boot process. | def initialize_config() -> AirflowConfigParser:
"""
Load the Airflow config files.
Called for you automatically as part of the Airflow boot process.
"""
airflow_config_parser = AirflowConfigParser()
if airflow_config_parser.getboolean("core", "unit_test_mode"):
airflow_config_parser.loa... |
Historical get. | def get(*args, **kwargs) -> ConfigType | None:
"""Historical get."""
warnings.warn(
"Accessing configuration method 'get' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.get'",
DeprecationW... |
Historical getboolean. | def getboolean(*args, **kwargs) -> bool:
"""Historical getboolean."""
warnings.warn(
"Accessing configuration method 'getboolean' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.getboolean'",
... |
Historical getfloat. | def getfloat(*args, **kwargs) -> float:
"""Historical getfloat."""
warnings.warn(
"Accessing configuration method 'getfloat' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.getfloat'",
Depr... |
Historical getint. | def getint(*args, **kwargs) -> int:
"""Historical getint."""
warnings.warn(
"Accessing configuration method 'getint' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.getint'",
DeprecationWar... |
Historical getsection. | def getsection(*args, **kwargs) -> ConfigOptionsDictType | None:
"""Historical getsection."""
warnings.warn(
"Accessing configuration method 'getsection' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'... |
Historical has_option. | def has_option(*args, **kwargs) -> bool:
"""Historical has_option."""
warnings.warn(
"Accessing configuration method 'has_option' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.has_option'",
... |
Historical remove_option. | def remove_option(*args, **kwargs) -> bool:
"""Historical remove_option."""
warnings.warn(
"Accessing configuration method 'remove_option' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.remove_opt... |
Historical as_dict. | def as_dict(*args, **kwargs) -> ConfigSourcesType:
"""Historical as_dict."""
warnings.warn(
"Accessing configuration method 'as_dict' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.as_dict'",
... |
Historical set. | def set(*args, **kwargs) -> None:
"""Historical set."""
warnings.warn(
"Accessing configuration method 'set' directly from the configuration module is "
"deprecated. Please access the configuration from the 'configuration.conf' object via "
"'conf.set'",
DeprecationWarning,
... |
Ensure that all secrets backends are loaded.
If the secrets_backend_list contains only 2 default backends, reload it. | def ensure_secrets_loaded() -> list[BaseSecretsBackend]:
"""
Ensure that all secrets backends are loaded.
If the secrets_backend_list contains only 2 default backends, reload it.
"""
# Check if the secrets_backend_list contains only 2 default backends
if len(secrets_backend_list) == 2:
... |
Get Secret Backend if defined in airflow.cfg. | def get_custom_secret_backend() -> BaseSecretsBackend | None:
"""Get Secret Backend if defined in airflow.cfg."""
secrets_backend_cls = conf.getimport(section="secrets", key="backend")
if not secrets_backend_cls:
return None
try:
backend_kwargs = conf.getjson(section="secrets", key="ba... |
Initialize secrets backend.
* import secrets backend classes
* instantiate them and return them in a list | def initialize_secrets_backends() -> list[BaseSecretsBackend]:
"""
Initialize secrets backend.
* import secrets backend classes
* instantiate them and return them in a list
"""
backend_list = []
custom_secret_backend = get_custom_secret_backend()
if custom_secret_backend is not None:
... |
Initialize auth manager.
* import user manager class
* instantiate it and return it | def initialize_auth_manager() -> BaseAuthManager:
"""
Initialize auth manager.
* import user manager class
* instantiate it and return it
"""
auth_manager_cls = conf.getimport(section="core", key="auth_manager")
if not auth_manager_cls:
raise AirflowConfigException(
"No... |
Configure & Validate Airflow Logging. | def configure_logging():
"""Configure & Validate Airflow Logging."""
logging_class_path = ""
try:
logging_class_path = conf.get("logging", "logging_config_class")
except AirflowConfigException:
log.debug("Could not find key logging_config_class in config")
if logging_class_path:
... |
Validate the provided Logging Config. | def validate_logging_config(logging_config):
"""Validate the provided Logging Config."""
# Now lets validate the other logging-related settings
task_log_reader = conf.get("logging", "task_log_reader")
logger = logging.getLogger("airflow.task")
def _get_handler(name):
return next((h for h i... |
Check whether a potential object is a subclass of the AirflowPlugin class.
:param plugin_obj: potential subclass of AirflowPlugin
:return: Whether or not the obj is a valid subclass of
AirflowPlugin | def is_valid_plugin(plugin_obj):
"""
Check whether a potential object is a subclass of the AirflowPlugin class.
:param plugin_obj: potential subclass of AirflowPlugin
:return: Whether or not the obj is a valid subclass of
AirflowPlugin
"""
global plugins
if (
inspect.isclas... |
Start plugin load and register it after success initialization.
If plugin is already registered, do nothing.
:param plugin_instance: subclass of AirflowPlugin | def register_plugin(plugin_instance):
"""
Start plugin load and register it after success initialization.
If plugin is already registered, do nothing.
:param plugin_instance: subclass of AirflowPlugin
"""
global plugins
if plugin_instance.name in loaded_plugins:
return
loaded... |
Load and register plugins AirflowPlugin subclasses from the entrypoints.
The entry_point group should be 'airflow.plugins'. | def load_entrypoint_plugins():
"""
Load and register plugins AirflowPlugin subclasses from the entrypoints.
The entry_point group should be 'airflow.plugins'.
"""
global import_errors
log.debug("Loading plugins from entrypoints")
for entry_point, dist in entry_points_with_dist("airflow.pl... |
Load and register Airflow Plugins from plugins directory. | def load_plugins_from_plugin_directory():
"""Load and register Airflow Plugins from plugins directory."""
global import_errors
log.debug("Loading plugins from directory: %s", settings.PLUGINS_FOLDER)
for file_path in find_path_from_directory(settings.PLUGINS_FOLDER, ".airflowignore"):
path = Pa... |
Create new module. | def make_module(name: str, objects: list[Any]):
"""Create new module."""
if not objects:
return None
log.debug("Creating module %s", name)
name = name.lower()
module = types.ModuleType(name)
module._name = name.split(".")[-1] # type: ignore
module._objects = objects # type: ignore
... |
Load plugins from plugins directory and entrypoints.
Plugins are only loaded if they have not been previously loaded. | def ensure_plugins_loaded():
"""
Load plugins from plugins directory and entrypoints.
Plugins are only loaded if they have not been previously loaded.
"""
from airflow.stats import Stats
global plugins, registered_hooks
if plugins is not None:
log.debug("Plugins are already loaded... |
Collect extension points for WEB UI. | def initialize_web_ui_plugins():
"""Collect extension points for WEB UI."""
global plugins
global flask_blueprints
global flask_appbuilder_views
global flask_appbuilder_menu_links
if (
flask_blueprints is not None
and flask_appbuilder_views is not None
and flask_appbuild... |
Create modules for loaded extension from custom task instance dependency rule plugins. | def initialize_ti_deps_plugins():
"""Create modules for loaded extension from custom task instance dependency rule plugins."""
global registered_ti_dep_classes
if registered_ti_dep_classes is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException(... |
Create modules for loaded extension from extra operators links plugins. | def initialize_extra_operators_links_plugins():
"""Create modules for loaded extension from extra operators links plugins."""
global global_operator_extra_links
global operator_extra_links
global registered_operator_link_classes
if (
global_operator_extra_links is not None
and opera... |
Collect timetable classes registered by plugins. | def initialize_timetables_plugins():
"""Collect timetable classes registered by plugins."""
global timetable_classes
if timetable_classes is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
log.debug("Initialize ... |
Integrate executor plugins to the context. | def integrate_executor_plugins() -> None:
"""Integrate executor plugins to the context."""
global plugins
global executors_modules
if executors_modules is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
log.... |
Integrates macro plugins. | def integrate_macros_plugins() -> None:
"""Integrates macro plugins."""
global plugins
global macros_modules
from airflow import macros
if macros_modules is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
... |
Add listeners from plugins. | def integrate_listener_plugins(listener_manager: ListenerManager) -> None:
"""Add listeners from plugins."""
global plugins
ensure_plugins_loaded()
if plugins:
for plugin in plugins:
if plugin.name is None:
raise AirflowPluginException("Invalid plugin name")
... |
Dump plugins attributes.
:param attrs_to_dump: A list of plugin attributes to dump | def get_plugin_info(attrs_to_dump: Iterable[str] | None = None) -> list[dict[str, Any]]:
"""
Dump plugins attributes.
:param attrs_to_dump: A list of plugin attributes to dump
"""
ensure_plugins_loaded()
integrate_executor_plugins()
integrate_macros_plugins()
initialize_web_ui_plugins()... |
Collect priority weight strategy classes registered by plugins. | def initialize_priority_weight_strategy_plugins():
"""Collect priority weight strategy classes registered by plugins."""
global priority_weight_strategy_classes
if priority_weight_strategy_classes is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginE... |
Allow altering tasks after they are loaded in the DagBag.
It allows administrator to rewire some task's parameters. Alternatively you can raise
``AirflowClusterPolicyViolation`` exception to stop DAG from being executed.
Here are a few examples of how this can be useful:
* You could enforce a specific queue (say th... | def task_policy(task: BaseOperator) -> None:
"""
Allow altering tasks after they are loaded in the DagBag.
It allows administrator to rewire some task's parameters. Alternatively you can raise
``AirflowClusterPolicyViolation`` exception to stop DAG from being executed.
Here are a few examples of ... |
Allow altering DAGs after they are loaded in the DagBag.
It allows administrator to rewire some DAG's parameters.
Alternatively you can raise ``AirflowClusterPolicyViolation`` exception
to stop DAG from being executed.
Here are a few examples of how this can be useful:
* You could enforce default user for DAGs
* Che... | def dag_policy(dag: DAG) -> None:
"""
Allow altering DAGs after they are loaded in the DagBag.
It allows administrator to rewire some DAG's parameters.
Alternatively you can raise ``AirflowClusterPolicyViolation`` exception
to stop DAG from being executed.
Here are a few examples of how this c... |
Allow altering task instances before being queued by the Airflow scheduler.
This could be used, for instance, to modify the task instance during retries.
:param task_instance: task instance to be mutated | def task_instance_mutation_hook(task_instance: TaskInstance) -> None:
"""
Allow altering task instances before being queued by the Airflow scheduler.
This could be used, for instance, to modify the task instance during retries.
:param task_instance: task instance to be mutated
""" |
Mutate pod before scheduling.
This setting allows altering ``kubernetes.client.models.V1Pod`` object before they are passed to the
Kubernetes client for scheduling.
This could be used, for instance, to add sidecar or init containers to every worker pod launched by
KubernetesExecutor or KubernetesPodOperator. | def pod_mutation_hook(pod) -> None:
"""
Mutate pod before scheduling.
This setting allows altering ``kubernetes.client.models.V1Pod`` object before they are passed to the
Kubernetes client for scheduling.
This could be used, for instance, to add sidecar or init containers to every worker pod launc... |
Inject airflow context vars into default airflow context vars.
This setting allows getting the airflow context vars, which are key value pairs. They are then injected
to default airflow context vars, which in the end are available as environment variables when running
tasks dag_id, task_id, execution_date, dag_run_id... | def get_airflow_context_vars(context) -> dict[str, str]: # type: ignore[empty-body]
"""
Inject airflow context vars into default airflow context vars.
This setting allows getting the airflow context vars, which are key value pairs. They are then injected
to default airflow context vars, which in the ... |
Allow for dynamic control of the DAG file parsing timeout based on the DAG file path.
It is useful when there are a few DAG files requiring longer parsing times, while others do not.
You can control them separately instead of having one value for all DAG files.
If the return value is less than or equal to 0, it means... | def get_dagbag_import_timeout(dag_file_path: str) -> int | float: # type: ignore[empty-body]
"""
Allow for dynamic control of the DAG file parsing timeout based on the DAG file path.
It is useful when there are a few DAG files requiring longer parsing times, while others do not.
You can control them s... |
Turn the functions from airflow_local_settings module into a custom/local plugin.
Allows plugin-registered functions to co-operate with pluggy/setuptool
entrypoint plugins of the same methods.
Airflow local settings will be "win" (i.e. they have the final say) as they are the last plugin
registered.
:meta private: | def make_plugin_from_local_settings(pm: pluggy.PluginManager, module, names: set[str]):
"""
Turn the functions from airflow_local_settings module into a custom/local plugin.
Allows plugin-registered functions to co-operate with pluggy/setuptool
entrypoint plugins of the same methods.
Airflow local... |
Verify the correct placeholder prefix.
If the given field_behaviors dict contains a placeholder's node, and there
are placeholders for extra fields (i.e. anything other than the built-in conn
attrs), and if those extra fields are unprefixed, then add the prefix.
The reason we need to do this is, all custom conn field... | def _ensure_prefix_for_placeholders(field_behaviors: dict[str, Any], conn_type: str):
"""
Verify the correct placeholder prefix.
If the given field_behaviors dict contains a placeholder's node, and there
are placeholders for extra fields (i.e. anything other than the built-in conn
attrs), and if th... |
Create JSON schema validator from the provider_info.schema.json. | def _create_provider_info_schema_validator():
"""Create JSON schema validator from the provider_info.schema.json."""
import jsonschema
schema = _read_schema_from_resources_or_local_file("provider_info.schema.json")
cls = jsonschema.validators.validator_for(schema)
validator = cls(schema)
return... |
Create JSON schema validator from the customized_form_field_behaviours.schema.json. | def _create_customized_form_field_behaviours_schema_validator():
"""Create JSON schema validator from the customized_form_field_behaviours.schema.json."""
import jsonschema
schema = _read_schema_from_resources_or_local_file("customized_form_field_behaviours.schema.json")
cls = jsonschema.validators.val... |
Log debug imports from sources. | def log_debug_import_from_sources(class_name, e, provider_package):
"""Log debug imports from sources."""
log.debug(
"Optional feature disabled on exception when importing '%s' from '%s' package",
class_name,
provider_package,
exc_info=e,
) |
Log optional feature disabled. | def log_optional_feature_disabled(class_name, e, provider_package):
"""Log optional feature disabled."""
log.debug(
"Optional feature disabled on exception when importing '%s' from '%s' package",
class_name,
provider_package,
exc_info=e,
)
log.info(
"Optional prov... |
Log import warning. | def log_import_warning(class_name, e, provider_package):
"""Log import warning."""
log.warning(
"Exception when importing '%s' from '%s' package",
class_name,
provider_package,
exc_info=e,
) |
Perform coherence check on provider classes.
For apache-airflow providers - it checks if it starts with appropriate package. For all providers
it tries to import the provider - checking that there are no exceptions during importing.
It logs appropriate warning in case it detects any problems.
:param provider_package:... | def _correctness_check(provider_package: str, class_name: str, provider_info: ProviderInfo) -> Any:
"""
Perform coherence check on provider classes.
For apache-airflow providers - it checks if it starts with appropriate package. For all providers
it tries to import the provider - checking that there ar... |
Decorate and cache provider info.
Decorator factory that create decorator that caches initialization of provider's parameters
:param cache_name: Name of the cache | def provider_info_cache(cache_name: str) -> Callable[[T], T]:
"""
Decorate and cache provider info.
Decorator factory that create decorator that caches initialization of provider's parameters
:param cache_name: Name of the cache
"""
def provider_info_cache_decorator(func: T):
@wraps(fu... |
Print rich and visible warnings. | def custom_show_warning(message, category, filename, lineno, file=None, line=None):
"""Print rich and visible warnings."""
# Delay imports until we need it
from rich.markup import escape
msg = f"[bold]{line}" if line else f"[bold][yellow]{filename}:{lineno}"
msg += f" {category.__name__}[/bold]: {e... |
Replace ``warnings.showwarning``, returning the original.
This is useful since we want to "reset" the ``showwarning`` hook on exit to
avoid lazy-loading issues. If a warning is emitted after Python cleaned up
the import system, we would no longer be able to import ``rich``. | def replace_showwarning(replacement):
"""Replace ``warnings.showwarning``, returning the original.
This is useful since we want to "reset" the ``showwarning`` hook on exit to
avoid lazy-loading issues. If a warning is emitted after Python cleaned up
the import system, we would no longer be able to impo... |
Configure Global Variables from airflow.cfg. | def configure_vars():
"""Configure Global Variables from airflow.cfg."""
global SQL_ALCHEMY_CONN
global DAGS_FOLDER
global PLUGINS_FOLDER
global DONOT_MODIFY_HANDLERS
SQL_ALCHEMY_CONN = conf.get("database", "SQL_ALCHEMY_CONN")
DAGS_FOLDER = os.path.expanduser(conf.get("core", "DAGS_FOLDER")... |
Configure ORM using SQLAlchemy. | def configure_orm(disable_connection_pool=False, pool_class=None):
"""Configure ORM using SQLAlchemy."""
from airflow.utils.log.secrets_masker import mask_secret
if (
SQL_ALCHEMY_CONN
and SQL_ALCHEMY_CONN.startswith("sqlite")
and not SQL_ALCHEMY_CONN.startswith("sqlite:////")
... |
Prepare SQLAlchemy engine args. | def prepare_engine_args(disable_connection_pool=False, pool_class=None):
"""Prepare SQLAlchemy engine args."""
default_args = {}
for dialect, default in DEFAULT_ENGINE_ARGS.items():
if SQL_ALCHEMY_CONN.startswith(dialect):
default_args = default.copy()
break
engine_args... |
Properly close pooled database connections. | def dispose_orm():
"""Properly close pooled database connections."""
log.debug("Disposing DB connection pool (PID %s)", os.getpid())
global engine
global Session
if Session is not None: # type: ignore[truthy-function]
Session.remove()
Session = None
if engine:
engine.d... |
Properly close database connections and re-configure ORM. | def reconfigure_orm(disable_connection_pool=False, pool_class=None):
"""Properly close database connections and re-configure ORM."""
dispose_orm()
configure_orm(disable_connection_pool=disable_connection_pool, pool_class=pool_class) |
Register Adapters and DB Converters. | def configure_adapters():
"""Register Adapters and DB Converters."""
from pendulum import DateTime as Pendulum
if SQL_ALCHEMY_CONN.startswith("sqlite"):
from sqlite3 import register_adapter
register_adapter(Pendulum, lambda val: val.isoformat(" "))
if SQL_ALCHEMY_CONN.startswith("mys... |
Validate ORM Session. | def validate_session():
"""Validate ORM Session."""
global engine
worker_precheck = conf.getboolean("celery", "worker_precheck")
if not worker_precheck:
return True
else:
check_session = sessionmaker(bind=engine)
session = check_session()
try:
session.exe... |
Any additional configuration (register callback) for airflow.utils.action_loggers module. | def configure_action_logging() -> None:
"""Any additional configuration (register callback) for airflow.utils.action_loggers module.""" |
Ensure certain subfolders of AIRFLOW_HOME are on the classpath. | def prepare_syspath():
"""Ensure certain subfolders of AIRFLOW_HOME are on the classpath."""
if DAGS_FOLDER not in sys.path:
sys.path.append(DAGS_FOLDER)
# Add ./config/ for loading custom log parsers etc, or
# airflow_local_settings etc.
config_path = os.path.join(AIRFLOW_HOME, "config")
... |
Get session timeout configs and handle outdated configs gracefully. | def get_session_lifetime_config():
"""Get session timeout configs and handle outdated configs gracefully."""
session_lifetime_minutes = conf.get("webserver", "session_lifetime_minutes", fallback=None)
session_lifetime_days = conf.get("webserver", "session_lifetime_days", fallback=None)
uses_deprecated_l... |
Import airflow_local_settings.py files to allow overriding any configs in settings.py file. | def import_local_settings():
"""Import airflow_local_settings.py files to allow overriding any configs in settings.py file."""
try:
import airflow_local_settings
except ModuleNotFoundError as e:
if e.name == "airflow_local_settings":
log.debug("No airflow_local_settings to import... |
Initialize Airflow with all the settings from this file. | def initialize():
"""Initialize Airflow with all the settings from this file."""
configure_vars()
prepare_syspath()
configure_policy_plugin_manager()
# Load policy plugins _before_ importing airflow_local_settings, as Pluggy uses LIFO and we want anything
# in airflow_local_settings to take prec... |
Date filter. | def ds_filter(value: datetime.date | datetime.time | None) -> str | None:
"""Date filter."""
if value is None:
return None
return value.strftime("%Y-%m-%d") |
Date filter without dashes. | def ds_nodash_filter(value: datetime.date | datetime.time | None) -> str | None:
"""Date filter without dashes."""
if value is None:
return None
return value.strftime("%Y%m%d") |
Timestamp filter. | def ts_filter(value: datetime.date | datetime.time | None) -> str | None:
"""Timestamp filter."""
if value is None:
return None
return value.isoformat() |
Timestamp filter without dashes. | def ts_nodash_filter(value: datetime.date | datetime.time | None) -> str | None:
"""Timestamp filter without dashes."""
if value is None:
return None
return value.strftime("%Y%m%dT%H%M%S") |
Timestamp filter with timezone. | def ts_nodash_with_tz_filter(value: datetime.date | datetime.time | None) -> str | None:
"""Timestamp filter with timezone."""
if value is None:
return None
return value.isoformat().replace("-", "").replace(":", "") |
Load authentication backends. | def load_auth():
"""Load authentication backends."""
auth_backends = "airflow.api.auth.backend.default"
try:
auth_backends = conf.get("api", "auth_backends")
except AirflowConfigException:
pass
backends = []
try:
for backend in auth_backends.split(","):
auth ... |
Initialize authentication backend. | def init_app(_):
"""Initialize authentication backend.""" |
Decorate functions that require authentication. | def requires_authentication(function: T):
"""Decorate functions that require authentication."""
@wraps(function)
def decorated(*args, **kwargs):
return function(*args, **kwargs)
return cast(T, decorated) |
Initialize authentication. | def init_app(_):
"""Initialize authentication.""" |
Decorate functions that require authentication. | def requires_authentication(function: T):
"""Decorate functions that require authentication."""
@wraps(function)
def decorated(*args, **kwargs):
return Response("Forbidden", 403)
return cast(T, decorated) |
Initialize application with kerberos. | def init_app(app):
"""Initialize application with kerberos."""
hostname = app.config.get("SERVER_NAME")
if not hostname:
hostname = getfqdn()
log.info("Kerberos: hostname %s", hostname)
service = "airflow"
_KERBEROS_SERVICE.service_name = f"{service}@{hostname}"
if "KRB5_KTNAME" ... |
Indicate that authorization is required. | def _unauthorized():
"""Indicate that authorization is required."""
return Response("Unauthorized", 401, {"WWW-Authenticate": "Negotiate"}) |
Decorate functions that require authentication with Kerberos. | def requires_authentication(function: T, find_user: Callable[[str], BaseUser] | None = None):
"""Decorate functions that require authentication with Kerberos."""
if not find_user:
warnings.warn(
"This module is deprecated. Please use "
"`airflow.providers.fab.auth_manager.api.aut... |
Initialize authentication backend. | def init_app(_):
"""Initialize authentication backend.""" |
Decorate functions that require authentication. | def requires_authentication(function: T):
"""Decorate functions that require authentication."""
@wraps(function)
def decorated(*args, **kwargs):
if not get_auth_manager().is_logged_in():
return Response("Unauthorized", 401, {})
return function(*args, **kwargs)
return cast(T... |
Return current API Client based on current Airflow configuration. | def get_current_api_client() -> Client:
"""Return current API Client based on current Airflow configuration."""
api_module = import_module(conf.get_mandatory_value("cli", "api_client"))
auth_backends = api.load_auth()
session = None
for backend in auth_backends:
session_factory = getattr(bac... |
Get the health for Airflow metadatabase, scheduler and triggerer. | def get_airflow_health() -> dict[str, Any]:
"""Get the health for Airflow metadatabase, scheduler and triggerer."""
metadatabase_status = HEALTHY
latest_scheduler_heartbeat = None
latest_triggerer_heartbeat = None
latest_dag_processor_heartbeat = None
scheduler_status = UNHEALTHY
triggerer_s... |
Delete a DAG by a dag_id.
:param dag_id: the dag_id of the DAG to delete
:param keep_records_in_log: whether keep records of the given dag_id
in the Log table in the backend database (for reasons like auditing).
The default value is True.
:param session: session used
:return count of deleted dags | def delete_dag(dag_id: str, keep_records_in_log: bool = True, session: Session = NEW_SESSION) -> int:
"""
Delete a DAG by a dag_id.
:param dag_id: the dag_id of the DAG to delete
:param keep_records_in_log: whether keep records of the given dag_id
in the Log table in the backend database (for r... |
Infers from data intervals which DAG runs need to be created and does so.
:param dag: The DAG to create runs for.
:param infos: List of logical dates and data intervals to evaluate.
:param state: The state to set the dag run to
:param run_type: The prefix will be used to construct dag run id: ``{run_id_prefix}__{execu... | def _create_dagruns(
dag: DAG,
infos: Iterable[_DagRunInfo],
state: DagRunState,
run_type: DagRunType,
) -> Iterable[DagRun]:
"""Infers from data intervals which DAG runs need to be created and does so.
:param dag: The DAG to create runs for.
:param infos: List of logical dates and data int... |
Set the state of a task instance and if needed its relatives.
Can set state for future tasks (calculated from run_id) and retroactively
for past tasks. Will verify integrity of past dag runs in order to create
tasks that did not exist. It will not create dag runs that are missing
on the schedule (but it will, as for s... | def set_state(
*,
tasks: Collection[Operator | tuple[Operator, int]],
run_id: str | None = None,
execution_date: datetime | None = None,
upstream: bool = False,
downstream: bool = False,
future: bool = False,
past: bool = False,
state: TaskInstanceState = TaskInstanceState.SUCCESS,
... |
Get *all* tasks of the sub dags. | def all_subdag_tasks_query(
sub_dag_run_ids: list[str],
session: SASession,
state: TaskInstanceState,
confirmed_dates: Iterable[datetime],
):
"""Get *all* tasks of the sub dags."""
qry_sub_dag = (
select(TaskInstance)
.where(TaskInstance.dag_id.in_(sub_dag_run_ids), TaskInstance.... |
Get all tasks of the main dag that will be affected by a state change. | def get_all_dag_task_query(
dag: DAG,
session: SASession,
state: TaskInstanceState,
task_ids: list[str | tuple[str, int]],
run_ids: Iterable[str],
):
"""Get all tasks of the main dag that will be affected by a state change."""
qry_dag = select(TaskInstance).where(
TaskInstance.dag_id... |
Go through subdag operators and create dag runs.
We only work within the scope of the subdag. A subdag does not propagate to
its parent DAG, but parent propagates to subdags. | def _iter_subdag_run_ids(
dag: DAG,
session: SASession,
state: DagRunState,
task_ids: list[str],
commit: bool,
confirmed_infos: Iterable[_DagRunInfo],
) -> Iterator[str]:
"""Go through subdag operators and create dag runs.
We only work within the scope of the subdag. A subdag does not p... |
Verify integrity of dag_runs.
:param dag_runs: dag runs to verify
:param commit: whether dag runs state should be updated
:param state: state of the dag_run to set if commit is True
:param session: session to use
:param current_task: current task | def verify_dagruns(
dag_runs: Iterable[DagRun],
commit: bool,
state: DagRunState,
session: SASession,
current_task: Operator,
):
"""Verify integrity of dag_runs.
:param dag_runs: dag runs to verify
:param commit: whether dag runs state should be updated
:param state: state of the da... |
Yield task ids and optionally ancestor and descendant ids. | def find_task_relatives(tasks, downstream, upstream):
"""Yield task ids and optionally ancestor and descendant ids."""
for item in tasks:
if isinstance(item, tuple):
task, map_index = item
yield task.task_id, map_index
else:
task = item
yield ta... |
Return DAG execution dates. | def get_execution_dates(
dag: DAG, execution_date: datetime, future: bool, past: bool, *, session: SASession = NEW_SESSION
) -> list[datetime]:
"""Return DAG execution dates."""
latest_execution_date = dag.get_latest_execution_date(session=session)
if latest_execution_date is None:
raise ValueEr... |
Return DAG executions' run_ids. | def get_run_ids(dag: DAG, run_id: str, future: bool, past: bool, session: SASession = NEW_SESSION):
"""Return DAG executions' run_ids."""
last_dagrun = dag.get_last_dagrun(include_externally_triggered=True, session=session)
current_dagrun = dag.get_dagrun(run_id=run_id, session=session)
first_dagrun = s... |
Set dag run state in the DB.
:param dag_id: dag_id of target dag run
:param run_id: run id of target dag run
:param state: target state
:param session: database session | def _set_dag_run_state(dag_id: str, run_id: str, state: DagRunState, session: SASession):
"""
Set dag run state in the DB.
:param dag_id: dag_id of target dag run
:param run_id: run id of target dag run
:param state: target state
:param session: database session
"""
dag_run = session.ex... |
Set the dag run's state to success.
Set for a specific execution date and its task instances to success.
:param dag: the DAG of which to alter state
:param execution_date: the execution date from which to start looking(deprecated)
:param run_id: the run_id to start looking from
:param commit: commit DAG and tasks to ... | def set_dag_run_state_to_success(
*,
dag: DAG,
execution_date: datetime | None = None,
run_id: str | None = None,
commit: bool = False,
session: SASession = NEW_SESSION,
) -> list[TaskInstance]:
"""
Set the dag run's state to success.
Set for a specific execution date and its task i... |
Set the dag run's state to failed.
Set for a specific execution date and its task instances to failed.
:param dag: the DAG of which to alter state
:param execution_date: the execution date from which to start looking(deprecated)
:param run_id: the DAG run_id to start looking from
:param commit: commit DAG and tasks t... | def set_dag_run_state_to_failed(
*,
dag: DAG,
execution_date: datetime | None = None,
run_id: str | None = None,
commit: bool = False,
session: SASession = NEW_SESSION,
) -> list[TaskInstance]:
"""
Set the dag run's state to failed.
Set for a specific execution date and its task ins... |
Set the dag run for a specific execution date to running.
:param dag: the DAG of which to alter state
:param execution_date: the execution date from which to start looking
:param run_id: the id of the DagRun
:param commit: commit DAG and tasks to be altered to the database
:param session: database session
:return: If ... | def __set_dag_run_state_to_running_or_queued(
*,
new_state: DagRunState,
dag: DAG,
execution_date: datetime | None = None,
run_id: str | None = None,
commit: bool = False,
session: SASession,
) -> list[TaskInstance]:
"""
Set the dag run for a specific execution date to running.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.