Skip to content

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

Add `create_and_populate_filtered_index` action to ingestion server (#1202)

sarayourfriend7427bbd4a817
diff --git a/docker/es/justfile b/docker/es/justfile
index 156fab591..be9cfa42d 100644
--- a/docker/es/justfile
+++ b/docker/es/justfile
@@ -26,19 +26,19 @@ NO_COLOR := "\\033[0m"
'"$(just docker/es/health {{ host }})" != "200"' \
"Waiting for Elasticsearch to be healthy..."
-@check-index index="image":
+@check-index index="image" dest="":
-curl \
-s \
-H 'Accept: application/json' \
'http://localhost:50292/_cat/indices/{{ index }}' \
- | grep -o "{{ index }}" \
+ | grep -o "{{ (if dest == "" { index } else { dest }) }}" \
| wc -l \
| xargs
# Wait for the media to be indexed in Elasticsearch
-@wait-for-index index="image":
+@wait-for-index index="image" dest="":
# The just command on the second line is executed in the context of the
# root directory and so must be prefixed with `docker/es/`.
just ../../_loop \
- '"$(just docker/es/check-index {{ index }})" != "1"' \
+ '"$(just docker/es/check-index {{ index }} {{ dest }})" != "1"' \
"Waiting for index '{{ index }}' to be ready..."
diff --git a/ingestion_server/ingestion_server/api.py b/ingestion_server/ingestion_server/api.py
index 1647bdfd3..3103e0853 100644
--- a/ingestion_server/ingestion_server/api.py
+++ b/ingestion_server/ingestion_server/api.py
@@ -6,6 +6,7 @@ import sys
import time
import uuid
from multiprocessing import Process, Value
+from pathlib import Path
from urllib.parse import urlparse
import falcon
@@ -146,6 +147,8 @@ class TaskResource(BaseTaskResource):
callback_url = body.get("callback_url")
since_date = body.get("since_date")
index_suffix = body.get("index_suffix", task_id)
+ origin_index_suffix = body.get("origin_index_suffix")
+ destination_index_suffix = body.get("destination_index_suffix")
alias = body.get("alias")
force_delete = body.get("force_delete", False)
@@ -169,6 +172,8 @@ class TaskResource(BaseTaskResource):
# Task-specific keyword arguments
"since_date": since_date,
"index_suffix": index_suffix,
+ "origin_index_suffix": origin_index_suffix,
+ "destination_index_suffix": destination_index_suffix,
"alias": alias,
"force_delete": force_delete,
},
@@ -338,6 +343,7 @@ def create_api(log=True):
_api.add_route("/task/{task_id}", TaskStatus(task_tracker))
_api.add_route("/worker_finished", WorkerFinishedResource(task_tracker))
_api.add_route("/state", StateResource())
+ _api.add_static_route("/static", (Path(".") / "static").absolute())
return _api
diff --git a/ingestion_server/ingestion_server/indexer.py b/ingestion_server/ingestion_server/indexer.py
index 5b578fc26..3833a74a2 100644
--- a/ingestion_server/ingestion_server/indexer.py
+++ b/ingestion_server/ingestion_server/indexer.py
@@ -38,6 +38,7 @@ from ingestion_server.es_helpers import get_stat
from ingestion_server.es_mapping import index_settings
from ingestion_server.qa import create_search_qa_index
from ingestion_server.queries import get_existence_queries
+from ingestion_server.utils.sensitive_terms import get_sensitive_terms
DATABASE_HOST = config("DATABASE_HOST", default="localhost")
@@ -479,3 +480,57 @@ class TableIndexer:
if self.progress is not None:
self.progress.value = 100
self.ping_callback()
+
+ def create_and_populate_filtered_index(
+ self,
+ model_name: str,
+ origin_index_suffix: str | None = None,
+ destination_index_suffix: str | None = None,
+ **_,
+ ):
+ # Allow relying on the model-name-based alias by
+ # not suppliying `origin_index_suffix`
+ source_index = (
+ f"{model_name}-{origin_index_suffix}" if origin_index_suffix else model_name
+ )
+
+ # Destination and origin index suffixes must be possible to separate
+ # to allow for re-runs of filtered index creation based on the same
+ # origin index.
+ destination_index_suffix = destination_index_suffix or uuid.uuid4().hex
+ destination_index = f"{model_name}-{destination_index_suffix}-filtered"
+
+ self.es.indices.create(
+ index=destination_index,
+ body=index_settings(model_name),
+ )
+
+ sensitive_terms = get_sensitive_terms()
+
+ self.es.reindex(
+ body={
+ "source": {
+ "index": source_index,
+ "query": {
+ "bool": {
+ "must_not": [
+ {
+ "multi_match": {
+ "query": f'"{term}"',
+ "fields": ["tags.name", "title", "description"],
+ }
+ }
+ for term in sensitive_terms
+ ]
+ }
+ },
+ },
+ "dest": {"index": destination_index},
+ },
+ slices="auto",
+ wait_for_completion=True,
+ )
+
+ self.refresh(index_name=destination_index, change_settings=True)
+
+ self.ping_callback()
diff --git a/ingestion_server/ingestion_server/static/mock_sensitive_terms.txt b/ingestion_server/ingestion_server/static/mock_sensitive_terms.txt
new file mode 100644
index 000000000..c2c370b80
--- /dev/null
+++ b/ingestion_server/ingestion_server/static/mock_sensitive_terms.txt
@@ -0,0 +1,3 @@
+running
+water
+bird
diff --git a/ingestion_server/ingestion_server/tasks.py b/ingestion_server/ingestion_server/tasks.py
index d801ace89..3ec2cdfcf 100644
--- a/ingestion_server/ingestion_server/tasks.py
+++ b/ingestion_server/ingestion_server/tasks.py
@@ -54,6 +54,9 @@ class TaskTypes(Enum):
"""create indices in ES for QA tests; this is not intended to run in production but
can be run without negative consequences"""
+ CREATE_AND_POPULATE_FILTERED_INDEX = auto()
+ """create a filtered index based on existing alias index"""
+
def __str__(self):
"""
Get the string representation of this enum.
diff --git a/ingestion_server/ingestion_server/utils/__init__.py b/ingestion_server/ingestion_server/utils/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/ingestion_server/ingestion_server/utils/sensitive_terms.py b/ingestion_server/ingestion_server/utils/sensitive_terms.py
new file mode 100644
index 000000000..7d0eeeead
--- /dev/null
+++ b/ingestion_server/ingestion_server/utils/sensitive_terms.py
@@ -0,0 +1,15 @@
+from http.client import HTTPResponse
+from urllib.request import urlopen
+
+from decouple import config
+
+
+SENSITIVE_TERMS_URL = config(
+ "SENSITIVE_TERMS_URL",
+ default="http://localhost:8001/static/mock_sensitive_terms.txt",
+)
+
+
+def get_sensitive_terms() -> list[str]:
+ response: HTTPResponse = urlopen(SENSITIVE_TERMS_URL)
+ return [line.decode("utf-8") for line in response.readlines()]
diff --git a/ingestion_server/justfile b/ingestion_server/justfile
index ccaecad0d..849da977a 100644
--- a/ingestion_server/justfile
+++ b/ingestion_server/justfile
@@ -71,6 +71,12 @@ promote model="image" suffix="init" alias="image":
delete model="image" suffix="init" alias="image":
just _curl-post '{"model": "{{ model }}", "action": "DELETE_INDEX", "index_suffix": "{{ suffix }}"}'
+point-alias model suffix alias:
+ just _curl-post '{"model": "{{ model }}", "action": "POINT_ALIAS", "index_suffix": "{{ suffix }}", "alias": "{{ alias }}"}'
+
+create-and-populate-filtered-index model="image" destination_suffix="init":
+ just _curl-post '{"model": "{{ model }}", "action": "CREATE_AND_POPULATE_FILTERED_INDEX", "destination_index_suffix": "{{ destination_suffix }}"}'
+
#########
# Tests #
#########
@@ -78,3 +84,7 @@ delete model="image" suffix="init" alias="image":
# Run ingestion-server tests locally
test-local *args:
pipenv run pytest {{ args }}
+
+# Clean integration test docker-compose stack. Useful if test tear down does not run due to catastrophic test failure.
+test-clean-dc:
+ docker-compose --profile=ingestion_server -f test/integration-docker-compose.yml down -v
diff --git a/ingestion_server/test/integration_test.py b/ingestion_server/test/integration_test.py
index 7770c6483..00802f77b 100644
--- a/ingestion_server/test/integration_test.py
+++ b/ingestion_server/test/integration_test.py
@@ -29,6 +29,11 @@ this_dir = pathlib.Path(__file__).resolve().parent
ingestion_server = f"http://localhost:{service_ports['ingestion_server']}"
+mock_sensitive_terms = (
+ (this_dir.parent / "ingestion_server" / "static" / "mock_sensitive_terms.txt")
+ .read_text()
+ .split("\n")
+)
#################
# Bottle server #
@@ -340,6 +345,52 @@ class TestIngestion(unittest.TestCase):
self.assertEqual(res.status_code, 400, msg=stat_msg)
self.check_index_exists(f"{model}-{suffix}")
+ def _create_and_populate_filtered_index(
+ self,
+ model,
+ origin_suffix=None,
+ destination_suffix=None,
+ ):
+ req = {
+ "model": model,
+ "action": "CREATE_AND_POPULATE_FILTERED_INDEX",
+ "callback_url": bottle_url,
+ }
+ if origin_suffix is not None:
+ req |= {
+ "origin_index_suffix": origin_suffix,
+ }
+ if destination_suffix is not None:
+ req |= {"destination_index_suffix": destination_suffix}
+
+ 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)
+
+ assert self.__class__.cb_queue.get(timeout=60) == "CALLBACK!"
+
+ index_pattern = (
+ f"{model}-{destination_suffix if destination_suffix else '*'}-filtered"
+ )
+ self.check_index_exists(index_pattern)
+
+ def _point_alias(self, model, suffix, alias):
+ req = {
+ "model": model,
+ "action": "POINT_ALIAS",
+ "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)
+
+ assert self.__class__.cb_queue.get(timeout=30) == "CALLBACK!"
+
+ self.check_index_exists(alias)
+
@classmethod
def setUpClass(cls) -> None:
# Launch a Bottle server to receive and handle callbacks
@@ -353,7 +404,7 @@ class TestIngestion(unittest.TestCase):
compose_path = gen_integration_compose()
cls.compose_path = compose_path
- cls._compose_cmd(["up", "-d"], capture_output=True)
+ cls._compose_cmd(["up", "-d"])
# Wait for services to be ready
cls.upstream_db, cls.downstream_db = cls._wait_for_dbs()
@@ -398,29 +449,28 @@ class TestIngestion(unittest.TestCase):
if conn:
conn.close()
- @pytest.mark.order(1)
def test_list_tasks_empty(self):
res = requests.get(f"{ingestion_server}/task")
res_json = res.json()
msg = "There should be no tasks in the task list"
self.assertEqual(res_json, [], msg)
- @pytest.mark.order(2)
+ @pytest.mark.order(after="test_list_tasks_empty")
def test_image_ingestion_succeeds(self):
self._ingest_upstream("image", "integration")
- @pytest.mark.order(3)
+ @pytest.mark.order(after="test_image_ingestion_succeeds")
def test_task_count_after_one(self):
res = requests.get(f"{ingestion_server}/task")
res_json = res.json()
msg = "There should be one task in the task list now."
self.assertEqual(1, len(res_json), msg)
- @pytest.mark.order(4)
+ @pytest.mark.order(after="test_task_count_after_one")
def test_audio_ingestion_succeeds(self):
self._ingest_upstream("audio", "integration")
- @pytest.mark.order(5)
+ @pytest.mark.order(after="test_audio_ingestion_succeeds")
def test_task_count_after_two(self):
res = requests.get(f"{ingestion_server}/task")
res_json = res.json()
@@ -439,15 +489,15 @@ class TestIngestion(unittest.TestCase):
wait_for_status="yellow",
)
- @pytest.mark.order(6)
+ @pytest.mark.order(after="test_task_count_after_two")
def test_promote_images(self):
self._promote("image", "integration", "image-main")
- @pytest.mark.order(7)
+ @pytest.mark.order(after="test_promote_images")
def test_promote_audio(self):
self._promote("audio", "integration", "audio-main")
- @pytest.mark.order(8)
+ @pytest.mark.order(after="test_promote_audio")
def test_upstream_indexed_images(self):
"""
Check that the image data has been successfully indexed in Elasticsearch.
@@ -462,7 +512,7 @@ class TestIngestion(unittest.TestCase):
msg = "There should be 5000 images in Elasticsearch after ingestion."
self.assertEqual(count, 5000, msg)
- @pytest.mark.order(9)
+ @pytest.mark.order(after="test_upstream_indexed_images")
def test_upstream_indexed_audio(self):
"""
Check that the audio data has been successfully indexed in Elasticsearch.
@@ -477,7 +527,49 @@ class TestIngestion(unittest.TestCase):
msg = "There should be 5000 audio tracks in Elasticsearch after ingestion."
self.assertEqual(count, 5000, msg)
- @pytest.mark.order(10)
+ @pytest.mark.order(after="test_promote_images")
+ def test_filtered_image_index_creation(self):
+ self._create_and_populate_filtered_index("image", "integration", "integration")
+
+ @pytest.mark.order(after="test_promote_audio")
+ def test_filtered_audio_index_creation(self):
+ self._create_and_populate_filtered_index("audio", "integration", "integration")
+
+ @pytest.mark.order(after="test_filtered_image_index_creation")
+ def test_point_filtered_image_alias(self):
+ self._point_alias("image", "integration-filtered", "image-filtered")
+
+ @pytest.mark.order(after="test_filtered_audio_index_creation")
+ def test_point_filtered_audio_alias(self):
+ self._point_alias("audio", "integration-filtered", "audio-filtered")
+
+ @pytest.mark.order(
+ after=["test_point_filtered_audio_alias", "test_point_filtered_image_alias"]
+ )
+ def test_filtered_indexes(self):
+ """
+ Check that the audio data has been successfully indexed in Elasticsearch.
+
+ The number of hits for a blank search should match the size of the loaded mock
+ data.
+ """
+ params = zip(mock_sensitive_terms, ["audio-filtered", "image-filtered"])
+ for sensitive_term, index in params:
+ with self.subTest(
+ f"Check that {index} does not include mock sensitive term {sensitive_term}"
+ ):
+ es = self._get_es()
+ res = es.search(
+ index=index, query={"query_string": {"query": sensitive_term}}
+ )
+ count = res["hits"]["total"]["value"]
+ self.assertEqual(
+ count,
+ 0,
+ f"There should be no results for {sensitive_term} in {index}. Found {count}.",
+ )
+
+ @pytest.mark.order(after="test_upstream_indexed_audio")
def test_update_index_images(self):
"""Check that the image data can be updated from the API database into ES."""
@@ -495,7 +587,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(11)
+ @pytest.mark.order(after="test_update_index_images")
def test_update_index_audio(self):
"""Check that the audio data can be updated from the API database into ES."""
@@ -513,43 +605,43 @@ 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(12)
+ @pytest.mark.order(after="test_update_index_audio")
def test_index_deletion_succeeds(self):
self._ingest_upstream("audio", "temporary")
self._delete_index("audio", "temporary")
- @pytest.mark.order(13)
+ @pytest.mark.order(after="test_index_deletion_succeeds")
def test_alias_force_deletion_succeeds(self):
self._ingest_upstream("audio", "temporary")
self._promote("audio", "temporary", "audio-temp")
self._delete_index("audio", "temporary", "audio-temp")
- @pytest.mark.order(14)
+ @pytest.mark.order(after="test_alias_force_deletion_succeeds")
def test_alias_soft_deletion_fails(self):
self._ingest_upstream("audio", "temporary")
self._promote("audio", "temporary", "audio-temp")
self._soft_delete_index("audio", "audio-temp", "temporary")
- @pytest.mark.order(15)
+ @pytest.mark.order(after="test_alias_soft_deletion_fails")
def test_alias_ambiguous_deletion_fails(self):
# No need to ingest or promote, index and alias exist
self._soft_delete_index("audio", "audio-temp", "temporary", True)
- @pytest.mark.order(16)
+ @pytest.mark.order(after="test_alias_ambiguous_deletion_fails")
def test_stat_endpoint_for_index(self):
res = requests.get(f"{ingestion_server}/stat/audio-integration")
data = res.json()
assert data["exists"]
assert data["alt_names"] == ["audio-main"]
- @pytest.mark.order(17)
+ @pytest.mark.order(after="test_stat_endpoint_for_index")
def test_stat_endpoint_for_alias(self):
res = requests.get(f"{ingestion_server}/stat/audio-main")
data = res.json()
assert data["exists"]
assert data["alt_names"] == "audio-integration"
- @pytest.mark.order(18)
+ @pytest.mark.order(after="test_stat_endpoint_for_alias")
def test_stat_endpoint_for_non_existent(self):
res = requests.get(f"{ingestion_server}/stat/non-existent")
data = res.json()
diff --git a/load_sample_data.sh b/load_sample_data.sh
index e5e9918db..1a70fef89 100755
--- a/load_sample_data.sh
+++ b/load_sample_data.sh
@@ -74,6 +74,10 @@ just ingestion_server/ingest-upstream "audio" "init"
just docker/es/wait-for-index "audio-init"
just ingestion_server/promote "audio" "init" "audio"
just docker/es/wait-for-index "audio"
+just ingestion_server/create-and-populate-filtered-index "audio" "init"
+just docker/es/wait-for-index "audio-init-filtered"
+just ingestion_server/point-alias "audio" "init-filtered" "audio-filtered"
+just docker/es/wait-for-index "audio-filtered" "audio-init-filtered"
# Image ingestion is flaky; but usually works on the next attempt
set +e
@@ -89,6 +93,10 @@ set -e
just ingestion_server/promote "image" "init" "image"
just docker/es/wait-for-index "image"
+just ingestion_server/create-and-populate-filtered-index "image" "init"
+just docker/es/wait-for-index "image-init-filtered"
+just ingestion_server/point-alias "image" "init-filtered" "image-filtered"
+just docker/es/wait-for-index "image-filtered" "image-init-filtered"
#########
# Redis #