Skip to content

Commit

Permalink
Migration of System Tests: Cloud Composer (AIP-47) (#27227)
Browse files Browse the repository at this point in the history
  • Loading branch information
bkossakowska committed Oct 31, 2022
1 parent 528ecbb commit eb8c0cf
Show file tree
Hide file tree
Showing 10 changed files with 353 additions and 107 deletions.
2 changes: 2 additions & 0 deletions airflow/providers/google/cloud/operators/cloud_composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ def execute(self, context: Context):
timeout=self.timeout,
metadata=self.metadata,
)
context["ti"].xcom_push(key="operation_id", value=result.operation.name)

if not self.deferrable:
environment = hook.wait_for_operation(timeout=self.timeout, operation=result)
return Environment.to_dict(environment)
Expand Down
99 changes: 99 additions & 0 deletions airflow/providers/google/cloud/sensors/cloud_composer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
#
# 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 a Cloud Composer sensor."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Sequence

from airflow.exceptions import AirflowException
from airflow.providers.google.cloud.triggers.cloud_composer import CloudComposerExecutionTrigger
from airflow.sensors.base import BaseSensorOperator

if TYPE_CHECKING:
from airflow.utils.context import Context


class CloudComposerEnvironmentSensor(BaseSensorOperator):
"""
Check the status of the Cloud Composer Environment task
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param operation_name: The name of the operation resource
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param delegate_to: The account to impersonate, if any. For this to work, the service account making the
request must have domain-wide delegation enabled.
: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 pooling_period_seconds: Optional: Control the rate of the poll for the result of deferrable run.
"""

def __init__(
self,
*,
project_id: str,
region: str,
operation_name: str,
gcp_conn_id: str = "google_cloud_default",
delegate_to: str | None = None,
impersonation_chain: str | Sequence[str] | None = None,
pooling_period_seconds: int = 30,
**kwargs,
):
super().__init__(**kwargs)
self.project_id = project_id
self.region = region
self.operation_name = operation_name
self.pooling_period_seconds = pooling_period_seconds
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
self.impersonation_chain = impersonation_chain

def execute(self, context: Context) -> None:
"""Airflow runs this method on the worker and defers using the trigger."""
self.defer(
trigger=CloudComposerExecutionTrigger(
project_id=self.project_id,
region=self.region,
operation_name=self.operation_name,
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
delegate_to=self.delegate_to,
pooling_period_seconds=self.pooling_period_seconds,
),
method_name="execute_complete",
)

def execute_complete(self, context: dict[str, Any], event: dict[str, str] | None = None) -> str:
"""
Callback for when the trigger fires - returns immediately.
Relies on trigger to throw an exception, otherwise it assumes execution was
successful.
"""
if event:
if event.get("operation_done"):
return event["operation_done"]
raise AirflowException(event["message"])
raise AirflowException("No event received in trigger callback")
3 changes: 1 addition & 2 deletions airflow/providers/google/cloud/triggers/cloud_composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from __future__ import annotations

