You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2022/02/04 19:30:01 UTC

[GitHub] [airflow] dstandish commented on a change in pull request #21231: Added AWS RDS sensors

dstandish commented on a change in pull request #21231:
URL: https://github.com/apache/airflow/pull/21231#discussion_r799753591



##########
File path: airflow/providers/amazon/aws/hooks/rds.py
##########
@@ -0,0 +1,57 @@
+#
+# 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.
+"""Interact with AWS RDS."""
+
+from mypy_boto3_rds import RDSClient
+
+from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook
+
+
+class RdsHook(AwsBaseHook):
+    """
+    Interact with AWS RDS using proper client from the boto3 library.
+
+    Hook attribute `client` has all methods that listed in documentation
+
+    .. seealso::
+        - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html
+        - https://docs.aws.amazon.com/rds/index.html
+
+    Additional arguments (such as ``aws_conn_id`` or ``region_name``) may be specified and
+    are passed down to the underlying AwsBaseHook.
+
+    .. seealso::
+        :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
+
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :type aws_conn_id: str
+    """
+
+    def __init__(self, *args, **kwargs) -> None:
+        kwargs["client_type"] = "rds"
+        super().__init__(*args, **kwargs)
+
+    @property
+    def conn(self) -> RDSClient:

Review comment:
       ```suggestion
       def conn(self) -> "RDSClient":
   ```

##########
File path: airflow/providers/amazon/aws/hooks/rds.py
##########
@@ -0,0 +1,57 @@
+#
+# 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.
+"""Interact with AWS RDS."""
+
+from mypy_boto3_rds import RDSClient

Review comment:
       ```suggestion
   from typing import TYPE_CHECKING
   
   if TYPE_CHECKING:
       from mypy_boto3_rds import RDSClient
   ```

##########
File path: airflow/providers/amazon/aws/sensors/rds.py
##########
@@ -0,0 +1,168 @@
+# 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 typing import TYPE_CHECKING, List, Optional, Sequence
+
+from botocore.exceptions import ClientError
+
+from airflow.providers.amazon.aws.hooks.rds import RdsHook
+from airflow.providers.amazon.aws.utils.rds import RdsDbType
+from airflow.sensors.base import BaseSensorOperator
+
+if TYPE_CHECKING:
+    from airflow.utils.context import Context
+
+
+class BaseRdsSensor(BaseSensorOperator):
+    """Base operator that implements common functions for all sensors"""
+
+    ui_color = "#ddbb77"
+    ui_fgcolor = "#ffffff"
+
+    def __init__(self, *args, aws_conn_id: str = "aws_conn_id", hook_params: Optional[dict] = None, **kwargs):
+        hook_params = hook_params or {}
+        self.hook = RdsHook(aws_conn_id=aws_conn_id, **hook_params)
+        self.target_statuses: List[str] = []
+        super().__init__(*args, **kwargs)
+
+    def _describe_item(self, **kwargs) -> list:
+        """Returns information about target item: snapshot or task"""
+        raise NotImplementedError
+
+    def _check_item(self, **kwargs) -> bool:
+        """Get certain item from `_describe_item()` and check it status"""
+        try:
+            item = self._describe_item()
+        except ClientError:
+            return False
+        else:
+            return item and any(map(lambda s: item[0]['Status'] == s, self.target_statuses))
+
+
+class RdsSnapshotExistenceSensor(BaseRdsSensor):
+    """
+    Waits for RDS snapshot with a specific status.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:RdsSnapshotExistenceSensor`
+
+    :param db_type: Type of the DB - either "instance" or "cluster"
+    :type db_type: RDSDbType
+    :param db_identifier: The identifier of the instance or cluster that you want to create the snapshot of
+    :type db_identifier: str
+    :param db_snapshot_identifier: The identifier for the DB snapshot
+    :type db_snapshot_identifier: str
+    :param target_statuses: Target status of snapshot
+    :type target_statuses: List[str]
+    """
+
+    template_fields: Sequence[str] = (
+        'db_identifier',
+        'db_snapshot_identifier',
+        'target_status',
+    )
+
+    def __init__(
+        self,
+        *,
+        db_type: str,
+        db_identifier: str = None,
+        db_snapshot_identifier: str = None,
+        target_statuses: Optional[List[str]] = None,
+        aws_conn_id: str = "aws_conn_id",
+        **kwargs,
+    ):
+        super().__init__(aws_conn_id=aws_conn_id, **kwargs)
+        self.db_type = RdsDbType(db_type)
+        self.db_identifier = db_identifier
+        self.db_snapshot_identifier = db_snapshot_identifier
+        self.target_statuses = target_statuses or ['available']
+
+    def _describe_item(self, **kwargs) -> list:
+        """Returns snapshot info"""
+        if self.db_type.value == "instance":
+            db_snapshots = self.hook.conn.describe_db_snapshots(
+                DBInstanceIdentifier=self.db_identifier,
+                DBSnapshotIdentifier=self.db_snapshot_identifier,
+                **kwargs,
+            )
+            return db_snapshots['DBSnapshots']
+        else:
+            db_cluster_snapshots = self.hook.conn.describe_db_cluster_snapshots(
+                DBClusterIdentifier=self.db_identifier,
+                DBClusterSnapshotIdentifier=self.db_snapshot_identifier,
+                **kwargs,
+            )
+            return db_cluster_snapshots['DBClusterSnapshots']

Review comment:
       i have the same comment here as on the operators PR  -- i think that you can reduce the code dupe somehow




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org