arch-mirror-receiver 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ .venv/
2
+ __pycache__/
3
+ dist/
4
+ *.egg-info/
5
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 arch-mirror-krdp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.5
2
+ Name: arch-mirror-receiver
3
+ Version: 0.1.0
4
+ Summary: Builds and serves a verified Arch Linux mirror from chunks shipped by arch-mirror-downloader
5
+ Project-URL: Repository, https://github.com/arch-mirror-krdp/arch-mirror
6
+ Author: arch-mirror-krdp
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Operating System :: POSIX :: Linux
10
+ Classifier: Programming Language :: Python :: 3.14
11
+ Classifier: Topic :: System :: Archiving :: Mirroring
12
+ Requires-Python: >=3.14
13
+ Requires-Dist: pydantic>=2
14
+ Requires-Dist: pyyaml>=6
15
+ Requires-Dist: typer>=0.12
16
+ Description-Content-Type: text/markdown
17
+
18
+ # arch-mirror-receiver
19
+
20
+ Builds and serves a verified Arch Linux mirror from the chunks
21
+ [arch-mirror-downloader](https://pypi.org/project/arch-mirror-downloader/) ships.
22
+
23
+ The service polls an inbox (polling, not inotify, so it works on a read-only network share) and
24
+ only ever reads it. For each new chunk it checks the magic, extracts it, and checks every file
25
+ against the chunk's `message.json`; a damaged chunk is rejected whole. Files join a hardlinked
26
+ copy of the current snapshot. Once a snapshot's last chunk is in, it drops files the new state no
27
+ longer has, verifies every package against its repo database, writes `index.html`, `style.css`
28
+ and `snapshot.json`, and only then switches `root/current`. Clients never see a half-updated
29
+ mirror. Chunks can come in any order; one made for a snapshot that isn't here yet waits.
30
+
31
+ Which chunks were applied is kept in `root/receiver.db` (by name, size and mtime), along with a
32
+ checksum cache keyed by inode, so no file is hashed twice. A chunk that is still being copied in
33
+ (modified less than `settle_seconds` ago) is left for the next poll.
34
+
35
+ ## Install
36
+
37
+ ```sh
38
+ sudo useradd --system --home-dir /srv/arch-mirror arch-mirror
39
+ sudo UV_TOOL_DIR=/opt/uv-tools UV_TOOL_BIN_DIR=/usr/local/bin uv tool install arch-mirror-receiver
40
+ arch-mirror-receiver default-config | sudo install -Dm644 /dev/stdin /etc/arch-mirror-receiver/config.yaml # then edit
41
+ sudo install -d -o arch-mirror -g arch-mirror /srv/arch-mirror
42
+ sudo install -m644 systemd/arch-mirror-receiver.service /etc/systemd/system/
43
+ sudo systemctl daemon-reload && sudo systemctl enable --now arch-mirror-receiver
44
+ ```
45
+
46
+ `default-config` prints every setting with its default and what it does. The units in `systemd/`
47
+ are in the [repository](https://github.com/arch-mirror-krdp/arch-mirror/tree/main/packages/receiver).
48
+
49
+ Serve `root/current/` with any web server. Its `index.html` shows the snapshot, when upstream
50
+ reached that state and when it was published here, each repo's size, what changed, the packages
51
+ built from the AUR, and a pacman.conf snippet. Clients:
52
+
53
+ ```ini
54
+ [core]
55
+ Server = http://mirror.example/$repo/os/$arch
56
+ # likewise extra, multilib, the -debug repos
57
+ [aur]
58
+ SigLevel = Optional TrustAll # built by the downloader, unsigned
59
+ Server = http://mirror.example/$repo/os/$arch
60
+ ```
61
+
62
+ ## Use
63
+
64
+ ```sh
65
+ arch-mirror-receiver watch # the service
66
+ arch-mirror-receiver apply # one pass
67
+ arch-mirror-receiver status # current snapshot, recent chunks and their state
68
+ arch-mirror-receiver default-config # commented default config (YAML) on stdout
69
+ ```
@@ -0,0 +1,52 @@
1
+ # arch-mirror-receiver
2
+
3
+ Builds and serves a verified Arch Linux mirror from the chunks
4
+ [arch-mirror-downloader](https://pypi.org/project/arch-mirror-downloader/) ships.
5
+
6
+ The service polls an inbox (polling, not inotify, so it works on a read-only network share) and
7
+ only ever reads it. For each new chunk it checks the magic, extracts it, and checks every file
8
+ against the chunk's `message.json`; a damaged chunk is rejected whole. Files join a hardlinked
9
+ copy of the current snapshot. Once a snapshot's last chunk is in, it drops files the new state no
10
+ longer has, verifies every package against its repo database, writes `index.html`, `style.css`
11
+ and `snapshot.json`, and only then switches `root/current`. Clients never see a half-updated
12
+ mirror. Chunks can come in any order; one made for a snapshot that isn't here yet waits.
13
+
14
+ Which chunks were applied is kept in `root/receiver.db` (by name, size and mtime), along with a
15
+ checksum cache keyed by inode, so no file is hashed twice. A chunk that is still being copied in
16
+ (modified less than `settle_seconds` ago) is left for the next poll.
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ sudo useradd --system --home-dir /srv/arch-mirror arch-mirror
22
+ sudo UV_TOOL_DIR=/opt/uv-tools UV_TOOL_BIN_DIR=/usr/local/bin uv tool install arch-mirror-receiver
23
+ arch-mirror-receiver default-config | sudo install -Dm644 /dev/stdin /etc/arch-mirror-receiver/config.yaml # then edit
24
+ sudo install -d -o arch-mirror -g arch-mirror /srv/arch-mirror
25
+ sudo install -m644 systemd/arch-mirror-receiver.service /etc/systemd/system/
26
+ sudo systemctl daemon-reload && sudo systemctl enable --now arch-mirror-receiver
27
+ ```
28
+
29
+ `default-config` prints every setting with its default and what it does. The units in `systemd/`
30
+ are in the [repository](https://github.com/arch-mirror-krdp/arch-mirror/tree/main/packages/receiver).
31
+
32
+ Serve `root/current/` with any web server. Its `index.html` shows the snapshot, when upstream
33
+ reached that state and when it was published here, each repo's size, what changed, the packages
34
+ built from the AUR, and a pacman.conf snippet. Clients:
35
+
36
+ ```ini
37
+ [core]
38
+ Server = http://mirror.example/$repo/os/$arch
39
+ # likewise extra, multilib, the -debug repos
40
+ [aur]
41
+ SigLevel = Optional TrustAll # built by the downloader, unsigned
42
+ Server = http://mirror.example/$repo/os/$arch
43
+ ```
44
+
45
+ ## Use
46
+
47
+ ```sh
48
+ arch-mirror-receiver watch # the service
49
+ arch-mirror-receiver apply # one pass
50
+ arch-mirror-receiver status # current snapshot, recent chunks and their state
51
+ arch-mirror-receiver default-config # commented default config (YAML) on stdout
52
+ ```
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "arch-mirror-receiver"
3
+ version = "0.1.0"
4
+ description = "Builds and serves a verified Arch Linux mirror from chunks shipped by arch-mirror-downloader"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "arch-mirror-krdp" }]
9
+ requires-python = ">=3.14"
10
+ dependencies = ["typer>=0.12", "pydantic>=2", "pyyaml>=6"]
11
+ classifiers = ["Programming Language :: Python :: 3.14", "Operating System :: POSIX :: Linux", "Topic :: System :: Archiving :: Mirroring"]
12
+
13
+ [project.scripts]
14
+ arch-mirror-receiver = "arch_mirror_receiver.cli:app"
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/arch-mirror-krdp/arch-mirror"
18
+
19
+ [build-system]
20
+ requires = ["hatchling"]
21
+ build-backend = "hatchling.build"
@@ -0,0 +1,86 @@
1
+ """arch-mirror-receiver: build a served Arch mirror from the chunks arch-mirror-downloader ships."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fcntl
6
+ import signal
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Annotated
11
+
12
+ import typer
13
+
14
+ from .config import DEFAULT_CONFIG, default_yaml, load
15
+ from .receiver import Receiver
16
+
17
+ app = typer.Typer(no_args_is_help=True, add_completion=False, help=__doc__)
18
+ ConfigOpt = Annotated[Path, typer.Option("--config", "-c", envvar="ARCH_MIRROR_RECEIVER_CONFIG", help="YAML config")]
19
+
20
+
21
+ def log(msg: str) -> None:
22
+ print(f"arch-mirror-receiver: {msg}", file=sys.stderr, flush=True)
23
+
24
+
25
+ def _open(config: Path) -> Receiver:
26
+ cfg = load(config)
27
+ cfg.root.mkdir(parents=True, exist_ok=True)
28
+ lock = open(cfg.root / ".lock", "w")
29
+ try:
30
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
31
+ except BlockingIOError:
32
+ log(f"another arch-mirror-receiver holds {cfg.root}/.lock")
33
+ raise typer.Exit(1)
34
+ r = Receiver(cfg, log)
35
+ r._lock = lock # held for the life of the process
36
+ return r
37
+
38
+
39
+ @app.command()
40
+ def apply(config: ConfigOpt = DEFAULT_CONFIG) -> None:
41
+ """Apply what's new in the inbox once; publish if a snapshot is complete."""
42
+ _open(config).scan()
43
+
44
+
45
+ @app.command()
46
+ def watch(config: ConfigOpt = DEFAULT_CONFIG) -> None:
47
+ """Poll the inbox forever (the service). Polling, not inotify: it works on network shares."""
48
+ r = _open(config)
49
+ stop = False
50
+
51
+ def _stop(*_: object) -> None:
52
+ nonlocal stop
53
+ stop = True
54
+ signal.signal(signal.SIGTERM, _stop)
55
+ signal.signal(signal.SIGINT, _stop)
56
+ log(f"watching {r.cfg.inbox} every {r.cfg.poll_interval:g}s; serving {r.cfg.root}/current")
57
+ while not stop:
58
+ try:
59
+ r.scan()
60
+ except OSError as e: # a share that dropped away comes back
61
+ log(f"scan failed: {e}")
62
+ deadline = time.monotonic() + r.cfg.poll_interval
63
+ while not stop and time.monotonic() < deadline:
64
+ time.sleep(0.5)
65
+
66
+
67
+ @app.command()
68
+ def status(config: ConfigOpt = DEFAULT_CONFIG) -> None:
69
+ """Current snapshot, and chunks seen."""
70
+ cfg = load(config)
71
+ r = Receiver(cfg, log)
72
+ print(f"current: {r.current_id()}")
73
+ for name, st, detail in r.db.execute("SELECT name, status, detail FROM chunks ORDER BY name DESC LIMIT 20"):
74
+ print(f" {st:8} {name} {detail}")
75
+ if r.meta("final"):
76
+ print("a complete snapshot is waiting for missing files (see the log)")
77
+
78
+
79
+ @app.command("default-config")
80
+ def default_config() -> None:
81
+ """Print a commented default config (YAML) to stdout."""
82
+ typer.echo(default_yaml())
83
+
84
+
85
+ if __name__ == "__main__":
86
+ app()
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import yaml
6
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
7
+
8
+ from .format import dump_defaults
9
+
10
+ DEFAULT_CONFIG = Path("/etc/arch-mirror-receiver/config.yaml")
11
+
12
+
13
+ class Config(BaseModel):
14
+ model_config = ConfigDict(extra="forbid")
15
+
16
+ inbox: Path = Field(description="Where chunks arrive; only ever read (a read-only network share is fine).",
17
+ examples=[Path("/mnt/inbox")])
18
+ root: Path = Field(Path("/srv/arch-mirror"), description="snapshots/ and current; serve root/current over http.")
19
+ chunk_magic: str = Field("AMC1", description="Must match the downloader.")
20
+ chunk_suffix: str = Field(".amc", description="Chunk file name ending; must match the downloader.")
21
+ keep: int = Field(3, description="Snapshots kept.")
22
+ poll_interval: float = Field(30.0, description="Seconds between inbox scans (polling works on network shares).")
23
+ settle_seconds: float = Field(10.0, description="A chunk modified more recently than this may still be arriving.")
24
+ title: str = Field("Arch Linux mirror", description="Shown on the status page.")
25
+ url: str = Field("", description="How clients reach root/current, for the page's pacman.conf snippet.")
26
+
27
+ @field_validator("chunk_magic")
28
+ @classmethod
29
+ def _magic(cls, v: str) -> str:
30
+ if len(v.encode()) != 4:
31
+ raise ValueError("chunk_magic must be exactly 4 bytes")
32
+ return v
33
+
34
+ @field_validator("chunk_suffix")
35
+ @classmethod
36
+ def _suffix(cls, v: str) -> str:
37
+ if not v or "/" in v or v.endswith(".part"):
38
+ raise ValueError("chunk_suffix must be non-empty, without / and not .part")
39
+ return v
40
+
41
+
42
+ def default_yaml() -> str:
43
+ return dump_defaults(Config, f"arch-mirror-receiver config: {DEFAULT_CONFIG}")
44
+
45
+
46
+ def load(path: Path) -> Config:
47
+ """The config at path; a missing or invalid one ends the program with a short message."""
48
+ try:
49
+ return Config.model_validate(yaml.safe_load(path.read_text()) or {})
50
+ except FileNotFoundError:
51
+ raise SystemExit(f"arch-mirror-receiver: no config at {path}; "
52
+ f"start from: arch-mirror-receiver default-config > {path}")
53
+ except yaml.YAMLError as e:
54
+ raise SystemExit(f"arch-mirror-receiver: {path} is not valid YAML: {e}")
55
+ except ValidationError as e:
56
+ problems = "\n".join(f" {'.'.join(map(str, x['loc'])) or 'config'}: {x['msg']}" for x in e.errors())
57
+ raise SystemExit(f"arch-mirror-receiver: {path}:\n{problems}")
@@ -0,0 +1,87 @@
1
+ """Chunk format, repo database parsing and config dumping, shared by arch-mirror-downloader and
2
+ arch-mirror-receiver.
3
+
4
+ Both packages carry an identical copy of this file (a test keeps them in sync).
5
+
6
+ A chunk is CHUNK_MAGIC (4 bytes) followed by a POSIX tar. Payload members sit at their repo paths
7
+ (``core/os/x86_64/foo.pkg.tar.zst``); the last member is ``message.json``, a ``Message`` listing
8
+ every payload file with its sha256. The last chunk of a snapshot carries ``final``: the snapshot id,
9
+ upstream stamp, repos and the full file list.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import tarfile
15
+ from pathlib import Path, PurePosixPath
16
+ from typing import Literal
17
+
18
+ import yaml
19
+ from pydantic import BaseModel
20
+
21
+ MESSAGE = "message.json"
22
+ FORMAT = 1
23
+
24
+
25
+ class FileEntry(BaseModel):
26
+ path: str
27
+ sha256: str
28
+ size: int
29
+ repo: str = ""
30
+ name: str = "" # package name; empty for signatures and databases
31
+ version: str = ""
32
+
33
+
34
+ class Final(BaseModel):
35
+ id: str
36
+ stamp: int
37
+ repos: list[str]
38
+ manifest: list[str] # every file of the snapshot
39
+
40
+
41
+ class Message(BaseModel):
42
+ format: Literal[1] = FORMAT
43
+ chunk: str
44
+ base: str # snapshot id the receiver must be at, or "full"
45
+ files: list[FileEntry]
46
+ final: Final | None = None
47
+
48
+
49
+ def safe_member(name: str) -> bool:
50
+ """A relative path that stays inside the extraction dir."""
51
+ p = PurePosixPath(name)
52
+ return bool(name) and not p.is_absolute() and ".." not in p.parts and "" not in name.split("/")
53
+
54
+
55
+ def parse_desc(text: str) -> dict[str, str]:
56
+ """First value of each %KEY% block of a pacman desc file."""
57
+ out: dict[str, str] = {}
58
+ lines = text.splitlines()
59
+ for i, line in enumerate(lines):
60
+ if line.startswith("%") and line.endswith("%") and i + 1 < len(lines):
61
+ out[line.strip("%")] = lines[i + 1]
62
+ return out
63
+
64
+
65
+ def parse_db(db: Path, repo: str) -> list[FileEntry]:
66
+ """Every package a pacman repo database lists (gzip, zstd or plain tar; an empty db yields none)."""
67
+ out = []
68
+ with tarfile.open(db, "r:*") as t:
69
+ for m in t:
70
+ if m.isfile() and m.name.endswith("/desc"):
71
+ f = t.extractfile(m)
72
+ assert f is not None
73
+ d = parse_desc(f.read().decode())
74
+ out.append(FileEntry(path=f"{repo}/os/x86_64/{d['FILENAME']}", sha256=d.get("SHA256SUM", ""),
75
+ size=int(d.get("CSIZE", 0)), repo=repo, name=d["NAME"], version=d["VERSION"]))
76
+ return out
77
+
78
+
79
+ def dump_defaults(model: type[BaseModel], header: str) -> str:
80
+ """A commented YAML config: every field's description, then its default (or example, if required)."""
81
+ out = [f"# {header}", ""]
82
+ for name, f in model.model_fields.items():
83
+ out += [f"# {line}".rstrip() for line in (f.description or "").splitlines()]
84
+ value = f.examples[0] if f.is_required() and f.examples else f.default
85
+ value = str(value) if isinstance(value, Path) else value
86
+ out += [yaml.safe_dump({name: value}, sort_keys=False, width=100).rstrip(), ""]
87
+ return "\n".join(out)
@@ -0,0 +1,256 @@
1
+ """Chunks from the inbox -> verified snapshots in ROOT/snapshots, ROOT/current pointing at the newest.
2
+
3
+ The inbox is only read. Which chunks were applied (or rejected) is kept in ROOT/receiver.db, keyed
4
+ by name, size and mtime: a chunk that changes (re-sent, or still arriving) is looked at again.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import shutil
13
+ import sqlite3
14
+ import tarfile
15
+ import time
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Callable
19
+
20
+ from pydantic import ValidationError
21
+
22
+ from .config import Config
23
+ from .format import MESSAGE, FileEntry, Final, Message, parse_db, safe_member
24
+ from .ui import Snapshot, write_site
25
+
26
+ SCHEMA = """
27
+ CREATE TABLE IF NOT EXISTS chunks (name TEXT PRIMARY KEY, size INT, mtime_ns INT, status TEXT,
28
+ detail TEXT, at TEXT);
29
+ CREATE TABLE IF NOT EXISTS hashes (key TEXT PRIMARY KEY, sha256 TEXT);
30
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
31
+ """
32
+
33
+
34
+ class Rejected(Exception):
35
+ """The chunk is bad as it is (until it changes)."""
36
+
37
+
38
+ class Waiting(Exception):
39
+ """The chunk is fine but can't go in yet (its base snapshot isn't here yet)."""
40
+
41
+
42
+ def now() -> str:
43
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
44
+
45
+
46
+ class Receiver:
47
+ def __init__(self, cfg: Config, log: Callable[[str], None]):
48
+ self.cfg, self.log = cfg, log
49
+ cfg.root.mkdir(parents=True, exist_ok=True)
50
+ (cfg.root / "snapshots").mkdir(exist_ok=True)
51
+ self.db = sqlite3.connect(cfg.root / "receiver.db")
52
+ self.db.executescript(SCHEMA)
53
+ self.incoming = cfg.root / "snapshots/.incoming"
54
+ self.unpack = cfg.root / ".unpack"
55
+
56
+ # -- state -------------------------------------------------------------------------------
57
+ def meta(self, key: str) -> str | None:
58
+ row = self.db.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
59
+ return row[0] if row else None
60
+
61
+ def set_meta(self, key: str, value: str | None) -> None:
62
+ if value is None:
63
+ self.db.execute("DELETE FROM meta WHERE key = ?", (key,))
64
+ else:
65
+ self.db.execute("INSERT OR REPLACE INTO meta VALUES (?, ?)", (key, value))
66
+ self.db.commit()
67
+
68
+ def current_id(self) -> str:
69
+ cur = self.cfg.root / "current"
70
+ return os.readlink(cur).rsplit("/", 1)[-1] if cur.is_symlink() else "none"
71
+
72
+ def sha256(self, p: Path) -> str:
73
+ """sha256 of p, read only once per dev:inode, mtime and size (snapshots hardlink)."""
74
+ st = p.stat()
75
+ key = f"{st.st_dev}:{st.st_ino}:{st.st_mtime_ns}:{st.st_size}"
76
+ row = self.db.execute("SELECT sha256 FROM hashes WHERE key = ?", (key,)).fetchone()
77
+ if row:
78
+ return row[0]
79
+ h = hashlib.sha256()
80
+ with open(p, "rb") as f:
81
+ while b := f.read(1 << 20):
82
+ h.update(b)
83
+ self.remember(p, h.hexdigest())
84
+ return h.hexdigest()
85
+
86
+ def remember(self, p: Path, sha: str) -> None:
87
+ st = p.stat()
88
+ self.db.execute("INSERT OR REPLACE INTO hashes VALUES (?, ?)",
89
+ (f"{st.st_dev}:{st.st_ino}:{st.st_mtime_ns}:{st.st_size}", sha))
90
+
91
+ # -- inbox -------------------------------------------------------------------------------
92
+ def scan(self) -> bool:
93
+ """Apply every new chunk in the inbox; publish if a snapshot became complete. True if published."""
94
+ applied = False
95
+ for p in sorted(self.cfg.inbox.iterdir()):
96
+ if not p.name.endswith(self.cfg.chunk_suffix) or not p.is_file():
97
+ continue
98
+ st = p.stat()
99
+ row = self.db.execute("SELECT size, mtime_ns, status FROM chunks WHERE name = ?", (p.name,)).fetchone()
100
+ if row and row[:2] == (st.st_size, st.st_mtime_ns) and row[2] in ("ok", "bad"):
101
+ continue
102
+ if time.time() - st.st_mtime < self.cfg.settle_seconds:
103
+ continue # may still be arriving
104
+ try:
105
+ n = self.apply(p)
106
+ status, detail = "ok", f"{n} files"
107
+ applied = True
108
+ self.log(f"{p.name}: {n} files in")
109
+ except Waiting as e:
110
+ status, detail = "waiting", str(e)
111
+ if not row or row[2] != "waiting":
112
+ self.log(f"{p.name}: waiting: {e}")
113
+ except (Rejected, tarfile.TarError, ValidationError, EOFError) as e:
114
+ status, detail = "bad", str(e).splitlines()[0][:500]
115
+ self.log(f"{p.name}: rejected: {detail}")
116
+ self.db.execute("INSERT OR REPLACE INTO chunks VALUES (?, ?, ?, ?, ?, ?)",
117
+ (p.name, st.st_size, st.st_mtime_ns, status, detail, now()))
118
+ self.db.commit()
119
+ if applied or self.meta("retry_publish"):
120
+ return self.try_publish()
121
+ return False
122
+
123
+ def apply(self, path: Path) -> int:
124
+ """Check one chunk against its message.json, then add its files to the incoming snapshot."""
125
+ shutil.rmtree(self.unpack, ignore_errors=True)
126
+ self.unpack.mkdir()
127
+ got: dict[str, str] = {}
128
+ msg = None
129
+ with open(path, "rb") as f:
130
+ if f.read(4) != self.cfg.chunk_magic.encode():
131
+ raise Rejected(f"not a chunk: does not start with {self.cfg.chunk_magic!r}")
132
+ with tarfile.open(fileobj=f, mode="r|") as t:
133
+ for m in t:
134
+ if not m.isfile() or not safe_member(m.name) or m.name in got:
135
+ raise Rejected(f"unexpected member {m.name!r}")
136
+ src = t.extractfile(m)
137
+ assert src is not None
138
+ if m.name == MESSAGE:
139
+ msg = Message.model_validate_json(src.read())
140
+ continue
141
+ dest = self.unpack / m.name
142
+ dest.parent.mkdir(parents=True, exist_ok=True)
143
+ h = hashlib.sha256()
144
+ with open(dest, "wb") as out:
145
+ while b := src.read(1 << 20):
146
+ h.update(b)
147
+ out.write(b)
148
+ got[m.name] = h.hexdigest()
149
+ if msg is None:
150
+ raise Rejected("no message.json (truncated?)")
151
+ want = {e.path: e.sha256 for e in msg.files}
152
+ if got != want:
153
+ bad = sorted(set(got) ^ set(want)) + sorted(p for p in got if p in want and got[p] != want[p])
154
+ raise Rejected(f"files not as message.json says: {', '.join(bad[:5])}")
155
+ self._start(msg.base)
156
+ for p, sha in got.items():
157
+ dest = self.incoming / p
158
+ dest.parent.mkdir(parents=True, exist_ok=True)
159
+ os.replace(self.unpack / p, dest) # replaces, never writes through a hardlink
160
+ self.remember(dest, sha)
161
+ if msg.final:
162
+ self.set_meta("final", msg.final.model_dump_json())
163
+ chunks = json.loads(self.meta("incoming_chunks") or "[]") + [msg.chunk]
164
+ self.set_meta("incoming_chunks", json.dumps(chunks))
165
+ (self.cfg.root / "messages").mkdir(exist_ok=True)
166
+ (self.cfg.root / "messages" / f"{path.name}.json").write_text(msg.model_dump_json(indent=1))
167
+ shutil.rmtree(self.unpack, ignore_errors=True)
168
+ return len(got)
169
+
170
+ def _start(self, base: str) -> None:
171
+ """Make sure incoming is a copy of the snapshot this chunk was made for."""
172
+ cur = self.current_id()
173
+ if self.incoming.is_dir() and self.meta("incoming_base") == base:
174
+ return
175
+ if base not in ("full", cur):
176
+ raise Waiting(f"made for snapshot {base}, this mirror is at {cur}")
177
+ shutil.rmtree(self.incoming, ignore_errors=True)
178
+ if cur != "none":
179
+ shutil.copytree(self.cfg.root / "current", self.incoming, copy_function=os.link)
180
+ for f in ("index.html", "style.css", "snapshot.json"):
181
+ (self.incoming / f).unlink(missing_ok=True)
182
+ else:
183
+ self.incoming.mkdir()
184
+ for k in ("final", "incoming_chunks"):
185
+ self.set_meta(k, None)
186
+ self.set_meta("incoming_base", base)
187
+
188
+ # -- publish -----------------------------------------------------------------------------
189
+ def try_publish(self) -> bool:
190
+ raw = self.meta("final")
191
+ if not raw or not self.incoming.is_dir():
192
+ return False
193
+ final = Final.model_validate_json(raw)
194
+ keep = set(final.manifest)
195
+ for p in [p for p in self.incoming.rglob("*") if p.is_file()]:
196
+ if str(p.relative_to(self.incoming)) not in keep:
197
+ p.unlink() # old package versions
198
+ bad, pkgs = self.verify(final)
199
+ if bad:
200
+ self.log(f"snapshot {final.id}: {len(bad)} files missing or bad, current left unchanged; "
201
+ f"waiting for more chunks: {', '.join(bad[:5])}")
202
+ self.set_meta("retry_publish", "1")
203
+ return False
204
+ self.publish(final, pkgs)
205
+ return True
206
+
207
+ def verify(self, final: Final) -> tuple[list[str], dict[str, list[FileEntry]]]:
208
+ """Every file in the manifest is there, and every package has its db's sha256."""
209
+ bad = [p for p in final.manifest if not (self.incoming / p).is_file()]
210
+ pkgs: dict[str, list[FileEntry]] = {}
211
+ for r in final.repos:
212
+ db = self.incoming / r / "os/x86_64" / f"{r}.db"
213
+ if not db.is_file():
214
+ continue # already in bad
215
+ pkgs[r] = parse_db(db, r)
216
+ for e in pkgs[r]:
217
+ p = self.incoming / e.path
218
+ if p.is_file() and self.sha256(p) != e.sha256:
219
+ bad.append(e.path)
220
+ p.unlink()
221
+ self.db.commit()
222
+ return bad, pkgs
223
+
224
+ def publish(self, final: Final, pkgs: dict[str, list[FileEntry]]) -> None:
225
+ root = self.cfg.root
226
+ # a published snapshot is never replaced (current may point at it): a repeat id, e.g. after
227
+ # the downloader was reset, gets the next free suffix
228
+ sid, n = final.id, 2
229
+ while (root / "snapshots" / sid).exists():
230
+ sid, n = f"{final.id.split('r')[0]}r{n}", n + 1
231
+ final = final.model_copy(update={"id": sid})
232
+ prev: dict[tuple[str, str], str] = {}
233
+ if (root / "current").is_dir():
234
+ for r in final.repos:
235
+ db = root / "current" / r / "os/x86_64" / f"{r}.db"
236
+ if db.is_file():
237
+ prev.update({(e.repo, e.name): e.version for e in parse_db(db, r)})
238
+ snap = Snapshot.build(final, pkgs, prev, json.loads(self.meta("incoming_chunks") or "[]"),
239
+ self.cfg, sorted(p.name for p in (root / "snapshots").iterdir()
240
+ if not p.name.startswith(".")))
241
+ write_site(self.incoming, snap, self.cfg)
242
+ dest = root / "snapshots" / final.id
243
+ self.incoming.rename(dest)
244
+ os.utime(dest) # kept snapshots are pruned oldest-published first
245
+ tmp = root / "current.new"
246
+ tmp.unlink(missing_ok=True)
247
+ tmp.symlink_to(f"snapshots/{final.id}")
248
+ tmp.replace(root / "current")
249
+ snaps = sorted((p for p in (root / "snapshots").iterdir() if not p.name.startswith(".")),
250
+ key=lambda p: p.stat().st_mtime)
251
+ for old in snaps[:-self.cfg.keep]:
252
+ shutil.rmtree(old)
253
+ for k in ("final", "incoming_base", "incoming_chunks", "retry_publish"):
254
+ self.set_meta(k, None)
255
+ self.log(f"current = {final.id} (upstream {time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(final.stamp))}), "
256
+ f"{sum(len(v) for v in pkgs.values())} packages")
@@ -0,0 +1,27 @@
1
+ :root {
2
+ --bg: #f7f7f5; --fg: #1d1f21; --muted: #6b6f76; --card: #fff; --line: #e3e3df; --accent: #1793d1;
3
+ color-scheme: light dark;
4
+ }
5
+ @media (prefers-color-scheme: dark) {
6
+ :root { --bg: #16181b; --fg: #e6e6e3; --muted: #9a9ea6; --card: #1f2226; --line: #2e3238; --accent: #4fb3e8; }
7
+ }
8
+ * { box-sizing: border-box; }
9
+ body { margin: 0; background: var(--bg); color: var(--fg);
10
+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
11
+ main { max-width: 960px; margin: 0 auto; padding: 2rem 1.25rem 3rem; }
12
+ h1 { margin: 0; font-size: 1.6rem; }
13
+ h2 { font-size: 1.05rem; margin: 2rem 0 .6rem; }
14
+ a { color: var(--accent); }
15
+ .muted { color: var(--muted); }
16
+ header p { margin: .2rem 0 0; }
17
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: .75rem; margin-top: 1.5rem; }
18
+ .cards div { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .75rem .9rem; }
19
+ .cards span { display: block; color: var(--muted); font-size: .8rem; }
20
+ .cards b { font-size: 1.05rem; font-variant-numeric: tabular-nums; }
21
+ table { width: 100%; border-collapse: collapse; background: var(--card); border: 1px solid var(--line);
22
+ border-radius: 8px; overflow: hidden; font-variant-numeric: tabular-nums; }
23
+ th, td { text-align: left; padding: .45rem .75rem; border-bottom: 1px solid var(--line); }
24
+ th { font-size: .8rem; color: var(--muted); font-weight: 600; }
25
+ tr:last-child td { border-bottom: 0; }
26
+ pre { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .9rem; overflow-x: auto; }
27
+ footer { margin-top: 2.5rem; font-size: .85rem; }
@@ -0,0 +1,115 @@
1
+ """snapshot.json, index.html and style.css at the root of each published snapshot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from datetime import datetime, timezone
7
+ from html import escape
8
+ from importlib.resources import files
9
+ from pathlib import Path
10
+
11
+ from pydantic import BaseModel
12
+
13
+ from .config import Config
14
+ from .format import FileEntry, Final
15
+
16
+
17
+ class RepoInfo(BaseModel):
18
+ name: str
19
+ packages: int
20
+ size: int
21
+
22
+
23
+ class Change(BaseModel):
24
+ repo: str
25
+ name: str
26
+ old: str | None # None: new package
27
+ new: str | None # None: removed
28
+
29
+
30
+ class Package(BaseModel):
31
+ name: str
32
+ version: str
33
+ size: int
34
+
35
+
36
+ class Snapshot(BaseModel):
37
+ id: str
38
+ stamp: int
39
+ published: str
40
+ repos: list[RepoInfo]
41
+ aur: list[Package]
42
+ changes: list[Change]
43
+ chunks: list[str]
44
+ kept: list[str]
45
+
46
+ @classmethod
47
+ def build(cls, final: Final, pkgs: dict[str, list[FileEntry]], prev: dict[tuple[str, str], str],
48
+ chunks: list[str], cfg: Config, kept: list[str]) -> "Snapshot":
49
+ now = {(e.repo, e.name): e.version for es in pkgs.values() for e in es}
50
+ changes = [] if not prev else [
51
+ Change(repo=k[0], name=k[1], old=prev.get(k), new=now.get(k))
52
+ for k in sorted(set(now) | set(prev)) if prev.get(k) != now.get(k)]
53
+ return cls(id=final.id, stamp=final.stamp, published=datetime.now(timezone.utc).isoformat(timespec="seconds"),
54
+ repos=[RepoInfo(name=r, packages=len(es), size=sum(e.size for e in es)) for r, es in pkgs.items()],
55
+ aur=[Package(name=e.name, version=e.version, size=e.size) for e in pkgs.get("aur", [])],
56
+ changes=changes, chunks=chunks, kept=sorted(set(kept) | {final.id}))
57
+
58
+
59
+ def human(n: float) -> str:
60
+ for unit in ("B", "KiB", "MiB", "GiB"):
61
+ if n < 1024:
62
+ return f"{n:.1f} {unit}"
63
+ n /= 1024
64
+ return f"{n:.1f} TiB"
65
+
66
+
67
+ def _rows(rows: list[list[str]]) -> str:
68
+ return "\n".join("<tr>" + "".join(f"<td>{c}</td>" for c in r) + "</tr>" for r in rows)
69
+
70
+
71
+ def render(s: Snapshot, cfg: Config) -> str:
72
+ e = escape
73
+ upstream = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(s.stamp))
74
+ total = sum(r.size for r in s.repos)
75
+ url = cfg.url.rstrip("/") or "http://THIS-HOST"
76
+ conf = "\n".join(f"[{r.name}]\n" + ("SigLevel = Optional TrustAll\n" if r.name == "aur" else "")
77
+ + f"Server = {url}/$repo/os/$arch" for r in s.repos)
78
+ shown = s.changes[:500]
79
+ changes = _rows([[e(c.repo), e(c.name), e(c.old or "new"), e(c.new or "removed")] for c in shown])
80
+ more = f"<p class=muted>and {len(s.changes) - len(shown)} more</p>" if len(s.changes) > len(shown) else ""
81
+ return f"""<!doctype html>
82
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
83
+ <title>{e(cfg.title)} · {e(s.id)}</title><link rel="stylesheet" href="style.css"></head>
84
+ <body><main>
85
+ <header><h1>{e(cfg.title)}</h1><p class=muted>Arch Linux repositories, one consistent upstream state</p></header>
86
+ <section class=cards>
87
+ <div><span>Snapshot</span><b>{e(s.id)}</b></div>
88
+ <div><span>Upstream state</span><b>{upstream}</b></div>
89
+ <div><span>Updated here</span><b>{e(s.published.replace("T", " ").replace("+00:00", " UTC"))}</b></div>
90
+ <div><span>Packages</span><b>{sum(r.packages for r in s.repos)}</b></div>
91
+ <div><span>Size</span><b>{human(total)}</b></div>
92
+ </section>
93
+ <section><h2>Repositories</h2>
94
+ <table><thead><tr><th>Repo</th><th>Packages</th><th>Size</th></tr></thead><tbody>
95
+ {_rows([[f'<a href="{e(r.name)}/os/x86_64/">{e(r.name)}</a>', str(r.packages), human(r.size)] for r in s.repos])}
96
+ </tbody></table></section>
97
+ <section><h2>Changes in this snapshot</h2>
98
+ {f'<table><thead><tr><th>Repo</th><th>Package</th><th>Was</th><th>Now</th></tr></thead><tbody>{changes}</tbody></table>{more}'
99
+ if s.changes else '<p class=muted>First snapshot here, or nothing changed.</p>'}
100
+ </section>
101
+ {f'''<section><h2>Built here (AUR and local)</h2>
102
+ <table><thead><tr><th>Package</th><th>Version</th><th>Size</th></tr></thead><tbody>
103
+ {_rows([[e(p.name), e(p.version), human(p.size)] for p in s.aur])}
104
+ </tbody></table></section>''' if s.aur else ''}
105
+ <section><h2>Use it</h2><pre>{e(conf)}</pre></section>
106
+ <footer class=muted>Arrived in {len(s.chunks)} chunk(s): {e(", ".join(s.chunks))} ·
107
+ snapshots kept: {e(", ".join(s.kept))} · <a href="snapshot.json">snapshot.json</a></footer>
108
+ </main></body></html>
109
+ """
110
+
111
+
112
+ def write_site(dest: Path, s: Snapshot, cfg: Config) -> None:
113
+ (dest / "snapshot.json").write_text(s.model_dump_json(indent=1))
114
+ (dest / "index.html").write_text(render(s, cfg))
115
+ (dest / "style.css").write_text(files(__package__).joinpath("style.css").read_text())
@@ -0,0 +1,19 @@
1
+ [Unit]
2
+ Description=Build the served Arch Linux mirror from arriving chunks (arch-mirror-receiver)
3
+ Documentation=https://github.com/arch-mirror-krdp/arch-mirror
4
+ After=network-online.target remote-fs.target
5
+
6
+ [Service]
7
+ User=arch-mirror
8
+ Group=arch-mirror
9
+ ExecStart=/usr/local/bin/arch-mirror-receiver watch
10
+ Restart=on-failure
11
+ RestartSec=30
12
+ Nice=10
13
+ IOSchedulingClass=idle
14
+ PrivateTmp=yes
15
+ ProtectSystem=full
16
+ ProtectHome=yes
17
+
18
+ [Install]
19
+ WantedBy=multi-user.target