wrolpi/tiles/cache.py

239 lines
9.6 KiB
Python
Raw Normal View History

Map tiles for ATAK and iTAK (#1024) * Map tiles for ATAK and iTAK A new service, wrolpi-tiles (tiles/), draws WROLPi's map as 256 px raster tiles from the map's PMTiles with MapLibre Native (mapli), so ATAK and iTAK can use the map as a map source, and ATAK can download an area of it. - Tiles are drawn in blocks of 4x4 (ATAK asks for tiles in quadtree order), each block once however many requests wait on it, in render processes of their own. Phones are served in turn. - A tile is always a 200: blank where there is no map, or when it was not drawn before ATAK's 5 second timeout. Five failed tiles in a row stop an ATAK download, and a 401/403 stops the map source. - Drawn tiles are kept in /var/cache/wrolpi-tiles, with a size cap and a free-space floor; JPEG, about a seventh of a PNG. - The basemap is the web map's (protomaps-themes-base, light), kept equal to it by a Jest test. Unreadable map files and missing map fonts are left out rather than failing every tile. - Caddy serves it at /tiles/ over HTTPS and on port 8088 over plain HTTP (a phone must trust WROLPi's CA for HTTPS). /tiles/wrolpi.xml is the MOBAC map source to import. - A separate service with lower CPU priority and a memory cap, so a phone downloading an area cannot slow the API. Docker runs it from the api image. - The map page has an ATAK tab: the map source links, how to use them, and what the tile service is doing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: bound PMTiles decompression before it happens A few bytes of a downloaded map file could decompress to far more than the cap, which was applied only afterwards. Decompress at most MAX_METADATA_SIZE, as modules.map.pmtiles does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: never send a blank for a late tile; start render processes with the service QA on a Pi 4 found the first tile after a start sent blank: starting the render processes and the first draw took 4.5 s, past the deadline. A downloader (ATAK's, iTAK's) keeps whatever a tile request returns, so a blank sent for a late or failed tile is a hole in its offline map for good. Such a tile is now a 503 (ATAK tries each tile twice; only 401 and 403 stop a map source), and the render processes start with the service. Also: - OOMScoreAdjust=500: Raspberry Pi OS disables the memory cgroup, so MemoryMax does nothing there; the tile service is killed before the API. - sanic-ext's auto extensions are off in the tile service. - The map's ATAK tab is before Manage: Manage is the last tab. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: put backgroundColor back in the map source; iTAK requires it iTAK refuses a MOBAC map source without <backgroundColor> ("The data couldn't be read because it is missing"). ATAK ignores it. It is the map's own background color. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: leave out the map files hidden on the Manage tab, as the web map does maps.yaml's ignored_files names the map files the user hid; the web map does not draw them, and the tiles drew them anyway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: bound the render processes' memory and the tiles-per-second times QA on a Pi 4, a phone taking 123,000 tiles offline: each render process grew from about 270 MB to 370 MB (MapLibre keeps what it has read and drawn) and did not shrink when idle. A render process is now replaced after 2,000 blocks. The serve times behind tiles-per-second were only forgotten when the status was asked for; they are forgotten as tiles are served. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Map ATAK tab: iTAK takes an area offline too An iPhone downloaded 123,000 tiles with iTAK and showed them offline with none missing; the tab said only ATAK could. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Map ATAK tab: a button to clear the tiles the tile service keeps POST /tiles/cache/clear on the tile service (which keeps the cache's size) removes the kept tiles; they are drawn again when next asked for. The button asks first, and says that maps already downloaded to phones are not changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: measure the cache as the disk does; clear it at once, delete in the background QA on a Pi 4 after a 123,000-tile download: the cache counted 375 MB of tile bytes while its files took 660 MB of the SD card (each small file takes a whole 4 KiB block), so the 1 GB cap allowed about 1.7 GB. The cache is now measured in disk blocks. Clearing deleted 128,000 files in the request: about 40 seconds, with the Pi's load warning on. A clear (or a new style) now renames the tiles out of the way at once and deletes them in a lowest-priority thread, pausing every 500 files; a deletion cut short is finished at the next start. A tile drawn again no longer counts twice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Help: ATAK and iTAK Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: a page on port 8088 saying what it is A person who finds port 8088 got a 404. / (and /tiles/) is now a short page: WROLPi's map tile service for ATAK and iTAK, the map source to open on a phone, and links to the WROLPi app and the map's ATAK tab, made from the address the page was reached by (Docker publishes the app on TILES_HTTPS_PORT). Port 8088 serves WROLPi's icon. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tiles: review fixes - Caddy: a tile request is never redirected to the fallback page when the tile service is down or restarting (handle_errors on 443). ATAK keeps whatever a tile request ends with, so the page was stored as the tile; it is now a 503 with Retry-After, which ATAK tries again. - The cache's oldest tiles are found and deleted in a lowest-priority thread, pausing as it goes, not in the tile request which filled it. - ATAK tab: only the newest status request writes the status, so a slow answer can not undo a newer one (or a clear). It says when the page was opened on localhost and the addresses work only there, and names each map source as the app lists it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:21:27 -07:00
"""Tiles already drawn, on the disk.
A phone taking an area offline asks for the same tiles a second phone will, and a block draws tiles beyond the
area asked for. A tile is a file `<root>/<style id>/<z>/<x>/<y>.jpg`. A new style (a map file was added,
replaced or removed) is a new directory; the others are removed.
Not on the media drive: there it would be indexed as files and copied by backups. `/var/cache/wrolpi-tiles` by
default (systemd makes it, see wrolpi-tiles.service). On a Raspberry Pi that is the SD card, so the cache is
small (`max_bytes`) and nothing is written when the disk is nearly full (`min_free_bytes`).
The cache is measured as the disk measures it (`du`), in the blocks its files take: a tile of a few kilobytes
takes a whole block (4 KiB), and counted by its bytes a full cache of 1 GB was 1.7 GB of the disk.
Tiles are removed by renaming their directory out of the way (`.trash-...`) and deleting it in a thread of the
lowest priority, a little at a time (and a full cache's oldest tiles are found and deleted the same way, never in
the request which filled it): a phone's download leaves 100,000 files and more, which take most of a minute
to delete from an SD card and load the Raspberry Pi while they are. A deletion cut short (a restart) is finished
when the service next starts.
"""
import logging
import os
import shutil
import threading
import time
import uuid
from pathlib import Path
from typing import Dict, Optional, Tuple
logger = logging.getLogger(__name__)
SUFFIX = '.jpg'
# Removing the oldest tiles when the cache is full takes it down to this much of `max_bytes`.
EVICT_TO = 0.8
TRASH_PREFIX = '.trash-'
# Deleting pauses this long after every DELETE_BATCH files, so it does not keep the disk from everything else.
DELETE_BATCH = 500
DELETE_PAUSE = 0.02
def disk_size(stat: os.stat_result) -> int:
"""What a file takes of the disk: its blocks (512 bytes each, whatever the filesystem's block size is)."""
blocks = getattr(stat, 'st_blocks', None)
return blocks * 512 if blocks is not None else stat.st_size
def _lower_priority():
"""Make the calling thread the least important to the scheduler (Linux gives each thread its own priority)."""
try:
os.setpriority(os.PRIO_PROCESS, threading.get_native_id(), 19)
except (OSError, AttributeError):
pass
def _delete_slowly(path: Path):
_lower_priority()
deleted = 0
for root, directories, files in os.walk(path, topdown=False):
for name in files:
try:
os.unlink(os.path.join(root, name))
except OSError:
pass
deleted += 1
if deleted % DELETE_BATCH == 0:
time.sleep(DELETE_PAUSE)
for name in directories:
try:
os.rmdir(os.path.join(root, name))
except OSError:
pass
shutil.rmtree(path, ignore_errors=True)
logger.info(f'Deleted {deleted} old tiles')
class TileCache:
def __init__(self, root: Path, max_bytes: int, min_free_bytes: int):
self.root = root
self.max_bytes = max_bytes
self.min_free_bytes = min_free_bytes
self.style_id: Optional[str] = None
self.size = 0
self._lock = threading.Lock()
self._evicting = False
self._deleting: list = []
@property
def enabled(self) -> bool:
return self.max_bytes > 0
def path(self, z: int, x: int, y: int) -> Path:
return self.root / self.style_id / str(z) / str(x) / f'{y}{SUFFIX}'
def _discard(self, path: Path):
"""Remove a directory of tiles: at once from the cache, from the disk in the background."""
trash = path if path.name.startswith(TRASH_PREFIX) else \
path.with_name(f'{TRASH_PREFIX}{path.name}-{uuid.uuid4().hex[:8]}')
try:
if trash != path:
path.rename(trash)
except FileNotFoundError:
return
except OSError as e:
logger.warning(f'Could not move {path} aside, deleting it now: {e}')
shutil.rmtree(path, ignore_errors=True)
return
thread = threading.Thread(target=_delete_slowly, args=(trash,), name='tile-cache-delete', daemon=True)
self._deleting = [i for i in self._deleting if i.is_alive()] + [thread]
thread.start()
def wait_for_deletes(self, timeout: float = None):
"""Wait for tiles being deleted in the background (for tests)."""
for thread in list(self._deleting):
thread.join(timeout)
def _measure(self, directory: Path) -> int:
size = 0
for path in directory.rglob(f'*{SUFFIX}'):
try:
size += disk_size(path.stat())
except OSError:
pass
return size
def use_style(self, style_id: str):
"""Serve tiles of this style; remove the tiles of every other (and any deletion left unfinished)."""
self.style_id = style_id
if not self.enabled:
return
try:
self.root.mkdir(parents=True, exist_ok=True)
for entry in self.root.iterdir():
if entry.name == style_id:
continue
if entry.is_dir():
self._discard(entry)
else:
entry.unlink(missing_ok=True)
current = self.root / style_id
size = self._measure(current) if current.is_dir() else 0
with self._lock:
self.size = size
except OSError as e:
logger.error(f'Tile cache {self.root} is not usable, tiles will not be kept', exc_info=e)
self.max_bytes = 0
def clear(self) -> int:
"""Remove every kept tile at once (they are deleted from the disk in the background); return how much of
the disk that frees. Tiles are drawn again when next asked for."""
if not self.enabled or not self.style_id:
return 0
with self._lock:
freed, self.size = self.size, 0
self._discard(self.root / self.style_id)
logger.info(f'Tile cache cleared ({freed // 2 ** 20} MiB)')
return freed
def get(self, z: int, x: int, y: int) -> Optional[bytes]:
if not self.enabled:
return None
try:
return self.path(z, x, y).read_bytes()
except OSError:
return None
def _disk_full(self) -> bool:
try:
return shutil.disk_usage(self.root).free < self.min_free_bytes
except OSError:
return True
def put(self, z: int, tiles: Dict[Tuple[int, int], bytes], style_id: str):
"""Keep the tiles of a block. Blocking; call it in a thread."""
if not self.enabled or style_id != self.style_id or self._disk_full():
return
added = 0
for (x, y), data in tiles.items():
path = self.path(z, x, y)
try:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f'.{path.name}.{os.getpid()}.{threading.get_ident()}')
temporary.write_bytes(data)
new = disk_size(temporary.stat())
try:
old = disk_size(path.stat()) # a tile drawn again replaces itself
except FileNotFoundError:
old = 0
temporary.replace(path)
added += new - old
except OSError as e:
logger.warning(f'Could not keep tile {z}/{x}/{y}: {e}')
return
with self._lock:
self.size += added
evict = self.size > self.max_bytes and not self._evicting
self._evicting = self._evicting or evict
if evict:
# Not here: finding and deleting tens of thousands of files on an SD card takes seconds, and this is a
# phone's tile request. The cache is a little over its size meanwhile.
thread = threading.Thread(target=self._evict, args=(self.style_id,), name='tile-cache-evict',
daemon=True)
self._deleting = [i for i in self._deleting if i.is_alive()] + [thread]
thread.start()
def _evict(self, style_id: str):
"""Remove the least recently written tiles until the cache is `EVICT_TO` of its size. Runs in a thread of
the lowest priority, pausing as it goes."""
_lower_priority()
try:
files = []
for count, path in enumerate((self.root / style_id).rglob(f'*{SUFFIX}'), 1):
try:
stat = path.stat()
except OSError:
continue
files.append((stat.st_mtime_ns, disk_size(stat), path))
if count % DELETE_BATCH == 0:
time.sleep(DELETE_PAUSE)
files.sort()
size = sum(i[1] for i in files)
target = self.max_bytes * EVICT_TO
removed = 0
for count, (_, file_size, path) in enumerate(files, 1):
if size - removed <= target or style_id != self.style_id:
break
try:
path.unlink()
removed += file_size
except OSError:
pass
if count % DELETE_BATCH == 0:
time.sleep(DELETE_PAUSE)
with self._lock:
# Less what was removed: tiles kept while this ran are still counted.
self.size = max(0, self.size - removed) if style_id == self.style_id else self.size
logger.info(f'Tile cache evicted {removed // 2 ** 20} MiB, down to {self.size // 2 ** 20} MiB')
finally:
self._evicting = False