diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 504df63..62e0c2d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,6 +81,33 @@ jobs: - name: Integration test against a real regtest node run: python -m unittest tests.test_regtest -v + btrfs: + # The result database on a real btrfs file system (as on StartOS): created nodatacow. + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.15" + - name: Mount a small btrfs file system + run: | + set -euo pipefail + sudo apt-get install -y -q btrfs-progs e2fsprogs >/dev/null + truncate -s 512M "$RUNNER_TEMP/btrfs.img" + mkfs.btrfs -q "$RUNNER_TEMP/btrfs.img" + sudo mkdir /mnt/btrfs + sudo mount -o loop "$RUNNER_TEMP/btrfs.img" /mnt/btrfs + sudo chown "$(id -u):$(id -g)" /mnt/btrfs + findmnt -no FSTYPE /mnt/btrfs + - name: Store tests on btrfs + env: + BMV_BTRFS_DIR: /mnt/btrfs + run: | + set -o pipefail + python -m unittest tests.test_store_fs -v 2>&1 | tee out.txt + ! grep -q "skipped 'no btrfs" out.txt + lsattr -R /mnt/btrfs || true + browser: # Every dashboard page in a real Chromium: no JavaScript or console errors, no failed # API calls, no requests outside the app, no sideways scrolling on phones and tablets. diff --git a/CHANGELOG.md b/CHANGELOG.md index f0e1064..8e3cd85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ All notable changes are documented here. This project uses [semantic versioning](https://semver.org/). +## [Unreleased] + +- **Gentler on the disk, especially on btrfs (StartOS):** the scan databases are created without + copy-on-write on btrfs (`chattr +C` on each network's data directory; other file systems are unaffected). + A database rewritten in small pieces fragments badly on copy-on-write file systems, and on one StartOS + server this drove btrfs into a fault that made the data drive read-only. The databases lose btrfs + checksums as a result; they can always be rebuilt from the node and are not in backups. Existing database + files keep their attribute (the StartOS package rewrites them once in its 0.3.10:1 update). +- SQLite now flushes the database to disk every 64 MB of changes instead of every 4 MB, so a fast scan forces + far fewer disk flushes (about 16 times fewer while the history scan runs). An app crash loses nothing; a + power cut can lose the scan progress since the last flush, which the scan then redoes (the database stays + consistent either way). + ## [0.3.10] — 2026-11-07 - **Trends and records:** a tile still waiting for its blocks now says "Available once the full scan is done" diff --git a/bitcoinmonetaryview/store.py b/bitcoinmonetaryview/store.py index 4bea6f3..e049497 100644 --- a/bitcoinmonetaryview/store.py +++ b/bitcoinmonetaryview/store.py @@ -18,15 +18,56 @@ import os import sqlite3 import struct +import sys import threading import time +try: + import fcntl +except ImportError: # not on Windows + fcntl = None + from .rules import monetary_rules as mr SCHEMA_VERSION = 1 REORG_WINDOW = 288 BUCKET = 1000 +# SQLite flushes the database to disk at each WAL checkpoint (synchronous=NORMAL). The default +# checkpoint every 1,000 pages (4 MB) means several flushes a second during a fast scan, which strains +# copy-on-write file systems; checkpoint every 64 MB instead and keep the WAL file at most that big. +WAL_CHECKPOINT_PAGES = 16384 +WAL_SIZE_LIMIT = 64 << 20 + +# Linux FS_IOC_GETFLAGS / FS_IOC_SETFLAGS and the btrfs "nodatacow" attribute (chattr +C). +FS_IOC_GETFLAGS = 0x80086601 +FS_IOC_SETFLAGS = 0x40086602 +FS_NOCOW_FL = 0x00800000 + + +def no_cow(directory): + """Mark the app's own data directory nodatacow, so files created in it later skip copy-on-write. + + On btrfs, a database rewritten in small pieces fragments into a huge number of extents, and + flushing it then strains the file system. The results are rebuildable from the node, so losing + btrfs checksums on them is acceptable. Existing files keep their attribute. Best effort: other + file systems and systems refuse it, which is fine. Returns True if the attribute is set.""" + if fcntl is None or not sys.platform.startswith("linux"): + return False + try: + fd = os.open(directory, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + except OSError: + return False + try: + flags = struct.unpack("q", fcntl.ioctl(fd, FS_IOC_GETFLAGS, struct.pack("q", 0)))[0] + if not flags & FS_NOCOW_FL: + fcntl.ioctl(fd, FS_IOC_SETFLAGS, struct.pack("q", flags | FS_NOCOW_FL)) + return True + except OSError: + return False + finally: + os.close(fd) + BLOCK_COLS = ("height", "hash", "time", "size", "stored", "weight", "tx_count", "envelope", "op_return", "multisig", "scriptsig", "whole", "modified", "stripped", "dust_outputs", "filter_entries", @@ -208,9 +249,12 @@ def __init__(self, path, readonly=False, cache_mb=64): self.db = sqlite3.connect(uri, uri=True, check_same_thread=False, timeout=30) else: os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) + no_cow(os.path.dirname(path)) self.db = sqlite3.connect(path, check_same_thread=False, timeout=30, isolation_level=None) self.db.execute("PRAGMA journal_mode=WAL") self.db.execute("PRAGMA synchronous=NORMAL") + self.db.execute(f"PRAGMA wal_autocheckpoint={WAL_CHECKPOINT_PAGES}") + self.db.execute(f"PRAGMA journal_size_limit={WAL_SIZE_LIMIT}") self.db.executescript(DDL) if self.get_meta("schema_version") is None: self.set_meta("schema_version", SCHEMA_VERSION) diff --git a/docs/startos.md b/docs/startos.md index d6d9533..b0bea34 100644 --- a/docs/startos.md +++ b/docs/startos.md @@ -16,7 +16,7 @@ Based on the [StartOS 0.4.0.x packaging guide](https://docs.start9.com/packaging | **Web UI interface** | Bind the app's port (8338) as a `ui` interface. The package protects it with the app's own basic auth (`auth_user` / `auth_password` in `settings.json`), set by a *Set Web Password* action that a critical task asks for; the action runs in any state and restarts a running service, so only the new password works. The Host-header check is delegated to the proxy in managed mode. | | **Health checks** | Daemon readiness: `GET /api/health` (cheap). Standalone check "Scan progress": read `GET /api/status` → `phase` (`quick`/`sample`/`full` → `loading` with `progress` %, `live` → `success`, `error` → `failure`). Use a cooldown trigger (e.g. 30 s). | | **Logs** | Plain lines on stdout. | -| **Volumes & backups** | One volume (`/data`). Back up `settings.json`; the per-network directories (`/data//`: the database `bmv.sqlite*` and the saved spent-output filter `spent-filter.bin`) can be rebuilt by rescanning and may be excluded to keep backups small. | +| **Volumes & backups** | One volume (`/data`). Back up `settings.json`; the per-network directories (`/data//`: the database `bmv.sqlite*` and the saved spent-output filter `spent-filter.bin`) can be rebuilt by rescanning and may be excluded to keep backups small. The app creates each per-network directory nodatacow on btrfs (`chattr +C`), so its files skip copy-on-write; files created before that keep their attribute and need a one-time copy (the package's `nocow.py`). | | **Stopping** | On SIGTERM the app finishes its current batch and saves the spent-output filter for a fast next start; give it up to 60 s (the StartOS default). If it is killed sooner, the next start rebuilds the filter (a few minutes on mainnet). | | **Languages** | The package texts (description, actions, settings, health check, release notes) come in English, German, Spanish, French and Polish; StartOS shows them in its system language, English otherwise. The dashboard has the same five languages and follows the browser's language (the header's language menu switches it). | | **Architectures** | Pure Python: `x86_64`, `aarch64` and `riscv64` (all three built by the StartOS package). | diff --git a/tests/test_store_fs.py b/tests/test_store_fs.py new file mode 100644 index 0000000..d1b474f --- /dev/null +++ b/tests/test_store_fs.py @@ -0,0 +1,124 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""How the result database sits on disk: WAL checkpoint size and btrfs nodatacow.""" + +import os +import shutil +import struct +import tempfile +import unittest +from unittest import mock + +from bitcoinmonetaryview import store + +# CI mounts a small btrfs file system and points this at a directory on it +BTRFS_DIR = os.environ.get("BMV_BTRFS_DIR") + + +def flags(path): + fd = os.open(path, os.O_RDONLY) + try: + return struct.unpack("q", store.fcntl.ioctl(fd, store.FS_IOC_GETFLAGS, struct.pack("q", 0)))[0] + finally: + os.close(fd) + + +class WalCheckpoints(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def test_writer_checkpoints_every_64_mb(self): + s = store.Store(os.path.join(self.dir, "regtest", "bmv.sqlite")) + try: + self.assertEqual(s.db.execute("PRAGMA journal_mode").fetchone()[0], "wal") + self.assertEqual(s.db.execute("PRAGMA wal_autocheckpoint").fetchone()[0], store.WAL_CHECKPOINT_PAGES) + self.assertEqual(s.db.execute("PRAGMA journal_size_limit").fetchone()[0], store.WAL_SIZE_LIMIT) + page = s.db.execute("PRAGMA page_size").fetchone()[0] + self.assertEqual(store.WAL_CHECKPOINT_PAGES * page, 64 << 20) + finally: + s.close() + + +@unittest.skipUnless(store.fcntl and os.name == "posix", "Linux only") +class NoCow(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def fake_ioctl(self, current, fail=None): + calls = [] + + def ioctl(fd, req, arg): + calls.append((req, struct.unpack("q", arg)[0])) + if fail and req == fail: + raise OSError(25, "Inappropriate ioctl for device") + return struct.pack("q", current) if req == store.FS_IOC_GETFLAGS else arg + return ioctl, calls + + def test_sets_the_attribute_and_keeps_other_flags(self): + ioctl, calls = self.fake_ioctl(0x1000) + with mock.patch.object(store.sys, "platform", "linux"), mock.patch.object(store.fcntl, "ioctl", ioctl): + self.assertTrue(store.no_cow(self.dir)) + self.assertEqual(calls[-1], (store.FS_IOC_SETFLAGS, 0x1000 | store.FS_NOCOW_FL)) + + def test_already_set_is_left_alone(self): + ioctl, calls = self.fake_ioctl(store.FS_NOCOW_FL) + with mock.patch.object(store.sys, "platform", "linux"), mock.patch.object(store.fcntl, "ioctl", ioctl): + self.assertTrue(store.no_cow(self.dir)) + self.assertEqual([c[0] for c in calls], [store.FS_IOC_GETFLAGS]) + + def test_other_file_systems_are_fine(self): + for fail in (store.FS_IOC_GETFLAGS, store.FS_IOC_SETFLAGS): + ioctl, _ = self.fake_ioctl(0, fail=fail) + with mock.patch.object(store.sys, "platform", "linux"), mock.patch.object(store.fcntl, "ioctl", ioctl): + self.assertFalse(store.no_cow(self.dir)) + self.assertFalse(store.no_cow(os.path.join(self.dir, "missing"))) + + def test_store_marks_its_network_directory(self): + seen = [] + with mock.patch.object(store, "no_cow", side_effect=seen.append): + store.Store(os.path.join(self.dir, "mainnet", "bmv.sqlite")).close() + store.Store(os.path.join(self.dir, "mainnet", "bmv.sqlite"), readonly=True).db.close() + self.assertEqual(seen, [os.path.join(self.dir, "mainnet")]) # the writer only + + +@unittest.skipUnless(BTRFS_DIR, "no btrfs test directory (set BMV_BTRFS_DIR)") +class NoCowOnBtrfs(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp(dir=BTRFS_DIR) + + def tearDown(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def test_database_files_are_created_nodatacow(self): + net = os.path.join(self.dir, "mainnet") + s = store.Store(os.path.join(net, "bmv.sqlite")) + try: + s.begin() + s.set_meta("probe", "1") + s.commit() + names = sorted(os.listdir(net)) + self.assertIn("bmv.sqlite", names) + self.assertTrue(flags(net) & store.FS_NOCOW_FL, "directory not nodatacow") + for name in names: + self.assertTrue(flags(os.path.join(net, name)) & store.FS_NOCOW_FL, f"{name} not nodatacow") + finally: + s.close() + + def test_existing_files_keep_their_attribute(self): + net = os.path.join(self.dir, "signet") + os.makedirs(net) + old = os.path.join(net, "spent-filter.bin") + with open(old, "wb") as f: + f.write(b"x" * 4096) + store.Store(os.path.join(net, "bmv.sqlite")).close() + self.assertFalse(flags(old) & store.FS_NOCOW_FL) + self.assertTrue(flags(os.path.join(net, "bmv.sqlite")) & store.FS_NOCOW_FL) + + +if __name__ == "__main__": + unittest.main()