Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Separate go-live step from indexing (#707)
Dhruv Bhanushalif159b4798077
diff --git a/ingestion_server/Pipfile b/ingestion_server/Pipfileindex 2bf71306b..9352f96ec 100644--- a/ingestion_server/Pipfile+++ b/ingestion_server/Pipfile@@ -22,6 +22,7 @@ filelock = "*"pytest = "*"tldextract = "*"python-decouple = "*"+jsonschema = "*"[requires]python_version = "3.10"diff --git a/ingestion_server/Pipfile.lock b/ingestion_server/Pipfile.lockindex ed6abda8d..4692db562 100644--- a/ingestion_server/Pipfile.lock+++ b/ingestion_server/Pipfile.lock@@ -1,7 +1,7 @@{"_meta": {"hash": {- "sha256": "d1fda0e000a854b22ec3613da87b2f981bfe4fdbd92fd840a1d91dbfa58727d6"+ "sha256": "c68989ab7a96278e2696b54ecbba1e2f3bf262df5739a9ac98565f37ee0616c3"},"pipfile-spec": 6,"requires": {@@ -34,19 +34,19 @@},"boto3": {"hashes": [- "sha256:626bbec91ca2423e427636db207a03c854b52d22715c9b34a953ee8260817f6f",- "sha256:7e0a5c86059866d7f9e27d6574da9bfb4f8a03c4caf055724145f3cd44785b81"+ "sha256:021f2a71cbcd75c87724b7dfbf28a691f07899345047f6bc999ef646d97461df",+ "sha256:cb1f1d443672a65e23756cc712d060222e53e68d0700af60b4d904125d9186db"],"index": "pypi",- "version": "==1.24.27"+ "version": "==1.24.32"},"botocore": {"hashes": [- "sha256:524da451350c41e3136353183e7424c95952124163ea8ec03f57f29597bbcb4b",- "sha256:583b85f8a799fb89d1a762db041163b5848b08e79cee06b609bcaaeb69ea1fa6"+ "sha256:10eb15e178f9e1aef679fd1d7dbeba11c851859e09f6c1a2e334287bd8ed3a7e",+ "sha256:d510a1d1956a18b6fa4b74b1b5dfbe8a7ca83f5ca4f59c43c368e143425f3725"],"markers": "python_version >= '3.7'",- "version": "==1.27.27"+ "version": "==1.27.32"},"bottle": {"hashes": [@@ -164,6 +164,14 @@"markers": "python_version >= '3.7'","version": "==1.0.1"},+ "jsonschema": {+ "hashes": [+ "sha256:73764f461d61eb97a057c929368610a134d1d1fffd858acfe88864ee94f1f1d3",+ "sha256:c7448a421b25e424fccfceea86b4e3a8672b4436e1988ccbde92c80828d4f085"+ ],+ "index": "pypi",+ "version": "==4.7.2"+ },"packaging": {"hashes": ["sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb",@@ -213,6 +221,33 @@"markers": "python_full_version >= '3.6.8'","version": "==3.0.9"},+ "pyrsistent": {+ "hashes": [+ "sha256:0e3e1fcc45199df76053026a51cc59ab2ea3fc7c094c6627e93b7b44cdae2c8c",+ "sha256:1b34eedd6812bf4d33814fca1b66005805d3640ce53140ab8bbb1e2651b0d9bc",+ "sha256:4ed6784ceac462a7d6fcb7e9b663e93b9a6fb373b7f43594f9ff68875788e01e",+ "sha256:5d45866ececf4a5fff8742c25722da6d4c9e180daa7b405dc0a2a2790d668c26",+ "sha256:636ce2dc235046ccd3d8c56a7ad54e99d5c1cd0ef07d9ae847306c91d11b5fec",+ "sha256:6455fc599df93d1f60e1c5c4fe471499f08d190d57eca040c0ea182301321286",+ "sha256:6bc66318fb7ee012071b2792024564973ecc80e9522842eb4e17743604b5e045",+ "sha256:7bfe2388663fd18bd8ce7db2c91c7400bf3e1a9e8bd7d63bf7e77d39051b85ec",+ "sha256:7ec335fc998faa4febe75cc5268a9eac0478b3f681602c1f27befaf2a1abe1d8",+ "sha256:914474c9f1d93080338ace89cb2acee74f4f666fb0424896fcfb8d86058bf17c",+ "sha256:b568f35ad53a7b07ed9b1b2bae09eb15cdd671a5ba5d2c66caee40dbf91c68ca",+ "sha256:cdfd2c361b8a8e5d9499b9082b501c452ade8bbf42aef97ea04854f4a3f43b22",+ "sha256:d1b96547410f76078eaf66d282ddca2e4baae8964364abb4f4dcdde855cd123a",+ "sha256:d4d61f8b993a7255ba714df3aca52700f8125289f84f704cf80916517c46eb96",+ "sha256:d7a096646eab884bf8bed965bad63ea327e0d0c38989fc83c5ea7b8a87037bfc",+ "sha256:df46c854f490f81210870e509818b729db4488e1f30f2a1ce1698b2295a878d1",+ "sha256:e24a828f57e0c337c8d8bb9f6b12f09dfdf0273da25fda9e314f0b684b415a07",+ "sha256:e4f3149fd5eb9b285d6bfb54d2e5173f6a116fe19172686797c056672689daf6",+ "sha256:e92a52c166426efbe0d1ec1332ee9119b6d32fc1f0bbfd55d5c1088070e7fc1b",+ "sha256:f87cc2863ef33c709e237d4b5f4502a62a00fab450c9e020892e8e2ede5847f5",+ "sha256:fd8da6d0124efa2f67d86fa70c851022f87c98e205f0594e1fae044e7119a5a6"+ ],+ "markers": "python_version >= '3.7'",+ "version": "==0.18.1"+ },"pytest": {"hashes": ["sha256:13d0e3ccfc2b6e26be000cb6568c832ba67ba32e719443bfe725814d3c42433c",@@ -301,11 +336,11 @@},"setuptools": {"hashes": [- "sha256:16923d366ced322712c71ccb97164d07472abeecd13f3a6c283f6d5d26722793",- "sha256:db3b8e2f922b2a910a29804776c643ea609badb6a32c4bcc226fd4fd902cce65"+ "sha256:0d33c374d41c7863419fc8f6c10bfe25b7b498aa34164d135c622e52580c6b16",+ "sha256:c04b44a57a6265fe34a4a444e965884716d34bae963119a76353434d6f18e450"],"markers": "python_version >= '3.7'",- "version": "==63.1.0"+ "version": "==63.2.0"},"six": {"hashes": [@@ -317,11 +352,11 @@},"tldextract": {"hashes": [- "sha256:5d88321b1b528ebb8f678c72ab023f37caf6381f6af9576b4e60fd266cff178c",- "sha256:adcd24abf21ce3450417cd5a00f23b7e57554ce8ae827334dd12bfcbb6274cf1"+ "sha256:35a0260570e214d8d3cfeeb403992fe9e2b686925f63c9b03c5933408ac2aa5a",+ "sha256:fe15ac3205e5a25b61689369f98cb45c7778a8f2af113d7c11559ece5195f2d6"],"index": "pypi",- "version": "==3.3.0"+ "version": "==3.3.1"},"tomli": {"hashes": [@@ -341,6 +376,14 @@}},"develop": {+ "appnope": {+ "hashes": [+ "sha256:02bd91c4de869fbb1e1c50aafc4098827a7a54ab2f39d9dcba6c9547ed920e24",+ "sha256:265a455292d0bd8a72453494fa24df5a11eb18373a60c7c0430889f22548605e"+ ],+ "markers": "sys_platform == 'darwin'",+ "version": "==0.1.3"+ },"asttokens": {"hashes": ["sha256:0844691e88552595a6f4a4281a9f7f79b8dd45ca4ccea82e5e05b4bbdb76705c",@@ -528,11 +571,11 @@},"setuptools": {"hashes": [- "sha256:16923d366ced322712c71ccb97164d07472abeecd13f3a6c283f6d5d26722793",- "sha256:db3b8e2f922b2a910a29804776c643ea609badb6a32c4bcc226fd4fd902cce65"+ "sha256:0d33c374d41c7863419fc8f6c10bfe25b7b498aa34164d135c622e52580c6b16",+ "sha256:c04b44a57a6265fe34a4a444e965884716d34bae963119a76353434d6f18e450"],"markers": "python_version >= '3.7'",- "version": "==63.1.0"+ "version": "==63.2.0"},"six": {"hashes": [diff --git a/ingestion_server/env.docker b/ingestion_server/env.dockerindex 95b678f8c..4594b2790 100644--- a/ingestion_server/env.docker+++ b/ingestion_server/env.docker@@ -9,3 +9,5 @@ UPSTREAM_DB_PORT="5432"LOCK_PATH="/worker_state/lock"SHELF_PATH="/worker_state/db"++INDEXER_WORKER_HOST="indexer_worker"diff --git a/ingestion_server/env.template b/ingestion_server/env.templateindex 1aa8d9423..b6deca535 100644--- a/ingestion_server/env.template+++ b/ingestion_server/env.template@@ -33,3 +33,5 @@ RELATIVE_UPSTREAM_DB_PORT="5432"#LOCK_PATH="/worker_state/lock"#SHELF_PATH="/worker_state/db"++#INDEXER_WORKER_HOST="localhost"diff --git a/ingestion_server/ingestion_server/api.py b/ingestion_server/ingestion_server/api.pyindex 6fcbf3718..73ef9c53b 100644--- a/ingestion_server/ingestion_server/api.py+++ b/ingestion_server/ingestion_server/api.py@@ -3,7 +3,6 @@ A small RPC API server for scheduling ingestion of upstream data andElasticsearch indexing tasks."""-import jsonimport loggingimport sysimport time@@ -12,12 +11,13 @@ from multiprocessing import Process, Valuefrom urllib.parse import urlparseimport falcon+from falcon.media.validators import jsonschema-import ingestion_server.indexer as indexerfrom ingestion_server import slack-from ingestion_server.constants.media_types import MEDIA_TYPES+from ingestion_server.constants.media_types import MEDIA_TYPES, MediaType+from ingestion_server.indexer import TableIndexer, elasticsearch_connectfrom ingestion_server.state import clear_state, worker_finished-from ingestion_server.tasks import Task, TaskTracker, TaskTypes+from ingestion_server.tasks import TaskTracker, TaskTypes, perform_taskMODEL = "model"@@ -47,140 +47,200 @@ class TaskResource(BaseTaskResource):parsed = urlparse(req.url)return parsed.scheme + "://" + parsed.netloc- @staticmethod- def _validate_create_task(request):+ @jsonschema.validate(+ req_schema={+ "type": "object",+ "properties": {+ "model": {"type": "string", "enum": MEDIA_TYPES},+ "action": {+ "type": "string",+ "enum": list(task_type.name for task_type in TaskTypes),+ },+ # Accepts all forms described in the PostgreSQL documentation:+ # https://www.postgresql.org/docs/current/datatype-datetime.html+ "since_date": {"type": "string"},+ "index_suffix": {"type": "string"},+ "alias": {"type": "string"},+ },+ "required": ["model", "action"],+ "allOf": [+ {+ "if": {+ "properties": {"action": {"const": TaskTypes.POINT_ALIAS.name}}+ },+ "then": {"required": ["index_suffix", "alias"]},+ },+ {+ "if": {"properties": {"action": {"const": TaskTypes.PROMOTE.name}}},+ "then": {"required": ["index_suffix", "alias"]},+ },+ # TODO: delete eventually, rarely used+ {+ "if": {+ "properties": {"action": {"const": TaskTypes.UPDATE_INDEX.name}}+ },+ "then": {"required": ["index_suffix", "since_date"]},+ },+ ],+ }+ )+ def on_post(self, req, res):"""- Validate an index creation task.- :return: None if valid else a string containing an error message.+ Handles an incoming POST request. Schedules the specified task.++ :param req: the incoming request+ :param res: the appropriate response"""- if request == b"":- return "Expected JSON request body but found nothing."- request = json.loads(request.decode("utf-8"))- if MODEL not in request:- return "No model supplied in request body."- if ACTION not in request:- return "No action supplied in request body."- if request[ACTION] not in [x.name for x in TaskTypes]:- return "Invalid action."- if request[ACTION] == TaskTypes.UPDATE_INDEX.name and SINCE_DATE not in request:- return "Received UPDATE request but no since_date."-- return None-- def on_post(self, req, resp):- """Create a task."""- raw_body = req.stream.read()- request_error = self._validate_create_task(raw_body)- if request_error:- logging.warning(f"Invalid request made. Reason: {request_error}")- resp.status = falcon.HTTP_400- resp.media = {"message": request_error}- return- body = json.loads(raw_body.decode("utf-8"))- model = body[MODEL]- action = body[ACTION]- callback_url = None- if CALLBACK_URL in body:- callback_url = body[CALLBACK_URL]- since_date = body[SINCE_DATE] if SINCE_DATE in body else None- task_id = str(uuid.uuid4())- # Inject shared memory++ body = req.get_media()++ # Generated fields+ task_id = uuid.uuid4().hex # no hyphens++ # Required fields++ model: MediaType = body[MODEL]+ action = TaskTypes[body[ACTION]]++ # Optional fields+ callback_url = body.get("callback_url")+ since_date = body.get("since_date")+ index_suffix = body.get("index_suffix", task_id)+ alias = body.get("alias")++ # Shared memoryprogress = Value("d", 0.0)finish_time = Value("d", 0.0)- active_workers = Value(- "i", int(False)- ) # Tracks whether the task has any active distributed workers- task = Task(+ active_workers = Value("i", int(False))++ task = Process(+ target=perform_task,+ kwargs={+ "task_id": task_id,+ "model": model,+ "action": action,+ "callback_url": callback_url,+ "progress": progress,+ "finish_time": finish_time,+ "active_workers": active_workers,+ # Task-specific keyword arguments+ "since_date": since_date,+ "index_suffix": index_suffix,+ "alias": alias,+ },+ )+ task.start()++ self.tracker.add_task(+ task_id,+ task=task,model=model,- task_type=TaskTypes[action],- since_date=since_date,+ action=action,+ callback_url=callback_url,progress=progress,- task_id=task_id,finish_time=finish_time,active_workers=active_workers,- callback_url=callback_url,- )- task.start()- task_id = self.tracker.add_task(- task, task_id, action, progress, finish_time, active_workers)+base_url = self._get_base_url(req)status_url = f"{base_url}/task/{task_id}"+# Give the task a moment to start so we can detect immediate failure.# TODO: Use IPC to detect if the job launched successfully instead# of giving it 100ms to crash. This is prone to race conditions.time.sleep(0.1)if task.is_alive():- resp.status = falcon.HTTP_202- resp.media = {+ res.status = falcon.HTTP_202+ res.media = {"message": "Successfully scheduled task","task_id": task_id,"status_check": status_url,}- return+ elif progress.value == 100:+ res.status = falcon.HTTP_202+ res.media = {+ "message": "Successfully completed task",+ "task_id": task_id,+ "status_check": status_url,+ }else:- resp.status = falcon.HTTP_500- resp.media = {+ res.status = falcon.HTTP_500+ res.media = {"message": "Failed to schedule task due to an internal server ""error. Check scheduler logs."}- return- def on_get(self, req, resp):- """List all indexing tasks."""- resp.media = self.tracker.list_task_statuses()+ def on_get(self, _, res):+ """+ Handles an incoming GET request. Provides information about all past tasks.++ :param _: the incoming request+ :param res: the appropriate response+ """++ res.media = self.tracker.list_task_statuses()class TaskStatus(BaseTaskResource):- def on_get(self, req, resp, task_id):- """Check the status of a single task."""- task = self.tracker.id_task.get(task_id)- if task is None:- resp.status = falcon.HTTP_404- resp.media = {"message": f"No task found with id {task_id}"}- return-- percent_completed = self.tracker.id_progress[task_id].value- active_workers = bool(self.tracker.id_active_workers[task_id].value)- active = task.is_alive() or active_workers-- resp.media = {- "active": active,- "percent_completed": percent_completed,- "error": percent_completed < 100 and not active,- }+ def on_get(self, _, res, task_id):+ """+ Handles an incoming GET request. Provides information about a single task.+ :param _: the incoming request+ :param res: the appropriate response+ :param task_id: the ID of the task for which to get the information+ """++ try:+ result = self.tracker.get_task_status(task_id)+ res.media = result+ except KeyError:+ res.status = falcon.HTTP_404+ res.media = {"message": f"No task found with id {task_id}."}-class WorkerFinishedResource(BaseTaskResource):- """- For notifying ingestion server that an indexing worker has finished its- task.- """+class WorkerFinishedResource(BaseTaskResource):def on_post(self, req, _):+ """+ Handles an incoming POST request. Records messages sent from indexer workers.++ :param req: the incoming request+ :param _: the appropriate response+ """+task_data = worker_finished(str(req.remote_addr), req.media["error"])task_id = task_data.task_idtarget_index = task_data.target_index- active_workers = self.tracker.id_active_workers[task_id]+ task_info = self.tracker.tasks[task_id]+ active_workers = task_info["active_workers"]# Update global task progress based on worker results- self.tracker.id_progress[task_id].value = task_data.percent_successful+ task_info["progress"].value = task_data.percent_successfulif task_data.percent_successful == 100:- logging.info(- "All indexer workers succeeded! Attempting to promote index "- f"{target_index}"- )+ logging.info(f"All indexer workers succeeded! New index: {target_index}")index_type = target_index.split("-")[0]if index_type not in MEDIA_TYPES:index_type = "image"- slack.verbose(- f"`{index_type}`: Elasticsearch reindex complete | "- f"_Next: promote index as primary_"+ slack.verbose(f"`{index_type}`: Elasticsearch reindex complete")++ elasticsearch = elasticsearch_connect()+ indexer = TableIndexer(+ elasticsearch,+ task_id,+ task_info["callback_url"],+ task_info["progress"],+ task_info["active_workers"],+ )+ task = Process(+ target=indexer.refresh,+ kwargs={+ "index_name": target_index,+ "change_settings": True,+ },)- f = indexer.TableIndexer.go_live- p = Process(target=f, args=(target_index, index_type, active_workers))- p.start()+ task.start()+ indexer.ping_callback()elif task_data.percent_completed == 100:# All workers finished, but not all were successful. Mark# workers as complete and do not attempt to go live with the newdiff --git a/ingestion_server/ingestion_server/constants/media_types.py b/ingestion_server/ingestion_server/constants/media_types.pyindex fe1d95205..eb6517bd8 100644--- a/ingestion_server/ingestion_server/constants/media_types.py+++ b/ingestion_server/ingestion_server/constants/media_types.py@@ -2,8 +2,13 @@Also see `api/constants/media_types.py`"""+from typing import Literal, get_args++AUDIO_TYPE = "audio"IMAGE_TYPE = "image"MODEL_3D_TYPE = "model_3d"-MEDIA_TYPES = [AUDIO_TYPE, IMAGE_TYPE, MODEL_3D_TYPE]+MediaType = Literal["audio", "image", "model_3d"]++MEDIA_TYPES: list[MediaType] = list(get_args(MediaType))diff --git a/ingestion_server/ingestion_server/distributed_reindex_scheduler.py b/ingestion_server/ingestion_server/distributed_reindex_scheduler.pyindex be60be4dd..f8ef4a599 100644--- a/ingestion_server/ingestion_server/distributed_reindex_scheduler.py+++ b/ingestion_server/ingestion_server/distributed_reindex_scheduler.py@@ -17,28 +17,23 @@ import boto3import requestsfrom decouple import config-from ingestion_server.constants.media_types import MEDIA_TYPESfrom ingestion_server.state import register_indexing_jobclient = boto3.client("ec2", region_name=config("AWS_REGION", default="us-east-1"))-def schedule_distributed_index(db_conn, target_index, task_id):+def schedule_distributed_index(db_conn, model_name, table_name, target_index, task_id):workers = _prepare_workers()registered = register_indexing_job(workers, target_index, task_id)if registered:- _assign_work(db_conn, workers, target_index)+ _assign_work(db_conn, workers, model_name, table_name, target_index)-def _assign_work(db_conn, workers, target_index):+def _assign_work(db_conn, workers, model_name, table_name, target_index):"""Target index has a form of `<media_type>-<uuid>`"""- table_name = target_index.split("-")[0]- # Defaulting to 'image' for backward compatibility- if not table_name or table_name not in MEDIA_TYPES:- table_name = "image"est_records_query = f"SELECT id FROM {table_name} ORDER BY id DESC LIMIT 1"with db_conn.cursor() as cur:cur.execute(est_records_query)@@ -55,6 +50,8 @@ def _assign_work(db_conn, workers, target_index):for idx, worker in enumerate(workers):worker_url = worker_url_template.format(worker)params = {+ "model_name": model_name,+ "table_name": table_name,"start_id": idx * records_per_worker,"end_id": (1 + idx) * records_per_worker,"target_index": target_index,@@ -72,7 +69,8 @@ def _prepare_workers():"""environment = config("ENVIRONMENT", default="local")if environment == "local":- return [socket.gethostbyname("indexer-worker")]+ indexer_worker_host = config("INDEXER_WORKER_HOST", default="localhost")+ return [socket.gethostbyname(indexer_worker_host)]instance_filters = [{"Name": "tag:Name", "Values": ["indexer-worker-" + environment + "*"]},{"Name": "instance-state-name", "Values": ["stopped", "running"]},diff --git a/ingestion_server/ingestion_server/elasticsearch_models.py b/ingestion_server/ingestion_server/elasticsearch_models.pyindex acd4524a6..11490972c 100644--- a/ingestion_server/ingestion_server/elasticsearch_models.py+++ b/ingestion_server/ingestion_server/elasticsearch_models.py@@ -361,7 +361,7 @@ class Audio(Media):# Table name -> Elasticsearch model-database_table_to_elasticsearch_model = {+media_type_to_elasticsearch_model = {"image": Image,"audio": Audio,}diff --git a/ingestion_server/ingestion_server/indexer.py b/ingestion_server/ingestion_server/indexer.pyindex c8c024d6d..9fedee6cc 100644--- a/ingestion_server/ingestion_server/indexer.py+++ b/ingestion_server/ingestion_server/indexer.py@@ -15,26 +15,27 @@ it will actively monitor Postgres for updates and index them automatically. Thisis useful for local development environments."""-import argparse-import datetimeimport logging as log-import sysimport timeimport uuidfrom collections import deque+from multiprocessing import Value+from typing import Optionalimport elasticsearchimport psycopg2+import requestsfrom aws_requests_auth.aws_auth import AWSRequestsAuthfrom decouple import configfrom elasticsearch import Elasticsearch, NotFoundError, RequestsHttpConnection, helpersfrom elasticsearch.exceptions import ConnectionError as ESConnectionError-from elasticsearch_dsl import Search, connections+from elasticsearch_dsl import connectionsfrom psycopg2.sql import SQL, Identifier, Literal+from requests import RequestExceptionfrom ingestion_server import slackfrom ingestion_server.distributed_reindex_scheduler import schedule_distributed_index-from ingestion_server.elasticsearch_models import database_table_to_elasticsearch_model+from ingestion_server.elasticsearch_models import media_type_to_elasticsearch_modelfrom ingestion_server.es_mapping import index_settingsfrom ingestion_server.qa import create_search_qa_indexfrom ingestion_server.queries import get_existence_queries@@ -69,33 +70,34 @@ REP_TABLES = config(TWELVE_HOURS_SEC = 60 * 60 * 12-def elasticsearch_connect(timeout=300):+def elasticsearch_connect(timeout: int = 300) -> Elasticsearch:"""Repeatedly try to connect to Elasticsearch until successful.- :return: An Elasticsearch connection object.++ :param timeout: the amount of time in seconds to wait for a successful connection+ :return: an Elasticsearch client."""- while True:++ while timeout > 0:try:return _elasticsearch_connect()- except ESConnectionError as e:- log.exception(e)- log.error("Reconnecting to Elasticsearch in 5 seconds. . .")+ except ESConnectionError as err:+ log.exception(err)+ log.error("Reconnecting to Elasticsearch in 5 seconds...")+ timeout -= 5time.sleep(5)continue-def _elasticsearch_connect():+def _elasticsearch_connect() -> Elasticsearch:"""- Connect to configured Elasticsearch domain.+ Connect to an Elasticsearch indices at the configured domain. This method also+ handles AWS authentication using the AWS access key ID and the secret access key.- :param timeout: How long to wait before ANY request to Elasticsearch times- out. Because we use parallel bulk uploads (which sometimes wait long periods- of time before beginning execution), a value of at least 30 seconds is- recommended.- :return: An Elasticsearch connection object.+ :return: an Elasticsearch client"""- log.info("Connecting to %s %s with AWS auth", ELASTICSEARCH_URL, ELASTICSEARCH_PORT)+ log.info(f"Connecting to {ELASTICSEARCH_URL}:{ELASTICSEARCH_PORT} with AWS auth")auth = AWSRequestsAuth(aws_access_key=AWS_ACCESS_KEY_ID,aws_secret_access_key=AWS_SECRET_ACCESS_KEY,@@ -169,64 +171,46 @@ def get_last_item_ids(table):class TableIndexer:def __init__(self,- es_instance,- tables,- task_id=None,- progress=None,- finish_time=None,- active_workers=None,+ es_instance: Elasticsearch,+ task_id: Optional[str] = None,+ callback_url: Optional[str] = None,+ progress: Optional[Value] = None,+ active_workers: Optional[Value] = None,):self.es = es_instanceconnections.connections.add_connection("default", self.es)- self.tables_to_watch = tables- # Optional multiprocessing.Values for examining indexing progress+self.task_id = task_id+ self.callback_url = callback_urlself.progress = progress- self.finish_time = finish_timeself.active_workers = active_workers- def _index_table(self, table, dest_idx=None):+ # Helpers+ # =======++ @staticmethod+ def pg_chunk_to_es(pg_chunk, columns, model_name, dest_index):"""- Check that the database tables are in sync with Elasticsearch. If not,- begin replication.+ Given a list of psycopg2 results, convert them all to Elasticsearch+ documents."""- last_pg_id, _ = get_last_item_ids(table)- if not last_pg_id:- log.warning(f"Tried to sync {table} but it was empty.")- return- # Find the last document inserted into elasticsearch- destination = dest_idx if dest_idx else table- s = Search(using=self.es, index=destination)- s.aggs.bucket("highest_pg_id", "max", field="id")- try:- es_res = s.execute()- last_es_id = int(es_res.aggregations["highest_pg_id"]["value"])- except (TypeError, NotFoundError):- log.info(- "No matching documents found in elasticsearch. "- "Replicating everything."- )- last_es_id = 0- log.info(f"highest_db_id, highest_es_id: {last_pg_id}, {last_es_id}")- # Select all documents in-between and replicate to Elasticsearch.- if last_pg_id > last_es_id:- log.info(f"Replicating range {last_es_id}-{last_pg_id}")-- deleted, mature = get_existence_queries(table)- query = SQL(- "SELECT *, {deleted}, {mature} "- "FROM {table} "- "WHERE id BETWEEN {last_es_id} AND {last_pg_id} "- "AND license_version IS NOT NULL;"- ).format(- deleted=deleted,- mature=mature,- table=Identifier(table),- last_es_id=Literal(last_es_id),- last_pg_id=Literal(last_pg_id),- )- self.es.indices.create(index=dest_idx, body=index_settings(table))- self.replicate(table, dest_idx, query)+ # Map column names to locations in the row tuple+ schema = {col[0]: idx for idx, col in enumerate(columns)}+ model = media_type_to_elasticsearch_model.get(model_name)+ if model is None:+ log.error(f"Table {model_name} is not defined in elasticsearch_models.")+ return []++ documents = []+ for row in pg_chunk:+ if not (row[schema["removed_from_source"]] or row[schema["deleted"]]):+ converted = model.database_row_to_elasticsearch_doc(row, schema)+ converted = converted.to_dict(include_meta=True)+ if dest_index:+ converted["_index"] = dest_index+ documents.append(converted)++ return documentsdef _bulk_upload(self, es_batch):max_attempts = 4@@ -252,16 +236,20 @@ class TableIndexer:continuebreak- def replicate(self, table, dest_index, query):+ # Job components+ # ==============++ def replicate(self, model_name: str, table_name: str, index_name: str, query: str):"""- Replicate records from a given query.+ Copy data from the given PostgreSQL table to the given Elasticsearch index.- :param table: The table to replicate the data from.- :param dest_index: The destination index to copy the data to.- :param query: The SQL query used to select data to copy.- :return:+ :param model_name: the name of the ES models to use to generate the ES docs+ :param table_name: the name of the PostgreSQL table from which to copy data+ :param index_name: the name of the Elasticsearch index to which to upload data+ :param query: the SQL query to use to select rows from the table"""- cursor_name = table + "_indexing_cursor"++ cursor_name = f"{table_name}_indexing_cursor"# Enable writing to Postgres so we can create a server-side cursor.pg_conn = database_connect()total_indexed_so_far = 0@@ -286,8 +274,8 @@ class TableIndexer:es_batch = self.pg_chunk_to_es(pg_chunk=chunk,columns=server_cur.description,- origin_table=table,- dest_index=dest_index,+ model_name=model_name,+ dest_index=index_name,)push_start_time = time.time()num_docs = len(es_batch)@@ -309,135 +297,89 @@ class TableIndexer:self.progress.value = (total_indexed_so_far / num_to_index) * 100log.info(f"Synchronized {num_converted_documents} from "- f"table '{table}' to Elasticsearch"+ f"table '{table_name}' to Elasticsearch")- if self.finish_time is not None:- self.finish_time.value = datetime.datetime.utcnow().timestamp()pg_conn.commit()pg_conn.close()- @staticmethod- def consistency_check(new_index, live_alias):+ def refresh(self, index_name: str, change_settings: bool = False):"""- Indexing can fail for a number of reasons, such as a full disk inside of- the Elasticsearch cluster, network errors that occurred during- synchronization, and numerous other scenarios. This function does some- basic comparison between the new search index and the database. If this- check fails, an alert gets raised and the old index will be left in- place. An operator must then investigate and either manually set the- alias or remediate whatever circumstances interrupted the indexing job- before running the indexing job once more.-- :param new_index: The newly created but not yet live index- :param live_alias: The name of the live index- :return: bool+ Re-enable replicas and refresh the given index.++ :param index_name: the name of the index to replicate and refresh+ :param change_settings: whether to set replication settings"""- es = elasticsearch_connect()- if not es.indices.exists(index=live_alias):- return True- log.info("Refreshing and performing sanity check...")- # Make sure there are roughly as many documents in Elasticsearch- # as there are in our database.- es.indices.refresh(index=new_index)- _id, _ = get_last_item_ids(live_alias)- new_count = Search(using=es, index=new_index).count()- max_delta = 100- delta = abs(_id - new_count)- log.info(f"delta, max_delta: {delta}, {max_delta}")- return delta < max_delta- @staticmethod- def go_live(write_index, live_alias, active_workers=None):+ self.es.indices.refresh(index=index_name)+ if change_settings:+ self.es.indices.put_settings(+ index=index_name,+ body={"index": {"number_of_replicas": 1}},+ )++ def ping_callback(self):"""- Point the live index alias at the index we just created. Delete the- previous one.+ Send a request to the callback URL indicating the completion of the task."""- es = elasticsearch_connect()- indices = set(es.indices.get("*"))- # Re-enable replicas and refresh.- es.indices.refresh(index=write_index)- es.indices.put_settings(- index=write_index, body={"index": {"number_of_replicas": 1}}- )- # Cluster status will always be yellow in development environments- # because there will only be one node available. In production, there- # are many nodes, and the index should not be promoted until all- # shards have been initialized.- environment = config("ENVIRONMENT", default="local")- if environment != "local":- log.info("Waiting for replica shards. . .")- es.cluster.health(index=write_index, wait_for_status="green", timeout="12h")- # If the index exists already and it's not an alias, delete it.- if live_alias in indices:- log.warning("Live index already exists. Deleting and realiasing.")- es.indices.delete(index=live_alias)- # Create or update the alias so it points to the new index.- if es.indices.exists_alias(live_alias):- old = list(es.indices.get(live_alias).keys())[0]- index_update = {- "actions": [- {"remove": {"index": old, "alias": live_alias}},- {"add": {"index": write_index, "alias": live_alias}},- ]- }- es.indices.update_aliases(index_update)- log.info(f"Updated '{live_alias}' index alias to point to {write_index}")- log.info(f"Deleting old index {old}")- es.indices.delete(index=old)- else:- es.indices.put_alias(index=write_index, name=live_alias)- log.info(f"Created '{live_alias}' index alias pointing to {write_index}")- # If there were any active workers for this task, we should mark them complete.- if active_workers:- active_workers.value = int(False)- slack.info(- f"`{write_index}`: ES index promoted - data refresh complete! :tada:"- )- def listen(self, poll_interval=10):+ if not self.callback_url:+ return++ try:+ log.info("Sending callback request")+ res = requests.post(self.callback_url)+ log.info(f"Response: {res.text}")+ except RequestException as err:+ log.error("Failed to send callback!")+ log.error(err)++ # Public API+ # ==========++ def reindex(+ self, model_name: str, table_name: str = None, index_suffix: str = None, **_+ ):"""- Poll the database for changes every poll_interval seconds. If new data- has been added to the database, index it.+ Copy contents of the database to a new Elasticsearch index.- :arg poll_interval: The number of seconds to wait before polling the- database for changes.+ :param model_name: the name of the media type+ :param table_name: the name of the DB table, if different from model name+ :param index_suffix: the unique suffix to add to the index name"""- while True:- log.info("Listening for updates...")- try:- for table in self.tables_to_watch:- self._index_table(table)- except ESConnectionError:- self.es = elasticsearch_connect()- time.sleep(poll_interval)- def reindex(self, model_name: str, distributed=None):+ if not index_suffix:+ index_suffix = uuid.uuid4().hex+ if not table_name:+ table_name = model_name+ destination_index = f"{model_name}-{index_suffix}"++ log.info(+ f"Creating index {destination_index} for model {model_name} "+ f"from table {table_name}."+ )+ self.es.indices.create(+ index=destination_index,+ body=index_settings(model_name),+ )++ log.info("Running distributed index using indexer workers.")+ self.active_workers.value = int(True)+ schedule_distributed_index(+ database_connect(), model_name, table_name, destination_index, self.task_id+ )++ def update_index(self, model_name: str, index_suffix: str, since_date: str, **_):"""- Copy contents of the database to a new Elasticsearch index. Create an- index alias to make the new index the "live" index when finished.+ Update index based on changes in the database after the given date.++ :param model_name: the name of the media type+ :param index_suffix: the unique suffix of the index to update+ :param since_date: the date after which to update the records"""- suffix = uuid.uuid4().hex- destination_index = f"{model_name}-{suffix}"- if distributed is None:- distributed = config("ENVIRONMENT", default="local") != "local"- if distributed:- self.es.indices.create(- index=destination_index, body=index_settings(model_name)- )- self.active_workers.value = int(True)- schedule_distributed_index(- database_connect(), destination_index, self.task_id- )- else:- self._index_table(model_name, dest_idx=destination_index)- slack.verbose(- f"`{model_name}`: Elasticsearch reindex complete | "- f"_Next: promote index as primary_"- )- self.go_live(destination_index, model_name)- def update(self, model_name: str, since_date):- log.info(f"Updating index {model_name} with changes since {since_date}")+ destination_index = f"{model_name}-{index_suffix}"++ log.info(f"Updating index {destination_index} with changes since {since_date}.")deleted, mature = get_existence_queries(model_name)query = SQL("SELECT *, {deleted}, {mature} "@@ -449,69 +391,81 @@ class TableIndexer:model_name=Identifier(model_name),since_date=Literal(since_date),)- self.replicate(model_name, model_name, query)+ self.replicate(model_name, model_name, destination_index, query)+ self.refresh(destination_index)+ self.ping_callback()- @staticmethod- def load_test_data(table):- """Create test indices in Elasticsearch for QA."""- create_search_qa_index(table)+ def load_test_data(self, model_name: str, **_):+ """+ Create test indices in Elasticsearch for QA.- @staticmethod- def pg_chunk_to_es(pg_chunk, columns, origin_table, dest_index):+ :param model_name: the name of the media type"""- Given a list of psycopg2 results, convert them all to Elasticsearch- documents.++ create_search_qa_index(model_name)+ if self.progress is not None:+ self.progress.value = 100 # mark job as completed++ def point_alias(self, model_name: str, index_suffix: str, alias: str, **_):"""- # Map column names to locations in the row tuple- schema = {col[0]: idx for idx, col in enumerate(columns)}- try:- model = database_table_to_elasticsearch_model[origin_table]- except KeyError:- log.error(f"Table {origin_table} is not defined in elasticsearch_models.")- return []+ Map the given index to the given alias.- documents = []- for row in pg_chunk:- if not (row[schema["removed_from_source"]] or row[schema["deleted"]]):- converted = model.database_row_to_elasticsearch_doc(row, schema)- converted = converted.to_dict(include_meta=True)- if dest_index:- converted["_index"] = dest_index- documents.append(converted)+ :param model_name: the name of the media type+ :param index_suffix: the suffix of the index for which to assign the alias+ :param alias: the name of the alias to assign to the index+ """- return documents+ dest_index = f"{model_name}-{index_suffix}"+ environment = config("ENVIRONMENT", default="local")+ if environment != "local":+ # Cluster status will always be yellow in development environments+ # because there will only be one node available. In production, there+ # are many nodes, and the index should not be promoted until all+ # shards have been initialized.+ log.info("Waiting for replica shards. . .")+ self.es.cluster.health(+ index=dest_index,+ wait_for_status="green",+ timeout="12h",+ )-if __name__ == "__main__":- parser = argparse.ArgumentParser()- parser.add_argument(- "--reindex",- default=None,- help="Reindex data from a specific model in the database. Data is "- "copied to a new index and then made 'live' using index aliases,"- " making it possible to reindex without downtime.",- )- parser.add_argument(- "--update",- nargs=2,- default=None,- help="Update the Elasticsearch index with all changes since a UTC date."- "ex: --update image 2018-11-09",- )- parsed = parser.parse_args()- fmt = "%(asctime)s %(message)s"- log.basicConfig(stream=sys.stdout, level=log.INFO, format=fmt)- log.getLogger(TableIndexer.__name__).setLevel(log.INFO)- log.info("Connecting to Elasticsearch")- elasticsearch_client = elasticsearch_connect()- syncer = TableIndexer(elasticsearch_client, REP_TABLES)- if parsed.reindex:- log.info(f"Reindexing {parsed.reindex}")- syncer.reindex(parsed.reindex)- elif parsed.update:- index, date = parsed.update- syncer.update(index, date)- log.info("Update finished.")- else:- log.info("Beginning indexer in daemon mode")- syncer.listen(SYNCER_POLL_INTERVAL)+ try:+ curr_index = list(self.es.indices.get(index=alias).keys())[0]+ if curr_index == alias:+ # Alias is an index, this is fatal.+ message = f"There is an index named {alias}, cannot proceed."+ log.error(message)+ slack.error(message)+ return+ elif curr_index != dest_index:+ # Alias is in use, atomically remap it to the new index.+ self.es.indices.update_aliases(+ body={+ "actions": [+ # unlink alias from the old index+ {"remove": {"index": curr_index, "alias": alias}},+ # link alias to the new index+ {"add": {"index": dest_index, "alias": alias}},+ ]+ }+ )+ message = (+ f"Migrated alias {alias} "+ f"from index {curr_index} to index {dest_index}."+ )+ log.info(message)+ slack.info(message)+ else:+ # Alias is already mapped.+ log.info(f"Alias {alias} already points to index {dest_index}.")+ except NotFoundError:+ # Alias does not exist, create it.+ self.es.indices.put_alias(index=dest_index, name=alias)+ message = f"Created alias {alias} pointing to index {dest_index}."+ log.info(message)+ slack.info(message)++ if self.progress is not None:+ self.progress.value = 100 # mark job as completed+ self.ping_callback()diff --git a/ingestion_server/ingestion_server/indexer_worker.py b/ingestion_server/ingestion_server/indexer_worker.pyindex 8859104c8..2eeadc395 100644--- a/ingestion_server/ingestion_server/indexer_worker.py+++ b/ingestion_server/ingestion_server/indexer_worker.py@@ -17,7 +17,6 @@ from decouple import configfrom psycopg2.sql import SQL, Identifier, Literalfrom ingestion_server import slack-from ingestion_server.constants.media_types import MEDIA_TYPESfrom ingestion_server.indexer import TableIndexer, elasticsearch_connectfrom ingestion_server.queries import get_existence_queries@@ -33,11 +32,15 @@ ec2_client = boto3.client(class IndexingJobResource:def on_post(self, req, resp):j = req.media+ model_name = j["model_name"]+ table_name = j["table_name"]start_id = j["start_id"]end_id = j["end_id"]target_index = j["target_index"]notify_url = f"http://{req.remote_addr}:8001/worker_finished"- _execute_indexing_task(target_index, start_id, end_id, notify_url)+ _execute_indexing_task(+ model_name, table_name, target_index, start_id, end_id, notify_url+ )log.info(f"Received indexing request for records {start_id}-{end_id}")resp.status = falcon.HTTP_201@@ -47,14 +50,12 @@ class HealthcheckResource:resp.status = falcon.HTTP_200-def _execute_indexing_task(target_index, start_id, end_id, notify_url):- # Defaulting to 'image' for backward compatibility- table_name = target_index.split("-")[0]- if table_name not in MEDIA_TYPES:- table_name = "image"+def _execute_indexing_task(+ model_name, table_name, target_index, start_id, end_id, notify_url+):elasticsearch = elasticsearch_connect()- deleted, mature = get_existence_queries(table_name)+ deleted, mature = get_existence_queries(model_name, table_name)query = SQL("SELECT *, {deleted}, {mature} ""FROM {table_name} "@@ -67,19 +68,19 @@ def _execute_indexing_task(target_index, start_id, end_id, notify_url):end_id=Literal(end_id),)log.info(f"Querying {query}")- indexer = TableIndexer(elasticsearch, table_name)+ indexer = TableIndexer(elasticsearch)p = Process(target=_launch_reindex,- args=(table_name, target_index, query, indexer, notify_url),+ args=(model_name, table_name, target_index, query, indexer, notify_url),)p.start()log.info("Started indexing task")-def _launch_reindex(table, target_index, query, indexer, notify_url):+def _launch_reindex(model, table, target_index, query, indexer, notify_url):worker_error = Falsetry:- indexer.replicate(table, target_index, query)+ indexer.replicate(model, table, target_index, query)except Exception as err:exception_type = f"{err.__class__.__module__}.{err.__class__.__name__}"slack.error(diff --git a/ingestion_server/ingestion_server/ingest.py b/ingestion_server/ingestion_server/ingest.pyindex 0483e858a..b2a2ef269 100644--- a/ingestion_server/ingestion_server/ingest.py+++ b/ingestion_server/ingestion_server/ingest.py@@ -15,7 +15,6 @@ table to replace the old data. This strategy is far faster than updating thedata in place."""-import datetimeimport logging as logimport multiprocessing@@ -249,10 +248,9 @@ def _update_progress(progress, new_value):progress.value = new_value-def reload_upstream(+def refresh_api_table(table: str,progress: multiprocessing.Value = None,- finish_time: multiprocessing.Value = None,approach: ApproachType = "advanced",):"""@@ -264,15 +262,11 @@ def reload_upstream(3. Create FDW for the data transfer: ``get_fdw_query``4. Import data into a temporary table: ``get_copy_data_query``5. Clean the data: ``clean_image_data``- 6. Recreate indices from the original table: ``_generate_indices``- 7. Recreate constraints from the original table: ``_generate_constraints``- 8. Promote the temp table and delete the original: ``get_go_live_query``This is the main function of this module.:param table: The upstream table to copy.:param progress: multiprocessing.Value float for sharing task progress- :param finish_time: multiprocessing.Value int for sharing finish timestamp:param approach: whether to use advanced logic specific to media ingestion"""@@ -326,11 +320,11 @@ def reload_upstream(downstream_cur.execute(copy_data)next_step = (- "starting data cleaning"+ "_Next: {starting data cleaning}_"if table == "image"- else "re-applying indices & constraints"+ else "Finished refreshing table")- slack.verbose(f"`{table}`: Data copy complete | _Next: {next_step}_")+ slack.verbose(f"`{table}`: Data copy complete | {next_step}")if table == "image":# Step 5: Clean the data@@ -338,14 +332,35 @@ def reload_upstream(clean_image_data(table)log.info("Cleaning completed!")slack.verbose(- f"`{table}`: Data cleaning complete | "- f"_Next: re-applying indices & constraints_"+ f"`{table}`: Data cleaning complete | " f"Finished refreshing table")- log.info("Starting post-cleaning work...")+ downstream_db.close()+ log.info(f"Finished refreshing table '{table}'.")+ _update_progress(progress, 100.0)+++def promote_api_table(+ table: str,+ progress: multiprocessing.Value = None,+):+ """+ This runs after ``refresh_api_table``. The process involves the following steps.++ 6. Recreate indices from the original table: ``_generate_indices``+ 7. Recreate constraints from the original table: ``_generate_constraints``+ 8. Promote the temp table and delete the original: ``get_go_live_query``++ :param table: the upstream table to copy+ :param progress: multiprocessing.Value float for sharing task progress+ """++ log.info(f"`{table}`: Starting table promotion | _Next: recreate-indices_")+ downstream_db = database_connect()+with downstream_db, downstream_db.cursor() as downstream_cur:# Step 6: Recreate indices from the original table- log.info("Copying finished! Recreating database indices...")+ log.info("Recreating database indices...")create_indices, index_mapping = _generate_indices(downstream_db, table)_update_progress(progress, 50.0)if create_indices != "":@@ -363,17 +378,19 @@ def reload_upstream(downstream_cur.execute(remap_constraint)log.info("Done remapping constraints! Going live with new table...")_update_progress(progress, 99.0)- slack.verbose(f"`{table}`: Indices & constraints applied | _Next: go-live_")+ slack.verbose(+ f"`{table}`: Indices & constraints applied, finished refreshing table | "+ f"_Next: Elasticsearch reindex_"+ )# Step 8: Promote the temporary table and delete the originalgo_live = get_go_live_query(table, index_mapping)log.info(f"Running go-live: \n{go_live.as_string(downstream_cur)}")downstream_cur.execute(go_live)+ slack.verbose(+ f"`{table}`: Finished table promotion | " f"_Next: Elasticsearch promotion_"+ )downstream_db.close()- log.info(f"Finished refreshing table '{table}'.")+ log.info(f"Finished promoting table {table}")_update_progress(progress, 100.0)- slack.verbose(f"`{table}`: Finished table refresh | _Next: Elasticsearch reindex_")-- if finish_time:- finish_time.value = datetime.datetime.utcnow().timestamp()diff --git a/ingestion_server/ingestion_server/queries.py b/ingestion_server/ingestion_server/queries.pyindex ec70cfbad..eb9f65a5c 100644--- a/ingestion_server/ingestion_server/queries.py+++ b/ingestion_server/ingestion_server/queries.py@@ -7,26 +7,30 @@ from psycopg2.sql import Literal as PgLiteralfrom ingestion_server.constants.internal_types import ApproachType-def get_existence_queries(table):+def get_existence_queries(model: str, table: str = None) -> tuple[SQL, SQL]:"""Get the query for checking whether an identifier exists in the deleted orthe mature tables for the media. The media tables are assumed to be namedwith the prefixes "api_deleted" and "api_mature" respectively.+ :param model: the name to use for the deleted and mature tables:param table: the name of the media table to check entries in:return: the queries to check if for presence in the deleted/mature table"""+ if not table:+ table = model # By default, tables are named after the model.+exists_in_table = ("EXISTS(SELECT 1 FROM {table} " "WHERE identifier = {identifier}) AS {name}")exists_in_deleted_table = SQL(exists_in_table).format(- table=Identifier(f"api_deleted{table}"),+ table=Identifier(f"api_deleted{model}"),identifier=Identifier(table, "identifier"),name=Identifier("deleted"),)exists_in_mature_table = SQL(exists_in_table).format(- table=Identifier(f"api_mature{table}"),+ table=Identifier(f"api_mature{model}"),identifier=Identifier(table, "identifier"),name=Identifier("mature"),)diff --git a/ingestion_server/ingestion_server/tasks.py b/ingestion_server/ingestion_server/tasks.pyindex 8dd75049f..9e5f6b210 100644--- a/ingestion_server/ingestion_server/tasks.py+++ b/ingestion_server/ingestion_server/tasks.py@@ -2,155 +2,212 @@Simple in-memory tracking of executed tasks."""-import datetime as dt+import datetimeimport logging-from enum import Enum-from multiprocessing import Process--import requests+from enum import Enum, auto+from multiprocessing import Value+from typing import Optionalfrom ingestion_server import slack+from ingestion_server.constants.media_types import MediaTypefrom ingestion_server.indexer import TableIndexer, elasticsearch_connect-from ingestion_server.ingest import reload_upstream+from ingestion_server.ingest import promote_api_table, refresh_api_tableclass TaskTypes(Enum):- # Completely reindex all data for a given model.- REINDEX = 0- # Reindex updates to a model from the database since a certain date.- UPDATE_INDEX = 1- # Download the latest copy of the data from the upstream database, then- # completely reindex the newly imported data.- INGEST_UPSTREAM = 2- # Create indices in Elasticsearch for QA tests.- # This is not intended for production use, but can be safely executed in a- # production environment without consequence.- LOAD_TEST_DATA = 3+ @staticmethod+ def _generate_next_value_(name: str, *args, **kwargs) -> str:+ """+ Generates the value for ``auto()`` given the name of the enum item. Therefore,+ this function must be defined before any of the enum items.++ :param name: the enum variable name+ :return: the enum value+ """++ return name.lower()++ # Major index update++ REINDEX = auto()+ """create a new index for a given model in Elasticsearch"""++ POINT_ALIAS = auto()+ """map a given index to a given alias, used when going live with an index"""++ # Periodic data refresh++ INGEST_UPSTREAM = auto() # includes `REINDEX`+ """refresh the API tables from the upstream database, then ``REINDEX``"""++ PROMOTE = auto() # includes `POINT_ALIAS`+ """promote the refreshed table, then ``POINT_ALIAS``"""++ # Other++ UPDATE_INDEX = auto() # TODO: delete eventually, rarely used+ """reindex updates to a model from the database since the given date"""++ LOAD_TEST_DATA = auto()+ """create indices in ES for QA tests; this is not intended to run in production but+ can be run without negative consequences"""++ def __str__(self):+ """+ Get the string representation of this enum. Unlike other objects, this+ does not default to ``__repr__``.++ :return: the string representation+ """++ return self.nameclass TaskTracker:def __init__(self):- self.id_task = {}- self.id_action = {}- self.id_progress = {}- self.id_start_time = {}- self.id_finish_time = {}- self.id_active_workers = {}-- def add_task(self, task, task_id, action, progress, finish_time, active_workers):- self._prune_old_tasks()- self.id_task[task_id] = task- self.id_action[task_id] = action- self.id_progress[task_id] = progress- self.id_start_time[task_id] = dt.datetime.utcnow().timestamp()- self.id_finish_time[task_id] = finish_time- self.id_active_workers[task_id] = active_workers- return task_id+ self.tasks = {}def _prune_old_tasks(self):+ # TODO: Populate, document or delete function stubpass- def list_task_statuses(self):+ def add_task(self, task_id: str, **kwargs):+ """+ Store information about a new task in memory.+ :param task: the task being performed+ :param task_id: the UUID of the task+ """+self._prune_old_tasks()- results = []- for _id, task in self.id_task.items():- percent_completed = self.id_progress[_id].value- active = task.is_alive()- start_time = self.id_start_time[_id]- finish_time = self.id_finish_time[_id].value- active_workers = self.id_active_workers[_id].value- results.append(- {- "task_id": _id,- "active": active,- "action": self.id_action[_id],- "progress": percent_completed,- "error": percent_completed < 100 and not active,- "start_time": start_time,- "finish_time": finish_time,- "active_workers": bool(active_workers),- }- )- sorted_results = sorted(results, key=lambda x: x["finish_time"])-- to_utc = dt.datetime.utcfromtimestamp-- def render_date(x):- return to_utc(x) if x != 0.0 else None-- # Convert date to a readable format- for idx, task in enumerate(sorted_results):- start_time = task["start_time"]- finish_time = task["finish_time"]- sorted_results[idx]["start_time"] = str(render_date(start_time))- sorted_results[idx]["finish_time"] = str(render_date(finish_time))-- return sorted_results---class Task(Process):- def __init__(- self,- model,- task_type,- since_date,- progress,++ self.tasks[task_id] = {+ "start_time": datetime.datetime.utcnow().timestamp(),+ } | kwargs++ @staticmethod+ def serialize_task_info(task_info: dict) -> dict:+ """+ Generate a response dictionary containing all relevant information about a task.+ :param task_info: the stored information about the task+ :return: the details of the task to show to the user+ """++ def _time_fmt(timestamp: int) -> Optional[str]:+ """+ Format the timestamp into a human-readable date and time notation.+ :param timestamp: the timestamp to format+ :return: the human-readable form of the timestamp+ """++ if timestamp == 0:+ return None+ return str(datetime.datetime.utcfromtimestamp(timestamp))++ active = task_info["task"].is_alive()+ start_time = task_info["start_time"]+ finish_time = task_info["finish_time"].value+ progress = task_info["progress"].value+ active_workers = task_info["active_workers"].value+ return {+ "active": active,+ "model": task_info["model"],+ "action": str(task_info["action"]),+ "progress": progress,+ "start_timestamp": start_time,+ "start_time": _time_fmt(start_time),+ "finish_timestamp": finish_time,+ "finish_time": _time_fmt(finish_time),+ "active_workers": bool(active_workers),+ "error": progress < 100 and not active,+ }++ def list_task_statuses(self) -> list:+ """+ Get the statuses of all tasks.+ :return: the statuses of all tasks+ """++ results = [self.get_task_status(task_id) for task_id in self.tasks.keys()]+ results.sort(key=lambda task: task["finish_timestamp"])+ return results++ def get_task_status(self, task_id) -> dict:+ """+ Get the status of a single task with the given task ID.+ :param task_id: the ID of the task to get the status for+ :return: the status of the task+ """++ self._prune_old_tasks()++ task_info = self.tasks[task_id]+ return {"task_id": task_id} | self.serialize_task_info(task_info)+++def perform_task(+ task_id: str,+ model: MediaType,+ action: TaskTypes,+ callback_url: Optional[str],+ progress: Value,+ finish_time: Value,+ active_workers: Value,+ **kwargs,+):+ """+ Perform the task defined by the API request by invoking the task function with the+ correct arguments. Any additional keyword arguments will be forwarded to the+ appropriate task functions.++ :param task_id: the UUID assigned to the task for tracking+ :param model: the media type for which the action is being performed+ :param action: the name of the action being performed+ :param callback_url: the URL to which to make a request after the task is completed+ :param progress: shared memory for tracking the task's progress+ :param finish_time: shared memory for tracking the finish time of the task+ :param active_workers: shared memory for counting workers assigned to the task+ """++ elasticsearch = elasticsearch_connect()+ indexer = TableIndexer(+ elasticsearch,task_id,- finish_time,- active_workers,callback_url,- ):- Process.__init__(self)- self.model = model- self.task_type = task_type- self.since_date = since_date- self.progress = progress- self.task_id = task_id- self.finish_time = finish_time- self.active_workers = active_workers- self.callback_url = callback_url-- def run(self):- try:- # Map task types to actions.- elasticsearch = elasticsearch_connect()- indexer = TableIndexer(- elasticsearch,- self.model,- self.task_id,- self.progress,- self.finish_time,- self.active_workers,- )- if self.task_type == TaskTypes.REINDEX:- slack.verbose(f"`{self.model}`: Beginning Elasticsearch reindex")- indexer.reindex(self.model)- elif self.task_type == TaskTypes.UPDATE_INDEX:- indexer.update(self.model, self.since_date)- elif self.task_type == TaskTypes.INGEST_UPSTREAM:- reload_upstream(self.model)- if self.model == "audio":- reload_upstream("audioset", approach="basic")- indexer.reindex(self.model)- elif self.task_type == TaskTypes.LOAD_TEST_DATA:- indexer.load_test_data(self.model)- logging.info(f"Task {self.task_id} exited.")- if self.callback_url:- try:- logging.info("Sending callback request")- res = requests.post(self.callback_url)- logging.info(f"Response: {res.text}")- except requests.exceptions.RequestException as e:- logging.error("Failed to send callback!")- logging.error(e)- except Exception as err:- exception_type = f"{err.__class__.__module__}.{err.__class__.__name__}"- logging.error(- f"Error processing task `{self.task_type}` for `{self.model}`: {err}"- )- slack.error(- f":x_red: Error processing task `{self.task_type}` for `{self.model}` "- f"(`{exception_type}`): \n"- f"```\n{err}\n```"- )- raise+ progress,+ active_workers,+ )++ # Task functions+ # ==============+ # These functions must have a signature of ``Callable[[], None]``.++ def ingest_upstream(): # includes ``reindex``+ refresh_api_table(model, progress)+ if model == "audio":+ refresh_api_table("audioset", progress, approach="basic")+ indexer.reindex(model, f"temp_import_{model}", **kwargs)++ def promote(): # includes point alias+ promote_api_table(model, progress)+ if model == "audio":+ promote_api_table("audioset", progress)+ indexer.point_alias(model, **kwargs)++ try:+ locs = locals() # contains all the task functions defined above+ if func := locs.get(action.value):+ func() # Run the task function if it is defined+ elif func := getattr(indexer, action.value):+ func(model, **kwargs) # Directly invoke indexer methods if no task function+ except Exception as err:+ exception_type = f"{err.__class__.__module__}.{err.__class__.__name__}"+ logging.error(f"Error processing task `{action}` for `{model}`: {err}")+ slack.error(+ f":x_red: Error processing task `{action}` for `{model}` "+ f"(`{exception_type}`): \n"+ f"```\n{err}\n```"+ )+ raise++ finish_time.value = datetime.datetime.utcnow().timestamp()+ logging.info(f"Task {task_id} completed.")diff --git a/ingestion_server/test/env.integration b/ingestion_server/test/env.integrationindex e88a2d5d2..1b2459438 100644--- a/ingestion_server/test/env.integration+++ b/ingestion_server/test/env.integration@@ -13,3 +13,5 @@ RELATIVE_UPSTREAM_DB_PORT="5432"LOCK_PATH="/worker_state/lock"SHELF_PATH="/worker_state/db"SLACK_WEBHOOK=""++INDEXER_WORKER_HOST="integration_indexer_worker"diff --git a/ingestion_server/test/gen_integration_compose.py b/ingestion_server/test/gen_integration_compose.pyindex 0825ecbf5..dbee263b9 100644--- a/ingestion_server/test/gen_integration_compose.py+++ b/ingestion_server/test/gen_integration_compose.py@@ -32,7 +32,7 @@ def _prune_services(conf: dict)::param conf: the Docker Compose configuration"""- services_to_keep = {"es", "ingestion_server", "db", "upstream_db"}+ services_to_keep = {"es", "ingestion_server", "indexer_worker", "db", "upstream_db"}for service_name in dict(conf["services"]):if service_name not in services_to_keep:del conf["services"][service_name]@@ -64,7 +64,8 @@ def _fixup_env(conf: dict):env_files = conf["services"][service]["env_file"]env_files = [str(src_dc_path.parent.joinpath(path)) for path in env_files]conf["services"][service]["env_file"] = env_files- conf["services"]["ingestion_server"]["env_file"] = ["env.integration"]+ for service in {"ingestion_server", "indexer_worker"}:+ conf["services"][service]["env_file"] = ["env.integration"]def _remove_volumes(conf: dict):@@ -94,8 +95,9 @@ def _change_directories(conf: dict)::param conf: the Docker Compose configuration"""- conf["services"]["ingestion_server"]["volumes"] = ["../:/ingestion_server"]- conf["services"]["ingestion_server"]["build"] = "../"+ for service in {"ingestion_server", "indexer_worker"}:+ conf["services"][service]["volumes"] = ["../:/ingestion_server"]+ conf["services"][service]["build"] = "../"conf["services"]["upstream_db"]["volumes"] = ["./mock_data:/mock_data"]@@ -111,10 +113,11 @@ def _rename_services(conf: dict):conf["services"][f"integration_{service_name}"] = servicedel conf["services"][service_name]- conf["services"]["integration_ingestion_server"]["depends_on"] = [- "integration_db",- "integration_es",- ]+ for service in {"ingestion_server", "indexer_worker"}:+ conf["services"][f"integration_{service}"]["depends_on"] = [+ "integration_db",+ "integration_es",+ ]def gen_integration_compose():diff --git a/ingestion_server/test/integration_test.py b/ingestion_server/test/integration_test.pyindex 6ab996c06..d318fe8aa 100644--- a/ingestion_server/test/integration_test.py+++ b/ingestion_server/test/integration_test.py@@ -213,7 +213,7 @@ class TestIngestion(unittest.TestCase):cursor.execute(constraint_sql)return {constraint: name for name, constraint in cursor}- def _ingest_upstream(self, model):+ def _ingest_upstream(self, model, suffix="integration"):"""Check that INGEST_UPSTREAM task completes successfully and respondswith a callback.@@ -223,6 +223,7 @@ class TestIngestion(unittest.TestCase):req = {"model": model,"action": "INGEST_UPSTREAM",+ "index_suffix": suffix,"callback_url": bottle_url,}res = requests.post(f"{ingestion_server}/task", json=req)@@ -242,6 +243,30 @@ class TestIngestion(unittest.TestCase):before_constraints == after_constraints), "Constraints in DB don't match the names they had before the go-live"+ def _promote(self, model, suffix="integration", alias=None):+ """+ Check that PROMOTE task completes successfully and configures alias mapping+ in Elasticsearch.+ """+ if alias is None:+ alias = model+ req = {+ "model": model,+ "action": "PROMOTE",+ "index_suffix": suffix,+ "alias": alias,+ "callback_url": bottle_url,+ }+ res = requests.post(f"{ingestion_server}/task", json=req)+ stat_msg = "The job should launch successfully and return 202 ACCEPTED."+ self.assertEqual(res.status_code, 202, msg=stat_msg)++ # Wait for the task to send us a callback.+ assert self.__class__.cb_queue.get(timeout=120) == "CALLBACK!"++ es = self._get_es()+ assert list(es.indices.get(index=alias).keys())[0] == f"{model}-{suffix}"+@classmethoddef setUpClass(cls) -> None:# Launch a Bottle server to receive and handle callbacks@@ -325,7 +350,7 @@ class TestIngestion(unittest.TestCase):@pytest.mark.order(2)def test_image_ingestion_succeeds(self):- self._ingest_upstream("image")+ self._ingest_upstream("image", "integration")@pytest.mark.order(3)def test_task_count_after_one(self):@@ -336,7 +361,7 @@ class TestIngestion(unittest.TestCase):@pytest.mark.order(4)def test_audio_ingestion_succeeds(self):- self._ingest_upstream("audio")+ self._ingest_upstream("audio", "integration")@pytest.mark.order(5)def test_task_count_after_two(self):@@ -358,6 +383,14 @@ class TestIngestion(unittest.TestCase):)@pytest.mark.order(6)+ def test_promote_images(self):+ self._promote("image", "integration", "image-main")++ @pytest.mark.order(7)+ def test_promote_audio(self):+ self._promote("audio", "integration", "audio-main")++ @pytest.mark.order(8)def test_upstream_indexed_images(self):"""Check that the image data has been successfully indexed in@@ -366,13 +399,12 @@ class TestIngestion(unittest.TestCase):"""es = self._get_es()- es_query = {"query": {"match_all": {}}}- es.indices.refresh(index="image")- search_response = es.search(index="image", body=es_query)+ es.indices.refresh(index="image-integration")+ count = es.count(index="image-integration")["count"]msg = "There should be 5000 images in Elasticsearch after ingestion."- self.assertEquals(search_response["hits"]["total"]["value"], 5000, msg)+ self.assertEquals(count, 5000, msg)- @pytest.mark.order(7)+ @pytest.mark.order(9)def test_upstream_indexed_audio(self):"""Check that the audio data has been successfully indexed in@@ -381,13 +413,12 @@ class TestIngestion(unittest.TestCase):"""es = self._get_es()- es_query = {"query": {"match_all": {}}}- es.indices.refresh(index="audio")- search_response = es.search(index="audio", body=es_query)+ es.indices.refresh(index="audio-integration")+ count = es.count(index="audio-integration")["count"]msg = "There should be 5000 audio tracks in Elasticsearch after ingestion."- self.assertEquals(search_response["hits"]["total"]["value"], 5000, msg)+ self.assertEquals(count, 5000, msg)- @pytest.mark.order(8)+ @pytest.mark.order(10)def test_update_index_images(self):"""Check that the image data can be updated from the API database into@@ -397,6 +428,7 @@ class TestIngestion(unittest.TestCase):"model": "image","action": "UPDATE_INDEX","since_date": "1999-01-01",+ "index_suffix": "integration","callback_url": bottle_url,}res = requests.post(f"{ingestion_server}/task", json=req)@@ -406,7 +438,7 @@ class TestIngestion(unittest.TestCase):# Wait for the task to send us a callback.assert self.__class__.cb_queue.get(timeout=120) == "CALLBACK!"- @pytest.mark.order(9)+ @pytest.mark.order(11)def test_update_index_audio(self):"""Check that the audio data can be updated from the API database into@@ -416,6 +448,7 @@ class TestIngestion(unittest.TestCase):"model": "audio","action": "UPDATE_INDEX","since_date": "1999-01-01",+ "index_suffix": "integration","callback_url": bottle_url,}res = requests.post(f"{ingestion_server}/task", json=req)diff --git a/ingestion_server/test/test_constants.py b/ingestion_server/test/test_constants.pyindex fad5615a1..d1cc41b50 100644--- a/ingestion_server/test/test_constants.py+++ b/ingestion_server/test/test_constants.py@@ -5,4 +5,5 @@ service_ports = {"db": 65432, # from 5432"es": 60200, # from 9200"ingestion_server": 60001, # from 8001+ "indexer_worker": 60002, # from 8002}diff --git a/justfile b/justfileindex 24d31b26a..507d995e8 100644--- a/justfile+++ b/justfile@@ -114,7 +114,7 @@ cert:# Check if the media is indexed in Elasticsearch@check-index index="image":- -curl -sb -H "Accept:application/json" "http://localhost:9200/_cat/aliases/{{ index }}" | grep -c "{{ index }}-"+ -curl -sb -H "Accept:application/json" "http://localhost:9200/_cat/indices/{{ index }}" | grep -o "{{ index }}" | wc -l | xargs# Wait for the media to be indexed in Elasticsearch@wait-for-index index="image":@@ -132,11 +132,11 @@ _ing-install:cd ingestion_server && pipenv install --dev# Perform the given action on the given model by invoking the ingestion-server API-_ing-api model action port="8001":+_ing-api data port="8001":curl \-X POST \-H 'Content-Type: application/json' \- -d '{"model": "{{ model }}", "action": "{{ action }}"}' \+ -d '{{ data }}' \'http://localhost:{{ port }}/task'# Check the health of the ingestion-server@@ -151,11 +151,15 @@ _ing-api model action port="8001":# Load QA data into QA indices in Elasticsearch@load-test-data model="image":- just _ing-api {{ model }} "LOAD_TEST_DATA"+ just _ing-api '{"model": "{{ model }}", "action": "LOAD_TEST_DATA"}'-# Load sample data into prod indices in Elasticsearch-@ingest-upstream model="image":- just _ing-api {{ model }} "INGEST_UPSTREAM"+# Load sample data into temp table in API and new index in Elasticsearch+@ingest-upstream model="image" suffix="init":+ just _ing-api '{"model": "{{ model }}", "action": "INGEST_UPSTREAM", "index_suffix": "{{ suffix }}"}'++# Promote temp table to prod in API and new index to primary in Elasticsearch+@promote model="image" suffix="init" alias="image":+ just _ing-api '{"model": "{{ model }}", "action": "PROMOTE", "index_suffix": "{{ suffix }}", "alias": "{{ alias }}"}'# Run ingestion-server tests locallying-testlocal *args:diff --git a/load_sample_data.sh b/load_sample_data.shindex 412197b19..f7eb5ea8b 100755--- a/load_sample_data.sh+++ b/load_sample_data.sh@@ -103,10 +103,14 @@ just load-test-data "image"sleep 2# Ingest and index the data-just ingest-upstream "audio"+just ingest-upstream "audio" "init"+just wait-for-index "audio-init"+just promote "audio" "init" "audio"just wait-for-index "audio"-just ingest-upstream "image"+just ingest-upstream "image" "init"+just wait-for-index "image-init"+just promote "image" "init" "image"just wait-for-index "image"# Clear source cache since it's out of date after data has been loaded