response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Generate documentation; used by Sphinx argparse. | def get_parser() -> argparse.ArgumentParser:
"""Generate documentation; used by Sphinx argparse."""
from airflow.cli.cli_parser import AirflowHelpFormatter, _add_command
parser = DefaultHelpParser(prog="airflow", formatter_class=AirflowHelpFormatter)
subparsers = parser.add_subparsers(dest="subcommand"... |
Return entity type.
:param resource_type: Resource type.
Example: Airflow::Action, Airflow::Group, Airflow::Variable, Airflow::User. | def get_entity_type(resource_type: AvpEntities) -> str:
"""
Return entity type.
:param resource_type: Resource type.
Example: Airflow::Action, Airflow::Group, Airflow::Variable, Airflow::User.
"""
return AVP_PREFIX_ENTITIES + resource_type.value |
Return action id.
Convention for action ID is <resource_type>.<method>. Example: Variable.GET.
:param resource_type: Resource type.
:param method: Resource method. | def get_action_id(resource_type: AvpEntities, method: ResourceMethod | str):
"""
Return action id.
Convention for action ID is <resource_type>.<method>. Example: Variable.GET.
:param resource_type: Resource type.
:param method: Resource method.
"""
return f"{resource_type.value}.{method}" |
Initialize Amazon Verified Permissions resources. | def init_avp(args):
"""Initialize Amazon Verified Permissions resources."""
client = _get_client()
# Create the policy store if needed
policy_store_id, is_new_policy_store = _create_policy_store(client, args)
if not is_new_policy_store:
print(
f"Since an existing policy store w... |
Update Amazon Verified Permissions policy store schema. | def update_schema(args):
"""Update Amazon Verified Permissions policy store schema."""
client = _get_client()
_set_schema(client, args.policy_store_id, args) |
Return Amazon Verified Permissions client. | def _get_client():
"""Return Amazon Verified Permissions client."""
region_name = conf.get(CONF_SECTION_NAME, CONF_REGION_NAME_KEY)
return boto3.client("verifiedpermissions", region_name=region_name) |
Create if needed the policy store.
This function returns two elements:
- the policy store ID
- whether the policy store ID returned refers to a newly created policy store. | def _create_policy_store(client: BaseClient, args) -> tuple[str | None, bool]:
"""
Create if needed the policy store.
This function returns two elements:
- the policy store ID
- whether the policy store ID returned refers to a newly created policy store.
"""
paginator = client.get_paginator... |
Set the policy store schema. | def _set_schema(client: BaseClient, policy_store_id: str, args) -> None:
"""Set the policy store schema."""
if args.dry_run:
print(f"Dry run, not updating the schema of the policy store with ID '{policy_store_id}'.")
return
schema_path = Path(__file__).parents[1] / "avp" / "schema.json"
... |
Initialize AWS IAM Identity Center resources. | def init_idc(args):
"""Initialize AWS IAM Identity Center resources."""
client = _get_client()
# Create the instance if needed
instance_arn = _create_instance(client, args)
# Create the application if needed
_create_application(client, instance_arn, args)
if not args.dry_run:
prin... |
Return AWS IAM Identity Center client. | def _get_client():
"""Return AWS IAM Identity Center client."""
region_name = conf.get(CONF_SECTION_NAME, CONF_REGION_NAME_KEY)
return boto3.client("sso-admin", region_name=region_name) |
Create if needed AWS IAM Identity Center instance. | def _create_instance(client: BaseClient, args) -> str | None:
"""Create if needed AWS IAM Identity Center instance."""
instances = client.list_instances()
if args.verbose:
log.debug("Instances found: %s", instances)
if len(instances["Instances"]) > 0:
print(
f"There is alr... |
Create if needed AWS IAM identity Center application. | def _create_application(client: BaseClient, instance_arn: str | None, args) -> str | None:
"""Create if needed AWS IAM identity Center application."""
paginator = client.get_paginator("list_applications")
pages = paginator.paginate(InstanceArn=instance_arn or "")
applications = [application for page in ... |
Recursively unpack a nested dict and return it as a flat dict.
For example, _flatten_dict({'a': 'a', 'b': 'b', 'c': {'d': 'd'}}) returns {'a': 'a', 'b': 'b', 'd': 'd'}. | def _recursive_flatten_dict(nested_dict):
"""
Recursively unpack a nested dict and return it as a flat dict.
For example, _flatten_dict({'a': 'a', 'b': 'b', 'c': {'d': 'd'}}) returns {'a': 'a', 'b': 'b', 'd': 'd'}.
"""
items = []
for key, value in nested_dict.items():
if isinstance(val... |
Convert "assign_public_ip" from True/False to ENABLE/DISABLE. | def parse_assign_public_ip(assign_public_ip):
"""Convert "assign_public_ip" from True/False to ENABLE/DISABLE."""
return "ENABLED" if assign_public_ip == "True" else "DISABLED" |
Accept a potentially nested dictionary and recursively convert all keys into camelCase. | def camelize_dict_keys(nested_dict) -> dict:
"""Accept a potentially nested dictionary and recursively convert all keys into camelCase."""
result = {}
for key, value in nested_dict.items():
new_key = camelize(key, uppercase_first_letter=False)
if isinstance(value, dict) and (key.lower() != ... |
Calculate the exponential backoff (in seconds) until the next attempt.
:param attempt_number: Number of attempts since last success.
:param max_delay: Maximum delay in seconds between retries. Default 120.
:param exponent_base: Exponent base to calculate delay. Default 4. | def calculate_next_attempt_delay(
attempt_number: int,
max_delay: int = 60 * 2,
exponent_base: int = 4,
) -> timedelta:
"""
Calculate the exponential backoff (in seconds) until the next attempt.
:param attempt_number: Number of attempts since last success.
:param max_delay: Maximum delay in... |
Retry a callable function with exponential backoff between attempts if it raises an exception.
:param last_attempt_time: Timestamp of last attempt call.
:param attempts_since_last_successful: Number of attempts since last success.
:param callable_function: Callable function that will be called if enough time has passe... | def exponential_backoff_retry(
last_attempt_time: datetime,
attempts_since_last_successful: int,
callable_function: Callable,
max_delay: int = 60 * 2,
max_attempts: int = -1,
exponent_base: int = 4,
) -> None:
"""
Retry a callable function with exponential backoff between attempts if it ... |
Resolve custom SessionFactory class. | def resolve_session_factory() -> type[BaseSessionFactory]:
"""Resolve custom SessionFactory class."""
clazz = conf.getimport("aws", "session_factory", fallback=None)
if not clazz:
return BaseSessionFactory
if not issubclass(clazz, BaseSessionFactory):
raise TypeError(
f"Your ... |
For compatibility with airflow.contrib.hooks.aws_hook. | def _parse_s3_config(config_file_name: str, config_format: str | None = "boto", profile: str | None = None):
"""For compatibility with airflow.contrib.hooks.aws_hook."""
from airflow.providers.amazon.aws.utils.connection_wrapper import _parse_s3_config
return _parse_s3_config(
config_file_name=conf... |
Check if exception is related to ECS resource quota (CPU, MEM). | def should_retry(exception: Exception):
"""Check if exception is related to ECS resource quota (CPU, MEM)."""
if isinstance(exception, EcsOperatorError):
return any(
quota_reason in failure["reason"]
for quota_reason in ["RESOURCE:MEMORY", "RESOURCE:CPU"]
for failure... |
Check if exception is related to ENI (Elastic Network Interfaces). | def should_retry_eni(exception: Exception):
"""Check if exception is related to ENI (Elastic Network Interfaces)."""
if isinstance(exception, EcsTaskFailToStart):
return any(
eni_reason in exception.message
for eni_reason in ["network interface provisioning", "ResourceInitializat... |
Provide a bucket name taken from the connection if no bucket name has been passed to the function. | def provide_bucket_name(func: Callable) -> Callable:
"""Provide a bucket name taken from the connection if no bucket name has been passed to the function."""
if hasattr(func, "_unify_bucket_name_and_key_wrapped"):
logger.warning("`unify_bucket_name_and_key` should wrap `provide_bucket_name`.")
funct... |
Provide a bucket name taken from the connection if no bucket name has been passed to the function. | def provide_bucket_name_async(func: Callable) -> Callable:
"""Provide a bucket name taken from the connection if no bucket name has been passed to the function."""
function_signature = signature(func)
@wraps(func)
async def wrapper(*args: Any, **kwargs: Any) -> Any:
bound_args = function_signat... |
Unify bucket name and key in case no bucket name and at least a key has been passed to the function. | def unify_bucket_name_and_key(func: Callable) -> Callable:
"""Unify bucket name and key in case no bucket name and at least a key has been passed to the function."""
function_signature = signature(func)
@wraps(func)
def wrapper(*args, **kwargs) -> Callable:
bound_args = function_signature.bind(... |
Given callable ``f``, find index in ``arr`` to minimize ``f(arr[i])``.
None is returned if ``arr`` is empty. | def argmin(arr, f: Callable) -> int | None:
"""Given callable ``f``, find index in ``arr`` to minimize ``f(arr[i])``.
None is returned if ``arr`` is empty.
"""
min_value = None
min_idx = None
for idx, item in enumerate(arr):
if item is not None:
if min_value is None or f(... |
Check if training job's secondary status message has changed.
:param current_job_description: Current job description, returned from DescribeTrainingJob call.
:param prev_job_description: Previous job description, returned from DescribeTrainingJob call.
:return: Whether the secondary status message of a training job ... | def secondary_training_status_changed(current_job_description: dict, prev_job_description: dict) -> bool:
"""Check if training job's secondary status message has changed.
:param current_job_description: Current job description, returned from DescribeTrainingJob call.
:param prev_job_description: Previous j... |
Format string containing start time and the secondary training job status message.
:param job_description: Returned response from DescribeTrainingJob call
:param prev_description: Previous job description from DescribeTrainingJob call
:return: Job status string to be printed. | def secondary_training_status_message(
job_description: dict[str, list[Any]], prev_description: dict | None
) -> str:
"""Format string containing start time and the secondary training job status message.
:param job_description: Returned response from DescribeTrainingJob call
:param prev_description: Pr... |
Retrieve the S3 URI to EMR Serverless Job logs.
Any EMR Serverless job may have a different S3 logging location (or none), which is an S3 URI.
The logging location is then {s3_uri}/applications/{application_id}/jobs/{job_run_id}. | def get_serverless_log_uri(*, s3_log_uri: str, application_id: str, job_run_id: str) -> str:
"""
Retrieve the S3 URI to EMR Serverless Job logs.
Any EMR Serverless job may have a different S3 logging location (or none), which is an S3 URI.
The logging location is then {s3_uri}/applications/{application... |
Retrieve the URL to EMR Serverless dashboard.
The URL is a one-use, ephemeral link that expires in 1 hour and is accessible without authentication.
Either an AWS connection ID or existing EMR Serverless client must be passed.
If the connection ID is passed, a client is generated using that connection. | def get_serverless_dashboard_url(
*,
aws_conn_id: str | None = None,
emr_serverless_client: boto3.client = None,
application_id: str,
job_run_id: str,
) -> ParseResult | None:
"""
Retrieve the URL to EMR Serverless dashboard.
The URL is a one-use, ephemeral link that expires in 1 hour a... |
Retrieve the S3 URI to the EMR Job logs.
Requires either the output of a describe_cluster call or both an EMR Client and a job_flow_id.. | def get_log_uri(
*, cluster: dict[str, Any] | None = None, emr_client: boto3.client = None, job_flow_id: str | None = None
) -> str | None:
"""
Retrieve the S3 URI to the EMR Job logs.
Requires either the output of a describe_cluster call or both an EMR Client and a job_flow_id..
"""
if not exa... |
JSON serializer replicating legacy watchtower behavior.
The legacy `watchtower@2.0.1` json serializer function that serialized
datetime objects as ISO format and all other non-JSON-serializable to `null`.
:param value: the object to serialize
:return: string representation of `value` if it is an instance of datetime ... | def json_serialize_legacy(value: Any) -> str | None:
"""
JSON serializer replicating legacy watchtower behavior.
The legacy `watchtower@2.0.1` json serializer function that serialized
datetime objects as ISO format and all other non-JSON-serializable to `null`.
:param value: the object to serializ... |
JSON serializer replicating current watchtower behavior.
This provides customers with an accessible import,
`airflow.providers.amazon.aws.log.cloudwatch_task_handler.json_serialize`
:param value: the object to serialize
:return: string representation of `value` | def json_serialize(value: Any) -> str | None:
"""
JSON serializer replicating current watchtower behavior.
This provides customers with an accessible import,
`airflow.providers.amazon.aws.log.cloudwatch_task_handler.json_serialize`
:param value: the object to serialize
:return: string represen... |
Parse a config file for S3 credentials.
Can currently parse boto, s3cmd.conf and AWS SDK config formats.
:param config_file_name: path to the config file
:param config_format: config type. One of "boto", "s3cmd" or "aws".
Defaults to "boto"
:param profile: profile name in AWS type config file | def _parse_s3_config(
config_file_name: str, config_format: str | None = "boto", profile: str | None = None
) -> tuple[str | None, str | None]:
"""Parse a config file for S3 credentials.
Can currently parse boto, s3cmd.conf and AWS SDK config formats.
:param config_file_name: path to the config file
... |
Email backend for SES. | def send_email(
to: list[str] | str,
subject: str,
html_content: str,
files: list | None = None,
cc: list[str] | str | None = None,
bcc: list[str] | str | None = None,
mime_subtype: str = "mixed",
mime_charset: str = "utf-8",
conn_id: str = "aws_default",
from_email: str | None =... |
Convert input values to deterministic UUID string representation.
This function is only intended to generate a hash which used as an identifier, not for any security use.
Generates a UUID v5 (SHA-1 + Namespace) for each value provided,
and this UUID is used as the Namespace for the next element.
If only one non-None... | def generate_uuid(*values: str | None, namespace: UUID = NAMESPACE_OID) -> str:
"""
Convert input values to deterministic UUID string representation.
This function is only intended to generate a hash which used as an identifier, not for any security use.
Generates a UUID v5 (SHA-1 + Namespace) for eac... |
Merge provided template_fields with generic one and return in alphabetical order. | def aws_template_fields(*template_fields: str) -> tuple[str, ...]:
"""Merge provided template_fields with generic one and return in alphabetical order."""
if not all(isinstance(tf, str) for tf in template_fields):
msg = (
"Expected that all provided arguments are strings, but got "
... |
Generate AWS credentials block for Redshift COPY and UNLOAD commands.
See AWS docs for details:
https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-authorization.html#copy-credentials
:param credentials: ReadOnlyCredentials object from `botocore` | def build_credentials_block(credentials: ReadOnlyCredentials) -> str:
"""Generate AWS credentials block for Redshift COPY and UNLOAD commands.
See AWS docs for details:
https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-authorization.html#copy-credentials
:param credentials: ReadOnlyCreden... |
Process the response from SQS.
:param response: The response from SQS
:return: The processed response | def process_response(
response: Any,
message_filtering: MessageFilteringType | None = None,
message_filtering_match_values: Any = None,
message_filtering_config: Any = None,
) -> Any:
"""
Process the response from SQS.
:param response: The response from SQS
:return: The processed respon... |
Suppress any ``Exception`` raised in decorator function.
Main use-case when functional is optional, however any error on functions/methods might
raise any error which are subclass of ``Exception``.
.. note::
Decorator doesn't intend to catch ``BaseException``,
e.g. ``GeneratorExit``, ``KeyboardInterrupt``, ``... | def return_on_error(return_value: RT):
"""
Suppress any ``Exception`` raised in decorator function.
Main use-case when functional is optional, however any error on functions/methods might
raise any error which are subclass of ``Exception``.
.. note::
Decorator doesn't intend to catch ``Bas... |
Format tags for boto call which expect a given format.
If given a dictionary, formats it as an array of objects with a key and a value field to be passed to boto
calls that expect this format.
Else, assumes that it's already in the right format and returns it as is. We do not validate
the format here since it's done ... | def format_tags(source: Any, *, key_label: str = "Key", value_label: str = "Value"):
"""
Format tags for boto call which expect a given format.
If given a dictionary, formats it as an array of objects with a key and a value field to be passed to boto
calls that expect this format.
Else, assumes th... |
Call get_state_callable until it reaches the desired_state or the failure_states.
PLEASE NOTE: While not yet deprecated, we are moving away from this method
and encourage using the custom boto waiters as explained in
https://github.com/apache/airflow/tree/main/airflow/providers/amazon/aws/... | def waiter(
get_state_callable: Callable,
get_state_args: dict,
parse_response: list,
desired_state: set,
failure_states: set,
object_type: str,
action: str,
countdown: int | float | None = 25 * 60,
check_interval_seconds: int = 60,
) -> None:
"""
Call get_state_callable unti... |
Use a boto waiter to poll an AWS service for the specified state.
Although this function uses boto waiters to poll the state of the
service, it logs the response of the service after every attempt,
which is not currently supported by boto waiters.
:param waiter: The boto waiter to use.
:param waiter_delay: The amount... | def wait(
waiter: Waiter,
waiter_delay: int,
waiter_max_attempts: int,
args: dict[str, Any],
failure_message: str,
status_message: str,
status_args: list[str],
) -> None:
"""
Use a boto waiter to poll an AWS service for the specified state.
Although this function uses boto waite... |
Convert a datetime object to an epoch integer (seconds). | def datetime_to_epoch(date_time: datetime) -> int:
"""Convert a datetime object to an epoch integer (seconds)."""
return int(date_time.timestamp()) |
Convert a datetime object to an epoch integer (milliseconds). | def datetime_to_epoch_ms(date_time: datetime) -> int:
"""Convert a datetime object to an epoch integer (milliseconds)."""
return int(date_time.timestamp() * 1_000) |
Convert a datetime object to an epoch integer (milliseconds) in UTC timezone. | def datetime_to_epoch_utc_ms(date_time: datetime) -> int:
"""Convert a datetime object to an epoch integer (milliseconds) in UTC timezone."""
return int(date_time.replace(tzinfo=timezone.utc).timestamp() * 1_000) |
Convert a datetime object to an epoch integer (microseconds). | def datetime_to_epoch_us(date_time: datetime) -> int:
"""Convert a datetime object to an epoch integer (microseconds)."""
return int(date_time.timestamp() * 1_000_000) |
Return a formatted pipeline options from a dictionary of arguments.
The logic of this method should be compatible with Apache Beam:
https://github.com/apache/beam/blob/b56740f0e8cd80c2873412847d0b336837429fb9/sdks/python/
apache_beam/options/pipeline_options.py#L230-L251
:param options: Dictionary with options
:retur... | def beam_options_to_args(options: dict) -> list[str]:
"""
Return a formatted pipeline options from a dictionary of arguments.
The logic of this method should be compatible with Apache Beam:
https://github.com/apache/beam/blob/b56740f0e8cd80c2873412847d0b336837429fb9/sdks/python/
apache_beam/options... |
Print output to logs.
:param proc: subprocess.
:param fd: File descriptor.
:param process_line_callback: Optional callback which can be used to process
stdout and stderr to detect job id.
:param log: logger. | def process_fd(
proc,
fd,
log: logging.Logger,
process_line_callback: Callable[[str], None] | None = None,
check_job_status_callback: Callable[[], bool | None] | None = None,
):
"""
Print output to logs.
:param proc: subprocess.
:param fd: File descriptor.
:param process_line_ca... |
Run pipeline command in subprocess.
:param cmd: Parts of the command to be run in subprocess
:param process_line_callback: Optional callback which can be used to process
stdout and stderr to detect job id
:param working_directory: Working directory
:param log: logger. | def run_beam_command(
cmd: list[str],
log: logging.Logger,
process_line_callback: Callable[[str], None] | None = None,
working_directory: str | None = None,
check_job_status_callback: Callable[[], bool | None] | None = None,
) -> None:
"""
Run pipeline command in subprocess.
:param cmd:... |
Extract context from env variable, (dag_id, task_id, etc) for use in BashOperator and PythonOperator.
:return: The context of interest. | def get_context_from_env_var() -> dict[Any, Any]:
"""
Extract context from env variable, (dag_id, task_id, etc) for use in BashOperator and PythonOperator.
:return: The context of interest.
"""
return {
format_map["default"]: os.environ.get(format_map["env_var_format"], "")
for form... |
Get the max partition for a table.
:param schema: The hive schema the table lives in
:param table: The hive table you are interested in, supports the dot
notation as in "my_database.my_table", if a dot is found,
the schema param is disregarded
:param metastore_conn_id: The hive connection you are interested in... | def max_partition(
table, schema="default", field=None, filter_map=None, metastore_conn_id="metastore_default"
):
"""
Get the max partition for a table.
:param schema: The hive schema the table lives in
:param table: The hive table you are interested in, supports the dot
notation as in "my_... |
Find the date in a list closest to the target date.
An optional parameter can be given to get the closest before or after.
:param target_dt: The target date
:param date_list: The list of dates to search
:param before_target: closest before or after the target
:returns: The closest date | def _closest_date(target_dt, date_list, before_target=None) -> datetime.date | None:
"""
Find the date in a list closest to the target date.
An optional parameter can be given to get the closest before or after.
:param target_dt: The target date
:param date_list: The list of dates to search
:p... |
Find the date in a list closest to the target date.
An optional parameter can be given to get the closest before or after.
:param table: A hive table name
:param ds: A datestamp ``%Y-%m-%d`` e.g. ``yyyy-mm-dd``
:param before: closest before (True), after (False) or either side of ds
:param schema: table schema
:param... | def closest_ds_partition(
table, ds, before=True, schema="default", metastore_conn_id="metastore_default"
) -> str | None:
"""
Find the date in a list closest to the target date.
An optional parameter can be given to get the closest before or after.
:param table: A hive table name
:param ds: A... |
Get Spark source from JDBC connection.
:param spark_source: Spark source, here is Spark reader or writer
:param url: JDBC resource url
:param jdbc_table: JDBC resource table name
:param user: JDBC resource user name
:param password: JDBC resource password
:param driver: JDBC resource driver | def set_common_options(
spark_source: Any,
url: str = "localhost:5432",
jdbc_table: str = "default.default",
user: str = "root",
password: str = "root",
driver: str = "driver",
) -> Any:
"""
Get Spark source from JDBC connection.
:param spark_source: Spark source, here is Spark read... |
Transfer data from Spark to JDBC source. | def spark_write_to_jdbc(
spark_session: SparkSession,
url: str,
user: str,
password: str,
metastore_table: str,
jdbc_table: str,
driver: Any,
truncate: bool,
save_mode: str,
batch_size: int,
num_partitions: int,
create_table_column_types: str,
) -> None:
"""Transfer d... |
Transfer data from JDBC source to Spark. | def spark_read_from_jdbc(
spark_session: SparkSession,
url: str,
user: str,
password: str,
metastore_table: str,
jdbc_table: str,
driver: Any,
save_mode: str,
save_format: str,
fetch_size: int,
num_partitions: int,
partition_column: str,
lower_bound: str,
upper_bo... |
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... |
Generate documentation; used by Sphinx.
:meta private: | def _get_parser() -> argparse.ArgumentParser:
"""
Generate documentation; used by Sphinx.
:meta private:
"""
return CeleryExecutor._get_parser() |
Init providers before importing the configuration, so the _SECRET and _CMD options work. | def _get_celery_app() -> Celery:
"""Init providers before importing the configuration, so the _SECRET and _CMD options work."""
global celery_configuration
if conf.has_option("celery", "celery_config_options"):
celery_configuration = conf.getimport("celery", "celery_config_options")
else:
... |
Preload some "expensive" airflow modules once, so other task processes won't have to import it again.
Loading these for each task adds 0.3-0.5s *per task* before the task can run. For long running tasks this
doesn't matter, but for short tasks this starts to be a noticeable impact. | def on_celery_import_modules(*args, **kwargs):
"""
Preload some "expensive" airflow modules once, so other task processes won't have to import it again.
Loading these for each task adds 0.3-0.5s *per task* before the task can run. For long running tasks this
doesn't matter, but for short tasks this sta... |
Execute command. | def execute_command(command_to_exec: CommandType) -> None:
"""Execute command."""
dag_id, task_id = BaseExecutor.validate_airflow_tasks_run_command(command_to_exec)
celery_task_id = app.current_task.request.id
log.info("[%s] Executing command in Celery: %s", celery_task_id, command_to_exec)
with _ai... |
Send task to executor. | def send_task_to_executor(
task_tuple: TaskInstanceInCelery,
) -> tuple[TaskInstanceKey, CommandType, AsyncResult | ExceptionWithTraceback]:
"""Send task to executor."""
key, command, queue, task_to_run = task_tuple
try:
with timeout(seconds=OPERATION_TIMEOUT):
result = task_to_run.a... |
Fetch and return the state of the given celery task.
The scope of this function is global so that it can be called by subprocesses in the pool.
:param async_result: a tuple of the Celery task key and the async Celery object used
to fetch the task's state
:return: a tuple of the Celery task key and the Celery stat... | def fetch_celery_task_state(async_result: AsyncResult) -> tuple[str, str | ExceptionWithTraceback, Any]:
"""
Fetch and return the state of the given celery task.
The scope of this function is global so that it can be called by subprocesses in the pool.
:param async_result: a tuple of the Celery task k... |
Attach additional specs to an existing pod object.
:param pod: A pod to attach a list of Kubernetes objects to
:param k8s_objects: a potential None list of K8SModels
:return: pod with the objects attached if they exist | def append_to_pod(pod: k8s.V1Pod, k8s_objects: list[K8SModel] | None):
"""
Attach additional specs to an existing pod object.
:param pod: A pod to attach a list of Kubernetes objects to
:param k8s_objects: a potential None list of K8SModels
:return: pod with the objects attached if they exist
"... |
Generate random lowercase alphanumeric string of length num.
:meta private: | def rand_str(num):
"""Generate random lowercase alphanumeric string of length num.
:meta private:
"""
return "".join(secrets.choice(alphanum_lower) for _ in range(num)) |
Add random string to pod or job name while staying under max length.
:param name: name of the pod or job
:param rand_len: length of the random string to append
:param max_len: maximum length of the pod name
:meta private: | def add_unique_suffix(*, name: str, rand_len: int = 8, max_len: int = POD_NAME_MAX_LENGTH) -> str:
"""Add random string to pod or job name while staying under max length.
:param name: name of the pod or job
:param rand_len: length of the random string to append
:param max_len: maximum length of the pod... |
Add random string to pod name while staying under max length.
:param pod_name: name of the pod
:param rand_len: length of the random string to append
:param max_len: maximum length of the pod name
:meta private: | def add_pod_suffix(*, pod_name: str, rand_len: int = 8, max_len: int = POD_NAME_MAX_LENGTH) -> str:
"""Add random string to pod name while staying under max length.
:param pod_name: name of the pod
:param rand_len: length of the random string to append
:param max_len: maximum length of the pod name
... |
Generate unique pod or job ID given a dag_id and / or task_id.
:param dag_id: DAG ID
:param task_id: Task ID
:param max_length: max number of characters
:param unique: whether a random string suffix should be added
:return: A valid identifier for a kubernetes pod name | def create_unique_id(
dag_id: str | None = None,
task_id: str | None = None,
*,
max_length: int = POD_NAME_MAX_LENGTH,
unique: bool = True,
) -> str:
"""
Generate unique pod or job ID given a dag_id and / or task_id.
:param dag_id: DAG ID
:param task_id: Task ID
:param max_lengt... |
Generate unique pod ID given a dag_id and / or task_id.
:param dag_id: DAG ID
:param task_id: Task ID
:param max_length: max number of characters
:param unique: whether a random string suffix should be added
:return: A valid identifier for a kubernetes pod name | def create_pod_id(
dag_id: str | None = None,
task_id: str | None = None,
*,
max_length: int = POD_NAME_MAX_LENGTH,
unique: bool = True,
) -> str:
"""
Generate unique pod ID given a dag_id and / or task_id.
:param dag_id: DAG ID
:param task_id: Task ID
:param max_length: max num... |
Build a TaskInstanceKey based on pod annotations. | def annotations_to_key(annotations: dict[str, str]) -> TaskInstanceKey:
"""Build a TaskInstanceKey based on pod annotations."""
log.debug("Creating task key for annotations %s", annotations)
dag_id = annotations["dag_id"]
task_id = annotations["task_id"]
try_number = int(annotations["try_number"])
... |
Enable TCP keepalive mechanism.
This prevents urllib3 connection to hang indefinitely when idle connection
is time-outed on services like cloud load balancers or firewalls.
See https://github.com/apache/airflow/pull/11406 for detailed explanation.
Please ping @michalmisiewicz or @dimberman in the PR if you want to m... | def _enable_tcp_keepalive() -> None:
"""
Enable TCP keepalive mechanism.
This prevents urllib3 connection to hang indefinitely when idle connection
is time-outed on services like cloud load balancers or firewalls.
See https://github.com/apache/airflow/pull/11406 for detailed explanation.
Plea... |
Retrieve Kubernetes client.
:param in_cluster: whether we are in cluster
:param cluster_context: context of the cluster
:param config_file: configuration file
:return: kubernetes client | def get_kube_client(
in_cluster: bool | None = None,
cluster_context: str | None = None,
config_file: str | None = None,
) -> client.CoreV1Api:
"""
Retrieve Kubernetes client.
:param in_cluster: whether we are in cluster
:param cluster_context: context of the cluster
:param config_file:... |
Normalize a provided label to be of valid length and characters.
Valid label values must be 63 characters or less and must be empty or begin and
end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_),
dots (.), and alphanumerics between.
If the label value is greater than 63 chars once made... | def make_safe_label_value(string: str) -> str:
"""
Normalize a provided label to be of valid length and characters.
Valid label values must be 63 characters or less and must be empty or begin and
end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_),
dots (.), and alphan... |
Transform a datetime string to use as a label.
Kubernetes doesn't like ":" in labels, since ISO datetime format uses ":" but
not "_" let's
replace ":" with "_"
:param datetime_obj: datetime.datetime object
:return: ISO-like string representing the datetime | def datetime_to_label_safe_datestring(datetime_obj: datetime.datetime) -> str:
"""
Transform a datetime string to use as a label.
Kubernetes doesn't like ":" in labels, since ISO datetime format uses ":" but
not "_" let's
replace ":" with "_"
:param datetime_obj: datetime.datetime object
:... |
Transform a label back to a datetime object.
Kubernetes doesn't permit ":" in labels. ISO datetime format uses ":" but not
"_", let's
replace ":" with "_"
:param string: str
:return: datetime.datetime object | def label_safe_datestring_to_datetime(string: str) -> datetime.datetime:
"""
Transform a label back to a datetime object.
Kubernetes doesn't permit ":" in labels. ISO datetime format uses ":" but not
"_", let's
replace ":" with "_"
:param string: str
:return: datetime.datetime object
"... |
Merge objects.
:param base_obj: has the base attributes which are overwritten if they exist
in the client_obj and remain if they do not exist in the client_obj
:param client_obj: the object that the client wants to create.
:return: the merged objects | def merge_objects(base_obj, client_obj):
"""
Merge objects.
:param base_obj: has the base attributes which are overwritten if they exist
in the client_obj and remain if they do not exist in the client_obj
:param client_obj: the object that the client wants to create.
:return: the merged obj... |
Add field values to existing objects.
:param base_obj: an object which has a property `field_name` that is a list
:param client_obj: an object which has a property `field_name` that is a list.
A copy of this object is returned with `field_name` modified
:param field_name: the name of the list field
:return: the cl... | def extend_object_field(base_obj, client_obj, field_name):
"""
Add field values to existing objects.
:param base_obj: an object which has a property `field_name` that is a list
:param client_obj: an object which has a property `field_name` that is a list.
A copy of this object is returned with ... |
Normalize a provided label to be of valid length and characters.
Valid label values must be 63 characters or less and must be empty or begin and
end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_),
dots (.), and alphanumerics between.
If the label value is greater than 63 chars once made... | def make_safe_label_value(string):
"""
Normalize a provided label to be of valid length and characters.
Valid label values must be 63 characters or less and must be empty or begin and
end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_),
dots (.), and alphanumerics betw... |
Remove @task.kubernetes or similar as well as @setup and @teardown.
:param python_source: python source code
:param task_decorator_name: the task decorator name | def remove_task_decorator(python_source: str, task_decorator_name: str) -> str:
"""
Remove @task.kubernetes or similar as well as @setup and @teardown.
:param python_source: python source code
:param task_decorator_name: the task decorator name
"""
def _remove_task_decorator(py_source, decorat... |
Render the python script to a file to execute in the virtual environment.
:param jinja_context: The jinja context variables to unpack and replace with its placeholders in the
template file.
:param filename: The name of the file to dump the rendered script to.
:param render_template_as_native_obj: If ``True``, rend... | def write_python_script(
jinja_context: dict,
filename: str,
render_template_as_native_obj: bool = False,
):
"""
Render the python script to a file to execute in the virtual environment.
:param jinja_context: The jinja context variables to unpack and replace with its placeholders in the
... |
Render k8s pod yaml. | def render_k8s_pod_yaml(task_instance: TaskInstance) -> dict | None:
"""Render k8s pod yaml."""
kube_config = KubeConfig()
pod = PodGenerator.construct_pod(
dag_id=task_instance.dag_id,
run_id=task_instance.run_id,
task_id=task_instance.task_id,
map_index=task_instance.map_in... |
Fetch rendered template fields from DB. | def get_rendered_k8s_spec(task_instance: TaskInstance, session=NEW_SESSION) -> dict | None:
"""Fetch rendered template fields from DB."""
from airflow.models.renderedtifields import RenderedTaskInstanceFields
rendered_k8s_spec = RenderedTaskInstanceFields.get_k8s_pod_yaml(task_instance, session=session)
... |
Convert an airflow Volume object into a k8s.V1Volume.
:param volume: | def convert_volume(volume) -> k8s.V1Volume:
"""
Convert an airflow Volume object into a k8s.V1Volume.
:param volume:
"""
return _convert_kube_model_object(volume, k8s.V1Volume) |
Convert an airflow VolumeMount object into a k8s.V1VolumeMount.
:param volume_mount: | def convert_volume_mount(volume_mount) -> k8s.V1VolumeMount:
"""
Convert an airflow VolumeMount object into a k8s.V1VolumeMount.
:param volume_mount:
"""
return _convert_kube_model_object(volume_mount, k8s.V1VolumeMount) |
Convert an airflow Port object into a k8s.V1ContainerPort.
:param port: | def convert_port(port) -> k8s.V1ContainerPort:
"""
Convert an airflow Port object into a k8s.V1ContainerPort.
:param port:
"""
return _convert_kube_model_object(port, k8s.V1ContainerPort) |
Coerce env var collection for kubernetes.
If the collection is a str-str dict, convert it into a list of ``V1EnvVar``s. | def convert_env_vars(env_vars: list[k8s.V1EnvVar] | dict[str, str]) -> list[k8s.V1EnvVar]:
"""
Coerce env var collection for kubernetes.
If the collection is a str-str dict, convert it into a list of ``V1EnvVar``s.
"""
if isinstance(env_vars, dict):
return [k8s.V1EnvVar(name=k, value=v) for... |
Separate function to convert env var collection for kubernetes and then raise an error if it is still the wrong type.
This is used after the template strings have been rendered. | def convert_env_vars_or_raise_error(env_vars: list[k8s.V1EnvVar] | dict[str, str]) -> list[k8s.V1EnvVar]:
"""
Separate function to convert env var collection for kubernetes and then raise an error if it is still the wrong type.
This is used after the template strings have been rendered.
"""
env_var... |
Convert a PodRuntimeInfoEnv into an k8s.V1EnvVar.
:param pod_runtime_info_envs: | def convert_pod_runtime_info_env(pod_runtime_info_envs) -> k8s.V1EnvVar:
"""
Convert a PodRuntimeInfoEnv into an k8s.V1EnvVar.
:param pod_runtime_info_envs:
"""
return _convert_kube_model_object(pod_runtime_info_envs, k8s.V1EnvVar) |
Convert a PodRuntimeInfoEnv into an k8s.V1EnvVar.
:param image_pull_secrets: | def convert_image_pull_secrets(image_pull_secrets) -> list[k8s.V1LocalObjectReference]:
"""
Convert a PodRuntimeInfoEnv into an k8s.V1EnvVar.
:param image_pull_secrets:
"""
if isinstance(image_pull_secrets, str):
secrets = image_pull_secrets.split(",")
return [k8s.V1LocalObjectRefer... |
Convert a str into an k8s.V1EnvFromSource.
:param configmaps: | def convert_configmap(configmaps) -> k8s.V1EnvFromSource:
"""
Convert a str into an k8s.V1EnvFromSource.
:param configmaps:
"""
return k8s.V1EnvFromSource(config_map_ref=k8s.V1ConfigMapEnvSource(name=configmaps)) |
Convert a dict into an k8s.V1Affinity. | def convert_affinity(affinity) -> k8s.V1Affinity:
"""Convert a dict into an k8s.V1Affinity."""
return _convert_from_dict(affinity, k8s.V1Affinity) |
Convert a dict into an k8s.V1Toleration. | def convert_toleration(toleration) -> k8s.V1Toleration:
"""Convert a dict into an k8s.V1Toleration."""
return _convert_from_dict(toleration, k8s.V1Toleration) |
Kubernetes operator decorator.
This wraps a function to be executed in K8s using KubernetesPodOperator.
Also accepts any argument that DockerOperator will via ``kwargs``. Can be
reused in a single DAG.
:param python_callable: Function to decorate
:param multiple_outputs: if set, function return value will be
unro... | def kubernetes_task(
python_callable: Callable | None = None,
multiple_outputs: bool | None = None,
**kwargs,
) -> TaskDecorator:
"""Kubernetes operator decorator.
This wraps a function to be executed in K8s using KubernetesPodOperator.
Also accepts any argument that DockerOperator will via ``k... |
Generate documentation; used by Sphinx.
:meta private: | def _get_parser() -> argparse.ArgumentParser:
"""
Generate documentation; used by Sphinx.
:meta private:
"""
return KubernetesExecutor._get_parser() |
Get base pod from template.
Reads either the pod_template_file set in the executor_config or the base pod_template_file
set in the airflow.cfg to craft a "base pod" that will be used by the KubernetesExecutor
:param pod_template_file: absolute path to a pod_template_file.yaml or None
:param kube_config: The KubeConfi... | def get_base_pod_from_template(pod_template_file: str | None, kube_config: Any) -> k8s.V1Pod:
"""
Get base pod from template.
Reads either the pod_template_file set in the executor_config or the base pod_template_file
set in the airflow.cfg to craft a "base pod" that will be used by the KubernetesExecu... |
Convert val to bool if can be done with certainty; if we cannot infer intention we return None. | def _get_bool(val) -> bool | None:
"""Convert val to bool if can be done with certainty; if we cannot infer intention we return None."""
if isinstance(val, bool):
return val
elif isinstance(val, str):
if val.strip().lower() == "true":
return True
elif val.strip().lower()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.