def test_validate_should_raise_if_version_mismatch_is_found(self): specification = [dict(name="name", allow_empty=False, api_version='v2')] body = {"name": "value"} validator = GcpBodyFieldValidator(specification, 'v1') validator.validate(body)
def test_validate_should_not_allow_both_type_and_allow_empty_in_a_spec(self): specification = [dict(name="labels", optional=True, type="dict", allow_empty=True)] body = {"labels": 1} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(GcpValidationSpecificationException): validator.validate(body)
def test_validate_should_fail_if_value_is_not_dict_as_per_specs(self): specification = [dict(name="labels", optional=True, type="dict")] body = {"labels": 1} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_raise_exception_if_optional_clause_is_false_and_field_not_present(self): specification = [dict(name="name", allow_empty=False, optional=False)] body = {} validator = GcpBodyFieldValidator(specification, 'v1') with self.assertRaises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_fail_if_specification_is_none(self): specification = None body = {} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(TypeError): validator.validate(body)
def test_validate_should_raise_if_empty_clause_is_false(self): specification = [dict(name="name", allow_empty=False)] body = {"name": None} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_raise_exception_if_field_is_not_present(self): specification = [dict(name="name", allow_empty=False)] body = {} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_raise_exception_name_attribute_is_missing_from_specs(self): specification = [dict(allow_empty=False)] body = {} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(KeyError): validator.validate(body)
def test_validate_should_fail_if_body_is_not_a_dict(self): specification = [dict(name="name", allow_empty=False)] body = [{"name": "bigquery"}] validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(AttributeError): validator.validate(body)
def test_validate_should_fail_for_set_allow_empty_when_field_is_none(self): specification = [dict(name="name", allow_empty=True)] body = {"name": None} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_fail_if_there_is_no_nested_field_for_union(self): specification = [dict(name="an_union", type="union", optional=False, fields=[])] body = {} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(GcpValidationSpecificationException): validator.validate(body)
def test_validate_should_fail_if_body_is_none(self): specification = [] body = None validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(AttributeError): validator.validate(body)
def test_validate_should_fail_when_value_does_not_match_regex(self): specification = [ dict(name="an_union", type="union", fields=[dict(name="variant_1", regexp=r'[^a-z]'),]) ] body = {"variant_1": "abc"} validator = GcpBodyFieldValidator(specification, 'v1') with self.assertRaises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_raise_if_custom_validation_is_not_true(self): def _int_equal_to_zero(value): if int(value) != 0: raise GcpFieldValidationException("The available memory has to be equal to 0") specification = [dict(name="availableMemoryMb", custom_validation=_int_equal_to_zero)] body = {"availableMemoryMb": 1} validator = GcpBodyFieldValidator(specification, 'v1') with pytest.raises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_fail_if_both_field_of_union_is_present(self): specification = [ dict( name="an_union", type="union", fields=[dict(name="variant_1", regexp=r'^.+$'), dict(name="variant_2", regexp=r'^.+$'),], ) ] body = {"variant_1": "abc", "variant_2": "def"} validator = GcpBodyFieldValidator(specification, 'v1') with self.assertRaises(GcpFieldValidationException): validator.validate(body)
def test_validate_should_interpret_optional_irrespective_of_allow_empty(self): specification = [dict(name="name", allow_empty=False, optional=True)] body = {"name": None} validator = GcpBodyFieldValidator(specification, 'v1') assert validator.validate(body) is None
def test_validate_should_interpret_dict_type(self): specification = [dict(name="labels", optional=True, type="dict")] body = {"labels": {"one": "value"}} validator = GcpBodyFieldValidator(specification, 'v1') assert validator.validate(body) is None
def test_validate_should_not_raise_exception_if_field_and_body_are_both_empty(self): specification = [] body = {} validator = GcpBodyFieldValidator(specification, 'v1') assert validator.validate(body) is None
def test_validate_should_allow_type_and_optional_in_a_spec(self): specification = [dict(name="labels", optional=True, type="dict")] body = {"labels": {}} validator = GcpBodyFieldValidator(specification, 'v1') assert validator.validate(body) is None
def test_validate_should_interpret_optional_clause(self): specification = [dict(name="name", allow_empty=False, optional=True)] body = {} validator = GcpBodyFieldValidator(specification, 'v1') self.assertIsNone(validator.validate(body))
def test_validate_should_interpret_allow_empty_clause(self): specification = [dict(name="name", allow_empty=True)] body = {"name": ""} validator = GcpBodyFieldValidator(specification, 'v1') assert validator.validate(body) is None
def test_validate_should_validate_a_single_field(self): specification = [dict(name="name", allow_empty=False)] body = {"name": "bigquery"} validator = GcpBodyFieldValidator(specification, 'v1') assert validator.validate(body) is None
def test_validate_should_interpret_union_with_one_field(self): specification = [ dict(name="an_union", type="union", fields=[dict(name="variant_1", regexp=r'^.+$'),]) ] body = {"variant_1": "abc", "variant_2": "def"} validator = GcpBodyFieldValidator(specification, 'v1') self.assertIsNone(validator.validate(body))
def test_validate_should_validate_when_value_matches_regex(self): specification = [ dict(name="an_union", type="union", fields=[dict(name="variant_1", regexp=r'[^a-z]'),]) ] body = {"variant_1": "12"} validator = GcpBodyFieldValidator(specification, 'v1') self.assertIsNone(validator.validate(body))
def test_validate_should_validate_group_of_specs(self): specification = [ dict(name="name", allow_empty=False), dict(name="description", allow_empty=False, optional=True), dict(name="labels", optional=True, type="dict"), dict( name="an_union", type="union", fields=[ dict(name="variant_1", regexp=r'^.+$'), dict(name="variant_2", regexp=r'^.+$', api_version='v1beta2'), dict(name="variant_3", type="dict", fields=[dict(name="url", regexp=r'^.+$')]), dict(name="variant_4"), ], ), ] body = {"variant_1": "abc", "name": "bigquery"} validator = GcpBodyFieldValidator(specification, 'v1') validator.validate(body)
def test_validate_should_fail_if_union_field_is_not_found(self): specification = [ dict( name="an_union", type="union", optional=False, fields=[dict(name="variant_1", regexp=r'^.+$', optional=False, allow_empty=False),], ) ] body = {} validator = GcpBodyFieldValidator(specification, 'v1') self.assertIsNone(validator.validate(body))
class CloudFunctionDeployFunctionOperator(BaseOperator): """ Creates a function in Google Cloud Functions. If a function with this name already exists, it will be updated. .. 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. :type location: str :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. :type body: dict or google.cloud.functions.v1.CloudFunction :param project_id: (Optional) Google Cloud project ID where the function should be created. :type project_id: str :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. Default 'google_cloud_default'. :type gcp_conn_id: str :param api_version: (Optional) API version used (for example v1 - default - or v1beta1). :type api_version: str :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. :type zip_path: str :param validate_body: If set to False, body validation is not performed. :type validate_body: bool :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]] """ # [START gcf_function_deploy_template_fields] template_fields = ( 'body', 'project_id', 'location', 'gcp_conn_id', 'api_version', 'impersonation_chain', ) # [END gcf_function_deploy_template_fields] @apply_defaults def __init__( self, *, location: str, body: Dict, project_id: Optional[str] = None, gcp_conn_id: str = 'google_cloud_default', api_version: str = 'v1', zip_path: Optional[str] = None, validate_body: bool = True, impersonation_chain: Optional[Union[str, Sequence[str]]] = None, **kwargs, ) -> None: self.project_id = project_id self.location = location self.body = body self.gcp_conn_id = gcp_conn_id self.api_version = api_version self.zip_path = zip_path self.zip_path_preprocessor = ZipPathPreprocessor(body, zip_path) self._field_validator = None # type: Optional[GcpBodyFieldValidator] self.impersonation_chain = impersonation_chain if validate_body: self._field_validator = GcpBodyFieldValidator( CLOUD_FUNCTION_VALIDATION, api_version=api_version) self._validate_inputs() super().__init__(**kwargs) def _validate_inputs(self) -> None: if not self.location: raise AirflowException( "The required parameter 'location' is missing") if not self.body: raise AirflowException("The required parameter 'body' is missing") self.zip_path_preprocessor.preprocess_body() def _validate_all_body_fields(self) -> None: if self._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') if not name: raise GcpFieldValidationException( "The 'name' field should be present in " "body: '{}'.".format(self.body)) try: hook.get_function(name) except HttpError as e: status = e.resp.status if status == 404: return False raise e return True def _upload_source_code(self, hook): return hook.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' not in self.body.keys(): self.body['labels'] = {} self.body['labels'].update({ 'airflow-version': 'v' + version.replace('.', '-').replace('+', '-') }) def execute(self, context): hook = CloudFunctionsHook( gcp_conn_id=self.gcp_conn_id, api_version=self.api_version, impersonation_chain=self.impersonation_chain, ) if self.zip_path_preprocessor.should_upload_function(): self.body[GCF_SOURCE_UPLOAD_URL] = self._upload_source_code(hook) self._validate_all_body_fields() self._set_airflow_version_label() if not self._check_if_function_exists(hook): self._create_new_function(hook) else: self._update_function(hook)
class ComputeEngineCopyInstanceTemplateOperator(ComputeEngineBaseOperator): """ Copies the instance template, applying specified changes. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ComputeEngineCopyInstanceTemplateOperator` :param resource_id: Name of the Instance Template :type resource_id: str :param body_patch: Patch to the body of instanceTemplates object following rfc7386 PATCH semantics. The body_patch content follows https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates Name field is required as we need to rename the template, all the other fields are optional. It is important to follow PATCH semantics - arrays are replaced fully, so if you need to update an array you should provide the whole target array as patch element. :type body_patch: dict :param project_id: Optional, Google Cloud Platform Project ID where the Compute Engine Instance exists. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :param request_id: Optional, unique request_id that you might add to achieve full idempotence (for example when client call times out repeating the request with the same request id will not create a new instance template again). It should be in UUID format as defined in RFC 4122. :type request_id: str :param gcp_conn_id: Optional, The connection ID used to connect to Google Cloud Platform. Defaults to 'google_cloud_default'. :type gcp_conn_id: str :param api_version: Optional, API version used (for example v1 - or beta). Defaults to v1. :type api_version: str :param validate_body: Optional, If set to False, body validation is not performed. Defaults to False. :type validate_body: bool """ # [START gce_instance_template_copy_operator_template_fields] template_fields = ('project_id', 'resource_id', 'request_id', 'gcp_conn_id', 'api_version') # [END gce_instance_template_copy_operator_template_fields] @apply_defaults def __init__(self, *, resource_id: str, body_patch: dict, project_id: Optional[str] = None, request_id: Optional[str] = None, gcp_conn_id: str = 'google_cloud_default', api_version: str = 'v1', validate_body: bool = True, **kwargs) -> None: self.body_patch = body_patch self.request_id = request_id self._field_validator = None # Optional[GcpBodyFieldValidator] if 'name' not in self.body_patch: raise AirflowException("The body '{}' should contain at least " "name for the new operator in the 'name' field". format(body_patch)) if validate_body: self._field_validator = GcpBodyFieldValidator( GCE_INSTANCE_TEMPLATE_VALIDATION_PATCH_SPECIFICATION, api_version=api_version) self._field_sanitizer = GcpBodyFieldSanitizer( GCE_INSTANCE_TEMPLATE_FIELDS_TO_SANITIZE) super().__init__( project_id=project_id, zone='global', resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, **kwargs) def _validate_all_body_fields(self): if self._field_validator: self._field_validator.validate(self.body_patch) def execute(self, context): hook = ComputeEngineHook(gcp_conn_id=self.gcp_conn_id, api_version=self.api_version) self._validate_all_body_fields() try: # Idempotence check (sort of) - we want to check if the new template # is already created and if is, then we assume it was created by previous run # of CopyTemplate operator - we do not check if content of the template # is as expected. Templates are immutable so we cannot update it anyway # and deleting/recreating is not worth the hassle especially # that we cannot delete template if it is already used in some Instance # Group Manager. We assume success if the template is simply present existing_template = hook.get_instance_template( resource_id=self.body_patch['name'], project_id=self.project_id) self.log.info( "The %s template already existed. It was likely created by previous run of the operator. " "Assuming success.", existing_template ) return existing_template except HttpError as e: # We actually expect to get 404 / Not Found here as the template should # not yet exist if not e.resp.status == 404: raise e old_body = hook.get_instance_template(resource_id=self.resource_id, project_id=self.project_id) new_body = deepcopy(old_body) self._field_sanitizer.sanitize(new_body) new_body = merge(new_body, self.body_patch) self.log.info("Calling insert instance template with updated body: %s", new_body) hook.insert_instance_template(body=new_body, request_id=self.request_id, project_id=self.project_id) return hook.get_instance_template(resource_id=self.body_patch['name'], project_id=self.project_id)
class ComputeEngineSetMachineTypeOperator(ComputeEngineBaseOperator): """ Changes the machine type for a stopped instance to the machine type specified in the request. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ComputeEngineSetMachineTypeOperator` :param zone: Google Cloud Platform zone where the instance exists. :type zone: str :param resource_id: Name of the Compute Engine instance resource. :type resource_id: str :param body: Body required by the Compute Engine setMachineType API, as described in https://cloud.google.com/compute/docs/reference/rest/v1/instances/setMachineType#request-body :type body: dict :param project_id: Optional, Google Cloud Platform Project ID where the Compute Engine Instance exists. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :param gcp_conn_id: Optional, The connection ID used to connect to Google Cloud Platform. Defaults to 'google_cloud_default'. :type gcp_conn_id: str :param api_version: Optional, API version used (for example v1 - or beta). Defaults to v1. :type api_version: str :param validate_body: Optional, If set to False, body validation is not performed. Defaults to False. :type validate_body: bool """ # [START gce_instance_set_machine_type_template_fields] template_fields = ('project_id', 'zone', 'resource_id', 'body', 'gcp_conn_id', 'api_version') # [END gce_instance_set_machine_type_template_fields] @apply_defaults def __init__(self, *, zone: str, resource_id: str, body: dict, project_id: Optional[str] = None, gcp_conn_id: str = 'google_cloud_default', api_version: str = 'v1', validate_body: bool = True, **kwargs) -> None: self.body = body self._field_validator = None # type: Optional[GcpBodyFieldValidator] if validate_body: self._field_validator = GcpBodyFieldValidator( SET_MACHINE_TYPE_VALIDATION_SPECIFICATION, api_version=api_version) super().__init__( project_id=project_id, zone=zone, resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, **kwargs) def _validate_all_body_fields(self): if self._field_validator: self._field_validator.validate(self.body) def execute(self, context): hook = ComputeEngineHook(gcp_conn_id=self.gcp_conn_id, api_version=self.api_version) self._validate_all_body_fields() return hook.set_machine_type(zone=self.zone, resource_id=self.resource_id, body=self.body, project_id=self.project_id)
class ComputeEngineSetMachineTypeOperator(ComputeEngineBaseOperator): """ Changes the machine type for a stopped instance to the machine type specified in the request. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ComputeEngineSetMachineTypeOperator` :param zone: Google Cloud zone where the instance exists. :type zone: str :param resource_id: Name of the Compute Engine instance resource. :type resource_id: str :param body: Body required by the Compute Engine setMachineType API, as described in https://cloud.google.com/compute/docs/reference/rest/v1/instances/setMachineType#request-body :type body: dict :param project_id: Optional, Google Cloud Project ID where the Compute Engine Instance exists. If set to None or missing, the default project_id from the Google Cloud connection is used. :type project_id: str :param gcp_conn_id: Optional, The connection ID used to connect to Google Cloud. Defaults to 'google_cloud_default'. :type gcp_conn_id: str :param api_version: Optional, API version used (for example v1 - or beta). Defaults to v1. :type api_version: str :param validate_body: Optional, If set to False, body validation is not performed. Defaults to False. :type validate_body: bool :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]] """ # [START gce_instance_set_machine_type_template_fields] template_fields = ( 'project_id', 'zone', 'resource_id', 'body', 'gcp_conn_id', 'api_version', 'impersonation_chain', ) # [END gce_instance_set_machine_type_template_fields] def __init__( self, *, zone: str, resource_id: str, body: dict, project_id: Optional[str] = None, gcp_conn_id: str = 'google_cloud_default', api_version: str = 'v1', validate_body: bool = True, impersonation_chain: Optional[Union[str, Sequence[str]]] = None, **kwargs, ) -> None: self.body = body self._field_validator = None # type: Optional[GcpBodyFieldValidator] if validate_body: self._field_validator = GcpBodyFieldValidator( SET_MACHINE_TYPE_VALIDATION_SPECIFICATION, api_version=api_version) super().__init__( project_id=project_id, zone=zone, resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, impersonation_chain=impersonation_chain, **kwargs, ) def _validate_all_body_fields(self) -> None: if self._field_validator: self._field_validator.validate(self.body) def execute(self, context) -> None: hook = ComputeEngineHook( gcp_conn_id=self.gcp_conn_id, api_version=self.api_version, impersonation_chain=self.impersonation_chain, ) self._validate_all_body_fields() return hook.set_machine_type(zone=self.zone, resource_id=self.resource_id, body=self.body, project_id=self.project_id)