Source code for airflow.providers.dbt.cloud.operators.dbt
# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.from__future__importannotationsimportjsonimporttimeimportwarningsfrompathlibimportPathfromtypingimportTYPE_CHECKING,Anyfromairflow.exceptionsimportAirflowExceptionfromairflow.modelsimportBaseOperator,BaseOperatorLink,XComfromairflow.providers.dbt.cloud.hooks.dbtimport(DbtCloudHook,DbtCloudJobRunException,DbtCloudJobRunStatus,JobRunInfo,)fromairflow.providers.dbt.cloud.triggers.dbtimportDbtCloudRunJobTriggerifTYPE_CHECKING:fromairflow.utils.contextimportContext
[docs]classDbtCloudRunJobOperatorLink(BaseOperatorLink):""" Operator link for DbtCloudRunJobOperator. This link allows users to monitor the triggered job run directly in dbt Cloud. """
[docs]classDbtCloudRunJobOperator(BaseOperator):""" Executes a dbt Cloud job. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DbtCloudRunJobOperator` :param dbt_cloud_conn_id: The connection ID for connecting to dbt Cloud. :param job_id: The ID of a dbt Cloud job. :param account_id: Optional. The ID of a dbt Cloud account. :param trigger_reason: Optional. Description of the reason to trigger the job. Defaults to "Triggered via Apache Airflow by task <task_id> in the <dag_id> DAG." :param steps_override: Optional. List of dbt commands to execute when triggering the job instead of those configured in dbt Cloud. :param schema_override: Optional. Override the destination schema in the configured target for this job. :param wait_for_termination: Flag to wait on a job run's termination. By default, this feature is enabled but could be disabled to perform an asynchronous wait for a long-running job run execution using the ``DbtCloudJobRunSensor``. :param timeout: Time in seconds to wait for a job run to reach a terminal status for non-asynchronous waits. Used only if ``wait_for_termination`` is True. Defaults to 7 days. :param check_interval: Time in seconds to check on a job run's status for non-asynchronous waits. Used only if ``wait_for_termination`` is True. Defaults to 60 seconds. :param additional_run_config: Optional. Any additional parameters that should be included in the API request when triggering the job. :param deferrable: Run operator in the deferrable mode :return: The ID of the triggered dbt Cloud job run. """
[docs]defexecute(self,context:Context):ifself.trigger_reasonisNone:self.trigger_reason=(f"Triggered via Apache Airflow by task {self.task_id!r} in the {self.dag.dag_id} DAG.")self.hook=DbtCloudHook(self.dbt_cloud_conn_id)trigger_job_response=self.hook.trigger_job_run(account_id=self.account_id,job_id=self.job_id,cause=self.trigger_reason,steps_override=self.steps_override,schema_override=self.schema_override,additional_run_config=self.additional_run_config,)self.run_id=trigger_job_response.json()["data"]["id"]job_run_url=trigger_job_response.json()["data"]["href"]# Push the ``job_run_url`` value to XCom regardless of what happens during execution so that the job# run can be monitored via the operator link.context["ti"].xcom_push(key="job_run_url",value=job_run_url)ifself.wait_for_termination:ifself.deferrableisFalse:self.log.info("Waiting for job run %s to terminate.",str(self.run_id))ifself.hook.wait_for_job_run_status(run_id=self.run_id,account_id=self.account_id,expected_statuses=DbtCloudJobRunStatus.SUCCESS.value,check_interval=self.check_interval,timeout=self.timeout,):self.log.info("Job run %s has completed successfully.",str(self.run_id))else:raiseDbtCloudJobRunException(f"Job run {self.run_id} has failed or has been cancelled.")returnself.run_idelse:end_time=time.time()+self.timeoutjob_run_info=JobRunInfo(account_id=self.account_id,run_id=self.run_id)job_run_status=self.hook.get_job_run_status(**job_run_info)ifnotDbtCloudJobRunStatus.is_terminal(job_run_status):self.defer(timeout=self.execution_timeout,trigger=DbtCloudRunJobTrigger(conn_id=self.dbt_cloud_conn_id,run_id=self.run_id,end_time=end_time,account_id=self.account_id,poll_interval=self.check_interval,),method_name="execute_complete",)elifjob_run_status==DbtCloudJobRunStatus.SUCCESS.value:self.log.info("Job run %s has completed successfully.",str(self.run_id))returnself.run_idelifjob_run_statusin(DbtCloudJobRunStatus.CANCELLED.value,DbtCloudJobRunStatus.ERROR.value,):raiseDbtCloudJobRunException(f"Job run {self.run_id} has failed or has been cancelled.")else:ifself.deferrableisTrue:warnings.warn("Argument `wait_for_termination` is False and `deferrable` is True , hence ""`deferrable` parameter doesn't have any effect",)returnself.run_id
[docs]defexecute_complete(self,context:Context,event:dict[str,Any])->int:""" Callback for when the trigger fires - returns immediately. Relies on trigger to throw an exception, otherwise it assumes execution was successful. """ifevent["status"]=="error":raiseAirflowException(event["message"])self.log.info(event["message"])returnint(event["run_id"])
[docs]defon_kill(self)->None:ifself.run_id:self.hook.cancel_job_run(account_id=self.account_id,run_id=self.run_id)ifself.hook.wait_for_job_run_status(run_id=self.run_id,account_id=self.account_id,expected_statuses=DbtCloudJobRunStatus.CANCELLED.value,check_interval=self.check_interval,timeout=self.timeout,):self.log.info("Job run %s has been cancelled successfully.",str(self.run_id))
[docs]classDbtCloudGetJobRunArtifactOperator(BaseOperator):""" Download artifacts from a dbt Cloud job run. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DbtCloudGetJobRunArtifactOperator` :param dbt_cloud_conn_id: The connection ID for connecting to dbt Cloud. :param run_id: The ID of a dbt Cloud job run. :param path: The file path related to the artifact file. Paths are rooted at the target/ directory. Use "manifest.json", "catalog.json", or "run_results.json" to download dbt-generated artifacts for the run. :param account_id: Optional. The ID of a dbt Cloud account. :param step: Optional. The index of the Step in the Run to query for artifacts. The first step in the run has the index 1. If the step parameter is omitted, artifacts for the last step in the run will be returned. :param output_file_name: Optional. The desired file name for the download artifact file. Defaults to <run_id>_<path> (e.g. "728368_run_results.json"). """
[docs]defexecute(self,context:Context)->str:hook=DbtCloudHook(self.dbt_cloud_conn_id)response=hook.get_job_run_artifact(run_id=self.run_id,path=self.path,account_id=self.account_id,step=self.step)output_file_path=Path(self.output_file_name)output_file_path.parent.mkdir(parents=True,exist_ok=True)withoutput_file_path.open(mode="w")asfile:self.log.info("Writing %s artifact for job run %s to %s.",self.path,self.run_id,self.output_file_name)ifself.path.endswith(".json"):json.dump(response.json(),file)else:file.write(response.text)returnself.output_file_name
[docs]classDbtCloudListJobsOperator(BaseOperator):""" List jobs in a dbt Cloud project. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DbtCloudListJobsOperator` Retrieves metadata for all jobs tied to a specified dbt Cloud account. If a ``project_id`` is supplied, only jobs pertaining to this project id will be retrieved. :param account_id: Optional. If an account ID is not provided explicitly, the account ID from the dbt Cloud connection will be used. :param order_by: Optional. Field to order the result by. Use '-' to indicate reverse order. For example, to use reverse order by the run ID use ``order_by=-id``. :param project_id: Optional. The ID of a dbt Cloud project. """
[docs]defexecute(self,context:Context)->list:hook=DbtCloudHook(self.dbt_cloud_conn_id)list_jobs_response=hook.list_jobs(account_id=self.account_id,order_by=self.order_by,project_id=self.project_id)buffer=[]forjob_metadatainlist_jobs_response:forjobinjob_metadata.json()["data"]:buffer.append(job["id"])self.log.info("Jobs in the specified dbt Cloud account are: %s",", ".join(map(str,buffer)))returnbuffer