Source code for airflow.providers.google.cloud.operators.functions
## 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."""This module contains Google Cloud Functions operators."""from__future__importannotationsimportrefromtypingimportTYPE_CHECKING,Any,Sequencefromgoogleapiclient.errorsimportHttpErrorfromairflow.exceptionsimportAirflowExceptionfromairflow.providers.google.cloud.hooks.functionsimportCloudFunctionsHookfromairflow.providers.google.cloud.links.cloud_functionsimport(CloudFunctionsDetailsLink,CloudFunctionsListLink,)fromairflow.providers.google.cloud.operators.cloud_baseimportGoogleCloudBaseOperatorfromairflow.providers.google.cloud.utils.field_validatorimport(GcpBodyFieldValidator,GcpFieldValidationException,)fromairflow.versionimportversionifTYPE_CHECKING:fromairflow.utils.contextimportContextdef_validate_available_memory_in_mb(value):ifint(value)<=0:raiseGcpFieldValidationException("The available memory has to be greater than 0")def_validate_max_instances(value):ifint(value)<=0:raiseGcpFieldValidationException("The max instances parameter has to be greater than 0")
[docs]CLOUD_FUNCTION_VALIDATION:list[dict[str,Any]]=[dict(name="name",regexp="^.+$"),dict(name="description",regexp="^.+$",optional=True),dict(name="entryPoint",regexp=r"^.+$",optional=True),dict(name="runtime",regexp=r"^.+$",optional=True),dict(name="timeout",regexp=r"^.+$",optional=True),dict(name="availableMemoryMb",custom_validation=_validate_available_memory_in_mb,optional=True),dict(name="labels",optional=True),dict(name="environmentVariables",optional=True),dict(name="network",regexp=r"^.+$",optional=True),dict(name="maxInstances",optional=True,custom_validation=_validate_max_instances),dict(name="source_code",type="union",fields=[dict(name="sourceArchiveUrl",regexp=r"^.+$"),dict(name="sourceRepositoryUrl",regexp=r"^.+$",api_version="v1beta2"),dict(name="sourceRepository",type="dict",fields=[dict(name="url",regexp=r"^.+$")]),dict(name="sourceUploadUrl"),],),dict(name="trigger",type="union",fields=[dict(name="httpsTrigger",type="dict",fields=[# This dict should be empty at input (url is added at output)],),dict(name="eventTrigger",type="dict",fields=[dict(name="eventType",regexp=r"^.+$"),dict(name="resource",regexp=r"^.+$"),dict(name="service",regexp=r"^.+$",optional=True),dict(name="failurePolicy",type="dict",optional=True,fields=[dict(name="retry",type="dict",optional=True)],),],),],),]
[docs]classCloudFunctionDeployFunctionOperator(GoogleCloudBaseOperator):""" Create or update a function in Google Cloud Functions. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudFunctionDeployFunctionOperator` :param location: Google Cloud region where the function should be created. :param body: Body of the Cloud Functions definition. The body must be a Cloud Functions dictionary as described in: https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions . Different API versions require different variants of the Cloud Functions dictionary. :param project_id: (Optional) Google Cloud project ID where the function should be created. :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. Default 'google_cloud_default'. :param api_version: (Optional) API version used (for example v1 - default - or v1beta1). :param zip_path: Path to zip file containing source code of the function. If the path is set, the sourceUploadUrl should not be specified in the body or it should be empty. Then the zip file will be uploaded using the upload URL generated via generateUploadUrl from the Cloud Functions API. :param validate_body: If set to False, body validation is not performed. :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). """# [START gcf_function_deploy_template_fields]
def__init__(self,*,location:str,body:dict,project_id:str|None=None,gcp_conn_id:str="google_cloud_default",api_version:str="v1",zip_path:str|None=None,validate_body:bool=True,impersonation_chain:str|Sequence[str]|None=None,**kwargs,)->None:self.project_id=project_idself.location=locationself.body=bodyself.gcp_conn_id=gcp_conn_idself.api_version=api_versionself.zip_path=zip_pathself.zip_path_preprocessor=ZipPathPreprocessor(body,zip_path)self._field_validator:GcpBodyFieldValidator|None=Noneself.impersonation_chain=impersonation_chainifvalidate_body:self._field_validator=GcpBodyFieldValidator(CLOUD_FUNCTION_VALIDATION,api_version=api_version)self._validate_inputs()super().__init__(**kwargs)def_validate_inputs(self)->None:ifnotself.location:raiseAirflowException("The required parameter 'location' is missing")ifnotself.body:raiseAirflowException("The required parameter 'body' is missing")self.zip_path_preprocessor.preprocess_body()def_validate_all_body_fields(self)->None:ifself._field_validator:self._field_validator.validate(self.body)def_create_new_function(self,hook)->None:hook.create_new_function(project_id=self.project_id,location=self.location,body=self.body)def_update_function(self,hook)->None:hook.update_function(self.body["name"],self.body,self.body.keys())def_check_if_function_exists(self,hook)->bool:name=self.body.get("name")ifnotname:raiseGcpFieldValidationException(f"The 'name' field should be present in body: '{self.body}'.")try:hook.get_function(name)exceptHttpErrorase:status=e.resp.statusifstatus==404:returnFalseraiseereturnTruedef_upload_source_code(self,hook):returnhook.upload_function_zip(project_id=self.project_id,location=self.location,zip_path=self.zip_path)def_set_airflow_version_label(self)->None:if"labels"notinself.body.keys():self.body["labels"]={}self.body["labels"].update({"airflow-version":"v"+version.replace(".","-").replace("+","-")})
[docs]classZipPathPreprocessor:""" Pre-processes zip path parameter. Responsible for checking if the zip path parameter is correctly specified in relation with source_code body fields. Non empty zip path parameter is special because it is mutually exclusive with sourceArchiveUrl and sourceRepository body fields. It is also mutually exclusive with non-empty sourceUploadUrl. The pre-process modifies sourceUploadUrl body field in special way when zip_path is not empty. An extra step is run when execute method is called and sourceUploadUrl field value is set in the body with the value returned by generateUploadUrl Cloud Function API method. :param body: Body passed to the create/update method calls. :param zip_path: (optional) Path to zip file containing source code of the function. If the path is set, the sourceUploadUrl should not be specified in the body or it should be empty. Then the zip file will be uploaded using the upload URL generated via generateUploadUrl from the Cloud Functions API. """
def__init__(self,body:dict,zip_path:str|None=None)->None:self.body=bodyself.zip_path=zip_path@staticmethoddef_is_present_and_empty(dictionary,field)->bool:returnfieldindictionaryandnotdictionary[field]def_verify_upload_url_and_no_zip_path(self)->None:ifself._is_present_and_empty(self.body,GCF_SOURCE_UPLOAD_URL):ifnotself.zip_path:raiseAirflowException("Parameter '{url}' is empty in the body and argument '{path}' ""is missing or empty. You need to have non empty '{path}' ""when '{url}' is present and empty.".format(url=GCF_SOURCE_UPLOAD_URL,path=GCF_ZIP_PATH))def_verify_upload_url_and_zip_path(self)->None:ifGCF_SOURCE_UPLOAD_URLinself.bodyandself.zip_path:ifnotself.body[GCF_SOURCE_UPLOAD_URL]:self.upload_function=Trueelse:raiseAirflowException(f"Only one of '{GCF_SOURCE_UPLOAD_URL}' in body or '{GCF_ZIP_PATH}' argument allowed. "f"Found both.")def_verify_archive_url_and_zip_path(self)->None:ifGCF_SOURCE_ARCHIVE_URLinself.bodyandself.zip_path:raiseAirflowException(f"Only one of '{GCF_SOURCE_ARCHIVE_URL}' in body or '{GCF_ZIP_PATH}' argument allowed. "f"Found both.")
[docs]defshould_upload_function(self)->bool:"""Checks if function source should be uploaded."""ifself.upload_functionisNone:raiseAirflowException("validate() method has to be invoked before should_upload_function")returnself.upload_function
[docs]defpreprocess_body(self)->None:"""Modifies sourceUploadUrl body field in special way when zip_path is not empty."""self._verify_archive_url_and_zip_path()self._verify_upload_url_and_zip_path()self._verify_upload_url_and_no_zip_path()ifself.upload_functionisNone:self.upload_function=False
[docs]classCloudFunctionDeleteFunctionOperator(GoogleCloudBaseOperator):""" Deletes the specified function from Google Cloud Functions. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudFunctionDeleteFunctionOperator` :param name: A fully-qualified function name, matching the pattern: `^projects/[^/]+/locations/[^/]+/functions/[^/]+$` :param gcp_conn_id: The connection ID to use to connect to Google Cloud. :param api_version: API version used (for example v1 or v1beta1). :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). """# [START gcf_function_delete_template_fields]
def__init__(self,*,name:str,gcp_conn_id:str="google_cloud_default",api_version:str="v1",impersonation_chain:str|Sequence[str]|None=None,project_id:str|None=None,**kwargs,)->None:self.name=nameself.project_id=project_idself.gcp_conn_id=gcp_conn_idself.api_version=api_versionself.impersonation_chain=impersonation_chainself._validate_inputs()super().__init__(**kwargs)def_validate_inputs(self)->None:ifnotself.name:raiseAttributeError("Empty parameter: name")else:pattern=FUNCTION_NAME_COMPILED_PATTERNifnotpattern.match(self.name):raiseAttributeError(f"Parameter name must match pattern: {FUNCTION_NAME_PATTERN}")
[docs]defexecute(self,context:Context):hook=CloudFunctionsHook(gcp_conn_id=self.gcp_conn_id,api_version=self.api_version,impersonation_chain=self.impersonation_chain,)try:project_id=self.project_idorhook.project_idifproject_id:CloudFunctionsListLink.persist(context=context,task_instance=self,project_id=project_id,)returnhook.delete_function(self.name)exceptHttpErrorase:status=e.resp.statusifstatus==404:self.log.info("The function does not exist in this project")returnNoneelse:self.log.error("An error occurred. Exiting.")raisee
[docs]classCloudFunctionInvokeFunctionOperator(GoogleCloudBaseOperator):""" Invokes a deployed Cloud Function. To be used for testing purposes as very limited traffic is allowed. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudFunctionDeployFunctionOperator` :param function_id: ID of the function to be called :param input_data: Input to be passed to the function :param location: The location where the function is located. :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 Google Cloud connection is used. :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). :return: None """
[docs]defexecute(self,context:Context):hook=CloudFunctionsHook(api_version=self.api_version,gcp_conn_id=self.gcp_conn_id,impersonation_chain=self.impersonation_chain,)self.log.info("Calling function %s.",self.function_id)result=hook.call_function(function_id=self.function_id,input_data=self.input_data,location=self.location,project_id=self.project_id,)self.log.info("Function called successfully. Execution id %s",result.get("executionId"))self.xcom_push(context=context,key="execution_id",value=result.get("executionId"))project_id=self.project_idorhook.project_idifproject_id:CloudFunctionsDetailsLink.persist(context=context,task_instance=self,location=self.location,project_id=project_id,function_name=self.function_id,)returnresult