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."""importjsonimportreimportwarningsfromcopyimportdeepcopyfromtypingimportAny,Dict,Optional,Sequence,Tuple,Unionfromurllib.parseimportunquote,urlparseimportyamlfromgoogle.api_core.retryimportRetryfromgoogle.cloud.devtools.cloudbuild_v1.typesimportBuild,BuildTrigger,RepoSourcefromairflow.exceptionsimportAirflowExceptionfromairflow.modelsimportBaseOperatorfromairflow.providers.google.cloud.hooks.cloud_buildimportCloudBuildHook
[docs]classCloudBuildCancelBuildOperator(BaseOperator):""" 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. :type id_: str :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. :type project_id: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
[docs]classCloudBuildCreateBuildOperator(BaseOperator):""" 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: Optional, 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`. Only either build or body should be passed. :type build: Optional[Union[dict, `google.cloud.devtools.cloudbuild_v1.types.Build`]] :param body: (Deprecated) The build resource to create. This parameter has been deprecated. You should pass the build parameter instead. :type body: Optional[dict] :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. :type project_id: Optional[str] :param wait: Optional, wait for operation to finish. :type wait: Optional[bool] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
def__init__(self,*,build:Optional[Union[Dict,Build,str]]=None,body:Optional[Dict]=None,project_id:Optional[str]=None,wait:bool=True,retry:Optional[Retry]=None,timeout:Optional[float]=None,metadata:Optional[Sequence[Tuple[str,str]]]=None,gcp_conn_id:str="google_cloud_default",impersonation_chain:Optional[Union[str,Sequence[str]]]=None,**kwargs,)->None:super().__init__(**kwargs)self.build=build# Not template fields to keep original valueself.build_raw=buildself.body=bodyself.project_id=project_idself.wait=waitself.retry=retryself.timeout=timeoutself.metadata=metadataself.gcp_conn_id=gcp_conn_idself.impersonation_chain=impersonation_chainifself.bodyandself.build:raiseAirflowException("Either build or body should be passed.")ifself.body:warnings.warn("The body parameter has been deprecated. You should pass body using the build parameter.",DeprecationWarning,stacklevel=4,)self.build=self.build_raw=self.body
[docs]defprepare_template(self)->None:# if no file is specified, skipifnotisinstance(self.build_raw,str):returnwithopen(self.build_raw)asfile:ifany(self.build_raw.endswith(ext)forextin['.yaml','.yml']):self.build=yaml.load(file.read(),Loader=yaml.FullLoader)ifself.build_raw.endswith('.json'):self.build=json.loads(file.read())
[docs]classCloudBuildCreateBuildTriggerOperator(BaseOperator):""" 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` :type trigger: Union[dict, `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. :type project_id: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
[docs]classCloudBuildDeleteBuildTriggerOperator(BaseOperator):""" 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. :type trigger_id: str :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. :type project_id: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] """
[docs]classCloudBuildGetBuildOperator(BaseOperator):""" 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. :type id_: str :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. :type project_id: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
[docs]classCloudBuildGetBuildTriggerOperator(BaseOperator):""" 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. :type trigger_id: str :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. :type project_id: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
[docs]classCloudBuildListBuildTriggersOperator(BaseOperator):""" 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. :type location: string :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. :type project_id: Optional[str] :param page_size: Optional, number of results to return in the list. :type page_size: Optional[int] :param page_token: Optional, token to provide to skip to a particular spot in the list. :type page_token: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: List[dict] """
[docs]classCloudBuildListBuildsOperator(BaseOperator):""" 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. :type location: string :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. :type project_id: str :param page_size: Optional, number of results to return in the list. :type page_size: Optional[int] :param filter_: Optional, the raw filter text to constrain the results. :type filter_: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: List[dict] """
[docs]classCloudBuildRetryBuildOperator(BaseOperator):""" Creates a new build based on the specified build. This method 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. :type id_: str :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. :type project_id: str :param wait: Optional, wait for operation to finish. :type wait: Optional[bool] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
[docs]classCloudBuildRunBuildTriggerOperator(BaseOperator):""" 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. :type trigger_id: str :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` :type source: Union[dict, `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. :type project_id: str :param wait: Optional, wait for operation to finish. :type wait: Optional[bool] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
[docs]classCloudBuildUpdateBuildTriggerOperator(BaseOperator):""" 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. :type trigger_id: str :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` :type trigger: Union[dict, `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. :type project_id: Optional[str] :param retry: Optional, a retry object used to retry requests. If `None` is specified, requests will not be retried. :type retry: Optional[Retry] :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. :type timeout: Optional[float] :param metadata: Optional, additional metadata that is provided to the method. :type metadata: Optional[Sequence[Tuple[str, str]]] :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: Optional[str] :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). :type impersonation_chain: Union[str, Sequence[str]] :rtype: dict """
[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 :type build: Union[Dict, Build] """def__init__(self,build:Union[Dict,Build])->None:ifisinstance(build,Build):self.build=Build(build)self.build=deepcopy(build)def_verify_source(self)->None:ifnot(("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:""" Processes the body passed in the constructor :return: the body. :rtype: `google.cloud.devtools.cloudbuild_v1.types.Build` """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=urlparse(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=urlparse(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={"bucket":url_parts.hostname,"object_":url_parts.path[1:],}ifurl_parts.fragment:source_dict["generation"]=int(url_parts.fragment)returnsource_dict