import asyncio
Expand Down Expand Up @@ -42,11 +43,9 @@ def __init__(
self.project_id = project_id
self.region = region
self.operation_name = operation_name

self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
self.delegate_to = delegate_to

self.pooling_period_seconds = pooling_period_seconds

self.gcp_hook = CloudComposerAsyncHook(
Expand Down
3 changes: 3 additions & 0 deletions airflow/providers/google/provider.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,9 @@ sensors:
- integration-name: Google Bigtable
python-modules:
- airflow.providers.google.cloud.sensors.bigtable
- integration-name: Google Cloud Composer
python-modules:
- airflow.providers.google.cloud.sensors.cloud_composer
- integration-name: Google Cloud Storage Transfer Service
python-modules:
- airflow.providers.google.cloud.sensors.cloud_storage_transfer_service
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ For more information about the available fields to pass when creating a environm

A simple environment configuration can look as followed:

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 0
:start-after: [START howto_operator_composer_simple_environment]
Expand All @@ -48,7 +48,7 @@ A simple environment configuration can look as followed:
With this configuration we can create the environment:
:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerCreateEnvironmentOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 4
:start-after: [START howto_operator_create_composer_environment]
Expand All @@ -57,7 +57,7 @@ With this configuration we can create the environment:
or you can define the same operator in the deferrable mode:
:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerCreateEnvironmentOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer_deferrable.py
:language: python
:dedent: 4
:start-after: [START howto_operator_create_composer_environment_deferrable_mode]
Expand All @@ -70,7 +70,7 @@ To get a environment you can use:

:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerGetEnvironmentOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 4
:start-after: [START howto_operator_get_composer_environment]
Expand All @@ -83,7 +83,7 @@ To get a environment you can use:

:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerListEnvironmentsOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 4
:start-after: [START howto_operator_list_composer_environments]
Expand All @@ -98,7 +98,7 @@ For more information on updateMask and other parameters take a look at `Cloud Co

An example of a new service config and the updateMask:

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 0
:start-after: [START howto_operator_composer_update_environment]
Expand All @@ -107,7 +107,7 @@ An example of a new service config and the updateMask:
To update a service you can use:
:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerUpdateEnvironmentOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 4
:start-after: [START howto_operator_update_composer_environment]
Expand All @@ -116,7 +116,7 @@ To update a service you can use:
or you can define the same operator in the deferrable mode:
:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerCreateEnvironmentOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer_deferrable.py
:language: python
:dedent: 4
:start-after: [START howto_operator_update_composer_environment_deferrable_mode]
Expand All @@ -129,7 +129,7 @@ To delete a service you can use:

:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerDeleteEnvironmentOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 4
:start-after: [START howto_operator_delete_composer_environment]
Expand All @@ -138,7 +138,7 @@ To delete a service you can use:
or you can define the same operator in the deferrable mode:
:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerDeleteEnvironmentOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer_deferrable.py
:language: python
:dedent: 4
:start-after: [START howto_operator_delete_composer_environment_deferrable_mode]
Expand All @@ -152,7 +152,7 @@ You can also list all supported Cloud Composer images:

:class:`~airflow.providers.google.cloud.operators.cloud_composer.CloudComposerListImageVersionsOperator`

.. exampleinclude:: /../../airflow/providers/google/cloud/example_dags/example_cloud_composer.py
.. exampleinclude:: /../../tests/system/providers/google/cloud/composer/example_cloud_composer.py
:language: python
:dedent: 4
:start-after: [START howto_operator_composer_image_list]
Expand Down

This file was deleted.

73 changes: 73 additions & 0 deletions tests/providers/google/cloud/sensors/test_cloud_composer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# 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__ import annotations

from unittest import TestCase, mock

import pytest

from airflow.exceptions import AirflowException, TaskDeferred
from airflow.providers.google.cloud.sensors.cloud_composer import CloudComposerEnvironmentSensor
from airflow.providers.google.cloud.triggers.cloud_composer import CloudComposerExecutionTrigger

TEST_PROJECT_ID = "test_project_id"
TEST_OPERATION_NAME = "test_operation_name"
TEST_REGION = "region"


class TestCloudComposerEnvironmentSensor(TestCase):
def test_cloud_composer_existence_sensor_async(self):
"""
Asserts that a task is deferred and a CloudComposerExecutionTrigger will be fired
when the CloudComposerEnvironmentSensor is executed.
"""
task = CloudComposerEnvironmentSensor(
task_id="task_id",
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
operation_name=TEST_OPERATION_NAME,
)
with pytest.raises(TaskDeferred) as exc:
task.execute(context={})
assert isinstance(
exc.value.trigger, CloudComposerExecutionTrigger
), "Trigger is not a CloudComposerExecutionTrigger"

def test_cloud_composer_existence_sensor_async_execute_failure(self):
"""Tests that an AirflowException is raised in case of error event."""
task = CloudComposerEnvironmentSensor(
task_id="task_id",
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
operation_name=TEST_OPERATION_NAME,
)
with pytest.raises(AirflowException, match="No event received in trigger callback"):
task.execute_complete(context={}, event=None)

def test_cloud_composer_existence_sensor_async_execute_complete(self):
"""Asserts that logging occurs as expected"""
task = CloudComposerEnvironmentSensor(
task_id="task_id",
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
operation_name=TEST_OPERATION_NAME,
)
with mock.patch.object(task.log, "info"):
task.execute_complete(
context={}, event={"operation_done": True, "operation_name": TEST_OPERATION_NAME}
)
16 changes: 16 additions & 0 deletions tests/system/providers/google/cloud/composer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 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.

0 comments on commit eb8c0cf

Please sign in to comment.