Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Add create_new_es_index DAGs (#3537)

Staci Mullins8e21893a2213
diff --git a/catalog/dags/common/constants.py b/catalog/dags/common/constants.py
index f660d49ab..13a7dab18 100644
--- a/catalog/dags/common/constants.py
+++ b/catalog/dags/common/constants.py
@@ -12,6 +12,9 @@ MEDIA_TYPES = [AUDIO, IMAGE]
MediaType = Literal["audio", "image"]
+STAGING = "staging"
+PRODUCTION = "production"
+
CONTACT_EMAIL = os.getenv("CONTACT_EMAIL")
DAG_DEFAULT_ARGS = {
diff --git a/catalog/dags/common/sensors/utils.py b/catalog/dags/common/sensors/utils.py
index 083e47598..bac5b8ce9 100644
--- a/catalog/dags/common/sensors/utils.py
+++ b/catalog/dags/common/sensors/utils.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from airflow.decorators import task
+from airflow.decorators import task, task_group
from airflow.exceptions import AirflowSensorTimeout
from airflow.models import DagRun
from airflow.sensors.external_task import ExternalTaskSensor
@@ -39,6 +39,14 @@ def wait_for_external_dag(external_dag_id: str, task_id: str | None = None):
"""
Return a Sensor task which will wait if the given external DAG is
running.
+
+ To fully ensure that the waiting DAG and the external DAG do not run
+ concurrently, the external DAG should have a `prevent_concurrency_with_dag`
+ task which fails immediately if the waiting DAG is running.
+
+ If the external DAG should _not_ fail when the waiting DAG is running,
+ but instead wait its turn, use the SingleRunExternalDagSensor in both
+ DAGs to avoid deadlock.
"""
if not task_id:
task_id = f"wait_for_{external_dag_id}"
@@ -57,6 +65,16 @@ def wait_for_external_dag(external_dag_id: str, task_id: str | None = None):
)
+@task_group(group_id="wait_for_external_dags")
+def wait_for_external_dags(external_dag_ids: list[str]):
+ """
+ Wait for all DAGs with the given external DAG ids to no longer be
+ in a running state before continuing.
+ """
+ for dag_id in external_dag_ids:
+ wait_for_external_dag(dag_id)
+
+
@task(retries=0)
def prevent_concurrency_with_dag(external_dag_id: str, **context):
"""
@@ -73,3 +91,12 @@ def prevent_concurrency_with_dag(external_dag_id: str, **context):
wait_for_dag.execute(context)
except AirflowSensorTimeout:
raise ValueError(f"Concurrency check with {external_dag_id} failed.")
+
+
+@task_group(group_id="prevent_concurrency")
+def prevent_concurrency_with_dags(external_dag_ids: list[str]):
+ """Fail immediately if any of the given external dags are in progress."""
+ for dag_id in external_dag_ids:
+ prevent_concurrency_with_dag.override(
+ task_id=f"prevent_concurrency_with_{dag_id}"
+ )(dag_id)
diff --git a/catalog/dags/data_refresh/create_filtered_index_dag.py b/catalog/dags/data_refresh/create_filtered_index_dag.py
index 72ce39313..7fc0f38ea 100644
--- a/catalog/dags/data_refresh/create_filtered_index_dag.py
+++ b/catalog/dags/data_refresh/create_filtered_index_dag.py
@@ -55,12 +55,15 @@ from datetime import datetime
from airflow import DAG
from airflow.models.param import Param
-from common.constants import DAG_DEFAULT_ARGS
-from common.sensors.utils import prevent_concurrency_with_dag
+from common.constants import DAG_DEFAULT_ARGS, PRODUCTION
+from common.sensors.utils import prevent_concurrency_with_dags
from data_refresh.create_filtered_index import (
create_filtered_index_creation_task_groups,
)
from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefresh
+from elasticsearch_cluster.create_new_es_index.create_new_es_index_types import (
+ CREATE_NEW_INDEX_CONFIGS,
+)
# Note: We can't use the TaskFlow `@dag` DAG factory decorator
@@ -80,7 +83,7 @@ def create_filtered_index_creation_dag(data_refresh: DataRefresh):
media_type = data_refresh.media_type
with DAG(
- dag_id=f"create_filtered_{media_type}_index",
+ dag_id=data_refresh.filtered_index_dag_id,
default_args=DAG_DEFAULT_ARGS,
schedule=None,
start_date=datetime(2023, 4, 1),
@@ -113,10 +116,15 @@ def create_filtered_index_creation_dag(data_refresh: DataRefresh):
},
render_template_as_native_obj=True,
) as dag:
- # Immediately fail if the associated data refresh is running.
- prevent_concurrency = prevent_concurrency_with_dag.override(
- task_id=f"prevent_concurrency_with_{media_type}_data_refresh"
- )(external_dag_id=f"{media_type}_data_refresh")
+ # Immediately fail if the associated data refresh is running, or the
+ # create_new_production_es_index DAG is running. This prevents multiple
+ # DAGs from reindexing from a single production index simultaneously.
+ prevent_concurrency = prevent_concurrency_with_dags(
+ external_dag_ids=[
+ data_refresh.dag_id,
+ CREATE_NEW_INDEX_CONFIGS[PRODUCTION].dag_id,
+ ]
+ )
# Once the concurrency check has passed, actually create the filtered
# index.
diff --git a/catalog/dags/data_refresh/data_refresh_task_factory.py b/catalog/dags/data_refresh/data_refresh_task_factory.py
index 1328e82b3..0531746aa 100644
--- a/catalog/dags/data_refresh/data_refresh_task_factory.py
+++ b/catalog/dags/data_refresh/data_refresh_task_factory.py
@@ -53,13 +53,16 @@ from airflow.utils.task_group import TaskGroup
from airflow.utils.trigger_rule import TriggerRule
from common import ingestion_server
-from common.constants import XCOM_PULL_TEMPLATE
+from common.constants import PRODUCTION, XCOM_PULL_TEMPLATE
from common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensor
-from common.sensors.utils import wait_for_external_dag
+from common.sensors.utils import wait_for_external_dags
from data_refresh.create_filtered_index import (
create_filtered_index_creation_task_groups,
)
from data_refresh.data_refresh_types import DataRefresh
+from elasticsearch_cluster.create_new_es_index.create_new_es_index_types import (
+ CREATE_NEW_INDEX_CONFIGS,
+)
logger = logging.getLogger(__name__)
@@ -112,16 +115,19 @@ def create_data_refresh_task_group(
pool=DATA_REFRESH_POOL,
)
- # If filtered index creation was manually triggered before the data refresh
- # started, we need to wait for it to finish or the data refresh could destroy
- # the origin index. Realistically the data refresh is too slow to beat the
- # filtered index creation process, even if it was triggered immediately after
- # filtered index creation. However, it is safer to avoid the possibility
- # of the race condition altogether.
- wait_for_filtered_index_creation = wait_for_external_dag(
- external_dag_id=f"create_filtered_{data_refresh.media_type}_index",
+ # Wait for other DAGs that operate on the ES cluster. If a new or filtered index
+ # is being created by one of these DAGs, we need to wait for it to finish or else
+ # the data refresh might destroy the index being used as the source index.
+ # Realistically the data refresh is too slow to beat the index creation process,
+ # even if it was triggered immediately after one of these DAGs; however, it is
+ # always safer to avoid the possibility of the race condition altogether.
+ wait_for_es_dags = wait_for_external_dags.override(group_id="wait_for_es_dags")(
+ external_dag_ids=[
+ data_refresh.filtered_index_dag_id,
+ CREATE_NEW_INDEX_CONFIGS[PRODUCTION].dag_id,
+ ]
)
- tasks.append([wait_for_data_refresh, wait_for_filtered_index_creation])
+ tasks.append([wait_for_data_refresh, wait_for_es_dags])
# Get the index currently mapped to our target alias, to delete later.
get_current_index = ingestion_server.get_current_index(target_alias)
diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.py
index 6791edb69..f6bc6dff6 100644
--- a/catalog/dags/data_refresh/data_refresh_types.py
+++ b/catalog/dags/data_refresh/data_refresh_types.py
@@ -53,6 +53,7 @@ class DataRefresh:
"""
dag_id: str = field(init=False)
+ filtered_index_dag_id: str = field(init=False)
media_type: str
start_date: datetime = datetime(2020, 1, 1)
schedule: str | None = "0 0 * * 1" # Mondays 00:00 UTC
@@ -69,6 +70,7 @@ class DataRefresh:
def __post_init__(self):
self.dag_id = f"{self.media_type}_data_refresh"
+ self.filtered_index_dag_id = f"create_filtered_{self.media_type}_index"
DATA_REFRESH_CONFIGS = {
diff --git a/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py b/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py
index 942bf1b80..85bed3561 100644
--- a/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py
+++ b/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py
@@ -29,9 +29,6 @@ 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 es.recreate_staging_index.recreate_full_staging_index import (
- DAG_ID as RECREATE_STAGING_INDEX_DAG_ID,
-)
from common.constants import (
AWS_RDS_CONN_ID,
@@ -51,6 +48,9 @@ from database.staging_database_restore.staging_database_restore import (
restore_staging_from_snapshot,
skip_restore,
)
+from elasticsearch_cluster.recreate_staging_index.recreate_full_staging_index import (
+ DAG_ID as RECREATE_STAGING_INDEX_DAG_ID,
+)
log = logging.getLogger(__name__)
diff --git a/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index.py b/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index.py
new file mode 100644
index 000000000..9fbc58192
--- /dev/null
+++ b/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index.py
@@ -0,0 +1,195 @@
+import logging
+from datetime import timedelta
+
+from airflow.decorators import task, task_group
+from airflow.models.connection import Connection
+from airflow.providers.elasticsearch.hooks.elasticsearch import ElasticsearchPythonHook
+from airflow.sensors.python import PythonSensor
+
+from common.constants import REFRESH_POKE_INTERVAL
+from elasticsearch_cluster.create_new_es_index.utils import merge_configurations
+
+
+logger = logging.getLogger(__name__)
+
+
+# Index settings that should not be copied over from the base configuration when
+# creating a new index.
+EXCLUDED_INDEX_SETTINGS = ["provided_name", "creation_date", "uuid", "version"]
+
+GET_FINAL_INDEX_CONFIG_TASK_NAME = "get_final_index_configuration"
+GET_CURRENT_INDEX_CONFIG_TASK_NAME = "get_current_index_configuration"
+
+
+@task
+def get_es_host(environment: str):
+ conn = Connection.get_connection_from_secrets(f"elasticsearch_http_{environment}")
+ return conn.host
+
+
+@task
+def get_index_name(media_type: str, index_suffix: str):
+ return f"{media_type}-{index_suffix}".lower()
+
+
+def check_override_config(override):
+ if override:
+ # Skip the steps to fetch the current index configuration
+ # and merge changes in.
+ return GET_FINAL_INDEX_CONFIG_TASK_NAME
+
+ return GET_CURRENT_INDEX_CONFIG_TASK_NAME
+
+
+@task
+def get_current_index_configuration(
+ source_index: str,
+ es_host: str,
+):
+ """
+ Return the configuration for the current index, identified by the
+ `source_index` param. `source_index` may be either an index name
+ or an alias, but must uniquely identify one existing index or an
+ error will be raised.
+ """
+ es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
+
+ response = es_conn.indices.get(
+ index=source_index,
+ # Return empty dict instead of throwing error if no index can be
+ # found. We raise our own error instead.
+ ignore_unavailable=True,
+ )
+
+ if len(response) != 1:
+ raise ValueError(f"Index {source_index} could not be uniquely identified.")
+
+ # The response has the form:
+ # { index_name: index_configuration }
+ # However, since `source_index` can be an alias rather than the index name,
+ # we do not necessarily know the index_name so we cannot access the configuration
+ # directly by key. We instead get the first value from the dict, knowing that we
+ # have already ensured in a previous check that there is exactly one value in the
+ # response.
+ config = next(iter(response.values()))
+ return config
+
+
+@task
+def merge_index_configurations(new_index_config, current_index_config):
+ """
+ Merge the `new_index_config` into the `current_index_config`, and
+ return an index configuration in the appropriate format for being
+ passed to the `create_index` API.
+ """
+ # Do not automatically apply any aliases to the new index
+ current_index_config.pop("aliases")
+
+ # Remove fields from the current_index_config that should not be copied
+ # over into the new index (such as uuid)
+ for setting in EXCLUDED_INDEX_SETTINGS:
+ current_index_config.get("settings", {}).get("index", {}).pop(setting)
+
+ # Merge the new configuration values into the current configuration
+ return merge_configurations(current_index_config, new_index_config)
+
+
+@task
+def get_final_index_configuration(
+ override_config: bool,
+ index_config,
+ merged_config,
+ index_name: str,
+):
+ """
+ Resolve the final index configuration to be used in the `create_index`
+ task.
+
+ Required arguments:
+
+ override_config: Whether the index_config should be used instead of
+ the merged_config
+ index_config: The new index configuration which was passed in via
+ DAG params
+ merged_config: The result of merging the index_config with the current
+ index configuration. This may be None if the merge
+ tasks were skipped using the override param.
+ index_name: Name of the index to update.
+ """
+ config = index_config if override_config else merged_config
+
+ # Apply the desired index name
+ config["index"] = index_name
+ return config
+
+
+@task
+def create_index(index_config, es_host: str):
+ es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
+
+ new_index = es_conn.indices.create(**index_config)
+
+ return new_index
+
+
+@task_group(group_id="trigger_and_wait_for_reindex")
+def trigger_and_wait_for_reindex(
+ index_name: str,
+ source_index: str,
+ query: dict,
+ timeout: timedelta,
+ requests_per_second: int,
+ es_host: str,
+):
+ @task
+ def trigger_reindex(
+ index_name: str,
+ source_index: str,
+ query: dict,
+ requests_per_second: int,
+ es_host: str,
+ ):
+ es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
+
+ source = {"index": source_index}
+ # An empty query is not accepted; only pass it
+ # if a query was actually supplied
+ if query:
+ source["query"] = query
+
+ response = es_conn.reindex(
+ source=source,
+ dest={"index": index_name},
+ # Parallelize indexing
+ slices="auto",
+ # Do not hold the slot while awaiting completion
+ wait_for_completion=False,
+ # Immediately refresh the index after completion to make
+ # the data available for search
+ refresh=True,
+ # Throttle
+ requests_per_second=requests_per_second,
+ )
+
+ return response["task"]
+
+ def _wait_for_reindex(task_id: str, es_host: str):
+ es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
+
+ response = es_conn.tasks.get(task_id=task_id)
+ return response.get("completed")
+
+ trigger_reindex_task = trigger_reindex(
+ index_name, source_index, query, requests_per_second, es_host
+ )
+
+ wait_for_reindex = PythonSensor(
+ task_id="wait_for_reindex",
+ python_callable=_wait_for_reindex,
+ timeout=timeout,
+ poke_interval=REFRESH_POKE_INTERVAL,
+ op_kwargs={"task_id": trigger_reindex_task, "es_host": es_host},
+ )
+
+ trigger_reindex_task >> wait_for_reindex
diff --git a/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index_dag.py b/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index_dag.py
new file mode 100644
index 000000000..39f23f0d9
--- /dev/null
+++ b/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index_dag.py
@@ -0,0 +1,248 @@
+"""
+# Create New ES Index DAG
+
+This file generates our Create New ES Index DAGs using a factory function. A
+separate DAG is generated for the staging and production environments.
+
+Each DAG can be used to create new Elasticsearch indices in their respective
+environment, based on an existing index. The following configuration options
+are available:
+
+* `media_type` : media type for which to create the new index
+* `index_suffix` : optional suffix to be added to the new index name. If not
+ supplied, a creation timestamp is used.
+* `source_index` : the existing index on which to base the new index, and from
+ which to copy records
+* `index_config` : a JSON object containing the configuration for the new index.
+ By default, this will be merged into the configuration of the
+ source index according to the merging policy documented below.
+* `query` : an optional Elasticsearch query, used to filter the documents
+ copied from the source index into the new index. If not
+ supplied, all records are copied.
+* `override_config`: boolean override; when True, the `index_config` will be used
+ for the new index configuration _without_ merging any values
+ from the source index config.
+
+## Merging policy
+
+The configuration will be merged such that a leaf key in the `index_config` overwrites
+the entire value present in the source configuration at that key. The leaf values are
+merged naively, so a list for instance is replaced entirely (rather than appending
+values). For example, if the base configuration is:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 1,
+ "number_of_replicas": 1
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": [
+ "animals => animal",
+ "animal => animal",
+ "anime => anime",
+ "animate => animate",
+ "animated => animate",
+ "universe => universe"
+ ]
+ }
+ }
+ }
+ }
+}
+```
+
+And the `index_config` passed in is:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 2,
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "rules": ["crim => cribble"]
+ }
+ }
+ }
+ }
+}
+```
+
+The resulting, merged configuration will be:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 2,
+ "number_of_replicas": 1
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": ["crim => cribble"]
+ }
+ }
+ }
+ }
+}
+```
+"""
+import logging
+
+from airflow import DAG
+from airflow.models.param import Param
+from airflow.utils.trigger_rule import TriggerRule
+
+from common.constants import AUDIO, DAG_DEFAULT_ARGS, MEDIA_TYPES
+from common.sensors.utils import prevent_concurrency_with_dags
+from elasticsearch_cluster.create_new_es_index import create_new_es_index as es
+from elasticsearch_cluster.create_new_es_index.create_new_es_index_types import (
+ CREATE_NEW_INDEX_CONFIGS,
+ CreateNewIndex,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def create_new_es_index_dag(config: CreateNewIndex):
+ dag = DAG(
+ dag_id=config.dag_id,
+ default_args=DAG_DEFAULT_ARGS,
+ schedule=None,
+ max_active_runs=1,
+ catchup=False,
+ doc_md=__doc__,
+ tags=["elasticsearch"],
+ render_template_as_native_obj=True,
+ params={
+ "media_type": Param(
+ default=AUDIO,
+ enum=MEDIA_TYPES,
+ description="The media type for which to create the index.",
+ ),
+ "index_suffix": Param(
+ default=None,
+ type=["string", "null"],
+ description=(
+ "The name suffix of the new index to create. This will be a string,"
+ " and will be used to name the index in Elasticsearch of the form"
+ " {media_type}-{index_suffix}. If not provided, the suffix will be a"
+ " timestamp of the form YYYYMMDDHHMMSS."
+ ),
+ ),
+ "source_index": Param(
+ default=None,
+ type=["string", "null"],
+ description=(
+ "The existing index on Elasticsearch to use as the basis for the new"
+ " index. If not provided, the index aliased to media_type will be used"
+ " (e.g. image for the image media type)."
+ ),
+ ),
+ "index_config": Param(
+ default={},
+ type=["object"],
+ description=(
+ "A JSON object containing the configuration for the new index."
+ " The values in this object will be merged with the existing"
+ " configuration, where the value specified at a leaf key in the"
+ " object will override the existing value (see Merging policy in"
+ " the DAG docs). This can also be the entire index configuration,"
+ " in which case the existing configuration will be replaced entirely"
+ " (see override_config parameter below)."
+ ),
+ ),
+ "query": Param(
+ default={},
+ type=["object", "null"],
+ description=(
+ "An optional Elasticsearch query to use to filter the documents to be"
+ " copied to the new index. If not provided, all documents will be"
+ " copied."
+ ),
+ ),
+ "override_config": Param(
+ default=False,
+ type="boolean",
+ description=(
+ " A boolean value which can be toggled to replace the existing index"
+ " configuration entirely with the new configuration. If True, the"
+ " index_config parameter will be used as the entire configuration. If"
+ " False, the index_config parameter will be merged with the existing"
+ " configuration."
+ ),
+ ),
+ },
+ )
+
+ with dag:
+ prevent_concurrency = prevent_concurrency_with_dags(config.blocking_dags)
+
+ es_host = es.get_es_host(environment=config.environment)
+
+ index_name = es.get_index_name(
+ media_type="{{ params.media_type }}",
+ index_suffix="{{ params.index_suffix or ts_nodash }}",
+ )
+
+ check_override = es.check_override_config(
+ override="{{ params.override_config }}"
+ )
+
+ current_index_config = es.get_current_index_configuration.override(
+ task_id=es.GET_CURRENT_INDEX_CONFIG_TASK_NAME
+ )(
+ source_index="{{ params.source_index or params.media_type }}",
+ es_host=es_host,
+ )
+
+ merged_index_config = es.merge_index_configurations(
+ new_index_config="{{ params.index_config }}",
+ current_index_config=current_index_config,
+ )
+
+ final_index_config = es.get_final_index_configuration.override(
+ task_id=es.GET_FINAL_INDEX_CONFIG_TASK_NAME,
+ trigger_rule=TriggerRule.NONE_FAILED,
+ )(
+ override_config="{{ params.override_config }}",
+ index_config="{{ params.index_config }}",
+ # May resolve to None if tasks were skipped
+ merged_config=merged_index_config,
+ index_name=index_name,
+ )
+
+ create_new_index = es.create_index(
+ index_config=final_index_config, es_host=es_host
+ )
+
+ reindex = es.trigger_and_wait_for_reindex(
+ index_name=index_name,
+ source_index="{{ params.source_index or params.media_type }}",
+ query="{{ params.query }}",
+ timeout=config.reindex_timeout,
+ requests_per_second=config.requests_per_second,
+ es_host=es_host,
+ )
+
+ # Set up dependencies
+ prevent_concurrency >> [es_host, index_name]
+ index_name >> check_override >> [current_index_config, final_index_config]
+ current_index_config >> merged_index_config >> final_index_config
+ final_index_config >> create_new_index >> reindex
+
+ return dag
+
+
+for config in CREATE_NEW_INDEX_CONFIGS.values():
+ # Generate the DAG for this environment
+ globals()[config.dag_id] = create_new_es_index_dag(config)
diff --git a/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index_types.py b/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index_types.py
new file mode 100644
index 000000000..cf631e4cb
--- /dev/null
+++ b/catalog/dags/elasticsearch_cluster/create_new_es_index/create_new_es_index_types.py
@@ -0,0 +1,66 @@
+from dataclasses import dataclass, field
+from datetime import timedelta
+
+from airflow.models import Variable
+
+from common.constants import PRODUCTION, STAGING
+from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS
+from database.staging_database_restore.constants import (
+ DAG_ID as STAGING_DB_RESTORE_DAG_ID,
+)
+from elasticsearch_cluster.recreate_staging_index.recreate_full_staging_index import (
+ DAG_ID as RECREATE_STAGING_INDEX_DAG_ID,
+)
+
+
+@dataclass
+class CreateNewIndex:
+ """
+ Configuration object for the create_new_es_index DAG.
+
+ Required Constructor Arguments:
+
+ environment: str representation of the environment in which to
+ create the new index
+ blocking_dags: list of dags with which to prevent concurrency; the
+ generated create_new_es_index dag will fail
+ immediately if any of these dags are running.
+ reindex_timeout: timedelta expressing maximum amount of time the
+ reindexing step may take
+ requests_per_second: number of requests to send per second during ES
+ reindexing, used to throttle the reindex step
+ """
+
+ dag_id: str = field(init=False)
+ es_host: str = field(init=False)
+ environment: str
+ blocking_dags: list
+ requests_per_second: int | None = None
+ reindex_timeout: timedelta = timedelta(hours=12)
+
+ def __post_init__(self):
+ self.dag_id = f"create_new_{self.environment}_es_index"
+
+ if not self.requests_per_second:
+ self.requests_per_second = Variable.get(
+ "ES_INDEX_THROTTLING_RATE", 20_000, deserialize_json=True
+ )
+
+
+CREATE_NEW_INDEX_CONFIGS = {
+ STAGING: CreateNewIndex(
+ environment=STAGING,
+ blocking_dags=[RECREATE_STAGING_INDEX_DAG_ID, STAGING_DB_RESTORE_DAG_ID],
+ ),
+ PRODUCTION: CreateNewIndex(
+ environment=PRODUCTION,
+ blocking_dags=(
+ # Block on all the data refreshes
+ [data_refresh.dag_id for data_refresh in DATA_REFRESH_CONFIGS.values()]
+ + [ # Block on the filtered index creation DAGs
+ data_refresh.filtered_index_dag_id
+ for data_refresh in DATA_REFRESH_CONFIGS.values()
+ ]
+ ),
+ ),
+}
diff --git a/catalog/dags/elasticsearch_cluster/create_new_es_index/utils.py b/catalog/dags/elasticsearch_cluster/create_new_es_index/utils.py
new file mode 100644
index 000000000..eaf69a9da
--- /dev/null
+++ b/catalog/dags/elasticsearch_cluster/create_new_es_index/utils.py
@@ -0,0 +1,53 @@
+def merge_configurations(base_configuration, update_configuration):
+ """
+ Return a new dictionary which is the result of merging the given
+ update_configuration dictionary into the base_configuration dictionary,
+ according to the following merge policy:
+
+ A leaf key in the `update_configuration` overwrites the entire value
+ present in the `base_configuration` at that key. This is a naive
+ overwrite, such that a list value for example is completely
+ overwritten rather than appended to. For example:
+
+ merge_configurations(
+ base_configuration={
+ "parent_key": {
+ "leaf_key": ["value1", "value2"]
+ },
+ "other_key": True,
+ },
+ update_configuration={
+ "parent_key": {
+ "leaf_key": ["value3",]
+ },
+ }
+ )
+
+ will return:
+
+ {
+ "parent_key": {
+ "leaf_key": ["value3",]
+ },
+ "other_key": True
+ }
+ """
+ merge_configuration = base_configuration.copy()
+ for key, val in update_configuration.items():
+ if (
+ # The key is not present in the base configuration, so
+ # we are adding a new value rather than updating an existing
+ # one and can simply add it.
+ key not in base_configuration
+ or
+ # This is a leaf node.
+ not isinstance(val, dict)
+ ):
+ merge_configuration[key] = val
+ else:
+ # Recurse down to the leaf nodes.
+ merge_configuration[key] = merge_configurations(
+ base_configuration[key], update_configuration[key]
+ )
+
+ return merge_configuration
diff --git a/catalog/dags/es/recreate_staging_index/recreate_full_staging_index.py b/catalog/dags/elasticsearch_cluster/recreate_staging_index/recreate_full_staging_index.py
similarity index 100%
rename from catalog/dags/es/recreate_staging_index/recreate_full_staging_index.py
rename to catalog/dags/elasticsearch_cluster/recreate_staging_index/recreate_full_staging_index.py
diff --git a/catalog/dags/es/recreate_staging_index/recreate_full_staging_index_dag.py b/catalog/dags/elasticsearch_cluster/recreate_staging_index/recreate_full_staging_index_dag.py
similarity index 89%
rename from catalog/dags/es/recreate_staging_index/recreate_full_staging_index_dag.py
rename to catalog/dags/elasticsearch_cluster/recreate_staging_index/recreate_full_staging_index_dag.py
index 55f0a60ea..3b4cb8eb5 100644
--- a/catalog/dags/es/recreate_staging_index/recreate_full_staging_index_dag.py
+++ b/catalog/dags/elasticsearch_cluster/recreate_staging_index/recreate_full_staging_index_dag.py
@@ -41,7 +41,23 @@ from datetime import datetime
from airflow.decorators import dag
from airflow.models.param import Param
from airflow.utils.trigger_rule import TriggerRule
-from es.recreate_staging_index.recreate_full_staging_index import (
+
+from common import ingestion_server, slack
+from common.constants import (
+ AUDIO,
+ DAG_DEFAULT_ARGS,
+ MEDIA_TYPES,
+ STAGING,
+ XCOM_PULL_TEMPLATE,
+)
+from common.sensors.utils import prevent_concurrency_with_dags
+from database.staging_database_restore.constants import (
+ DAG_ID as STAGING_DB_RESTORE_DAG_ID,
+)
+from elasticsearch_cluster.create_new_es_index.create_new_es_index_types import (
+ CREATE_NEW_INDEX_CONFIGS,
+)
+from elasticsearch_cluster.recreate_staging_index.recreate_full_staging_index import (
DAG_ID,
create_index,
get_target_alias,
@@ -49,13 +65,6 @@ from es.recreate_staging_index.recreate_full_staging_index import (
should_delete_index,
)
-from common import ingestion_server, slack
-from common.constants import AUDIO, DAG_DEFAULT_ARGS, MEDIA_TYPES, XCOM_PULL_TEMPLATE
-from common.sensors.utils import prevent_concurrency_with_dag
-from database.staging_database_restore.constants import (
- DAG_ID as STAGING_DB_RESTORE_DAG_ID,
-)
-
@dag(
dag_id=DAG_ID,
@@ -94,10 +103,14 @@ from database.staging_database_restore.constants import (
render_template_as_native_obj=True,
)
def recreate_full_staging_index():
- # Fail early if the staging_db_restore DAG is running
- prevent_concurrency = prevent_concurrency_with_dag.override(
- task_id="prevent_concurrency_with_staging_db_restore"
- )(external_dag_id=STAGING_DB_RESTORE_DAG_ID)
+ # Fail early if the staging_db_restore DAG or the create_new_staging_es_index DAG
+ # is running
+ prevent_concurrency = prevent_concurrency_with_dags(
+ external_dag_ids=[
+ STAGING_DB_RESTORE_DAG_ID,
+ CREATE_NEW_INDEX_CONFIGS[STAGING].dag_id,
+ ]
+ )
target_alias = get_target_alias(
media_type="{{ params.media_type }}",
diff --git a/catalog/env.template b/catalog/env.template
index 8e94e2471..93fed3759 100644
--- a/catalog/env.template
+++ b/catalog/env.template
@@ -46,8 +46,9 @@ AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING=postgres://deploy:deploy@upstream_db:54
AIRFLOW_CONN_POSTGRES_OPENLEDGER_API_STAGING=postgres://deploy:deploy@db:5432/openledger
TEST_CONN_ID=postgres_openledger_testing
-# Elasticsearch connections. Change the following line in prod to use the appropriate URL.
+# Elasticsearch connections. Change the following line in prod to use the appropriate URLs.
AIRFLOW_CONN_ELASTICSEARCH_HTTP_PRODUCTION=http://es:9200
+AIRFLOW_CONN_ELASTICSEARCH_HTTP_STAGING=http://es:9200
# API DB connection. Change the following line in prod to use the appropriate DB
AIRFLOW_CONN_POSTGRES_OPENLEDGER_API=postgres://deploy:deploy@db:5432/openledger
@@ -106,6 +107,10 @@ AIRFLOW_VAR_CATCHUP_ENABLED=false
# Number of records to expect in a healthy ES index. Used during the data refresh to verify that
# a new index is healthy before promoting.
ES_INDEX_READINESS_RECORD_COUNT=1000
+# Throttle for elasticsearch reindexing. This is used by DAGs that directly connect
+# to Elasticsearch; it is not used for DAGs which reindex via the ingestion server, such as
+# the data refreshes.
+AIRFLOW_VAR_ES_INDEX_THROTTLING_RATE=20000
# Warning in dependency, nothing we can do
# https://docs.sqlalchemy.org/en/20/errors.html#error-b8d9
SQLALCHEMY_SILENCE_UBER_WARNING=1
diff --git a/catalog/tests/dags/elasticsearch_cluster/create_new_es_index/test_create_new_es_index.py b/catalog/tests/dags/elasticsearch_cluster/create_new_es_index/test_create_new_es_index.py
new file mode 100644
index 000000000..b307f272b
--- /dev/null
+++ b/catalog/tests/dags/elasticsearch_cluster/create_new_es_index/test_create_new_es_index.py
@@ -0,0 +1,89 @@
+from elasticsearch_cluster.create_new_es_index.create_new_es_index import (
+ merge_index_configurations,
+)
+
+
+def test_merge_index_configurations():
+ """Test merge_index_configurations with realistic data."""
+ current_index_config = {
+ "aliases": {"audio": {}},
+ "mappings": {
+ "dynamic": "false",
+ "properties": {"authority_boost": {"type": "rank_feature"}},
+ },
+ "settings": {
+ "index": {
+ "routing": {
+ "allocation": {"include": {"_tier_preference": "data_content"}}
+ },
+ "refresh_interval": "-1",
+ "number_of_shards": "1",
+ "provided_name": "audio-init",
+ "creation_date": "1704314839358",
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": ["animals => animal", "animal => animal"],
+ },
+ },
+ "analyzer": {"tokenizer": "standard"},
+ },
+ "number_of_replicas": "1",
+ "uuid": "fHs6A-7oSpOmutQLgWA0sw",
+ "version": {"created": "8080299"},
+ }
+ },
+ }
+
+ # New index config contains changes to some keys, including nested keys.
+ new_index_config = {
+ "settings": {
+ "index": {
+ "routing": {"allocation": {"include": {"_tier_preference": "foo"}}},
+ "refresh_interval": "9999",
+ "number_of_shards": "9999",
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": [
+ "foo => bar",
+ ],
+ },
+ }
+ },
+ }
+ }
+ }
+
+ # Aliases and excluded settings dropped, changes merged.
+ expected_merged_config = {
+ "mappings": {
+ "dynamic": "false",
+ "properties": {"authority_boost": {"type": "rank_feature"}},
+ },
+ "settings": {
+ "index": {
+ "routing": {"allocation": {"include": {"_tier_preference": "foo"}}},
+ "refresh_interval": "9999",
+ "number_of_shards": "9999",
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": [
+ "foo => bar",
+ ],
+ },
+ },
+ "analyzer": {"tokenizer": "standard"},
+ },
+ "number_of_replicas": "1",
+ }
+ },
+ }
+ actual_merged_config = merge_index_configurations.function(
+ new_index_config, current_index_config
+ )
+ assert actual_merged_config == expected_merged_config
diff --git a/catalog/tests/dags/elasticsearch_cluster/create_new_es_index/test_util.py b/catalog/tests/dags/elasticsearch_cluster/create_new_es_index/test_util.py
new file mode 100644
index 000000000..f00bdff0f
--- /dev/null
+++ b/catalog/tests/dags/elasticsearch_cluster/create_new_es_index/test_util.py
@@ -0,0 +1,81 @@
+import pytest
+
+from elasticsearch_cluster.create_new_es_index.utils import merge_configurations
+
+
+ "base_configuration, update_configuration, expected_merge_configuration",
+ [
+ # Update config includes keys not present in base config
+ pytest.param(
+ {"foo_key": "foo", "bar_key": "bar"},
+ {"new_key": "new_val"},
+ {"foo_key": "foo", "bar_key": "bar", "new_key": "new_val"},
+ id="add_new_keys_to_base_config",
+ ),
+ # Nested leaf nodes
+ pytest.param(
+ {
+ "grandparent_key": {
+ "parent_key": {"leaf_key": "foo", "other_leaf_key": "foobar"},
+ "other_key": "bar",
+ },
+ "other_top_key": "baz",
+ },
+ {"grandparent_key": {"parent_key": {"leaf_key": "new_leaf_val"}}},
+ {
+ "grandparent_key": {
+ "parent_key": {
+ "leaf_key": "new_leaf_val",
+ "other_leaf_key": "foobar",
+ },
+ "other_key": "bar",
+ },
+ "other_top_key": "baz",
+ },
+ id="update_nested_leaf_nodes",
+ ),
+ # Naively overwrite entire list values, rather than appending
+ # to them
+ pytest.param(
+ {
+ "parent_key": {"leaf_key": ["value1", "value2"]},
+ },
+ {
+ "parent_key": {
+ "leaf_key": [
+ "value3",
+ ]
+ },
+ },
+ {
+ "parent_key": {
+ "leaf_key": [
+ "value3",
+ ]
+ },
+ },
+ id="overwrite_list_values",
+ ),
+ pytest.param(
+ {},
+ {"foo": "bar", "parent": {"leaf": "baz"}},
+ {"foo": "bar", "parent": {"leaf": "baz"}},
+ id="empty_base_configuration",
+ ),
+ pytest.param(
+ {"foo": "bar", "parent": {"leaf": "baz"}},
+ {},
+ {"foo": "bar", "parent": {"leaf": "baz"}},
+ id="empty_update_configuration",
+ ),
+ ],
+)
+def test_merge_configurations(
+ base_configuration, update_configuration, expected_merge_configuration
+):
+ actual_merge_configuration = merge_configurations(
+ base_configuration, update_configuration
+ )
+
+ assert actual_merge_configuration == expected_merge_configuration
diff --git a/catalog/tests/dags/test_dag_parsing.py b/catalog/tests/dags/test_dag_parsing.py
index 83f1648a0..2a070e022 100644
--- a/catalog/tests/dags/test_dag_parsing.py
+++ b/catalog/tests/dags/test_dag_parsing.py
@@ -24,7 +24,7 @@ DAG_PATHS = [
"popularity/popularity_refresh_dag_factory.py",
"data_refresh/dag_factory.py",
"data_refresh/create_filtered_index_dag.py",
- "es/recreate_staging_index/recreate_full_staging_index_dag.py",
+ "elasticsearch_cluster/recreate_staging_index/recreate_full_staging_index_dag.py",
"oauth2/authorize_dag.py",
"oauth2/token_refresh_dag.py",
"database/delete_records/delete_records_dag.py",
diff --git a/documentation/catalog/reference/DAGs.md b/documentation/catalog/reference/DAGs.md
index 0b8e1266b..471cfd2e2 100644
--- a/documentation/catalog/reference/DAGs.md
+++ b/documentation/catalog/reference/DAGs.md
@@ -17,6 +17,7 @@ The following are DAGs grouped by their primary tag:
1. [Data Normalization](#data-normalization)
1. [Data Refresh](#data-refresh)
1. [Database](#database)
+1. [Elasticsearch](#elasticsearch)
1. [Maintenance](#maintenance)
1. [Oauth](#oauth)
1. [Other](#other)
@@ -51,6 +52,13 @@ The following are DAGs grouped by their primary tag:
| [`report_pending_reported_media`](#report_pending_reported_media) | `@weekly` |
| [`staging_database_restore`](#staging_database_restore) | `@monthly` |
+### Elasticsearch
+
+| DAG ID | Schedule Interval |
+| ------------------------------------------------------------------- | ----------------- |
+| [`create_new_production_es_index`](#create_new_production_es_index) | `None` |
+| [`create_new_staging_es_index`](#create_new_staging_es_index) | `None` |
+
### Maintenance
| DAG ID | Schedule Interval |
@@ -130,6 +138,8 @@ The following is documentation associated with each DAG (where available):
1. [`check_silenced_dags`](#check_silenced_dags)
1. [`create_filtered_audio_index`](#create_filtered_audio_index)
1. [`create_filtered_image_index`](#create_filtered_image_index)
+1. [`create_new_production_es_index`](#create_new_production_es_index)
+1. [`create_new_staging_es_index`](#create_new_staging_es_index)
1. [`delete_records`](#delete_records)
1. [`europeana_workflow`](#europeana_workflow)
1. [`finnish_museums_workflow`](#finnish_museums_workflow)
@@ -464,6 +474,204 @@ There are two mechanisms that prevent this from happening:
This ensures that neither are depending on or modifying the origin indexes
critical for the creation of the filtered indexes.
+### `create_new_production_es_index`
+
+#### Create New ES Index DAG
+
+This file generates our Create New ES Index DAGs using a factory function. A
+separate DAG is generated for the staging and production environments.
+
+Each DAG can be used to create new Elasticsearch indices in their respective
+environment, based on an existing index. The following configuration options are
+available:
+
+- `media_type` : media type for which to create the new index
+- `index_suffix` : optional suffix to be added to the new index name. If not
+ supplied, a creation timestamp is used.
+- `source_index` : the existing index on which to base the new index, and from
+ which to copy records
+- `index_config` : a JSON object containing the configuration for the new index.
+ By default, this will be merged into the configuration of the source index
+ according to the merging policy documented below.
+- `query` : an optional Elasticsearch query, used to filter the documents copied
+ from the source index into the new index. If not supplied, all records are
+ copied.
+- `override_config`: boolean override; when True, the `index_config` will be
+ used for the new index configuration _without_ merging any values from the
+ source index config.
+
+##### Merging policy
+
+The configuration will be merged such that a leaf key in the `index_config`
+overwrites the entire value present in the source configuration at that key. The
+leaf values are merged naively, so a list for instance is replaced entirely
+(rather than appending values). For example, if the base configuration is:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 1,
+ "number_of_replicas": 1
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": [
+ "animals => animal",
+ "animal => animal",
+ "anime => anime",
+ "animate => animate",
+ "animated => animate",
+ "universe => universe"
+ ]
+ }
+ }
+ }
+ }
+}
+```
+
+And the `index_config` passed in is:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 2,
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "rules": ["crim => cribble"]
+ }
+ }
+ }
+ }
+}
+```
+
+The resulting, merged configuration will be:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 2,
+ "number_of_replicas": 1
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": ["crim => cribble"]
+ }
+ }
+ }
+ }
+}
+```
+
+### `create_new_staging_es_index`
+
+#### Create New ES Index DAG
+
+This file generates our Create New ES Index DAGs using a factory function. A
+separate DAG is generated for the staging and production environments.
+
+Each DAG can be used to create new Elasticsearch indices in their respective
+environment, based on an existing index. The following configuration options are
+available:
+
+- `media_type` : media type for which to create the new index
+- `index_suffix` : optional suffix to be added to the new index name. If not
+ supplied, a creation timestamp is used.
+- `source_index` : the existing index on which to base the new index, and from
+ which to copy records
+- `index_config` : a JSON object containing the configuration for the new index.
+ By default, this will be merged into the configuration of the source index
+ according to the merging policy documented below.
+- `query` : an optional Elasticsearch query, used to filter the documents copied
+ from the source index into the new index. If not supplied, all records are
+ copied.
+- `override_config`: boolean override; when True, the `index_config` will be
+ used for the new index configuration _without_ merging any values from the
+ source index config.
+
+##### Merging policy
+
+The configuration will be merged such that a leaf key in the `index_config`
+overwrites the entire value present in the source configuration at that key. The
+leaf values are merged naively, so a list for instance is replaced entirely
+(rather than appending values). For example, if the base configuration is:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 1,
+ "number_of_replicas": 1
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": [
+ "animals => animal",
+ "animal => animal",
+ "anime => anime",
+ "animate => animate",
+ "animated => animate",
+ "universe => universe"
+ ]
+ }
+ }
+ }
+ }
+}
+```
+
+And the `index_config` passed in is:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 2,
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "rules": ["crim => cribble"]
+ }
+ }
+ }
+ }
+}
+```
+
+The resulting, merged configuration will be:
+
+```
+{
+ "settings": {
+ "index": {
+ "number_of_shards": 2,
+ "number_of_replicas": 1
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": ["crim => cribble"]
+ }
+ }
+ }
+ }
+}
+```
+
### `delete_records`
#### Delete Records DAG