INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Replaces invalid MLEngine job_id characters with _. | def _normalize_mlengine_job_id(job_id):
"""
Replaces invalid MLEngine job_id characters with '_'.
This also adds a leading 'z' in case job_id starts with an invalid
character.
Args:
job_id: A job_id str that may have invalid characters.
Returns:
A valid job_id representation.
... |
Extract error code from ftp exception | def _get_error_code(self, e):
"""Extract error code from ftp exception"""
try:
matches = self.error_code_pattern.match(str(e))
code = int(matches.group(0))
return code
except ValueError:
return e |
Integrate plugins to the context | def _integrate_plugins():
"""Integrate plugins to the context"""
import sys
from airflow.plugins_manager import sensors_modules
for sensors_module in sensors_modules:
sys.modules[sensors_module.__name__] = sensors_module
globals()[sensors_module._name] = sensors_module |
Remove any existing DAG runs for the perf test DAGs. | def clear_dag_runs():
"""
Remove any existing DAG runs for the perf test DAGs.
"""
session = settings.Session()
drs = session.query(DagRun).filter(
DagRun.dag_id.in_(DAG_IDS),
).all()
for dr in drs:
logging.info('Deleting DagRun :: {}'.format(dr))
session.delete(dr) |
Remove any existing task instances for the perf test DAGs. | def clear_dag_task_instances():
"""
Remove any existing task instances for the perf test DAGs.
"""
session = settings.Session()
TI = TaskInstance
tis = (
session
.query(TI)
.filter(TI.dag_id.in_(DAG_IDS))
.all()
)
for ti in tis:
logging.info('Delet... |
Toggle the pause state of the DAGs in the test. | def set_dags_paused_state(is_paused):
"""
Toggle the pause state of the DAGs in the test.
"""
session = settings.Session()
dms = session.query(DagModel).filter(
DagModel.dag_id.in_(DAG_IDS))
for dm in dms:
logging.info('Setting DAG :: {} is_paused={}'.format(dm, is_paused))
... |
Print operational metrics for the scheduler test. | def print_stats(self):
"""
Print operational metrics for the scheduler test.
"""
session = settings.Session()
TI = TaskInstance
tis = (
session
.query(TI)
.filter(TI.dag_id.in_(DAG_IDS))
.all()
)
successful_t... |
Override the scheduler heartbeat to determine when the test is complete | def heartbeat(self):
"""
Override the scheduler heartbeat to determine when the test is complete
"""
super(SchedulerMetricsJob, self).heartbeat()
session = settings.Session()
# Get all the relevant task instances
TI = TaskInstance
successful_tis = (
... |
Invoke Lambda Function | def invoke_lambda(self, payload):
"""
Invoke Lambda Function
"""
awslambda_conn = self.get_conn()
response = awslambda_conn.invoke(
FunctionName=self.function_name,
InvocationType=self.invocation_type,
LogType=self.log_type,
Paylo... |
Return the task object identified by the given dag_id and task_id. | def get_dag_run_state(dag_id, execution_date):
"""Return the task object identified by the given dag_id and task_id."""
dagbag = DagBag()
# Check DAG exists.
if dag_id not in dagbag.dags:
error_message = "Dag id {} not found".format(dag_id)
raise DagNotFound(error_message)
# Get D... |
Creates Operators needed for model evaluation and returns. | def create_evaluate_ops(task_prefix,
data_format,
input_paths,
prediction_path,
metric_fn_and_keys,
validate_fn,
batch_prediction_job_id=None,
project_i... |
Creates the directory specified by path creating intermediate directories as necessary. If directory already exists this is a no - op. | def mkdirs(path, mode):
"""
Creates the directory specified by path, creating intermediate directories
as necessary. If directory already exists, this is a no-op.
:param path: The directory to create
:type path: str
:param mode: The mode to give to the directory e.g. 0o755, ignores umask
:t... |
A small helper function to convert a string to a numeric value if appropriate | def _convert_to_float_if_possible(s):
"""
A small helper function to convert a string to a numeric value
if appropriate
:param s: the string to be converted
:type s: str
"""
try:
ret = float(s)
except (ValueError, TypeError):
ret = s
return ret |
Get the current date and time in UTC: return: | def utcnow():
"""
Get the current date and time in UTC
:return:
"""
# pendulum utcnow() is not used as that sets a TimezoneInfo object
# instead of a Timezone. This is not pickable and also creates issues
# when using replace()
d = dt.datetime.utcnow()
d = d.replace(tzinfo=utc)
... |
Gets the epoch in the users timezone: return: | def utc_epoch():
"""
Gets the epoch in the users timezone
:return:
"""
# pendulum utcnow() is not used as that sets a TimezoneInfo object
# instead of a Timezone. This is not pickable and also creates issues
# when using replace()
d = dt.datetime(1970, 1, 1)
d = d.replace(tzinfo=utc... |
Returns the datetime with the default timezone added if timezone information was not associated: param value: datetime: return: datetime with tzinfo | def convert_to_utc(value):
"""
Returns the datetime with the default timezone added if timezone
information was not associated
:param value: datetime
:return: datetime with tzinfo
"""
if not value:
return value
if not is_localized(value):
value = pendulum.instance(value,... |
Make a naive datetime. datetime in a given time zone aware. | def make_aware(value, timezone=None):
"""
Make a naive datetime.datetime in a given time zone aware.
:param value: datetime
:param timezone: timezone
:return: localized datetime in settings.TIMEZONE or timezone
"""
if timezone is None:
timezone = TIMEZONE
# Check that we won't... |
Make an aware datetime. datetime naive in a given time zone. | def make_naive(value, timezone=None):
"""
Make an aware datetime.datetime naive in a given time zone.
:param value: datetime
:param timezone: timezone
:return: naive datetime
"""
if timezone is None:
timezone = TIMEZONE
# Emulate the behavior of astimezone() on Python < 3.6.
... |
Wrapper around datetime. datetime that adds settings. TIMEZONE if tzinfo not specified | def datetime(*args, **kwargs):
"""
Wrapper around datetime.datetime that adds settings.TIMEZONE if tzinfo not specified
:return: datetime.datetime
"""
if 'tzinfo' not in kwargs:
kwargs['tzinfo'] = TIMEZONE
return dt.datetime(*args, **kwargs) |
Sets the environment variable GOOGLE_APPLICATION_CREDENTIALS with either: | def _set_env_from_extras(self, extras):
"""
Sets the environment variable `GOOGLE_APPLICATION_CREDENTIALS` with either:
- The path to the keyfile from the specified connection id
- A generated file's path if the user specified JSON in the connection id. The
file is assumed t... |
Fetches a field from extras and returns it. This is some Airflow magic. The google_cloud_platform hook type adds custom UI elements to the hook page which allow admins to specify service_account key_path etc. They get formatted as shown below. | def _get_field(self, extras, field, default=None):
"""
Fetches a field from extras, and returns it. This is some Airflow
magic. The google_cloud_platform hook type adds custom UI elements
to the hook page, which allow admins to specify service_account,
key_path, etc. They get for... |
Establish a connection to druid broker. | def get_conn(self):
"""
Establish a connection to druid broker.
"""
conn = self.get_connection(self.druid_broker_conn_id)
druid_broker_conn = connect(
host=conn.host,
port=conn.port,
path=conn.extra_dejson.get('endpoint', '/druid/v2/sql'),
... |
Returns http session for use with requests | def get_conn(self, headers=None):
"""
Returns http session for use with requests
:param headers: additional headers to be passed through as a dictionary
:type headers: dict
"""
session = requests.Session()
if self.http_conn_id:
conn = self.get_connect... |
Performs the request | def run(self, endpoint, data=None, headers=None, extra_options=None):
"""
Performs the request
:param endpoint: the endpoint to be called i.e. resource/v1/query?
:type endpoint: str
:param data: payload to be uploaded or request parameters
:type data: dict
:param... |
Checks the status code and raise an AirflowException exception on non 2XX or 3XX status codes | def check_response(self, response):
"""
Checks the status code and raise an AirflowException exception on non 2XX or 3XX
status codes
:param response: A requests response object
:type response: requests.response
"""
try:
response.raise_for_status()
... |
Grabs extra options like timeout and actually runs the request checking for the result | def run_and_check(self, session, prepped_request, extra_options):
"""
Grabs extra options like timeout and actually runs the request,
checking for the result
:param session: the session to be used to execute the request
:type session: requests.Session
:param prepped_requ... |
Runs Hook. run () with a Tenacity decorator attached to it. This is useful for connectors which might be disturbed by intermittent issues and should not instantly fail. | def run_with_advanced_retry(self, _retry_args, *args, **kwargs):
"""
Runs Hook.run() with a Tenacity decorator attached to it. This is useful for
connectors which might be disturbed by intermittent issues and should not
instantly fail.
:param _retry_args: Arguments which define ... |
Contextmanager that will create and teardown a session. | def create_session():
"""
Contextmanager that will create and teardown a session.
"""
session = settings.Session()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close() |
Function decorator that provides a session if it isn t provided. If you want to reuse a session or run the function as part of a database transaction you pass it to the function if not this wrapper will create one and close it for you. | def provide_session(func):
"""
Function decorator that provides a session if it isn't provided.
If you want to reuse a session or run the function as part of a
database transaction, you pass it to the function, if not this wrapper
will create one and close it for you.
"""
@wraps(func)
de... |
Clear out the database | def resetdb():
"""
Clear out the database
"""
from airflow import models
# alembic adds significant import time, so we import it lazily
from alembic.migration import MigrationContext
log.info("Dropping tables that exist")
models.base.Base.metadata.drop_all(settings.engine)
mc = Mi... |
Upload a file to Azure Blob Storage. | def execute(self, context):
"""Upload a file to Azure Blob Storage."""
hook = WasbHook(wasb_conn_id=self.wasb_conn_id)
self.log.info(
'Uploading %s to wasb://%s '
'as %s'.format(self.file_path, self.container_name, self.blob_name)
)
hook.load_file(self.fil... |
Returns a connection object | def get_conn(self):
"""Returns a connection object"""
db = self.get_connection(self.presto_conn_id)
reqkwargs = None
if db.password is not None:
reqkwargs = {'auth': HTTPBasicAuth(db.login, db.password)}
return presto.connect(
host=db.host,
por... |
Parses some DatabaseError to provide a better error message | def _get_pretty_exception_message(e):
"""
Parses some DatabaseError to provide a better error message
"""
if (hasattr(e, 'message') and
'errorName' in e.message and
'message' in e.message):
return ('{name}: {message}'.format(
na... |
Get a set of records from Presto | def get_records(self, hql, parameters=None):
"""
Get a set of records from Presto
"""
try:
return super().get_records(
self._strip_sql(hql), parameters)
except DatabaseError as e:
raise PrestoException(self._get_pretty_exception_message(e)) |
Get a pandas dataframe from a sql query. | def get_pandas_df(self, hql, parameters=None):
"""
Get a pandas dataframe from a sql query.
"""
import pandas
cursor = self.get_cursor()
try:
cursor.execute(self._strip_sql(hql), parameters)
data = cursor.fetchall()
except DatabaseError as ... |
Execute the statement against Presto. Can be used to create views. | def run(self, hql, parameters=None):
"""
Execute the statement against Presto. Can be used to create views.
"""
return super().run(self._strip_sql(hql), parameters) |
A generic way to insert a set of tuples into a table. | def insert_rows(self, table, rows, target_fields=None):
"""
A generic way to insert a set of tuples into a table.
:param table: Name of the target table
:type table: str
:param rows: The rows to insert into the table
:type rows: iterable of tuples
:param target_f... |
Return a cosmos db client. | def get_conn(self):
"""
Return a cosmos db client.
"""
if self.cosmos_client is not None:
return self.cosmos_client
# Initialize the Python Azure Cosmos DB client
self.cosmos_client = cosmos_client.CosmosClient(self.endpoint_uri, {'masterKey': self.master_key... |
Checks if a collection exists in CosmosDB. | def does_collection_exist(self, collection_name, database_name=None):
"""
Checks if a collection exists in CosmosDB.
"""
if collection_name is None:
raise AirflowBadRequest("Collection name cannot be None.")
existing_container = list(self.get_conn().QueryContainers(
... |
Creates a new collection in the CosmosDB database. | def create_collection(self, collection_name, database_name=None):
"""
Creates a new collection in the CosmosDB database.
"""
if collection_name is None:
raise AirflowBadRequest("Collection name cannot be None.")
# We need to check to see if this container already exi... |
Checks if a database exists in CosmosDB. | def does_database_exist(self, database_name):
"""
Checks if a database exists in CosmosDB.
"""
if database_name is None:
raise AirflowBadRequest("Database name cannot be None.")
existing_database = list(self.get_conn().QueryDatabases({
"query": "SELECT * ... |
Creates a new database in CosmosDB. | def create_database(self, database_name):
"""
Creates a new database in CosmosDB.
"""
if database_name is None:
raise AirflowBadRequest("Database name cannot be None.")
# We need to check to see if this database already exists so we don't try
# to create it t... |
Deletes an existing database in CosmosDB. | def delete_database(self, database_name):
"""
Deletes an existing database in CosmosDB.
"""
if database_name is None:
raise AirflowBadRequest("Database name cannot be None.")
self.get_conn().DeleteDatabase(get_database_link(database_name)) |
Deletes an existing collection in the CosmosDB database. | def delete_collection(self, collection_name, database_name=None):
"""
Deletes an existing collection in the CosmosDB database.
"""
if collection_name is None:
raise AirflowBadRequest("Collection name cannot be None.")
self.get_conn().DeleteContainer(
get_... |
Inserts a new document ( or updates an existing one ) into an existing collection in the CosmosDB database. | def upsert_document(self, document, database_name=None, collection_name=None, document_id=None):
"""
Inserts a new document (or updates an existing one) into an existing
collection in the CosmosDB database.
"""
# Assign unique ID if one isn't provided
if document_id is No... |
Insert a list of new documents into an existing collection in the CosmosDB database. | def insert_documents(self, documents, database_name=None, collection_name=None):
"""
Insert a list of new documents into an existing collection in the CosmosDB database.
"""
if documents is None:
raise AirflowBadRequest("You cannot insert empty documents")
created_do... |
Delete an existing document out of a collection in the CosmosDB database. | def delete_document(self, document_id, database_name=None, collection_name=None):
"""
Delete an existing document out of a collection in the CosmosDB database.
"""
if document_id is None:
raise AirflowBadRequest("Cannot delete a document without an id")
self.get_conn... |
Get a document from an existing collection in the CosmosDB database. | def get_document(self, document_id, database_name=None, collection_name=None):
"""
Get a document from an existing collection in the CosmosDB database.
"""
if document_id is None:
raise AirflowBadRequest("Cannot get a document without an id")
try:
return ... |
Get a list of documents from an existing collection in the CosmosDB database via SQL query. | def get_documents(self, sql_string, database_name=None, collection_name=None, partition_key=None):
"""
Get a list of documents from an existing collection in the CosmosDB database via SQL query.
"""
if sql_string is None:
raise AirflowBadRequest("SQL query string cannot be No... |
Return python code of a given dag_id. | def get_code(dag_id):
"""Return python code of a given dag_id."""
session = settings.Session()
DM = models.DagModel
dag = session.query(DM).filter(DM.dag_id == dag_id).first()
session.close()
# Check DAG exists.
if dag is None:
error_message = "Dag id {} not found".format(dag_id)
... |
Returns the Cloud Function with the given name. | def get_function(self, name):
"""
Returns the Cloud Function with the given name.
:param name: Name of the function.
:type name: str
:return: A Cloud Functions object representing the function.
:rtype: dict
"""
return self.get_conn().projects().locations(... |
Creates a new function in Cloud Function in the location specified in the body. | def create_new_function(self, location, body, project_id=None):
"""
Creates a new function in Cloud Function in the location specified in the body.
:param location: The location of the function.
:type location: str
:param body: The body required by the Cloud Functions insert API... |
Updates Cloud Functions according to the specified update mask. | def update_function(self, name, body, update_mask):
"""
Updates Cloud Functions according to the specified update mask.
:param name: The name of the function.
:type name: str
:param body: The body required by the cloud function patch API.
:type body: dict
:param ... |
Uploads zip file with sources. | def upload_function_zip(self, location, zip_path, project_id=None):
"""
Uploads zip file with sources.
:param location: The location where the function is created.
:type location: str
:param zip_path: The path of the valid .zip file to upload.
:type zip_path: str
... |
Deletes the specified Cloud Function. | def delete_function(self, name):
"""
Deletes the specified Cloud Function.
:param name: The name of the function.
:type name: str
:return: None
"""
response = self.get_conn().projects().locations().functions().delete(
name=name).execute(num_retries=se... |
Waits for the named operation to complete - checks status of the asynchronous call. | def _wait_for_operation_to_complete(self, operation_name):
"""
Waits for the named operation to complete - checks status of the
asynchronous call.
:param operation_name: The name of the operation.
:type operation_name: str
:return: The response returned by the operation.... |
Publishes messages to a Pub/ Sub topic. | def publish(self, project, topic, messages):
"""Publishes messages to a Pub/Sub topic.
:param project: the GCP project ID in which to publish
:type project: str
:param topic: the Pub/Sub topic to which to publish; do not
include the ``projects/{project}/topics/`` prefix.
... |
Creates a Pub/ Sub topic if it does not already exist. | def create_topic(self, project, topic, fail_if_exists=False):
"""Creates a Pub/Sub topic, if it does not already exist.
:param project: the GCP project ID in which to create
the topic
:type project: str
:param topic: the Pub/Sub topic name to create; do not
inclu... |
Deletes a Pub/ Sub topic if it exists. | def delete_topic(self, project, topic, fail_if_not_exists=False):
"""Deletes a Pub/Sub topic if it exists.
:param project: the GCP project ID in which to delete the topic
:type project: str
:param topic: the Pub/Sub topic name to delete; do not
include the ``projects/{projec... |
Creates a Pub/ Sub subscription if it does not already exist. | def create_subscription(self, topic_project, topic, subscription=None,
subscription_project=None, ack_deadline_secs=10,
fail_if_exists=False):
"""Creates a Pub/Sub subscription, if it does not already exist.
:param topic_project: the GCP project I... |
Deletes a Pub/ Sub subscription if it exists. | def delete_subscription(self, project, subscription,
fail_if_not_exists=False):
"""Deletes a Pub/Sub subscription, if it exists.
:param project: the GCP project ID where the subscription exists
:type project: str
:param subscription: the Pub/Sub subscription ... |
Pulls up to max_messages messages from Pub/ Sub subscription. | def pull(self, project, subscription, max_messages,
return_immediately=False):
"""Pulls up to ``max_messages`` messages from Pub/Sub subscription.
:param project: the GCP project ID where the subscription exists
:type project: str
:param subscription: the Pub/Sub subscripti... |
Pulls up to max_messages messages from Pub/ Sub subscription. | def acknowledge(self, project, subscription, ack_ids):
"""Pulls up to ``max_messages`` messages from Pub/Sub subscription.
:param project: the GCP project name or ID in which to create
the topic
:type project: str
:param subscription: the Pub/Sub subscription name to delete;... |
Wrapper around the private _get_dep_statuses method that contains some global checks for all dependencies. | def get_dep_statuses(self, ti, session, dep_context=None):
"""
Wrapper around the private _get_dep_statuses method that contains some global
checks for all dependencies.
:param ti: the task instance to get the dependency status for
:type ti: airflow.models.TaskInstance
:... |
Returns whether or not this dependency is met for a given task instance. A dependency is considered met if all of the dependency statuses it reports are passing. | def is_met(self, ti, session, dep_context=None):
"""
Returns whether or not this dependency is met for a given task instance. A
dependency is considered met if all of the dependency statuses it reports are
passing.
:param ti: the task instance to see if this dependency is met fo... |
Returns an iterable of strings that explain why this dependency wasn t met. | def get_failure_reasons(self, ti, session, dep_context=None):
"""
Returns an iterable of strings that explain why this dependency wasn't met.
:param ti: the task instance to see if this dependency is met for
:type ti: airflow.models.TaskInstance
:param session: database session
... |
Parses a config file for s3 credentials. Can currently parse boto s3cmd. conf and AWS SDK config formats | def _parse_s3_config(config_file_name, config_format='boto', profile=None):
"""
Parses 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
:type config_file_name: str
:param config_format: config type... |
Get the underlying botocore. Credentials object. | def get_credentials(self, region_name=None):
"""Get the underlying `botocore.Credentials` object.
This contains the following authentication attributes: access_key, secret_key and token.
"""
session, _ = self._get_credentials(region_name)
# Credentials are refreshable, so access... |
If the IAM role is a role name get the Amazon Resource Name ( ARN ) for the role. If IAM role is already an IAM role ARN no change is made. | def expand_role(self, role):
"""
If the IAM role is a role name, get the Amazon Resource Name (ARN) for the role.
If IAM role is already an IAM role ARN, no change is made.
:param role: IAM role name or ARN
:return: IAM role ARN
"""
if '/' in role:
re... |
Returns verticaql connection object | def get_conn(self):
"""
Returns verticaql connection object
"""
conn = self.get_connection(self.vertica_conn_id)
conn_config = {
"user": conn.login,
"password": conn.password or '',
"database": conn.schema,
"host": conn.host or 'loc... |
Walks the tree of loggers and tries to set the context for each handler: param logger: logger: param value: value to set | def set_context(logger, value):
"""
Walks the tree of loggers and tries to set the context for each handler
:param logger: logger
:param value: value to set
"""
_logger = logger
while _logger:
for handler in _logger.handlers:
try:
handler.set_context(value... |
Do whatever it takes to actually log the specified logging record: param message: message to log | def write(self, message):
"""
Do whatever it takes to actually log the specified logging record
:param message: message to log
"""
if not message.endswith("\n"):
self._buffer += message
else:
self._buffer += message
self.logger.log(self... |
Ensure all logging output has been flushed | def flush(self):
"""
Ensure all logging output has been flushed
"""
if len(self._buffer) > 0:
self.logger.log(self.level, self._buffer)
self._buffer = str() |
If the path contains a folder with a. zip suffix then the folder is treated as a zip archive and path to zip is returned. | def correct_maybe_zipped(fileloc):
"""
If the path contains a folder with a .zip suffix, then
the folder is treated as a zip archive and path to zip is returned.
"""
_, archive, filename = re.search(
r'((.*\.zip){})?(.*)'.format(re.escape(os.sep)), fileloc).groups()
if archive and zipfi... |
Traverse a directory and look for Python files. | def list_py_file_paths(directory, safe_mode=True,
include_examples=None):
"""
Traverse a directory and look for Python files.
:param directory: the directory to traverse
:type directory: unicode
:param safe_mode: whether to use a heuristic to determine whether a file
... |
Construct a TaskInstance from the database based on the primary key | def construct_task_instance(self, session=None, lock_for_update=False):
"""
Construct a TaskInstance from the database based on the primary key
:param session: DB session.
:param lock_for_update: if True, indicates that the database should
lock the TaskInstance (issuing a FO... |
: param dag_id: DAG ID: type dag_id: unicode: return: if the given DAG ID exists in the bag return the BaseDag corresponding to that ID. Otherwise throw an Exception: rtype: airflow. utils. dag_processing. SimpleDag | def get_dag(self, dag_id):
"""
:param dag_id: DAG ID
:type dag_id: unicode
:return: if the given DAG ID exists in the bag, return the BaseDag
corresponding to that ID. Otherwise, throw an Exception
:rtype: airflow.utils.dag_processing.SimpleDag
"""
if dag_... |
Launch DagFileProcessorManager processor and start DAG parsing loop in manager. | def start(self):
"""
Launch DagFileProcessorManager processor and start DAG parsing loop in manager.
"""
self._process = self._launch_process(self._dag_directory,
self._file_paths,
self._max_runs,
... |
Harvest DAG parsing results from result queue and sync metadata from stat queue.: return: List of parsing result in SimpleDag format. | def harvest_simple_dags(self):
"""
Harvest DAG parsing results from result queue and sync metadata from stat queue.
:return: List of parsing result in SimpleDag format.
"""
# Metadata and results to be harvested can be inconsistent,
# but it should not be a big problem.
... |
Heartbeat DAG file processor and start it if it is not alive.: return: | def _heartbeat_manager(self):
"""
Heartbeat DAG file processor and start it if it is not alive.
:return:
"""
if self._process and not self._process.is_alive() and not self.done:
self.start() |
Sync metadata from stat queue and only keep the latest stat.: return: | def _sync_metadata(self):
"""
Sync metadata from stat queue and only keep the latest stat.
:return:
"""
while not self._stat_queue.empty():
stat = self._stat_queue.get()
self._file_paths = stat.file_paths
self._all_pids = stat.all_pids
... |
Send termination signal to DAG parsing processor manager and expect it to terminate all DAG file processors. | def terminate(self):
"""
Send termination signal to DAG parsing processor manager
and expect it to terminate all DAG file processors.
"""
self.log.info("Sending termination message to manager.")
self._child_signal_conn.send(DagParsingSignal.TERMINATE_MANAGER) |
Terminate ( and then kill ) the manager process launched.: return: | def end(self):
"""
Terminate (and then kill) the manager process launched.
:return:
"""
if not self._process:
self.log.warn('Ending without manager process.')
return
this_process = psutil.Process(os.getpid())
try:
manager_proces... |
Helper method to clean up DAG file processors to avoid leaving orphan processes. | def _exit_gracefully(self, signum, frame):
"""
Helper method to clean up DAG file processors to avoid leaving orphan processes.
"""
self.log.info("Exiting gracefully upon receiving signal %s", signum)
self.terminate()
self.end()
self.log.debug("Finished terminatin... |
Use multiple processes to parse and generate tasks for the DAGs in parallel. By processing them in separate processes we can get parallelism and isolation from potentially harmful user code. | def start(self):
"""
Use multiple processes to parse and generate tasks for the
DAGs in parallel. By processing them in separate processes,
we can get parallelism and isolation from potentially harmful
user code.
"""
self.log.info("Processing files using up to %s... |
Parse DAG files repeatedly in a standalone loop. | def start_in_async(self):
"""
Parse DAG files repeatedly in a standalone loop.
"""
while True:
loop_start_time = time.time()
if self._signal_conn.poll():
agent_signal = self._signal_conn.recv()
if agent_signal == DagParsingSignal.T... |
Parse DAG files in a loop controlled by DagParsingSignal. Actual DAG parsing loop will run once upon receiving one agent heartbeat message and will report done when finished the loop. | def start_in_sync(self):
"""
Parse DAG files in a loop controlled by DagParsingSignal.
Actual DAG parsing loop will run once upon receiving one
agent heartbeat message and will report done when finished the loop.
"""
while True:
agent_signal = self._signal_con... |
Refresh file paths from dag dir if we haven t done it for too long. | def _refresh_dag_dir(self):
"""
Refresh file paths from dag dir if we haven't done it for too long.
"""
elapsed_time_since_refresh = (timezone.utcnow() -
self.last_dag_dir_refresh_time).total_seconds()
if elapsed_time_since_refresh > self.dag... |
Occasionally print out stats about how fast the files are getting processed | def _print_stat(self):
"""
Occasionally print out stats about how fast the files are getting processed
"""
if ((timezone.utcnow() - self.last_stat_print_time).total_seconds() >
self.print_stats_interval):
if len(self._file_paths) > 0:
self._log... |
Clears import errors for files that no longer exist. | def clear_nonexistent_import_errors(self, session):
"""
Clears import errors for files that no longer exist.
:param session: session for ORM operations
:type session: sqlalchemy.orm.session.Session
"""
query = session.query(errors.ImportError)
if self._file_paths... |
Print out stats about how files are getting processed. | def _log_file_processing_stats(self, known_file_paths):
"""
Print out stats about how files are getting processed.
:param known_file_paths: a list of file paths that may contain Airflow
DAG definitions
:type known_file_paths: list[unicode]
:return: None
"""
... |
: param file_path: the path to the file that s being processed: type file_path: unicode: return: the PID of the process processing the given file or None if the specified file is not being processed: rtype: int | def get_pid(self, file_path):
"""
:param file_path: the path to the file that's being processed
:type file_path: unicode
:return: the PID of the process processing the given file or None if
the specified file is not being processed
:rtype: int
"""
if f... |
: param file_path: the path to the file that s being processed: type file_path: unicode: return: the current runtime ( in seconds ) of the process that s processing the specified file or None if the file is not currently being processed | def get_runtime(self, file_path):
"""
:param file_path: the path to the file that's being processed
:type file_path: unicode
:return: the current runtime (in seconds) of the process that's
processing the specified file or None if the file is not currently
being pr... |
: param file_path: the path to the file that s being processed: type file_path: unicode: return: the start time of the process that s processing the specified file or None if the file is not currently being processed: rtype: datetime | def get_start_time(self, file_path):
"""
:param file_path: the path to the file that's being processed
:type file_path: unicode
:return: the start time of the process that's processing the
specified file or None if the file is not currently being processed
:rtype: dat... |
Update this with a new set of paths to DAG definition files. | def set_file_paths(self, new_file_paths):
"""
Update this with a new set of paths to DAG definition files.
:param new_file_paths: list of paths to DAG definition files
:type new_file_paths: list[unicode]
:return: None
"""
self._file_paths = new_file_paths
... |
Sleeps until all the processors are done. | def wait_until_finished(self):
"""
Sleeps until all the processors are done.
"""
for file_path, processor in self._processors.items():
while not processor.done:
time.sleep(0.1) |
This should be periodically called by the manager loop. This method will kick off new processes to process DAG definition files and read the results from the finished processors. | def heartbeat(self):
"""
This should be periodically called by the manager loop. This method will
kick off new processes to process DAG definition files and read the
results from the finished processors.
:return: a list of SimpleDags that were produced by processors that
... |
Find zombie task instances which are tasks haven t heartbeated for too long.: return: Zombie task instances in SimpleTaskInstance format. | def _find_zombies(self, session):
"""
Find zombie task instances, which are tasks haven't heartbeated for too long.
:return: Zombie task instances in SimpleTaskInstance format.
"""
now = timezone.utcnow()
zombies = []
if (now - self._last_zombie_query_time).total_... |
: return: whether all file paths have been processed max_runs times | def max_runs_reached(self):
"""
:return: whether all file paths have been processed max_runs times
"""
if self._max_runs == -1: # Unlimited runs.
return False
for file_path in self._file_paths:
if self._run_count[file_path] < self._max_runs:
... |
Kill all child processes on exit since we don t want to leave them as orphaned. | def end(self):
"""
Kill all child processes on exit since we don't want to leave
them as orphaned.
"""
pids_to_kill = self.get_all_pids()
if len(pids_to_kill) > 0:
# First try SIGTERM
this_process = psutil.Process(os.getpid())
# Only ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.