Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Stop the crawler filling its own disk

Daoud Clarkee9e967e0146a
diff --git a/docker-compose.yml b/docker-compose.yml
index 3016b11..6cdffa9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -23,31 +23,34 @@ services:
- REDIS_URL=redis://redis:6379
volumes:
- crawler_data:/home/mwmbl/.mwmbl
- deploy:
- restart_policy:
- condition: on-failure
- delay: 30s
- max_attempts: 3
+ # Compose applies deploy.restart_policy in swarm mode only, so what was here was no
+ # restart policy at all: a crawler that exited stayed exited. One did, for three days.
+ restart: unless-stopped
logging:
driver: "json-file"
options:
max-size: "50m"
max-file: "3"
- # CPU restrictions if needed:
- # resources:
- # limits:
- # cpus: '0.50'
+ # CPU restrictions if needed (deploy.resources.limits compose does apply):
+ # deploy:
+ # resources:
+ # limits:
+ # cpus: '0.50'
redis:
image: redis:alpine
restart: unless-stopped
- # stop-writes-on-bgsave-error no: a failed snapshot otherwise makes Redis reject
- # every write until someone intervenes, which stops the crawler dead. What is in
- # here is a work queue that allkeys-lru is already free to evict, so a snapshot we
- # could not write is worth losing, and carrying on is worth more than the snapshot.
+ # save "": no snapshots at all. What is in here is a work queue that allkeys-lru is
+ # already free to evict, so there is nothing worth the cost of saving it, and the cost
+ # was real - a crawler host was found with 8.5GB of temp-*.rdb next to a 209MB dump.rdb.
+ # A snapshot forks a Redis holding up to maxmemory and writes a second copy of the data
+ # beside the first, and every one of those children that the OOM killer took left its
+ # temp file behind for good. That filled the disk, which failed the next snapshot, which
+ # (before stop-writes-on-bgsave-error no, kept below for a save anyone triggers by hand)
+ # made Redis reject every write and stopped the crawler.
command: >
redis-server --maxmemory 2gb --maxmemory-policy allkeys-lru
- --stop-writes-on-bgsave-error no
+ --save "" --stop-writes-on-bgsave-error no
volumes:
- redis_data:/data
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.py
index 10b62b8..2eea80c 100644
--- a/mwmbl/crawl.py
+++ b/mwmbl/crawl.py
@@ -49,6 +49,7 @@ from mwmbl.redis_url_queue import RedisURLQueue
from mwmbl.tinysearchengine.indexer import Document, TinyIndex
from mwmbl.tinysearchengine.rank import score_result
from mwmbl.tokenizer import tokenize
+from mwmbl.utils import prune_request_cache
BATCH_QUEUE_KEY = "batch-queue"
REMOTE_SERVER = "https://api.mwmbl.org"
@@ -61,6 +62,13 @@ CURATED_DOMAINS_CACHE_SECONDS = 300.0
# submit the term at all. See count_new_index_entries for where the expectation comes from.
MIN_NEW_INDEX_ENTRIES = 1
+# How long run_indexing may reuse a cached copy of what the main index holds for a term.
+# Never expiring it, which is what request_cache does by default, is wrong here twice over:
+# the diff below decides what to submit by comparing local items against remote ones, so a
+# stale copy submits what the index already has, and a crawler sees a term it will never see
+# again often enough that the cache grew by around 800MB a day until the disk filled.
+REMOTE_INDEX_CACHE_EXPIRY = timedelta(hours=1)
+
def _fetch_curated_domains() -> set[str]:
global _curated_domains_cache, _curated_domains_fetched_at
@@ -264,7 +272,10 @@ class Crawler:
term_new_doc_count = index_batches(batches, index_path)
logger.info(f"Indexed, top terms to sync: {term_new_doc_count.most_common(10)}")
- remote_index = RemoteIndex()
+ # Once a round is often enough to keep the cache at roughly an hour's worth of terms,
+ # and the rounds are minutes apart, so the sweep costs nothing worth measuring.
+ prune_request_cache()
+ remote_index = RemoteIndex(expire_after=REMOTE_INDEX_CACHE_EXPIRY)
with TinyIndex(Document, index_path, "w") as local_index:
for term, count in term_new_doc_count.most_common(100):
logger.info(f"Syncing term {term} with {count} new local items")
@@ -324,7 +335,7 @@ class Crawler:
logger.info(f"Completed indexing for term {term}")
new_page_content = local_index.get_page(page_index)
- logger.info(f"Page content: {new_page_content}")
+ logger.info(f"Page {page_index} now holds {len(new_page_content)} documents")
def process_batch_continuously(self):
"""Continuously process batches with error handling.
diff --git a/mwmbl/crawler/domains.py b/mwmbl/crawler/domains.py
index 83d1235..1432a30 100644
--- a/mwmbl/crawler/domains.py
+++ b/mwmbl/crawler/domains.py
@@ -63,7 +63,7 @@ class DomainLinkDatabase:
# This is a URL that we don't care about
return
- logger.info(f"Updating domain links for {domain_group} with {target} links")
+ logger.info(f"Updating domain links for {domain_group} with {len(target)} links")
bloom_filter, score = self.links[domain_group]
bloom_filter.update(target)
diff --git a/mwmbl/rankeval/evaluation/remote_index.py b/mwmbl/rankeval/evaluation/remote_index.py
index 7aa05ed..89f4d76 100644
--- a/mwmbl/rankeval/evaluation/remote_index.py
+++ b/mwmbl/rankeval/evaluation/remote_index.py
@@ -3,7 +3,9 @@ Pretend to be an index but retrieve results from a remote index.
"""
import time
+from datetime import timedelta
from logging import getLogger
+from typing import Optional
import requests
@@ -14,14 +16,22 @@ logger = getLogger(__name__)
class RemoteIndex:
- def __init__(self, remote_server: str = "https://api.mwmbl.org"):
+ def __init__(self, remote_server: str = "https://api.mwmbl.org", expire_after: Optional[timedelta] = None):
+ """expire_after is how long a cached copy of the index's results may be reused.
+
+ None never expires it, which is what the evaluation scripts want: they replay one
+ set of queries over and over against an index that moves slowly enough not to
+ matter. A caller that runs for weeks against a moving index wants a real expiry -
+ see REMOTE_INDEX_CACHE_EXPIRY in crawl.py.
+ """
self.remote_server = remote_server
+ self.expire_after = expire_after
self.url = f"{remote_server}/api/v1/search/raw?s="
def retrieve(self, query: str, refresh: bool = False):
url = self.url + query
response = None
- with request_cache() as session:
+ with request_cache(self.expire_after) as session:
for i in range(3):
try:
response = session.get(url, timeout=15, force_refresh=refresh)
diff --git a/mwmbl/settings_crawler.py b/mwmbl/settings_crawler.py
index df46595..63b7909 100644
--- a/mwmbl/settings_crawler.py
+++ b/mwmbl/settings_crawler.py
@@ -15,4 +15,11 @@ NUM_URLS_IN_BLOOM_FILTER = 10_000_000
DOMAIN_LINKS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "links_{domain_group}.bloom")
NUM_DOMAINS_IN_BLOOM_FILTER = 100_000
+# settings_dev computed this against its own DATA_PATH of ./devdata, and a relative path in
+# the crawler container resolves under the working directory rather than the volume mounted
+# at DATA_PATH: the cache went into the container's writable layer, where nothing bounds it
+# and a restart silently discards it. Every path derived from DATA_PATH has to be re-derived
+# here, the same way settings_prod does it.
+REQUEST_CACHE_PATH = f"{DATA_PATH}/request_cache"
+
HAS_DATABASE = False
diff --git a/mwmbl/utils.py b/mwmbl/utils.py
index 10f3179..cf80f06 100644
--- a/mwmbl/utils.py
+++ b/mwmbl/utils.py
@@ -121,9 +121,27 @@ def validate_domain(domain_or_url: str):
def request_cache(expire_after: Optional[timedelta] = None) -> CachedSession:
+ """A session backed by a cache on disk. expire_after of None never expires a response.
+
+ Never expiring suits a caller that replays the same requests - the evaluation scripts -
+ and is wrong for one with an endless supply of new ones, which should pass the longest
+ staleness it can live with and prune_request_cache what is left over.
+ """
return CachedSession(expire_after=expire_after, backend="filesystem", cache_name=settings.REQUEST_CACHE_PATH)
+def prune_request_cache() -> None:
+ """Delete the cached responses that have expired.
+
+ Asking for a request again replaces its expired response, so a cache whose requests come
+ round again keeps itself in order. One whose requests mostly do not - a response per
+ search term, say - only ever grows, because the entry nobody asks for a second time is
+ the one nothing replaces. Expiry alone does not reclaim a byte without this.
+ """
+ with request_cache() as session:
+ session.cache.delete(expired=True)
+
+
def float_or_none(s: str) -> Optional[float]:
try:
return float(s)
diff --git a/test/test_crawl_functional.py b/test/test_crawl_functional.py
index 84de41d..7a0271a 100644
--- a/test/test_crawl_functional.py
+++ b/test/test_crawl_functional.py
@@ -11,7 +11,7 @@ import fakeredis
import pytest
from django.test import override_settings
-from mwmbl.crawl import Crawler, crawl_url
+from mwmbl.crawl import REMOTE_INDEX_CACHE_EXPIRY, Crawler, crawl_url
from mwmbl.crawler.batch import HashedBatch, Item, ItemContent
from mwmbl.crawler.urls import FoundURL, URLStatus
from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider
@@ -214,6 +214,10 @@ class TestCrawlFunctional:
remaining_batches = fake_redis.llen("batch-queue")
assert remaining_batches == 0
+ # A never-expiring cache of the index's answers fills the disk:
+ # see test_request_cache.py
+ mock_remote_index.assert_called_once_with(expire_after=REMOTE_INDEX_CACHE_EXPIRY)
+
def test_crawl_url_functionality(self, mock_environment):
"""Test individual URL crawling functionality"""
mock_html_content = b"""<!DOCTYPE html>
diff --git a/test/test_request_cache.py b/test/test_request_cache.py
new file mode 100644
index 0000000..4b411b0
--- /dev/null
+++ b/test/test_request_cache.py
@@ -0,0 +1,71 @@
+"""Where the crawler's cache of index results lives, and what stops it growing.
+
+A volunteer crawler was found with a full disk. 8.95GB of it was this cache: run_indexing
+asks the main index what it holds for each of a round's top 100 terms, and every distinct
+term left a response on disk that nothing ever expired or removed. It was not even on the
+volume - settings_crawler inherited a REQUEST_CACHE_PATH of ./devdata/request_cache from
+settings_dev, which resolves under the container's working directory - so it grew invisibly
+in the writable layer and a restart silently reset it.
+"""
+
+from datetime import datetime, timedelta, timezone
+from io import BytesIO
+from unittest.mock import MagicMock, patch
+
+import requests
+import urllib3
+from django.test import override_settings
+from requests_cache import CachedSession
+
+from mwmbl import settings_crawler
+from mwmbl.crawl import REMOTE_INDEX_CACHE_EXPIRY
+from mwmbl.rankeval.evaluation.remote_index import RemoteIndex
+from mwmbl.utils import prune_request_cache
+
+
+def expiry_used_by(remote_index: RemoteIndex):
+ """The expire_after that a retrieve asks request_cache for."""
+ session = MagicMock()
+ session.get.return_value.json.return_value = {"results": []}
+ with patch("mwmbl.rankeval.evaluation.remote_index.request_cache") as request_cache:
+ request_cache.return_value.__enter__.return_value = session
+ remote_index.retrieve("example")
+ return request_cache.call_args.args[0]
+
+
+def test_crawler_request_cache_is_under_the_data_path():
+ assert settings_crawler.REQUEST_CACHE_PATH.startswith(settings_crawler.DATA_PATH)
+
+
+def test_the_crawler_expires_what_the_index_told_it():
+ assert expiry_used_by(RemoteIndex(expire_after=REMOTE_INDEX_CACHE_EXPIRY)) == REMOTE_INDEX_CACHE_EXPIRY
+
+
+def test_an_unasked_expiry_still_never_expires():
+ """The evaluation scripts replay one set of queries and want the cache to keep them."""
+ assert expiry_used_by(RemoteIndex()) is None
+
+
+def response_for(url: str) -> requests.Response:
+ """A response complete enough for the cache to store, built without going near a network."""
+ request = requests.Request("GET", url).prepare()
+ raw = urllib3.HTTPResponse(body=BytesIO(b"{}"), status=200, preload_content=False, request_url=url)
+ return requests.adapters.HTTPAdapter().build_response(request, raw)
+
+
+def test_pruning_deletes_what_has_expired_and_keeps_the_rest(tmp_path):
+ cache_path = str(tmp_path / "request_cache")
+ now = datetime.now(timezone.utc)
+ with override_settings(REQUEST_CACHE_PATH=cache_path):
+ with CachedSession(backend="filesystem", cache_name=cache_path) as session:
+ session.cache.save_response(
+ response_for("https://example.com/stale"), cache_key="stale", expires=now - timedelta(hours=1)
+ )
+ session.cache.save_response(
+ response_for("https://example.com/fresh"), cache_key="fresh", expires=now + timedelta(hours=1)
+ )
+
+ prune_request_cache()
+
+ assert not session.cache.contains("stale")
+ assert session.cache.contains("fresh")