mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-28 19:06:19 -05:00
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>
This commit is contained in:
parent
92761e1c52
commit
ee30d99212
35 changed files with 13180 additions and 12 deletions
7
.github/workflows/backend.yml
vendored
7
.github/workflows/backend.yml
vendored
|
|
@ -28,21 +28,22 @@ jobs:
|
|||
- name: core
|
||||
paths: wrolpi/test
|
||||
- name: media
|
||||
paths: modules/videos modules/zim modules/docs modules/map modules/inventory modules/flasher
|
||||
paths: modules/videos modules/zim modules/docs modules/map modules/inventory modules/flasher tiles
|
||||
- name: files
|
||||
paths: wrolpi/files wrolpi/collections
|
||||
- name: rest
|
||||
paths: >-
|
||||
--ignore=wrolpi/test
|
||||
--ignore=modules/videos --ignore=modules/zim --ignore=modules/docs --ignore=modules/map
|
||||
--ignore=modules/inventory --ignore=modules/flasher
|
||||
--ignore=modules/inventory --ignore=modules/flasher --ignore=tiles
|
||||
--ignore=wrolpi/files --ignore=wrolpi/collections
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install system packages
|
||||
run: sudo apt-get update && sudo apt-get install -y ffmpeg catdoc
|
||||
# Mesa's EGL and GL drivers: the map tile service (tiles/) draws with them.
|
||||
run: sudo apt-get update && sudo apt-get install -y ffmpeg catdoc libegl1 libegl-mesa0 libgl1-mesa-dri libgles2
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import maplibregl from "maplibre-gl";
|
|||
import {Protocol} from "pmtiles";
|
||||
import layers from "protomaps-themes-base";
|
||||
import {planMapFiles, pmtilesUrl} from "./mapOverlays";
|
||||
import {MapAtak} from "./MapAtak";
|
||||
|
||||
// Ensure PMTiles protocol is registered (may already be registered by MapViewer).
|
||||
try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ }
|
||||
|
|
@ -860,6 +861,8 @@ export function MapRoute() {
|
|||
const links = [
|
||||
{text: 'Map', to: '/map', key: 'map', end: true},
|
||||
{text: 'Pins', to: '/map/pins', key: 'pins'},
|
||||
// Manage (and Statistics, on pages which have one) are the last tabs.
|
||||
{text: 'ATAK', to: '/map/atak', key: 'atak'},
|
||||
{text: 'Manage', to: '/map/manage', key: 'manage'},
|
||||
];
|
||||
|
||||
|
|
@ -870,6 +873,7 @@ export function MapRoute() {
|
|||
<Routes>
|
||||
<Route path='/' exact element={<MapPage/>}/>
|
||||
<Route path='pins' exact element={<MapPins/>}/>
|
||||
<Route path='atak' exact element={<MapAtak/>}/>
|
||||
<Route path='manage' exact element={<ManageMap/>}/>
|
||||
</Routes>
|
||||
</div>
|
||||
|
|
|
|||
222
app/src/components/MapAtak.js
Normal file
222
app/src/components/MapAtak.js
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
// The map's ATAK tab: how to use this WROLPi's map in ATAK (Android) and iTAK (iPhone), and what the
|
||||
// tile service (tiles/, wrolpi-tiles) is doing.
|
||||
import React, {useCallback, useEffect, useRef, useState} from "react";
|
||||
import {APIButton, ErrorMessage, humanFileSize, InfoMessage} from "./Common";
|
||||
import {Group, Header, Panel, Table} from "./ui";
|
||||
|
||||
// How often the status is asked for while the tab is open.
|
||||
const STATUS_INTERVAL_MS = 5000;
|
||||
|
||||
// The map source over plain HTTP: no certificate is needed, so it works on any phone.
|
||||
export function httpMapSourceUrl(hostname = window.location.hostname) {
|
||||
return `http://${hostname}:8088/tiles/wrolpi.xml`;
|
||||
}
|
||||
|
||||
// The map source over HTTPS: the phone must trust this WROLPi's certificate authority.
|
||||
export function httpsMapSourceUrl(origin = window.location.origin) {
|
||||
return `${origin}/tiles/wrolpi.xml`;
|
||||
}
|
||||
|
||||
// Whether this page was opened on the WROLPi itself (or through Docker's localhost): then the map
|
||||
// source addresses name this computer, and a phone can not open them.
|
||||
export function isLoopback(hostname = window.location.hostname) {
|
||||
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1';
|
||||
}
|
||||
|
||||
// Remove the tiles the tile service keeps; they are drawn again when a phone next asks for them.
|
||||
export async function clearTileCache() {
|
||||
const response = await fetch('/tiles/cache/clear', {method: 'POST'});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Could not clear the kept tiles: ${response.status}`);
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
// The status of the tile service, and a function which asks for it now. The status is null while
|
||||
// the first request is pending, undefined when the service did not answer.
|
||||
//
|
||||
// Only the newest request may write the status: a slow answer which settles after a newer poll (or
|
||||
// after the refresh which follows clearing the kept tiles) would put an older status back.
|
||||
export function useTileStatus(interval = STATUS_INTERVAL_MS) {
|
||||
const [status, setStatus] = useState(null);
|
||||
// Each request's number; a request writes only while it is the newest. Unmounting makes every
|
||||
// request in flight old.
|
||||
const generation = useRef(0);
|
||||
|
||||
const fetchStatus = useCallback(async () => {
|
||||
const mine = ++generation.current;
|
||||
let data;
|
||||
try {
|
||||
const response = await fetch('/tiles/status');
|
||||
data = response.ok ? await response.json() : undefined;
|
||||
} catch (e) {
|
||||
data = undefined;
|
||||
}
|
||||
if (mine === generation.current) setStatus(data);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// The counter itself (not a DOM node): on unmount every request in flight becomes old.
|
||||
const requests = generation;
|
||||
fetchStatus();
|
||||
const timer = setInterval(fetchStatus, interval);
|
||||
return () => {
|
||||
requests.current++;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [interval, fetchStatus]);
|
||||
|
||||
return [status, fetchStatus];
|
||||
}
|
||||
|
||||
function MapSourceRow({label, name, url, note}) {
|
||||
return <Table.Row>
|
||||
<Table.Cell>
|
||||
<b>{label}</b>
|
||||
<div style={{fontSize: '0.8125rem', color: 'var(--muted)'}}>{note} Called <b>{name}</b> in the app.</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell style={{wordBreak: 'break-all'}}><a href={url}>{url}</a></Table.Cell>
|
||||
<Table.Cell>
|
||||
<APIButton icon='copy' aria-label={`Copy ${label} map source address`}
|
||||
onClick={() => navigator.clipboard.writeText(url)}/>
|
||||
</Table.Cell>
|
||||
</Table.Row>;
|
||||
}
|
||||
|
||||
function HowTo() {
|
||||
return <Panel>
|
||||
<Header as='h3'>Use this map in ATAK or iTAK</Header>
|
||||
<p>
|
||||
ATAK (Android) and iTAK (iPhone) can draw this WROLPi's map while the phone is on this
|
||||
WROLPi's network, and download an area of it to use when it is not.
|
||||
</p>
|
||||
{isLoopback() && <InfoMessage>
|
||||
This page was opened on this computer ({window.location.hostname}), so these addresses only
|
||||
work here. On the phone, open this page (or these addresses) with this WROLPi's address on
|
||||
your network or its hotspot instead.
|
||||
</InfoMessage>}
|
||||
<Table>
|
||||
<Table.Body>
|
||||
<MapSourceRow label='HTTP' name='WROLPi Map' url={httpMapSourceUrl()}
|
||||
note='Works on any phone, nothing to install.'/>
|
||||
<MapSourceRow label='HTTPS' name='WROLPi Map (HTTPS)' url={httpsMapSourceUrl()}
|
||||
note="Only once the phone trusts this WROLPi's certificate."/>
|
||||
</Table.Body>
|
||||
</Table>
|
||||
<ol>
|
||||
<li>On the phone, open a map source address above in its browser; it downloads a small
|
||||
file.
|
||||
</li>
|
||||
<li>Open that file with ATAK or iTAK (or import it with the app's import tool).</li>
|
||||
<li>Choose <b>WROLPi Map</b> (or <b>WROLPi Map (HTTPS)</b>) in the app's list of maps.</li>
|
||||
<li>To use the map away from this WROLPi, download an area of it with the app's map
|
||||
download tool while still connected.
|
||||
</li>
|
||||
</ol>
|
||||
<p>
|
||||
For HTTPS, the phone must first install and trust{' '}
|
||||
<a href='/ca.crt'>this WROLPi's certificate</a>. On an iPhone, after installing it, turn
|
||||
it on in Settings, General, About, Certificate Trust Settings.
|
||||
</p>
|
||||
<p style={{color: 'var(--muted)'}}>
|
||||
The map is of the map files on the Manage tab. Map data © OpenStreetMap contributors.
|
||||
</p>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function secondsAgo(timestamp) {
|
||||
const seconds = Math.max(0, Math.round(Date.now() / 1000 - timestamp));
|
||||
if (seconds < 60) return `${seconds}s ago`;
|
||||
if (seconds < 3600) return `${Math.round(seconds / 60)}m ago`;
|
||||
return `${Math.round(seconds / 3600)}h ago`;
|
||||
}
|
||||
|
||||
function TileServiceStatus({status, refresh}) {
|
||||
if (status === null) {
|
||||
return <Panel><Header as='h3'>Tile service</Header><p>Loading...</p></Panel>;
|
||||
}
|
||||
if (status === undefined) {
|
||||
return <Panel>
|
||||
<Header as='h3'>Tile service</Header>
|
||||
<ErrorMessage>The tile service is not running. Start <b>wrolpi-tiles</b> on the
|
||||
Controller page.</ErrorMessage>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
const basemaps = status.maps.length;
|
||||
const cache = status.cache;
|
||||
return <Panel>
|
||||
<Header as='h3'>Tile service</Header>
|
||||
{!status.renderer && <ErrorMessage>The tile service cannot draw tiles: its renderer (mapli) is not
|
||||
installed.</ErrorMessage>}
|
||||
{basemaps === 0 && <InfoMessage>There are no map files; download some on the Manage tab.</InfoMessage>}
|
||||
<Table>
|
||||
<Table.Body>
|
||||
<Table.Row>
|
||||
<Table.Cell>Map files</Table.Cell>
|
||||
<Table.Cell>{basemaps}</Table.Cell>
|
||||
</Table.Row>
|
||||
<Table.Row>
|
||||
<Table.Cell>Tiles sent</Table.Cell>
|
||||
<Table.Cell>{status.tiles_per_second} per second (last minute)</Table.Cell>
|
||||
</Table.Row>
|
||||
<Table.Row>
|
||||
<Table.Cell>Waiting to be drawn</Table.Cell>
|
||||
<Table.Cell>{status.queued_blocks + status.drawing_blocks} blocks of 16 tiles</Table.Cell>
|
||||
</Table.Row>
|
||||
<Table.Row>
|
||||
<Table.Cell>Kept tiles</Table.Cell>
|
||||
<Table.Cell>
|
||||
{cache.enabled
|
||||
? <Group gap='sm'>
|
||||
<span>{humanFileSize(cache.bytes)} of {humanFileSize(cache.max_bytes)}</span>
|
||||
<APIButton
|
||||
size='xs'
|
||||
role='danger'
|
||||
icon='trash'
|
||||
disabled={!cache.bytes}
|
||||
confirmHeader='Clear kept tiles?'
|
||||
confirmContent={'The tiles this WROLPi keeps are removed, and drawn again when a ' +
|
||||
'phone next asks for them. Maps already downloaded to phones are not ' +
|
||||
'changed: a phone keeps its own copy.'}
|
||||
confirmButton='Clear'
|
||||
onClick={async () => {
|
||||
await clearTileCache();
|
||||
await refresh();
|
||||
}}
|
||||
>Clear</APIButton>
|
||||
</Group>
|
||||
: 'Not kept'}
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
</Table.Body>
|
||||
</Table>
|
||||
<Header as='h4'>Phones (last day)</Header>
|
||||
{status.clients.length === 0
|
||||
? <p>No phone has asked for tiles.</p>
|
||||
: <Table>
|
||||
<Table.Header>
|
||||
<Table.Row>
|
||||
<Table.HeaderCell>Address</Table.HeaderCell>
|
||||
<Table.HeaderCell>Tiles</Table.HeaderCell>
|
||||
<Table.HeaderCell>Last tile</Table.HeaderCell>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{status.clients.map(client => <Table.Row key={client.client}>
|
||||
<Table.Cell>{client.client}</Table.Cell>
|
||||
<Table.Cell>{client.tiles}</Table.Cell>
|
||||
<Table.Cell>{secondsAgo(client.last_seen)}</Table.Cell>
|
||||
</Table.Row>)}
|
||||
</Table.Body>
|
||||
</Table>}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export function MapAtak() {
|
||||
const [status, refresh] = useTileStatus();
|
||||
return <>
|
||||
<HowTo/>
|
||||
<TileServiceStatus status={status} refresh={refresh}/>
|
||||
</>;
|
||||
}
|
||||
171
app/src/components/MapAtak.test.js
Normal file
171
app/src/components/MapAtak.test.js
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
import React from 'react';
|
||||
import {act, fireEvent, renderHook, screen, waitFor, within} from '@testing-library/react';
|
||||
import {mockFetch, renderWithProviders} from '../test-utils';
|
||||
import {humanFileSize} from './Common';
|
||||
import {clearTileCache, httpMapSourceUrl, httpsMapSourceUrl, isLoopback, MapAtak, useTileStatus} from './MapAtak';
|
||||
|
||||
const STATUS = {
|
||||
renderer: true,
|
||||
processes: 2,
|
||||
max_zoom: 17,
|
||||
maps: ['/opt/wrolpi-blobs/map-overview.pmtiles', '/media/wrolpi/map/mexico.pmtiles'],
|
||||
style_id: 'abc',
|
||||
queued_blocks: 3,
|
||||
drawing_blocks: 2,
|
||||
tiles_per_second: 31.5,
|
||||
block_ms: 310,
|
||||
cache: {enabled: true, bytes: 25 * 1024 * 1024, max_bytes: 1024 * 1024 * 1024},
|
||||
stats: {},
|
||||
clients: [{client: '192.0.2.34', tiles: 578, first_seen: 0, last_seen: Date.now() / 1000 - 30, queued_blocks: 0}],
|
||||
};
|
||||
|
||||
describe('MapAtak', () => {
|
||||
const realFetch = global.fetch;
|
||||
afterEach(() => {
|
||||
global.fetch = realFetch;
|
||||
});
|
||||
|
||||
it('builds the map source addresses from how the browser reached this WROLPi', () => {
|
||||
expect(httpMapSourceUrl('192.0.2.8')).toBe('http://192.0.2.8:8088/tiles/wrolpi.xml');
|
||||
expect(httpsMapSourceUrl('https://wrolpi.local')).toBe('https://wrolpi.local/tiles/wrolpi.xml');
|
||||
});
|
||||
|
||||
it('shows the map sources and what the tile service is doing', async () => {
|
||||
global.fetch = mockFetch(STATUS);
|
||||
renderWithProviders(<MapAtak/>);
|
||||
|
||||
expect(screen.getByText(httpMapSourceUrl())).toHaveAttribute('href', httpMapSourceUrl());
|
||||
expect(screen.getByText(httpsMapSourceUrl())).toHaveAttribute('href', httpsMapSourceUrl());
|
||||
expect(screen.getByText("this WROLPi's certificate")).toHaveAttribute('href', '/ca.crt');
|
||||
// Both apps take an area offline (tested with iTAK on an iPhone).
|
||||
expect(screen.getByText(/download an area of it with the app's map download tool/)).toBeInTheDocument();
|
||||
|
||||
expect(await screen.findByText('31.5 per second (last minute)')).toBeInTheDocument();
|
||||
expect(global.fetch).toHaveBeenCalledWith('/tiles/status');
|
||||
expect(screen.getByText('5 blocks of 16 tiles')).toBeInTheDocument();
|
||||
expect(screen.getByText(`${humanFileSize(25 * 1024 * 1024)} of ${humanFileSize(1024 * 1024 * 1024)}`))
|
||||
.toBeInTheDocument();
|
||||
expect(screen.getByText('192.0.2.34')).toBeInTheDocument();
|
||||
expect(screen.getByText('578')).toBeInTheDocument();
|
||||
expect(screen.getByText('30s ago')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says when the tile service is not running', async () => {
|
||||
global.fetch = jest.fn(() => Promise.reject(new Error('connection refused')));
|
||||
renderWithProviders(<MapAtak/>);
|
||||
expect(await screen.findByText(/The tile service is not running/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says when there are no map files', async () => {
|
||||
global.fetch = mockFetch({...STATUS, maps: [], clients: []});
|
||||
renderWithProviders(<MapAtak/>);
|
||||
expect(await screen.findByText(/There are no map files/)).toBeInTheDocument();
|
||||
expect(screen.getByText('No phone has asked for tiles.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clears the kept tiles after asking, then shows the new size', async () => {
|
||||
let bytes = 25 * 1024 * 1024;
|
||||
global.fetch = jest.fn(async (url, options) => {
|
||||
if (url === '/tiles/cache/clear') {
|
||||
expect(options).toEqual({method: 'POST'});
|
||||
const freed = bytes;
|
||||
bytes = 0;
|
||||
return {ok: true, status: 200, json: async () => ({freed_bytes: freed})};
|
||||
}
|
||||
return {ok: true, status: 200, json: async () => ({...STATUS, cache: {...STATUS.cache, bytes}})};
|
||||
});
|
||||
renderWithProviders(<MapAtak/>);
|
||||
await screen.findByText('31.5 per second (last minute)');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', {name: /Clear/}));
|
||||
// Nothing is removed until it is confirmed.
|
||||
expect(await screen.findByText(/a phone keeps its own copy/)).toBeInTheDocument();
|
||||
expect(global.fetch).not.toHaveBeenCalledWith('/tiles/cache/clear', expect.anything());
|
||||
|
||||
const dialog = screen.getByRole('dialog');
|
||||
fireEvent.click(within(dialog).getByRole('button', {name: 'Clear'}));
|
||||
await waitFor(() => expect(global.fetch).toHaveBeenCalledWith('/tiles/cache/clear', {method: 'POST'}));
|
||||
expect(await screen.findByText(`${humanFileSize(0)} of ${humanFileSize(1024 * 1024 * 1024)}`))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cannot clear when no tiles are kept', async () => {
|
||||
global.fetch = mockFetch({...STATUS, cache: {...STATUS.cache, bytes: 0}});
|
||||
renderWithProviders(<MapAtak/>);
|
||||
await screen.findByText('31.5 per second (last minute)');
|
||||
expect(screen.getByRole('button', {name: /Clear/})).toBeDisabled();
|
||||
});
|
||||
|
||||
it('clearTileCache fails loudly when the service refuses', async () => {
|
||||
global.fetch = jest.fn(async () => ({ok: false, status: 502, json: async () => ({})}));
|
||||
await expect(clearTileCache()).rejects.toThrow('502');
|
||||
});
|
||||
|
||||
it('names each map source as the app will list it', async () => {
|
||||
global.fetch = mockFetch(STATUS);
|
||||
renderWithProviders(<MapAtak/>);
|
||||
await screen.findByText('31.5 per second (last minute)');
|
||||
// The tile service names the HTTPS source differently (tiles/service.py).
|
||||
expect(screen.getAllByText('WROLPi Map').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getAllByText('WROLPi Map (HTTPS)').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('says when the addresses only work on this computer', async () => {
|
||||
expect(isLoopback('localhost')).toBe(true);
|
||||
expect(isLoopback('127.0.0.1')).toBe(true);
|
||||
expect(isLoopback('[::1]')).toBe(true);
|
||||
expect(isLoopback('wrolpi.local')).toBe(false);
|
||||
expect(isLoopback('192.0.2.8')).toBe(false);
|
||||
|
||||
// jsdom's page is on localhost.
|
||||
global.fetch = mockFetch(STATUS);
|
||||
renderWithProviders(<MapAtak/>);
|
||||
expect(screen.getByText(/these addresses only\s+work here/)).toBeInTheDocument();
|
||||
await screen.findByText('31.5 per second (last minute)');
|
||||
});
|
||||
|
||||
it('does not put an older status back over a newer one', async () => {
|
||||
// The first request is slow and its answer old. A newer one (as Clear's refresh makes) is
|
||||
// answered first. The old answer settles last, and must not undo the newer.
|
||||
let answerFirst;
|
||||
let calls = 0;
|
||||
global.fetch = jest.fn(() => {
|
||||
calls++;
|
||||
if (calls === 1) {
|
||||
return new Promise(resolve => {
|
||||
answerFirst = () => resolve({ok: true, status: 200, json: async () => STATUS});
|
||||
});
|
||||
}
|
||||
return Promise.resolve({ok: true, status: 200,
|
||||
json: async () => ({...STATUS, cache: {...STATUS.cache, bytes: 0}})});
|
||||
});
|
||||
const {result} = renderHook(() => useTileStatus(60000));
|
||||
await waitFor(() => expect(calls).toBe(1));
|
||||
|
||||
await act(async () => {
|
||||
await result.current[1](); // the newer request
|
||||
});
|
||||
expect(result.current[0].cache.bytes).toBe(0);
|
||||
|
||||
await act(async () => {
|
||||
answerFirst(); // the older one settles last
|
||||
});
|
||||
expect(result.current[0].cache.bytes).toBe(0);
|
||||
});
|
||||
|
||||
it('polls the status while open', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
global.fetch = mockFetch(STATUS);
|
||||
const {unmount} = renderWithProviders(<MapAtak/>);
|
||||
await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1));
|
||||
jest.advanceTimersByTime(5000);
|
||||
await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(2));
|
||||
unmount();
|
||||
jest.advanceTimersByTime(20000);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
19
app/src/components/mapTileStyle.test.js
Normal file
19
app/src/components/mapTileStyle.test.js
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// The tile service (tiles/) draws the map for ATAK and iTAK with the basemap layers the web map
|
||||
// draws with (MapViewer's buildStyle). It runs no JavaScript, so it reads them from a file made
|
||||
// from protomaps-themes-base; this keeps that file the same as what the web map uses.
|
||||
//
|
||||
// After upgrading protomaps-themes-base, write the file again:
|
||||
// cd app && UPDATE_TILE_STYLE=1 CI=true npm test -- --watchAll=false mapTileStyle
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import layers from "protomaps-themes-base";
|
||||
|
||||
const FILE = path.resolve(__dirname, "../../../tiles/basemap-light.json");
|
||||
// The name of the source in the file; the tile service gives each map file a source of its own.
|
||||
const SOURCE = "protomaps";
|
||||
|
||||
it("the tile service's basemap is the web map's light basemap", () => {
|
||||
const expected = JSON.stringify(layers(SOURCE, "light"), null, 1) + "\n";
|
||||
if (process.env.UPDATE_TILE_STYLE) fs.writeFileSync(FILE, expected);
|
||||
expect(fs.readFileSync(FILE, "utf8")).toEqual(expected);
|
||||
});
|
||||
|
|
@ -81,6 +81,14 @@ DEFAULT_CONFIG = {
|
|||
"use_https": True,
|
||||
"description": "Kiwix/Zim server",
|
||||
},
|
||||
{
|
||||
"name": "wrolpi-tiles",
|
||||
"systemd_name": "wrolpi-tiles",
|
||||
"port": 8088,
|
||||
"viewable": False,
|
||||
"use_https": False,
|
||||
"description": "Map tiles for ATAK and iTAK",
|
||||
},
|
||||
{
|
||||
"name": "wrolpi-rsyncd",
|
||||
"systemd_name": "wrolpi-rsyncd",
|
||||
|
|
|
|||
|
|
@ -1577,6 +1577,7 @@ async def restart_all_services() -> dict:
|
|||
"wrolpi-api",
|
||||
"wrolpi-app",
|
||||
"wrolpi-kiwix",
|
||||
"wrolpi-tiles",
|
||||
"wrolpi-help",
|
||||
# Controller restarts itself last (scheduled after response)
|
||||
]
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ except ImportError:
|
|||
CONTAINER_PREFIX = os.environ.get("COMPOSE_PROJECT_NAME", "wrolpi")
|
||||
|
||||
# Containers that should not have a "View" button (non-HTTP services)
|
||||
NON_VIEWABLE_CONTAINERS = {"redis", "memcached", "samba", "rsyncd"}
|
||||
NON_VIEWABLE_CONTAINERS = {"redis", "memcached", "samba", "rsyncd", "tiles"}
|
||||
|
||||
# Containers that should use HTTPS
|
||||
HTTPS_CONTAINERS = {"web"}
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ class TestManagedServicesConfig:
|
|||
def test_managed_services_count(self):
|
||||
"""Should have expected number of managed services."""
|
||||
services = DEFAULT_CONFIG["managed_services"]
|
||||
assert len(services) == 12
|
||||
assert len(services) == 13
|
||||
|
||||
@pytest.mark.parametrize("name,expected", [
|
||||
("wrolpi-api",
|
||||
|
|
@ -65,6 +65,7 @@ class TestManagedServicesConfig:
|
|||
("wrolpi-api-dev",
|
||||
{"systemd_name": "wrolpi-api-dev", "port": 8081, "viewable": True, "show_only_when_running": True}),
|
||||
("wrolpi-app", {"port": 3000, "viewable": False}),
|
||||
("wrolpi-tiles", {"systemd_name": "wrolpi-tiles", "port": 8088, "viewable": False}),
|
||||
("wrolpi-app-dev", {"port": 3000, "viewable": False, "show_only_when_running": True}),
|
||||
("caddy", {"port": 443}),
|
||||
("wrolpi-upgrade", {"port": None, "viewable": False, "show_only_when_running": True}),
|
||||
|
|
|
|||
|
|
@ -280,8 +280,8 @@ fi
|
|||
# with --no-block so systemd queues the starts after we exit.
|
||||
|
||||
progress "Starting WROLPi services..."
|
||||
systemctl enable wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-rsyncd.service
|
||||
systemctl start --no-block wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-rsyncd.service
|
||||
systemctl enable wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service
|
||||
systemctl start --no-block wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service
|
||||
|
||||
# If we did anything notable, leave a summary for the XFCE autostart to
|
||||
# show as a zenity dialog once the user lands on the desktop.
|
||||
|
|
|
|||
|
|
@ -99,3 +99,7 @@ wpasupplicant
|
|||
zenity
|
||||
zim-tools
|
||||
zlib1g-dev
|
||||
libegl1
|
||||
libegl-mesa0
|
||||
libgl1-mesa-dri
|
||||
libgles2
|
||||
|
|
|
|||
|
|
@ -58,6 +58,29 @@ services:
|
|||
test: [ 'CMD-SHELL', 'curl http://127.0.0.1:8081/api/echo' ]
|
||||
interval: 2m
|
||||
|
||||
tiles: # Map tiles for ATAK and iTAK, drawn from the map's PMTiles (tiles/). The api image, another command.
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/api/Dockerfile
|
||||
entrypoint: [ 'python3', '-O', '-m', 'tiles', '--host', '0.0.0.0', '--port', '9088' ]
|
||||
command: [ ]
|
||||
environment:
|
||||
- CACHE_DIRECTORY=/var/cache/wrolpi-tiles
|
||||
# The page at :8088/ links to the WROLPi app, which Docker publishes on this port.
|
||||
- TILES_HTTPS_PORT=${WEB_HTTPS_PORT-8443}
|
||||
volumes:
|
||||
- './tiles:/opt/wrolpi/tiles'
|
||||
- './modules/map/static:/opt/wrolpi/modules/map/static:ro'
|
||||
- './test:/media/wrolpi:ro'
|
||||
user: '${UID-1000}:${GID-1000}'
|
||||
# Two render processes are about 600 MB; a phone taking an area offline keeps them busy for minutes, so it
|
||||
# gets less of the CPU than the API.
|
||||
mem_limit: 1200m
|
||||
cpu_shares: 512
|
||||
healthcheck:
|
||||
test: [ 'CMD-SHELL', 'curl -f http://127.0.0.1:9088/tiles/status' ]
|
||||
interval: 2m
|
||||
|
||||
archive: # Python/Sanic wrapper around Singlefile and Readability.
|
||||
build:
|
||||
context: .
|
||||
|
|
@ -111,6 +134,7 @@ services:
|
|||
- app
|
||||
- zim
|
||||
- help
|
||||
- tiles
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/web/Dockerfile
|
||||
|
|
@ -119,6 +143,7 @@ services:
|
|||
- '8084:8084'
|
||||
- '8085:8085'
|
||||
- '8086:8086'
|
||||
- '8088:8088'
|
||||
volumes:
|
||||
- './docker/web/Caddyfile:/etc/caddy/Caddyfile'
|
||||
- './icon.ico:/etc/caddy/favicon.ico'
|
||||
|
|
|
|||
|
|
@ -6,7 +6,9 @@ WORKDIR /opt/wrolpi
|
|||
|
||||
# Update dependencies for the services install.
|
||||
RUN apt-get update && apt-get install -y ffmpeg catdoc sysstat aria2 iputils-ping unrar-free unzip rsync \
|
||||
build-essential libsqlite3-dev zlib1g-dev git
|
||||
build-essential libsqlite3-dev zlib1g-dev git \
|
||||
# Mesa's EGL and GL drivers: the map tile service (tiles/) draws with them, in software here (no GPU).
|
||||
libegl1 libegl-mesa0 libgl1-mesa-dri libgles2
|
||||
|
||||
# Install tippecanoe (for map search index building via tippecanoe-decode).
|
||||
RUN git clone --depth 1 --branch 2.79.0 https://github.com/felt/tippecanoe.git /tmp/tippecanoe \
|
||||
|
|
@ -36,6 +38,14 @@ RUN DENO_VERSION="v2.8.3" \
|
|||
|
||||
# yt-dlp needs cache directory
|
||||
RUN mkdir /.cache && chown -R 1000:1000 /.cache
|
||||
# The planet overview (the world at zoom 0-6) the map tile service draws under the regional maps; Raspberry Pi and
|
||||
# Debian installs have it at the same path. The web image has its own copy, which Caddy serves to the web map.
|
||||
RUN mkdir -p /opt/wrolpi-blobs && \
|
||||
curl -fsSL https://wrolpi.nyc3.cdn.digitaloceanspaces.com/maps/map-overview.pmtiles \
|
||||
-o /opt/wrolpi-blobs/map-overview.pmtiles && \
|
||||
[ -s /opt/wrolpi-blobs/map-overview.pmtiles ]
|
||||
# Where the map tile service keeps drawn tiles (systemd's CacheDirectory on a Raspberry Pi).
|
||||
RUN mkdir -p /var/cache/wrolpi-tiles && chown 1000:1000 /var/cache/wrolpi-tiles
|
||||
|
||||
# Install dependencies from the hash-locked requirements.
|
||||
COPY requirements.txt requirements.lock /opt/wrolpi/
|
||||
|
|
@ -46,6 +56,7 @@ RUN /opt/wrolpi/scripts/install_python_requirements.sh pip3 /opt/wrolpi/requirem
|
|||
COPY main.py /opt/wrolpi/
|
||||
COPY wrolpi /opt/wrolpi/wrolpi
|
||||
COPY modules /opt/wrolpi/modules
|
||||
COPY tiles /opt/wrolpi/tiles
|
||||
|
||||
ENTRYPOINT [ "python3", "/opt/wrolpi/main.py"]
|
||||
# Log level controlled by LOG_LEVEL env var or wrolpi.yaml config (default: info)
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
Subproject commit 647bc56138a7c7f9a8f00c107eccb97cbc32e6aa
|
||||
Subproject commit 32d8746222d6b0ada3a98d2e4d35c6d9c57a1727
|
||||
|
|
@ -63,6 +63,11 @@
|
|||
}
|
||||
|
||||
|
||||
# Map tiles for ATAK and iTAK (tiles/). Also plain HTTP on 8088, below.
|
||||
handle /tiles/* {
|
||||
reverse_proxy tiles:9088
|
||||
}
|
||||
|
||||
# WROLPi blobs (planet overview map, fonts, etc.)
|
||||
handle_path /blobs/* {
|
||||
root * /opt/wrolpi-blobs
|
||||
|
|
@ -111,7 +116,18 @@
|
|||
}
|
||||
|
||||
handle_errors 502 503 504 {
|
||||
redir * "http://{host}:8080/?fallback=true" 302
|
||||
# A tile is never redirected to the fallback page (the tile service is starting, restarting, or down):
|
||||
# ATAK keeps whatever a tile request ends with, so the page would be stored as the tile for good. A 503
|
||||
# is tried again.
|
||||
@tiles path /tiles/*
|
||||
handle @tiles {
|
||||
header Retry-After 1
|
||||
header Cache-Control no-store
|
||||
respond 503
|
||||
}
|
||||
handle {
|
||||
redir * "http://{host}:8080/?fallback=true" 302
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -131,6 +147,22 @@
|
|||
reverse_proxy help:80
|
||||
}
|
||||
|
||||
# Map tiles for ATAK and iTAK over plain HTTP: a phone must trust WROLPi's CA for HTTPS, and only once it has
|
||||
# is the HTTPS map source (/tiles/ on 443) usable.
|
||||
http://:8088 {
|
||||
# /: a page saying what this port is.
|
||||
@tiles path / /tiles /tiles/*
|
||||
handle @tiles {
|
||||
reverse_proxy tiles:9088
|
||||
}
|
||||
handle /favicon.ico {
|
||||
root * /etc/caddy
|
||||
rewrite * /favicon.ico
|
||||
file_server
|
||||
}
|
||||
respond 404
|
||||
}
|
||||
|
||||
# Map viewer - serves MapLibre static assets and PMTiles data via Caddy.
|
||||
:8084 {
|
||||
tls /etc/ssl/caddy/cert.crt /etc/ssl/caddy/cert.key
|
||||
|
|
|
|||
|
|
@ -57,6 +57,11 @@
|
|||
}
|
||||
|
||||
|
||||
# Map tiles for ATAK and iTAK (tiles/). Also plain HTTP on 8088, below.
|
||||
handle /tiles/* {
|
||||
reverse_proxy 127.0.0.1:9088
|
||||
}
|
||||
|
||||
# WROLPi blobs (planet overview map, fonts, etc.)
|
||||
handle_path /blobs/* {
|
||||
root * /opt/wrolpi-blobs
|
||||
|
|
@ -105,7 +110,18 @@
|
|||
}
|
||||
|
||||
handle_errors 502 503 504 {
|
||||
redir * "http://{host}/?fallback=true" 302
|
||||
# A tile is never redirected to the fallback page (the tile service is starting, restarting, or down):
|
||||
# ATAK keeps whatever a tile request ends with, so the page would be stored as the tile for good. A 503
|
||||
# is tried again.
|
||||
@tiles path /tiles/*
|
||||
handle @tiles {
|
||||
header Retry-After 1
|
||||
header Cache-Control no-store
|
||||
respond 503
|
||||
}
|
||||
handle {
|
||||
redir * "http://{host}/?fallback=true" 302
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -125,6 +141,22 @@
|
|||
reverse_proxy 0.0.0.0:9086
|
||||
}
|
||||
|
||||
# Map tiles for ATAK and iTAK over plain HTTP: a phone must trust WROLPi's CA for HTTPS, and only once it has
|
||||
# is the HTTPS map source (/tiles/ on 443) usable.
|
||||
http://:8088 {
|
||||
# /: a page saying what this port is.
|
||||
@tiles path / /tiles /tiles/*
|
||||
handle @tiles {
|
||||
reverse_proxy 127.0.0.1:9088
|
||||
}
|
||||
handle /favicon.ico {
|
||||
root * /opt/wrolpi
|
||||
rewrite * /icon.ico
|
||||
file_server
|
||||
}
|
||||
respond 404
|
||||
}
|
||||
|
||||
# Map viewer - serves MapLibre static assets and PMTiles data via Caddy.
|
||||
:8084 {
|
||||
tls /etc/ssl/wrolpi/cert.crt /etc/ssl/wrolpi/cert.key
|
||||
|
|
|
|||
30
etc/raspberrypios/wrolpi-tiles.service
Normal file
30
etc/raspberrypios/wrolpi-tiles.service
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
[Unit]
|
||||
Description=WROLPi map tiles for ATAK and iTAK
|
||||
PartOf=wrolpi.target
|
||||
|
||||
[Service]
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
# Caddy serves it: HTTPS at /tiles/ on 443, plain HTTP on 8088.
|
||||
ExecStart=/opt/wrolpi/venv/bin/python -O -m tiles --host 127.0.0.1 --port 9088
|
||||
Group=wrolpi
|
||||
User=wrolpi
|
||||
# The GPU (/dev/dri/renderD128); without it tiles are drawn in software, a little slower.
|
||||
SupplementaryGroups=render
|
||||
WorkingDirectory=/opt/wrolpi/
|
||||
# Drawn tiles are kept in /var/cache/wrolpi-tiles (CACHE_DIRECTORY), not on the media drive.
|
||||
CacheDirectory=wrolpi-tiles
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
# A phone taking an area offline keeps this busy for minutes; the API, the App and the user come first.
|
||||
Nice=10
|
||||
CPUWeight=50
|
||||
IOWeight=50
|
||||
# Two render processes are about 600 MB. Past this the service is restarted, rather than the kernel killing
|
||||
# something else. Raspberry Pi OS boots with the memory cgroup disabled (cgroup_disable=memory), so there these
|
||||
# do nothing; OOMScoreAdjust makes this the first the kernel kills when a 4 GB Pi runs out, not the API.
|
||||
MemoryHigh=900M
|
||||
MemoryMax=1200M
|
||||
OOMScoreAdjust=500
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
[Unit]
|
||||
Description=WROLPi services group
|
||||
Wants=wrolpi-controller.service wrolpi-api.service wrolpi-app.service caddy.service wrolpi-kiwix.service wrolpi-rsyncd.service
|
||||
Wants=wrolpi-controller.service wrolpi-api.service wrolpi-app.service caddy.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service
|
||||
|
|
|
|||
|
|
@ -76,3 +76,7 @@ vlc
|
|||
wget
|
||||
zim-tools
|
||||
zlib1g-dev
|
||||
libegl1
|
||||
libegl-mesa0
|
||||
libgl1-mesa-dri
|
||||
libgles2
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ asyncio_mode = auto
|
|||
testpaths =
|
||||
wrolpi
|
||||
modules
|
||||
tiles
|
||||
asyncio_default_fixture_loop_scope = function
|
||||
markers =
|
||||
allow_unexpected_queries: the test trips the serializer query guard on purpose (see wrolpi.db.no_db_access)
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ systemctl stop wrolpi-controller.service || :
|
|||
systemctl stop wrolpi-api.service || :
|
||||
systemctl stop wrolpi-app.service || :
|
||||
systemctl stop wrolpi-kiwix.service || :
|
||||
systemctl stop wrolpi-tiles.service || :
|
||||
systemctl stop caddy || :
|
||||
|
||||
# Clear Python bytecode cache from virtual environments to fix potential corruption.
|
||||
|
|
@ -92,6 +93,7 @@ systemctl enable wrolpi-controller.service
|
|||
systemctl enable wrolpi-api.service
|
||||
systemctl enable wrolpi-app.service
|
||||
systemctl enable wrolpi-kiwix.service
|
||||
systemctl enable wrolpi-tiles.service
|
||||
systemctl enable wrolpi-help.service
|
||||
systemctl enable wrolpi-mounts.service
|
||||
systemctl enable wrolpi-rsyncd.service
|
||||
|
|
|
|||
|
|
@ -1558,6 +1558,11 @@ mako==1.4.3 \
|
|||
--hash=sha256:723296007c870bfd6b3f0c3230dba7198096e5269297ebf5e4eff9e7ffa39d4f \
|
||||
--hash=sha256:cd6537fe88d5fec315c55c2f8529bc4ce7a9a352ad7db3eeaa6a66e2dd4ec37a
|
||||
# via alembic
|
||||
mapli==0.5.0 ; sys_platform == 'linux' \
|
||||
--hash=sha256:3233570f57df1e86b7d53910af543ca00c9a7d2b3c0c108eed7e99ccdae8c6c0 \
|
||||
--hash=sha256:a99f4a9a9855dca828220c10c9e729835b1801c132db04cb3f6c8cbfe912c24b \
|
||||
--hash=sha256:c2e2961f7a48d3bbce86c9ec93c03c7a962e6266215bf2695ad6343d5aa19b09
|
||||
# via -r requirements.txt
|
||||
markupsafe==3.0.4 \
|
||||
--hash=sha256:007e1ffd9bf65bb6ee96df7b258fc632a4868dd5566037986c64781f35a36e98 \
|
||||
--hash=sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002 \
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ feedparser==6.0.14
|
|||
jc==1.26.0
|
||||
libzim==3.13.1
|
||||
mock==5.2.0
|
||||
# MapLibre Native, for the map tile service (tiles/). Linux only: no wheels for macOS.
|
||||
mapli==0.5.0 ; sys_platform == "linux"
|
||||
psutil==7.2.2
|
||||
pydantic>=2.0.0
|
||||
PyMuPDF>=2.0
|
||||
|
|
|
|||
|
|
@ -314,6 +314,15 @@ if ! command -v dnsmasq &>/dev/null || ! command -v iw &>/dev/null || ! command
|
|||
-o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold dnsmasq-base iw rfkill
|
||||
fi
|
||||
|
||||
# Install Mesa's EGL and GL drivers if missing (the map tile service draws with them).
|
||||
if ! ldconfig -p | grep -q 'libEGL.so.1 ' || ! ldconfig -p | grep -q libEGL_mesa \
|
||||
|| ! ldconfig -p | grep -q 'libGLESv2.so.2 '; then
|
||||
echo "Installing libegl1, libegl-mesa0, libgl1-mesa-dri, libgles2..."
|
||||
apt-get update
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
-o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold libegl1 libegl-mesa0 libgl1-mesa-dri libgles2
|
||||
fi
|
||||
|
||||
# Clean up stale landing page (Controller now serves port 80 directly).
|
||||
rm -f /var/www/landing.html
|
||||
|
||||
|
|
|
|||
8
tiles/__init__.py
Normal file
8
tiles/__init__.py
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
"""The tile service: WROLPi's map as raster tiles, for apps which draw only those (ATAK, iTAK).
|
||||
|
||||
A service of its own (wrolpi-tiles), not part of the API: a phone taking an area offline asks for thousands of
|
||||
tiles, each a few dozen milliseconds of CPU, and the API on a Raspberry Pi must stay responsive meanwhile.
|
||||
|
||||
Nothing here imports `wrolpi` or `modules`: importing them costs about a second and 130 MB, and every render
|
||||
process would pay it.
|
||||
"""
|
||||
36
tiles/__main__.py
Normal file
36
tiles/__main__.py
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
"""Run the tile service: `python -m tiles` (see `tiles.service`)."""
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from tiles import maps
|
||||
from tiles.cache import TileCache
|
||||
from tiles.service import DEFAULT_MAX_ZOOM, TileService, create_app
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='WROLPi map tiles for ATAK and iTAK')
|
||||
parser.add_argument('--host', default='127.0.0.1')
|
||||
parser.add_argument('--port', type=int, default=9088)
|
||||
parser.add_argument('--processes', type=int, default=int(os.environ.get('TILES_PROCESSES', 2)),
|
||||
help='Render processes; each is about 250 MB (default 2, or TILES_PROCESSES)')
|
||||
parser.add_argument('--max-zoom', type=int, default=DEFAULT_MAX_ZOOM)
|
||||
parser.add_argument('--cache-directory', type=Path,
|
||||
default=Path(os.environ.get('CACHE_DIRECTORY', '/var/cache/wrolpi-tiles')),
|
||||
help='Where drawn tiles are kept (default: systemd CACHE_DIRECTORY)')
|
||||
parser.add_argument('--cache-mb', type=int, default=int(os.environ.get('TILES_CACHE_MB', 1024)),
|
||||
help='Most the cache may hold, 0 to keep nothing (default 1024, or TILES_CACHE_MB)')
|
||||
parser.add_argument('--min-free-mb', type=int, default=2048,
|
||||
help='Keep no tiles when the disk has less free than this (default 2048)')
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s')
|
||||
cache = TileCache(args.cache_directory, args.cache_mb * 2 ** 20, args.min_free_mb * 2 ** 20)
|
||||
service = TileService(maps.get_map_directory(), cache, processes=args.processes, max_zoom=args.max_zoom)
|
||||
app = create_app(service)
|
||||
app.run(host=args.host, port=args.port, single_process=True, access_log=False, motd=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
10912
tiles/basemap-light.json
Normal file
10912
tiles/basemap-light.json
Normal file
File diff suppressed because it is too large
Load diff
49
tiles/blocks.py
Normal file
49
tiles/blocks.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"""Tiles and the blocks they are drawn in.
|
||||
|
||||
ATAK and iTAK take 256 px tiles in the Web Mercator "XYZ" scheme. A tile is drawn as part of a block of 4x4
|
||||
tiles (one 1024 px image): ATAK asks for the tiles of an area in quadtree order, so 16 requests in a row are of
|
||||
one block, and a block costs about a third of what its 16 tiles cost drawn alone. Labels are whole inside a block.
|
||||
"""
|
||||
import math
|
||||
from typing import Iterator, NamedTuple, Tuple
|
||||
|
||||
TILE_SIZE = 256
|
||||
BLOCK = 4 # tiles on a side of a block
|
||||
# Below this zoom the world is fewer than 4x4 tiles: each is drawn alone (see `render`).
|
||||
MIN_BLOCK_ZOOM = 2
|
||||
MAX_ZOOM = 22
|
||||
|
||||
|
||||
class Block(NamedTuple):
|
||||
z: int
|
||||
x: int # of the block, not of a tile
|
||||
y: int
|
||||
|
||||
def tiles(self) -> Iterator[Tuple[int, int]]:
|
||||
"""The x, y of each tile of the block."""
|
||||
side = BLOCK if self.z >= MIN_BLOCK_ZOOM else 2 ** self.z
|
||||
for dy in range(side):
|
||||
for dx in range(side):
|
||||
yield self.x * side + dx, self.y * side + dy
|
||||
|
||||
|
||||
def is_tile(z: int, x: int, y: int) -> bool:
|
||||
return 0 <= z <= MAX_ZOOM and 0 <= x < 2 ** z and 0 <= y < 2 ** z
|
||||
|
||||
|
||||
def block_of(z: int, x: int, y: int) -> Block:
|
||||
if z < MIN_BLOCK_ZOOM:
|
||||
return Block(z, 0, 0)
|
||||
return Block(z, x // BLOCK, y // BLOCK)
|
||||
|
||||
|
||||
def tile_corner(z: int, x: float, y: float) -> Tuple[float, float]:
|
||||
"""The longitude and latitude of the north-west corner of tile x, y (fractions are inside the tile)."""
|
||||
n = 2 ** z
|
||||
longitude = x / n * 360 - 180
|
||||
latitude = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n))))
|
||||
return longitude, latitude
|
||||
|
||||
|
||||
def block_center(block: Block) -> Tuple[float, float]:
|
||||
return tile_corner(block.z, block.x * BLOCK + BLOCK / 2, block.y * BLOCK + BLOCK / 2)
|
||||
238
tiles/cache.py
Normal file
238
tiles/cache.py
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
"""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
|
||||
149
tiles/maps.py
Normal file
149
tiles/maps.py
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
"""Which map files the tiles are drawn from.
|
||||
|
||||
The tiles are of the basemap: the Protomaps files in the map directory, over the planet overview (the world at
|
||||
zoom 0 to 6) as the web map draws them. A file is a basemap by the rule of `modules.map.pmtiles.classify`, read
|
||||
here without importing it (see `tiles`); a test holds the two to the same answer.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import yaml
|
||||
|
||||
# As `wrolpi.vars`.
|
||||
MEDIA_DIRECTORY = Path(os.environ.get('MEDIA_DIRECTORY', '/media/wrolpi'))
|
||||
# Raspberry Pi and Debian installs have it here; the Docker image puts it at the same path.
|
||||
OVERVIEW = Path('/opt/wrolpi-blobs/map-overview.pmtiles')
|
||||
|
||||
PMTILES_MAGIC = b'PMTiles'
|
||||
PMTILES_HEADER_SIZE = 127
|
||||
PMTILES_MVT = 1
|
||||
PMTILES_GZIP = 2
|
||||
# Larger metadata is not read (as modules.map.pmtiles).
|
||||
MAX_METADATA_SIZE = 16 * 1024 * 1024
|
||||
BASEMAP_LAYERS = frozenset({'earth', 'water', 'roads'})
|
||||
TERRAIN_PREFIX = 'terrain-'
|
||||
|
||||
|
||||
def gunzip(raw: bytes) -> bytes:
|
||||
"""Decompress at most `MAX_METADATA_SIZE`: a few bytes of a downloaded file must not fill the memory. Raises
|
||||
ValueError for more."""
|
||||
decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)
|
||||
out = decompressor.decompress(raw, MAX_METADATA_SIZE)
|
||||
if decompressor.unconsumed_tail:
|
||||
raise ValueError('Decompresses to more than MAX_METADATA_SIZE')
|
||||
return out
|
||||
|
||||
|
||||
def get_map_directory(media_directory: Path = None) -> Path:
|
||||
"""The map directory: `map_destination` of wrolpi.yaml (default `map`) in the media directory."""
|
||||
media_directory = media_directory or MEDIA_DIRECTORY
|
||||
destination = 'map'
|
||||
try:
|
||||
config = yaml.safe_load((media_directory / 'config/wrolpi.yaml').read_text()) or dict()
|
||||
destination = config.get('map_destination') or destination
|
||||
except (OSError, yaml.YAMLError, AttributeError):
|
||||
pass
|
||||
return media_directory / destination
|
||||
|
||||
|
||||
def get_ignored_files(media_directory: Path = None) -> set:
|
||||
"""The map files the user hid on the Manage tab (`ignored_files` of maps.yaml, relative to the map directory,
|
||||
see `modules.map.config.MapsConfig`): the web map does not draw them, so neither do the tiles."""
|
||||
media_directory = media_directory or MEDIA_DIRECTORY
|
||||
try:
|
||||
config = yaml.safe_load((media_directory / 'config/maps.yaml').read_text()) or dict()
|
||||
return {str(i) for i in config.get('ignored_files') or []}
|
||||
except (OSError, yaml.YAMLError, AttributeError, TypeError):
|
||||
return set()
|
||||
|
||||
|
||||
def is_basemap(path: Path) -> bool:
|
||||
"""Whether a PMTiles file is a Protomaps basemap: vector tiles with the layers the basemap theme draws."""
|
||||
if path.name.startswith(TERRAIN_PREFIX):
|
||||
return False
|
||||
try:
|
||||
with path.open('rb') as fh:
|
||||
header = fh.read(PMTILES_HEADER_SIZE)
|
||||
if len(header) < PMTILES_HEADER_SIZE or not header.startswith(PMTILES_MAGIC) or header[7] != 3:
|
||||
return False
|
||||
offset, length = struct.unpack_from('<QQ', header, 24)
|
||||
compression, tile_type = header[97], header[99]
|
||||
if tile_type != PMTILES_MVT or not 0 < length <= MAX_METADATA_SIZE:
|
||||
return False
|
||||
fh.seek(offset)
|
||||
raw = fh.read(length)
|
||||
if compression == PMTILES_GZIP:
|
||||
raw = gunzip(raw)
|
||||
metadata = json.loads(raw)
|
||||
layers = metadata.get('vector_layers') if isinstance(metadata, dict) else None
|
||||
ids = {str(i['id']) for i in layers if isinstance(i, dict) and i.get('id')} if isinstance(layers, list) else set()
|
||||
return BASEMAP_LAYERS <= ids
|
||||
except (OSError, ValueError, EOFError, struct.error, zlib.error):
|
||||
return False
|
||||
|
||||
|
||||
def is_drawable(path: Path) -> bool:
|
||||
"""Whether MapLibre can read a PMTiles file's tiles: its root directory is there and can be decompressed.
|
||||
|
||||
A file it cannot read (empty, cut short, corrupt) fails every tile drawn with it, of every place; such a file
|
||||
is left out."""
|
||||
try:
|
||||
with path.open('rb') as fh:
|
||||
header = fh.read(PMTILES_HEADER_SIZE)
|
||||
if len(header) < PMTILES_HEADER_SIZE or not header.startswith(PMTILES_MAGIC):
|
||||
return False
|
||||
offset, length = struct.unpack_from('<QQ', header, 8)
|
||||
if not 0 < length <= MAX_METADATA_SIZE:
|
||||
return False
|
||||
fh.seek(offset)
|
||||
raw = fh.read(length)
|
||||
if len(raw) != length:
|
||||
return False
|
||||
if header[97] == PMTILES_GZIP:
|
||||
raw = gunzip(raw)
|
||||
return len(raw) > 0
|
||||
except (OSError, ValueError, EOFError, struct.error, zlib.error):
|
||||
return False
|
||||
|
||||
|
||||
def find_basemaps(map_directory: Path, ignored: set = frozenset()) -> List[Path]:
|
||||
"""The basemap files in the map directory (at any depth), sorted, but those `ignored` (paths relative to the
|
||||
map directory). Hidden directories are skipped: an unfinished download waits in one."""
|
||||
paths = []
|
||||
for root, directories, files in os.walk(map_directory):
|
||||
directories[:] = sorted(i for i in directories if not i.startswith('.'))
|
||||
for name in files:
|
||||
path = Path(root) / name
|
||||
if str(path.relative_to(map_directory)) in ignored:
|
||||
continue
|
||||
if name.endswith('.pmtiles') and path.is_file() and is_basemap(path) and is_drawable(path):
|
||||
paths.append(path)
|
||||
return sorted(paths)
|
||||
|
||||
|
||||
Signature = Tuple[Tuple[str, int, int], ...]
|
||||
|
||||
|
||||
def signature(paths: List[Path]) -> Signature:
|
||||
"""What changes when a map file is added, removed or replaced."""
|
||||
entries = []
|
||||
for path in paths:
|
||||
try:
|
||||
stat = path.stat()
|
||||
except OSError:
|
||||
continue
|
||||
entries.append((str(path), stat.st_mtime_ns, stat.st_size))
|
||||
return tuple(entries)
|
||||
|
||||
|
||||
def find_maps(map_directory: Path, overview: Optional[Path] = OVERVIEW, media_directory: Path = None) -> List[Path]:
|
||||
"""The files the tiles are drawn from, in the order they are drawn: the overview, then each basemap the user
|
||||
has not hidden."""
|
||||
maps = find_basemaps(map_directory, get_ignored_files(media_directory))
|
||||
if overview and overview.is_file() and is_drawable(overview):
|
||||
maps.insert(0, overview)
|
||||
return maps
|
||||
86
tiles/render.py
Normal file
86
tiles/render.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
"""Drawing blocks of tiles with MapLibre Native (mapli), in a render process.
|
||||
|
||||
Each render process has one MapLibre renderer, made in the process (`init_process`). It draws with the GPU when
|
||||
the process may open one (/dev/dri/renderD128; on a Raspberry Pi the user must be in the `render` group), and
|
||||
otherwise in software, about 20% slower: the work is mostly the CPU's. No display is needed.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from tiles.blocks import BLOCK, MIN_BLOCK_ZOOM, TILE_SIZE, Block, block_center
|
||||
|
||||
# MapLibre Native needs an OpenGL context; without a display, only Mesa's "surfaceless" platform gives one.
|
||||
os.environ.setdefault('EGL_PLATFORM', 'surfaceless')
|
||||
|
||||
try:
|
||||
import mapli
|
||||
except ImportError: # mapli has wheels for Linux only.
|
||||
mapli = None
|
||||
|
||||
# Tiles are JPEG: ATAK and iTAK decode it, it is a seventh of the size of a PNG of a dense tile, and twice as quick
|
||||
# to make. The map has no transparency to keep.
|
||||
JPEG_QUALITY = 85
|
||||
CONTENT_TYPE = 'image/jpeg'
|
||||
|
||||
_renderer = None
|
||||
_registered = set()
|
||||
|
||||
|
||||
def available() -> bool:
|
||||
return mapli is not None
|
||||
|
||||
|
||||
def init_process():
|
||||
"""Runs once in each render process."""
|
||||
global _renderer
|
||||
if mapli is None:
|
||||
raise RuntimeError('mapli is not installed; the tile service needs it (Linux only)')
|
||||
_renderer = mapli.RenderPool(workers=1)
|
||||
|
||||
|
||||
def encode(image: Image.Image) -> bytes:
|
||||
out = io.BytesIO()
|
||||
image.convert('RGB').save(out, 'JPEG', quality=JPEG_QUALITY)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def blank(color: str) -> bytes:
|
||||
"""A tile of one color: of nowhere the map files have anything, or when a tile could not be drawn in time."""
|
||||
return encode(Image.new('RGB', (TILE_SIZE, TILE_SIZE), color))
|
||||
|
||||
|
||||
def render_block(style_id: str, style: Optional[dict], block: Block) -> Dict[Tuple[int, int], bytes]:
|
||||
"""Draw a block, return the JPEG of each of its tiles.
|
||||
|
||||
`style` is sent the first time a process is asked for `style_id`; after that it may be None."""
|
||||
if style_id not in _registered:
|
||||
if style is None:
|
||||
raise LookupError(style_id)
|
||||
_renderer.register_style(style_id, json=style)
|
||||
_registered.add(style_id)
|
||||
|
||||
if block.z < MIN_BLOCK_ZOOM:
|
||||
# MapLibre cannot draw a 256 px tile at zoom 0 (its zooms count 512 px tiles), so each tile of a world of
|
||||
# fewer than 4x4 is drawn at 512 px and made smaller.
|
||||
tiles = dict()
|
||||
for x, y in block.tiles():
|
||||
raw = _renderer.render_tile(style_id, z=block.z, x=x, y=y, tile_size=TILE_SIZE * 2, output='rgba')
|
||||
image = Image.frombytes('RGBA', (TILE_SIZE * 2, TILE_SIZE * 2), raw)
|
||||
tiles[(x, y)] = encode(image.resize((TILE_SIZE, TILE_SIZE), Image.LANCZOS))
|
||||
return tiles
|
||||
|
||||
side = TILE_SIZE * BLOCK
|
||||
longitude, latitude = block_center(block)
|
||||
# MapLibre's zoom z is of 512 px tiles: the zoom of 256 px tiles less one.
|
||||
raw = _renderer.render(style_id, lon=longitude, lat=latitude, zoom=block.z - 1, width=side, height=side,
|
||||
output='rgba')
|
||||
image = Image.frombytes('RGBA', (side, side), raw)
|
||||
tiles = dict()
|
||||
for x, y in block.tiles():
|
||||
left = (x - block.x * BLOCK) * TILE_SIZE
|
||||
top = (y - block.y * BLOCK) * TILE_SIZE
|
||||
tiles[(x, y)] = encode(image.crop((left, top, left + TILE_SIZE, top + TILE_SIZE)))
|
||||
return tiles
|
||||
421
tiles/service.py
Normal file
421
tiles/service.py
Normal file
|
|
@ -0,0 +1,421 @@
|
|||
"""The tile service's HTTP server.
|
||||
|
||||
GET /, /tiles/ a page saying what this is, for a person who finds the port
|
||||
GET /tiles/{z}/{x}/{y}.jpg a 256 px tile
|
||||
GET /tiles/wrolpi.xml the map source for ATAK and iTAK (MOBAC XML), with this server's address in it
|
||||
GET /tiles/status what the service is doing (the map's ATAK tab shows it)
|
||||
POST /tiles/cache/clear remove the kept tiles (the map's ATAK tab); they are drawn again when asked for
|
||||
|
||||
What ATAK does with a tile server (read from its source, `TileScraper` and `CustomMobacMapSource`), and what this
|
||||
must do because of it:
|
||||
|
||||
- A downloader keeps whatever a tile request returns, whatever the response's headers say: a blank tile sent in
|
||||
place of one which was late would be a hole in the phone's map for good. So a tile not drawn in time
|
||||
(`DEADLINE`, under ATAK's 5 seconds), or which failed, is a 503: ATAK tries each tile twice, and the second
|
||||
try finds the block drawn. Only five tiles in a row failing both tries stop a download, and only a 401 or
|
||||
403 stops a map source; this sends neither. Where there is no map, a tile is drawn of the background.
|
||||
- The render processes are started with the service, not by the first tile: starting one is seconds.
|
||||
- It asks for 4 tiles at a time (iTAK: 6), of the same block. A block is drawn once however many ask for it.
|
||||
- Phones are served in turn, a block of one then a block of the next, so one phone's download does not keep
|
||||
another's tiles waiting past the deadline.
|
||||
"""
|
||||
import asyncio
|
||||
import collections
|
||||
import html
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from concurrent.futures.process import BrokenProcessPool
|
||||
from email.utils import formatdate
|
||||
from pathlib import Path
|
||||
from typing import Deque, Dict, Optional, Tuple
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
from sanic import Sanic, response
|
||||
|
||||
from tiles import maps, render
|
||||
from tiles.blocks import MAX_ZOOM, Block, block_of, is_tile
|
||||
from tiles.cache import TileCache
|
||||
from tiles.style import background_color, build_style, style_id
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ATAK gives up on a tile after 5 seconds; this leaves time for the tile to reach it.
|
||||
DEADLINE = 4.0
|
||||
# How long a phone keeps a tile. ATAK keeps one at least a week whatever this says.
|
||||
EXPIRES_SECONDS = 7 * 24 * 60 * 60
|
||||
# Blocks a client may have waiting. More is a phone which gave up on them; the oldest are dropped.
|
||||
MAX_QUEUED_PER_CLIENT = 64
|
||||
# How often the map directory is looked at for added, replaced and removed map files.
|
||||
WATCH_SECONDS = 30
|
||||
# Tiles per second is counted over this long.
|
||||
RATE_SECONDS = 60
|
||||
# A render process is replaced after drawing this many blocks. MapLibre keeps what it has read and drawn, and
|
||||
# nothing bounds it: on a Raspberry Pi 4 a process grew from about 270 MB to 370 MB over 8,000 blocks (a phone
|
||||
# taking 120,000 tiles offline). Starting one is about 2 seconds, a few minutes apart at most.
|
||||
BLOCKS_PER_PROCESS = 2000
|
||||
DEFAULT_MAX_ZOOM = 17
|
||||
NAME = 'WROLPi Map'
|
||||
|
||||
|
||||
def mobac_xml(base_url: str, name: str, max_zoom: int, background: str = '#cccccc') -> str:
|
||||
"""The MOBAC map source ATAK and iTAK import.
|
||||
|
||||
`backgroundColor` is required by iTAK: without it, it refuses the file ("The data couldn't be read because it
|
||||
is missing"). ATAK ignores it (it reads only `#` and one digit)."""
|
||||
return f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<customMapSource>
|
||||
<name>{escape(name)}</name>
|
||||
<minZoom>0</minZoom>
|
||||
<maxZoom>{max_zoom}</maxZoom>
|
||||
<tileType>jpg</tileType>
|
||||
<tileUpdate>None</tileUpdate>
|
||||
<url>{escape(base_url)}/tiles/{{$z}}/{{$x}}/{{$y}}.jpg</url>
|
||||
<backgroundColor>{escape(background)}</backgroundColor>
|
||||
</customMapSource>
|
||||
'''
|
||||
|
||||
|
||||
class TileService:
|
||||
|
||||
def __init__(self, map_directory: Path, cache: TileCache, processes: int = 2, max_zoom: int = DEFAULT_MAX_ZOOM,
|
||||
overview: Optional[Path] = maps.OVERVIEW):
|
||||
self.map_directory = map_directory
|
||||
self.cache = cache
|
||||
self.processes = processes
|
||||
self.max_zoom = max_zoom
|
||||
self.overview = overview
|
||||
self.maps = []
|
||||
self.signature = None
|
||||
self.style: Optional[dict] = None
|
||||
self.style_id: Optional[str] = None
|
||||
self.blank_tile = b''
|
||||
self.executor: Optional[ProcessPoolExecutor] = None
|
||||
self.inflight: Dict[Tuple[str, Block], asyncio.Future] = dict()
|
||||
self.queues: 'collections.OrderedDict[str, Deque[Tuple[str, Block]]]' = collections.OrderedDict()
|
||||
self.condition: Optional[asyncio.Condition] = None
|
||||
self.tasks = []
|
||||
self.rendering = 0
|
||||
self.stats = collections.Counter()
|
||||
self.clients: Dict[str, dict] = dict()
|
||||
self.served = collections.deque() # times tiles were served, for tiles per second
|
||||
|
||||
# Map files and style.
|
||||
|
||||
def refresh_maps(self) -> bool:
|
||||
"""Draw with the map files now in the map directory. Blocking. True when they changed."""
|
||||
found = maps.find_maps(self.map_directory, self.overview)
|
||||
signature = maps.signature(found)
|
||||
if signature == self.signature:
|
||||
return False
|
||||
self.maps, self.signature = found, signature
|
||||
self.style = build_style(found)
|
||||
self.style_id = style_id(self.style, signature)
|
||||
self.blank_tile = render.blank(background_color(self.style))
|
||||
self.cache.use_style(self.style_id)
|
||||
logger.info(f'Drawing tiles of {len(found)} map files (style {self.style_id})')
|
||||
return True
|
||||
|
||||
async def _watch(self):
|
||||
while True:
|
||||
await asyncio.sleep(WATCH_SECONDS)
|
||||
try:
|
||||
await asyncio.to_thread(self.refresh_maps)
|
||||
except Exception as e:
|
||||
logger.error('Failed to look for map files', exc_info=e)
|
||||
|
||||
# Starting and stopping.
|
||||
|
||||
def _new_executor(self) -> ProcessPoolExecutor:
|
||||
# spawn, not fork: a fork of this process would copy its event loop and threads.
|
||||
return ProcessPoolExecutor(max_workers=self.processes, mp_context=multiprocessing.get_context('spawn'),
|
||||
initializer=render.init_process, max_tasks_per_child=BLOCKS_PER_PROCESS)
|
||||
|
||||
async def start(self):
|
||||
self.condition = asyncio.Condition()
|
||||
await asyncio.to_thread(self.refresh_maps)
|
||||
self.executor = self._new_executor()
|
||||
self.tasks = [asyncio.create_task(self._render_loop()) for _ in range(self.processes)]
|
||||
self.tasks.append(asyncio.create_task(self._watch()))
|
||||
self.tasks.append(asyncio.create_task(self._warm()))
|
||||
|
||||
async def _warm(self):
|
||||
"""Start every render process now, by drawing the world (zoom 0) in each, rather than when the first
|
||||
tiles are asked for."""
|
||||
loop = asyncio.get_running_loop()
|
||||
sid, style, block = self.style_id, self.style, Block(0, 0, 0)
|
||||
started = time.perf_counter()
|
||||
results = await asyncio.gather(
|
||||
*(loop.run_in_executor(self.executor, render.render_block, sid, style, block)
|
||||
for _ in range(self.processes)), return_exceptions=True)
|
||||
errors = [i for i in results if isinstance(i, BaseException)]
|
||||
if errors:
|
||||
logger.error('A render process could not draw', exc_info=errors[0])
|
||||
return
|
||||
await asyncio.to_thread(self.cache.put, block.z, results[0], sid)
|
||||
logger.info(f'{self.processes} render processes ready in {time.perf_counter() - started:.1f}s')
|
||||
|
||||
async def stop(self):
|
||||
for task in self.tasks:
|
||||
task.cancel()
|
||||
if self.executor:
|
||||
self.executor.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
# Drawing.
|
||||
|
||||
async def _next(self) -> Tuple[str, Block]:
|
||||
"""The next block to draw: the oldest of the client whose turn it is."""
|
||||
async with self.condition:
|
||||
await self.condition.wait_for(lambda: bool(self.queues))
|
||||
client, queue = self.queues.popitem(last=False)
|
||||
item = queue.popleft()
|
||||
if queue:
|
||||
self.queues[client] = queue # to the back of the line
|
||||
return item
|
||||
|
||||
async def _render_loop(self):
|
||||
loop = asyncio.get_running_loop()
|
||||
while True:
|
||||
sid, block = await self._next()
|
||||
future = self.inflight.get((sid, block))
|
||||
if future is None or future.done():
|
||||
continue
|
||||
self.rendering += 1
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
tiles = await loop.run_in_executor(self.executor, render.render_block, sid, self.style, block) \
|
||||
if sid == self.style_id else None
|
||||
except BrokenProcessPool as e:
|
||||
# A render process died (the out-of-memory killer, most likely). Start them again.
|
||||
logger.error('A render process died; starting new ones', exc_info=e)
|
||||
self.executor = self._new_executor()
|
||||
tiles, error = None, e
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to draw block {block}', exc_info=e)
|
||||
tiles, error = None, e
|
||||
else:
|
||||
error = None
|
||||
finally:
|
||||
self.rendering -= 1
|
||||
self.inflight.pop((sid, block), None)
|
||||
if tiles:
|
||||
self.stats['blocks_drawn'] += 1
|
||||
self.stats['draw_ms'] += int((time.perf_counter() - started) * 1000)
|
||||
future.set_result(tiles)
|
||||
asyncio.create_task(asyncio.to_thread(self.cache.put, block.z, tiles, sid))
|
||||
elif error:
|
||||
self.stats['blocks_failed'] += 1
|
||||
future.set_exception(error)
|
||||
else:
|
||||
future.set_result(None) # the map files changed while it waited
|
||||
|
||||
async def _queue(self, client: str, sid: str, block: Block) -> asyncio.Future:
|
||||
future = asyncio.get_running_loop().create_future()
|
||||
self.inflight[(sid, block)] = future
|
||||
async with self.condition:
|
||||
queue = self.queues.setdefault(client, collections.deque())
|
||||
queue.append((sid, block))
|
||||
while len(queue) > MAX_QUEUED_PER_CLIENT:
|
||||
dropped = self.inflight.pop(queue.popleft(), None)
|
||||
if dropped and not dropped.done():
|
||||
dropped.set_result(None)
|
||||
self.stats['blocks_dropped'] += 1
|
||||
self.condition.notify()
|
||||
return future
|
||||
|
||||
async def tile(self, z: int, x: int, y: int, client: str) -> Tuple[Optional[bytes], bool]:
|
||||
"""A tile, and whether it may be kept. None when it was not drawn in time or could not be drawn: the
|
||||
phone must ask again (see the top of this module)."""
|
||||
self._seen(client)
|
||||
if not is_tile(z, x, y):
|
||||
self.stats['tiles_outside'] += 1
|
||||
return self.blank_tile, False
|
||||
sid = self.style_id
|
||||
data = await asyncio.to_thread(self.cache.get, z, x, y) if self.cache.enabled else None
|
||||
if data:
|
||||
self.stats['tiles_cached'] += 1
|
||||
return data, True
|
||||
|
||||
block = block_of(z, x, y)
|
||||
future = self.inflight.get((sid, block))
|
||||
if future is None:
|
||||
future = await self._queue(client, sid, block)
|
||||
try:
|
||||
tiles = await asyncio.wait_for(asyncio.shield(future), DEADLINE)
|
||||
except asyncio.TimeoutError:
|
||||
self.stats['tiles_late'] += 1
|
||||
return None, False
|
||||
except Exception:
|
||||
self.stats['tiles_failed'] += 1
|
||||
return None, False
|
||||
if not tiles:
|
||||
self.stats['tiles_dropped'] += 1
|
||||
return None, False
|
||||
self.stats['tiles_drawn'] += 1
|
||||
return tiles[(x, y)], True
|
||||
|
||||
def _seen(self, client: str):
|
||||
now = time.time()
|
||||
entry = self.clients.setdefault(client, dict(tiles=0, first_seen=now))
|
||||
entry['tiles'] += 1
|
||||
entry['last_seen'] = now
|
||||
self.served.append(now)
|
||||
self._forget_served(now)
|
||||
|
||||
def _forget_served(self, now: float):
|
||||
"""Tiles per second is of the last minute: forget tiles served before it (or a long download would keep a
|
||||
time for every tile it took)."""
|
||||
while self.served and self.served[0] < now - RATE_SECONDS:
|
||||
self.served.popleft()
|
||||
|
||||
def status(self) -> dict:
|
||||
now = time.time()
|
||||
self._forget_served(now)
|
||||
for client in [k for k, v in self.clients.items() if v['last_seen'] < now - 24 * 60 * 60]:
|
||||
del self.clients[client]
|
||||
drawn = self.stats['blocks_drawn']
|
||||
return dict(
|
||||
renderer=render.available(),
|
||||
processes=self.processes,
|
||||
max_zoom=self.max_zoom,
|
||||
maps=[str(i) for i in self.maps],
|
||||
style_id=self.style_id,
|
||||
queued_blocks=sum(len(i) for i in self.queues.values()),
|
||||
drawing_blocks=self.rendering,
|
||||
tiles_per_second=round(len(self.served) / RATE_SECONDS, 1),
|
||||
block_ms=round(self.stats['draw_ms'] / drawn) if drawn else None,
|
||||
cache=dict(enabled=self.cache.enabled, bytes=self.cache.size, max_bytes=self.cache.max_bytes),
|
||||
stats=dict(self.stats),
|
||||
clients=[dict(client=k, tiles=v['tiles'], first_seen=round(v['first_seen']),
|
||||
last_seen=round(v['last_seen']),
|
||||
queued_blocks=len(self.queues.get(k, ())))
|
||||
for k, v in sorted(self.clients.items(), key=lambda i: -i[1]['last_seen'])],
|
||||
)
|
||||
|
||||
|
||||
def client_of(request) -> str:
|
||||
"""The phone asking: Caddy puts its address first in X-Forwarded-For."""
|
||||
forwarded = request.headers.get('x-forwarded-for')
|
||||
return forwarded.split(',')[0].strip() if forwarded else request.ip
|
||||
|
||||
|
||||
def base_url_of(request) -> str:
|
||||
"""The address the phone reached this server by, as Caddy says (the LAN, the hotspot, or a name)."""
|
||||
scheme = request.headers.get('x-forwarded-proto') or request.scheme
|
||||
host = request.headers.get('x-forwarded-host') or request.headers.get('host') or request.host
|
||||
return f'{scheme}://{host}'
|
||||
|
||||
|
||||
# The port of the WROLPi app's HTTPS (Caddy), for the page's links to it: 443 on a Raspberry Pi or Debian, the
|
||||
# published port of the web container in Docker (8443 by default).
|
||||
HTTPS_PORT = int(os.environ.get('TILES_HTTPS_PORT', 443))
|
||||
|
||||
INDEX_HTML = '''<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>WROLPi Map Tiles</title>
|
||||
<style>
|
||||
:root {{ color-scheme: light dark; --bg: #f3f4f3; --panel: #fff; --text: #222; --muted: #666; --border: #ccc;
|
||||
--link: #2c5aa0; }}
|
||||
@media (prefers-color-scheme: dark) {{
|
||||
:root {{ --bg: #1b1c1d; --panel: #262728; --text: #ddd; --muted: #999; --border: #444; --link: #8ab4f8; }}
|
||||
}}
|
||||
body {{ margin: 0; padding: 16px; background: var(--bg); color: var(--text);
|
||||
font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }}
|
||||
main {{ max-width: 42rem; margin: 2rem auto; background: var(--panel); border: 1px solid var(--border);
|
||||
border-radius: 6px; padding: 1.5rem; }}
|
||||
h1 {{ margin-top: 0; font-size: 1.5rem; }}
|
||||
a {{ color: var(--link); }}
|
||||
code {{ word-break: break-all; }}
|
||||
.muted {{ color: var(--muted); font-size: 0.875rem; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>WROLPi Map Tiles</h1>
|
||||
<p>This is the map tile service of a <a href="{app}">WROLPi</a>. It draws the WROLPi's map as tiles for
|
||||
ATAK (Android) and iTAK (iPhone), which can use it as a map source and download areas of it for offline use.</p>
|
||||
<p>To add the map to ATAK or iTAK, open this map source on the phone and open the file it downloads with the app:</p>
|
||||
<p><a href="{xml}"><code>{xml}</code></a></p>
|
||||
<p>The map's <a href="{atak}">ATAK tab</a> on the WROLPi has the steps, and what the tile service is doing.</p>
|
||||
<p class="muted">{maps} · Map data © OpenStreetMap contributors</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
'''
|
||||
|
||||
|
||||
def index_html(base_url: str, map_count: int) -> str:
|
||||
"""The page a person finds at this port: what it is, and links to the map source and to WROLPi."""
|
||||
hostname = urlsplit(base_url).hostname or 'localhost'
|
||||
if ':' in hostname:
|
||||
hostname = f'[{hostname}]' # IPv6
|
||||
app = f'https://{hostname}' + (f':{HTTPS_PORT}' if HTTPS_PORT != 443 else '')
|
||||
maps_text = f'Drawn from {map_count} map file{"" if map_count == 1 else "s"}' if map_count else \
|
||||
'There are no map files yet; download some on the WROLPi\'s Map page'
|
||||
return INDEX_HTML.format(app=html.escape(f'{app}/'), atak=html.escape(f'{app}/map/atak'),
|
||||
xml=html.escape(f'{base_url}/tiles/wrolpi.xml'), maps=html.escape(maps_text))
|
||||
|
||||
|
||||
def create_app(service: TileService, name: str = 'wrolpi_tiles') -> Sanic:
|
||||
app = Sanic(name)
|
||||
# sanic-ext (installed for the API) would add OpenAPI docs and more, for nothing: seconds of startup on a Pi.
|
||||
app.config.AUTO_EXTEND = False
|
||||
app.ctx.service = service
|
||||
|
||||
@app.before_server_start
|
||||
async def start(app_):
|
||||
await app_.ctx.service.start()
|
||||
|
||||
@app.after_server_stop
|
||||
async def stop(app_):
|
||||
await app_.ctx.service.stop()
|
||||
|
||||
@app.get('/tiles/<z:int>/<x:int>/<name:str>')
|
||||
async def get_tile(request, z: int, x: int, name: str):
|
||||
y, _, suffix = name.partition('.')
|
||||
if suffix != 'jpg' or not y.isdigit():
|
||||
return response.text('not found', status=404)
|
||||
data, keep = await app.ctx.service.tile(z, x, int(y), client_of(request))
|
||||
if data is None:
|
||||
# Not a 401 or 403: those stop an ATAK map source.
|
||||
return response.text('Not drawn yet, try again', status=503,
|
||||
headers={'Retry-After': '1', 'Cache-Control': 'no-store'})
|
||||
if keep:
|
||||
headers = {'Cache-Control': f'max-age={EXPIRES_SECONDS}',
|
||||
'Expires': formatdate(time.time() + EXPIRES_SECONDS, usegmt=True)}
|
||||
else:
|
||||
headers = {'Cache-Control': 'no-store', 'Expires': formatdate(0, usegmt=True)}
|
||||
return response.raw(data, content_type=render.CONTENT_TYPE, headers=headers)
|
||||
|
||||
@app.get('/', name='index')
|
||||
@app.get('/tiles', name='tiles_index', strict_slashes=False)
|
||||
async def get_index(request):
|
||||
return response.html(index_html(base_url_of(request), len(app.ctx.service.maps)))
|
||||
|
||||
@app.get('/tiles/wrolpi.xml')
|
||||
async def get_xml(request):
|
||||
base_url = base_url_of(request)
|
||||
https = base_url.startswith('https:')
|
||||
name = f'{NAME} (HTTPS)' if https else NAME
|
||||
filename = 'wrolpi-map-https.xml' if https else 'wrolpi-map.xml'
|
||||
service_ = app.ctx.service
|
||||
background = background_color(service_.style) if service_.style else '#cccccc'
|
||||
return response.text(mobac_xml(base_url, name, service_.max_zoom, background), content_type='application/xml',
|
||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||
|
||||
@app.get('/tiles/status')
|
||||
async def get_status(request):
|
||||
return response.json(app.ctx.service.status())
|
||||
|
||||
@app.post('/tiles/cache/clear')
|
||||
async def post_clear_cache(request):
|
||||
freed = await asyncio.to_thread(app.ctx.service.cache.clear)
|
||||
return response.json(dict(freed_bytes=freed))
|
||||
|
||||
return app
|
||||
85
tiles/style.py
Normal file
85
tiles/style.py
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
"""The MapLibre style the tiles are drawn with: the web map's basemap (MapViewer's `buildStyle`) for map files on
|
||||
the disk.
|
||||
|
||||
`basemap-light.json` is the layers of the web map's light basemap, written from protomaps-themes-base (see
|
||||
app/src/components/mapTileStyle.test.js), for a source named `protomaps`. Each map file gets a source and the
|
||||
layers of its own. As on the web map: the first file's layers are as they are, every later file's are renamed
|
||||
and leave out the background and the earth (which would cover the files before it), and every label is over the
|
||||
ground of every file.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LAYERS_FILE = Path(__file__).with_name('basemap-light.json')
|
||||
STATIC = Path(__file__).resolve().parents[1] / 'modules/map/static'
|
||||
TEMPLATE_SOURCE = 'protomaps'
|
||||
SKIP_SECONDARY = frozenset({'background', 'earth'})
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _template() -> str:
|
||||
return LAYERS_FILE.read_text()
|
||||
|
||||
|
||||
def basemap_layers(source: str) -> List[dict]:
|
||||
layers = json.loads(_template())
|
||||
for layer in layers:
|
||||
if layer.get('source') == TEMPLATE_SOURCE:
|
||||
layer['source'] = source
|
||||
return layers
|
||||
|
||||
|
||||
def has_fonts(static: Path = STATIC) -> bool:
|
||||
"""Whether the map's fonts are installed (unpacked from a blob, not in the repository)."""
|
||||
return any((static / 'fonts').glob('*/0-255.pbf'))
|
||||
|
||||
|
||||
def build_style(maps: List[Path], static: Path = STATIC) -> dict:
|
||||
"""The style which draws these PMTiles files, the first under the rest.
|
||||
|
||||
Without the map's fonts a label cannot be drawn, and MapLibre fails the whole tile; the labels are left out."""
|
||||
sources = dict()
|
||||
layers = []
|
||||
for index, path in enumerate(maps):
|
||||
name = f'{index}-{path.stem}'
|
||||
sources[name] = dict(type='vector', url=f'pmtiles://file://{path}')
|
||||
for layer in basemap_layers(name):
|
||||
if index == 0:
|
||||
layers.append(layer)
|
||||
elif layer['id'] not in SKIP_SECONDARY:
|
||||
layers.append(dict(layer, id=f'{name}:{layer["id"]}'))
|
||||
if not sources:
|
||||
# No map files: the background alone, which every tile is drawn as.
|
||||
layers = [i for i in basemap_layers(TEMPLATE_SOURCE) if i['type'] == 'background']
|
||||
labels = [i for i in layers if i['type'] == 'symbol']
|
||||
layers = [i for i in layers if i['type'] != 'symbol']
|
||||
style = dict(version=8, sprite=f'file://{static}/sprites/light', sources=sources)
|
||||
if has_fonts(static):
|
||||
style['glyphs'] = f'file://{static}/fonts/{{fontstack}}/{{range}}.pbf'
|
||||
layers += labels # over the ground of every file
|
||||
elif labels:
|
||||
logger.warning(f'The map fonts are not in {static / "fonts"}: tiles are drawn without labels')
|
||||
style['layers'] = layers
|
||||
return style
|
||||
|
||||
|
||||
def style_id(style: dict, signature) -> str:
|
||||
"""Names a style and the map files it draws: tiles drawn with one are never served for another."""
|
||||
digest = hashlib.sha256(json.dumps([style, signature], sort_keys=True).encode()).hexdigest()
|
||||
return digest[:16]
|
||||
|
||||
|
||||
def background_color(style: dict) -> str:
|
||||
"""The color of a tile of nowhere the map files have anything (`#rrggbb`)."""
|
||||
for layer in style['layers']:
|
||||
if layer['type'] == 'background':
|
||||
color = layer.get('paint', {}).get('background-color')
|
||||
if isinstance(color, str) and color.startswith('#') and len(color) in (4, 7):
|
||||
return color
|
||||
return '#cccccc'
|
||||
0
tiles/test/__init__.py
Normal file
0
tiles/test/__init__.py
Normal file
600
tiles/test/test_tiles.py
Normal file
600
tiles/test/test_tiles.py
Normal file
|
|
@ -0,0 +1,600 @@
|
|||
import asyncio
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ElementTree
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from modules.map import pmtiles as map_pmtiles
|
||||
from modules.map.conftest import PROTOMAPS_LAYERS, pmtiles_bytes, vector_metadata
|
||||
from tiles import maps, render, service as tile_service
|
||||
from tiles.blocks import BLOCK, Block, block_center, block_of, is_tile, tile_corner
|
||||
from tiles.cache import TileCache, disk_size
|
||||
from tiles.service import TileService, create_app, index_html, mobac_xml
|
||||
from tiles.style import SKIP_SECONDARY, background_color, basemap_layers, build_style, style_id
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def media_directory(tmp_path, monkeypatch) -> Path:
|
||||
"""The tile service reads configs (wrolpi.yaml, maps.yaml) from a media directory of the test's own."""
|
||||
monkeypatch.setattr(maps, 'MEDIA_DIRECTORY', tmp_path / 'media')
|
||||
return tmp_path / 'media'
|
||||
|
||||
|
||||
def write_header_only(path: Path, metadata=None, **kwargs) -> Path:
|
||||
"""A PMTiles file with a header and metadata but no tiles (as modules.map's tests make)."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if metadata is None and kwargs.get('tile_type', 1) == 1:
|
||||
metadata = vector_metadata(*PROTOMAPS_LAYERS)
|
||||
path.write_bytes(pmtiles_bytes(metadata, **kwargs))
|
||||
return path
|
||||
|
||||
|
||||
def varint(n: int) -> bytes:
|
||||
out = bytearray()
|
||||
while True:
|
||||
byte, n = n & 0x7f, n >> 7
|
||||
out.append(byte | 0x80 if n else byte)
|
||||
if not n:
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def write_pmtiles(path: Path, metadata: dict = None) -> Path:
|
||||
"""A PMTiles (version 3) file MapLibre can read: one empty vector tile, of the whole world at zoom 0."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
metadata = metadata if metadata is not None else vector_metadata(*PROTOMAPS_LAYERS)
|
||||
tile = gzip.compress(b'')
|
||||
# One entry: tile id 0, run length 1, its length, offset 0 (written as offset + 1).
|
||||
root = gzip.compress(varint(1) + varint(0) + varint(1) + varint(len(tile)) + varint(1))
|
||||
raw_metadata = gzip.compress(json.dumps(metadata).encode())
|
||||
header = bytearray(127)
|
||||
header[0:7] = b'PMTiles'
|
||||
header[7] = 3
|
||||
root_offset = 127
|
||||
metadata_offset = root_offset + len(root)
|
||||
tiles_offset = metadata_offset + len(raw_metadata)
|
||||
struct.pack_into('<QQQQQQQQ', header, 8, root_offset, len(root), metadata_offset, len(raw_metadata),
|
||||
tiles_offset, 0, tiles_offset, len(tile))
|
||||
struct.pack_into('<QQQ', header, 72, 1, 1, 1)
|
||||
# Clustered, gzip directories, gzip tiles, vector, zoom 0 to 0.
|
||||
struct.pack_into('<6B', header, 96, 1, 2, 2, 1, 0, 0)
|
||||
struct.pack_into('<4i', header, 102, -1800000000, -850000000, 1800000000, 850000000)
|
||||
path.write_bytes(bytes(header) + root + raw_metadata + tile)
|
||||
return path
|
||||
|
||||
|
||||
# Map files.
|
||||
|
||||
@pytest.mark.parametrize('name,metadata,kwargs', [
|
||||
('basemap.pmtiles', None, dict()),
|
||||
('uncompressed.pmtiles', None, dict(compress=False)),
|
||||
('roads-only.pmtiles', vector_metadata('roads'), dict()),
|
||||
('overlay.pmtiles', vector_metadata('trails', 'campsites'), dict()),
|
||||
('raster.pmtiles', None, dict(tile_type=2)),
|
||||
('terrain-z0-8.pmtiles', None, dict()),
|
||||
('no-layers.pmtiles', dict(name='x'), dict()),
|
||||
])
|
||||
def test_is_basemap_agrees_with_the_map(tmp_path, name, metadata, kwargs):
|
||||
"""The tile service decides what a basemap is without importing modules.map; both must say the same."""
|
||||
path = write_header_only(tmp_path / name, metadata, **kwargs)
|
||||
expected = map_pmtiles.classify(path.name, map_pmtiles.read_pmtiles_info(path)) == map_pmtiles.KIND_BASEMAP
|
||||
assert maps.is_basemap(path) is expected
|
||||
|
||||
|
||||
def test_is_basemap_unreadable(tmp_path):
|
||||
(tmp_path / 'junk.pmtiles').write_bytes(b'not a map')
|
||||
(tmp_path / 'empty.pmtiles').write_bytes(b'')
|
||||
assert not maps.is_basemap(tmp_path / 'junk.pmtiles')
|
||||
assert not maps.is_basemap(tmp_path / 'empty.pmtiles')
|
||||
assert not maps.is_basemap(tmp_path / 'missing.pmtiles')
|
||||
|
||||
|
||||
def test_is_drawable(tmp_path):
|
||||
"""A file MapLibre cannot read would fail every tile, so it is left out."""
|
||||
assert maps.is_drawable(write_pmtiles(tmp_path / 'good.pmtiles'))
|
||||
# No tiles: an empty root directory.
|
||||
assert not maps.is_drawable(write_header_only(tmp_path / 'empty.pmtiles'))
|
||||
# Cut short.
|
||||
data = (tmp_path / 'good.pmtiles').read_bytes()
|
||||
(tmp_path / 'short.pmtiles').write_bytes(data[:140])
|
||||
assert not maps.is_drawable(tmp_path / 'short.pmtiles')
|
||||
# A corrupt root directory.
|
||||
(tmp_path / 'corrupt.pmtiles').write_bytes(data[:127] + b'x' * (len(data) - 127))
|
||||
assert not maps.is_drawable(tmp_path / 'corrupt.pmtiles')
|
||||
assert not maps.is_drawable(tmp_path / 'missing.pmtiles')
|
||||
|
||||
(tmp_path / 'map').mkdir()
|
||||
for name in ('empty.pmtiles', 'short.pmtiles', 'corrupt.pmtiles', 'good.pmtiles'):
|
||||
(tmp_path / 'map' / name).write_bytes((tmp_path / name).read_bytes())
|
||||
assert maps.find_basemaps(tmp_path / 'map') == [tmp_path / 'map/good.pmtiles']
|
||||
|
||||
|
||||
def test_decompression_is_bounded(tmp_path, monkeypatch):
|
||||
"""Metadata or a directory which decompresses to more than MAX_METADATA_SIZE is not read."""
|
||||
monkeypatch.setattr(maps, 'MAX_METADATA_SIZE', 1000)
|
||||
bomb = gzip.compress(b'0' * 100_000) # small, but 100 KB decompressed
|
||||
with pytest.raises(ValueError):
|
||||
maps.gunzip(bomb)
|
||||
assert maps.gunzip(gzip.compress(b'ok')) == b'ok'
|
||||
# Metadata padded past the limit.
|
||||
path = write_header_only(tmp_path / 'big.pmtiles', vector_metadata(*PROTOMAPS_LAYERS, padding='x' * 100_000))
|
||||
assert not maps.is_basemap(path)
|
||||
|
||||
|
||||
def test_find_maps(tmp_path):
|
||||
write_pmtiles(tmp_path / 'map/b.pmtiles')
|
||||
write_pmtiles(tmp_path / 'map/region/a.pmtiles')
|
||||
write_pmtiles(tmp_path / 'map/.partial/c.pmtiles') # an unfinished download
|
||||
write_pmtiles(tmp_path / 'map/overlay.pmtiles', vector_metadata('trails'))
|
||||
write_header_only(tmp_path / 'map/no-tiles.pmtiles')
|
||||
overview = write_pmtiles(tmp_path / 'blobs/map-overview.pmtiles')
|
||||
|
||||
assert maps.find_basemaps(tmp_path / 'map') == [tmp_path / 'map/b.pmtiles', tmp_path / 'map/region/a.pmtiles']
|
||||
# The overview is under every other file.
|
||||
assert maps.find_maps(tmp_path / 'map', overview)[0] == overview
|
||||
assert maps.find_maps(tmp_path / 'map', tmp_path / 'missing.pmtiles') == maps.find_basemaps(tmp_path / 'map')
|
||||
|
||||
|
||||
def test_find_maps_leaves_out_hidden_files(tmp_path):
|
||||
"""A map file hidden on the Manage tab (maps.yaml's ignored_files) is not drawn, as on the web map."""
|
||||
write_pmtiles(tmp_path / 'map/a.pmtiles')
|
||||
write_pmtiles(tmp_path / 'map/region/b.pmtiles')
|
||||
assert len(maps.find_maps(tmp_path / 'map', None, tmp_path)) == 2
|
||||
|
||||
(tmp_path / 'config').mkdir()
|
||||
(tmp_path / 'config/maps.yaml').write_text('version: 1\nignored_files:\n- region/b.pmtiles\n')
|
||||
assert maps.find_maps(tmp_path / 'map', None, tmp_path) == [tmp_path / 'map/a.pmtiles']
|
||||
# A broken config hides nothing.
|
||||
(tmp_path / 'config/maps.yaml').write_text('ignored_files: [')
|
||||
assert len(maps.find_maps(tmp_path / 'map', None, tmp_path)) == 2
|
||||
|
||||
|
||||
def test_get_map_directory(tmp_path):
|
||||
assert maps.get_map_directory(tmp_path) == tmp_path / 'map'
|
||||
(tmp_path / 'config').mkdir()
|
||||
(tmp_path / 'config/wrolpi.yaml').write_text('map_destination: maps/osm\n')
|
||||
assert maps.get_map_directory(tmp_path) == tmp_path / 'maps/osm'
|
||||
(tmp_path / 'config/wrolpi.yaml').write_text(': not yaml [')
|
||||
assert maps.get_map_directory(tmp_path) == tmp_path / 'map'
|
||||
|
||||
|
||||
# Style.
|
||||
|
||||
def make_static(directory: Path) -> Path:
|
||||
"""The map's static directory, with a font installed."""
|
||||
(directory / 'fonts/Noto Sans Regular').mkdir(parents=True)
|
||||
(directory / 'fonts/Noto Sans Regular/0-255.pbf').write_bytes(b'')
|
||||
return directory
|
||||
|
||||
|
||||
def test_build_style_as_the_web_map(tmp_path):
|
||||
first, second = tmp_path / 'overview.pmtiles', tmp_path / 'mexico.pmtiles'
|
||||
static = make_static(tmp_path / 'static')
|
||||
style = build_style([first, second], static=static)
|
||||
|
||||
assert style['sources'] == {
|
||||
'0-overview': dict(type='vector', url=f'pmtiles://file://{first}'),
|
||||
'1-mexico': dict(type='vector', url=f'pmtiles://file://{second}'),
|
||||
}
|
||||
ids = [i['id'] for i in style['layers']]
|
||||
assert len(ids) == len(set(ids)), 'layer ids must be unique'
|
||||
template = basemap_layers('x')
|
||||
# Every layer of the first file; the second file's renamed, without what would cover the first.
|
||||
assert {'background', 'earth'} <= set(ids)
|
||||
assert len(ids) == 2 * len(template) - len(SKIP_SECONDARY)
|
||||
assert not {f'1-mexico:{i}' for i in SKIP_SECONDARY} & set(ids)
|
||||
assert {i['source'] for i in style['layers'] if i['id'].startswith('1-mexico:')} == {'1-mexico'}
|
||||
# Every label is over the ground of every file.
|
||||
types = [i['type'] for i in style['layers']]
|
||||
assert types.index('symbol') > max(i for i, t in enumerate(types) if t != 'symbol')
|
||||
assert style['glyphs'] == f'file://{static}/fonts/{{fontstack}}/{{range}}.pbf'
|
||||
assert style['sprite'] == f'file://{static}/sprites/light'
|
||||
|
||||
|
||||
def test_build_style_without_fonts(tmp_path):
|
||||
"""Without the fonts MapLibre fails every tile with a label; the map is drawn without them."""
|
||||
style = build_style([tmp_path / 'a.pmtiles'], static=tmp_path / 'static')
|
||||
assert 'glyphs' not in style
|
||||
assert style['layers'] and not [i for i in style['layers'] if i['type'] == 'symbol']
|
||||
|
||||
make_static(tmp_path / 'static')
|
||||
assert [i for i in build_style([tmp_path / 'a.pmtiles'], static=tmp_path / 'static')['layers']
|
||||
if i['type'] == 'symbol']
|
||||
|
||||
|
||||
def test_build_style_without_maps():
|
||||
style = build_style([])
|
||||
assert style['sources'] == dict()
|
||||
assert [i['type'] for i in style['layers']] == ['background']
|
||||
assert background_color(style).startswith('#')
|
||||
|
||||
|
||||
def test_style_id():
|
||||
style = build_style([Path('/a.pmtiles')])
|
||||
assert style_id(style, (('/a.pmtiles', 1, 2),)) == style_id(style, (('/a.pmtiles', 1, 2),))
|
||||
assert style_id(style, (('/a.pmtiles', 1, 2),)) != style_id(style, (('/a.pmtiles', 3, 2),))
|
||||
|
||||
|
||||
# Blocks.
|
||||
|
||||
def test_blocks():
|
||||
assert block_of(15, 7361, 14583) == Block(15, 1840, 3645)
|
||||
assert list(Block(15, 1840, 3645).tiles())[0] == (7360, 14580)
|
||||
assert len(list(Block(15, 1840, 3645).tiles())) == BLOCK * BLOCK
|
||||
# Below zoom 2 the world is the block.
|
||||
assert block_of(1, 1, 1) == Block(1, 0, 0)
|
||||
assert sorted(Block(1, 0, 0).tiles()) == [(0, 0), (0, 1), (1, 0), (1, 1)]
|
||||
assert list(Block(0, 0, 0).tiles()) == [(0, 0)]
|
||||
# The center of a block is the corner its middle four tiles share.
|
||||
assert block_center(Block(15, 1840, 3645)) == tile_corner(15, 7362, 14582)
|
||||
assert tile_corner(1, 1, 1) == (0, 0)
|
||||
assert is_tile(0, 0, 0) and not is_tile(3, 8, 0) and not is_tile(-1, 0, 0) and not is_tile(30, 0, 0)
|
||||
|
||||
|
||||
# Cache.
|
||||
|
||||
def du(directory: Path) -> int:
|
||||
"""What the tiles in a directory take of the disk, as `du` counts it."""
|
||||
return sum(disk_size(i.stat()) for i in directory.rglob('*.jpg'))
|
||||
|
||||
|
||||
def test_cache(tmp_path):
|
||||
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
|
||||
cache.use_style('a')
|
||||
cache.put(15, {(1, 2): b'one', (1, 3): b'two'}, 'a')
|
||||
assert cache.get(15, 1, 2) == b'one' and cache.get(15, 1, 3) == b'two'
|
||||
assert cache.get(15, 9, 9) is None
|
||||
# Measured as the disk measures it: a whole block for each little file, not its bytes.
|
||||
assert cache.size == du(tmp_path / 'cache/a') >= 2 * 512
|
||||
# A tile drawn again replaces itself; it is not counted twice.
|
||||
cache.put(15, {(1, 2): b'one again'}, 'a')
|
||||
assert cache.size == du(tmp_path / 'cache/a')
|
||||
|
||||
# Tiles of a style no longer drawn are not kept, and a new style removes the old.
|
||||
cache.put(15, {(5, 5): b'old'}, 'gone')
|
||||
assert cache.get(15, 5, 5) is None
|
||||
cache.use_style('b')
|
||||
assert cache.get(15, 1, 2) is None
|
||||
assert not (tmp_path / 'cache/a').exists()
|
||||
assert cache.size == 0
|
||||
cache.wait_for_deletes(5)
|
||||
assert [i.name for i in (tmp_path / 'cache').iterdir()] == []
|
||||
|
||||
# A kept cache is counted again when the service starts.
|
||||
cache.put(3, {(0, 0): b'x' * 100}, 'b')
|
||||
again = TileCache(tmp_path / 'cache', 10_000_000, 0)
|
||||
again.use_style('b')
|
||||
assert again.size == du(tmp_path / 'cache/b') > 0
|
||||
|
||||
|
||||
def test_cache_clear(tmp_path):
|
||||
"""Clearing is at once: the tiles are moved out of the way, and deleted in the background."""
|
||||
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
|
||||
cache.use_style('a')
|
||||
cache.put(15, {(x, 0): b'tile' for x in range(50)}, 'a')
|
||||
size = cache.size
|
||||
|
||||
assert cache.clear() == size > 0
|
||||
assert cache.size == 0 and cache.get(15, 1, 0) is None
|
||||
assert not (tmp_path / 'cache/a').exists()
|
||||
# Tiles are kept again at once, beside the old ones being deleted.
|
||||
cache.put(15, {(1, 0): b'new'}, 'a')
|
||||
assert cache.get(15, 1, 0) == b'new' and cache.size == du(tmp_path / 'cache/a')
|
||||
cache.wait_for_deletes(5)
|
||||
assert sorted(i.name for i in (tmp_path / 'cache').iterdir()) == ['a']
|
||||
assert TileCache(tmp_path / 'off', 0, 0).clear() == 0
|
||||
|
||||
|
||||
def test_cache_finishes_deleting_at_start(tmp_path):
|
||||
"""A deletion cut short (the service restarted) is finished when the service starts again."""
|
||||
leftover = tmp_path / 'cache/.trash-a-1234abcd/15/1'
|
||||
leftover.mkdir(parents=True)
|
||||
(leftover / '2.jpg').write_bytes(b'old')
|
||||
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
|
||||
cache.use_style('b')
|
||||
cache.wait_for_deletes(5)
|
||||
assert list((tmp_path / 'cache').iterdir()) == []
|
||||
|
||||
|
||||
def test_cache_evicts_oldest(tmp_path):
|
||||
probe = TileCache(tmp_path / 'probe', max_bytes=10_000_000, min_free_bytes=0)
|
||||
probe.use_style('a')
|
||||
probe.put(10, {(0, 0): b'x' * 200}, 'a')
|
||||
tile = probe.size # one tile, on this disk
|
||||
|
||||
cache = TileCache(tmp_path / 'cache', max_bytes=5 * tile, min_free_bytes=0)
|
||||
cache.use_style('a')
|
||||
for x in range(10):
|
||||
cache.put(10, {(x, 0): b'x' * 200}, 'a')
|
||||
cache.wait_for_deletes(5) # evicting is in the background
|
||||
time.sleep(0.01)
|
||||
assert cache.size == du(tmp_path / 'cache/a') <= 5 * tile * 0.8
|
||||
assert cache.get(10, 9, 0) # the newest are kept
|
||||
assert cache.get(10, 0, 0) is None
|
||||
|
||||
|
||||
def test_cache_evicts_in_the_background(tmp_path, monkeypatch):
|
||||
"""A tile request which fills the cache does not wait while the oldest tiles are found and deleted."""
|
||||
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
|
||||
cache.use_style('a')
|
||||
cache.put(10, {(x, 0): b'x' * 200 for x in range(20)}, 'a')
|
||||
|
||||
started, release = threading.Event(), threading.Event()
|
||||
real_evict = cache._evict
|
||||
|
||||
def slow_evict(style_id):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
real_evict(style_id)
|
||||
|
||||
monkeypatch.setattr(cache, '_evict', slow_evict)
|
||||
cache.max_bytes = cache.size # the next tile fills it
|
||||
begun = time.perf_counter()
|
||||
cache.put(10, {(99, 0): b'new'}, 'a')
|
||||
assert time.perf_counter() - begun < 1 and started.wait(5)
|
||||
# Kept while evicting is still counted after.
|
||||
cache.put(10, {(98, 0): b'newer'}, 'a')
|
||||
release.set()
|
||||
cache.wait_for_deletes(5)
|
||||
assert cache.size == du(tmp_path / 'cache/a') <= cache.max_bytes * 0.8
|
||||
assert cache.get(10, 98, 0) == b'newer'
|
||||
|
||||
|
||||
def test_cache_disabled_or_disk_full(tmp_path):
|
||||
disabled = TileCache(tmp_path / 'off', max_bytes=0, min_free_bytes=0)
|
||||
disabled.use_style('a')
|
||||
disabled.put(1, {(0, 0): b'x'}, 'a')
|
||||
assert disabled.get(1, 0, 0) is None and not (tmp_path / 'off').exists()
|
||||
|
||||
full = TileCache(tmp_path / 'full', max_bytes=1000, min_free_bytes=2 ** 62)
|
||||
full.use_style('a')
|
||||
full.put(1, {(0, 0): b'x'}, 'a')
|
||||
assert full.get(1, 0, 0) is None
|
||||
|
||||
|
||||
# The map source file.
|
||||
|
||||
def test_mobac_xml():
|
||||
root = ElementTree.fromstring(mobac_xml('http://192.0.2.8:8088', 'WROLPi & Map', 17).encode())
|
||||
assert root.tag == 'customMapSource'
|
||||
assert root.findtext('name') == 'WROLPi & Map'
|
||||
assert root.findtext('url') == 'http://192.0.2.8:8088/tiles/{$z}/{$x}/{$y}.jpg'
|
||||
# ATAK requires a maxZoom.
|
||||
assert (root.findtext('minZoom'), root.findtext('maxZoom')) == ('0', '17')
|
||||
# iTAK refuses a map source without one.
|
||||
assert root.findtext('backgroundColor') == '#cccccc'
|
||||
|
||||
|
||||
def test_index_html(monkeypatch):
|
||||
"""The page a person finds on port 8088 says what it is and links to the map source and to WROLPi."""
|
||||
page = index_html('http://192.0.2.8:8088', 5)
|
||||
assert 'WROLPi Map Tiles' in page and 'ATAK' in page and 'iTAK' in page
|
||||
assert 'href="http://192.0.2.8:8088/tiles/wrolpi.xml"' in page
|
||||
assert 'href="https://192.0.2.8/"' in page and 'href="https://192.0.2.8/map/atak"' in page
|
||||
assert 'Drawn from 5 map files' in page
|
||||
assert 'There are no map files' in index_html('https://wrolpi.local', 0)
|
||||
# Offline: nothing from elsewhere.
|
||||
assert 'src=' not in page and '<link' not in page
|
||||
|
||||
# Docker publishes the WROLPi app on another port.
|
||||
monkeypatch.setattr(tile_service, 'HTTPS_PORT', 8443)
|
||||
assert 'href="https://wrolpi.local:8443/map/atak"' in index_html('http://wrolpi.local:8088', 1)
|
||||
assert 'href="https://[fd00::8]:8443/"' in index_html('http://[fd00::8]:8088', 1)
|
||||
|
||||
|
||||
def test_index_html_escapes_the_host():
|
||||
"""The address is the request's Host header, which anyone can write."""
|
||||
page = index_html('http://evil"><script>alert(1)</script>', 1)
|
||||
assert '<script>' not in page
|
||||
|
||||
|
||||
# The service, with a renderer which draws nothing.
|
||||
|
||||
class FakeRenderer:
|
||||
|
||||
def __init__(self, delay: float = 0, fail: bool = False):
|
||||
self.delay = delay
|
||||
self.fail = fail
|
||||
self.blocks = []
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def __call__(self, sid, style, block):
|
||||
with self.lock:
|
||||
self.blocks.append(block)
|
||||
time.sleep(self.delay)
|
||||
if self.fail:
|
||||
raise RuntimeError('cannot draw')
|
||||
return {(x, y): f'{block.z}/{x}/{y}'.encode() for x, y in block.tiles()}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_service(tmp_path, monkeypatch):
|
||||
"""A TileService drawing in threads with a fake renderer."""
|
||||
services = []
|
||||
|
||||
async def _(renderer: FakeRenderer = None, processes: int = 2, cache_bytes: int = 0) -> TileService:
|
||||
monkeypatch.setattr(render, 'render_block', renderer or FakeRenderer())
|
||||
write_pmtiles(tmp_path / 'map/basemap.pmtiles')
|
||||
cache = TileCache(tmp_path / 'cache', cache_bytes, 0)
|
||||
service = TileService(tmp_path / 'map', cache, processes=processes, overview=None)
|
||||
monkeypatch.setattr(service, '_new_executor', lambda: ThreadPoolExecutor(processes))
|
||||
await service.start()
|
||||
services.append(service)
|
||||
await service.tasks[-1] # the render processes are warmed
|
||||
if isinstance(render.render_block, FakeRenderer):
|
||||
render.render_block.blocks.clear()
|
||||
return service
|
||||
|
||||
yield _
|
||||
for service in services:
|
||||
service.executor.shutdown(wait=False, cancel_futures=True)
|
||||
for task in service.tasks:
|
||||
task.cancel()
|
||||
|
||||
|
||||
async def test_service_draws_a_block_once(make_service):
|
||||
"""ATAK asks for 4 tiles at a time, all of one block; the block is drawn once."""
|
||||
renderer = FakeRenderer(delay=0.1)
|
||||
service = await make_service(renderer)
|
||||
tiles = [(x, y) for x in range(8, 12) for y in range(20, 24)]
|
||||
results = await asyncio.gather(*(service.tile(15, x, y, 'phone') for x, y in tiles))
|
||||
|
||||
assert renderer.blocks == [Block(15, 2, 5)]
|
||||
assert [data for data, _ in results] == [f'15/{x}/{y}'.encode() for x, y in tiles]
|
||||
assert all(keep for _, keep in results)
|
||||
|
||||
|
||||
async def test_service_serves_phones_in_turn(make_service):
|
||||
"""A phone downloading many blocks does not keep another's tiles waiting behind all of them."""
|
||||
renderer = FakeRenderer(delay=0.05)
|
||||
service = await make_service(renderer, processes=1)
|
||||
downloading = [asyncio.create_task(service.tile(15, 4 * i, 0, 'downloading')) for i in range(10)]
|
||||
await asyncio.sleep(0)
|
||||
other = await service.tile(15, 0, 400, 'browsing')
|
||||
|
||||
assert other[0] == b'15/0/400'
|
||||
assert renderer.blocks.index(Block(15, 0, 100)) <= 2
|
||||
await asyncio.gather(*downloading)
|
||||
|
||||
|
||||
async def test_service_warms_render_processes(make_service):
|
||||
"""Every render process draws when the service starts, not when the first tile is asked for; the world it
|
||||
draws is kept."""
|
||||
renderer = FakeRenderer()
|
||||
service = await make_service(renderer, processes=2, cache_bytes=10_000_000)
|
||||
assert service.cache.get(0, 0, 0) == b'0/0/0'
|
||||
assert await service.tile(0, 0, 0, 'phone') == (b'0/0/0', True)
|
||||
assert renderer.blocks == [] # from the cache
|
||||
|
||||
|
||||
async def test_service_late_tile(make_service, monkeypatch):
|
||||
"""A tile not drawn before ATAK gives up on it is not sent at all (a downloader would keep a blank in its
|
||||
place for good): the phone asks again, and then the tile has been drawn."""
|
||||
monkeypatch.setattr(tile_service, 'DEADLINE', 0.05)
|
||||
service = await make_service(FakeRenderer(delay=0.3), cache_bytes=10_000_000)
|
||||
|
||||
data, keep = await service.tile(12, 1, 1, 'phone')
|
||||
assert (data, keep) == (None, False)
|
||||
await asyncio.sleep(0.5)
|
||||
assert await service.tile(12, 1, 1, 'phone') == (b'12/1/1', True)
|
||||
assert service.stats['tiles_late'] == 1 and service.stats['tiles_cached'] == 1
|
||||
|
||||
|
||||
async def test_service_failed_tile(make_service):
|
||||
"""A tile which could not be drawn is not sent (not as a blank a downloader would keep); a tile outside the
|
||||
world is the background."""
|
||||
service = await make_service(FakeRenderer(fail=True))
|
||||
assert await service.tile(12, 1, 1, 'phone') == (None, False)
|
||||
assert await service.tile(3, 8, 8, 'phone') == (service.blank_tile, False) # not a tile
|
||||
|
||||
|
||||
async def test_service_forgets_old_serve_times(make_service, monkeypatch):
|
||||
"""Tiles per second counts the last minute; older times are not kept, whether or not anyone asks."""
|
||||
service = await make_service()
|
||||
now = time.time()
|
||||
service.served.extend([now - 120] * 1000)
|
||||
await service.tile(12, 1, 1, 'phone')
|
||||
assert len(service.served) == 1
|
||||
|
||||
|
||||
async def test_service_new_map_file(make_service, tmp_path):
|
||||
service = await make_service()
|
||||
first = service.style_id
|
||||
assert not service.refresh_maps()
|
||||
write_pmtiles(tmp_path / 'map/another.pmtiles')
|
||||
assert service.refresh_maps()
|
||||
assert service.style_id != first and len(service.maps) == 2
|
||||
|
||||
|
||||
async def test_service_drops_tiles_a_phone_gave_up_on(make_service, monkeypatch):
|
||||
monkeypatch.setattr(tile_service, 'MAX_QUEUED_PER_CLIENT', 2)
|
||||
monkeypatch.setattr(tile_service, 'DEADLINE', 1)
|
||||
service = await make_service(FakeRenderer(delay=0.2), processes=1)
|
||||
results = await asyncio.gather(*(service.tile(15, 4 * i, 0, 'phone') for i in range(5)))
|
||||
assert service.stats['blocks_dropped'] >= 1
|
||||
assert (None, False) in results
|
||||
|
||||
|
||||
async def test_service_http(make_service):
|
||||
service = await make_service(cache_bytes=10_000_000)
|
||||
app = create_app(service, name=f'tiles_{uuid.uuid4().hex}')
|
||||
# The service is started by the fixture.
|
||||
app.ctx.service.start = app.ctx.service.stop = lambda: asyncio.sleep(0)
|
||||
|
||||
headers = {'x-forwarded-proto': 'https', 'x-forwarded-host': 'wrolpi.local', 'x-forwarded-for': '192.0.2.34'}
|
||||
_, resp = await app.asgi_client.get('/tiles/wrolpi.xml', headers=headers)
|
||||
assert resp.status == 200
|
||||
root = ElementTree.fromstring(resp.body)
|
||||
assert root.findtext('url') == 'https://wrolpi.local/tiles/{$z}/{$x}/{$y}.jpg'
|
||||
assert root.findtext('name') == 'WROLPi Map (HTTPS)'
|
||||
assert 'wrolpi-map-https.xml' in resp.headers['content-disposition']
|
||||
|
||||
_, resp = await app.asgi_client.get('/tiles/10/5/6.jpg', headers=headers)
|
||||
assert resp.status == 200 and resp.body == b'10/5/6'
|
||||
assert resp.headers['content-type'] == 'image/jpeg'
|
||||
assert 'max-age' in resp.headers['cache-control']
|
||||
|
||||
_, resp = await app.asgi_client.get('/tiles/10/5/6.png')
|
||||
assert resp.status == 404
|
||||
|
||||
# The page for a person who finds the port.
|
||||
for path in ('/', '/tiles', '/tiles/'):
|
||||
_, resp = await app.asgi_client.get(path, headers=headers)
|
||||
assert resp.status == 200 and 'text/html' in resp.headers['content-type'], path
|
||||
assert 'https://wrolpi.local/tiles/wrolpi.xml' in resp.text
|
||||
|
||||
# Not drawn in time: a 503 (never a 401 or 403, which stop an ATAK map source), never a blank to keep.
|
||||
async def late(*args):
|
||||
return None, False
|
||||
|
||||
app.ctx.service.tile = late
|
||||
_, resp = await app.asgi_client.get('/tiles/10/5/7.jpg')
|
||||
assert resp.status == 503 and resp.headers['retry-after'] == '1'
|
||||
assert resp.headers['cache-control'] == 'no-store'
|
||||
|
||||
_, resp = await app.asgi_client.get('/tiles/status')
|
||||
assert resp.status == 200
|
||||
assert resp.json['clients'][0]['client'] == '192.0.2.34'
|
||||
assert resp.json['stats']['blocks_drawn'] >= 1
|
||||
|
||||
# The ATAK tab clears the kept tiles. (The tile drawn above is kept in the background; wait for it, or it
|
||||
# would be kept after the clear.)
|
||||
for _ in range(100):
|
||||
if service.cache.get(10, 5, 6):
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
assert service.cache.get(10, 5, 6) == b'10/5/6'
|
||||
_, resp = await app.asgi_client.post('/tiles/cache/clear')
|
||||
assert resp.status == 200 and resp.json['freed_bytes'] >= 4
|
||||
assert service.cache.get(10, 5, 6) is None and service.cache.size == 0
|
||||
|
||||
|
||||
# Real drawing. mapli has wheels for Linux only: everywhere WROLPi runs.
|
||||
|
||||
@pytest.mark.skipif(sys.platform != 'linux', reason='mapli is Linux-only')
|
||||
def test_render_block(tmp_path):
|
||||
render.init_process()
|
||||
style = build_style([write_pmtiles(tmp_path / 'overview.pmtiles'), write_pmtiles(tmp_path / 'basemap.pmtiles')])
|
||||
tiles = render.render_block('test', style, Block(15, 1840, 3645))
|
||||
assert set(tiles) == set(Block(15, 1840, 3645).tiles())
|
||||
image = Image.open(io.BytesIO(tiles[(7360, 14580)]))
|
||||
assert image.format == 'JPEG' and image.size == (256, 256)
|
||||
# The files have no features: every tile is the background.
|
||||
expected = tuple(int(background_color(style)[i:i + 2], 16) for i in (1, 3, 5))
|
||||
assert all(abs(a - b) <= 3 for a, b in zip(image.getpixel((128, 128)), expected))
|
||||
|
||||
world = render.render_block('test', style, Block(1, 0, 0))
|
||||
assert len(world) == 4 and Image.open(io.BytesIO(world[(1, 1)])).size == (256, 256)
|
||||
|
||||
# Without map files, the background alone.
|
||||
empty = render.render_block('empty', build_style([]), Block(0, 0, 0))
|
||||
assert Image.open(io.BytesIO(empty[(0, 0)])).size == (256, 256)
|
||||
Loading…
Add table
Add a link
Reference in a new issue