mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 20:06:22 -05:00
Species: a monthly build of the packs, signed where the key is (#1036)
* Species: a monthly build of the packs, signed where the key is The build host builds the packs unsigned (inat-build.sh, a systemd timer), and the machine with the signing key signs the hashes and the manifest from manifest.json alone (inat-publish.sh), so the packs never leave the build host and the key never goes to it. build_inat_regions.py --no-sign now still writes each pack's sha256, and --sign signs such a build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: sign only a well-formed build manifest, written again where the key is Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: inat-publish.sh passes the bucket to the upload, so a try stays out of the live packs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: the monthly build publishes nothing older than what is published The version is the observations' publication date; a build of the same (or older) observations would replace the published packs with an older version, and the prune would delete the newer ones. 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
e61d87483a
commit
04ddc7c63c
7 changed files with 378 additions and 6 deletions
|
|
@ -1,5 +1,6 @@
|
|||
import csv
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sqlite3
|
||||
|
|
@ -363,6 +364,91 @@ def test_write_manifest(test_directory, west_pack):
|
|||
sign_manifest.assert_called_once_with(str(manifest_path))
|
||||
|
||||
|
||||
def test_write_manifest_unsigned(test_directory, west_pack):
|
||||
"""Without signing, the manifest still has each pack's sha256, for `sign_build` to sign elsewhere."""
|
||||
db_path, _ = west_pack
|
||||
with mock.patch.object(build, 'write_meta4') as write_meta4, \
|
||||
mock.patch.object(build, 'sign_manifest') as sign_manifest:
|
||||
manifest_path = build.write_manifest(test_directory, '20261123', 'https://cdn.example/inat',
|
||||
{'us-west': db_path}, sign=False)
|
||||
url = 'https://cdn.example/inat/20261123/inat-us-west-20261123.species.db'
|
||||
assert json.loads(manifest_path.read_text())['sha256'] == {url: hashlib.sha256(db_path.read_bytes()).hexdigest()}
|
||||
write_meta4.assert_not_called()
|
||||
sign_manifest.assert_not_called()
|
||||
|
||||
|
||||
CDN = 'https://cdn.example/inat'
|
||||
URL = f'{CDN}/20261123/inat-us-west-20261123.species.db'
|
||||
|
||||
|
||||
def unsigned_build(output_dir, **changes):
|
||||
"""The manifest of an unsigned build, without the packs (they stay on the build host)."""
|
||||
manifest = dict(version='20261123', license='CC BY-NC 4.0', attribution='...', regions={'us-west': URL},
|
||||
sizes={'us-west': 1234}, sha256={URL: 'a' * 64})
|
||||
manifest.update(changes)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
(output_dir / 'manifest.json').write_text(json.dumps(manifest))
|
||||
|
||||
|
||||
def test_sign_build(test_directory):
|
||||
"""Signs an unsigned build's hashes (a meta4 per pack) and its manifest, without the packs."""
|
||||
output_dir = test_directory / 'out'
|
||||
unsigned_build(output_dir, extra='not signed')
|
||||
old_signature = output_dir / 'manifest.json.sig'
|
||||
old_signature.write_text('old')
|
||||
with mock.patch.object(build, 'sign_hash', return_value='SIGNATURE') as sign_hash, \
|
||||
mock.patch.object(build, 'sign_manifest', side_effect=lambda path: assert_not_exists(old_signature)) \
|
||||
as sign_manifest:
|
||||
build.sign_build(output_dir, CDN)
|
||||
|
||||
sign_hash.assert_called_once_with('a' * 64)
|
||||
sign_manifest.assert_called_once_with(str(output_dir / 'manifest.json'))
|
||||
meta4 = (output_dir / '20261123' / 'inat-us-west-20261123.species.db.meta4').read_text()
|
||||
assert 'a' * 64 in meta4 and URL in meta4 and '<size>1234</size>' in meta4 and 'SIGNATURE' in meta4
|
||||
# The manifest that is signed is written here, from what was checked: nothing else is carried over.
|
||||
manifest = json.loads((output_dir / 'manifest.json').read_text())
|
||||
assert 'extra' not in manifest
|
||||
assert manifest['attribution'] == build.ATTRIBUTION
|
||||
assert manifest['regions'] == {'us-west': URL} and manifest['sha256'] == {URL: 'a' * 64}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [
|
||||
dict(version='../../etc'),
|
||||
dict(version=20261123),
|
||||
dict(regions={'atlantis': URL}),
|
||||
dict(regions={'us-west': 'https://elsewhere.example/inat-us-west-20261123.species.db'}),
|
||||
dict(regions={'us-west': f'{CDN}/20261123/../../evil.species.db'}),
|
||||
dict(regions={}),
|
||||
dict(sha256={URL: None}),
|
||||
dict(sha256={URL: 'not a hash'}),
|
||||
dict(sizes={'us-west': 0}),
|
||||
dict(sizes={'us-west': '1234'}),
|
||||
])
|
||||
def test_sign_build_refuses(test_directory, changes):
|
||||
"""Only what a build writes is signed: a manifest from a compromised or broken build host is refused."""
|
||||
output_dir = test_directory / 'out'
|
||||
unsigned_build(output_dir, **changes)
|
||||
with mock.patch.object(build, 'sign_hash') as sign_hash, \
|
||||
mock.patch.object(build, 'sign_manifest') as sign_manifest, pytest.raises(ValueError):
|
||||
build.sign_build(output_dir, CDN)
|
||||
sign_hash.assert_not_called()
|
||||
sign_manifest.assert_not_called()
|
||||
assert not list(test_directory.rglob('*.meta4'))
|
||||
|
||||
|
||||
def test_main_sign(test_directory):
|
||||
"""--sign signs an unsigned build; it needs no work directory."""
|
||||
with mock.patch('sys.argv', ['build_inat_regions.py', '--sign', str(test_directory), '--cdn-base', CDN]), \
|
||||
mock.patch.object(build, 'sign_build') as sign_build:
|
||||
build.main()
|
||||
sign_build.assert_called_once_with(test_directory, CDN)
|
||||
|
||||
|
||||
def test_main_needs_directories():
|
||||
with mock.patch('sys.argv', ['build_inat_regions.py']), pytest.raises(SystemExit):
|
||||
build.main()
|
||||
|
||||
|
||||
def test_main(test_directory, dwca_path, taxa_path, taxonomy_path):
|
||||
"""The whole build, offline: given sources, two regions, no signing."""
|
||||
work_dir, output_dir = test_directory / 'work', test_directory / 'out'
|
||||
|
|
@ -396,6 +482,18 @@ def test_main(test_directory, dwca_path, taxa_path, taxonomy_path):
|
|||
assert db.execute('SELECT COUNT(*) FROM species').fetchone() == (4,)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('newer_than,built', [('20261122', True), ('20261123', False), ('20261129', False)])
|
||||
def test_main_newer_than(test_directory, dwca_path, taxa_path, taxonomy_path, newer_than, built):
|
||||
"""--newer-than: observations no newer than those published build nothing, so nothing older is published."""
|
||||
output_dir = test_directory / 'out'
|
||||
argv = ['build_inat_regions.py', str(test_directory / 'work'), str(output_dir), '--dwca', str(dwca_path), '--taxa',
|
||||
str(taxa_path), '--taxonomy', str(taxonomy_path), '--regions', 'us-west', '--no-sign',
|
||||
'--newer-than', newer_than]
|
||||
with mock.patch('sys.argv', argv), mock.patch.object(build, 'query_wikidata', return_value=[]):
|
||||
build.main()
|
||||
assert (output_dir / 'manifest.json').is_file() == built
|
||||
|
||||
|
||||
@pytest.mark.parametrize('extra', [['--version', '2026-11-28'], ['--reuse-split']])
|
||||
def test_main_invalid(test_directory, dwca_path, taxa_path, taxonomy_path, extra):
|
||||
"""A version must be YYYYMMDD; --reuse-split needs the work files of a last build."""
|
||||
|
|
|
|||
55
release/inat-build.sh
Executable file
55
release/inat-build.sh
Executable file
|
|
@ -0,0 +1,55 @@
|
|||
#!/bin/bash
|
||||
# Build the iNaturalist species packs, unsigned, for inat-publish.sh to sign and publish.
|
||||
#
|
||||
# Run monthly by wrolpi-inat-build.timer on the build host. The build (wrolpi/scripts/build_inat_regions.py) runs in a
|
||||
# one-off container of the api image, so it has the same Python and dependencies as WROLPi. It downloads ~30 GB of
|
||||
# observations and needs ~50 GB more of work space, kept in $INAT_DIR/work between builds (the Wikidata cache saves
|
||||
# hours).
|
||||
#
|
||||
# The signing key is not on the build host. The finished build is left in $INAT_DIR/out with a READY file holding its
|
||||
# version; inat-publish.sh, run where the key is, signs the hashes and the manifest, and uploads them with the packs.
|
||||
#
|
||||
# Arguments are passed to build_inat_regions.py (e.g. `--regions antarctica --cdn-base URL`, to try a build).
|
||||
#
|
||||
# Optional env vars:
|
||||
# INAT_DIR where the work and output live (default ~/inat-build)
|
||||
# INAT_NOTIFY a command given one message when the build finishes or fails (e.g. a Pushover script)
|
||||
# INAT_MANIFEST the published manifest; nothing is built unless the observations are newer than its version
|
||||
# (default the Spaces origin's, which the CDN does not cache)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
REPO_DIR=$(dirname "${SCRIPT_DIR}")
|
||||
INAT_DIR=${INAT_DIR:-${HOME}/inat-build}
|
||||
INAT_NOTIFY=${INAT_NOTIFY:-}
|
||||
INAT_MANIFEST=${INAT_MANIFEST:-https://wrolpi.nyc3.digitaloceanspaces.com/maps/inat/manifest.json}
|
||||
|
||||
notify() {
|
||||
echo "$1"
|
||||
if [ -n "${INAT_NOTIFY}" ]; then
|
||||
"${INAT_NOTIFY}" "$1" || echo "Notify failed"
|
||||
fi
|
||||
}
|
||||
trap 'notify "The species pack build failed; see journalctl -u wrolpi-inat-build"' ERR
|
||||
|
||||
mkdir -p "${INAT_DIR}/work"
|
||||
# A newer build replaces one that was never published.
|
||||
rm -rf "${INAT_DIR}/out"
|
||||
mkdir -p "${INAT_DIR}/out"
|
||||
|
||||
published=$(curl -fsS "${INAT_MANIFEST}" | python3 -c 'import json, sys; print(json.load(sys.stdin)["version"])')
|
||||
echo "Published version: ${published}"
|
||||
|
||||
cd "${REPO_DIR}"
|
||||
docker compose run --rm --no-deps -T -v "${INAT_DIR}:/inat" --entrypoint nice api \
|
||||
-n 10 python3 wrolpi/scripts/build_inat_regions.py /inat/work /inat/out --no-sign --newer-than "${published}" "$@"
|
||||
|
||||
if [ ! -f "${INAT_DIR}/out/manifest.json" ]; then
|
||||
notify "No species packs were built: iNaturalist has published no observations newer than ${published}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
version=$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["version"])' "${INAT_DIR}/out/manifest.json")
|
||||
echo "${version}" > "${INAT_DIR}/out/READY"
|
||||
notify "Species packs ${version} are built, and wait to be signed and published (inat-publish.sh)"
|
||||
67
release/inat-publish.sh
Executable file
67
release/inat-publish.sh
Executable file
|
|
@ -0,0 +1,67 @@
|
|||
#!/bin/bash
|
||||
# Sign and publish the species packs inat-build.sh built on the build host.
|
||||
#
|
||||
# Run daily (e.g. by launchd) on the machine with the WROLPi signing key; it does nothing until a build is READY.
|
||||
# Only manifest.json comes here. Its hashes are signed (a meta4 per pack), and the manifest is written again from what
|
||||
# was checked and signed. Those go back to the build host, which uploads everything (inat-upload.sh). Then the CDN's
|
||||
# cached manifest is flushed, and the older versions are deleted.
|
||||
#
|
||||
# Required env vars:
|
||||
# INAT_HOST ssh destination of the build host
|
||||
# INAT_CDN_ID the DigitalOcean CDN endpoint id (for `doctl compute cdn flush`)
|
||||
# Optional env vars:
|
||||
# INAT_REMOTE_REPO the WROLPi checkout on the build host (default projects/wrolpi, from its home)
|
||||
# INAT_REMOTE_DIR inat-build.sh's INAT_DIR on the build host (default inat-build, from its home)
|
||||
# INAT_CDN_PATH the manifest's directory on the CDN (default maps/inat)
|
||||
# INAT_CDN_BASE the packs' URL base, which the signed manifest must use (default build_inat_regions.py's)
|
||||
# INAT_BUCKET inat-upload.sh's INAT_BUCKET, given to it on the build host (to try a build elsewhere)
|
||||
# INAT_NOTIFY a command, on the build host, given one message when publishing finishes or fails
|
||||
# PYTHON a Python with WROLPi's requirements (default the checkout's .venv)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
REPO_DIR=$(dirname "${SCRIPT_DIR}")
|
||||
INAT_HOST=${INAT_HOST:?Set INAT_HOST to the build host}
|
||||
INAT_CDN_ID=${INAT_CDN_ID:?Set INAT_CDN_ID to the CDN endpoint id}
|
||||
INAT_REMOTE_REPO=${INAT_REMOTE_REPO:-projects/wrolpi}
|
||||
INAT_REMOTE_DIR=${INAT_REMOTE_DIR:-inat-build}
|
||||
INAT_CDN_PATH=${INAT_CDN_PATH:-maps/inat}
|
||||
INAT_NOTIFY=${INAT_NOTIFY:-}
|
||||
INAT_CDN_BASE=${INAT_CDN_BASE:-}
|
||||
INAT_BUCKET=${INAT_BUCKET:-}
|
||||
PYTHON=${PYTHON:-${REPO_DIR}/.venv/bin/python}
|
||||
|
||||
notify() {
|
||||
echo "$1"
|
||||
if [ -n "${INAT_NOTIFY}" ]; then
|
||||
ssh "${INAT_HOST}" "${INAT_NOTIFY}" "$(printf '%q' "$1")" || echo "Notify failed"
|
||||
fi
|
||||
}
|
||||
|
||||
version=$(ssh "${INAT_HOST}" "cat ${INAT_REMOTE_DIR}/out/READY 2>/dev/null" || true)
|
||||
if [ -z "${version}" ]; then
|
||||
echo "No species build is waiting to be published"
|
||||
exit 0
|
||||
fi
|
||||
trap 'notify "Publishing species packs ${version} failed; see inat-publish.sh log"' ERR
|
||||
echo "Publishing species packs ${version}"
|
||||
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "${work}"' EXIT
|
||||
scp -q "${INAT_HOST}:${INAT_REMOTE_DIR}/out/manifest.json" "${work}/"
|
||||
# The build host is not trusted with the key: only a well-formed manifest is signed, and it is written again here.
|
||||
"${PYTHON}" "${REPO_DIR}/wrolpi/scripts/build_inat_regions.py" --sign "${work}" ${INAT_CDN_BASE:+--cdn-base "${INAT_CDN_BASE}"}
|
||||
signed=$("${PYTHON}" -c 'import json, sys; print(json.load(open(sys.argv[1]))["version"])' "${work}/manifest.json")
|
||||
if [ "${signed}" != "${version}" ]; then
|
||||
echo "The build host's READY (${version}) is not its manifest's version (${signed})" >&2
|
||||
exit 1
|
||||
fi
|
||||
scp -q "${work}/${version}/"*.meta4 "${INAT_HOST}:${INAT_REMOTE_DIR}/out/${version}/"
|
||||
scp -q "${work}/manifest.json" "${work}/manifest.json.sig" "${INAT_HOST}:${INAT_REMOTE_DIR}/out/"
|
||||
|
||||
remote_upload="INAT_DIR=${INAT_REMOTE_DIR} ${INAT_BUCKET:+INAT_BUCKET=${INAT_BUCKET} }${INAT_REMOTE_REPO}/release/inat-upload.sh"
|
||||
ssh "${INAT_HOST}" "${remote_upload} upload ${version}"
|
||||
doctl compute cdn flush "${INAT_CDN_ID}" --files "${INAT_CDN_PATH}/manifest.json,${INAT_CDN_PATH}/manifest.json.sig"
|
||||
ssh "${INAT_HOST}" "${remote_upload} prune ${version}"
|
||||
notify "Species packs ${version} are published"
|
||||
47
release/inat-upload.sh
Executable file
47
release/inat-upload.sh
Executable file
|
|
@ -0,0 +1,47 @@
|
|||
#!/bin/bash
|
||||
# Upload a signed species pack build to the CDN, or delete the versions before it. Run on the build host, by
|
||||
# inat-publish.sh (over ssh), after it has signed the build.
|
||||
#
|
||||
# inat-upload.sh upload <version> the packs and meta4 files, then manifest.json and its signature
|
||||
# inat-upload.sh prune <version> delete every other version from the CDN (after the manifest is flushed)
|
||||
#
|
||||
# Honors $S3CFG. Optional env vars:
|
||||
# INAT_DIR where inat-build.sh left the build (default ~/inat-build)
|
||||
# INAT_BUCKET where the packs are published (default s3://wrolpi/maps/inat)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
INAT_DIR=${INAT_DIR:-${HOME}/inat-build}
|
||||
INAT_BUCKET=${INAT_BUCKET:-s3://wrolpi/maps/inat}
|
||||
action=${1:?upload or prune}
|
||||
version=${2:?the version}
|
||||
out="${INAT_DIR}/out"
|
||||
|
||||
case "${action}" in
|
||||
upload)
|
||||
if [ "$(cat "${out}/READY" 2>/dev/null)" != "${version}" ]; then
|
||||
echo "The build in ${out} is not version ${version}" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -s "${out}/manifest.json.sig" ]; then
|
||||
echo "${out}/manifest.json is not signed" >&2
|
||||
exit 1
|
||||
fi
|
||||
# The packs first: the manifest must never name a pack that is not there yet.
|
||||
s3cmd put --acl-public --recursive --no-progress "${out}/${version}/" "${INAT_BUCKET}/${version}/"
|
||||
s3cmd put --acl-public --no-progress "${out}/manifest.json" "${out}/manifest.json.sig" "${INAT_BUCKET}/"
|
||||
mv "${out}/READY" "${out}/PUBLISHED"
|
||||
;;
|
||||
prune)
|
||||
s3cmd ls "${INAT_BUCKET}/" | awk '$1 == "DIR" {print $2}' | while read -r dir; do
|
||||
if [ "$(basename "${dir}")" != "${version}" ]; then
|
||||
echo "Deleting ${dir}"
|
||||
s3cmd del --recursive --force "${dir}"
|
||||
fi
|
||||
done
|
||||
;;
|
||||
*)
|
||||
echo "Unknown action: ${action}" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
26
release/wrolpi-inat-build.service
Normal file
26
release/wrolpi-inat-build.service
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# WROLPi species pack build (oneshot, driven by wrolpi-inat-build.timer).
|
||||
#
|
||||
# Builds the iNaturalist species packs, unsigned (release/inat-build.sh). release/inat-publish.sh, run where the
|
||||
# signing key is, signs and publishes them.
|
||||
#
|
||||
# Install (as root):
|
||||
# cp release/wrolpi-inat-build.service release/wrolpi-inat-build.timer /etc/systemd/system/
|
||||
# # edit the user and paths below to match this host; it must be in the docker group. Then:
|
||||
# systemctl daemon-reload
|
||||
# systemctl enable --now wrolpi-inat-build.timer
|
||||
#
|
||||
# INAT_NOTIFY (e.g. a Pushover script) is set in a drop-in.
|
||||
|
||||
[Unit]
|
||||
Description=Build the iNaturalist species packs
|
||||
After=network-online.target docker.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=wrolpi
|
||||
WorkingDirectory=/opt/wrolpi
|
||||
ExecStart=/opt/wrolpi/release/inat-build.sh
|
||||
# The download and build take a few hours.
|
||||
TimeoutStartSec=12h
|
||||
Nice=10
|
||||
11
release/wrolpi-inat-build.timer
Normal file
11
release/wrolpi-inat-build.timer
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
[Unit]
|
||||
Description=Monthly iNaturalist species pack build
|
||||
|
||||
[Timer]
|
||||
# iNaturalist publishes the observations weekly; the packs are rebuilt once a month.
|
||||
OnCalendar=*-*-02 02:00:00
|
||||
RandomizedDelaySec=1h
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
|
|
@ -6,6 +6,7 @@ Usage:
|
|||
python wrolpi/scripts/build_inat_regions.py <work_dir> <output_dir> [--regions us-west,us-central]
|
||||
[--dwca FILE] [--taxa FILE] [--taxonomy FILE] [--cdn-base URL]
|
||||
[--version YYYYMMDD] [--reuse-split] [--no-sign]
|
||||
python wrolpi/scripts/build_inat_regions.py --sign <output_dir>
|
||||
|
||||
Run by the maintainers, monthly, on a machine with the Internet and ~200 GB free. WROLPi devices never contact
|
||||
iNaturalist or Wikidata; they download these packs.
|
||||
|
|
@ -30,6 +31,8 @@ Steps:
|
|||
The planet (`inat-planet-<version>.species.db`) is built like a region, from each observation once; its work
|
||||
is split into PLANET_BUCKETS files by species, built one at a time, so it fits in memory.
|
||||
5. sha256 + signed meta4 of each pack, and the signed manifest.json. Upload <output_dir> to the CDN base.
|
||||
With --no-sign, the manifest has the hashes but nothing is signed: `--sign <output_dir>` signs them later, on the
|
||||
machine with the key, from manifest.json alone (release/inat-build.sh and release/inat-publish.sh do this monthly).
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
|
|
@ -57,7 +60,8 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspa
|
|||
from modules.map.catalog import MAP_REGIONS
|
||||
from modules.map.species import (GROUPS, HIGH_GRID, LOOKUP_GRID, LOW_GRID, PLANET, SCHEMA, SPECIES_DB_SUFFIX, cell_id,
|
||||
encode_cells, encode_months, month_bit, pack_name, parse_pack_name)
|
||||
from wrolpi.scripts.build_map_regions import format_size, sign_manifest, write_meta4
|
||||
from wrolpi.scripts.build_map_regions import format_size, generate_meta4, sha256_file, sign_hash, sign_manifest, \
|
||||
write_meta4
|
||||
|
||||
DWCA_URL = 'https://static.inaturalist.org/observations/gbif-observations-dwca.zip'
|
||||
TAXA_URL = 'https://inaturalist-open-data.s3.amazonaws.com/taxa.csv.gz'
|
||||
|
|
@ -446,13 +450,15 @@ def _add_work_file(db: sqlite3.Connection, path: Path, taxa: Taxa, wikidata: Dic
|
|||
|
||||
|
||||
def write_manifest(output_dir: Path, version: str, cdn_base: str, packs: Dict[str, Path], sign: bool = True) -> Path:
|
||||
"""manifest.json: each region's pack URL, size and sha256 (from its signed meta4), then its signature."""
|
||||
"""manifest.json: each region's pack URL, size and sha256 (from its signed meta4), then its signature.
|
||||
|
||||
Unsigned, the manifest still has each pack's sha256, so `sign_build` can sign it where the key is."""
|
||||
regions, sizes, hashes = dict(), dict(), dict()
|
||||
for region, path in sorted(packs.items()):
|
||||
url = f'{cdn_base}/{version}/{path.name}'
|
||||
regions[region] = url
|
||||
sizes[region] = path.stat().st_size
|
||||
hashes[url] = write_meta4(str(path), url) if sign else None
|
||||
hashes[url] = write_meta4(str(path), url) if sign else sha256_file(str(path))
|
||||
manifest = dict(version=version, license=LICENSE, attribution=ATTRIBUTION, regions=regions, sizes=sizes,
|
||||
sha256=hashes)
|
||||
manifest_path = output_dir / 'manifest.json'
|
||||
|
|
@ -465,10 +471,57 @@ def write_manifest(output_dir: Path, version: str, cdn_base: str, packs: Dict[st
|
|||
return manifest_path
|
||||
|
||||
|
||||
SHA256_PATTERN = re.compile(r'[0-9a-f]{64}')
|
||||
|
||||
|
||||
def sign_build(output_dir: Path, cdn_base: str = DEFAULT_CDN_BASE):
|
||||
"""Sign an unsigned build (see --no-sign): a signed meta4 for each pack's hash, and the manifest.
|
||||
|
||||
Needs only manifest.json; the packs can stay on the machine that built them, and are uploaded with these files.
|
||||
That manifest comes from another machine, so only what a build writes is signed: known regions, each pack at its
|
||||
own URL under `cdn_base`, a sha256 and a size. The manifest is written again from those, and that is signed."""
|
||||
manifest_path = output_dir / 'manifest.json'
|
||||
received = json.loads(manifest_path.read_text())
|
||||
version = received.get('version')
|
||||
if not isinstance(version, str) or not re.fullmatch(r'\d{8}', version):
|
||||
raise ValueError(f'Not a version: {version!r}')
|
||||
known = {name for name, _ in bbox_regions()} | {PLANET}
|
||||
regions, sizes, hashes = dict(), dict(), dict()
|
||||
received_sizes, received_hashes = received.get('sizes') or dict(), received.get('sha256') or dict()
|
||||
for region, url in sorted((received.get('regions') or dict()).items()):
|
||||
if region not in known:
|
||||
raise ValueError(f'Unknown region: {region!r}')
|
||||
if url != f'{cdn_base}/{version}/{pack_name(region, version)}':
|
||||
raise ValueError(f'Unexpected URL for {region}: {url!r}')
|
||||
sha256, size = received_hashes.get(url), received_sizes.get(region)
|
||||
if not isinstance(sha256, str) or not SHA256_PATTERN.fullmatch(sha256):
|
||||
raise ValueError(f'No sha256 for {region}: {sha256!r}')
|
||||
if type(size) is not int or size <= 0:
|
||||
raise ValueError(f'No size for {region}: {size!r}')
|
||||
regions[region], sizes[region], hashes[url] = url, size, sha256
|
||||
if not regions:
|
||||
raise ValueError(f'No packs in {manifest_path}')
|
||||
|
||||
pack_dir = output_dir / version
|
||||
pack_dir.mkdir(parents=True, exist_ok=True)
|
||||
for region, url in regions.items():
|
||||
name = pack_name(region, version)
|
||||
print(f' Signing hash for {name}...')
|
||||
meta4 = generate_meta4(name, url, hashes[url], sizes[region], sign_hash(hashes[url]))
|
||||
(pack_dir / f'{name}.meta4').write_text(meta4)
|
||||
manifest = dict(version=version, license=LICENSE, attribution=ATTRIBUTION, regions=regions, sizes=sizes,
|
||||
sha256=hashes)
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2))
|
||||
# gpg asks before replacing a signature, and no one is there to answer: it would wait forever.
|
||||
manifest_path.with_name(f'{manifest_path.name}.sig').unlink(missing_ok=True)
|
||||
sign_manifest(str(manifest_path))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Build iNaturalist species packs for the map regions.')
|
||||
parser.add_argument('work_dir', help='Downloads, work files and the Wikidata cache (kept between builds)')
|
||||
parser.add_argument('output_dir', help='The packs and manifest.json, to upload to --cdn-base')
|
||||
parser.add_argument('work_dir', nargs='?',
|
||||
help='Downloads, work files and the Wikidata cache (kept between builds)')
|
||||
parser.add_argument('output_dir', nargs='?', help='The packs and manifest.json, to upload to --cdn-base')
|
||||
parser.add_argument('--regions', help=f'Comma separated map regions, and/or {PLANET!r} (default: all of them)')
|
||||
parser.add_argument('--dwca', help='Use this DwC-A zip instead of downloading it')
|
||||
parser.add_argument('--taxa', help='Use this taxa.csv.gz instead of downloading it')
|
||||
|
|
@ -478,9 +531,21 @@ def main():
|
|||
'date; to publish a rebuild of the same observations')
|
||||
parser.add_argument('--reuse-split', action='store_true',
|
||||
help="Use the region work files of the last build instead of reading the observations")
|
||||
parser.add_argument('--no-sign', action='store_true', help='Skip the meta4 files and signatures (testing)')
|
||||
parser.add_argument('--no-sign', action='store_true',
|
||||
help='Write the hashes, but no meta4 files or signatures; sign later with --sign')
|
||||
parser.add_argument('--newer-than', metavar='YYYYMMDD',
|
||||
help='Build nothing (and write no manifest) unless the version is newer than this one, '
|
||||
'e.g. the published version')
|
||||
parser.add_argument('--sign', metavar='OUTPUT_DIR',
|
||||
help='Only sign the unsigned build in OUTPUT_DIR (its manifest.json); builds nothing')
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.sign:
|
||||
sign_build(Path(args.sign), args.cdn_base)
|
||||
return
|
||||
if not (args.work_dir and args.output_dir):
|
||||
parser.error('work_dir and output_dir are required, unless --sign')
|
||||
|
||||
work_dir, output_dir = Path(args.work_dir), Path(args.output_dir)
|
||||
work_dir.mkdir(parents=True, exist_ok=True)
|
||||
regions = bbox_regions()
|
||||
|
|
@ -506,6 +571,9 @@ def main():
|
|||
if not re.fullmatch(r'\d{8}', version):
|
||||
parser.error(f'The version must be YYYYMMDD, not {version!r}')
|
||||
print(f'Version {version}')
|
||||
if args.newer_than and version <= args.newer_than:
|
||||
print(f'Version {version} is not newer than {args.newer_than}; nothing to build')
|
||||
return
|
||||
pack_dir = output_dir / version
|
||||
pack_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue