Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add distributed reindex steps (#4572)
Staci Mullins2d364ed7c864
diff --git a/catalog/dags/common/constants.py b/catalog/dags/common/constants.pyindex f2b1f45a4..0105ecda9 100644--- a/catalog/dags/common/constants.py+++ b/catalog/dags/common/constants.py@@ -49,6 +49,7 @@ AWS_CLOUDWATCH_CONN_ID = os.environ.get("AWS_CLOUDWATCH_CONN_ID", AWS_CONN_ID)AWS_RDS_CONN_ID = os.environ.get("AWS_RDS_CONN_ID", AWS_CONN_ID)ES_PROD_HTTP_CONN_ID = "elasticsearch_http_production"REFRESH_POKE_INTERVAL = int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 30))+DATA_REFRESH_POOL = os.getenv("DATA_REFRESH_POOL", "data_refresh")@dataclassdiff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.pyindex 048133594..005829b99 100644--- a/catalog/dags/common/elasticsearch.py+++ b/catalog/dags/common/elasticsearch.py@@ -78,6 +78,24 @@ def remove_excluded_index_settings(index_config):return index_config+@task+def get_index_configuration_copy(+ source_index: str, target_index_name: str, es_host: str+):+ """+ Create a new index configuration based off the `source_index` but with the given+ `target_index_name`, in the format needed for `create_index`. Removes fields that+ should not be copied into a new index configuration such as the uuid.+ """+ base_config = get_index_configuration.function(source_index, es_host)++ cleaned_config = remove_excluded_index_settings(base_config)++ cleaned_config["index"] = target_index_name++ return cleaned_config++@taskdef get_record_count_group_by_sources(es_host: str, index: str):"""diff --git a/catalog/dags/common/operators/http.py b/catalog/dags/common/operators/http.pynew file mode 100644index 000000000..b68e9ba7f--- /dev/null+++ b/catalog/dags/common/operators/http.py@@ -0,0 +1,11 @@+from airflow.providers.http.operators.http import HttpOperator+++class TemplatedConnectionHttpOperator(HttpOperator):+ """+ Wrapper around the HTTPOperator which allows templating of the conn_id,+ in order to support using a conn_id passed through XCOMs.+ """++ # Extended to allow templating of conn_id+ template_fields = HttpOperator.template_fields + ("http_conn_id",)diff --git a/catalog/dags/common/sensors/http.py b/catalog/dags/common/sensors/http.pynew file mode 100644index 000000000..0dc2652f7--- /dev/null+++ b/catalog/dags/common/sensors/http.py@@ -0,0 +1,11 @@+from airflow.providers.http.sensors.http import HttpSensor+++class TemplatedConnectionHttpSensor(HttpSensor):+ """+ Wrapper around the HTTPSensor which allows templating of the conn_id,+ in order to support using a conn_id passed through XCOMs.+ """++ # Extended to allow templating of conn_id+ template_fields = HttpSensor.template_fields + ("http_conn_id",)diff --git a/catalog/dags/data_refresh/alter_data.py b/catalog/dags/data_refresh/alter_data.pyindex fb0ab98ac..260900bd3 100644--- a/catalog/dags/data_refresh/alter_data.py+++ b/catalog/dags/data_refresh/alter_data.py@@ -182,12 +182,12 @@ def report(counts: list[int]):@task_group(group_id="alter_table_data")def alter_table_data(- environment: Environment,+ target_environment: Environment,data_refresh_config: DataRefreshConfig,):"""Perform data altering across a number of tasks."""- postgres_conn_id = POSTGRES_API_CONN_IDS.get(environment)- temp_table = data_refresh_config.table_mappings[0].temp_table_name+ postgres_conn_id = POSTGRES_API_CONN_IDS.get(target_environment)+ temp_table = data_refresh_config.table_mapping.temp_table_nameestimated_record_count = PGExecuteQueryOperator(task_id="get_estimated_record_count",diff --git a/catalog/dags/data_refresh/constants.py b/catalog/dags/data_refresh/constants.pynew file mode 100644index 000000000..6a74f93d8--- /dev/null+++ b/catalog/dags/data_refresh/constants.py@@ -0,0 +1,9 @@+from common.constants import PRODUCTION, STAGING+++INDEXER_WORKER_COUNTS = {STAGING: 2, PRODUCTION: 6}++INDEXER_LAUNCH_TEMPLATES = {+ STAGING: "indexer-worker-pool-s",+ PRODUCTION: "indexer-worker-pool-p",+}diff --git a/catalog/dags/data_refresh/copy_data.py b/catalog/dags/data_refresh/copy_data.pyindex dea6a2cc7..eecda7b3e 100644--- a/catalog/dags/data_refresh/copy_data.py+++ b/catalog/dags/data_refresh/copy_data.py@@ -198,7 +198,6 @@ def copy_data(def copy_upstream_table(upstream_conn_id: str,downstream_conn_id: str,- environment: Environment,timeout: timedelta,limit: int,upstream_table_name: str,@@ -275,12 +274,13 @@ def copy_upstream_table(create_temp_table >> setup_id_columns >> setup_tertiary_columnssetup_tertiary_columns >> copycopy >> add_primary_key+return@task_group(group_id="copy_upstream_tables")def copy_upstream_tables(- environment: Environment, data_refresh_config: DataRefreshConfig+ target_environment: Environment, data_refresh_config: DataRefreshConfig):"""For each upstream table associated with the given media type, create a new@@ -290,7 +290,7 @@ def copy_upstream_tables(This task does _not_ apply all indices and constraints, merely copiesthe data."""- downstream_conn_id = POSTGRES_API_CONN_IDS.get(environment)+ downstream_conn_id = POSTGRES_API_CONN_IDS.get(target_environment)upstream_conn_id = POSTGRES_CONN_IDcreate_fdw = _run_sql.override(task_id="create_fdw")(@@ -309,7 +309,6 @@ def copy_upstream_tables(copy_tables = copy_upstream_table.partial(upstream_conn_id=upstream_conn_id,downstream_conn_id=downstream_conn_id,- environment=environment,timeout=data_refresh_config.copy_data_timeout,limit=limit,).expand_kwargs([asdict(tm) for tm in data_refresh_config.table_mappings])diff --git a/catalog/dags/data_refresh/create_and_promote_index.py b/catalog/dags/data_refresh/create_and_promote_index.pynew file mode 100644index 000000000..2f5dd2650--- /dev/null+++ b/catalog/dags/data_refresh/create_and_promote_index.py@@ -0,0 +1,46 @@+"""+# Create and Promote Index++This file contains TaskGroups related to creating and promoting Elasticsearch indices+as part of the Data Refresh.+"""++import logging+import uuid++from airflow.decorators import task, task_group++from common import elasticsearch as es+from data_refresh.data_refresh_types import DataRefreshConfig+++logger = logging.getLogger(__name__)+++@task+def generate_index_name(media_type: str) -> str:+ return f"{media_type}-{uuid.uuid4().hex}"+++@task_group(group_id="create_temp_index")+def create_index(+ data_refresh_config: DataRefreshConfig,+ es_host: str,+):+ # Generate a UUID suffix that will be used by the newly created index.+ temp_index_name = generate_index_name(media_type=data_refresh_config.media_type)++ # Get the configuration for the new Elasticsearch index, based off the existing index.+ index_config = es.get_index_configuration_copy.override(+ task_id="get_index_configuration"+ )(+ source_index=data_refresh_config.media_type,+ target_index_name=temp_index_name,+ es_host=es_host,+ )++ # Create a new index matching the existing configuration+ es.create_index(index_config=index_config, es_host=es_host)++ # Return the name of the created index+ return temp_index_namediff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.pyindex 32533ac3a..bb92755bd 100644--- a/catalog/dags/data_refresh/dag_factory.py+++ b/catalog/dags/data_refresh/dag_factory.py@@ -27,7 +27,6 @@ https://github.com/WordPress/openverse-catalog/issues/453)"""import logging-import osfrom collections.abc import Sequencefrom itertools import product@@ -38,22 +37,26 @@ from airflow.utils.trigger_rule import TriggerRulefrom common import cloudwatchfrom common import elasticsearch as es-from common.constants import DAG_DEFAULT_ARGS, ENVIRONMENTS, Environment+from common.constants import (+ DAG_DEFAULT_ARGS,+ DATA_REFRESH_POOL,+ ENVIRONMENTS,+ Environment,+)from common.sensors.constants import ES_CONCURRENCY_TAGSfrom common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensorfrom common.sensors.utils import wait_for_external_dags_with_tagfrom data_refresh.alter_data import alter_table_datafrom data_refresh.copy_data import copy_upstream_tables+from data_refresh.create_and_promote_index import create_indexfrom data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefreshConfig+from data_refresh.distributed_reindex import perform_distributed_reindexfrom data_refresh.reporting import report_record_differencelogger = logging.getLogger(__name__)-DATA_REFRESH_POOL = os.getenv("DATA_REFRESH_POOL", "data_refresh")--@task_group(group_id="wait_for_conflicting_dags")def wait_for_conflicting_dags(data_refresh_config: DataRefreshConfig,@@ -65,7 +68,7 @@ def wait_for_conflicting_dags(task_id="wait_for_data_refresh",external_dag_ids=external_dag_ids,check_existence=True,- poke_interval=data_refresh_config.data_refresh_poke_interval,+ poke_interval=data_refresh_config.concurrency_check_poke_interval,mode="reschedule",pool=DATA_REFRESH_POOL,)@@ -86,7 +89,7 @@ def wait_for_conflicting_dags(def create_data_refresh_dag(data_refresh_config: DataRefreshConfig,- environment: Environment,+ target_environment: Environment,external_dag_ids: Sequence[str],):"""@@ -96,40 +99,40 @@ def create_data_refresh_dag(Required Arguments:- data_refresh: dataclass containing configuration information for the- DAG- environment: the environment in which the data refresh is performed- external_dag_ids: list of ids of the other data refresh DAGs. The data refresh step- of this DAG will not run concurrently with the corresponding step- of any dependent DAG.+ data_refresh: dataclass containing configuration information for the+ DAG+ target_environment: the API environment in which the data refresh is performed+ external_dag_ids: list of ids of the other data refresh DAGs. The data refresh step+ of this DAG will not run concurrently with the corresponding step+ of any dependent DAG."""default_args = {**DAG_DEFAULT_ARGS,**data_refresh_config.default_args,}- concurrency_tag = ES_CONCURRENCY_TAGS.get(environment)+ concurrency_tag = ES_CONCURRENCY_TAGS.get(target_environment)dag = DAG(- dag_id=f"{environment}_{data_refresh_config.dag_id}",+ dag_id=f"{target_environment}_{data_refresh_config.dag_id}",dagrun_timeout=data_refresh_config.dag_timeout,default_args=default_args,start_date=data_refresh_config.start_date,schedule=data_refresh_config.schedule,- render_template_as_native_obj=True,max_active_runs=1,catchup=False,doc_md=__doc__,tags=["data_refresh",- f"{environment}_data_refresh",+ f"{target_environment}_data_refresh",concurrency_tag,],+ render_template_as_native_obj=True,)with dag:# Connect to the appropriate Elasticsearch cluster- es_host = es.get_es_host(environment=environment)+ es_host = es.get_es_host(environment=target_environment)# Get the current number of records in the target API tablebefore_record_count = es.get_record_count_group_by_sources.override(@@ -144,11 +147,19 @@ def create_data_refresh_dag()copy_data = copy_upstream_tables(- environment=environment, data_refresh_config=data_refresh_config+ target_environment=target_environment,+ data_refresh_config=data_refresh_config,)alter_data = alter_table_data(- environment=environment, data_refresh_config=data_refresh_config+ target_environment=target_environment,+ data_refresh_config=data_refresh_config,+ )++ # Create a new temporary index based off the configuration of the existing media index.+ # This will later replace the live index.+ target_index = create_index(+ data_refresh_config=data_refresh_config, es_host=es_host)# Disable Cloudwatch alarms that are noisy during the reindexing steps of a@@ -161,8 +172,13 @@ def create_data_refresh_dag(},)- # TODO create_and_populate_index- # (TaskGroup that creates index, triggers and waits for reindexing)+ # Populate the Elasticsearch index.+ reindex = perform_distributed_reindex(+ environment="{{ var.value.ENVIRONMENT }}",+ target_environment=target_environment,+ target_index=target_index,+ data_refresh_config=data_refresh_config,+ )# TODO create_and_populate_filtered_index@@ -207,10 +223,11 @@ def create_data_refresh_dag(>> wait_for_dags>> copy_data>> alter_data+ >> target_index>> disable_alarms+ >> reindex)- # TODO: this will include reindex/etc once added- disable_alarms >> [enable_alarms, after_record_count]+ reindex >> [enable_alarms, after_record_count]after_record_count >> report_countsreturn dag@@ -219,7 +236,7 @@ def create_data_refresh_dag(# Generate data refresh DAGs for each DATA_REFRESH_CONFIG, per environment.all_data_refresh_dag_ids = {refresh.dag_id for refresh in DATA_REFRESH_CONFIGS.values()}-for data_refresh_config, environment in product(+for data_refresh_config, target_environment in product(DATA_REFRESH_CONFIGS.values(), ENVIRONMENTS):# Construct a set of all data refresh DAG ids other than the current DAG@@ -227,6 +244,6 @@ for data_refresh_config, environment in product(globals()[data_refresh_config.dag_id] = create_data_refresh_dag(data_refresh_config,- environment,- [f"{environment}_{dag_id}" for dag_id in other_dag_ids],+ target_environment,+ [f"{target_environment}_{dag_id}" for dag_id in other_dag_ids],)diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.pyindex 94523c18e..643671389 100644--- a/catalog/dags/data_refresh/data_refresh_types.py+++ b/catalog/dags/data_refresh/data_refresh_types.py@@ -8,6 +8,7 @@ This configuration information is used to generate the dynamic Data Refresh dagsimport osfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta+from typing import Optionalfrom common.constants import AUDIO, IMAGE, REFRESH_POKE_INTERVALfrom data_refresh import queries@@ -48,9 +49,13 @@ class DataRefreshConfig:Required Constructor Arguments:- media_type: str describing the media type to be refreshed.- table_mappings: list of TableMapping information for all tables that should be- refreshed as part of a data refresh for this media type.+ media_type: str describing the media type to be refreshed.+ table_mapping: TableMapping information for the main media table for this+ media type+ additional_table_mappings: list of TableMapping information for any additional tables+ that should be refreshed as part of a data refresh for this+ media type+Optional Constructor Arguments:@@ -65,52 +70,69 @@ class DataRefreshConfig:data refresh may take.copy_data_timeout: timedelta expressing the amount of time it may take tocopy the upstream table into the downstream DB+ indexer_worker_timeout: timedelta expressing the amount of time it may take for+ any individual indexer worker to perform its portion of+ the distributed reindexindex_readiness_timeout: timedelta expressing amount of time it may taketo await a healthy ES index after reindexing- data_refresh_poke_interval: int number of seconds to wait between- checks to see if conflicting DAGs are running.+ concurrency_check_poke_interval: int number of seconds to wait between+ checks to see if conflicting DAGs are running+ reindex_poke_interval: int number of seconds to wait between checks to see if+ the reindexing task has completeddoc_md: str used for the DAG's documentation markdown"""dag_id: str = field(init=False)filtered_index_dag_id: str = field(init=False)media_type: str- table_mappings: list[TableMapping]+ table_mapping: TableMapping+ additional_table_mappings: Optional[list[TableMapping]] = Nonestart_date: datetime = datetime(2020, 1, 1)schedule: str | None = "0 0 * * 1" # Mondays 00:00 UTCdefault_args: dict = field(default_factory=dict)dag_timeout: timedelta = timedelta(days=1)copy_data_timeout: timedelta = timedelta(hours=1)+ indexer_worker_timeout: timedelta = timedelta(hours=12)index_readiness_timeout: timedelta = timedelta(days=1)- data_refresh_poke_interval: int = REFRESH_POKE_INTERVAL+ concurrency_check_poke_interval: int = REFRESH_POKE_INTERVAL+ reindex_poke_interval: int = REFRESH_POKE_INTERVALdef __post_init__(self):self.dag_id = f"{self.media_type}_data_refresh"self.filtered_index_dag_id = f"create_filtered_{self.media_type}_index"+ @property+ def table_mappings(self) -> list[TableMapping]:+ """Return the complete list of all table mappings for this media type."""+ if not self.additional_table_mappings:+ return [self.table_mapping]++ return [self.table_mapping] + self.additional_table_mappings+DATA_REFRESH_CONFIGS = {IMAGE: DataRefreshConfig(media_type=IMAGE,- table_mappings=[- TableMapping(- upstream_table_name=IMAGE,- downstream_table_name=IMAGE,- tertiary_column_query=queries.TIMESTAMP_COLUMN_SETUP_QUERY,- )- ],+ table_mapping=TableMapping(+ upstream_table_name=IMAGE,+ downstream_table_name=IMAGE,+ tertiary_column_query=queries.TIMESTAMP_COLUMN_SETUP_QUERY,+ ),dag_timeout=timedelta(days=4),copy_data_timeout=timedelta(hours=12),- data_refresh_poke_interval=int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60)),+ concurrency_check_poke_interval=int(+ os.getenv("DATA_REFRESH_POKE_INTERVAL", 60)+ ),+ reindex_poke_interval=int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60)),),AUDIO: DataRefreshConfig(media_type=AUDIO,- table_mappings=[- TableMapping(- upstream_table_name=AUDIO,- downstream_table_name=AUDIO,- tertiary_column_query=queries.TIMESTAMP_COLUMN_SETUP_QUERY,- ),+ table_mapping=TableMapping(+ upstream_table_name=AUDIO,+ downstream_table_name=AUDIO,+ tertiary_column_query=queries.TIMESTAMP_COLUMN_SETUP_QUERY,+ ),+ additional_table_mappings=[TableMapping(upstream_table_name="audioset_view",downstream_table_name="audioset",@@ -120,8 +142,9 @@ DATA_REFRESH_CONFIGS = {copy_data_query=queries.BASIC_COPY_DATA_QUERY,),],- data_refresh_poke_interval=int(+ concurrency_check_poke_interval=int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 30)),+ reindex_poke_interval=int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60)),),}diff --git a/catalog/dags/data_refresh/distributed_reindex.py b/catalog/dags/data_refresh/distributed_reindex.pynew file mode 100644index 000000000..1a9b50881--- /dev/null+++ b/catalog/dags/data_refresh/distributed_reindex.py@@ -0,0 +1,397 @@+"""+# Distributed Reindex TaskGroup++This module contains the Airflow tasks used for orchestrating the reindexing of records from the temporary tables in the downstream (API) database, into a new Elasticsearch index. Reindexing is performed on a fleet of indexer worker EC2 instances, with instance creation and termination managed by Airflow.+"""++import functools+import logging+import math+from textwrap import dedent+from urllib.parse import urlparse++from airflow import settings+from airflow.decorators import task, task_group+from airflow.exceptions import AirflowSkipException+from airflow.models.connection import Connection+from airflow.providers.amazon.aws.hooks.ec2 import EC2Hook+from airflow.sensors.base import PokeReturnValue+from airflow.utils.trigger_rule import TriggerRule+from requests import Response++from common.constants import (+ AWS_CONN_ID,+ OPENLEDGER_API_CONN_ID,+ PRODUCTION,+ Environment,+)+from common.operators.http import TemplatedConnectionHttpOperator+from common.sensors.http import TemplatedConnectionHttpSensor+from common.sql import PGExecuteQueryOperator, single_value+from data_refresh.constants import INDEXER_LAUNCH_TEMPLATES, INDEXER_WORKER_COUNTS+from data_refresh.data_refresh_types import DataRefreshConfig+++logger = logging.getLogger(__name__)+++def setup_ec2_hook(func: callable) -> callable:+ """+ Provide an ec2_hook as one of the parameters for the called function.+ If the function is explicitly supplied with an ec2_hook, use that one.+ :return:+ """++ @functools.wraps(func)+ def wrapped(*args, **kwargs):+ ec2_hook = kwargs.pop("ec2_hook", None) or EC2Hook(+ aws_conn_id=AWS_CONN_ID, api_type="client_type"+ )+ return func(*args, **kwargs, ec2_hook=ec2_hook)++ return wrapped+++def response_filter_status_check_endpoint(response: Response) -> str:+ """+ Handle the response from the `trigger_reindex` task.++ This is used to get the status endpoint from the response, which is used to poll for the status+ of the reindexing task.+ """+ status_check_url = response.json()["status_check"]+ return urlparse(status_check_url).path+++def response_check_wait_for_completion(response: Response) -> bool:+ """+ Handle the response for `wait_for_reindex` Sensor.++ Processes the response to determine whether the task can complete.+ """+ data = response.json()++ if data["active"]:+ # The reindex is still running. Poll again later.+ return False++ if data["error"]:+ raise ValueError("An error was encountered during reindexing.")++ logger.info(f"Reindexing done with {data['progress']}% completed.")+ return True+++@task+def get_worker_params(+ estimated_record_count: int,+ environment: str,+ target_environment: Environment,+):+ """Determine the set of start/end indices to be passed to each indexer worker."""+ # Defaults to one indexer worker in local development+ worker_count = (+ INDEXER_WORKER_COUNTS.get(target_environment)+ if environment == PRODUCTION+ else 1+ )+ records_per_worker = math.floor(estimated_record_count / worker_count)++ return [+ {+ "start_id": worker_index * records_per_worker,+ "end_id": (1 + worker_index) * records_per_worker,+ }+ for worker_index in range(worker_count)+ ]+++@task+@setup_ec2_hook+def get_launch_template_version_number(+ environment: str,+ target_environment: Environment,+ ec2_hook: EC2Hook = None,+):+ """+ Get the latest version number of the launch template. Indexer workers will all be created with this+ version. Importantly, this allows us to retry an individual indexer worker and ensure that+ it will run with the same version of the indexer worker as the others, even if code has been+ deployed to the indexer worker in the meantime.+ """+ if environment != PRODUCTION:+ raise AirflowSkipException("Skipping instance creation in local environment.")++ launch_templates = ec2_hook.conn.describe_launch_templates(+ LaunchTemplateNames=INDEXER_LAUNCH_TEMPLATES.get(target_environment)+ )+ return launch_templates.get("LaunchTemplates")[0].get("LatestVersionNumber")+++@task(+ # Prevents the entire reindex TaskGroup from skipping when get_launch_template_version_number+ # was skipped locally+ trigger_rule=TriggerRule.NONE_FAILED+)+@setup_ec2_hook+def create_worker(+ environment: str,+ target_environment: Environment,+ launch_template_version_number: int | str,+ ec2_hook: EC2Hook = None,+):+ """+ Create a new EC2 instance using the launch template for the target+ environment. In local development, this step is skipped.+ """+ if environment != PRODUCTION:+ raise AirflowSkipException("Skipping instance creation in local environment.")++ instances = ec2_hook.conn.run_instances(+ MinCount=1,+ MaxCount=1,+ LaunchTemplate={+ "LaunchTemplateName": INDEXER_LAUNCH_TEMPLATES.get(target_environment),+ "Version": str(launch_template_version_number),+ },+ # Name the instance by applying a tag+ TagSpecifications=[+ {+ "ResourceType": "instance",+ "Tags": [+ {+ "Key": "Name",+ "Value": f"catalog-indexer-worker-{target_environment}",+ },+ ],+ },+ ],+ )["Instances"]++ if not len(instances) == 1:+ raise Exception(+ f"Expected one new instance, but {len(instances)} were created."+ )++ return instances[0]["InstanceId"]++[email protected](poke_interval=60, timeout=3600, mode="reschedule")+@setup_ec2_hook+def wait_for_worker(+ environment: str,+ instance_id: str,+ ec2_hook: EC2Hook = None,+):+ """Await the EC2 instance with the given id to be in a healthy running state."""+ if environment != PRODUCTION:+ raise AirflowSkipException("Skipping instance creation in local environment.")++ result = ec2_hook.conn.describe_instance_status(InstanceIds=[instance_id])++ instance_status = result.get("InstanceStatuses", [])[0]+ state = instance_status.get("InstanceState", {}).get("Name")+ status = next(+ (+ status.get("Status")+ for status in instance_status.get("InstanceStatus", {}).get("Details", [])+ if status.get("Name") == "reachability"+ ),+ None,+ )++ return PokeReturnValue(+ # Sensor completes only when the instance is running and has finished initializing+ is_done=(state == "running" and status == "ok")+ )+++@task(+ # Run locally when create instance tasks are skipped+ trigger_rule=TriggerRule.NONE_FAILED+)+@setup_ec2_hook+def get_instance_ip_address(+ environment: str,+ instance_id: str,+ ec2_hook: EC2Hook = None,+):+ if environment != PRODUCTION:+ return "catalog_indexer_worker"++ reservations = ec2_hook.describe_instances(instance_ids=[instance_id]).get(+ "Reservations"+ )+ return reservations[0].get("Instances", {})[0].get("PrivateIpAddress")+++@task(+ # Instance creation tasks are skipped locally, but we still want this task to run.+ trigger_rule=TriggerRule.NONE_FAILED+)+def create_connection(+ instance_id: str,+ server: str,+):+ """+ Create an Airflow Connection for the given indexer worker and persist it. It will+ later be dropped in a cleanup task.+ """+ worker_conn_id = f"indexer_worker_{instance_id or 'localhost'}"++ # Create the Connection+ logger.info(f"Creating connection with id {worker_conn_id}")+ worker_conn = Connection(conn_id=worker_conn_id, uri=f"http://{server}:8003/")+ session = settings.Session()+ session.add(worker_conn)+ session.commit()++ return worker_conn_id+++@task+@setup_ec2_hook+def terminate_indexer_worker(+ environment: str,+ instance_id: str,+ ec2_hook: EC2Hook = None,+):+ """Terminate an individual indexer worker."""+ if environment != PRODUCTION:+ raise AirflowSkipException(+ "Skipping instance termination in local environment."+ )+ return ec2_hook.conn.terminate_instances(instance_ids=[instance_id])+++@task(trigger_rule=TriggerRule.ALL_DONE)+def drop_connection(worker_conn: str):+ """Drop the Connection to the now terminated instance."""+ conn = Connection.get_connection_from_secrets(worker_conn)++ session = settings.Session()+ session.delete(conn)+ session.commit()+++@task_group(group_id="reindex")+def reindex(+ data_refresh_config: DataRefreshConfig,+ target_index: str,+ launch_template_version_number: int | str,+ start_id: int,+ end_id: int,+ environment: str,+ target_environment: Environment,+):+ """+ Trigger a reindexing task on a remote indexer worker and wait for it to complete. Once done,+ terminate the indexer worker instance.+ """++ # Create a new EC2 instance+ instance_id = create_worker(+ environment=environment,+ target_environment=target_environment,+ launch_template_version_number=launch_template_version_number,+ )++ # Wait for the worker to finish initializing+ await_worker = wait_for_worker.override(+ poke_interval=data_refresh_config.reindex_poke_interval,+ timeout=data_refresh_config.indexer_worker_timeout.total_seconds(),+ )(environment=environment, instance_id=instance_id)++ instance_ip_address = get_instance_ip_address(+ environment=environment, instance_id=instance_id+ )++ worker_conn = create_connection(+ instance_id=instance_id,+ server=instance_ip_address,+ )++ trigger_reindexing_task = TemplatedConnectionHttpOperator(+ task_id="trigger_reindexing_task",+ http_conn_id=worker_conn,+ endpoint="task",+ data={+ "model_name": data_refresh_config.media_type,+ "table_name": data_refresh_config.table_mapping.temp_table_name,+ "target_index": target_index,+ "start_id": start_id,+ "end_id": end_id,+ },+ response_check=lambda response: response.status_code == 202,+ response_filter=response_filter_status_check_endpoint,+ )++ wait_for_reindexing_task = TemplatedConnectionHttpSensor(+ task_id="wait_for_reindexing_task",+ http_conn_id=worker_conn,+ endpoint=trigger_reindexing_task.output,+ method="GET",+ response_check=response_check_wait_for_completion,+ mode="reschedule",+ poke_interval=data_refresh_config.reindex_poke_interval,+ timeout=data_refresh_config.indexer_worker_timeout,+ )++ terminate_instance = terminate_indexer_worker.override(+ # Terminate the instance even if there is an upstream failure+ trigger_rule=TriggerRule.ALL_DONE+ )(+ environment=environment,+ instance_id=instance_id,+ )++ drop_conn = drop_connection(worker_conn=worker_conn)++ instance_id >> [await_worker, instance_ip_address]+ worker_conn >> trigger_reindexing_task >> wait_for_reindexing_task+ wait_for_reindexing_task >> [terminate_instance, drop_conn]+++@task_group(+ group_id="run_distributed_reindex",+)+def perform_distributed_reindex(+ environment: str,+ target_environment: Environment,+ target_index: str,+ data_refresh_config: DataRefreshConfig,+):+ """Perform the distributed reindex on a fleet of remote indexer workers."""+ estimated_record_count = PGExecuteQueryOperator(+ task_id="get_estimated_record_count",+ conn_id=OPENLEDGER_API_CONN_ID,+ sql=dedent(+ f"""+ SELECT max(id) FROM {data_refresh_config.table_mapping.temp_table_name};+ """+ ),+ handler=single_value,+ return_last=True,+ trigger_rule=TriggerRule.NONE_FAILED,+ )++ launch_template_version_number = get_launch_template_version_number(+ environment=environment,+ target_environment=target_environment,+ )++ worker_params = get_worker_params(+ estimated_record_count=estimated_record_count.output,+ environment=environment,+ target_environment=target_environment,+ )++ estimated_record_count >> worker_params++ reindex.partial(+ data_refresh_config=data_refresh_config,+ target_index=target_index,+ launch_template_version_number=launch_template_version_number,+ environment=environment,+ target_environment=target_environment,+ ).expand_kwargs(worker_params)diff --git a/catalog/dags/legacy_data_refresh/data_refresh_task_factory.py b/catalog/dags/legacy_data_refresh/data_refresh_task_factory.pyindex 396e76d65..ad3848a21 100644--- a/catalog/dags/legacy_data_refresh/data_refresh_task_factory.py+++ b/catalog/dags/legacy_data_refresh/data_refresh_task_factory.py@@ -46,7 +46,6 @@ https://github.com/WordPress/openverse-catalog/issues/353)"""import logging-import osfrom collections.abc import Sequencefrom airflow.models.baseoperator import chain@@ -55,7 +54,7 @@ from airflow.utils.task_group import TaskGroupfrom airflow.utils.trigger_rule import TriggerRulefrom common import cloudwatch, ingestion_server-from common.constants import XCOM_PULL_TEMPLATE+from common.constants import DATA_REFRESH_POOL, XCOM_PULL_TEMPLATEfrom common.sensors.constants import PRODUCTION_ES_CONCURRENCY_TAGfrom common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensorfrom common.sensors.utils import wait_for_external_dags_with_tag@@ -68,9 +67,6 @@ from legacy_data_refresh.data_refresh_types import DataRefreshlogger = logging.getLogger(__name__)-DATA_REFRESH_POOL = os.getenv("DATA_REFRESH_POOL", "data_refresh")--def create_data_refresh_task_group(data_refresh: DataRefresh, external_dag_ids: Sequence[str]):diff --git a/indexer_worker/indexer_worker/api.py b/indexer_worker/indexer_worker/api.pyindex 94952d7ed..f55a8d010 100644--- a/indexer_worker/indexer_worker/api.py+++ b/indexer_worker/indexer_worker/api.py@@ -68,8 +68,8 @@ class IndexingJobResource(BaseTaskResource):"model_name": model_name,"table_name": table_name,"target_index": target_index,- "start_id": start_id,- "end_id": end_id,+ "start_id": int(start_id),+ "end_id": int(end_id),# Task tracking arguments"progress": progress,"finish_time": finish_time,