Source code for airflow.providers.google.cloud.operators.cloud_build
## 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."""Operators that integrates with Google Cloud Build service."""from__future__importannotationsimportjsonimportrefromcopyimportdeepcopyfromtypingimportTYPE_CHECKING,Any,Sequencefromurllib.parseimportunquote,urlsplitfromgoogle.api_core.gapic_v1.methodimportDEFAULT,_MethodDefaultfromgoogle.cloud.devtools.cloudbuild_v1.typesimportBuild,BuildTrigger,RepoSourcefromairflow.configurationimportconffromairflow.exceptionsimportAirflowExceptionfromairflow.providers.google.cloud.hooks.cloud_buildimportCloudBuildHookfromairflow.providers.google.cloud.links.cloud_buildimport(CloudBuildLink,CloudBuildListLink,CloudBuildTriggerDetailsLink,CloudBuildTriggersListLink,)fromairflow.providers.google.cloud.operators.cloud_baseimportGoogleCloudBaseOperatorfromairflow.providers.google.cloud.triggers.cloud_buildimportCloudBuildCreateBuildTriggerfromairflow.providers.google.common.constsimportGOOGLE_DEFAULT_DEFERRABLE_METHOD_NAMEfromairflow.providers.google.common.hooks.base_googleimportPROVIDE_PROJECT_IDfromairflow.utilsimportyamlfromairflow.utils.helpersimportexactly_oneifTYPE_CHECKING:fromgoogle.api_core.retryimportRetryfromairflow.utils.contextimportContext
[docs]classCloudBuildCancelBuildOperator(GoogleCloudBaseOperator):""" Cancels a build in progress. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildCancelBuildOperator` :param id_: The ID of the build. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classCloudBuildCreateBuildOperator(GoogleCloudBaseOperator):""" Starts a build with the specified configuration. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildCreateBuildOperator` :param build: The build resource to create. If a dict is provided, it must be of the same form as the protobuf message `google.cloud.devtools.cloudbuild_v1.types.Build`. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param wait: Optional, wait for operation to finish. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. :param deferrable: Run operator in the deferrable mode :param location: The location of the project. """
def__init__(self,*,build:dict|Build,project_id:str=PROVIDE_PROJECT_ID,wait:bool=True,retry:Retry|_MethodDefault=DEFAULT,timeout:float|None=None,metadata:Sequence[tuple[str,str]]=(),gcp_conn_id:str="google_cloud_default",impersonation_chain:str|Sequence[str]|None=None,poll_interval:float=4.0,deferrable:bool=conf.getboolean("operators","default_deferrable",fallback=False),location:str="global",**kwargs,)->None:super().__init__(**kwargs)self.build=build# Not template fields to keep original valueself.build_raw=buildself.project_id=project_idself.wait=waitself.retry=retryself.timeout=timeoutself.metadata=metadataself.gcp_conn_id=gcp_conn_idself.impersonation_chain=impersonation_chainself.poll_interval=poll_intervalself.deferrable=deferrableself.location=location
[docs]defprepare_template(self)->None:# if no file is specified, skipifnotisinstance(self.build_raw,str):returnwithopen(self.build_raw)asfile:ifself.build_raw.endswith((".yaml",".yml")):self.build=yaml.safe_load(file.read())ifself.build_raw.endswith(".json"):self.build=json.loads(file.read())
[docs]defexecute_complete(self,context:Context,event:dict):ifevent["status"]=="success":hook=CloudBuildHook(gcp_conn_id=self.gcp_conn_id,impersonation_chain=self.impersonation_chain,)self.log.info("Cloud Build completed with response %s ",event["message"])project_id=self.project_idorhook.project_idifproject_id:CloudBuildLink.persist(context=context,task_instance=self,project_id=project_id,region=self.location,build_id=event["id_"],)returnevent["instance"]else:raiseAirflowException(f"Unexpected error in the operation: {event['message']}")
[docs]classCloudBuildCreateBuildTriggerOperator(GoogleCloudBaseOperator):""" Creates a new BuildTrigger. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildCreateBuildTriggerOperator` :param trigger: The BuildTrigger to create. If a dict is provided, it must be of the same form as the protobuf message `google.cloud.devtools.cloudbuild_v1.types.BuildTrigger` :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classCloudBuildDeleteBuildTriggerOperator(GoogleCloudBaseOperator):""" Deletes a BuildTrigger by its project ID and trigger ID. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildDeleteBuildTriggerOperator` :param trigger_id: The ID of the BuildTrigger to delete. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classCloudBuildGetBuildOperator(GoogleCloudBaseOperator):""" Returns information about a previously requested build. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildGetBuildOperator` :param id_: The ID of the build. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classCloudBuildGetBuildTriggerOperator(GoogleCloudBaseOperator):""" Returns information about a BuildTrigger. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildGetBuildTriggerOperator` :param trigger_id: The ID of the BuildTrigger to get. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classCloudBuildListBuildTriggersOperator(GoogleCloudBaseOperator):""" Lists existing BuildTriggers. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildListBuildTriggersOperator` :param location: The location of the project. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param page_size: Optional, number of results to return in the list. :param page_token: Optional, token to provide to skip to a particular spot in the list. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """
[docs]classCloudBuildListBuildsOperator(GoogleCloudBaseOperator):""" Lists previously requested builds. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildListBuildsOperator` :param location: The location of the project. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param page_size: Optional, number of results to return in the list. :param filter_: Optional, the raw filter text to constrain the results. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """
[docs]classCloudBuildRetryBuildOperator(GoogleCloudBaseOperator):""" Creates a new build using the original build request, which may or may not result in an identical build. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildRetryBuildOperator` :param id_: Build ID of the original build. :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param wait: Optional, wait for operation to finish. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classCloudBuildRunBuildTriggerOperator(GoogleCloudBaseOperator):""" Runs a BuildTrigger at a particular source revision. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildRunBuildTriggerOperator` :param trigger_id: The ID of the trigger. :param source: Source to build against this trigger. If a dict is provided, it must be of the same form as the protobuf message `google.cloud.devtools.cloudbuild_v1.types.RepoSource` :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param wait: Optional, wait for operation to finish. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classCloudBuildUpdateBuildTriggerOperator(GoogleCloudBaseOperator):""" Updates a BuildTrigger by its project ID and trigger ID. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildUpdateBuildTriggerOperator` :param trigger_id: The ID of the trigger. :param trigger: The BuildTrigger to create. If a dict is provided, it must be of the same form as the protobuf message `google.cloud.devtools.cloudbuild_v1.types.BuildTrigger` :param project_id: Optional, Google Cloud Project project_id where the function belongs. If set to None or missing, the default project_id from the GCP connection is used. :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional, the amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional, additional metadata that is provided to the method. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param location: The location of the project. """
[docs]classBuildProcessor:""" Processes build configurations to add additional functionality to support the use of operators. The following improvements are made: * It is required to provide the source and only one type can be given, * It is possible to provide the source as the URL address instead dict. :param build: The request body of the build. See: https://cloud.google.com/cloud-build/docs/api/reference/rest/Shared.Types/Build """def__init__(self,build:dict|Build)->None:self.build=deepcopy(build)def_verify_source(self)->None:ifnotexactly_one("storage_source"inself.build["source"],"repo_source"inself.build["source"]):raiseAirflowException("The source could not be determined. Please choose one data source from: ""storage_source and repo_source.")def_reformat_source(self)->None:self._reformat_repo_source()self._reformat_storage_source()def_reformat_repo_source(self)->None:if"repo_source"notinself.build["source"]:returnrepo_source=self.build["source"]["repo_source"]ifnotisinstance(repo_source,str):returnself.build["source"]["repo_source"]=self._convert_repo_url_to_dict(repo_source)def_reformat_storage_source(self)->None:if"storage_source"notinself.build["source"]:returnstorage_source=self.build["source"]["storage_source"]ifnotisinstance(storage_source,str):returnself.build["source"]["storage_source"]=self._convert_storage_url_to_dict(storage_source)
[docs]defprocess_body(self)->Build:""" Process the body passed in the constructor. :return: the body. """if"source"inself.build:self._verify_source()self._reformat_source()returnBuild(self.build)
@staticmethoddef_convert_repo_url_to_dict(source:str)->dict[str,Any]:""" Convert url to repository in Google Cloud Source to a format supported by the API. Example valid input: .. code-block:: none https://source.cloud.google.com/airflow-project/airflow-repo/+/branch-name: """url_parts=urlsplit(source)match=REGEX_REPO_PATH.search(url_parts.path)ifurl_parts.scheme!="https"orurl_parts.hostname!="source.cloud.google.com"ornotmatch:raiseAirflowException("Invalid URL. You must pass the URL in the format: ""https://source.cloud.google.com/airflow-project/airflow-repo/+/branch-name:")project_id=unquote(match.group("project_id"))repo_name=unquote(match.group("repo_name"))branch_name=unquote(match.group("branch_name"))ifmatch.group("branch_name")else"master"source_dict={"project_id":project_id,"repo_name":repo_name,"branch_name":branch_name,}returnsource_dict@staticmethoddef_convert_storage_url_to_dict(storage_url:str)->dict[str,Any]:""" Convert url to object in Google Cloud Storage to a format supported by the API. Example valid input: .. code-block:: none gs://bucket-name/object-name.tar.gz """url_parts=urlsplit(storage_url)ifurl_parts.scheme!="gs"ornoturl_parts.hostnameornoturl_parts.pathorurl_parts.path=="/":raiseAirflowException("Invalid URL. You must pass the URL in the format: ""gs://bucket-name/object-name.tar.gz#24565443")source_dict:dict[str,Any]={"bucket":url_parts.hostname,"object_":url_parts.path[1:],}ifurl_parts.fragment:source_dict["generation"]=int(url_parts.fragment)returnsource_dict