INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns the log found at the remote_log_location. Returns if no logs are found or there is an error.: param remote_log_location: the log s location in remote storage: type remote_log_location: str ( path ): param return_error: if True returns a string error message if an error occurs. Otherwise returns when an error oc...
def s3_read(self, remote_log_location, return_error=False): """ Returns the log found at the remote_log_location. Returns '' if no logs are found or there is an error. :param remote_log_location: the log's location in remote storage :type remote_log_location: str (path) :...
Writes the log to the remote_log_location. Fails silently if no hook was created.: param log: the log to write to the remote_log_location: type log: str: param remote_log_location: the log s location in remote storage: type remote_log_location: str ( path ): param append: if False any existing log file is overwritten. ...
def s3_write(self, log, remote_log_location, append=True): """ Writes the log to the remote_log_location. Fails silently if no hook was created. :param log: the log to write to the remote_log_location :type log: str :param remote_log_location: the log's location in remote...
When using git to retrieve the DAGs use the GitSync Init Container
def _get_init_containers(self): """When using git to retrieve the DAGs, use the GitSync Init Container""" # If we're using volume claims to mount the dags, no init container is needed if self.kube_config.dags_volume_claim or \ self.kube_config.dags_volume_host or self.kube_config.dags...
Defines any necessary environment variables for the pod executor
def _get_environment(self): """Defines any necessary environment variables for the pod executor""" env = {} for env_var_name, env_var_val in six.iteritems(self.kube_config.kube_env_vars): env[env_var_name] = env_var_val env["AIRFLOW__CORE__EXECUTOR"] = "LocalExecutor" ...
Defines any necessary secrets for the pod executor
def _get_secrets(self): """Defines any necessary secrets for the pod executor""" worker_secrets = [] for env_var_name, obj_key_pair in six.iteritems(self.kube_config.kube_secrets): k8s_secret_obj, k8s_secret_key = obj_key_pair.split('=') worker_secrets.append( ...
Defines the security context
def _get_security_context(self): """Defines the security context""" security_context = {} if self.kube_config.worker_run_as_user: security_context['runAsUser'] = self.kube_config.worker_run_as_user if self.kube_config.worker_fs_group: security_context['fsGroup']...
Kill ( cancel ) a Qubole command: param ti: Task Instance of the dag used to determine the Quboles command id: return: response from Qubole
def kill(self, ti): """ Kill (cancel) a Qubole command :param ti: Task Instance of the dag, used to determine the Quboles command id :return: response from Qubole """ if self.cmd is None: if not ti and not self.task_instance: raise Exception("U...
Get results ( or just s3 locations ) of a command from Qubole and save into a file: param ti: Task Instance of the dag used to determine the Quboles command id: param fp: Optional file pointer will create one and return if None passed: param inline: True to download actual results False to get s3 locations only: param ...
def get_results(self, ti=None, fp=None, inline=True, delim=None, fetch=True): """ Get results (or just s3 locations) of a command from Qubole and save into a file :param ti: Task Instance of the dag, used to determine the Quboles command id :param fp: Optional file pointer, will create o...
Get Logs of a command from Qubole: param ti: Task Instance of the dag used to determine the Quboles command id: return: command log as text
def get_log(self, ti): """ Get Logs of a command from Qubole :param ti: Task Instance of the dag, used to determine the Quboles command id :return: command log as text """ if self.cmd is None: cmd_id = ti.xcom_pull(key="qbol_cmd_id", task_ids=self.task_id) ...
Get jobs associated with a Qubole commands: param ti: Task Instance of the dag used to determine the Quboles command id: return: Job information associated with command
def get_jobs_id(self, ti): """ Get jobs associated with a Qubole commands :param ti: Task Instance of the dag, used to determine the Quboles command id :return: Job information associated with command """ if self.cmd is None: cmd_id = ti.xcom_pull(key="qbol_cm...
Get link to qubole command result page.
def get_extra_links(self, operator, dttm): """ Get link to qubole command result page. :param operator: operator :param dttm: datetime :return: url link """ conn = BaseHook.get_connection(operator.kwargs['qubole_conn_id']) if conn and conn.host: ...
Heartbeats update the job s entry in the database with a timestamp for the latest_heartbeat and allows for the job to be killed externally. This allows at the system level to monitor what is actually active.
def heartbeat(self): """ Heartbeats update the job's entry in the database with a timestamp for the latest_heartbeat and allows for the job to be killed externally. This allows at the system level to monitor what is actually active. For instance, an old heartbeat for Sch...
This function checks if there are any tasks in the dagrun ( or all ) that have a scheduled state but are not known by the executor. If it finds those it will reset the state to None so they will get picked up again. The batch option is for performance reasons as the queries are made in sequence.
def reset_state_for_orphaned_tasks(self, filter_by_dag_run=None, session=None): """ This function checks if there are any tasks in the dagrun (or all) that have a scheduled state but are not known by the executor. If it finds those it will reset the state to None so they will get...
Launch a process to process the given file.
def _launch_process(result_queue, file_path, pickle_dags, dag_id_white_list, thread_name, zombies): """ Launch a process to process the given file. :param result_queue: the qu...
Launch the process and start processing the DAG.
def start(self): """ Launch the process and start processing the DAG. """ self._process = DagFileProcessor._launch_process( self._result_queue, self.file_path, self._pickle_dags, self._dag_id_white_list, "DagFileProcessor{}".for...
Terminate ( and then kill ) the process launched to process the file.
def terminate(self, sigkill=False): """ Terminate (and then kill) the process launched to process the file. :param sigkill: whether to issue a SIGKILL if SIGTERM doesn't work. :type sigkill: bool """ if self._process is None: raise AirflowException("Tried to ...
Check if the process launched to process this file is done.
def done(self): """ Check if the process launched to process this file is done. :return: whether the process is finished running :rtype: bool """ if self._process is None: raise AirflowException("Tried to see if it's done before starting!") if self._...
Helper method to clean up processor_agent to avoid leaving orphan processes.
def _exit_gracefully(self, signum, frame): """ Helper method to clean up processor_agent to avoid leaving orphan processes. """ self.log.info("Exiting gracefully upon receiving signal %s", signum) if self.processor_agent: self.processor_agent.end() sys.exit(os...
Finding all tasks that have SLAs defined and sending alert emails where needed. New SLA misses are also recorded in the database.
def manage_slas(self, dag, session=None): """ Finding all tasks that have SLAs defined, and sending alert emails where needed. New SLA misses are also recorded in the database. Where assuming that the scheduler runs often, so we only check for tasks that should have succeeded in...
For the DAGs in the given DagBag record any associated import errors and clears errors for files that no longer have them. These are usually displayed through the Airflow UI so that users know that there are issues parsing DAGs.
def update_import_errors(session, dagbag): """ For the DAGs in the given DagBag, record any associated import errors and clears errors for files that no longer have them. These are usually displayed through the Airflow UI so that users know that there are issues parsing DAGs. :p...
This method checks whether a new DagRun needs to be created for a DAG based on scheduling interval. Returns DagRun if one is scheduled. Otherwise returns None.
def create_dag_run(self, dag, session=None): """ This method checks whether a new DagRun needs to be created for a DAG based on scheduling interval. Returns DagRun if one is scheduled. Otherwise returns None. """ if dag.schedule_interval and conf.getboolean('scheduler', '...
This method schedules the tasks for a single DAG by looking at the active DAG runs and adding task instances that should run to the queue.
def _process_task_instances(self, dag, queue, session=None): """ This method schedules the tasks for a single DAG by looking at the active DAG runs and adding task instances that should run to the queue. """ # update the state of the previously active dag runs da...
For all DAG IDs in the SimpleDagBag look for task instances in the old_states and set them to new_state if the corresponding DagRun does not exist or exists but is not in the running state. This normally should not happen but it can if the state of DagRuns are changed manually.
def _change_state_for_tis_without_dagrun(self, simple_dag_bag, old_states, new_state, session=None): """ For all DAG IDs in ...
Get the concurrency maps.
def __get_concurrency_maps(self, states, session=None): """ Get the concurrency maps. :param states: List of states to query for :type states: list[airflow.utils.state.State] :return: A map from (dag_id, task_id) to # of task instances and a map from (dag_id, task_id) t...
Finds TIs that are ready for execution with respect to pool limits dag concurrency executor state and priority.
def _find_executable_task_instances(self, simple_dag_bag, states, session=None): """ Finds TIs that are ready for execution with respect to pool limits, dag concurrency, executor state, and priority. :param simple_dag_bag: TaskInstances associated with DAGs in the simple_dag...
Changes the state of task instances in the list with one of the given states to QUEUED atomically and returns the TIs changed in SimpleTaskInstance format.
def _change_state_for_executable_task_instances(self, task_instances, acceptable_states, session=None): """ Changes the state of task instances in the list with one of the given states to QUEUED atomically, and returns the TIs changed in Simple...
Takes task_instances which should have been set to queued and enqueues them with the executor.
def _enqueue_task_instances_with_queued_state(self, simple_dag_bag, simple_task_instances): """ Takes task_instances, which should have been set to queued, and enqueues them with the executor. :param simple_task_instances: TaskInstances ...
Attempts to execute TaskInstances that should be executed by the scheduler.
def _execute_task_instances(self, simple_dag_bag, states, session=None): """ Attempts to execute TaskInstances that should be executed by the scheduler. There are three steps: 1. Pick TIs by ...
If there are tasks left over in the executor we set them back to SCHEDULED to avoid creating hanging tasks.
def _change_state_for_tasks_failed_to_execute(self, session): """ If there are tasks left over in the executor, we set them back to SCHEDULED to avoid creating hanging tasks. :param session: session for ORM operations """ if self.executor.queued_tasks: TI = m...
Iterates over the dags and processes them. Processing includes:
def _process_dags(self, dagbag, dags, tis_out): """ Iterates over the dags and processes them. Processing includes: 1. Create appropriate DagRun(s) in the DB. 2. Create appropriate TaskInstance(s) in the DB. 3. Send emails for tasks that have missed SLAs. :param dagbag:...
Respond to executor events.
def _process_executor_events(self, simple_dag_bag, session=None): """ Respond to executor events. """ # TODO: this shares quite a lot of code with _manage_executor_state TI = models.TaskInstance for key, state in list(self.executor.get_event_buffer(simple_dag_bag.dag_ids...
The actual scheduler loop. The main steps in the loop are: #. Harvest DAG parsing results through DagFileProcessorAgent #. Find and queue executable tasks #. Change task instance state in DB #. Queue tasks in executor #. Heartbeat executor #. Execute queued tasks in executor asynchronously #. Sync on the states of runn...
def _execute_helper(self): """ The actual scheduler loop. The main steps in the loop are: #. Harvest DAG parsing results through DagFileProcessorAgent #. Find and queue executable tasks #. Change task instance state in DB #. Queue tasks in executor...
Process a Python file containing Airflow DAGs.
def process_file(self, file_path, zombies, pickle_dags=False, session=None): """ Process a Python file containing Airflow DAGs. This includes: 1. Execute the file and look for DAG objects in the namespace. 2. Pickle the DAG and save it to the DB (if necessary). 3. For e...
Updates the counters per state of the tasks that were running. Can re - add to tasks to run in case required.
def _update_counters(self, ti_status): """ Updates the counters per state of the tasks that were running. Can re-add to tasks to run in case required. :param ti_status: the internal status of the backfill job tasks :type ti_status: BackfillJob._DagRunTaskStatus """ ...
Checks if the executor agrees with the state of task instances that are running
def _manage_executor_state(self, running): """ Checks if the executor agrees with the state of task instances that are running :param running: dict of key, task to verify """ executor = self.executor for key, state in list(executor.get_event_buffer().items()): ...
Returns a dag run for the given run date which will be matched to an existing dag run if available or create a new dag run otherwise. If the max_active_runs limit is reached this function will return None.
def _get_dag_run(self, run_date, session=None): """ Returns a dag run for the given run date, which will be matched to an existing dag run if available or create a new dag run otherwise. If the max_active_runs limit is reached, this function will return None. :param run_date: th...
Returns a map of task instance key to task instance object for the tasks to run in the given dag run.
def _task_instances_for_dag_run(self, dag_run, session=None): """ Returns a map of task instance key to task instance object for the tasks to run in the given dag run. :param dag_run: the dag run to get the tasks from :type dag_run: airflow.models.DagRun :param session: ...
Process a set of task instances from a set of dag runs. Special handling is done to account for different task instance states that could be present when running them in a backfill process.
def _process_backfill_task_instances(self, ti_status, executor, pickle_id, start_date=None, session=None): """ Process a set of task instanc...
Computes the dag runs and their respective task instances for the given run dates and executes the task instances. Returns a list of execution dates of the dag runs that were executed.
def _execute_for_run_dates(self, run_dates, ti_status, executor, pickle_id, start_date, session=None): """ Computes the dag runs and their respective task instances for the given run dates and executes the task instances. Returns a list of execution dates o...
Go through the dag_runs and update the state based on the task_instance state. Then set DAG runs that are not finished to failed.
def _set_unfinished_dag_runs_to_failed(self, dag_runs, session=None): """ Go through the dag_runs and update the state based on the task_instance state. Then set DAG runs that are not finished to failed. :param dag_runs: DAG runs :param session: session :return: None ...
Initializes all components required to run a dag for a specified date range and calls helper method to execute the tasks.
def _execute(self, session=None): """ Initializes all components required to run a dag for a specified date range and calls helper method to execute the tasks. """ ti_status = BackfillJob._DagRunTaskStatus() start_date = self.bf_start_date # Get intervals betwee...
Self destruct task if state has been moved away from running externally
def heartbeat_callback(self, session=None): """Self destruct task if state has been moved away from running externally""" if self.terminating: # ensure termination if processes are created later self.task_runner.terminate() return self.task_instance.refresh_...
Provides a client for interacting with the Cloud Spanner API.
def _get_client(self, project_id): """ Provides a client for interacting with the Cloud Spanner API. :param project_id: The ID of the GCP project. :type project_id: str :return: google.cloud.spanner_v1.client.Client :rtype: object """ if not self._client...
Gets information about a particular instance.
def get_instance(self, instance_id, project_id=None): """ Gets information about a particular instance. :param project_id: Optional, The ID of the GCP project that owns the Cloud Spanner database. If set to None or missing, the default project_id from the GCP connection is used. ...
Invokes a method on a given instance by applying a specified Callable.
def _apply_to_instance(self, project_id, instance_id, configuration_name, node_count, display_name, func): """ Invokes a method on a given instance by applying a specified Callable. :param project_id: The ID of the GCP project that owns the Cloud Spanner ...
Creates a new Cloud Spanner instance.
def create_instance(self, instance_id, configuration_name, node_count, display_name, project_id=None): """ Creates a new Cloud Spanner instance. :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param configuration_name: Th...
Updates an existing Cloud Spanner instance.
def update_instance(self, instance_id, configuration_name, node_count, display_name, project_id=None): """ Updates an existing Cloud Spanner instance. :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param configuration_na...
Deletes an existing Cloud Spanner instance.
def delete_instance(self, instance_id, project_id=None): """ Deletes an existing Cloud Spanner instance. :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param project_id: Optional, the ID of the GCP project that owns the Cloud Spanner ...
Retrieves a database in Cloud Spanner. If the database does not exist in the specified instance it returns None.
def get_database(self, instance_id, database_id, project_id=None): """ Retrieves a database in Cloud Spanner. If the database does not exist in the specified instance, it returns None. :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :para...
Creates a new database in Cloud Spanner.
def create_database(self, instance_id, database_id, ddl_statements, project_id=None): """ Creates a new database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the dat...
Updates DDL of a database in Cloud Spanner.
def update_database(self, instance_id, database_id, ddl_statements, project_id=None, operation_id=None): """ Updates DDL of a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. ...
Drops a database in Cloud Spanner.
def delete_database(self, instance_id, database_id, project_id=None): """ Drops a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the database in Cloud Spanner...
Executes an arbitrary DML query ( INSERT UPDATE DELETE ).
def execute_dml(self, instance_id, database_id, queries, project_id=None): """ Executes an arbitrary DML query (INSERT, UPDATE, DELETE). :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the database in Cloud Spanner. ...
Pokes for a mail attachment on the mail server.
def poke(self, context): """ Pokes for a mail attachment on the mail server. :param context: The context that is being provided when poking. :type context: dict :return: True if attachment with the given name is present and False if not. :rtype: bool """ ...
Creates additional_properties parameter based on language_hints web_detection_params and additional_properties parameters specified by the user
def prepare_additional_parameters(additional_properties, language_hints, web_detection_params): """ Creates additional_properties parameter based on language_hints, web_detection_params and additional_properties parameters specified by the user """ if language_hints is None and web_detection_params ...
Returns a cassandra Session object
def get_conn(self): """ Returns a cassandra Session object """ if self.session and not self.session.is_shutdown: return self.session self.session = self.cluster.connect(self.keyspace) return self.session
Checks if a table exists in Cassandra
def table_exists(self, table): """ Checks if a table exists in Cassandra :param table: Target Cassandra table. Use dot notation to target a specific keyspace. :type table: str """ keyspace = self.keyspace if '.' in table: keyspac...
Checks if a record exists in Cassandra
def record_exists(self, table, keys): """ Checks if a record exists in Cassandra :param table: Target Cassandra table. Use dot notation to target a specific keyspace. :type table: str :param keys: The keys and their values to check the existence. :t...
Construct the spark - submit command to execute.: param application: command to append to the spark - submit command: type application: str: return: full command to be executed
def _build_spark_submit_command(self, application): """ Construct the spark-submit command to execute. :param application: command to append to the spark-submit command :type application: str :return: full command to be executed """ connection_cmd = self._get_spar...
Construct the command to poll the driver status.
def _build_track_driver_status_command(self): """ Construct the command to poll the driver status. :return: full command to be executed """ connection_cmd = self._get_spark_binary_path() # The url ot the spark master connection_cmd += ["--master", self._connecti...
Remote Popen to execute the spark - submit job
def submit(self, application="", **kwargs): """ Remote Popen to execute the spark-submit job :param application: Submitted application, jar or py file :type application: str :param kwargs: extra arguments to Popen (see subprocess.Popen) """ spark_submit_cmd = sel...
Processes the log files and extracts useful information out of it.
def _process_spark_submit_log(self, itr): """ Processes the log files and extracts useful information out of it. If the deploy-mode is 'client', log the output of the submit command as those are the output logs of the Spark worker directly. Remark: If the driver needs to be tra...
parses the logs of the spark driver status query process
def _process_spark_status_log(self, itr): """ parses the logs of the spark driver status query process :param itr: An iterator which iterates over the input of the subprocess """ # Consume the iterator for line in itr: line = line.strip() # Check...
Polls the driver based on self. _driver_id to get the status. Finish successfully when the status is FINISHED. Finish failed when the status is ERROR/ UNKNOWN/ KILLED/ FAILED.
def _start_driver_status_tracking(self): """ Polls the driver based on self._driver_id to get the status. Finish successfully when the status is FINISHED. Finish failed when the status is ERROR/UNKNOWN/KILLED/FAILED. Possible status: SUBMITTED Submitted but ...
Construct the spark - submit command to kill a driver.: return: full command to kill a driver
def _build_spark_driver_kill_command(self): """ Construct the spark-submit command to kill a driver. :return: full command to kill a driver """ # If the spark_home is passed then build the spark-submit executable path using # the spark_home; otherwise assume that spark-s...
Get the task runner that can be used to run the given job.
def get_task_runner(local_task_job): """ Get the task runner that can be used to run the given job. :param local_task_job: The LocalTaskJob associated with the TaskInstance that needs to be executed. :type local_task_job: airflow.jobs.LocalTaskJob :return: The task runner to use to run the ...
Try to use a waiter from the below pull request
def _wait_for_task_ended(self): """ Try to use a waiter from the below pull request * https://github.com/boto/botocore/pull/1307 If the waiter is not available apply a exponential backoff * docs.aws.amazon.com/general/latest/gr/api-retries.html """ try:...
Queries mysql and returns a cursor to the results.
def _query_mysql(self): """ Queries mysql and returns a cursor to the results. """ mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id) conn = mysql.get_conn() cursor = conn.cursor() cursor.execute(self.sql) return cursor
Takes a cursor and writes results to a local file.
def _write_local_data_files(self, cursor): """ Takes a cursor, and writes results to a local file. :return: A dictionary where keys are filenames to be used as object names in GCS, and values are file handles to local files that contain the data for the GCS objects. ...
Configure a csv writer with the file_handle and write schema as headers for the new file.
def _configure_csv_file(self, file_handle, schema): """Configure a csv writer with the file_handle and write schema as headers for the new file. """ csv_writer = csv.writer(file_handle, encoding='utf-8', delimiter=self.field_delimiter) csv_writer.w...
Takes a cursor and writes the BigQuery schema in. json format for the results to a local file system.
def _write_local_schema_file(self, cursor): """ Takes a cursor, and writes the BigQuery schema in .json format for the results to a local file system. :return: A dictionary where key is a filename to be used as an object name in GCS, and values are file handles to local file...
Upload all of the file splits ( and optionally the schema. json file ) to Google cloud storage.
def _upload_to_gcs(self, files_to_upload): """ Upload all of the file splits (and optionally the schema .json file) to Google cloud storage. """ hook = GoogleCloudStorageHook( google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, delegate_to=self...
Takes a value from MySQLdb and converts it to a value that s safe for JSON/ Google cloud storage/ BigQuery. Dates are converted to UTC seconds. Decimals are converted to floats. Binary type fields are encoded with base64 as imported BYTES data must be base64 - encoded according to Bigquery SQL date type documentation: ...
def _convert_types(schema, col_type_dict, row): """ Takes a value from MySQLdb, and converts it to a value that's safe for JSON/Google cloud storage/BigQuery. Dates are converted to UTC seconds. Decimals are converted to floats. Binary type fields are encoded with base64, as impo...
Return a dict of column name and column type based on self. schema if not None.
def _get_col_type_dict(self): """ Return a dict of column name and column type based on self.schema if not None. """ schema = [] if isinstance(self.schema, string_types): schema = json.loads(self.schema) elif isinstance(self.schema, list): schema =...
Helper function that maps from MySQL fields to BigQuery fields. Used when a schema_filename is set.
def type_map(cls, mysql_type): """ Helper function that maps from MySQL fields to BigQuery fields. Used when a schema_filename is set. """ d = { FIELD_TYPE.INT24: 'INTEGER', FIELD_TYPE.TINY: 'INTEGER', FIELD_TYPE.BIT: 'INTEGER', FIE...
Authenticate a PasswordUser with the specified username/ password.
def authenticate(session, username, password): """ Authenticate a PasswordUser with the specified username/password. :param session: An active SQLAlchemy session :param username: The username :param password: The password :raise AuthenticationError: if an error occurred :return: a Pass...
Execute sqoop job
def execute(self, context): """ Execute sqoop job """ self.hook = SqoopHook( conn_id=self.conn_id, verbose=self.verbose, num_mappers=self.num_mappers, hcatalog_database=self.hcatalog_database, hcatalog_table=self.hcatalog_table,...
Saves the lineage to XCom and if configured to do so sends it to the backend.
def apply_lineage(func): """ Saves the lineage to XCom and if configured to do so sends it to the backend. """ backend = _get_backend() @wraps(func) def wrapper(self, context, *args, **kwargs): self.log.debug("Backend: %s, Lineage called with inlets: %s, outlets: %s", ...
Prepares the lineage inlets and outlets. Inlets can be:
def prepare_lineage(func): """ Prepares the lineage inlets and outlets. Inlets can be: * "auto" -> picks up any outlets from direct upstream tasks that have outlets defined, as such that if A -> B -> C and B does not have outlets but A does, these are provided as inlets. * "list of task_ids" -> p...
Returns the extra property by deserializing json.
def extra_dejson(self): """Returns the extra property by deserializing json.""" obj = {} if self.extra: try: obj = json.loads(self.extra) except Exception as e: self.log.exception(e) self.log.error("Failed parsing the json f...
Get a set of dates as a list based on a start end and delta delta can be something that can be added to datetime. datetime or a cron expression as a str
def date_range(start_date, end_date=None, num=None, delta=None): """ Get a set of dates as a list based on a start, end and delta, delta can be something that can be added to `datetime.datetime` or a cron expression as a `str` :Example:: date_range(datetime(2016, 1, 1), datetime(2016, 1, 3...
Returns the datetime of the form start_date + i * delta which is closest to dt for any non - negative integer i. Note that delta may be a datetime. timedelta or a dateutil. relativedelta >>> round_time ( datetime ( 2015 1 1 6 ) timedelta ( days = 1 )) datetime. datetime ( 2015 1 1 0 0 ) >>> round_time ( datetime ( 2015...
def round_time(dt, delta, start_date=timezone.make_aware(datetime.min)): """ Returns the datetime of the form start_date + i * delta which is closest to dt for any non-negative integer i. Note that delta may be a datetime.timedelta or a dateutil.relativedelta >>> round_time(datetime(2015, 1, 1, 6), ...
Determine the most appropriate time unit for an array of time durations specified in seconds. e. g. 5400 seconds = > minutes 36000 seconds = > hours
def infer_time_unit(time_seconds_arr): """ Determine the most appropriate time unit for an array of time durations specified in seconds. e.g. 5400 seconds => 'minutes', 36000 seconds => 'hours' """ if len(time_seconds_arr) == 0: return 'hours' max_time_seconds = max(time_seconds_arr)...
Convert an array of time durations in seconds to the specified time unit.
def scale_time_units(time_seconds_arr, unit): """ Convert an array of time durations in seconds to the specified time unit. """ if unit == 'minutes': return list(map(lambda x: x * 1.0 / 60, time_seconds_arr)) elif unit == 'hours': return list(map(lambda x: x * 1.0 / (60 * 60), time_s...
Get a datetime object representing n days ago. By default the time is set to midnight.
def days_ago(n, hour=0, minute=0, second=0, microsecond=0): """ Get a datetime object representing `n` days ago. By default the time is set to midnight. """ today = timezone.utcnow().replace( hour=hour, minute=minute, second=second, microsecond=microsecond) return...
Returns a list of Dag Runs for a specific DAG ID.: param dag_id: String identifier of a DAG: param state: queued|running|success...: return: List of DAG runs of a DAG with requested state or all runs if the state is not specified
def get_dag_runs(dag_id, state=None): """ Returns a list of Dag Runs for a specific DAG ID. :param dag_id: String identifier of a DAG :param state: queued|running|success... :return: List of DAG runs of a DAG with requested state, or all runs if the state is not specified """ dagbag = Da...
Initialize the role with the permissions and related view - menus.
def init_role(self, role_name, role_vms, role_perms): """ Initialize the role with the permissions and related view-menus. :param role_name: :param role_vms: :param role_perms: :return: """ pvms = self.get_session.query(sqla_models.PermissionView).all() ...
Delete the given Role
def delete_role(self, role_name): """Delete the given Role :param role_name: the name of a role in the ab_role table """ session = self.get_session role = session.query(sqla_models.Role)\ .filter(sqla_models.Role.name == role_name)\ .f...
Get all the roles associated with the user.
def get_user_roles(self, user=None): """ Get all the roles associated with the user. :param user: the ab_user in FAB model. :return: a list of roles associated with the user. """ if user is None: user = g.user if user.is_anonymous: public_...
Returns a set of tuples with the perm name and view menu name
def get_all_permissions_views(self): """ Returns a set of tuples with the perm name and view menu name """ perms_views = set() for role in self.get_user_roles(): perms_views.update({(perm_view.permission.name, perm_view.view_menu.name) ...
Return a set of dags that user has access to ( either read or write ).
def get_accessible_dag_ids(self, username=None): """ Return a set of dags that user has access to(either read or write). :param username: Name of the user. :return: A set of dag ids that the user could access. """ if not username: username = g.user i...
Verify whether a given user could perform certain permission ( e. g can_read can_write ) on the given dag_id.
def has_access(self, permission, view_name, user=None): """ Verify whether a given user could perform certain permission (e.g can_read, can_write) on the given dag_id. :param permission: permission on dag_id(e.g can_read, can_edit). :type permission: str :param view_name...
Whether the user has this role name
def _has_role(self, role_name_or_list): """ Whether the user has this role name """ if not isinstance(role_name_or_list, list): role_name_or_list = [role_name_or_list] return any( [r.name in role_name_or_list for r in self.get_user_roles()])
Whether the user has this perm
def _has_perm(self, permission_name, view_menu_name): """ Whether the user has this perm """ if hasattr(self, 'perms'): if (permission_name, view_menu_name) in self.perms: return True # rebuild the permissions set self._get_and_cache_perms() ...
FAB leaves faulty permissions that need to be cleaned up
def clean_perms(self): """ FAB leaves faulty permissions that need to be cleaned up """ self.log.debug('Cleaning faulty perms') sesh = self.get_session pvms = ( sesh.query(sqla_models.PermissionView) .filter(or_( sqla_models.Permiss...
Add the new permission view_menu to ab_permission_view_role if not exists. It will add the related entry to ab_permission and ab_view_menu two meta tables as well.
def _merge_perm(self, permission_name, view_menu_name): """ Add the new permission , view_menu to ab_permission_view_role if not exists. It will add the related entry to ab_permission and ab_view_menu two meta tables as well. :param permission_name: Name of the permission. ...
Workflow: 1. Fetch all the existing ( permissions view - menu ) from Airflow DB. 2. Fetch all the existing dag models that are either active or paused. Exclude the subdags. 3. Create both read and write permission view - menus relation for every dags from step 2 4. Find out all the dag specific roles ( excluded pubic a...
def create_custom_dag_permission_view(self, session=None): """ Workflow: 1. Fetch all the existing (permissions, view-menu) from Airflow DB. 2. Fetch all the existing dag models that are either active or paused. Exclude the subdags. 3. Create both read and write permission view-m...
Admin should have all the permission - views. Add the missing ones to the table for admin.
def update_admin_perm_view(self): """ Admin should have all the permission-views. Add the missing ones to the table for admin. :return: None. """ pvms = self.get_session.query(sqla_models.PermissionView).all() pvms = [p for p in pvms if p.permission and p.view_me...
1. Init the default role ( Admin Viewer User Op public ) with related permissions. 2. Init the custom role ( dag - user ) with related permissions.
def sync_roles(self): """ 1. Init the default role(Admin, Viewer, User, Op, public) with related permissions. 2. Init the custom role(dag-user) with related permissions. :return: None. """ self.log.debug('Start syncing user roles.') # Create global all...
Sync permissions for given dag id. The dag id surely exists in our dag bag as only/ refresh button or cli. sync_perm will call this function
def sync_perm_for_dag(self, dag_id, access_control=None): """ Sync permissions for given dag id. The dag id surely exists in our dag bag as only / refresh button or cli.sync_perm will call this function :param dag_id: the ID of the DAG whose permissions should be updated :type d...