Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Staging database restore DAG: base restore (#2099)
Madison Swain-Bowden988381da7c70
diff --git a/catalog/DAGs.md b/catalog/DAGs.mdindex b479a4dbd..987040ce0 100644--- a/catalog/DAGs.md+++ b/catalog/DAGs.md@@ -44,6 +44,7 @@ The following are DAGs grouped by their primary tag:| [`recreate_audio_popularity_calculation`](#recreate_audio_popularity_calculation) | `None` || [`recreate_image_popularity_calculation`](#recreate_image_popularity_calculation) | `None` || [`report_pending_reported_media`](#report_pending_reported_media) | `@weekly` |+| [`staging_database_restore`](#staging_database_restore) | `@monthly` |## Maintenance@@ -133,6 +134,7 @@ The following is documentation associated with each DAG (where available):1. [`science_museum_workflow`](#science_museum_workflow)1. [`smithsonian_workflow`](#smithsonian_workflow)1. [`smk_workflow`](#smk_workflow)+1. [`staging_database_restore`](#staging_database_restore)1. [`stocksnap_workflow`](#stocksnap_workflow)1. [`wikimedia_commons_workflow`](#wikimedia_commons_workflow)1. [`wikimedia_reingestion_workflow`](#wikimedia_reingestion_workflow)@@ -704,6 +706,25 @@ Output: TSV file containing the media metadata.Notes: https://www.smk.dk/en/article/smk-api/+## `staging_database_restore`++### Update the staging database++This DAG is responsible for updating the staging database using the most recent+snapshot of the production database.++For a full explanation of the DAG, see the implementation plan description:+https://docs.openverse.org/projects/proposals/search_relevancy_sandbox/20230406-implementation_plan_update_staging_database.html#dag++This DAG will default to using the standard AWS connection ID for the RDS+operations. For local testing, you can set up two environment variables to have+the RDS operations run using a different hook:++- `AWS_RDS_CONN_ID`: The Airflow connection ID to use for RDS operations (e.g.+ `aws_rds`)+- `AIRFLOW_CONN_<ID>`: The connection string to use for RDS operations (per the+ above example, it might be `AIRFLOW_CONN_AWS_RDS`)+## `stocksnap_workflow`Content Provider: StockSnapdiff --git a/catalog/dags/common/constants.py b/catalog/dags/common/constants.pyindex 274ed3e14..b6f965cf8 100644--- a/catalog/dags/common/constants.py+++ b/catalog/dags/common/constants.py@@ -31,3 +31,4 @@ XCOM_PULL_TEMPLATE = "{{{{ ti.xcom_pull(task_ids='{}', key='{}') }}}}"POSTGRES_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")OPENLEDGER_API_CONN_ID = os.getenv("OPENLEDGER_API_CONN_ID", "postgres_openledger_api")+AWS_CONN_ID = os.getenv("AWS_CONN_ID", "aws_conn_id")diff --git a/catalog/dags/database/staging_database_restore/constants.py b/catalog/dags/database/staging_database_restore/constants.pynew file mode 100644index 000000000..2fb85e554--- /dev/null+++ b/catalog/dags/database/staging_database_restore/constants.py@@ -0,0 +1,19 @@+import os++from common.constants import AWS_CONN_ID+++_ID_FORMAT = "{}-openverse-db"++DAG_ID = "staging_database_restore"+PROD_IDENTIFIER = _ID_FORMAT.format("prod")+STAGING_IDENTIFIER = _ID_FORMAT.format("dev")+TEMP_IDENTIFIER = _ID_FORMAT.format("dev-next")+OLD_IDENTIFIER = _ID_FORMAT.format("dev-old")++SAFE_TO_MUTATE = {STAGING_IDENTIFIER, TEMP_IDENTIFIER, OLD_IDENTIFIER}++SKIP_VARIABLE = "SKIP_STAGING_DATABASE_RESTORE"+AWS_RDS_CONN_ID = os.environ.get("AWS_RDS_CONN_ID", AWS_CONN_ID)+SLACK_USERNAME = "Staging Database Restore"+SLACK_ICON = ":database-pink:"diff --git a/catalog/dags/database/staging_database_restore/staging_database_restore.py b/catalog/dags/database/staging_database_restore/staging_database_restore.pynew file mode 100644index 000000000..aae8ccfdf--- /dev/null+++ b/catalog/dags/database/staging_database_restore/staging_database_restore.py@@ -0,0 +1,208 @@+import logging+from datetime import timedelta+from pprint import pformat++from airflow.decorators import task+from airflow.models import Variable+from airflow.providers.amazon.aws.hooks.rds import RdsHook+from airflow.providers.amazon.aws.sensors.rds import RdsDbSensor+from airflow.utils.task_group import TaskGroup+from airflow.utils.trigger_rule import TriggerRule++from common import slack+from database.staging_database_restore import constants+from database.staging_database_restore.utils import (+ ensure_mutate_allowed,+ setup_rds_hook,+)+++REQUIRED_DB_INFO = {+ "MultiAZ",+ "AvailabilityZone",+ "VpcSecurityGroups",+ "DBSubnetGroup",+ "PubliclyAccessible",+ "DBInstanceClass",+ "AllocatedStorage",+}+++log = logging.getLogger(__name__)++[email protected]_circuit+def skip_restore(should_skip: bool = False) -> bool:+ """+ Determine whether to skip the restore process.+ Can be overridden by setting the `SKIP_STAGING_DATABASE_RESTORE` Airflow Variable+ to `true`.+ Should return `True` to have the DAG continue, and `False` to have it skipped.+ https://docs.astronomer.io/learn/airflow-branch-operator#taskshort_circuit-shortcircuitoperator+ """+ should_continue = not (+ should_skip+ or Variable.get(+ constants.SKIP_VARIABLE, default_var=False, deserialize_json=True+ )+ )+ if not should_continue:+ notify_slack.function(+ "The staging database restore has been skipped. "+ f"(Set the `{constants.SKIP_VARIABLE}` Airflow Variable to `false`"+ "to disable this behavior.)"+ )+ return should_continue+++@task+@setup_rds_hook+def get_latest_prod_snapshot(rds_hook: RdsHook = None) -> str:+ """+ Get the latest automated snapshot for the production database.+ https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds/client/describe_db_snapshots.html+ Status is checked using a sensor in a later step, in case a snapshot creation is+ currently in progress.+ """+ # Get snapshots+ snapshots = rds_hook.conn.describe_db_snapshots(+ DBInstanceIdentifier=constants.PROD_IDENTIFIER,+ SnapshotType="automated",+ ).get("DBSnapshots", [])+ # Sort by descending creation time+ snapshots = sorted(+ snapshots,+ key=lambda x: x["SnapshotCreateTime"],+ reverse=True,+ )+ if not snapshots:+ raise ValueError(f"No snapshots found for {constants.PROD_IDENTIFIER}")+ latest_snapshot = snapshots[0]+ log.info(f"Latest snapshot: {latest_snapshot}")+ return latest_snapshot["DBSnapshotIdentifier"]+++@task+@setup_rds_hook+def get_staging_db_details(rds_hook: RdsHook = None) -> dict:+ """+ Retrieve the details of the staging database. Only some details are required (and+ others are actually sensitive) so filter down to only what we need.+ https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds/client/describe_db_instances.html+ """+ # Get staging DB details+ instances = rds_hook.conn.describe_db_instances(+ DBInstanceIdentifier=constants.STAGING_IDENTIFIER,+ ).get("DBInstances", [])+ if not instances:+ raise ValueError(f"No staging DB found for {constants.STAGING_IDENTIFIER}")+ staging_db = instances[0]+ # While it might be tempting to log this information, it contains sensitive+ # values. Instead, we'll select only the information we need, then log that.+ staging_db = {+ key: value for key, value in staging_db.items() if key in REQUIRED_DB_INFO+ }+ # Pull the DBSubnetGroup name out of the DBSubnetGroup object+ staging_db["DBSubnetGroupName"] = staging_db.pop("DBSubnetGroup")[+ "DBSubnetGroupName"+ ]+ # Pull the VPC IDs out of the VpcSecurityGroups objects+ staging_db["VpcSecurityGroupIds"] = [+ vpc["VpcSecurityGroupId"] for vpc in staging_db.pop("VpcSecurityGroups")+ ]+ log.info(f"Staging DB config: \n{pformat(staging_db)}")+ return staging_db+++@task+@setup_rds_hook+def restore_staging_from_snapshot(+ latest_snapshot: str, staging_config: dict, rds_hook: RdsHook = None+) -> None:+ """+ Restore the staging database from the latest snapshot.+ Augment the restore operation with the existing details determined from+ a previous step.+ https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds/client/restore_db_instance_from_db_snapshot.html+ """+ log.info(+ f"Creating a new {constants.TEMP_IDENTIFIER} instance from {latest_snapshot} "+ f"with: \n{pformat(staging_config)}"+ )+ rds_hook.conn.restore_db_instance_from_db_snapshot(+ DBInstanceIdentifier=constants.TEMP_IDENTIFIER,+ DBSnapshotIdentifier=latest_snapshot,+ **staging_config,+ )+++@task+@setup_rds_hook+def rename_db_instance(source: str, target: str, rds_hook: RdsHook = None) -> None:+ """+ Rename a database instance.+ This can only be run on instances where mutation is allowed.+ https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds/client/modify_db_instance.html+ """+ log.info("Checking input values")+ ensure_mutate_allowed(source)+ ensure_mutate_allowed(target)+ log.info(f"Renaming {source} to {target}")+ rds_hook.conn.modify_db_instance(+ DBInstanceIdentifier=source,+ NewDBInstanceIdentifier=target,+ ApplyImmediately=True,+ )+++@task+def notify_slack(text: str) -> None:+ slack.send_message(+ text,+ username=constants.SLACK_USERNAME,+ icon_emoji=constants.SLACK_ICON,+ dag_id=constants.DAG_ID,+ )+++def make_rds_sensor(task_id: str, db_identifier: str, retries: int = 0) -> RdsDbSensor:+ return RdsDbSensor(+ task_id=task_id,+ db_identifier=db_identifier,+ target_statuses=["available"],+ aws_conn_id=constants.AWS_RDS_CONN_ID,+ mode="reschedule",+ timeout=60 * 60, # 1 hour+ retries=retries,+ retry_delay=timedelta(minutes=1),+ )+++def make_rename_task_group(+ source: str,+ target: str,+ trigger_rule: TriggerRule = TriggerRule.ALL_SUCCESS,+) -> TaskGroup:+ """+ Create a task group which includes both a rename operation, and a sensor to wait+ for the new database to be ready. This requires retries because the database+ may not be ready immediately after the rename when the first await is tried.+ """+ source_name = source.removesuffix("-openverse-db")+ target_name = target.removesuffix("-openverse-db")+ with TaskGroup(group_id=f"rename_{source_name}_to_{target_name}") as rename_group:+ rename = rename_db_instance.override(+ task_id=f"rename_{source_name}_to_{target_name}",+ trigger_rule=trigger_rule,+ )(+ source=source,+ target=target,+ )+ await_rename = make_rds_sensor(+ task_id=f"await_{target_name}",+ db_identifier=target,+ retries=2,+ )+ rename >> await_rename++ return rename_groupdiff --git a/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py b/catalog/dags/database/staging_database_restore/staging_database_restore_dag.pynew file mode 100644index 000000000..c22b03878--- /dev/null+++ b/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py@@ -0,0 +1,128 @@+"""+# Update the staging database++This DAG is responsible for updating the staging database using the most recent+snapshot of the production database.++For a full explanation of the DAG, see the implementation plan description:+https://docs.openverse.org/projects/proposals/search_relevancy_sandbox/20230406-implementation_plan_update_staging_database.html#dag++This DAG will default to using the standard AWS connection ID for the RDS operations.+For local testing, you can set up two environment variables to have the RDS operations+run using a different hook:+- `AWS_RDS_CONN_ID`: The Airflow connection ID to use for RDS operations+ (e.g. `aws_rds`)+- `AIRFLOW_CONN_<ID>`: The connection string to use for RDS operations (per the above+ example, it might be `AIRFLOW_CONN_AWS_RDS`)+"""++import logging+from datetime import datetime, timedelta++from airflow.decorators import dag+from airflow.providers.amazon.aws.operators.rds import RdsDeleteDbInstanceOperator+from airflow.providers.amazon.aws.sensors.rds import RdsSnapshotExistenceSensor+from airflow.utils.trigger_rule import TriggerRule++from common.constants import DAG_DEFAULT_ARGS+from database.staging_database_restore import constants+from database.staging_database_restore.staging_database_restore import (+ get_latest_prod_snapshot,+ get_staging_db_details,+ make_rds_sensor,+ make_rename_task_group,+ notify_slack,+ restore_staging_from_snapshot,+ skip_restore,+)+++log = logging.getLogger(__name__)+++@dag(+ dag_id=constants.DAG_ID,+ schedule="@monthly",+ start_date=datetime(2023, 5, 1),+ tags=["database"],+ max_active_runs=1,+ dagrun_timeout=timedelta(days=1),+ catchup=False,+ # Use the docstring at the top of the file as md docs in the UI+ doc_md=__doc__,+ default_args={+ **DAG_DEFAULT_ARGS,+ # Don't add any retries by default+ "retries": 0,+ },+ render_template_as_native_obj=True,+)+def restore_staging_database():+ should_skip = skip_restore()+ latest_snapshot = get_latest_prod_snapshot()+ should_skip >> latest_snapshot++ ensure_snapshot_ready = RdsSnapshotExistenceSensor(+ task_id="ensure_snapshot_ready",+ db_type="instance",+ db_snapshot_identifier=latest_snapshot,+ aws_conn_id=constants.AWS_RDS_CONN_ID,+ mode="reschedule",+ timeout=60 * 60 * 4, # 4 hours+ )++ staging_details = get_staging_db_details()+ should_skip >> staging_details++ restore_snapshot = restore_staging_from_snapshot(latest_snapshot, staging_details)+ ensure_snapshot_ready >> restore_snapshot++ await_staging_creation = make_rds_sensor(+ task_id="await_staging_creation",+ db_identifier=constants.TEMP_IDENTIFIER,+ )+ restore_snapshot >> await_staging_creation++ notify_outage = notify_slack.override(task_id="notify_outage")(+ ":warning: Staging database is being restored, staging will "+ "be down for the duration."+ )++ rename_staging_to_old = make_rename_task_group(+ constants.STAGING_IDENTIFIER, constants.OLD_IDENTIFIER+ )+ await_staging_creation >> [notify_outage, rename_staging_to_old]++ rename_temp_to_staging = make_rename_task_group(+ constants.TEMP_IDENTIFIER, constants.STAGING_IDENTIFIER+ )+ rename_staging_to_old >> rename_temp_to_staging++ # Only run this if the secondary rename failed+ rename_old_to_staging = make_rename_task_group(+ constants.OLD_IDENTIFIER,+ constants.STAGING_IDENTIFIER,+ trigger_rule=TriggerRule.ALL_FAILED,+ )+ notify_failed_but_back = notify_slack.override(task_id="notify_failed_but_back")(+ ":warning: Staging database rename failed, but staging should "+ "now be available. Please investigate the cause of the failure."+ )+ rename_temp_to_staging >> rename_old_to_staging >> notify_failed_but_back++ notify_complete = notify_slack.override(task_id="notify_complete")(+ ":info: Staging database restore complete, staging should now be available.",+ )++ delete_old = RdsDeleteDbInstanceOperator(+ task_id="delete_old",+ db_instance_identifier=constants.OLD_IDENTIFIER,+ rds_kwargs={"SkipFinalSnapshot": True, "DeleteAutomatedBackups": False},+ aws_conn_id=constants.AWS_RDS_CONN_ID,+ wait_for_completion=True,+ )++ rename_temp_to_staging >> [notify_complete, delete_old]+++restore_staging_database()diff --git a/catalog/dags/database/staging_database_restore/utils.py b/catalog/dags/database/staging_database_restore/utils.pynew file mode 100644index 000000000..82a83a0a9--- /dev/null+++ b/catalog/dags/database/staging_database_restore/utils.py@@ -0,0 +1,35 @@+import functools++from airflow.providers.amazon.aws.hooks.rds import RdsHook++from database.staging_database_restore import constants+++def setup_rds_hook(func: callable) -> callable:+ """+ Provide an rds_hook as one of the parameters for the called function.+ If the function is explicitly supplied with an rds_hook, use that one.+ :return:+ """++ @functools.wraps(func)+ def wrapped(*args, **kwargs):+ rds_hook = kwargs.pop("rds_hook", None) or RdsHook(+ aws_conn_id=constants.AWS_RDS_CONN_ID+ )+ return func(*args, **kwargs, rds_hook=rds_hook)++ return wrapped+++def ensure_mutate_allowed(db_identifier: str) -> None:+ """+ Ensure that the only those databases which are safe to mutate are being used+ for a target function.+ """++ if db_identifier not in constants.SAFE_TO_MUTATE:+ raise ValueError(+ f"The target function must be called with a non-production database "+ f"identifier, not {db_identifier}"+ )diff --git a/catalog/dags/providers/provider_api_scripts/inaturalist.py b/catalog/dags/providers/provider_api_scripts/inaturalist.pyindex d321ac471..000b9bd37 100644--- a/catalog/dags/providers/provider_api_scripts/inaturalist.py+++ b/catalog/dags/providers/provider_api_scripts/inaturalist.py@@ -33,7 +33,7 @@ from airflow.providers.amazon.aws.hooks.s3 import S3Hookfrom airflow.utils.task_group import TaskGroupfrom airflow.utils.trigger_rule import TriggerRule-from common.constants import IMAGE, POSTGRES_CONN_ID, XCOM_PULL_TEMPLATE+from common.constants import AWS_CONN_ID, IMAGE, POSTGRES_CONN_ID, XCOM_PULL_TEMPLATEfrom common.loader import provider_details, reporting, sqlfrom common.sql import PGExecuteQueryOperator, PostgresHookfrom providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester@@ -41,7 +41,6 @@ from providers.provider_api_scripts.provider_data_ingester import ProviderDataInlogger = logging.getLogger(__name__)-AWS_CONN_ID = os.getenv("AWS_CONN_ID", "test_conn_id")SCRIPT_DIR = Path(__file__).parents[1] / "provider_csv_load_scripts/inaturalist"SOURCE_FILE_NAMES = ["photos", "observations", "taxa", "observers"]LOADER_ARGS = {diff --git a/catalog/dags/providers/provider_dag_factory.py b/catalog/dags/providers/provider_dag_factory.pyindex a4dec84a1..954023110 100644--- a/catalog/dags/providers/provider_dag_factory.py+++ b/catalog/dags/providers/provider_dag_factory.py@@ -76,7 +76,9 @@ from airflow.operators.python import PythonOperatorfrom airflow.utils.task_group import TaskGroupfrom airflow.utils.trigger_rule import TriggerRule-from common.constants import DAG_DEFAULT_ARGS, XCOM_PULL_TEMPLATE+from common.constants import AWS_CONN_ID, DAG_DEFAULT_ARGS+from common.constants import POSTGRES_CONN_ID as DB_CONN_ID+from common.constants import XCOM_PULL_TEMPLATEfrom common.loader import loader, reporting, s3, sqlfrom providers.factory_utils import date_partition_for_prefix, pull_media_wrapperfrom providers.provider_reingestion_workflows import ProviderReingestionWorkflow@@ -90,8 +92,6 @@ from providers.provider_workflows import (logger = logging.getLogger(__name__)-DB_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")-AWS_CONN_ID = os.getenv("AWS_CONN_ID", "no_aws_conn_id")OPENVERSE_BUCKET = os.getenv("OPENVERSE_BUCKET")OUTPUT_DIR_PATH = os.path.realpath(os.getenv("OUTPUT_DIR", "/tmp/"))_DATE_RANGE_INNER_TEMPLATE = "macros.ds_add(ds, -{} )"diff --git a/catalog/tests/dags/common/loader/test_s3.py b/catalog/tests/dags/common/loader/test_s3.pyindex 3b935af0b..467867276 100644--- a/catalog/tests/dags/common/loader/test_s3.py+++ b/catalog/tests/dags/common/loader/test_s3.py@@ -5,13 +5,13 @@ import pytestfrom airflow.exceptions import AirflowSkipExceptionfrom airflow.models import TaskInstance+from common.constants import AWS_CONN_IDfrom common.loader import s3TEST_ID = "testing"TEST_MEDIA_PREFIX = "media"TEST_STAGING_PREFIX = "test_staging"-AWS_CONN_ID = os.getenv("AWS_CONN_ID", "test_conn_id")S3_LOCAL_ENDPOINT = os.getenv("S3_LOCAL_ENDPOINT")S3_TEST_BUCKET = f"cccatalog-storage-{TEST_ID}"ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")diff --git a/catalog/tests/dags/database/staging_database_restore/data.py b/catalog/tests/dags/database/staging_database_restore/data.pynew file mode 100644index 000000000..c24da19bf--- /dev/null+++ b/catalog/tests/dags/database/staging_database_restore/data.py@@ -0,0 +1,175 @@+from datetime import datetime+++# Taken from+# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds/client/describe_db_instances.html+DESCRIBE_DB_INSTANCES_RESPONSE = {+ "DBInstanceIdentifier": "string",+ "DBInstanceClass": "string",+ "Engine": "string",+ "DBInstanceStatus": "string",+ "AutomaticRestartTime": datetime(2015, 1, 1),+ "MasterUsername": "string",+ "DBName": "string",+ "Endpoint": {"Address": "string", "Port": 123, "HostedZoneId": "string"},+ "AllocatedStorage": 123,+ "InstanceCreateTime": datetime(2015, 1, 1),+ "PreferredBackupWindow": "string",+ "BackupRetentionPeriod": 123,+ "DBSecurityGroups": [+ {"DBSecurityGroupName": "string", "Status": "string"},+ ],+ "VpcSecurityGroups": [+ {"VpcSecurityGroupId": "vpcsg1", "Status": "string"},+ {"VpcSecurityGroupId": "vpcsg2", "Status": "string"},+ ],+ "DBParameterGroups": [+ {"DBParameterGroupName": "string", "ParameterApplyStatus": "string"},+ ],+ "AvailabilityZone": "string",+ "DBSubnetGroup": {+ "DBSubnetGroupName": "string",+ "DBSubnetGroupDescription": "string",+ "VpcId": "string",+ "SubnetGroupStatus": "string",+ "Subnets": [+ {+ "SubnetIdentifier": "string",+ "SubnetAvailabilityZone": {"Name": "string"},+ "SubnetOutpost": {"Arn": "string"},+ "SubnetStatus": "string",+ },+ ],+ "DBSubnetGroupArn": "string",+ "SupportedNetworkTypes": [+ "string",+ ],+ },+ "PreferredMaintenanceWindow": "string",+ "PendingModifiedValues": {+ "DBInstanceClass": "string",+ "AllocatedStorage": 123,+ "MasterUserPassword": "string",+ "Port": 123,+ "BackupRetentionPeriod": 123,+ "MultiAZ": False,+ "EngineVersion": "string",+ "LicenseModel": "string",+ "Iops": 123,+ "DBInstanceIdentifier": "string",+ "StorageType": "string",+ "CACertificateIdentifier": "string",+ "DBSubnetGroupName": "string",+ "PendingCloudwatchLogsExports": {+ "LogTypesToEnable": [+ "string",+ ],+ "LogTypesToDisable": [+ "string",+ ],+ },+ "ProcessorFeatures": [+ {"Name": "string", "Value": "string"},+ ],+ "IAMDatabaseAuthenticationEnabled": False,+ "AutomationMode": "full",+ "ResumeFullAutomationModeTime": datetime(2015, 1, 1),+ "StorageThroughput": 123,+ },+ "LatestRestorableTime": datetime(2015, 1, 1),+ "MultiAZ": False,+ "EngineVersion": "string",+ "AutoMinorVersionUpgrade": False,+ "ReadReplicaSourceDBInstanceIdentifier": "string",+ "ReadReplicaDBInstanceIdentifiers": [+ "string",+ ],+ "ReadReplicaDBClusterIdentifiers": [+ "string",+ ],+ "ReplicaMode": "open-read-only",+ "LicenseModel": "string",+ "Iops": 123,+ "OptionGroupMemberships": [+ {"OptionGroupName": "string", "Status": "string"},+ ],+ "CharacterSetName": "string",+ "NcharCharacterSetName": "string",+ "SecondaryAvailabilityZone": "string",+ "PubliclyAccessible": False,+ "StatusInfos": [+ {+ "StatusType": "string",+ "Normal": True,+ "Status": "string",+ "Message": "string",+ },+ ],+ "StorageType": "string",+ "TdeCredentialArn": "string",+ "DbInstancePort": 123,+ "DBClusterIdentifier": "string",+ "StorageEncrypted": True,+ "KmsKeyId": "string",+ "DbiResourceId": "string",+ "CACertificateIdentifier": "string",+ "DomainMemberships": [+ {+ "Domain": "string",+ "Status": "string",+ "FQDN": "string",+ "IAMRoleName": "string",+ },+ ],+ "CopyTagsToSnapshot": True,+ "MonitoringInterval": 123,+ "EnhancedMonitoringResourceArn": "string",+ "MonitoringRoleArn": "string",+ "PromotionTier": 123,+ "DBInstanceArn": "string",+ "Timezone": "string",+ "IAMDatabaseAuthenticationEnabled": True,+ "PerformanceInsightsEnabled": True,+ "PerformanceInsightsKMSKeyId": "string",+ "PerformanceInsightsRetentionPeriod": 123,+ "EnabledCloudwatchLogsExports": [+ "string",+ ],+ "ProcessorFeatures": [+ {"Name": "string", "Value": "string"},+ ],+ "DeletionProtection": True,+ "AssociatedRoles": [+ {"RoleArn": "string", "FeatureName": "string", "Status": "string"},+ ],+ "ListenerEndpoint": {"Address": "string", "Port": 123, "HostedZoneId": "string"},+ "MaxAllocatedStorage": 123,+ "TagList": [+ {"Key": "string", "Value": "string"},+ ],+ "DBInstanceAutomatedBackupsReplications": [+ {"DBInstanceAutomatedBackupsArn": "string"},+ ],+ "CustomerOwnedIpEnabled": True,+ "AwsBackupRecoveryPointArn": "string",+ "ActivityStreamStatus": "stopped",+ "ActivityStreamKmsKeyId": "string",+ "ActivityStreamKinesisStreamName": "string",+ "ActivityStreamMode": "sync",+ "ActivityStreamEngineNativeAuditFieldsIncluded": True,+ "AutomationMode": "full",+ "ResumeFullAutomationModeTime": datetime(2015, 1, 1),+ "CustomIamInstanceProfile": "string",+ "BackupTarget": "string",+ "NetworkType": "string",+ "ActivityStreamPolicyStatus": "locked",+ "StorageThroughput": 123,+ "DBSystemId": "string",+ "MasterUserSecret": {+ "SecretArn": "string",+ "SecretStatus": "string",+ "KmsKeyId": "string",+ },+ "CertificateDetails": {"CAIdentifier": "string", "ValidTill": datetime(2015, 1, 1)},+ "ReadReplicaSourceDBClusterIdentifier": "string",+}diff --git a/catalog/tests/dags/database/staging_database_restore/test_staging_database_restore.py b/catalog/tests/dags/database/staging_database_restore/test_staging_database_restore.pynew file mode 100644index 000000000..5605b43ee--- /dev/null+++ b/catalog/tests/dags/database/staging_database_restore/test_staging_database_restore.py@@ -0,0 +1,110 @@+from datetime import datetime, timedelta+from unittest import mock++import pytest+from airflow import DAG+from airflow.providers.amazon.aws.hooks.rds import RdsHook+from airflow.utils.trigger_rule import TriggerRule++from catalog.tests.dags.database.staging_database_restore.data import (+ DESCRIBE_DB_INSTANCES_RESPONSE,+)+from database.staging_database_restore import staging_database_restore+++REFERENCE_DATE = datetime(2021, 1, 1, 0, 0, 0)+++def mock_rds_hook() -> RdsHook:+ return mock.MagicMock(spec=RdsHook)++[email protected]("should_skip", [True, False])+def test_skip_restore(should_skip):+ with mock.patch.object(+ staging_database_restore.slack, "send_message"+ ) as mock_send_message:+ actual = staging_database_restore.skip_restore.function(should_skip)+ assert actual == (not should_skip)+ assert mock_send_message.called == should_skip+++ "snapshots, expected",+ [+ (+ [+ {+ "SnapshotCreateTime": REFERENCE_DATE,+ "DBSnapshotIdentifier": str(REFERENCE_DATE),+ }+ ],+ str(REFERENCE_DATE),+ ),+ (+ [+ {+ "SnapshotCreateTime": (d := REFERENCE_DATE - timedelta(days=days)),+ "DBSnapshotIdentifier": str(d),+ }+ for days in range(10, 0, -1) # Reversed so that the latest is last+ ],+ REFERENCE_DATE,+ ),+ pytest.param(+ [],+ None,+ marks=pytest.mark.raises(exception=ValueError, match="No snapshots found"),+ ),+ ],+)+def test_get_latest_prod_snapshot(snapshots, expected, mock_rds_hook):+ mock_rds_hook.conn.describe_db_snapshots.return_value = {"DBSnapshots": snapshots}+ staging_database_restore.get_latest_prod_snapshot.function(rds_hook=mock_rds_hook)+++ "details",+ [+ [DESCRIBE_DB_INSTANCES_RESPONSE],+ # Missing keys raises a KeyError+ pytest.param([{}], marks=pytest.mark.raises(exception=KeyError)),+ # No data+ pytest.param(+ [],+ marks=pytest.mark.raises(exception=ValueError, match="No staging DB found"),+ ),+ ],+)+def test_get_staging_db_details(details, mock_rds_hook):+ mock_rds_hook.conn.describe_db_instances.return_value = {"DBInstances": details}+ actual = staging_database_restore.get_staging_db_details.function(+ rds_hook=mock_rds_hook+ )+ # Easiest way to test the logic is just to assert that it looks exactly how we+ # want after the function is called.+ assert actual == {+ "AllocatedStorage": 123,+ "AvailabilityZone": "string",+ "DBInstanceClass": "string",+ "DBSubnetGroupName": "string",+ "MultiAZ": False,+ "PubliclyAccessible": False,+ "VpcSecurityGroupIds": ["vpcsg1", "vpcsg2"],+ }+++def test_make_rename_task_group():+ rule = TriggerRule.NONE_FAILED+ with DAG(dag_id="test_make_rename_task_group", start_date=datetime(1970, 1, 1)):+ group = staging_database_restore.make_rename_task_group("dibble", "crim", rule)+ assert group.group_id == "rename_dibble_to_crim"+ rename, await_rename = list(group)+ assert rename.task_id == "rename_dibble_to_crim.rename_dibble_to_crim"+ assert rename.trigger_rule == TriggerRule.NONE_FAILED+ assert rename.retries == 0+ assert await_rename.task_id == "rename_dibble_to_crim.await_crim"+ # This should not be affected by the trigger rule+ assert await_rename.trigger_rule == TriggerRule.ALL_SUCCESS+ assert await_rename.retries == 2diff --git a/catalog/tests/dags/database/staging_database_restore/test_utils.py b/catalog/tests/dags/database/staging_database_restore/test_utils.pynew file mode 100644index 000000000..bc5c27ca7--- /dev/null+++ b/catalog/tests/dags/database/staging_database_restore/test_utils.py@@ -0,0 +1,50 @@+import pytest+from airflow.providers.amazon.aws.hooks.rds import RdsHook++from database.staging_database_restore import constants, utils+++def test_setup_rds_hook():+ @utils.setup_rds_hook+ def test_func(rds_hook: RdsHook = None):+ assert isinstance(rds_hook, RdsHook)++ test_func()+++def test_setup_rds_hook_uses_existing():+ shim_hook = object()++ @utils.setup_rds_hook+ def test_func(rds_hook: RdsHook = None):+ assert rds_hook is shim_hook++ test_func(rds_hook=shim_hook)+++def test_setup_rds_hook_fails_without_kwargs():+ @utils.setup_rds_hook+ def test_func():+ pass++ with pytest.raises(+ TypeError,+ match="got an unexpected keyword argument 'rds_hook'",+ ):+ test_func()+++ "db_identifier",+ [+ *sorted(constants.SAFE_TO_MUTATE),+ pytest.param(+ constants.PROD_IDENTIFIER, marks=pytest.mark.raises(exception=ValueError)+ ),+ pytest.param(+ "completely_unacceptable", marks=pytest.mark.raises(exception=ValueError)+ ),+ ],+)+def test_ensure_mutate_allowed(db_identifier):+ utils.ensure_mutate_allowed(db_identifier)