Compare commits
18
Commits
No files matched your search
@@ -1,10 +1,10 @@
|
||||
.PHONY: build check doctor dev-config dev-up dev-down dev-status dev-smoke dev-shell dev-restart-check dev-migration-test dev-native-build dev-native-test dev-smallfiles-test dev-million-start dev-million-status dev-million-finish
|
||||
.PHONY: build check doctor dev-config dev-up dev-down dev-status dev-smoke dev-shell dev-restart-check dev-native-build dev-native-test dev-smallfiles-test dev-million-start dev-million-status dev-million-finish
|
||||
build:
|
||||
go build -buildvcs=false -o bin/cephmig ./cmd/cephmig
|
||||
check:
|
||||
go vet ./...
|
||||
go test ./...
|
||||
bash -n dev/cluster.sh dev/client.sh dev/smoke.sh dev/restart-check.sh dev/migration-test.sh dev/native-test.sh dev/smallfiles-test.sh dev/million-start.sh dev/million-finish.sh
|
||||
bash -n dev/cluster.sh dev/client.sh dev/smoke.sh dev/restart-check.sh dev/native-test.sh dev/smallfiles-test.sh dev/million-start.sh dev/million-finish.sh
|
||||
python3 -c 'import ast,pathlib; [ast.parse(pathlib.Path(p).read_text()) for p in ("dev/native-fixture.py", "dev/smallfiles.py", "dev/million.py")]'
|
||||
doctor:
|
||||
go run ./cmd/cephmig doctor
|
||||
@@ -24,8 +24,6 @@ dev-shell:
|
||||
docker compose -f dev/compose.yaml exec client bash
|
||||
dev-restart-check:
|
||||
bash dev/restart-check.sh
|
||||
dev-migration-test: build
|
||||
docker compose -f dev/compose.yaml exec -T client timeout --kill-after=10s 600s bash /lab/migration-test.sh
|
||||
dev-native-build:
|
||||
docker compose -f dev/compose.yaml build native
|
||||
dev-native-test: dev-native-build
|
||||
|
||||
@@ -1,96 +1,140 @@
|
||||
# CephMig: CephFS-Subvolumes zwischen Ceph-Clustern migrieren
|
||||
# CephMig: migrate CephFS subvolumes between Ceph clusters
|
||||
|
||||
Ein Go-Werkzeug, das ein CephFS-Subvolume samt Snapshots, POSIX-ACLs, xattrs
|
||||
und Quotas von einem Ceph-Cluster in einen anderen kopiert, während die
|
||||
Anwendung weiterläuft.
|
||||
A Go tool that copies a CephFS subvolume, including its snapshots, POSIX ACLs,
|
||||
xattrs, quotas and timestamps, from one Ceph cluster to another while the
|
||||
application keeps running.
|
||||
|
||||
## Beschreibung
|
||||
## Description
|
||||
|
||||
**Warum?** Ein Subvolume soll mit kurzem Schreibstopp in einen neuen Cluster
|
||||
umziehen. Die Zielgröße liegt bei bis zu 200 TB und mehr als 200 Millionen
|
||||
Dateien. Ein einfaches Kopieren reicht dafür nicht: Snapshots, Hardlinks und
|
||||
Ceph-Metadaten müssen erhalten bleiben, und ein abgebrochener Lauf muss sich
|
||||
fortsetzen lassen.
|
||||
**Why?** A subvolume has to move to a new cluster with only a short write
|
||||
stop. The target size is up to 200 TB and more than 200 million files. A
|
||||
plain copy is not enough: snapshots, hardlinks and Ceph metadata must be
|
||||
preserved, and an interrupted run must be resumable.
|
||||
|
||||
**Wie?** CephMig arbeitet in Runden. Jede Runde überträgt einen konsistenten
|
||||
Quellsnapshot, prüft das Ziel und legt dort einen gleichnamigen Snapshot an.
|
||||
Ein Journal auf lokalem Datenträger hält jeden Schritt fest. Für den letzten
|
||||
Abgleich werden alle Schreiber kurz angehalten.
|
||||
**How?** CephMig works in rounds. Each round transfers a consistent source
|
||||
snapshot, verifies the target and creates a snapshot of the same name there.
|
||||
A journal on local disk records every step. For the last round, all writers
|
||||
are stopped briefly.
|
||||
|
||||
Es gibt zwei Backends:
|
||||
The copier talks to both clusters directly through libcephfs. It needs no
|
||||
kernel or FUSE mount. After the initial transfer it uses snapdiff and, where
|
||||
possible, blockdiff.
|
||||
|
||||
- **native** (empfohlen): Der Kopierer spricht direkt über libcephfs mit
|
||||
beiden Clustern. Er braucht weder rsync noch einen Kernel- oder FUSE-Mount.
|
||||
Nach der Erstübertragung nutzt er Snapdiff und, wo möglich, Blockdiff.
|
||||
- **rsync**: Er kopiert zwischen zwei gemounteten CephFS-Dateisystemen.
|
||||
**Status:** prototype. The features are verified in the local lab. Load
|
||||
tests at the target size and a production cutover are still missing.
|
||||
|
||||
**Status:** Prototyp. Die Funktionen sind im lokalen Labor geprüft.
|
||||
Lastnachweise für die Zielgröße und die produktive Umschaltung fehlen noch.
|
||||
|
||||
> **Dokumentierte Abweichung:** Native Snapshot-IDs und Ceph-Geburtszeitpunkte
|
||||
> werden am Ziel neu vergeben. Die ursprünglichen Erstellungszeiten stehen im
|
||||
> Journal. Details: [docs/migration.md](docs/migration.md).
|
||||
> **Documented deviations:** native snapshot IDs and snapshot creation times
|
||||
> are assigned anew at the target. CephMig takes mtime, atime,
|
||||
> ctime and birth time (btime) of every file from the source; the ctime is
|
||||
> never lower than the mtime. The original snapshot creation times are kept
|
||||
> in the journal.
|
||||
> Details: [docs/migration.md](docs/migration.md).
|
||||
|
||||
## Installation
|
||||
|
||||
Voraussetzungen:
|
||||
Requirements:
|
||||
|
||||
- Linux, Go ab 1.25 und GNU Make
|
||||
- für das native Backend und die Laborumgebung: Docker Engine mit Docker
|
||||
Compose sowie `/dev/fuse` auf dem Docker-Host
|
||||
- für die Laborumgebung: bis zu 12 GiB RAM für Container und etwa 8 GiB
|
||||
Speicherplatz für die zwei OSDs, dazu Platz für die Images
|
||||
- Linux, Go 1.25 or later and GNU Make
|
||||
- for building the copier: Docker Engine with Docker Compose (the build
|
||||
runs in a container)
|
||||
- for the lab in addition: `/dev/fuse` on the Docker host, for the
|
||||
independent application client
|
||||
- for the lab: up to 12 GiB RAM for the containers and about 8 GiB of disk
|
||||
space for the two OSDs, plus space for the images
|
||||
|
||||
Quellcode holen und bauen:
|
||||
Get the source and build it:
|
||||
|
||||
```sh
|
||||
git clone ssh://git@git.zb-server.de:30022/Sebi/CephfsMig.git
|
||||
cd CephfsMig
|
||||
make doctor # prüft Go, Docker und Docker Compose
|
||||
make build # erzeugt bin/cephmig (nur rsync-Backend)
|
||||
make check # go vet, Go-Tests und Syntaxprüfung der Testskripte
|
||||
make doctor # checks Go, Docker and Docker Compose
|
||||
make build # builds bin/cephmig without libcephfs (doctor and status only)
|
||||
make check # go vet, Go tests and a syntax check of the test scripts
|
||||
```
|
||||
|
||||
Das native Backend braucht CGO und die libcephfs-Header. Es wird deshalb in
|
||||
einem Container gebaut. Dabei laufen auch die Go-Tests mit Race Detector:
|
||||
The copier needs CGO and the libcephfs headers (build tag `ceph`), so it is
|
||||
built in a container. The build also runs the Go tests with the race
|
||||
detector:
|
||||
|
||||
```sh
|
||||
make dev-native-build # erzeugt das Image cephmig-native:dev
|
||||
make dev-native-build # builds the image cephmig-native:dev
|
||||
```
|
||||
|
||||
## Verwendung
|
||||
## Usage
|
||||
|
||||
```text
|
||||
cephmig doctor
|
||||
cephmig inspect --config FILE
|
||||
cephmig sync --config FILE --state FILE
|
||||
cephmig finalize --config FILE --state FILE --writers-stopped
|
||||
cephmig cleanup --config FILE --state FILE
|
||||
cephmig status --state FILE
|
||||
```
|
||||
|
||||
| Kommando | Wirkung |
|
||||
|------------|-------------------------------------------------------------------------|
|
||||
| `inspect` | prüft Quelle und Ziel, ohne etwas zu ändern |
|
||||
| `sync` | überträgt den aktuellen Stand; beliebig oft wiederholbar |
|
||||
| `finalize` | letzter Abgleich nach dem Schreibstopp, danach bereit zur Umschaltung |
|
||||
| `status` | gibt das Journal aus |
|
||||
| Command | Effect |
|
||||
|------------|----------------------------------------------------------------------|
|
||||
| `inspect` | checks source and target without changing anything |
|
||||
| `sync` | transfers the current state; can be repeated any number of times |
|
||||
| `finalize` | last round after the write stop, then ready for cutover |
|
||||
| `cleanup` | deletes the snapshots cephmig created and its claim on the target |
|
||||
| `status` | prints the journal |
|
||||
|
||||
Alle Ergebnisse erscheinen als JSON auf der Standardausgabe. Die State-Datei
|
||||
muss außerhalb der CephFS-Mounts liegen.
|
||||
All results are written to standard output as JSON. The state file belongs
|
||||
on local disk.
|
||||
|
||||
Ablauf einer Migration:
|
||||
Steps of a migration:
|
||||
|
||||
1. Mit `inspect` Quelle, Ziel, Berechtigungen und Kapazität prüfen.
|
||||
2. Mit `sync` bei laufender Anwendung initial kopieren.
|
||||
3. `sync` wiederholen, um Änderungen nachzuziehen.
|
||||
4. Alle schreibenden Anwendungen anhalten, dann `finalize --writers-stopped`.
|
||||
5. Clients auf das Ziel umstellen und Anwendungen freigeben.
|
||||
1. Check source, target, permissions and capacity with `inspect`.
|
||||
2. Make the initial copy with `sync` while the application keeps running.
|
||||
3. Repeat `sync` to catch up with changes.
|
||||
4. Stop all writing applications, then run `finalize --writers-stopped`.
|
||||
5. Switch the clients to the target and release the applications.
|
||||
6. Once the cutover is checked, remove the migration snapshots with `cleanup`.
|
||||
|
||||
Ein Dateisystemsnapshot macht eine Datenbank nicht anwendungskonsistent.
|
||||
Der Schreibstopp muss alle Clients umfassen.
|
||||
A file system snapshot does not make a database application-consistent. The
|
||||
write stop must cover all clients.
|
||||
|
||||
Die Konfiguration ist eine JSON-Datei, hier
|
||||
[dev/migration.example.json](dev/migration.example.json) aus dem Labor:
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor Op as Operator
|
||||
participant M as cephmig
|
||||
participant S as Source cluster
|
||||
participant T as Target cluster
|
||||
|
||||
Op->>M: inspect
|
||||
M->>S: check subvolume
|
||||
M->>T: check subvolume
|
||||
loop sync, repeated while the application runs
|
||||
Op->>M: sync
|
||||
M->>S: create round snapshot
|
||||
M->>T: copy changes, verify
|
||||
M->>T: create round snapshot
|
||||
M->>S: remove previous round snapshot
|
||||
M->>T: remove previous round snapshot
|
||||
end
|
||||
Note over Op,S: stop all writers
|
||||
Op->>M: finalize --writers-stopped
|
||||
M->>S: create final snapshot
|
||||
M->>T: copy, full verification, create final snapshot
|
||||
M-->>Op: ready-for-cutover
|
||||
Note over Op,T: switch clients to the target
|
||||
Op->>M: cleanup
|
||||
M->>S: remove final snapshot
|
||||
M->>T: remove final snapshot
|
||||
```
|
||||
|
||||
The detailed sequence is in [docs/migration.md](docs/migration.md#workflow-in-detail).
|
||||
|
||||
Every round reads the metadata of the whole subvolume; only changed file
|
||||
contents are copied.
|
||||
|
||||
Each round creates a snapshot `cephmig-<job>-<round>` at source and target;
|
||||
`sync` deletes the older ones as soon as a newer round is complete. Users of
|
||||
the subvolume therefore see at most one such snapshot during the migration,
|
||||
and none after `cleanup`. Application snapshots are never deleted.
|
||||
|
||||
The configuration is a JSON file, here
|
||||
[dev/migration.example.json](dev/migration.example.json) from the lab:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -100,90 +144,88 @@ Die Konfiguration ist eine JSON-Datei, hier
|
||||
"keyring": "/clusters/source/ceph.client.admin.keyring",
|
||||
"filesystem": "cephfs",
|
||||
"group": "migration",
|
||||
"subvolume": "demo",
|
||||
"mount": "/mnt/source-fs"
|
||||
"subvolume": "demo"
|
||||
},
|
||||
"target": {
|
||||
"config": "/clusters/target/ceph.conf",
|
||||
"keyring": "/clusters/target/ceph.client.admin.keyring",
|
||||
"filesystem": "cephfs",
|
||||
"group": "migration",
|
||||
"subvolume": "demo",
|
||||
"mount": "/mnt/target-fs"
|
||||
"subvolume": "demo"
|
||||
},
|
||||
"bandwidth_kib": 0
|
||||
}
|
||||
```
|
||||
|
||||
Optional sind außerdem `user` (Ceph-Client-Identität, z. B. `client.migration`)
|
||||
und `workers` (0 bis 64; 0 wählt den Standard). `mount` ist nur für das
|
||||
rsync-Backend nötig: dort der Mount des Dateisystem-Wurzelverzeichnisses.
|
||||
Optional fields are `user` (Ceph client identity, e.g. `client.migration`),
|
||||
and `workers` (0 to 64; 0 selects the default). `backend` may be omitted;
|
||||
its only value is `native`.
|
||||
|
||||
## Beispiele
|
||||
## Examples
|
||||
|
||||
Die Laborumgebung startet zwei unabhängige Ceph-Cluster (Ceph 21.2.0) in
|
||||
Docker und führt die Migration darin aus:
|
||||
The lab starts two independent Ceph clusters (Ceph 21.2.0) in Docker and runs
|
||||
the migration between them:
|
||||
|
||||
```sh
|
||||
make dev-up # Cluster starten
|
||||
make dev-status # Zustand beider Cluster
|
||||
make dev-smoke # Smoke-Test: Snapshot, ACLs, xattrs, Hardlinks, Quotas
|
||||
make dev-native-test # nativer Funktionstest
|
||||
make dev-up # start the clusters
|
||||
make dev-status # state of both clusters
|
||||
make dev-smoke # smoke test: snapshot, ACLs, xattrs, hardlinks, quotas
|
||||
make dev-native-test # native functional test
|
||||
docker compose -f dev/compose.yaml exec native cephmig-native inspect \
|
||||
--config /lab/migration.example.json
|
||||
make dev-down # stoppen; die Daten bleiben erhalten
|
||||
make dev-down # stop; the data is kept
|
||||
```
|
||||
|
||||
Weitere Tests:
|
||||
More tests:
|
||||
|
||||
| Ziel | Inhalt |
|
||||
|----------------------------|--------------------------------------------------------------|
|
||||
| `make dev-migration-test` | Migration mit dem rsync-Backend |
|
||||
| `make dev-smallfiles-test` | 10.000 kleine Dateien (`FILES=2000` begrenzt die Anzahl) |
|
||||
| `make dev-million-start` | eine Million Dateien mit vier Snapshot-Ständen |
|
||||
| `make dev-restart-check` | Neustart des Labors; FSIDs und Daten bleiben erhalten |
|
||||
| Target | Content |
|
||||
|----------------------------|-----------------------------------------------------------|
|
||||
| `make dev-smallfiles-test` | 10,000 small files (`FILES=2000` limits the number) |
|
||||
| `make dev-million-start` | one million files with four snapshot states |
|
||||
| `make dev-restart-check` | restart of the lab; FSIDs and data are preserved |
|
||||
|
||||
Ergebnisse dokumentierter Läufe: [docs/smallfiles-local.md](docs/smallfiles-local.md)
|
||||
und [docs/million-local.md](docs/million-local.md).
|
||||
Results of documented runs: [docs/smallfiles-local.md](docs/smallfiles-local.md)
|
||||
and [docs/million-local.md](docs/million-local.md).
|
||||
|
||||
## Projektstruktur
|
||||
## Project structure
|
||||
|
||||
```text
|
||||
.
|
||||
├── cmd/
|
||||
│ ├── cephmig/ Kommandozeilenprogramm
|
||||
│ └── nativeprobe/ Diagnosewerkzeug für die libcephfs-Anbindung
|
||||
│ ├── cephmig/ command-line program
|
||||
│ └── nativeprobe/ diagnostic tool for the libcephfs binding
|
||||
├── internal/
|
||||
│ ├── migration/ Migrationsablauf, Journal, rsync- und native Übertragung
|
||||
│ ├── storage/ Dateisystem-Schnittstelle des nativen Kopierers
|
||||
│ └── cephfsnative/ CGO-Anbindung an libcephfs (Build-Tag ceph)
|
||||
├── dev/ Laborumgebung: Compose-Dateien, Dockerfiles, Testskripte
|
||||
├── docs/ Ausführliche Dokumentation und Messergebnisse
|
||||
└── Makefile Build-, Prüf- und Laborziele
|
||||
│ ├── migration/ migration workflow, journal and native transfer
|
||||
│ ├── storage/ file system interface of the native copier
|
||||
│ └── cephfsnative/ CGO binding to libcephfs (build tag ceph)
|
||||
├── dev/ lab: Compose files, Dockerfiles, test scripts
|
||||
├── docs/ detailed documentation and measurements
|
||||
└── Makefile build, check and lab targets
|
||||
```
|
||||
|
||||
## Dokumentation
|
||||
## Documentation
|
||||
|
||||
- [docs/migration.md](docs/migration.md): Kommandos, Grenzen und Nachweise
|
||||
- [docs/lab.md](docs/lab.md): Laborumgebung im Detail, Ceph-Version, bekannte Warnungen
|
||||
- [docs/raw-transfer.md](docs/raw-transfer.md): direkter RADOS-Import und Grenzen der nativen Implementierung
|
||||
- API-Dokumentation der Go-Pakete: `go doc -all ./internal/migration`
|
||||
- [docs/migration.md](docs/migration.md): commands, limits and evidence
|
||||
- [docs/lab.md](docs/lab.md): the lab in detail, Ceph version, known warnings
|
||||
- [docs/raw-transfer.md](docs/raw-transfer.md): direct RADOS import, why libcephfs through CGO, limits of the native implementation
|
||||
- [docs/verify-concept.md](docs/verify-concept.md): concept for a full content verification after the cutover
|
||||
- API documentation of the Go packages: `go doc -all ./internal/migration`
|
||||
|
||||
## Mitwirken
|
||||
## Contributing
|
||||
|
||||
- Go-Code folgt [Effective Go](https://go.dev/doc/effective_go) und ist mit
|
||||
`gofmt` formatiert. Exportierte Bezeichner haben Doc-Kommentare.
|
||||
- Vor jedem Commit `make check` ausführen.
|
||||
- Commit-Nachrichten folgen [Conventional Commits 1.0.0](https://www.conventionalcommits.org/en/v1.0.0/),
|
||||
zum Beispiel `feat(migration): add bandwidth limit` oder
|
||||
`fix(native): retry on EEXIST`. Inkompatible Änderungen werden mit `!`
|
||||
und einem `BREAKING CHANGE:`-Footer gekennzeichnet.
|
||||
- Go code follows [Effective Go](https://go.dev/doc/effective_go) and is
|
||||
formatted with `gofmt`. Exported identifiers have doc comments.
|
||||
- Run `make check` before every commit.
|
||||
- Commit messages follow [Conventional Commits 1.0.0](https://www.conventionalcommits.org/en/v1.0.0/),
|
||||
for example `feat(migration): add bandwidth limit` or
|
||||
`fix(native): retry on EEXIST`. Breaking changes are marked with `!` and a
|
||||
`BREAKING CHANGE:` footer.
|
||||
|
||||
## Lizenz
|
||||
## License
|
||||
|
||||
Bisher ist keine Lizenz festgelegt. Ohne Lizenz gilt: alle Rechte vorbehalten.
|
||||
No license has been chosen yet. Without a license, all rights are reserved.
|
||||
|
||||
## Kontakt
|
||||
## Contact
|
||||
|
||||
Sebastian Unterschütz. Fragen und Fehlermeldungen bitte als Issue im
|
||||
Repository [Sebi/CephfsMig](https://git.zb-server.de/Sebi/CephfsMig).
|
||||
Sebastian Unterschütz. Please report questions and bugs as issues in the
|
||||
repository [Sebi/CephfsMig](https://git.zb-server.de/Sebi/CephfsMig).
|
||||
+37
-11
@@ -7,12 +7,15 @@
|
||||
// cephmig inspect --config FILE
|
||||
// cephmig sync --config FILE --state FILE
|
||||
// cephmig finalize --config FILE --state FILE --writers-stopped
|
||||
// cephmig cleanup --config FILE --state FILE
|
||||
// cephmig status --state FILE
|
||||
//
|
||||
// inspect checks both clusters without changing them. sync copies the
|
||||
// current state and may be repeated. finalize performs the last round after
|
||||
// all writers are stopped and marks the job ready for cutover. status prints
|
||||
// the migration journal. All results are written to standard output as JSON.
|
||||
// all writers are stopped and marks the job ready for cutover. cleanup
|
||||
// deletes the snapshots cephmig created, at source and target, once the
|
||||
// cutover is done. status prints the migration journal. All results are
|
||||
// written to standard output as JSON.
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -40,92 +43,113 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
const usage = "usage: cephmig doctor | inspect --config FILE | sync --config FILE --state FILE | finalize --config FILE --state FILE --writers-stopped | status --state FILE"
|
||||
const usage = "usage: cephmig doctor | inspect --config FILE | sync --config FILE --state FILE | finalize --config FILE --state FILE --writers-stopped | cleanup --config FILE --state FILE | status --state FILE"
|
||||
|
||||
func run(ctx context.Context, args []string, out, log io.Writer) error {
|
||||
if len(args) == 0 {
|
||||
return errors.New(usage)
|
||||
}
|
||||
|
||||
if args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
|
||||
fmt.Fprintln(out, usage)
|
||||
return nil
|
||||
}
|
||||
|
||||
if args[0] == "doctor" {
|
||||
if len(args) != 1 {
|
||||
return errors.New(usage)
|
||||
}
|
||||
|
||||
return doctor(ctx, out, log)
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
case "inspect", "sync", "finalize", "status":
|
||||
case "inspect", "sync", "finalize", "cleanup", "status":
|
||||
default:
|
||||
return errors.New(usage)
|
||||
}
|
||||
|
||||
flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
|
||||
flags.SetOutput(log)
|
||||
configPath := flags.String("config", "", "JSON migration configuration")
|
||||
statePath := flags.String("state", "", "persistent local state file (outside CephFS mounts)")
|
||||
statePath := flags.String("state", "", "persistent state file on local disk")
|
||||
stopped := flags.Bool("writers-stopped", false, "confirm ALL source writers are stopped; keep them stopped until cutover completes")
|
||||
if err := flags.Parse(args[1:]); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if flags.NArg() != 0 {
|
||||
return errors.New("unexpected positional arguments")
|
||||
}
|
||||
|
||||
if args[0] == "status" {
|
||||
if *statePath == "" {
|
||||
return errors.New("--state is required")
|
||||
}
|
||||
|
||||
s, err := migration.LoadState(*statePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return json.NewEncoder(out).Encode(s)
|
||||
}
|
||||
|
||||
if *configPath == "" {
|
||||
return errors.New("--config is required")
|
||||
}
|
||||
|
||||
c, err := migration.ReadConfig(*configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
process := migration.Process{Stderr: log}
|
||||
if args[0] != "inspect" && *statePath == "" {
|
||||
return errors.New("--state is required")
|
||||
}
|
||||
|
||||
if args[0] == "finalize" && !*stopped {
|
||||
return errors.New("finalize requires --writers-stopped; stop and flush all application writers first")
|
||||
}
|
||||
|
||||
if args[0] != "finalize" && *stopped {
|
||||
return errors.New("--writers-stopped is only valid with finalize")
|
||||
}
|
||||
if c.Backend != "native" && args[0] != "inspect" {
|
||||
if _, err = exec.LookPath("rsync"); err != nil {
|
||||
return fmt.Errorf("rsync is required: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
engine, closeEngine, err := migration.NewEngine(ctx, c, process, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer closeEngine.Close()
|
||||
if args[0] == "inspect" {
|
||||
info, err := engine.Inspect(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return json.NewEncoder(out).Encode(info)
|
||||
}
|
||||
if err = engine.Sync(ctx, c, *statePath, args[0] == "finalize"); err != nil {
|
||||
|
||||
if args[0] == "cleanup" {
|
||||
err = engine.Cleanup(ctx, c, *statePath)
|
||||
} else {
|
||||
err = engine.Sync(ctx, c, *statePath, args[0] == "finalize")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s, err := migration.LoadState(*statePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return json.NewEncoder(out).Encode(s)
|
||||
}
|
||||
|
||||
@@ -138,6 +162,7 @@ func doctor(ctx context.Context, out, log io.Writer) error {
|
||||
{"docker", []string{"compose", "version"}},
|
||||
{"docker", []string{"info", "--format", "Docker server: {{.ServerVersion}}"}},
|
||||
}
|
||||
|
||||
for _, check := range checks {
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
cmd := exec.CommandContext(checkCtx, check.name, check.args...)
|
||||
@@ -148,5 +173,6 @@ func doctor(ctx context.Context, out, log io.Writer) error {
|
||||
return fmt.Errorf("check %s: %w", check.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -14,15 +14,18 @@ func TestCLIRejectsFinalizationWithoutWriterStop(t *testing.T) {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIUsage(t *testing.T) {
|
||||
var out, log bytes.Buffer
|
||||
if err := run(context.Background(), []string{"--help"}, &out, &log); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !strings.Contains(out.String(), "finalize") {
|
||||
t.Fatal("help missing")
|
||||
}
|
||||
for _, args := range [][]string{nil, {"unknown"}, {"sync"}, {"status"}, {"sync", "--config", "x", "extra"}} {
|
||||
|
||||
for _, args := range [][]string{nil, {"unknown"}, {"sync"}, {"status"}, {"cleanup"}, {"cleanup", "--config", "../../dev/migration.example.json"}, {"sync", "--config", "x", "extra"}} {
|
||||
if err := run(context.Background(), args, &out, &log); err == nil {
|
||||
t.Fatalf("accepted %v", args)
|
||||
}
|
||||
|
||||
@@ -35,29 +35,36 @@ func run(out io.Writer, config, root, rel, from, to string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var c struct{ Source storage.Options }
|
||||
if err = json.Unmarshal(data, &c); err != nil {
|
||||
return fmt.Errorf("config: %w", err)
|
||||
}
|
||||
|
||||
fs, err := cephfsnative.Open(c.Source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer fs.Close()
|
||||
n, err := fs.Stat(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = json.NewEncoder(out).Encode(n); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if from == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
d, err := fs.SnapDiff(root, rel, from, to)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer d.Close()
|
||||
for {
|
||||
name, err := d.Next()
|
||||
@@ -67,6 +74,7 @@ func run(out io.Writer, config, root, rel, from, to string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Fprintf(out, "diff: %q\n", name)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
ARG CEPH_IMAGE=quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d
|
||||
FROM ${CEPH_IMAGE}
|
||||
ARG RSYNC_VERSION=3.5.0-3.el10_2
|
||||
RUN dnf install -y "rsync-${RSYNC_VERSION}" && dnf clean all
|
||||
@@ -1,6 +1,13 @@
|
||||
ARG CEPH_IMAGE=quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d
|
||||
# Go toolchain 1.26.11 from the official image, pinned by digest: distribution
|
||||
# RPM pins disappear from the repositories when updates are published.
|
||||
ARG GO_IMAGE=golang:1.26.11@sha256:dd1390438221f8eeb6ac8d2c298a22a55a7212a09d2e66bee100f6103e036d62
|
||||
FROM ${GO_IMAGE} AS go
|
||||
|
||||
FROM ${CEPH_IMAGE} AS build
|
||||
RUN dnf install -y gcc golang-1.26.10-1.el10_2 \
|
||||
COPY --from=go /usr/local/go /usr/local/go
|
||||
ENV PATH=/usr/local/go/bin:$PATH GOTOOLCHAIN=local
|
||||
RUN dnf install -y gcc \
|
||||
https://download.ceph.com/rpm-21.2.0/el10/x86_64/libcephfs-devel-21.2.0-0.el10.x86_64.rpm \
|
||||
https://download.ceph.com/rpm-21.2.0/el10/x86_64/libcephfs-proxy2-21.2.0-0.el10.x86_64.rpm \
|
||||
https://download.ceph.com/rpm-21.2.0/el10/x86_64/librados-devel-21.2.0-0.el10.x86_64.rpm \
|
||||
|
||||
@@ -16,6 +16,10 @@ services:
|
||||
image: cephmig-native:dev
|
||||
init: true
|
||||
entrypoint: [python3, -u, /lab/million.py]
|
||||
environment:
|
||||
FILES: ${FILES:-1000000}
|
||||
RUN_LABEL: ${RUN_LABEL:-main}
|
||||
WORKERS: ${WORKERS:-8}
|
||||
networks: [lab]
|
||||
depends_on:
|
||||
source: {condition: service_healthy}
|
||||
|
||||
@@ -55,12 +55,6 @@ services:
|
||||
- ./:/lab:ro
|
||||
client:
|
||||
<<: *ceph
|
||||
image: cephmig-client:dev
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.client
|
||||
args:
|
||||
CEPH_IMAGE: ${CEPH_IMAGE:-quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d}
|
||||
# FUSE mounts remain in the container mount namespace.
|
||||
privileged: true
|
||||
entrypoint: [bash, /lab/client.sh]
|
||||
@@ -71,7 +65,6 @@ services:
|
||||
- source-config:/clusters/source:ro
|
||||
- target-config:/clusters/target:ro
|
||||
- ./:/lab:ro
|
||||
- ../:/workspace:ro
|
||||
- migration-state:/state
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'mountpoint -q /mnt/source && mountpoint -q /mnt/target && mountpoint -q /mnt/source-fs && mountpoint -q /mnt/target-fs']
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
mountpoint -q /mnt/source-fs
|
||||
mountpoint -q /mnt/target-fs
|
||||
id=$(cat /proc/sys/kernel/random/uuid)
|
||||
name="itest-$id"
|
||||
mkdir -p /state/test-runs
|
||||
work=$(mktemp -d /state/test-runs/cephmig-itest.XXXXXX)
|
||||
state="/state/$name.json"
|
||||
config="$work/config.json"
|
||||
binary=/workspace/bin/cephmig
|
||||
ceph_real=$(command -v ceph)
|
||||
rsync_real=$(command -v rsync)
|
||||
source_ceph() { "$ceph_real" -c /clusters/source/ceph.conf -k /clusters/source/ceph.client.admin.keyring "$@"; }
|
||||
target_ceph() { "$ceph_real" -c /clusters/target/ceph.conf -k /clusters/target/ceph.client.admin.keyring "$@"; }
|
||||
completed=false
|
||||
cleanup() {
|
||||
if [[ $completed != true ]]; then
|
||||
echo "FAIL: retained fixtures subvolume=$name state=$state config=$config" >&2
|
||||
return
|
||||
fi
|
||||
for cluster in source target; do
|
||||
helper="$cluster"_ceph
|
||||
while IFS= read -r snap; do
|
||||
"$helper" fs subvolume snapshot rm cephfs "$name" "$snap" --group_name migration
|
||||
done < <("$helper" fs subvolume snapshot ls cephfs "$name" --group_name migration |
|
||||
python3 -c 'import json,sys; print("\n".join(x["name"] for x in json.load(sys.stdin)))')
|
||||
"$helper" fs subvolume rm cephfs "$name" --group_name migration --force
|
||||
done
|
||||
target_fsid=$(target_ceph fsid)
|
||||
claim=$(python3 - "$target_fsid" "$name" <<'PY'
|
||||
import hashlib, sys
|
||||
print(hashlib.sha256("\0".join([sys.argv[1], "cephfs", "migration", sys.argv[2]]).encode()).hexdigest())
|
||||
PY
|
||||
)
|
||||
rm -f "/mnt/target-fs/.cephmig/claims/$claim" "$state" "$state.lock" "$state.second" "$state.second.lock"
|
||||
rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
source_ceph fs subvolume create cephfs "$name" --group_name migration
|
||||
target_ceph fs subvolume create cephfs "$name" --group_name migration
|
||||
src="/mnt/source-fs$(source_ceph fs subvolume getpath cephfs "$name" --group_name migration)"
|
||||
dst="/mnt/target-fs$(target_ceph fs subvolume getpath cephfs "$name" --group_name migration)"
|
||||
python3 - /lab/migration.example.json "$config" "$name" <<'PY'
|
||||
import json,sys
|
||||
c=json.load(open(sys.argv[1]))
|
||||
c["backend"]="rsync" # Retained as an explicit regression/reference backend.
|
||||
c["source"]["subvolume"]=c["target"]["subvolume"]=sys.argv[3]
|
||||
with open(sys.argv[2],"w") as f: json.dump(c,f)
|
||||
PY
|
||||
python3 - "$src" <<'PY'
|
||||
import os, struct, sys
|
||||
root=sys.argv[1]
|
||||
os.mkdir(root+"/d")
|
||||
with open(root+"/data","wb") as f: f.write(b"version-A")
|
||||
os.chmod(root+"/data",0o640)
|
||||
os.chown(root+"/data",12345,23456)
|
||||
os.link(root+"/data",root+"/d/hardlink")
|
||||
os.symlink("../data",root+"/d/symlink")
|
||||
os.symlink("nonexistent",root+"/dangling")
|
||||
os.symlink("/etc/passwd",root+"/external")
|
||||
os.mkfifo(root+"/fifo",0o600)
|
||||
# A separate link group will be split in a later snapshot without changing bytes.
|
||||
with open(root+"/split-a","wb") as f: f.write(b"unchanged")
|
||||
os.link(root+"/split-a",root+"/d/split-b")
|
||||
with open(root+"/sparse","wb") as f: f.truncate(16*1024*1024)
|
||||
with open(root+"/deleted-later","w") as f: f.write("historical")
|
||||
with open(root+"/name with spaces\nand newline","w") as f: f.write("name")
|
||||
os.setxattr(root+"/data","user.cephmig",b"preserve")
|
||||
entries=[(1,6,0xffffffff),(2,4,12345),(4,0,0xffffffff),(16,4,0xffffffff),(32,0,0xffffffff)]
|
||||
acl=struct.pack("<I",2)+b"".join(struct.pack("<HHI",*e) for e in entries)
|
||||
os.setxattr(root+"/data","system.posix_acl_access",acl)
|
||||
os.setxattr(root+"/d","system.posix_acl_default",acl)
|
||||
os.setxattr(root+"/d","ceph.quota.max_bytes",b"33554432")
|
||||
os.setxattr(root+"/d","ceph.quota.max_files",b"1000")
|
||||
os.setxattr(root,"ceph.quota.max_bytes",b"134217728")
|
||||
PY
|
||||
source_ceph fs subvolume metadata set cephfs "$name" owner --value="-value with spaces" --group_name migration
|
||||
source_ceph fs subvolume snapshot create cephfs "$name" history-1 --group_name migration
|
||||
source_ceph fs subvolume snapshot metadata set cephfs "$name" history-1 app first --group_name migration
|
||||
python3 - "$src" <<'PY'
|
||||
import os,sys
|
||||
p=sys.argv[1]+"/data"
|
||||
st=os.stat(p)
|
||||
with open(p,"wb") as f: f.write(b"version-B")
|
||||
os.utime(p,ns=(st.st_atime_ns,st.st_mtime_ns))
|
||||
os.unlink(sys.argv[1]+"/deleted-later")
|
||||
split=sys.argv[1]+"/d/split-b"
|
||||
st=os.stat(split)
|
||||
attrs={k:os.getxattr(split,k) for k in os.listxattr(split) if not k.startswith("ceph.")}
|
||||
os.unlink(split)
|
||||
with open(split,"wb") as f: f.write(b"unchanged")
|
||||
for k in os.listxattr(split):
|
||||
if k not in attrs and not k.startswith("ceph."): os.removexattr(split,k)
|
||||
for k,v in attrs.items(): os.setxattr(split,k,v)
|
||||
os.chmod(split,st.st_mode & 0o7777)
|
||||
os.utime(split,ns=(st.st_atime_ns,st.st_mtime_ns))
|
||||
os.setxattr(sys.argv[1]+"/d","ceph.quota.max_bytes",b"50331648")
|
||||
os.setxattr(sys.argv[1],"ceph.quota.max_bytes",b"201326592")
|
||||
PY
|
||||
source_ceph fs subvolume snapshot create cephfs "$name" history-2 --group_name migration
|
||||
source_ceph fs subvolume snapshot metadata set cephfs "$name" history-2 app second --group_name migration
|
||||
printf 'version-C' > "$src/data"
|
||||
python3 - "$src" <<'PY'
|
||||
import os,sys
|
||||
os.setxattr(sys.argv[1]+"/d","ceph.quota.max_files",b"2000")
|
||||
PY
|
||||
"$binary" inspect --config "$config" > "$work/inspection.json"
|
||||
|
||||
mkdir "$work/bin"
|
||||
cat > "$work/bin/rsync" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [[ -f $CEPHMIG_FAIL_COPY_ONCE && " $* " != *" --dry-run "* ]]; then
|
||||
rm "$CEPHMIG_FAIL_COPY_ONCE"
|
||||
"$CEPHMIG_REAL_RSYNC" "$@"
|
||||
exit 23
|
||||
fi
|
||||
exec "$CEPHMIG_REAL_RSYNC" "$@"
|
||||
SH
|
||||
cat > "$work/bin/ceph" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [[ -f $CEPHMIG_CRASH_ONCE &&
|
||||
" $* " == *"/clusters/target/ceph.conf"* &&
|
||||
" $* " == *" fs subvolume snapshot create "* ]]; then
|
||||
"$CEPHMIG_REAL_CEPH" "$@"
|
||||
rm "$CEPHMIG_CRASH_ONCE"
|
||||
kill -KILL "$PPID"
|
||||
exit 0
|
||||
fi
|
||||
exec "$CEPHMIG_REAL_CEPH" "$@"
|
||||
SH
|
||||
chmod +x "$work/bin/rsync" "$work/bin/ceph"
|
||||
export CEPHMIG_REAL_RSYNC="$rsync_real" CEPHMIG_REAL_CEPH="$ceph_real"
|
||||
export CEPHMIG_FAIL_COPY_ONCE="$work/fail-copy" CEPHMIG_CRASH_ONCE="$work/crash"
|
||||
touch "$CEPHMIG_FAIL_COPY_ONCE"
|
||||
if PATH="$work/bin:$PATH" "$binary" sync --config "$config" --state "$state" > "$work/interrupted.json"; then
|
||||
echo 'expected injected transfer failure' >&2; exit 1
|
||||
fi
|
||||
python3 - "$state" <<'PY'
|
||||
import json,sys
|
||||
s=json.load(open(sys.argv[1]))
|
||||
assert s["phase"]=="syncing" and not s["snapshots"][0]["done"]
|
||||
PY
|
||||
touch "$CEPHMIG_CRASH_ONCE"
|
||||
if PATH="$work/bin:$PATH" "$binary" sync --config "$config" --state "$state" > "$work/crashed.json"; then
|
||||
echo 'expected injected process crash' >&2; exit 1
|
||||
fi
|
||||
test ! -f "$CEPHMIG_CRASH_ONCE"
|
||||
"$binary" sync --config "$config" --state "$state" > "$work/synced.json"
|
||||
for snap in history-1 history-2; do
|
||||
path=$(target_ceph fs subvolume snapshot getpath cephfs "$name" "$snap" migration)
|
||||
value=$(cat "/mnt/target-fs$path/data")
|
||||
if [[ $snap = history-1 ]]; then test "$value" = version-A; else test "$value" = version-B; fi
|
||||
python3 - "/mnt/target-fs$path" "$snap" <<'PY'
|
||||
import os,sys
|
||||
root,snap=sys.argv[1:3]
|
||||
linked=os.stat(root+"/split-a").st_ino==os.stat(root+"/d/split-b").st_ino
|
||||
assert linked==(snap=="history-1"), (snap,linked)
|
||||
PY
|
||||
done
|
||||
test "$(cat "$dst/data")" = version-C
|
||||
if "$binary" sync --config "$config" --state "$state.second" > "$work/stolen.json"; then
|
||||
echo 'second job adopted existing target' >&2; exit 1
|
||||
fi
|
||||
printf 'version-D' > "$src/data"
|
||||
printf extra > "$dst/obsolete"
|
||||
source_ceph fs subvolume metadata rm cephfs "$name" owner --group_name migration
|
||||
source_ceph fs subvolume metadata set cephfs "$name" project new-value --group_name migration
|
||||
"$binary" sync --config "$config" --state "$state" > "$work/caught-up.json"
|
||||
test "$(cat "$dst/data")" = version-D
|
||||
test ! -e "$dst/obsolete"
|
||||
if "$binary" finalize --config "$config" --state "$state" > "$work/refused.json"; then
|
||||
echo 'finalization accepted missing writer-stop acknowledgement' >&2; exit 1
|
||||
fi
|
||||
"$binary" finalize --config "$config" --state "$state" --writers-stopped > "$work/final.json"
|
||||
"$binary" status --state "$state" > "$work/status.json"
|
||||
"$binary" finalize --config "$config" --state "$state" --writers-stopped > "$work/idempotent.json"
|
||||
python3 - "$src" "$dst" "$work/status.json" "$work/idempotent.json" <<'PY'
|
||||
import json,os,stat,sys
|
||||
src,dst=sys.argv[1:3]
|
||||
s=json.load(open(sys.argv[3])); again=json.load(open(sys.argv[4]))
|
||||
assert s==again and s["phase"]=="ready-for-cutover"
|
||||
assert s["notes"] and "birthtimes" in s["notes"][0]
|
||||
assert all(x["done"] for x in s["snapshots"])
|
||||
assert len(s["snapshots"])==5, s["snapshots"]
|
||||
assert os.stat(dst+"/data").st_uid==12345 and os.stat(dst+"/data").st_gid==23456
|
||||
assert os.stat(dst+"/data").st_ino==os.stat(dst+"/d/hardlink").st_ino
|
||||
assert os.stat(dst+"/split-a").st_ino!=os.stat(dst+"/d/split-b").st_ino
|
||||
assert stat.S_ISFIFO(os.lstat(dst+"/fifo").st_mode)
|
||||
assert os.readlink(dst+"/external")=="/etc/passwd"
|
||||
for rel,key in [("data","user.cephmig"),("data","system.posix_acl_access"),
|
||||
("d","system.posix_acl_default"),("d","ceph.quota.max_bytes"),
|
||||
("d","ceph.quota.max_files"),(".","ceph.quota.max_bytes")]:
|
||||
assert os.getxattr(src+"/"+rel,key)==os.getxattr(dst+"/"+rel,key),(rel,key)
|
||||
# CephFS st_blocks reflects logical size and cannot prove physical sparseness.
|
||||
assert os.stat(dst+"/sparse").st_size==16*1024*1024
|
||||
with open(dst+"/sparse","rb") as f:
|
||||
while chunk:=f.read(65536):
|
||||
assert not any(chunk)
|
||||
PY
|
||||
a=$(source_ceph fs subvolume metadata ls cephfs "$name" --group_name migration)
|
||||
b=$(target_ceph fs subvolume metadata ls cephfs "$name" --group_name migration)
|
||||
test "$a" = "$b"
|
||||
for snap in history-1 history-2; do
|
||||
a=$(source_ceph fs subvolume snapshot metadata ls cephfs "$name" "$snap" --group_name migration)
|
||||
b=$(target_ceph fs subvolume snapshot metadata ls cephfs "$name" "$snap" --group_name migration)
|
||||
test "$a" = "$b"
|
||||
done
|
||||
python3 /lab/snapshot-identity.py --config "$config" --snapshot history-1
|
||||
completed=true
|
||||
echo 'PASS: Go migration, historical snapshots, live catch-up, quotas, ACLs, xattrs, sparse-file contents, crash/error resume, exclusive target, finalization'
|
||||
|
||||
@@ -5,16 +5,14 @@
|
||||
"keyring": "/clusters/source/ceph.client.admin.keyring",
|
||||
"filesystem": "cephfs",
|
||||
"group": "migration",
|
||||
"subvolume": "demo",
|
||||
"mount": "/mnt/source-fs"
|
||||
"subvolume": "demo"
|
||||
},
|
||||
"target": {
|
||||
"config": "/clusters/target/ceph.conf",
|
||||
"keyring": "/clusters/target/ceph.client.admin.keyring",
|
||||
"filesystem": "cephfs",
|
||||
"group": "migration",
|
||||
"subvolume": "demo",
|
||||
"mount": "/mnt/target-fs"
|
||||
"subvolume": "demo"
|
||||
},
|
||||
"bandwidth_kib": 0
|
||||
}
|
||||
@@ -18,5 +18,5 @@ mkdir -p .dev/million
|
||||
"${compose[@]}" up -d --wait --wait-timeout 600 source target
|
||||
"${compose[@]}" up -d benchmark
|
||||
docker inspect cephmig-million-benchmark-1 --format '{{.Image}}' > .dev/million/native-image.txt
|
||||
echo 'Persistent test started. Status: .dev/million/main/status.json'
|
||||
echo "Persistent test started. Status: .dev/million/${RUN_LABEL:-main}/status.json"
|
||||
echo 'Logs: docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml logs -f benchmark'
|
||||
+50
-12
@@ -23,8 +23,8 @@ import cephfs
|
||||
from smallfiles import ceph, volume, snap, payload, posix_acl
|
||||
|
||||
RUN_LABEL = os.environ.get('RUN_LABEL', 'main')
|
||||
if RUN_LABEL not in ('main', 'pilot'):
|
||||
raise ValueError('RUN_LABEL must be main or pilot')
|
||||
if not RUN_LABEL or not all(c.isascii() and (c.isalnum() or c == '-') for c in RUN_LABEL):
|
||||
raise ValueError('RUN_LABEL must consist of letters, digits and hyphens')
|
||||
REPORT = Path('/report') / RUN_LABEL
|
||||
WORK = Path('/state') / ('million-' + RUN_LABEL)
|
||||
COUNT = int(os.environ.get('FILES', '1000000'))
|
||||
@@ -58,6 +58,16 @@ def progress(**changes):
|
||||
print(json.dumps(changes), flush=True)
|
||||
|
||||
|
||||
def timed(step, function, *args):
|
||||
"""Run function and record its duration under timings[step]."""
|
||||
started = time.monotonic()
|
||||
result = function(*args)
|
||||
timings = dict(state.get('timings', {}))
|
||||
timings[step] = round(time.monotonic() - started, 3)
|
||||
progress(timings=timings)
|
||||
return result
|
||||
|
||||
|
||||
def guard():
|
||||
if STOP.is_set():
|
||||
raise RuntimeError('test stopped')
|
||||
@@ -180,10 +190,9 @@ def prepare():
|
||||
roots = {c: volume(c, 'getpath', 'cephfs', name) for c in ('source', 'target')}
|
||||
state['roots'] = roots
|
||||
config = json.loads(Path('/lab/migration.example.json').read_text())
|
||||
config.update(backend='native', workers=8, bandwidth_kib=0)
|
||||
config.update(backend='native', workers=int(os.environ.get('WORKERS', '8')), bandwidth_kib=0)
|
||||
for c in ('source', 'target'):
|
||||
config[c]['subvolume'] = name
|
||||
config[c].pop('mount', None)
|
||||
atomic_json(WORK / 'config.json', config)
|
||||
with FS('source') as fs:
|
||||
root = roots['source']
|
||||
@@ -262,6 +271,11 @@ def mutate():
|
||||
create_file(fs, root, i, 2)
|
||||
reset_dir_times(fs, root, end)
|
||||
fs.sync_fs()
|
||||
# A second application snapshot holds the changed state.
|
||||
name = state['name']
|
||||
if 'changed' not in {x['name'] for x in json.loads(snap('source', 'ls', 'cephfs', name))}:
|
||||
snap('source', 'create', 'cephfs', name, 'changed')
|
||||
snap('source', 'metadata', 'set', 'cephfs', name, 'changed', 'fixture', 'million-v1')
|
||||
progress(mutated=True)
|
||||
|
||||
|
||||
@@ -278,13 +292,24 @@ def run_phase(phase):
|
||||
progress(phase=phase, phase_started=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
phase_attempts=attempts)
|
||||
before = {c: counters(c) for c in ('source', 'target')}
|
||||
args = ['/usr/local/bin/cephmig-native', 'finalize' if phase == 'final' else 'sync',
|
||||
command = {'final': 'finalize', 'cleanup': 'cleanup'}.get(phase, 'sync')
|
||||
args = ['/usr/local/bin/cephmig-native', command,
|
||||
'--config', str(WORK / 'config.json'), '--state', str(WORK / 'job.json')]
|
||||
if phase == 'final': args.append('--writers-stopped')
|
||||
started, wall_started, last = time.monotonic(), time.time(), 0
|
||||
peak = 0
|
||||
with (REPORT / f'{phase}.stdout.json').open('w') as out, (REPORT / f'{phase}.log').open('w') as log:
|
||||
p = subprocess.Popen(args, stdout=out, stderr=log)
|
||||
p = subprocess.Popen(args, stdout=out, stderr=subprocess.PIPE)
|
||||
|
||||
def stamp_lines():
|
||||
# Prefix every engine log line with the UTC time and the phase time.
|
||||
for raw in p.stderr:
|
||||
now = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds')
|
||||
log.write(f'{now} +{time.monotonic() - started:9.3f}s {raw.decode(errors="replace")}')
|
||||
log.flush()
|
||||
|
||||
logger = threading.Thread(target=stamp_lines, daemon=True)
|
||||
logger.start()
|
||||
try:
|
||||
while p.poll() is None:
|
||||
now = time.monotonic()
|
||||
@@ -311,6 +336,8 @@ def run_phase(phase):
|
||||
except subprocess.TimeoutExpired:
|
||||
p.kill(); p.wait()
|
||||
raise
|
||||
finally:
|
||||
logger.join(timeout=30)
|
||||
if p.returncode:
|
||||
raise RuntimeError(f'{phase} failed ({p.returncode}); see {phase}.log')
|
||||
result = json.loads((WORK / 'job.json').read_text())
|
||||
@@ -325,6 +352,9 @@ def run_phase(phase):
|
||||
if phase == 'final':
|
||||
if result['phase'] != 'ready-for-cutover' or result['snapshots'][-1]['transfer']['bytes_copied']:
|
||||
raise RuntimeError('unchanged final round must be ready and write zero payload bytes')
|
||||
timings = dict(state.get('timings', {}))
|
||||
timings[phase] = round(metrics['seconds'], 3)
|
||||
state['timings'] = timings
|
||||
completed = {phase + '_complete': True}
|
||||
if phase == 'initial':
|
||||
completed['initial_snapshots'] = [record['name'] for record in result['snapshots']]
|
||||
@@ -470,12 +500,12 @@ def main():
|
||||
started_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
|
||||
for sig in (signal.SIGTERM, signal.SIGINT): signal.signal(sig, lambda *_: STOP.set())
|
||||
try:
|
||||
if not state.get('prepared'): prepare()
|
||||
if not state.get('prepared'): timed('prepare', prepare)
|
||||
thread = threading.Thread(target=other_writer, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
if not state.get('initial_complete'): run_phase('initial')
|
||||
if not state.get('mutated'): mutate()
|
||||
if not state.get('mutated'): timed('mutate', mutate)
|
||||
if not state.get('catchup_complete'): run_phase('catchup')
|
||||
before = state.get('other_subvolume_writes', 0)
|
||||
if not state.get('final_complete'):
|
||||
@@ -485,18 +515,26 @@ def main():
|
||||
job = json.loads((WORK / 'job.json').read_text())
|
||||
if len(job['snapshots']) < 4: raise RuntimeError('expected at least four snapshot stands')
|
||||
initial = set(state.get('initial_snapshots', [x['name'] for x in job['snapshots'][:2]]))
|
||||
verify_view('live', state['roots']['target'], True)
|
||||
for record in job['snapshots']:
|
||||
timed('verify live', verify_view, 'live', state['roots']['target'], True)
|
||||
# Round snapshots that sync already removed are not verifiable.
|
||||
present = [record for record in job['snapshots'] if not record.get('removed')]
|
||||
for record in present:
|
||||
path = ceph('target', 'fs', 'subvolume', 'snapshot', 'getpath',
|
||||
'cephfs', state['name'], record['name'], 'migration')
|
||||
verify_view(record['name'], path, record['name'] not in initial)
|
||||
timed('verify ' + record['name'], verify_view, record['name'], path, record['name'] not in initial)
|
||||
if snap('source', 'metadata', 'ls', 'cephfs', state['name'], record['name']) != snap(
|
||||
'target', 'metadata', 'ls', 'cephfs', state['name'], record['name']):
|
||||
raise RuntimeError('snapshot custom metadata mismatch')
|
||||
if not state.get('cleanup_complete'): run_phase('cleanup')
|
||||
application = {'baseline', 'changed'}
|
||||
for cluster in ('source', 'target'):
|
||||
left = {x['name'] for x in json.loads(snap(cluster, 'ls', 'cephfs', state['name']))}
|
||||
if left != application:
|
||||
raise RuntimeError(f'{cluster} snapshots after cleanup: {sorted(left)}')
|
||||
if state.get('other_writer_error'): raise RuntimeError(state['other_writer_error'])
|
||||
progress(phase='complete', result='PASS',
|
||||
snapshot_count=len(job['snapshots']),
|
||||
total_regular_paths_verified=(COUNT + 100) * (len(job['snapshots']) + 1))
|
||||
total_regular_paths_verified=(COUNT + 100) * (len(present) + 1))
|
||||
finally:
|
||||
STOP.set()
|
||||
thread.join(timeout=30)
|
||||
|
||||
+86
-3
@@ -12,6 +12,8 @@ import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import cephfs
|
||||
|
||||
|
||||
def ceph(cluster, *args):
|
||||
return subprocess.check_output([
|
||||
@@ -27,6 +29,15 @@ def snapshot(cluster, *args):
|
||||
return volume(cluster, "snapshot", *args)
|
||||
|
||||
|
||||
def claim_path():
|
||||
claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest()
|
||||
return "/mnt/target-fs/.cephmig/claims/" + claim
|
||||
|
||||
|
||||
def snapshot_names(cluster):
|
||||
return {x["name"] for x in json.loads(snapshot(cluster, "ls", "cephfs", name))}
|
||||
|
||||
|
||||
def acl():
|
||||
entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff),
|
||||
(16, 4, 0xffffffff), (32, 0, 0xffffffff)]
|
||||
@@ -64,6 +75,12 @@ def populate(root):
|
||||
os.setxattr(root + "/d", "ceph.quota.max_bytes", b"33554432")
|
||||
os.setxattr(root + "/d", "ceph.quota.max_files", b"1000")
|
||||
os.setxattr(root, "ceph.quota.max_bytes", b"268435456")
|
||||
# A subtree no round changes.
|
||||
os.makedirs(root + "/static/deep/deeper")
|
||||
pathlib.Path(root + "/static/deep/deeper/file").write_bytes(b"static" * 1000)
|
||||
os.link(root + "/static/deep/deeper/file", root + "/static/alias")
|
||||
os.setxattr(root + "/static/deep", "user.static", b"kept")
|
||||
os.symlink("deep/deeper/file", root + "/static/link")
|
||||
|
||||
|
||||
def edit_large(root, offset, data):
|
||||
@@ -122,6 +139,48 @@ def compare(src, dst):
|
||||
visit(src, dst)
|
||||
|
||||
|
||||
def mount(cluster):
|
||||
fs = cephfs.LibCephFS(conffile=f"/clusters/{cluster}/ceph.conf",
|
||||
conf={"keyring": f"/clusters/{cluster}/ceph.client.admin.keyring"})
|
||||
fs.mount(filesystem_name=b"cephfs")
|
||||
return fs
|
||||
|
||||
|
||||
def compare_times(src, dst, atime):
|
||||
"""Compare times through libcephfs; FUSE does not expose the birth time.
|
||||
|
||||
The access time is only compared for immutable snapshots, because the FUSE
|
||||
reads in compare() update it in the live trees."""
|
||||
keys = ("atime", "mtime", "ctime", "btime") if atime else ("mtime", "ctime", "btime")
|
||||
mask = cephfs.CEPH_STATX_BASIC_STATS | cephfs.CEPH_STATX_BTIME
|
||||
fa, fb = mount("source"), mount("target")
|
||||
|
||||
def ceph_path(p, cluster):
|
||||
prefix = f"/mnt/{cluster}-fs"
|
||||
assert p.startswith(prefix + "/"), p
|
||||
return p[len(prefix):].encode()
|
||||
|
||||
def visit(a, b):
|
||||
x = fa.statx(a, mask, cephfs.AT_SYMLINK_NOFOLLOW)
|
||||
y = fb.statx(b, mask, cephfs.AT_SYMLINK_NOFOLLOW)
|
||||
assert {k: x[k] for k in keys} == {k: y[k] for k in keys}, (a, x, y)
|
||||
if not stat.S_ISDIR(x["mode"]):
|
||||
return 1
|
||||
d = fa.opendir(a)
|
||||
names = []
|
||||
while entry := fa.readdir(d):
|
||||
if entry.d_name not in (b".", b"..", b".snap"):
|
||||
names.append(entry.d_name)
|
||||
fa.closedir(d)
|
||||
return 1 + sum(visit(a + b"/" + n, b + b"/" + n) for n in names)
|
||||
|
||||
try:
|
||||
return visit(ceph_path(src, "source"), ceph_path(dst, "target"))
|
||||
finally:
|
||||
fa.unmount()
|
||||
fb.unmount()
|
||||
|
||||
|
||||
action = sys.argv[1]
|
||||
if action == "setup":
|
||||
name = "native-itest-" + str(uuid.uuid4())
|
||||
@@ -144,7 +203,6 @@ if action == "setup":
|
||||
c.update(backend="native", workers=2, bandwidth_kib=2048)
|
||||
for endpoint in ("source", "target"):
|
||||
c[endpoint]["subvolume"] = name
|
||||
c[endpoint].pop("mount", None)
|
||||
pathlib.Path(config).write_text(json.dumps(c))
|
||||
src = roots["source"]
|
||||
populate(src)
|
||||
@@ -201,12 +259,22 @@ elif action == "mutate":
|
||||
elif action in ("verify", "final"):
|
||||
roots = json.load(open(fixture))
|
||||
compare(roots["source"], roots["target"])
|
||||
compare_times(roots["source"], roots["target"], atime=False)
|
||||
s = json.load(open(state))
|
||||
listed = {c: snapshot_names(c) for c in ("source", "target")}
|
||||
# Only the newest round snapshot remains as base; older ones are removed.
|
||||
kept = [x["name"] for x in s["snapshots"] if x["owned"] and not x.get("removed")]
|
||||
assert kept == [s["live_snapshot"]], (kept, s["live_snapshot"])
|
||||
for c in ("source", "target"):
|
||||
assert {n for n in listed[c] if n.startswith("cephmig-")} == set(kept), (c, listed[c])
|
||||
for snap in s["snapshots"]:
|
||||
assert snap["done"], snap
|
||||
if snap.get("removed"):
|
||||
continue
|
||||
a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath",
|
||||
"cephfs", name, snap["name"], "migration") for c in ("source", "target")]
|
||||
compare(a, b)
|
||||
assert compare_times(a, b, atime=True) > 10
|
||||
assert snapshot("source", "metadata", "ls", "cephfs", name, snap["name"]) == snapshot(
|
||||
"target", "metadata", "ls", "cephfs", name, snap["name"])
|
||||
h2 = next(x for x in s["snapshots"] if x["name"] == "history-2")["transfer"]
|
||||
@@ -218,6 +286,19 @@ elif action in ("verify", "final"):
|
||||
assert s["phase"] == "ready-for-cutover" and len(s["snapshots"]) == 5, s
|
||||
assert s["snapshots"][-1]["transfer"]["bytes_copied"] == 0, s["snapshots"][-1]
|
||||
print(json.dumps({"phase": s["phase"], "rounds": len(s["snapshots"]), "history_2": h2}))
|
||||
elif action == "cleaned":
|
||||
roots = json.load(open(fixture))
|
||||
compare(roots["source"], roots["target"])
|
||||
compare_times(roots["source"], roots["target"], atime=False)
|
||||
s = json.load(open(state))
|
||||
assert s["phase"] == "ready-for-cutover" and not s.get("live_snapshot"), s
|
||||
assert all(x.get("removed") for x in s["snapshots"] if x["owned"]), s
|
||||
application = {x["name"] for x in s["snapshots"] if not x["owned"]}
|
||||
assert application == {"history-1", "history-2"}, application
|
||||
for c in ("source", "target"):
|
||||
assert snapshot_names(c) == application, (c, snapshot_names(c))
|
||||
assert not os.path.exists(claim_path()), "claim not released"
|
||||
print(json.dumps({"remaining_snapshots": sorted(application)}))
|
||||
elif action == "busy":
|
||||
# An unrelated source subvolume remains writable throughout migration/finalization.
|
||||
p = "/mnt/source/" + name
|
||||
@@ -238,8 +319,10 @@ elif action == "cleanup":
|
||||
for snap in json.loads(snapshot(cluster, "ls", "cephfs", name)):
|
||||
snapshot(cluster, "rm", "cephfs", name, snap["name"])
|
||||
volume(cluster, "rm", "cephfs", name, "--force")
|
||||
claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest()
|
||||
os.unlink("/mnt/target-fs/.cephmig/claims/" + claim)
|
||||
try:
|
||||
os.unlink(claim_path())
|
||||
except FileNotFoundError:
|
||||
pass # cleanup released it
|
||||
shutil.rmtree(work)
|
||||
else:
|
||||
raise ValueError(action)
|
||||
+8
-1
@@ -90,5 +90,12 @@ assert json.loads((p/"before.json").read_text()) == json.loads((p/"idempotent.js
|
||||
assert int((p/"busy-count").read_text()) > int((p/"busy-before-final").read_text()) > 20
|
||||
PY
|
||||
SH
|
||||
# Remove all cephmig snapshots; a second run must find nothing left to do.
|
||||
"${compose[@]}" exec -T native "$binary" cleanup --config "$config" --state "$state"
|
||||
"${compose[@]}" exec -T native "$binary" cleanup --config "$config" --state "$state"
|
||||
fixture cleaned "$name"
|
||||
# A finished job stays finished and does not claim the target again.
|
||||
"${compose[@]}" exec -T native "$binary" finalize --config "$config" --state "$state" --writers-stopped
|
||||
fixture cleaned "$name"
|
||||
completed=true
|
||||
echo 'PASS: native libcephfs without FUSE/rsync, blockdiff, snapshots, links, ACLs, xattrs, quotas, cancellation, SIGKILL resume, unrelated writers, finalization'
|
||||
echo 'PASS: native libcephfs without FUSE/rsync, blockdiff, snapshots, links, ACLs, xattrs, quotas, cancellation, SIGKILL resume, unrelated writers, finalization, snapshot cleanup'
|
||||
+5
-3
@@ -135,7 +135,6 @@ def main():
|
||||
c.update(backend="native", workers=4, bandwidth_kib=0)
|
||||
for endpoint in ("source", "target"):
|
||||
c[endpoint]["subvolume"] = name
|
||||
c[endpoint].pop("mount", None)
|
||||
config.write_text(json.dumps(c))
|
||||
root = Path(roots["source"])
|
||||
(root / "flat").mkdir()
|
||||
@@ -237,10 +236,13 @@ def main():
|
||||
state = json.loads(journal.read_text())
|
||||
started = time.monotonic()
|
||||
checked = compare(roots["source"], roots["target"])
|
||||
if checked != count + 100 or state["phase"] != "ready-for-cutover" or len(state["snapshots"]) != 4:
|
||||
# sync removes older round snapshots; only the final one remains.
|
||||
present = [s for s in state["snapshots"] if not s.get("removed")]
|
||||
if (checked != count + 100 or state["phase"] != "ready-for-cutover" or len(state["snapshots"]) != 4 or
|
||||
[s["name"] for s in present if s.get("owned")] != [state["snapshots"][-1]["name"]]):
|
||||
raise AssertionError("unexpected file count or incomplete migration")
|
||||
snapshots = []
|
||||
for s in state["snapshots"]:
|
||||
for s in present:
|
||||
a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath",
|
||||
"cephfs", name, s["name"], "migration") for c in ("source", "target")]
|
||||
snapshot_checked = compare(a, b, s["name"])
|
||||
|
||||
+90
-87
@@ -1,108 +1,111 @@
|
||||
# Lokale Laborumgebung
|
||||
# Local lab
|
||||
|
||||
Diese Seite beschreibt die Docker-Compose-Umgebung unter `dev/` mit zwei
|
||||
unabhängigen Ceph-Clustern. Einstieg und Kurzüberblick: [README](../README.md).
|
||||
This page describes the Docker Compose environment under `dev/` with two
|
||||
independent Ceph clusters. Introduction and overview: [README](../README.md).
|
||||
|
||||
## Aufbau und Dienste
|
||||
## Layout and services
|
||||
|
||||
Der Dienst `native` läuft ohne privilegierten Modus, ohne `/dev/fuse` und ohne
|
||||
CephFS-Mounts. Der separate privilegierte `client` dient als unabhängiger
|
||||
Anwendungsclient und für den rsync-Vergleichstest.
|
||||
The service `native` runs without privileged mode, without `/dev/fuse` and
|
||||
without CephFS mounts. The separate privileged `client` serves as an
|
||||
independent application client that checks the results through FUSE.
|
||||
|
||||
`make dev-smallfiles-test` prüft standardmäßig 10.000 Dateien mit jeweils
|
||||
128 Byte Inhalt, zusätzlich Hardlinks und Symlinks. Die Hälfte der Dateien
|
||||
liegt in einem großen Verzeichnis, die andere verteilt auf 50 Unterverzeichnisse.
|
||||
Der Test misst Erstübertragung, Änderungsabgleich und finalen Abgleich einschließlich
|
||||
Prüfung. Ein separater Anwendungsclient vergleicht danach alle Inhalte, Metadaten
|
||||
und Snapshot-Stände. Berichte liegen unter `/tmp/cephmig-smallfiles-report`;
|
||||
erfolgreiche Testdaten und Snapshots werden entfernt. Die Dateianzahl lässt sich
|
||||
beispielsweise mit `FILES=2000 make dev-smallfiles-test` begrenzen.
|
||||
Ein dokumentierter lokaler Lauf einschließlich Vorher-/Nachher-Zählern für
|
||||
MDS-Anfragen steht in [docs/smallfiles-local.md](smallfiles-local.md).
|
||||
Der getrennte Test mit einer Million Dateien und vier Snapshot-Ständen wird
|
||||
mit `make dev-million-start` gestartet; Speicherbedarf, Status und Bereinigung
|
||||
stehen in [docs/million-local.md](million-local.md).
|
||||
VCS-Stamping ist im Build deaktiviert, damit auch ein
|
||||
Quellverzeichnis ohne nutzbare Git-Metadaten gebaut werden kann.
|
||||
`make dev-smallfiles-test` checks 10,000 files of 128 bytes each by default,
|
||||
plus hardlinks and symlinks. Half of the files are in one large directory,
|
||||
the other half spread over 50 subdirectories. The test measures the initial
|
||||
transfer, the catch-up round and the final round including verification. A
|
||||
separate application client then compares all contents, metadata and
|
||||
snapshot states. Reports are written to `/tmp/cephmig-smallfiles-report`;
|
||||
test data and snapshots of a successful run are removed. The number of files
|
||||
can be limited, for example with `FILES=2000 make dev-smallfiles-test`.
|
||||
A documented local run including before/after counters of MDS requests is in
|
||||
[docs/smallfiles-local.md](smallfiles-local.md).
|
||||
The separate test with one million files and four snapshot states is started
|
||||
with `make dev-million-start`; disk requirements, status and cleanup are
|
||||
described in [docs/million-local.md](million-local.md).
|
||||
VCS stamping is disabled in the build, so that a source directory without
|
||||
usable Git metadata can also be built.
|
||||
|
||||
Der Smoke-Test erstellt einen Subvolume-Snapshot, verändert danach die Quelle
|
||||
und kopiert den unveränderten Snapshot zum Ziel. Er prüft Inhalte, Dateirechte,
|
||||
POSIX-ACLs, ein Benutzer-xattr, Hardlinks, Symlinks, Quota-Operationen und die
|
||||
Isolation der beiden Cluster. `make dev-restart-check` startet das Labor neu
|
||||
und prüft, dass FSIDs und Daten beider Subvolumes erhalten bleiben.
|
||||
Die Sparse-Testdatei wird auf ihren Inhalt geprüft; die physische Platzbelegung
|
||||
ist keine Zusicherung dieses Tests.
|
||||
The smoke test creates a subvolume snapshot, then changes the source and
|
||||
copies the unchanged snapshot to the target. It checks contents, file modes,
|
||||
POSIX ACLs, a user xattr, hardlinks, symlinks, quota operations and the
|
||||
isolation of the two clusters. `make dev-restart-check` restarts the lab and
|
||||
checks that the FSIDs and the data of both subvolumes are preserved. The
|
||||
sparse test file is checked for its content; physical space usage is not
|
||||
asserted by this test.
|
||||
|
||||
`source` und `target` sind unabhängige Ceph-Cluster mit unterschiedlichen FSIDs
|
||||
und Schlüsseln. Jeder enthält MON, MGR, OSD und MDS sowie das Dateisystem
|
||||
`cephfs`, die Subvolume-Gruppe `migration` und das Subvolume `demo`.
|
||||
Der Client mountet diese Subvolumes unter `/mnt/source` und `/mnt/target`.
|
||||
Für die von der Ceph-API gelieferten Snapshotpfade ist das Quelldateisystem
|
||||
zusätzlich unter `/mnt/source-fs` und das Ziel unter `/mnt/target-fs` gemountet;
|
||||
Subvolume-Snapshots liegen außerhalb
|
||||
des aktuellen Daten-UUID-Verzeichnisses.
|
||||
Es werden keine Host-Geräte formatiert und keine Ports am Host veröffentlicht.
|
||||
Die OSD-Daten liegen in Docker-Volumes. Die Replikationszahl 1 und die
|
||||
Administratorschlüssel im Testclient dienen ausschließlich dem lokalen Labor.
|
||||
Der Client ergänzt das feste Ceph-Basisimage um die festgeschriebene
|
||||
rsync-Paketversion. Das Journal kann unter `/state` in einem eigenen
|
||||
Docker-Volume dauerhaft gespeichert werden.
|
||||
`source` and `target` are independent Ceph clusters with different FSIDs and
|
||||
keys. Each contains a MON, MGR, OSD and MDS as well as the file system
|
||||
`cephfs`, the subvolume group `migration` and the subvolume `demo`. The
|
||||
client mounts these subvolumes at `/mnt/source` and `/mnt/target`. For the
|
||||
snapshot paths returned by the Ceph API, the source file system is also
|
||||
mounted at `/mnt/source-fs` and the target at `/mnt/target-fs`; subvolume
|
||||
snapshots live outside the current data UUID directory.
|
||||
No host devices are formatted and no ports are published on the host. The
|
||||
OSD data lives in Docker volumes. The replication factor 1 and the
|
||||
administrator keys in the test client are for the local lab only. The client
|
||||
uses the pinned Ceph base image unchanged. The journal can be stored permanently under `/state` in a dedicated Docker
|
||||
volume.
|
||||
|
||||
```sh
|
||||
# Status und Logs
|
||||
# Status and logs
|
||||
docker compose -f dev/compose.yaml logs --tail 100 source target client
|
||||
|
||||
# Ceph CLI gegen den Quellcluster
|
||||
# Ceph CLI against the source cluster
|
||||
docker compose -f dev/compose.yaml exec source ceph fs subvolume info cephfs demo --group_name migration
|
||||
|
||||
# Stoppen; die Daten bleiben für den nächsten Start erhalten
|
||||
# Stop; the data is kept for the next start
|
||||
make dev-down
|
||||
```
|
||||
|
||||
Für einen vollständig frischen Testlauf löscht
|
||||
`docker compose -f dev/compose.yaml down --volumes` **alle Labordaten**.
|
||||
Das Basisimage lässt sich mit `CEPH_IMAGE=quay.io/ceph/ceph:<version>` ändern.
|
||||
Die Dockerfiles enthalten Paket- und SDK-Pins für Ceph 21.2.0 / EL10; bei einem
|
||||
Versionswechsel müssen diese passend angepasst werden.
|
||||
Die Baseline ist Ceph Umbrella 21.2.0 gemäß der
|
||||
[offiziellen Releaseübersicht](https://docs.ceph.com/en/latest/releases/),
|
||||
geprüft am 05.11.2026.
|
||||
Das veröffentlichte Containerimage trägt intern den Versionszusatz `dev`;
|
||||
für die Reproduzierbarkeit ist zusätzlich der Image-Digest festgeschrieben.
|
||||
Der Bootstrap legt die Pools mit expliziten PG-Zahlen an, da das Standardkommando
|
||||
`fs volume create` in diesem Image mit `EINVAL` scheiterte.
|
||||
For a completely fresh test run,
|
||||
`docker compose -f dev/compose.yaml down --volumes` deletes **all lab data**.
|
||||
The base image can be changed with `CEPH_IMAGE=quay.io/ceph/ceph:<version>`.
|
||||
The Dockerfiles contain package and SDK pins for Ceph 21.2.0 / EL10; they
|
||||
must be adjusted when the version changes. The Go toolchain of the native
|
||||
image comes from a pinned `golang` image.
|
||||
The baseline is Ceph Umbrella 21.2.0 according to the
|
||||
[official release overview](https://docs.ceph.com/en/latest/releases/),
|
||||
checked on 2026-11-05.
|
||||
The published container image internally carries the version suffix `dev`;
|
||||
for reproducibility, the image digest is pinned as well.
|
||||
The bootstrap creates the pools with explicit PG counts, because the default
|
||||
command `fs volume create` failed with `EINVAL` in this image.
|
||||
|
||||
`ceph health detail` kann im Labor `POOL_NO_REDUNDANCY` (ein OSD) und
|
||||
`MON_DISK_LOW` (weniger als 30 % freier Platz im Host-Dateisystem) melden.
|
||||
Diese Meldungen werden nicht unterdrückt. Container-Healthchecks prüfen die
|
||||
Nutzbarkeit des Subvolumes; sie ersetzen keine Produktions-Healthchecks.
|
||||
`ceph health detail` can report `POOL_NO_REDUNDANCY` (one OSD) and
|
||||
`MON_DISK_LOW` (less than 30 % free space in the host file system) in the
|
||||
lab. These messages are not suppressed. Container health checks verify that
|
||||
the subvolume is usable; they do not replace production health checks.
|
||||
|
||||
## Zielgröße und Grenzen
|
||||
## Target size and limits
|
||||
|
||||
Zielgröße: bis zu 200 TB und mehr als 200 Millionen Dateien, einschließlich
|
||||
vorhandener Snapshots, POSIX-ACLs, xattrs und Quotas. Pro Node stehen zwei
|
||||
25-Gbit/s-Verbindungen zur Verfügung; effektiver Durchsatz und eine feste
|
||||
Obergrenze für den Schreibstopp werden später bestimmt. Die lokale Umgebung prüft
|
||||
Funktionen, bildet diese Datenmenge jedoch nicht ab. Der native Kopierer verwendet
|
||||
begrenzte Worker und Puffer, einen dauerhaften Index auf lokalem Datenträger und
|
||||
optionale Bandbreitendrosselung. Vollständige Metadatenscans bleiben erforderlich.
|
||||
Ein Nachweis für Speicher, Indexgröße, Laufzeit und finalen Schreibstopp fehlt.
|
||||
Target size: up to 200 TB and more than 200 million files, including existing
|
||||
snapshots, POSIX ACLs, xattrs and quotas. Each node has two 25 Gbit/s links;
|
||||
effective throughput and a fixed upper bound for the write stop will be
|
||||
determined later. The local environment verifies functionality but does not
|
||||
reproduce this amount of data, and its single OSD per cluster limits the
|
||||
measured durations (see [smallfiles-local.md](smallfiles-local.md#limits-and-reproduction)). The native copier uses bounded workers and
|
||||
buffers, a persistent index on local disk and optional bandwidth limiting.
|
||||
Every round, the final one included, scans all metadata. Evidence for
|
||||
memory, index size,
|
||||
runtime and the final write stop is missing.
|
||||
|
||||
1. Quelle, Ziel, Berechtigungen, Kapazität und benötigte Metadaten prüfen.
|
||||
2. Konsistenten Quellsnapshot erstellen und initial bei laufender Anwendung kopieren.
|
||||
3. Änderungen mit weiteren Snapshots und Abgleichen nachziehen.
|
||||
4. Alle schreibenden Anwendungen anhalten, offene Schreibvorgänge abschließen,
|
||||
letzten Snapshot übertragen und Daten sowie Metadaten verifizieren.
|
||||
5. Clients auf das Ziel ummounten und Anwendungen freigeben.
|
||||
1. Check source, target, permissions, capacity and required metadata.
|
||||
2. Create a consistent source snapshot and make the initial copy while the
|
||||
application keeps running.
|
||||
3. Catch up with changes through further snapshots and rounds.
|
||||
4. Stop all writing applications, complete pending writes, transfer the last
|
||||
snapshot and verify data and metadata.
|
||||
5. Remount the clients on the target and release the applications.
|
||||
6. Remove the migration snapshots with `cephmig cleanup`.
|
||||
|
||||
Ein Dateisystemsnapshot allein stellt keine Anwendungskonsistenz für Datenbanken
|
||||
her. Der finale Schreibstopp muss alle Clients umfassen. Ein Umhängen eines
|
||||
Mounts übernimmt keine bereits offenen Dateideskriptoren. Nach ersten
|
||||
Schreibzugriffen am Ziel benötigt ein Rückwechsel einen erneuten Abgleich.
|
||||
Die derzeit implementierte Datenübertragung ist im Labormodus prüfbar;
|
||||
produktive Umschaltung und Lastnachweise für die Zielgröße sind noch offen.
|
||||
A file system snapshot alone does not make databases application-consistent.
|
||||
The final write stop must cover all clients. Moving a mount does not carry
|
||||
over file descriptors that are already open. After the first writes to the
|
||||
target, switching back requires another round.
|
||||
The data transfer implemented so far can be verified in lab mode; a
|
||||
production cutover and load tests at the target size are still open.
|
||||
|
||||
Die Umgebung folgt dem
|
||||
[manuellen Ceph-Bootstrap](https://docs.ceph.com/en/latest/install/manual-deployment/).
|
||||
Die Einordnung des direkten RADOS-Objektimports und die Grenzen der nativen
|
||||
Implementierung stehen in [docs/raw-transfer.md](raw-transfer.md).
|
||||
The environment follows the
|
||||
[manual Ceph bootstrap](https://docs.ceph.com/en/latest/install/manual-deployment/).
|
||||
The assessment of a direct RADOS object import and the limits of the native
|
||||
implementation are in [docs/raw-transfer.md](raw-transfer.md).
|
||||
+358
-218
@@ -1,58 +1,58 @@
|
||||
# Migrationsprototyp
|
||||
# Migration prototype
|
||||
|
||||
Die Prüfung eines direkten RADOS-Objekttransfers und die native Alternative
|
||||
über libcephfs sind in [raw-transfer.md](raw-transfer.md) dokumentiert.
|
||||
The evaluation of a direct RADOS object transfer and the native alternative
|
||||
through libcephfs are documented in [raw-transfer.md](raw-transfer.md).
|
||||
|
||||
## Snapshot-Identität: dokumentierte Abweichung
|
||||
## Snapshot identity: documented deviation
|
||||
|
||||
Native Snapshot-IDs und Ceph-Geburtszeitpunkte werden am Ziel neu vergeben.
|
||||
Wie vereinbart blockiert diese Abweichung die Migration nicht. `inspect`,
|
||||
die Übertragungsausgabe und das persistente Journal enthalten einen Hinweis;
|
||||
ursprüngliche und neue Erstellungszeiten stehen bei jedem übertragenen Snapshot.
|
||||
Eine Anwendung, die native IDs direkt speichert, muss die neuen Werte beachten.
|
||||
Native snapshot IDs and Ceph birth times are assigned anew at the target. As
|
||||
agreed, this deviation does not block the migration. `inspect`, the transfer
|
||||
output and the persistent journal contain a note; the original and the new
|
||||
creation times are recorded for every transferred snapshot. An application
|
||||
that stores native IDs directly must account for the new values.
|
||||
|
||||
Die unterstützte `ceph_mksnap`-Schnittstelle nimmt Namen, Modus und
|
||||
benutzerdefinierte Metadaten entgegen, aber keine gewünschte native ID oder
|
||||
Geburtszeit. `ceph.snap.btime` ist im Client ausdrücklich schreibgeschützt.
|
||||
Auch CephFS-Mirroring erzeugt im Ziel einen neuen Snapshot und hält die
|
||||
Quell-ID als separate Metadaten fest.
|
||||
The supported `ceph_mksnap` interface accepts a name, a mode and custom
|
||||
metadata, but no desired native ID or birth time. `ceph.snap.btime` is
|
||||
explicitly read-only in the client. CephFS mirroring also creates a new
|
||||
snapshot at the target and records the source ID as separate metadata.
|
||||
|
||||
Quellen:
|
||||
Sources:
|
||||
|
||||
- [libcephfs-Schnittstelle](https://github.com/ceph/ceph/blob/main/src/include/cephfs/libcephfs.h)
|
||||
- [Client: virtuelle Snapshot-Attribute](https://github.com/ceph/ceph/blob/main/src/client/Client.cc)
|
||||
- [Mirror: Anlegen eines Zielsnapshots](https://github.com/ceph/ceph/blob/main/src/tools/cephfs_mirror/PeerReplayer.cc)
|
||||
- [libcephfs interface](https://github.com/ceph/ceph/blob/main/src/include/cephfs/libcephfs.h)
|
||||
- [Client: virtual snapshot attributes](https://github.com/ceph/ceph/blob/main/src/client/Client.cc)
|
||||
- [Mirror: creating a target snapshot](https://github.com/ceph/ceph/blob/main/src/tools/cephfs_mirror/PeerReplayer.cc)
|
||||
|
||||
Im lokalen Ceph-21.2.0-Labor wurden bei einem gleichnamigen Snapshot
|
||||
Quell-ID 6 und Ziel-ID 2 sowie unterschiedliche Geburtszeiten gemessen.
|
||||
Ein Schreibversuch mit dem bereits vorhandenen Wert von `ceph.snap.btime`
|
||||
am eigenen Testsnapshot wurde mit `EROFS` abgewiesen.
|
||||
In the local Ceph 21.2.0 lab, a snapshot of the same name had source ID 6 and
|
||||
target ID 2 and different birth times. An attempt to write the existing value
|
||||
of `ceph.snap.btime` on our own test snapshot was rejected with `EROFS`.
|
||||
|
||||
Mit den geprüften Schnittstellen lässt sich die native Snapshot-Identität nicht
|
||||
vorgeben. Diese Einschränkung ist akzeptiert; sie wird ausdrücklich vermerkt.
|
||||
Lastnachweise und eine automatisierte produktive Client-Umschaltung fehlen noch.
|
||||
The examined interfaces do not allow the native snapshot identity to be set.
|
||||
This limitation is accepted and explicitly recorded. Load tests and an
|
||||
automated production client cutover are still missing.
|
||||
|
||||
## Kommandos
|
||||
## Commands
|
||||
|
||||
Das native Backend benötigt Linux, Ceph CLI, libcephfs und einen mit CGO und
|
||||
`-tags ceph` gebauten Kopierer. Es benötigt keine Betriebssystem-Mounts und
|
||||
keinen privilegierten Container. Zum Erhalten fremder UID/GID und geschützter
|
||||
xattrs sind entsprechende Client-/Prozessrechte nötig; das Labor verwendet root.
|
||||
Der optionale Referenzpfad `backend: rsync` benötigt zusätzlich rsync und am
|
||||
Dateisystem-Root gemountete Quell-/Zieldateisysteme.
|
||||
Die Subvolumes müssen schon existieren. Für einen neuen Job müssen Datenbaum,
|
||||
Snapshots und benutzerdefinierte Metadaten des Ziels leer sein.
|
||||
Keine Anwendung darf ins Ziel schreiben.
|
||||
CephMig needs Linux, the Ceph CLI, libcephfs and a copier built with CGO and
|
||||
`-tags ceph`. It needs no operating system mounts and no privileged
|
||||
container. Preserving foreign UID/GID and protected xattrs requires the
|
||||
corresponding client and process privileges; the lab uses root. An rsync
|
||||
backend over mounted file systems existed earlier and was removed; a
|
||||
configuration with `backend: rsync` or `mount` is rejected.
|
||||
The subvolumes must already exist. For a new job, the data tree, snapshots and
|
||||
custom metadata of the target must be empty. No application may write to the
|
||||
target.
|
||||
|
||||
Die Konfiguration in `dev/migration.example.json` wählt `backend: native` und
|
||||
gilt im Labordienst `native`. `mount` wird dort nicht verwendet und kann fehlen.
|
||||
`workers` begrenzt gleichzeitige Dateikopien (Standard 8, maximal 64),
|
||||
`bandwidth_kib` begrenzt die Summe geschriebener Nutzdatenbytes pro Sekunde.
|
||||
Beide Werte dürfen bei Wiederaufnahme geändert werden.
|
||||
Die nativen `transfer`-Statistiken im Journal nennen Modus, Basis-Snapshot,
|
||||
besuchte/kopierte Dateien sowie geschriebene und zur Prüfung gelesene Bytes.
|
||||
`bytes_copied` zählt Nutzdaten-Schreibzugriffe ohne ausgesparte Nullbereiche;
|
||||
es misst nicht das gesamte Netzwerkaufkommen einschließlich Protokoll und Prüfung.
|
||||
The configuration in `dev/migration.example.json` applies to the lab service
|
||||
`native`. `backend` may be omitted; its only value is `native`. `workers`
|
||||
limits concurrent file copies and verification checks (default 8, at most 64),
|
||||
`bandwidth_kib` limits the total payload bytes written per second. Both values
|
||||
may be changed when resuming.
|
||||
The `transfer` statistics in the journal report the mode, the base
|
||||
snapshot, visited and copied files, bytes written and read for verification,
|
||||
the files transferred with blockdiff, the entries reported by snapdiff and
|
||||
the duration of the round in seconds. `bytes_copied` counts payload writes without skipped zero
|
||||
ranges; it does not measure the total network traffic including protocol and
|
||||
verification.
|
||||
|
||||
```sh
|
||||
make dev-native-build
|
||||
@@ -61,222 +61,362 @@ docker compose -f dev/compose.yaml exec native \
|
||||
cephmig-native inspect --config /lab/migration.example.json
|
||||
```
|
||||
|
||||
Der lesende Preflight vergleicht CLI-FSID und die über den Client gelesene
|
||||
`ceph.cluster_fsid`, prüft Pfade und Subvolume-Status und meldet die aktuelle
|
||||
Datenmenge sowie Snapshotnamen. Die Datenmenge ist **keine** Kapazitätsprognose
|
||||
für alle historischen Snapshots.
|
||||
The read-only preflight compares the FSID from the CLI with the
|
||||
`ceph.cluster_fsid` read through the client, checks paths and subvolume state
|
||||
and reports the current data size and snapshot names. The data size is **not**
|
||||
a capacity forecast for all historical snapshots.
|
||||
|
||||
Das Backend hat folgende Übertragungskommandos:
|
||||
The transfer commands are:
|
||||
|
||||
```sh
|
||||
cephmig sync --config /absolute/config.json --state /local-state/job.json
|
||||
cephmig status --state /local-state/job.json
|
||||
# Alle Quellwriter einschließlich weiterer Clients stoppen und flushen.
|
||||
# Stop and flush all source writers, including other clients.
|
||||
cephmig finalize --config /absolute/config.json \
|
||||
--state /local-state/job.json --writers-stopped
|
||||
# After the cutover has been checked:
|
||||
cephmig cleanup --config /absolute/config.json --state /local-state/job.json
|
||||
```
|
||||
|
||||
`sync` verarbeitet bekannte, noch nicht abgeschlossene Stände, neu entdeckte
|
||||
Anwendungssnapshots und danach einen neuen Quellsnapshot. Weitere Änderungen
|
||||
werden durch erneutes `sync` nachgezogen. Das native Backend verwendet Snapdiff
|
||||
und die Ceph-Inode-Version; dadurch werden auch Datenänderungen gleicher Größe
|
||||
und gleicher mtime erkannt. Der rsync-Pfad verwendet Prüfsummen.
|
||||
`sync` processes known, unfinished states, newly discovered application
|
||||
snapshots and then a new source snapshot. Further changes are caught up by
|
||||
running `sync` again. CephMig uses snapdiff and the Ceph inode version, so it
|
||||
also detects data changes with the same size and mtime.
|
||||
|
||||
`finalize` bestätigt den Schreibstopp ausschließlich über die ausdrückliche
|
||||
Operatorangabe; es stoppt oder sperrt selbst keine Anwendung. Alle Writer
|
||||
müssen bis zur abgeschlossenen Umschaltung gestoppt bleiben. Der Job endet
|
||||
bei `ready-for-cutover`. Remounts, Neustarts der Anwendungen und eine
|
||||
Rückmigration nach Schreibzugriffen am Ziel sind nicht automatisiert.
|
||||
### Metadata scan
|
||||
|
||||
## Übertragene Daten
|
||||
Every round reads the metadata of all entries of its snapshot. This is the
|
||||
main cost of a round: in the [one-million-file test](million-local.md), even
|
||||
an unchanged finalization took 1 h 20 min and 19.3 million MDS requests.
|
||||
Snapdiff cannot replace this scan; in the lab it reported every directory and
|
||||
missed pure chmod, xattr changes and writes through a hardlink alias.
|
||||
|
||||
- Snapshotnamen und Inhalte; bestehende Snapshots werden chronologisch übertragen.
|
||||
- Numerische UID/GID, Modus, mtime, POSIX-ACLs einschließlich Default-ACLs.
|
||||
- Benutzer-xattrs und weitere portable xattrs; einschließlich leerer Werte und Löschungen.
|
||||
- Hardlinks innerhalb des Subvolumes, Symlinks und FIFOs.
|
||||
- Sparse-Dateiinhalte; der native Pfad überspringt Nullbereiche bzw. verwendet Hole-Punching.
|
||||
Die physische Platzbelegung wird nicht zugesichert.
|
||||
- Verzeichnisquotas `ceph.quota.max_bytes` und `ceph.quota.max_files`, auch am Datenroot.
|
||||
- Benutzerdefinierte Subvolume- und Snapshot-Metadaten über die Manager-API.
|
||||
- Ursprüngliche und neue Snapshot-Erstellungszeiten im Journal.
|
||||
An earlier version skipped a subdirectory in intermediate rounds when its
|
||||
inode version and its `ceph.dir.rctime` matched the previous round. It was
|
||||
removed because it missed changes. In the 10,000-file test on 2026-12-03, a
|
||||
round snapshot taken seconds after changes skipped the directory `tree/`
|
||||
with about 250 changed files in its subdirectories: the inode version of
|
||||
`tree/` changes only with its own entries, and Ceph had not yet propagated
|
||||
the rctime of the grandchildren to it. That target snapshot was incomplete,
|
||||
and its verification did not notice, because it skipped the same subtrees;
|
||||
only `finalize`, which always scanned everything, closed the gap. Base index
|
||||
entries that this version marked `carried` are never trusted; such files are
|
||||
copied in full in the next round.
|
||||
|
||||
Softlinks bleiben als Linktext erhalten, auch wenn das Ziel nicht existiert.
|
||||
Der native Pfad erhält auch Hardlinks auf Symlinks und FIFOs; bei Symlinks
|
||||
verknüpft er die Inode über die öffentliche Low-Level-Schnittstelle, damit der
|
||||
Link selbst und nicht sein Referent verknüpft wird.
|
||||
Absolute Links werden nicht umgeschrieben; bei der Umschaltung muss der
|
||||
Anwendungs-Mountpfad dazu passen. Hardlinks über die Grenze des übertragenen
|
||||
Subvolumes hinaus werden nicht als gemeinsame Verknüpfung migriert.
|
||||
`finalize` relies solely on the operator's explicit confirmation of the write
|
||||
stop; it does not stop or lock any application itself. All writers must stay
|
||||
stopped until the cutover is complete. The job ends in `ready-for-cutover`.
|
||||
Remounts, application restarts and a migration back after writes to the
|
||||
target are not automated.
|
||||
|
||||
Clusterinterne Layout-, Pool- und andere `ceph.*`-Attribute werden nicht
|
||||
blind kopiert; Quotas werden gesondert übertragen. Pool-/Layout-Mappings,
|
||||
Subvolumegruppenquotas, Pinning, Authorisierungen, Snapshot-Zeitpläne, aktive
|
||||
Clone-Jobs und weitere Ceph-Verwaltungszustände sind nicht implementiert.
|
||||
Die Migration übernimmt die von der Subvolume-API aufgelisteten Snapshots mit
|
||||
ihrem gesamten Verzeichnisbaum. CephFS unterstützt allgemein Verzeichnissnapshots;
|
||||
eigene Snapshots unterhalb eines verwalteten Subvolumes verweigert der MDS jedoch.
|
||||
Im Ceph-21.2.0-Labor war ein Snapshot eines normalen Verzeichnisses erfolgreich,
|
||||
derselbe Versuch in einem Subvolume-Unterordner scheiterte mit `EPERM`.
|
||||
In Unterordnern sichtbare, geerbte Snapshot-Ansichten sind Bestandteil des
|
||||
übergeordneten Subvolume-Snapshots. Die frühere Warnung zu separaten
|
||||
Unterverzeichnissnapshots war für dieses verwaltete Subvolume-Modell zu pauschal.
|
||||
Siehe [MDS-Prüfung der Subvolume-Grenze](https://github.com/ceph/ceph/blob/main/src/mds/Server.cc).
|
||||
ctime, atime, originale Inode-Nummern und native Snapshot-IDs bleiben nicht erhalten.
|
||||
Verschlüsselte, normalisierte, nicht case-sensitive oder mit Earmark versehene
|
||||
Subvolumes werden abgelehnt.
|
||||
### Migration snapshots
|
||||
|
||||
## Wiederaufnahme und Verifikation
|
||||
Each round creates a snapshot `cephmig-<job>-<round>` at source and target.
|
||||
Only the newest one is needed, as base for the next round. As soon as a round
|
||||
is complete, `sync` deletes the older round snapshots on both sides. Users of
|
||||
the subvolume therefore see at most one migration snapshot at a time.
|
||||
|
||||
Der Job speichert ein atomar ersetztes, mit fsync gesichertes JSON-Journal
|
||||
mit Modus 0600. Es enthält Konfiguration, Cluster-FSIDs, die konkreten
|
||||
Subvolume-Datenpfade und Snapshot-Intent-/Abschlussinformationen. Eine
|
||||
Neuanlage desselben Subvolumenamens mit anderer Daten-UUID wird abgewiesen.
|
||||
`cleanup` deletes the remaining round snapshot, including the final one,
|
||||
after the job is `ready-for-cutover`. Afterwards the subvolumes hold only the
|
||||
snapshots of the application. Since the final snapshot is the immutable
|
||||
reference of the last round, run `cleanup` only after the cutover has been
|
||||
checked. As its last step, `cleanup` deletes the target claim (see below) and
|
||||
the directories `.cephmig/claims` and `.cephmig` if they are empty. The job
|
||||
is then finished: `cleanup` and `finalize` do nothing more, and `sync` is
|
||||
refused. `cleanup` is idempotent.
|
||||
|
||||
Eine lokale flock-Sperre verhindert parallele Zugriffe auf dasselbe Journal.
|
||||
Ein persistenter Claim unter `<target-filesystem>/.cephmig/claims/` mit
|
||||
exklusiver Datei-/CephFS-Sperre schützt das Ziel auch bei verschiedenen lokalen
|
||||
Journalpfaden. Ein fehlendes oder unvollständiges Journal wird nicht durch
|
||||
automatische Übernahme vorhandener Zieldaten ersetzt.
|
||||
Application snapshots are never deleted. The journal marks a snapshot as
|
||||
`removed` before deleting it, so an interrupted run completes the deletion
|
||||
next time.
|
||||
|
||||
Jeder Snapshotstand wird kopiert, einschließlich Quotas verifiziert und erst
|
||||
danach am Ziel als Snapshot angelegt. Ein bereits angelegter, aber noch nicht
|
||||
im Journal bestätigter Zielsnapshot wird bei Wiederaufnahme erneut gegen die
|
||||
unveränderliche Quelle geprüft. Ersatz oder Verlust bereits abgeschlossener
|
||||
Snapshots wird anhand der gespeicherten Identität erkannt.
|
||||
## Workflow in detail
|
||||
|
||||
Der native Datenpfad verwendet einen lokalen bbolt-Index mit Quell-Inode,
|
||||
Inode-Version, Größe und Ziel-Inode pro Pfad. Er enthält keine Dateiinhalte.
|
||||
Die bestätigte Basis wird vor jeder Zieländerung im JSON-Journal ungültig
|
||||
gemacht und erst nach erfolgreicher Verifikation und einem fsync des Index
|
||||
erneut bestätigt. Cluster, Daten-UUID-Pfade und Snapshotname müssen passen.
|
||||
Nach einem Abbruch wird der offene Stand vollständig nativ rekonstruiert;
|
||||
ein nur teilweise ausgeführter Blockdiff darf nicht als Basis gelten.
|
||||
Ein bereits publizierter, unbestätigter Zielsnapshot wird erneut geprüft.
|
||||
Nach SIGKILL kann die Freigabe alter Ceph-Clientsitzungen den Wiederanlauf verzögern.
|
||||
The diagram shows one migration with the native backend: an intermediate
|
||||
`sync` round, `finalize` and `cleanup`. Application snapshots discovered at
|
||||
the source are transferred like a round, but are never deleted.
|
||||
|
||||
Der Index enthält außerdem das vollständige Pfadinventar des unveränderlichen
|
||||
Quellsnapshots: Dateien, Verzeichnisse, Hardlink-Aliase und Spezialdateien.
|
||||
Erst nach vollständiger Erfassung wird es als vollständig markiert. Aufräumen
|
||||
und Überhangprüfung gleichen Zielpfade mit diesem lokalen Inventar ab und
|
||||
vermeiden dadurch erneute `stat`-Abfragen für jeden Quellpfad. Unvollständige
|
||||
oder beschädigte Inventare führen zum Abbruch. Bereits identische Inode-Zeilen
|
||||
werden bei der Verifikation nicht erneut in den Index geschrieben.
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor Op as Operator
|
||||
participant M as cephmig
|
||||
participant J as Journal (local)
|
||||
participant I as Index (local bbolt)
|
||||
participant S as Source cluster
|
||||
participant T as Target cluster
|
||||
participant V as Verify client
|
||||
|
||||
Unveränderliche Pfade unter `.snap` werden bei `stat` und `readdirplus` mit
|
||||
`AT_STATX_DONT_SYNC` gelesen, wie in Cephs eigenem Mirror. Dadurch werden
|
||||
Metadatensperren nicht allein für eine erneute Synchronisation bereits
|
||||
unveränderlicher Snapshot-Inodes angefordert. Live-Zielpfade behalten ihre
|
||||
normale Synchronisationssemantik. Details und Messergebnisse stehen in
|
||||
[smallfiles-local.md](smallfiles-local.md).
|
||||
Op->>M: sync --config --state
|
||||
M->>S: fsid, subvolume info, snapshot ls
|
||||
M->>T: fsid, subvolume info, snapshot ls
|
||||
M->>T: lock claim in /.cephmig/claims
|
||||
M->>J: record intent for round snapshot R(n)
|
||||
M->>S: create snapshot R(n)
|
||||
M->>J: invalidate the confirmed base
|
||||
M->>I: open base R(n-1), create pending index
|
||||
M->>S: snapdiff R(n-1) to R(n)
|
||||
|
||||
Bei einer vollständigen Kopie vergleicht die native Prüfung alle Dateiinhalte.
|
||||
Bei Folgeständen prüft sie kopierte Dateien bzw. die von Blockdiff gemeldeten
|
||||
Bereiche. Unveränderte Bytes stammen aus der zuvor verifizierten Basis. Daher
|
||||
muss der Zielbaum während des gesamten Jobs ausschließlich dem Kopierer gehören.
|
||||
Fremde Änderungen unveränderter Dateibereiche werden damit nicht zuverlässig
|
||||
gefunden. Metadaten, Quotas und Hardlink-Topologie werden in jedem Stand geprüft.
|
||||
Ein direkt nach der Prüfung angelegter Zielsnapshot wird auf Metadaten und
|
||||
Links geprüft; dieselben unveränderlichen Daten werden nicht erneut gelesen.
|
||||
loop every entry, from the root down
|
||||
M->>I: record path inventory
|
||||
M->>T: mkdir, copy changed files (blockdiff or full), symlinks, FIFOs
|
||||
M->>T: xattrs and quotas, then setattr and ctime stamp
|
||||
end
|
||||
|
||||
Die rsync-Prüfung liest Dateiinhalte per Checksumme und vergleicht zusätzlich
|
||||
die unterstützten Metadaten. Quotawerte werden separat geprüft. Wiederaufnahme
|
||||
innerhalb eines Standes nutzt die vorhandenen Teilkopien, muss den Baum aber
|
||||
erneut scannen; Checkpoints sind derzeit pro Snapshot, nicht pro Datei.
|
||||
Bei einem im Labor reproduzierten Hardlink-`EEXIST` wird genau einmal
|
||||
idempotent wiederholt; andere Fehler werden sofort zurückgegeben.
|
||||
M->>T: hardlink aliases, prune surplus entries
|
||||
M->>T: restore directory metadata, deepest first
|
||||
M->>T: sync_fs
|
||||
M->>V: connect a fresh client, close the writing client
|
||||
V->>T: compare metadata, links and copied ranges with R(n)
|
||||
M->>T: create snapshot R(n), copy snapshot metadata
|
||||
V->>T: compare snapshot R(n) with R(n)
|
||||
M->>I: commit pending index as new base
|
||||
M->>J: mark R(n) done, base = R(n)
|
||||
M->>J: mark R(n-1) removed
|
||||
M->>S: remove snapshot R(n-1)
|
||||
M->>T: remove snapshot R(n-1)
|
||||
M-->>Op: journal as JSON
|
||||
|
||||
Zusätzlich wird die Hardlink-Topologie in beide Richtungen geprüft: alle
|
||||
Quellpfade derselben Inode müssen im Ziel zusammengehören; unabhängige
|
||||
Quelldateien dürfen im Ziel nicht versehentlich dieselbe Inode teilen.
|
||||
Das ist nötig, weil [rsync -H](https://download.samba.org/pub/rsync/rsync.1)
|
||||
überzählige bestehende Zielverknüpfungen nicht in jedem Fall auflöst.
|
||||
Im rsync-Pfad werden vor dem Kopieren solche überzähligen Verknüpfungen am
|
||||
exklusiven Ziel entfernt und aus dem Quellsnapshot neu aufgebaut. Der native
|
||||
Pfad erzeugt vollständige Kopien atomar als neue Inodes und setzt anschließend
|
||||
die Hardlink-Aliase. Alte Zielsnapshots
|
||||
bleiben unverändert. Symlink-Verzeichnisse werden dabei nicht verfolgt.
|
||||
Note over Op,S: all writers stopped
|
||||
Op->>M: finalize --writers-stopped
|
||||
M->>S: create final snapshot F
|
||||
Note over M,T: same steps as a sync round
|
||||
M->>J: mark F done, R(n) removed
|
||||
M->>S: remove snapshot R(n)
|
||||
M->>T: remove snapshot R(n)
|
||||
V->>T: verify complete inventory against F
|
||||
M->>J: phase = ready-for-cutover
|
||||
|
||||
Die Prüfzuordnungen liegen in einem temporären bbolt-Index neben dem Journal;
|
||||
Schreibtransaktionen werden nach 4.096 Beobachtungen abgeschlossen. Der Index
|
||||
wird nach jedem Prüf-/Reparaturlauf verworfen und bei Bedarf neu aufgebaut.
|
||||
Er ist kein Wiederaufnahmejournal. Der native Basisindex unter
|
||||
`<journal>.native/base.bolt` bleibt dagegen erhalten. Dafür muss lokal ausreichend Platz
|
||||
vorhanden sein. Pfadtiefen über 128 Verzeichnisse werden derzeit abgewiesen.
|
||||
Nach einem harten Prozessabbruch während eines Indexlaufs können temporäre
|
||||
Indexverzeichnisse übrig bleiben; sie werden nicht als Checkpoints verwendet.
|
||||
Note over Op,T: clients switched to the target and checked
|
||||
Op->>M: cleanup
|
||||
M->>J: mark F removed
|
||||
M->>S: remove snapshot F
|
||||
M->>T: remove snapshot F
|
||||
```
|
||||
|
||||
Quell- und Zielsnapshots werden nicht automatisch gelöscht. Journal und Claim
|
||||
müssen für Wiederaufnahme erhalten bleiben. Ein unvollständiger Claim nach
|
||||
einem Absturz während seiner allerersten Anlage wird absichtlich nicht
|
||||
automatisch repariert; dafür ist eine Prüfung der ursprünglichen Job-ID nötig.
|
||||
## Transferred data
|
||||
|
||||
## Tests und Größenordnung
|
||||
- Snapshot names and contents; existing snapshots are transferred in
|
||||
chronological order.
|
||||
- Numeric UID/GID, mode, POSIX ACLs including default ACLs.
|
||||
- Timestamps of every file, directory and symlink:
|
||||
|
||||
| Timestamp | preserved |
|
||||
| --- | --- |
|
||||
| mtime (last modification) | yes |
|
||||
| btime (creation) | yes |
|
||||
| atime (last access) | yes |
|
||||
| ctime (last status change) | yes¹ |
|
||||
|
||||
¹ To the nanosecond, but never lower than the mtime: if the source mtime is
|
||||
newer than its ctime (mtime set into the future), the target gets
|
||||
ctime = mtime.
|
||||
|
||||
No file system interface sets the ctime directly; Ceph 21.2.0 ignores
|
||||
`CEPH_SETATTR_CTIME`. The MDS does, however, take the ctime from the time
|
||||
stamp the client sends with each request, and libcephfs reads that stamp
|
||||
from `clock_gettime(CLOCK_REALTIME)`. The native backend replaces
|
||||
`clock_gettime` in its own process (symbol interposition, only in the
|
||||
calling thread and only for the duration of one libcephfs call; the Go
|
||||
runtime reads the clock through the vDSO and is not affected):
|
||||
|
||||
- Every modifying call runs with the time stamp 1970-01-01T00:00:01Z.
|
||||
- As the last change to an entry, the backend creates and removes the xattr
|
||||
`user.cephmig.ctime`, stamped with the source ctime. The MDS then sets
|
||||
ctime = max(stamp, mtime), also backwards. Setattr and cap flushes, in
|
||||
contrast, only move the ctime forward.
|
||||
- Directories are stamped after all changes to their children, hardlinks
|
||||
after linking and after removing surplus names.
|
||||
- The writing client sometimes caches a different ctime for directories.
|
||||
The verification before publication therefore reads the target through a
|
||||
freshly connected client. The writing client is closed first and the
|
||||
fresh client writes from then on. Closing returns all caps of the writer
|
||||
at once; otherwise the MDS recalls them entry by entry, which in the lab
|
||||
cost about five seconds per lookup for the files written last. The claim
|
||||
lock is held through a client of its own, so it survives the change.
|
||||
|
||||
This behaviour was measured in the lab and is not guaranteed by Ceph; the
|
||||
verification reports every deviation. The atime at the target subsequently
|
||||
changes through normal reads of the application.
|
||||
- User xattrs and other portable xattrs, including empty values and removals.
|
||||
- Hardlinks within the subvolume, symlinks and FIFOs.
|
||||
- Sparse file contents; the native path skips zero ranges or punches holes.
|
||||
The physical space usage is not guaranteed.
|
||||
- Directory quotas `ceph.quota.max_bytes` and `ceph.quota.max_files`, also at
|
||||
the data root.
|
||||
- Custom subvolume and snapshot metadata through the manager API.
|
||||
- Original and new snapshot creation times in the journal.
|
||||
|
||||
Symlinks are kept as link text, even if their target does not exist. The
|
||||
native path also preserves hardlinks to symlinks and FIFOs; for symlinks it
|
||||
links the inode through the public low-level interface, so that the link
|
||||
itself and not its referent is linked.
|
||||
Absolute links are not rewritten; at cutover, the application's mount path
|
||||
must match them. Hardlinks across the boundary of the transferred subvolume
|
||||
are not migrated as a shared link.
|
||||
|
||||
Cluster-internal layout, pool and other `ceph.*` attributes are not copied
|
||||
blindly; quotas are transferred separately. Pool and layout mappings,
|
||||
subvolume group quotas, pinning, authorizations, snapshot schedules, active
|
||||
clone jobs and other Ceph management state are not implemented.
|
||||
The migration transfers the snapshots listed by the subvolume API with their
|
||||
entire directory tree. CephFS supports directory snapshots in general, but
|
||||
the MDS refuses separate snapshots below a managed subvolume. In the Ceph
|
||||
21.2.0 lab, a snapshot of a plain directory succeeded, while the same attempt
|
||||
in a subvolume subdirectory failed with `EPERM`. Inherited snapshot views
|
||||
visible in subdirectories are part of the parent subvolume snapshot. The
|
||||
earlier warning about separate subdirectory snapshots was too broad for this
|
||||
managed subvolume model.
|
||||
See [MDS check of the subvolume boundary](https://github.com/ceph/ceph/blob/main/src/mds/Server.cc).
|
||||
Original inode numbers and native snapshot IDs are assigned anew.
|
||||
Encrypted, normalized, case-insensitive or earmarked subvolumes are rejected.
|
||||
|
||||
## Resumption and verification
|
||||
|
||||
The job keeps a JSON journal with mode 0600 that is replaced atomically and
|
||||
secured with fsync. It contains the configuration, the cluster FSIDs, the
|
||||
concrete subvolume data paths and per-snapshot intent and completion records.
|
||||
Recreating the same subvolume name with a different data UUID is rejected.
|
||||
|
||||
A local flock lock prevents concurrent access to the same journal. A
|
||||
persistent claim under `<target-filesystem>/.cephmig/claims/` with an
|
||||
exclusive file/CephFS lock protects the target even across different local
|
||||
journal paths. A missing or incomplete journal is never replaced by
|
||||
automatically adopting existing target data.
|
||||
|
||||
Each snapshot state is copied, verified including quotas, and only then
|
||||
created as a snapshot at the target. A target snapshot that was created but
|
||||
not yet confirmed in the journal is verified again against the immutable
|
||||
source on resumption. Replacement or loss of already completed snapshots is
|
||||
detected from the stored identity; snapshots the journal marks as `removed`
|
||||
are exempt.
|
||||
|
||||
The native data path uses a local bbolt index with source inode, inode
|
||||
version, size and target inode per path. It contains no file contents. The
|
||||
confirmed base is invalidated in the JSON journal before any change to the
|
||||
target and confirmed again only after successful verification and an fsync of
|
||||
the index. Clusters, data UUID paths and snapshot name must match. After an
|
||||
interruption, the open state is reconstructed fully and natively; a partially
|
||||
applied blockdiff must not count as a base. An already published but
|
||||
unconfirmed target snapshot is verified again. After SIGKILL, the release of
|
||||
old Ceph client sessions can delay the restart.
|
||||
|
||||
The index also contains the complete path inventory of the immutable source
|
||||
snapshot: files, directories, hardlink aliases and special files. It is
|
||||
marked complete only after it has been fully recorded. Pruning and the check
|
||||
for surplus target paths compare target paths with this local inventory and
|
||||
thus avoid another `stat` call for every source path. Incomplete or damaged
|
||||
inventories abort the run. Identical inode rows are not written to the index
|
||||
again during verification.
|
||||
|
||||
Immutable paths under `.snap` are read with `AT_STATX_DONT_SYNC` for `stat`
|
||||
and `readdirplus`, as in Ceph's own mirror. This avoids requesting metadata
|
||||
locks just to resynchronize snapshot inodes that cannot change anyway. Live
|
||||
target paths keep their normal synchronization semantics. Details and
|
||||
measurements are in [smallfiles-local.md](smallfiles-local.md).
|
||||
|
||||
For a full copy, the native verification compares all file contents. For
|
||||
later states, it checks copied files or the ranges reported by blockdiff.
|
||||
Unchanged bytes come from the previously verified base. The target tree must
|
||||
therefore belong exclusively to the copier for the entire job. Foreign
|
||||
changes to unchanged file ranges are not reliably detected this way.
|
||||
Metadata, quotas and hardlink topology are checked in every state. A full
|
||||
content comparison after the cutover is proposed in
|
||||
[verify-concept.md](verify-concept.md). A target
|
||||
snapshot created right after the verification is checked for metadata and
|
||||
links; the same immutable data is not read again.
|
||||
|
||||
In addition, the hardlink topology is verified in both directions: all source
|
||||
paths of the same inode must belong together at the target, and independent
|
||||
source files must not accidentally share an inode at the target. The copier
|
||||
creates full copies atomically as new inodes and then sets the hardlink
|
||||
aliases. Old target snapshots stay unchanged. Symlinked directories are not
|
||||
followed. The verification walks the tree in order and checks directories
|
||||
itself; all other entries are checked by up to `workers` goroutines.
|
||||
|
||||
The verification mappings live in a temporary bbolt index next to the
|
||||
journal; write transactions are committed after 4,096 observations. The index
|
||||
is discarded after every verification or repair run and rebuilt when needed.
|
||||
It is not a resumption journal. The native base index under
|
||||
`<journal>.native/base.bolt`, in contrast, is kept. Sufficient local disk
|
||||
space is required for it. Path depths beyond 128 directories are currently
|
||||
rejected. After a hard process abort during an index run, temporary index
|
||||
directories can remain; they are never used as checkpoints.
|
||||
|
||||
Journal and claim must be kept for resumption; `cleanup` deletes the claim
|
||||
only after the job is finished, and only if it holds the job's own ID. The
|
||||
lock is an advisory CephFS `flock`: it excludes other cephmig processes, but
|
||||
does not block any application. An incomplete claim after a
|
||||
crash during its very first creation is deliberately not repaired
|
||||
automatically; that requires checking the original job ID.
|
||||
|
||||
## Tests and scale
|
||||
|
||||
```sh
|
||||
make check
|
||||
go test -race ./...
|
||||
make dev-migration-test
|
||||
make dev-native-test
|
||||
```
|
||||
|
||||
Die Integrationstests erzeugen eigene Subvolumes und prüfen historische Stände,
|
||||
Änderungsnachlauf, Metadaten, entfernte Dateien, Kopierfehler und einen
|
||||
SIGKILL nach dem Anlegen eines Zielsnapshots, aber vor dem Journal-Commit.
|
||||
Er prüft auch den gespeicherten Hinweis auf neue Snapshot-Identitäten und das
|
||||
Auflösen zuvor vorhandener Hardlinks bei unveränderten Dateiinhalten.
|
||||
Bei Erfolg entfernt er ausschließlich seine eigenen Fixtures; bei Fehlern
|
||||
bleiben die ausgegebenen Testpfade zur Diagnose erhalten.
|
||||
The integration tests create their own subvolumes and check historical
|
||||
states, catching up with changes, metadata, removed files, copy errors and a
|
||||
SIGKILL after a target snapshot was created but before the journal commit.
|
||||
They also check the stored note about new snapshot identities, the
|
||||
resolution of previously existing hardlinks with unchanged file contents, the
|
||||
removal of older round snapshots during `sync` and the removal of all
|
||||
migration snapshots by `cleanup`. On success they remove only their own
|
||||
fixtures; on failure the reported test paths are kept for diagnosis.
|
||||
|
||||
Der native Test verwendet einen Kopierer ohne FUSE-Gerät, CephFS-Mounts und
|
||||
rsync. Ein separater FUSE-Anwendungsclient prüft unabhängig alle Dateiinhalte
|
||||
mit SHA-256 sowie Metadaten, Links und Snapshots. Er prüft eine 4-KiB-Änderung
|
||||
in einer 64-MiB-Datei bei gleicher mtime, Wachstum und Nullbereiche, Linkgruppen
|
||||
mit Trennung/Wiedervereinigung sowie Wechsel zwischen Verzeichnis und Symlink.
|
||||
Hardlinks auf nicht auflösbare Symlinks und FIFOs werden ebenfalls unabhängig
|
||||
anhand der Inodes verglichen, einschließlich späterer Trennung einer FIFO-Gruppe.
|
||||
Weitere Prüfungen betreffen Abbruch während der Kopie, SIGKILL unmittelbar nach
|
||||
Snapshot-Erzeugung, Wiederanlauf und idempotenten Abschluss. Währenddessen
|
||||
schreibt eine Anwendung fortlaufend in ein anderes Quell-Subvolume.
|
||||
The native test uses a copier without a FUSE device, CephFS mounts or rsync.
|
||||
A separate FUSE application client independently checks all file contents
|
||||
with SHA-256, as well as metadata, links and snapshots. It checks a 4 KiB
|
||||
change in a 64 MiB file with the same mtime, growth and zero ranges, link
|
||||
groups that are split and rejoined, and changes between directory and
|
||||
symlink. Hardlinks to unresolvable symlinks and FIFOs are also compared
|
||||
independently by inode, including a later split of a FIFO group. Further
|
||||
checks cover cancellation during the copy, SIGKILL right after snapshot
|
||||
creation, restart and idempotent completion. Meanwhile, an application keeps
|
||||
writing to another source subvolume.
|
||||
|
||||
Laborergebnis vom 05.11.2026 mit Ceph 21.2.0: nativer Integrationstest und
|
||||
rsync-Regression erfolgreich; Go-Tests einschließlich Race Detector und
|
||||
`go vet` für den Ceph-Build erfolgreich. Der native Test schloss fünf Stände
|
||||
mit `ready-for-cutover` ab und prüfte sie zusätzlich über den Anwendungsclient.
|
||||
Bei der Änderung von 4 KiB in der 64-MiB-Datei wurden für diese Datei 4 KiB,
|
||||
für den gesamten zweiten Stand einschließlich weiterer geänderter Dateien
|
||||
4.128 Nutzdatenbytes geschrieben. Im unveränderten finalen Stand waren es
|
||||
0 Nutzdatenbytes. Das ist ein Funktionsnachweis, kein Durchsatzbenchmark.
|
||||
Latest lab result, 2026-12-03 with Ceph 21.2.0 and code state `6dcb7b6`:
|
||||
the Go tests including the race detector for the Ceph build, `make
|
||||
dev-smoke`, `make dev-native-test` and `make dev-smallfiles-test` passed
|
||||
(results in [smallfiles-local.md](smallfiles-local.md)).
|
||||
|
||||
Der lesende Identitätsvergleich für bereits vorhandene Laborsnapshots lautet:
|
||||
Lab result of 2026-11-05 with Ceph 21.2.0: native integration test and the
|
||||
regression test of the since removed rsync backend passed; Go tests
|
||||
including the race detector and `go vet` for the Ceph build passed. The
|
||||
native test completed five states with
|
||||
`ready-for-cutover` and additionally checked them through the application
|
||||
client. For the 4 KiB change in the 64 MiB file, 4 KiB were written for this
|
||||
file and 4,128 payload bytes for the whole second state including other
|
||||
changed files. In the unchanged final state, 0 payload bytes were written.
|
||||
This is a functional proof, not a throughput benchmark.
|
||||
|
||||
The read-only identity comparison for existing lab snapshots is:
|
||||
|
||||
```sh
|
||||
python3 /lab/snapshot-identity.py \
|
||||
--config /absolute/lab-config.json --snapshot existing-snapshot
|
||||
```
|
||||
|
||||
Go liest Verzeichnisquotas in Batches und hält keine Liste aller Dateien.
|
||||
Das gilt **nicht** als Speicherobergrenze des externen rsync-Prozesses:
|
||||
große Einzelverzeichnisse und Hardlinkgruppen können dort erheblichen
|
||||
Speicher benötigen. Jeder Stand verursacht vollständige Scans und
|
||||
Checksum-Lesevorgänge. Geänderte große Dateien können bei neuen Snapshots
|
||||
erheblichen zusätzlichen Zielplatz benötigen.
|
||||
Changed large files can need considerable additional target space for new
|
||||
snapshots.
|
||||
|
||||
Im nativen Pfad sind Datei-Worker, Datenpuffer und Verzeichnisiteration begrenzt;
|
||||
Kopier- und Vergleichspuffer sind höchstens 4 MiB groß und werden für kleine
|
||||
Dateien bzw. kurze Prüfbereiche entsprechend verkleinert. Identische Besitzer,
|
||||
Rechte und mtime lösen keinen erneuten `setattr`-Aufruf aus; eine unmittelbar
|
||||
zuvor gelesene Zielstatistik wird bei der Metadatenprüfung wiederverwendet.
|
||||
Pfad-/Hardlink-Zuordnungen liegen auf lokalem Datenträger. Snapdiff und Blockdiff
|
||||
vermeiden wiederholte Vollübertragung und vollständiges Lesen unveränderter
|
||||
Dateiinhalte. Die Implementierung scannt aber weiterhin alle Metadaten,
|
||||
einschließlich vollständiger Topologie- und Quotaprüfung. Umbenannte Dateien
|
||||
können erneut vollständig kopiert werden. Einzeltransaktionen des nativen
|
||||
Index sind noch nicht auf 200 Millionen Pfade optimiert.
|
||||
|
||||
200 TB und mehr als 200 Millionen Dateien sind damit noch nicht nachgewiesen.
|
||||
Für diese Freigabe fehlen insbesondere Scans vermeidende Änderungsplanung,
|
||||
belastbare Speicher-/Laufzeitmessungen, ein Kapazitätsmodell für historische
|
||||
Versionen sowie ein automatisierter Client-Cutover. Eine feste maximale
|
||||
Schreibstopplänge wird nicht zugesichert. Native API-Aufrufe sind blockierend;
|
||||
Abbruch wird zwischen Aufrufen geprüft und wartet auf bereits laufende I/O.
|
||||
File workers, data buffers and directory iteration are
|
||||
bounded; copy and compare buffers are at most 4 MiB and shrink for small
|
||||
files and short verification ranges. Unchanged owner, mode and timestamps do
|
||||
not trigger another `setattr` call; a target stat read just before is reused
|
||||
for the metadata check. Path and hardlink mappings live on local disk.
|
||||
Snapdiff and blockdiff avoid repeated full transfers and full reads of
|
||||
unchanged file contents. Every round, `finalize` included, still scans all
|
||||
metadata, including the full topology and quota check, so the write stop
|
||||
scales with the total number of entries. Renamed
|
||||
files may be copied again in full. Single transactions of the native index are not yet optimized
|
||||
for 200 million paths.
|
||||
|
||||
200 TB and more than 200 million files are therefore not yet proven. What is
|
||||
missing for that release in particular: a final round that avoids full scans,
|
||||
reliable memory and runtime measurements, a capacity model for historical
|
||||
versions and an automated client cutover. A fixed maximum write-stop duration
|
||||
is not guaranteed. Native API calls block; cancellation is checked between
|
||||
calls and waits for I/O already in progress.
|
||||
+77
-73
@@ -1,64 +1,68 @@
|
||||
# Lokaler Millionentest mit Snapshots
|
||||
# Local one-million-file test with snapshots
|
||||
|
||||
## Ergebnis vom 06./07.11.2026
|
||||
## Result of 2026-11-06/07
|
||||
|
||||
**PASS**, abgeschlossen am 07.11.2026 um 01:58:57 Uhr MEZ. Der Job erreichte
|
||||
`ready-for-cutover`. Die unabhängige Prüfung bestätigte den aktuellen Zielstand
|
||||
und vier Snapshots: insgesamt **5.000.500 reguläre Dateipfade**, zusätzlich
|
||||
Symlinks, Verzeichnisse, Besitzer, Rechte, ACLs, xattrs, Quotas und Snapshot-
|
||||
Benutzermetadaten. Ein anderes Subvolume blieb mit 14.640 bestätigten
|
||||
Schreibvorgängen beschreibbar.
|
||||
**PASS**, completed on 2026-11-07 at 01:58:57 CET. The job reached
|
||||
`ready-for-cutover`. The independent check confirmed the current target state
|
||||
and four snapshots: a total of **5,000,500 regular file paths**, plus
|
||||
symlinks, directories, owners, modes, ACLs, xattrs, quotas and snapshot user
|
||||
metadata. Another subvolume stayed writable with 14,640 confirmed writes.
|
||||
|
||||
| Phase einschließlich interner Prüfungen | Dauer | Geschriebene Nutzdaten | MDS-Anfragen, beide Cluster |
|
||||
| Phase including internal checks | Duration | Payload written | MDS requests, both clusters |
|
||||
|---|---:|---:|---:|
|
||||
| Erstabgleich, bestehender und neuer Snapshot | 5 h 01 min 11 s | 128.000.000 Byte | 40.451.000 |
|
||||
| Änderungsabgleich | 1 h 12 min 13 s | 6.400.128 Byte | 16.875.108 |
|
||||
| Finalisierung, unveränderte Quelle | 1 h 20 min 24 s | 0 Byte | 19.259.091 |
|
||||
| Initial round, existing and new snapshot | 5 h 01 min 11 s | 128,000,000 bytes | 40,451,000 |
|
||||
| Catch-up round | 1 h 12 min 13 s | 6,400,128 bytes | 16,875,108 |
|
||||
| Finalization, unchanged source | 1 h 20 min 24 s | 0 bytes | 19,259,091 |
|
||||
|
||||
Die erste vollständige Kopie einschließlich abschließender Inventar- und
|
||||
Metadatenarbeit dauerte rund 1 h 40 min; die erste vollständige Prüfung des
|
||||
Live-Ziels danach etwa 1 h 21 min. Das gesamte Testszenario einschließlich
|
||||
Datenerzeugung, Änderungen und unabhängiger Prüfung dauerte 9 h 04 min 37 s.
|
||||
Maximal erfasster RSS des Go-Prozesses über die drei Phasen: 646,2 MiB.
|
||||
Die Rohmesswerte stehen in [million-local.json](million-local.json).
|
||||
The first full copy including the final inventory and metadata work took
|
||||
about 1 h 40 min; the first full verification of the live target afterwards
|
||||
about 1 h 21 min. The whole test scenario including data generation, changes
|
||||
and independent verification took 9 h 04 min 37 s. Maximum sampled RSS of
|
||||
the Go process across the three phases: 646.2 MiB. The raw measurements are
|
||||
in [million-local.json](million-local.json).
|
||||
|
||||
Die vollständigen Metadatendurchläufe bleiben teuer: Selbst die Finalisierung
|
||||
ohne Nutzdatenänderungen verursachte rund 19,3 Millionen MDS-Anfragen. Der
|
||||
Prüfpfad ist derzeit seriell. Ceph meldete während des Laufs außerdem langsame
|
||||
BlueStore-Operationen und einen hohen BlueFS-Anteil auf den kleinen Test-OSDs.
|
||||
Die genauen Anteile von CPU und Datenträgerlatenz wurden nicht isoliert
|
||||
profiliert. Es gab keine Prüfung der produktiven 2×25-Gbit-Verbindung.
|
||||
Der Lauf belegt die geprüfte Datenkorrektheit im Labor; ein kurzer finaler
|
||||
Schreibstopp für 200 Millionen Dateien ist damit noch nicht nachgewiesen.
|
||||
Die Finalisierungsdauer enthält keinen Anwendungsneustart oder Client-Remount.
|
||||
The full metadata passes remain expensive: even the finalization without any
|
||||
payload changes caused about 19.3 million MDS requests. This run predates
|
||||
two later changes: verification now checks entries in parallel, and the
|
||||
writing client is replaced before verification, which removed long waits for
|
||||
recalled caps (see [migration.md](migration.md)). The durations above are
|
||||
therefore not those of the current code; a new run is pending. The single OSD per cluster of the local setup limits these tests, not the copier. During an aborted 100,000-file run in December 2026, writing one small file took about 50 ms, mostly OSD write latency (`op_w` about 32 ms) plus MDS journal latency (about 20 ms). Each cluster has only one OSD, both share one host disk (encrypted with LUKS), and they run without replication. More workers therefore hardly shorten the runs. The durations measured here say little about a production cluster with many OSDs.
|
||||
During the run, Ceph also reported slow BlueStore
|
||||
operations and a high BlueFS share on the small test OSDs. The exact shares
|
||||
of CPU and disk latency were not profiled separately. The production
|
||||
2×25 Gbit link was not tested. The run proves data correctness in the lab;
|
||||
a short final write stop for 200 million files is not yet proven. The
|
||||
finalization time does not include an application restart or client
|
||||
remount.
|
||||
|
||||
Die automatische Bereinigung entfernte ausschließlich das Projekt
|
||||
`cephmig-million` samt Testvolumes am 07.11.2026 gegen 02:03 Uhr MEZ.
|
||||
Die Berichte blieben erhalten; danach waren rund 84 GiB Hostspeicher frei.
|
||||
The automatic cleanup removed only the project `cephmig-million` and its
|
||||
test volumes on 2026-11-07 at about 02:03 CET. The reports were kept;
|
||||
afterwards about 84 GiB of host disk were free.
|
||||
|
||||
## Testaufbau
|
||||
## Test setup
|
||||
|
||||
Der Test legt 1.000.000 Dateien mit je 128 Byte reproduzierbarem Inhalt an,
|
||||
verteilt auf 1.000 Verzeichnisse. Dazu kommen 100 Hardlink-Namen und 100 Symlinks,
|
||||
numerische Besitzer, POSIX-Zugriffs-/Default-ACLs, Benutzer-xattrs und Quotas.
|
||||
The test creates 1,000,000 files of 128 bytes of reproducible content each,
|
||||
spread over 1,000 directories. In addition there are 100 hardlink names and
|
||||
100 symlinks, numeric owners, POSIX access and default ACLs, user xattrs and
|
||||
quotas.
|
||||
|
||||
Ein vor der Migration angelegter Snapshot enthält den ursprünglichen Stand.
|
||||
Nach dem Erstabgleich ändert der Anwendungsclient jeweils 1 % der Inhalte,
|
||||
Dateinamen, Rechte/xattrs, löscht 1 % der Dateien und legt 1 % neue Dateien an.
|
||||
Inhaltsänderungen behalten die ursprüngliche mtime. Danach folgen Änderungsabgleich
|
||||
und Finalisierung mit gestopptem Testschreiber. Ein Schreiber in einem anderen
|
||||
Subvolume läuft währenddessen weiter und bestätigt seine Schreibvorgänge mit fsync.
|
||||
A snapshot taken before the migration holds the original state. After the
|
||||
initial round, the application client changes 1 % each of the contents, file
|
||||
names and modes/xattrs, deletes 1 % of the files and creates 1 % new files.
|
||||
Content changes keep the original mtime. Then follow the catch-up round and
|
||||
the finalization with the test writer stopped. Meanwhile, a writer in another
|
||||
subvolume keeps running and confirms its writes with fsync.
|
||||
|
||||
Nach der Migration liest ein separater Python-libcephfs-Client den aktuellen
|
||||
Zielstand und vier Ziel-Snapshots vollständig. Erwartete Inhalte und Metadaten
|
||||
werden aus dem Testmodell berechnet. SQLite prüft auf Platte die bijektive
|
||||
Zuordnung der Inodes zu Hardlink-Gruppen. Insgesamt sind 5.000.500 reguläre
|
||||
Dateipfade sowie Symlinks, Verzeichnisse, ACLs, xattrs, Quotas und Snapshot-
|
||||
Benutzermetadaten zu prüfen. Die Go-Migration prüft zusätzlich intern.
|
||||
Ceph-interne Snapshot-IDs und ursprüngliche Erstellungszeitpunkte werden nicht
|
||||
erhalten; diese bekannte Einschränkung bleibt bestehen.
|
||||
After the migration, a separate Python libcephfs client reads the current
|
||||
target state and four target snapshots in full. Expected contents and
|
||||
metadata are computed from the test model. SQLite checks on disk that inodes
|
||||
map bijectively to hardlink groups. In total, 5,000,500 regular file paths
|
||||
as well as symlinks, directories, ACLs, xattrs, quotas and snapshot user
|
||||
metadata are checked. The Go migration additionally verifies internally.
|
||||
Ceph-internal snapshot IDs and original creation times are not preserved;
|
||||
this known limitation remains.
|
||||
|
||||
## Start und Fortschritt
|
||||
## Start and progress
|
||||
|
||||
```sh
|
||||
make dev-million-start
|
||||
@@ -66,35 +70,35 @@ make dev-million-status
|
||||
docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml logs -f benchmark
|
||||
```
|
||||
|
||||
Das getrennte Compose-Projekt verwendet zwei dünn belegte 24-GiB-OSDs und
|
||||
höchstens 10 GiB Container-RAM. Für den ersten Start sind 68 GiB freier
|
||||
Hostspeicher vorgesehen: maximal 48 GiB OSDs plus 20 GiB Reserve. Die laufende
|
||||
Prüfung stoppt weitere Schreibvorgänge bei weniger als 20 GiB Hostreserve,
|
||||
3 GiB freiem Host-RAM oder 3 GiB freiem Ceph-Speicher je Cluster.
|
||||
Images, bestehende Testcluster und deren Speicher kommen hinzu. Es werden keine
|
||||
Kernel- oder FUSE-Mounts benötigt. Die Daemons laufen mit einem MDS-Cachelimit
|
||||
von jeweils 768 MiB. Die Laufzeit hängt stark vom Datenträger und den anderen
|
||||
Prozessen auf dem Host ab.
|
||||
The separate Compose project uses two thinly provisioned 24 GiB OSDs and at
|
||||
most 10 GiB of container RAM. The first start requires 68 GiB of free host
|
||||
disk: at most 48 GiB for the OSDs plus a 20 GiB reserve. The running check
|
||||
stops further writes when less than 20 GiB of host reserve, 3 GiB of free
|
||||
host RAM or 3 GiB of free Ceph capacity per cluster remain. Images, existing
|
||||
test clusters and their storage come on top. No kernel or FUSE mounts are
|
||||
needed. The daemons run with an MDS cache limit of 768 MiB each. The runtime
|
||||
depends heavily on the disk and the other processes on the host.
|
||||
|
||||
Der Treiber läuft als eigener Container weiter. Status, Protokolle, MDS-Zähler,
|
||||
Laufzeiten und abgetasteter maximaler RSS des Go-Prozesses liegen unter
|
||||
`.dev/million/main/`. Nur `result: PASS` bestätigt die vollständige Prüfung.
|
||||
Erzeugung und abgeschlossene Prüfansichten haben Checkpoints; ein unterbrochener
|
||||
Go-Abgleich verwendet das bestehende Migrationsjournal. Eine unterbrochene
|
||||
Phase zählt nicht als verwertbare Laufzeitmessung. Die Testerzeugung läuft mit
|
||||
acht Threads, der Kopierer mit acht Workern, die unabhängige Prüfung mit 16 Threads.
|
||||
Queues und Datenpuffer sind begrenzt; Index und Inode-Zuordnung liegen auf Platte.
|
||||
The driver keeps running as a container of its own. Status, logs, MDS
|
||||
counters, durations and the sampled maximum RSS of the Go process are written
|
||||
to `.dev/million/main/`. Only `result: PASS` confirms the complete check.
|
||||
Generation and completed verification views have checkpoints; an interrupted
|
||||
Go round uses the existing migration journal. An interrupted phase does not
|
||||
count as a usable runtime measurement. Test generation runs with eight
|
||||
threads, the copier with eight workers (`WORKERS=` changes that), the independent check with 16
|
||||
threads. Queues and data buffers are bounded; index and inode mapping live on
|
||||
disk.
|
||||
|
||||
## Bereinigung
|
||||
## Cleanup
|
||||
|
||||
Nach erfolgreicher Prüfung Messwerte nach `docs/million-local.json` sichern
|
||||
und ausschließlich dieses Testprojekt entfernen. Der Befehl verweigert die
|
||||
Bereinigung ohne `PASS` und erfolgreichen Container-Exit:
|
||||
After a successful check, save the measurements to `docs/million-local.json`
|
||||
and remove only this test project. The command refuses to clean up without
|
||||
`PASS` and a successful container exit:
|
||||
|
||||
```sh
|
||||
make dev-million-finish
|
||||
```
|
||||
|
||||
Die Berichte auf dem Host bleiben erhalten. Das Projekt `cephmig-dev` ist separat.
|
||||
Ein lokaler Lauf ist kein Leistungsnachweis für 200 TB oder 200 Millionen Dateien.
|
||||
MDS-Anfragen sind keine Messung physischer Datenträger-IOPS.
|
||||
The reports on the host are kept. The project `cephmig-dev` is separate. A
|
||||
local run is no performance proof for 200 TB or 200 million files. MDS
|
||||
requests are not a measurement of physical disk IOPS.
|
||||
+183
-86
@@ -1,107 +1,204 @@
|
||||
# Direkter RADOS-Transfer eines einzelnen Subvolumes
|
||||
# Direct RADOS transfer of a single subvolume
|
||||
|
||||
Geprüft am 05.11.2026 für die Anforderung: genau ein CephFS-Subvolume zwischen
|
||||
unabhängigen Clustern migrieren, während andere Subvolumes weiterlaufen.
|
||||
Native Snapshot-IDs und Geburtszeitpunkte dürfen dabei abweichen.
|
||||
Evaluated on 2026-11-05 against the requirement: migrate exactly one CephFS
|
||||
subvolume between independent clusters while other subvolumes keep running.
|
||||
Native snapshot IDs and birth times may differ.
|
||||
|
||||
## Ergebnis
|
||||
## Result
|
||||
|
||||
Ein roher Import von RADOS-Daten- und Metadatenobjekten ist unter diesen
|
||||
Bedingungen kein geprüfter Ersatz für den vorhandenen Transport. Der aktuelle
|
||||
Code wurde deshalb nicht auf einen solchen Import umgestellt.
|
||||
Under these conditions, a raw import of RADOS data and metadata objects is
|
||||
not a verified replacement for the existing transport. The code was
|
||||
therefore not switched to such an import.
|
||||
|
||||
RADOS kann Objektinhalt, xattrs und OMAP lesen und schreiben. Damit ist jedoch
|
||||
noch kein separat einhängbares CephFS-Subvolume übertragen:
|
||||
RADOS can read and write object contents, xattrs and OMAP. That alone does
|
||||
not transfer a separately mountable CephFS subvolume:
|
||||
|
||||
- Der MDS-Metadatenpool enthält die Hierarchie und dateisystemweite Zustände,
|
||||
etwa Journale, Inode-/Snapshot-Verwaltung und Clientsitzungen.
|
||||
- Ein Subvolume hat keinen unabhängigen MDS-Metadatenpool. Ein separater
|
||||
Daten-Namespace würde nur bei der Zuordnung von Datenobjekten helfen.
|
||||
- Dateilayouts und Metadaten beziehen sich auf Inodes, Pools und Snapshots der
|
||||
Quelle. Sie dürfen nicht unverändert in ein laufendes, anders aufgebautes
|
||||
Ziel-Dateisystem importiert werden.
|
||||
- Der untersuchte RADOS-Pool-Export schreibt ausdrücklich nur HEAD-Objekte.
|
||||
Historische RADOS-Snapshot-Versionen sind damit nicht als vollständige
|
||||
CephFS-Snapshot-Historie migriert.
|
||||
- Die dokumentierte Pool-Migration beschreibt Migration zwischen Pools
|
||||
innerhalb desselben Clusters. Sie ist keine Subvolume-Replikation zwischen
|
||||
unabhängigen Clustern.
|
||||
- The MDS metadata pool holds the hierarchy and file-system-wide state, such
|
||||
as journals, inode and snapshot management and client sessions.
|
||||
- A subvolume has no metadata pool of its own. A separate data namespace
|
||||
would only help to map data objects.
|
||||
- File layouts and metadata refer to the inodes, pools and snapshots of the
|
||||
source. They must not be imported unchanged into a running target file
|
||||
system with a different structure.
|
||||
- The examined RADOS pool export explicitly writes only HEAD objects.
|
||||
Historical RADOS snapshot versions are therefore not migrated as a complete
|
||||
CephFS snapshot history.
|
||||
- The documented pool migration covers migration between pools within the
|
||||
same cluster. It is not subvolume replication between independent
|
||||
clusters.
|
||||
|
||||
Die Schlussfolgerung folgt aus diesen Verwaltungs- und Konsistenzabhängigkeiten:
|
||||
Ein eigener Raw-Kopierer müsste zusätzlich eine konsistente Teilmenge der
|
||||
CephFS-Metadaten exportieren, auf die Zielidentitäten abbilden und mit dessen
|
||||
laufendem MDS koordinieren. Ein gewöhnlicher Objektkopierer leistet das nicht.
|
||||
Auch ein Objekttransfer muss die erforderlichen Nutzdaten zum Ziel bewegen.
|
||||
The conclusion follows from these management and consistency dependencies:
|
||||
a raw copier of its own would additionally have to export a consistent
|
||||
subset of the CephFS metadata, map it to the target identities and
|
||||
coordinate with the target's running MDS. An ordinary object copier does not
|
||||
do that. An object transfer, too, has to move the required payload to the
|
||||
target.
|
||||
|
||||
## Geprüfte native Alternative
|
||||
## Verified native alternative
|
||||
|
||||
Der Go-Transport `backend: native` verwendet libcephfs ohne rsync und ohne
|
||||
Kernel-/FUSE-Mount. Metadatenoperationen erfolgen über den Ziel-MDS;
|
||||
Daten-I/O übernimmt der native Ceph-Client direkt gegen RADOS. Ein roher Import
|
||||
des gemeinsamen MDS-Metadatenpools ist weiterhin nicht Bestandteil der Migration.
|
||||
The Go transport uses libcephfs without rsync and without a kernel or FUSE
|
||||
mount. Metadata operations go through the target MDS; data
|
||||
I/O is handled by the native Ceph client directly against RADOS. A raw import
|
||||
of the shared MDS metadata pool remains outside the migration.
|
||||
|
||||
In der tatsächlich laufenden Bibliothek des Labors wurden folgende Symbole
|
||||
geprüft:
|
||||
The following symbols were checked in the library actually running in the
|
||||
lab:
|
||||
|
||||
| Schnittstelle | Vorhanden |
|
||||
| --- | --- |
|
||||
| ceph_open_snapdiff | ja |
|
||||
| ceph_open_snapdiff2 | nein |
|
||||
| ceph_readdir_snapdiff2 | nein |
|
||||
| ceph_file_blockdiff_init | ja |
|
||||
| ceph_file_blockdiff | ja |
|
||||
| ceph_file_blockdiff_finish | ja |
|
||||
| Interface | Ceph 21.2.0 (lab) | Ceph `main` (2026-12-03) |
|
||||
| --- | --- | --- |
|
||||
| ceph_open_snapdiff | yes | yes |
|
||||
| ceph_open_snapdiff2 | no | yes, unreleased |
|
||||
| ceph_readdir_snapdiff2 | no | yes, unreleased |
|
||||
| ceph_close_snapdiff2 | no | yes, unreleased |
|
||||
| ceph_file_blockdiff_init | yes | yes |
|
||||
| ceph_file_blockdiff | yes | yes |
|
||||
| ceph_file_blockdiff_finish | yes | yes |
|
||||
|
||||
Die installierte Ceph-21.2.0-Konfiguration kennt
|
||||
`cephfs_mirror_blockdiff_min_file_size` mit Standardwert 16 MiB.
|
||||
### snapdiff2: available in Ceph `main` only
|
||||
|
||||
Implementierter Ablauf:
|
||||
As of 2026-12-03, the snapdiff2 interface exists in the development branch
|
||||
`main` of Ceph, but in no release: the v21.2.0 header does not declare it,
|
||||
and the lab library does not export it. cephmig does not use it; nothing is
|
||||
built until a release contains it.
|
||||
|
||||
1. Initialer nativer Transfer des Snapshotstands.
|
||||
2. Snapdiff zum Ermitteln geänderter Verzeichniseinträge.
|
||||
3. Blockdiff für geeignete geänderte Dateien; notwendige Datenbereiche übertragen.
|
||||
4. Hardlink-Zuordnungen, ACLs, xattrs, Quotas und Journal weiterhin explizit verwalten.
|
||||
5. Gezielte Verifikation der Änderungen und ein finaler Abgleich beim Schreibstopp.
|
||||
What `main` contains, read from the source code:
|
||||
|
||||
Der Backendpfad liegt in `internal/migration/native_*.go`, die schmale CGO-Anbindung
|
||||
an öffentliche Ceph-Schnittstellen in `internal/cephfsnative`. Aktivierung:
|
||||
`go build -tags ceph` mit CGO, C-Compiler und passenden libcephfs-Headern.
|
||||
`make dev-native-test` baut diese Abhängigkeiten im Container und prüft den
|
||||
Transport zwischen den unabhängigen Laborclustern.
|
||||
- `ceph_open_snapdiff2(cmount, root_path, rel_path, snap1, snap2, diff_mask, &out)`,
|
||||
`ceph_readdir_snapdiff2` and `ceph_close_snapdiff2`, with an opaque handle
|
||||
`struct ceph_snapdiff_info2`. The entries have the same type as in v1
|
||||
(`ceph_snapdiff_entry_t`: directory entry and snapshot ID; removed entries
|
||||
carry the former snapshot ID).
|
||||
- `diff_mask` selects which file metadata changes count as a difference:
|
||||
`CEPH_SNAPDIFF_MODE`, `_UID`, `_GID`, `_SIZE`, `_NLINK`, `_MTIME`, `_ATIME`,
|
||||
`_CTIME`, `_BTIME`.
|
||||
- libcephfs only passes the mask through. It is a field `mask` of the MDS
|
||||
request `CEPH_MDS_OP_READDIR_SNAPDIFF` (`ceph_mds_request_args.snapdiff`),
|
||||
so it is most likely evaluated by the MDS. The MDS handler itself was not
|
||||
read; this point is unconfirmed.
|
||||
- Sources: [libcephfs.h](https://github.com/ceph/ceph/blob/main/src/include/cephfs/libcephfs.h),
|
||||
[libcephfs.cc](https://github.com/ceph/ceph/blob/main/src/libcephfs.cc),
|
||||
[ceph_fs.h](https://github.com/ceph/ceph/blob/main/src/include/ceph_fs.h).
|
||||
|
||||
Snapdiff markiert geänderte Inodes; zusätzlich verhindert der Vergleich der
|
||||
Ceph-Inode-Version, dass Datenänderungen mit gleicher Größe und mtime entgehen.
|
||||
Blockdiff wird ab 16 MiB verwendet, sofern eine bestätigte Basis mit passenden
|
||||
Quell-/Ziel-Inodes vorliegt. Bei nicht verfügbaren Diff-Schnittstellen wird
|
||||
nativ vollständig rekonstruiert. Es gibt keinen stillen rsync-Fallback.
|
||||
Consequences for cephmig:
|
||||
|
||||
Die Implementierung scannt derzeit trotzdem alle Metadaten und prüft die
|
||||
Hardlink-Topologie jedes Standes vollständig. Snapdiff ersetzt diese Scans noch
|
||||
nicht. Datenprüfung liest beim ersten Stand alle Bytes, bei bestätigten
|
||||
Folgeständen nur kopierte Bereiche. Unveränderte Bereiche werden aus der zuvor
|
||||
verifizierten Basis übernommen. Das Ziel muss exklusiv dem Migrationsjob gehören;
|
||||
fremde Änderungen an unveränderten Bereichen werden damit nicht umfassend erkannt.
|
||||
Ein Index auf lokalem Datenträger bindet die Basis an Cluster, Datenpfade und
|
||||
Journal. Vor jeder Änderung wird ihre Gültigkeit im Journal entzogen. Ein Abbruch
|
||||
erzwingt im nächsten Prozess eine vollständige Rekonstruktion des offenen Standes.
|
||||
- Snapdiff runs against the **source** cluster. A newer libcephfs alone is
|
||||
not enough; the source MDS must run a release that evaluates the mask.
|
||||
An older MDS presumably ignores the field and behaves like v1.
|
||||
- With `CEPH_SNAPDIFF_CTIME`, snapdiff2 should report the changes v1 missed
|
||||
in the lab (chmod, xattr changes, writes through a hardlink alias,
|
||||
overwrites with a reset mtime), because all of them change the ctime.
|
||||
- It compares the two snapshots in the MDS, so unlike the removed rctime
|
||||
shortcut (see [metadata scan](migration.md#metadata-scan)) it depends
|
||||
neither on delayed rctime propagation nor on client clocks. After a lab
|
||||
proof, it could shorten rounds and possibly `finalize`.
|
||||
- Open: v1 reported every directory, including unchanged ones. The sources
|
||||
do not say whether snapdiff2 behaves differently; without that, it cannot
|
||||
be used to skip subtrees.
|
||||
|
||||
Ein Laufzeit- oder Durchsatznachweis für 200 TB / 200 Millionen Dateien fehlt.
|
||||
Auch nach einem Abbruch kann die vollständige Rekonstruktion entsprechend lange
|
||||
dauern. Die Zahl der durch die Anwendung geänderten Bytes ist keine feste
|
||||
Obergrenze für die vom OSD gemeldeten geänderten Bereiche.
|
||||
Once a release contains snapdiff2, the next step is a lab test with that
|
||||
release: repeat the snapdiff test cases (chmod, xattr change, alias write,
|
||||
overwrite with reset mtime, untouched subtrees) and check which entries are
|
||||
reported. The copier would then detect the symbol at runtime and fall back
|
||||
to the current path without it.
|
||||
|
||||
Das fertige cephfs-mirror verwendet native Replikation, unterstützt laut
|
||||
Dokumentation aber keine Erhaltung gemeinsamer Hardlink-Inodes. Es würde
|
||||
Hardlink-Dateien als getrennte Dateien synchronisieren. Deshalb wäre ein
|
||||
ungeprüfter Wechsel auf cephfs-mirror kein Ersatz für die vereinbarten
|
||||
Link-Anforderungen.
|
||||
The installed Ceph 21.2.0 configuration knows
|
||||
`cephfs_mirror_blockdiff_min_file_size` with a default of 16 MiB.
|
||||
|
||||
## Primärquellen
|
||||
Implemented workflow:
|
||||
|
||||
- [MDS-Metadatenpool und Journale](https://docs.ceph.com/en/latest/cephfs/mds-journaling/)
|
||||
- [CephFS-Architektur und direkter RADOS-Datenzugriff](https://docs.ceph.com/en/latest/cephfs/index.html)
|
||||
- [PoolDump: Export nur des HEAD-Zustands](https://github.com/ceph/ceph/blob/main/src/tools/rados/PoolDump.cc)
|
||||
- [Pool-Migration innerhalb desselben Clusters](https://docs.ceph.com/en/latest/dev/pool-migration-design/)
|
||||
- [libcephfs: Snapdiff und Blockdiff](https://github.com/ceph/ceph/blob/main/src/include/cephfs/libcephfs.h)
|
||||
- [CephFS-Mirroring: Blockdiff und Hardlink-Grenzen](https://docs.ceph.com/en/latest/cephfs/cephfs-mirroring/)
|
||||
1. Initial native transfer of the snapshot state.
|
||||
2. Snapdiff to find changed directory entries.
|
||||
3. Blockdiff for suitable changed files; transfer of the required data
|
||||
ranges.
|
||||
4. Hardlink mappings, ACLs, xattrs, quotas and the journal are still managed
|
||||
explicitly.
|
||||
5. Targeted verification of the changes and a final round at the write stop.
|
||||
|
||||
The backend lives in `internal/migration/native_*.go`, the thin CGO binding
|
||||
to public Ceph interfaces in `internal/cephfsnative`. Activation:
|
||||
`go build -tags ceph` with CGO, a C compiler and matching libcephfs headers.
|
||||
`make dev-native-test` builds these dependencies in a container and checks
|
||||
the transport between the independent lab clusters.
|
||||
|
||||
### Why a C binding and not a Go library
|
||||
|
||||
No CephFS client is written in pure Go. Every Go route ends in the C library
|
||||
libcephfs or in a kernel mount:
|
||||
|
||||
- **go-ceph** (`github.com/ceph/go-ceph`) is itself a CGO wrapper around
|
||||
libcephfs and librados. It would keep CGO, `-lcephfs` and the build
|
||||
dependency, and add a layer between the copier and the library.
|
||||
- **A CephFS client in Go** would have to implement msgr2, cephx, the MDS
|
||||
protocol with its capability handling and direct object I/O against the
|
||||
OSDs. That is a large, error-prone project; the cap handling alone decides
|
||||
whether verification waits seconds per entry (see the client replacement
|
||||
in [migration.md](migration.md)).
|
||||
- **A kernel mount and the Go standard library** was the former rsync
|
||||
backend. It cannot do what the copier needs (list below).
|
||||
|
||||
What the copier uses from libcephfs and gets nowhere else:
|
||||
|
||||
- `ceph_open_snapdiff`/`ceph_readdir_snapdiff`: changed directory entries
|
||||
between two snapshots.
|
||||
- `ceph_file_blockdiff_*`: changed data ranges of one file between two
|
||||
snapshots.
|
||||
- `ceph_setattrx` with the birth time; POSIX interfaces cannot set btime.
|
||||
- `ceph_ll_walk`/`ceph_ll_link`: inode-level operations for hardlinks.
|
||||
- The ctime: libcephfs stamps each request with `clock_gettime`, and the
|
||||
backend replaces that function in its own process (see
|
||||
[migration.md](migration.md)). This works only with the client library
|
||||
inside the process.
|
||||
- Separate client instances per purpose (writer, verifier, claim), so caps
|
||||
are returned together when a client closes. On a kernel mount all callers
|
||||
share one client.
|
||||
- Both clusters in one process, without mounts and without root privileges.
|
||||
|
||||
The binding in `internal/cephfsnative` is our own instead of go-ceph. It
|
||||
wraps only the roughly 45 functions the copier calls, and it can call a new
|
||||
interface such as snapdiff or blockdiff as soon as the installed libcephfs
|
||||
provides it, without waiting for a wrapper release. In return, we maintain it
|
||||
ourselves.
|
||||
|
||||
Costs of CGO: the copier build needs a C compiler, the libcephfs headers and
|
||||
the build tag `ceph`; the binary links dynamically against libcephfs; cross
|
||||
compiling is harder. A build without libcephfs supports only `doctor` and
|
||||
`status`.
|
||||
|
||||
Snapdiff marks changed inodes; in addition, comparing the Ceph inode version
|
||||
ensures that data changes with the same size and mtime are not missed.
|
||||
Blockdiff is used from 16 MiB on, provided a confirmed base with matching
|
||||
source and target inodes exists. If the diff interfaces are unavailable, the
|
||||
state is reconstructed fully and natively. There is no fallback to another
|
||||
transfer method.
|
||||
|
||||
Snapdiff cannot replace the metadata scan (see
|
||||
[metadata scan](migration.md#metadata-scan)). Every round scans all metadata
|
||||
and checks the full hardlink topology.
|
||||
Data verification reads all bytes for the first state and only the copied
|
||||
ranges for confirmed later states. Unchanged ranges are taken from the
|
||||
previously verified base. The target must belong exclusively to the
|
||||
migration job; foreign changes to unchanged ranges are not fully detected
|
||||
this way.
|
||||
An index on local disk binds the base to clusters, data paths and journal.
|
||||
Before every change its validity is withdrawn in the journal. An
|
||||
interruption forces a full reconstruction of the open state in the next
|
||||
process.
|
||||
|
||||
Evidence of runtime or throughput for 200 TB / 200 million files is missing.
|
||||
After an interruption, too, the full reconstruction can take correspondingly
|
||||
long. The number of bytes changed by the application is not a fixed upper
|
||||
bound for the changed ranges reported by the OSD.
|
||||
|
||||
The ready-made cephfs-mirror uses native replication but, according to its
|
||||
documentation, does not preserve shared hardlink inodes. It would synchronize
|
||||
hardlinked files as separate files. An unverified switch to cephfs-mirror
|
||||
would therefore not satisfy the agreed link requirements.
|
||||
|
||||
## Primary sources
|
||||
|
||||
- [MDS metadata pool and journals](https://docs.ceph.com/en/latest/cephfs/mds-journaling/)
|
||||
- [CephFS architecture and direct RADOS data access](https://docs.ceph.com/en/latest/cephfs/index.html)
|
||||
- [PoolDump: export of the HEAD state only](https://github.com/ceph/ceph/blob/main/src/tools/rados/PoolDump.cc)
|
||||
- [Pool migration within the same cluster](https://docs.ceph.com/en/latest/dev/pool-migration-design/)
|
||||
- [libcephfs: snapdiff and blockdiff](https://github.com/ceph/ceph/blob/main/src/include/cephfs/libcephfs.h)
|
||||
- [CephFS mirroring: blockdiff and hardlink limits](https://docs.ceph.com/en/latest/cephfs/cephfs-mirroring/)
|
||||
@@ -400,6 +400,157 @@
|
||||
"source_raw_used_delta_bytes": 18640896,
|
||||
"target_raw_used_delta_bytes": 138170368,
|
||||
"local_state_kib": 464
|
||||
},
|
||||
"current_10000": {
|
||||
"date": "2026-12-03",
|
||||
"code": "6dcb7b6",
|
||||
"settings": {
|
||||
"files": 10000,
|
||||
"bytes_per_file": 128,
|
||||
"workers": 4,
|
||||
"binary": "/usr/local/bin/cephmig-native"
|
||||
},
|
||||
"phases": {
|
||||
"initial": {
|
||||
"seconds": 197.693,
|
||||
"peak_rss_kib": 170984,
|
||||
"bytes_written": 1280000,
|
||||
"files_copied": 10000,
|
||||
"rounds": [
|
||||
{
|
||||
"name": "baseline",
|
||||
"mode": "full",
|
||||
"files_visited": 10254,
|
||||
"files_copied": 10000,
|
||||
"bytes_copied": 1280000,
|
||||
"bytes_verified": 1280000,
|
||||
"blockdiff_files": 0,
|
||||
"snapdiff_entries": 0,
|
||||
"seconds": 165.309
|
||||
},
|
||||
{
|
||||
"name": "cephmig-f8b6df4b9f8d-8c82b1411e76",
|
||||
"mode": "snapdiff",
|
||||
"base_snapshot": "baseline",
|
||||
"files_visited": 10254,
|
||||
"files_copied": 0,
|
||||
"bytes_copied": 0,
|
||||
"bytes_verified": 0,
|
||||
"blockdiff_files": 0,
|
||||
"snapdiff_entries": 53,
|
||||
"seconds": 20.294
|
||||
}
|
||||
],
|
||||
"mds_requests_delta": {
|
||||
"source": {
|
||||
"requests": 191563,
|
||||
"getattr": 86457,
|
||||
"lookup": 258,
|
||||
"lookupsnap": 84612,
|
||||
"setattr": 0,
|
||||
"readdir": 120
|
||||
},
|
||||
"target": {
|
||||
"requests": 225826,
|
||||
"getattr": 44513,
|
||||
"lookup": 86949,
|
||||
"lookupsnap": 41964,
|
||||
"setattr": 10355,
|
||||
"readdir": 399
|
||||
}
|
||||
}
|
||||
},
|
||||
"catchup": {
|
||||
"seconds": 36.224,
|
||||
"peak_rss_kib": 122112,
|
||||
"bytes_written": 64128,
|
||||
"files_copied": 501,
|
||||
"rounds": [
|
||||
{
|
||||
"name": "cephmig-f8b6df4b9f8d-2c4fa190089d",
|
||||
"mode": "snapdiff",
|
||||
"base_snapshot": "cephmig-f8b6df4b9f8d-8c82b1411e76",
|
||||
"files_visited": 10254,
|
||||
"files_copied": 501,
|
||||
"bytes_copied": 64128,
|
||||
"bytes_verified": 64128,
|
||||
"blockdiff_files": 0,
|
||||
"snapdiff_entries": 453,
|
||||
"seconds": 21.874
|
||||
}
|
||||
],
|
||||
"mds_requests_delta": {
|
||||
"source": {
|
||||
"requests": 69902,
|
||||
"getattr": 34743,
|
||||
"lookup": 310,
|
||||
"lookupsnap": 33702,
|
||||
"setattr": 0,
|
||||
"readdir": 58
|
||||
},
|
||||
"target": {
|
||||
"requests": 95364,
|
||||
"getattr": 22347,
|
||||
"lookup": 48225,
|
||||
"lookupsnap": 20982,
|
||||
"setattr": 652,
|
||||
"readdir": 181
|
||||
}
|
||||
}
|
||||
},
|
||||
"final": {
|
||||
"seconds": 39.141,
|
||||
"peak_rss_kib": 130336,
|
||||
"bytes_written": 0,
|
||||
"files_copied": 0,
|
||||
"rounds": [
|
||||
{
|
||||
"name": "cephmig-f8b6df4b9f8d-b3c6cb4c6202",
|
||||
"mode": "snapdiff",
|
||||
"base_snapshot": "cephmig-f8b6df4b9f8d-2c4fa190089d",
|
||||
"files_visited": 10254,
|
||||
"files_copied": 0,
|
||||
"bytes_copied": 0,
|
||||
"bytes_verified": 0,
|
||||
"blockdiff_files": 0,
|
||||
"snapdiff_entries": 53,
|
||||
"seconds": 19.463
|
||||
}
|
||||
],
|
||||
"mds_requests_delta": {
|
||||
"source": {
|
||||
"requests": 87616,
|
||||
"getattr": 44333,
|
||||
"lookup": 120,
|
||||
"lookupsnap": 43013,
|
||||
"setattr": 0,
|
||||
"readdir": 58
|
||||
},
|
||||
"target": {
|
||||
"requests": 96415,
|
||||
"getattr": 22605,
|
||||
"lookup": 51947,
|
||||
"lookupsnap": 20982,
|
||||
"setattr": 100,
|
||||
"readdir": 230
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"verification": {
|
||||
"live_files_checked": 10100,
|
||||
"snapshots": [
|
||||
{
|
||||
"name": "baseline",
|
||||
"files_checked": 10100
|
||||
},
|
||||
{
|
||||
"name": "cephmig-f8b6df4b9f8d-b3c6cb4c6202",
|
||||
"files_checked": 10100
|
||||
}
|
||||
],
|
||||
"seconds": 422.157
|
||||
}
|
||||
}
|
||||
},
|
||||
"binaries_sha256": "af66d7499e10961c0bd0f4a7e07b81b706b5061abf0c08bda67fb9b03835cba9 /state/benchmark-binaries/cephmig-before\n871f69016ce2f692397bf578a2a207d02580df3c072c307fb82d4b3df5615ae0 /usr/local/bin/cephmig-native\n",
|
||||
|
||||
+45
-29
@@ -1,53 +1,69 @@
|
||||
# Lokaler Test mit vielen kleinen Dateien
|
||||
# Local test with many small files
|
||||
|
||||
Gemessen am 05./06.11.2026 mit Ceph 21.2.0. Zwei unabhängige Laborcluster, je ein MON/MGR/MDS und ein dateibasierter 4-GiB-BlueStore-OSD auf demselben Host; vier Kopier-Worker.
|
||||
Measured with Ceph 21.2.0, most recently on 2026-12-03. Two independent lab clusters, each with one MON/MGR/MDS and one file-backed 4 GiB BlueStore OSD on the same host; four copy workers.
|
||||
|
||||
Jede Datei enthält 128 Byte deterministische, nicht ausschließlich nullwertige Daten. Eine Hälfte liegt in einem großen Verzeichnis, die andere verteilt auf 50 Verzeichnisse. Zusätzlich: 100 Hardlink-Namen und 100 Symlinks. Änderungen: jeweils 1 % Inhalt, Löschungen, Umbenennungen, neue Dateien, Modus/xattr-Änderungen und xattr-Löschungen. Die 2.000-Dateien-Läufe enthalten außerdem numerische Besitzer und Zugriffs-/Default-ACLs.
|
||||
Each file contains 128 bytes of deterministic data that is not all zeros. Half of the files are in one large directory, the other half spread over 50 directories. In addition: 100 hardlink names and 100 symlinks. Changes: 1 % each of contents, deletions, renames, new files, mode/xattr changes and xattr removals. The 2,000-file runs also contain numeric owners and access/default ACLs.
|
||||
|
||||
## Vergleich mit 2.000 Dateien
|
||||
## Current run with 10,000 files (2026-12-03)
|
||||
|
||||
| Phase | Vorher | Nachher | MDS-Anfragen vorher | MDS-Anfragen nachher |
|
||||
Code state `6dcb7b6`: the writing client is replaced before verification, verification runs in parallel, and skipping unchanged subtrees is removed.
|
||||
|
||||
| Phase | Duration | Payload written | MDS requests, both clusters |
|
||||
|---|---:|---:|---:|
|
||||
| Initial run, two states | 197.7 s | 1,280,000 bytes | 417,389 |
|
||||
| Catch-up round | 36.2 s | 64,128 bytes | 165,266 |
|
||||
| Final round | 39.1 s | 0 bytes | 184,031 |
|
||||
|
||||
The catch-up round copied 501 files. Maximum process RSS across the phases: 167.0 MiB. The independent application client compared the live target, the source snapshot `baseline` and the remaining round snapshot, each with 10,100 regular file paths including hardlinks, plus symlinks and metadata; all checks passed in 422.2 s. Older round snapshots were already removed by `sync`.
|
||||
|
||||
Compared with the run before optimization below, the catch-up round dropped from 459.3 s to 36.2 s and the final round from 84.1 s to 39.1 s. Between the two runs lie the optimizations listed under [implemented changes](#implemented-changes), the client replacement before verification and parallel verification; their individual shares were not measured.
|
||||
|
||||
## Comparison with 2,000 files (2026-11-05/06)
|
||||
|
||||
| Phase | Before | After | MDS requests before | MDS requests after |
|
||||
|---|---:|---:|---:|---:|
|
||||
| Erstlauf, zwei Stände | 490.2 s | 55.2 s | 115.132 | 87.437 |
|
||||
| Änderungsabgleich | 52.2 s | 21.2 s | 52.677 | 38.911 |
|
||||
| Finaler Abgleich | 30.1 s | 24.1 s | 59.350 | 41.074 |
|
||||
| Initial run, two states | 490.2 s | 55.2 s | 115,132 | 87,437 |
|
||||
| Catch-up round | 52.2 s | 21.2 s | 52,677 | 38,911 |
|
||||
| Final round | 30.1 s | 24.1 s | 59,350 | 41,074 |
|
||||
|
||||
Im finalen Lauf: 30.8 % weniger MDS-Anfragen, 20.0 % kürzere Laufzeit. In beiden Varianten wurden dabei 0 Nutzdatenbytes geschrieben. Der Änderungsabgleich schrieb in beiden Varianten 12.928 Byte für 101 Dateien.
|
||||
In the final run: 30.8 % fewer MDS requests, 20.0 % shorter runtime. Both variants wrote 0 payload bytes there. The catch-up round wrote 12,928 bytes for 101 files in both variants.
|
||||
|
||||
Gemessener maximaler Prozess-RSS über die Phasen: vorher 93.7 MiB, nachher 76.4 MiB. Ceph-Daemons, CLI-Kinder und Anwendungsclient sind darin nicht enthalten.
|
||||
Measured maximum process RSS across the phases: 93.7 MiB before, 76.4 MiB after. Ceph daemons, CLI children and the application client are not included.
|
||||
|
||||
Die alte Version zeigte beim Erstlauf MDS-Lesesperren-Wartezeiten. Andere Vorläufe lagen dort bei etwa 99 s. Die große Differenz des Erstlaufs ist deshalb kein allgemeines Beschleunigungsversprechen. Der über Nacht unterbrochene Vergleich sowie dessen Wiederanlauf sind nicht als Vergleichsmessung enthalten.
|
||||
The old version showed MDS read lock waits in the initial run. Other earlier runs took about 99 s there. The large difference in the initial run is therefore no general promise of a speedup. The comparison interrupted overnight and its restart are not included as a comparison measurement.
|
||||
|
||||
## Abgeschlossener Test mit 10.000 Dateien, vor Optimierung
|
||||
## Completed test with 10,000 files, before optimization (2026-11-05/06)
|
||||
|
||||
| Phase | Dauer | Geschriebene Nutzdaten |
|
||||
| Phase | Duration | Payload written |
|
||||
|---|---:|---:|
|
||||
| Erstlauf, zwei Stände | 554.4 s | 1.280.000 Byte |
|
||||
| Änderungsabgleich | 459.3 s | 64.128 Byte |
|
||||
| Finaler Abgleich | 84.1 s | 0 Byte |
|
||||
| Initial run, two states | 554.4 s | 1,280,000 bytes |
|
||||
| Catch-up round | 459.3 s | 64,128 bytes |
|
||||
| Final round | 84.1 s | 0 bytes |
|
||||
|
||||
Der unabhängige Anwendungsclient verglich live und in vier historischen Ständen insgesamt 50.500 reguläre Dateipfade einschließlich Hardlinks, zusätzlich Symlinks und Metadaten. Alle Prüfungen waren erfolgreich. Diese zusätzliche Testprüfung dauert 600,7 s und gehört nicht zur gemessenen Dauer von `finalize`. Remount und Anwendungsneustart sind ebenfalls nicht enthalten.
|
||||
The independent application client compared a total of 50,500 regular file paths including hardlinks, live and in four historical states, plus symlinks and metadata. All checks passed. This additional test check takes 600.7 s and is not part of the measured duration of `finalize`. Remount and application restart are not included either.
|
||||
|
||||
Der Kopierer erreichte 135.4 MiB Prozess-RSS. Journal und Index belegten am Ende 1.59 MiB. Ceph meldete vor der Bereinigung etwa 271.2 MiB zusätzliche Rohbelegung an der Quelle und 726.6 MiB am Ziel. Diese Werte enthalten auch internen Verwaltungsaufwand, Journal- und BlueFS/RocksDB-Wachstum.
|
||||
The copier reached 135.4 MiB process RSS. Journal and index took 1.59 MiB at the end. Before the cleanup, Ceph reported about 271.2 MiB of additional raw usage at the source and 726.6 MiB at the target. These values also include internal overhead and journal and BlueFS/RocksDB growth.
|
||||
|
||||
## Umgesetzte Änderungen
|
||||
## Implemented changes
|
||||
|
||||
- Vollständiges lokales Pfadinventar des unveränderlichen Quellsnapshots für Aufräumen und Überhangprüfung; erneute Quell-`stat`-Abfragen je Zielpfad entfallen. Unvollständige Inventare verhindern das Aufräumen.
|
||||
- Keine erneuten Index-Schreibtransaktionen für identische Inode-Zeilen.
|
||||
- Keine erneuten `setattr`-Aufrufe für bereits gleiche Besitzer, Rechte und mtime; Zielstatistik wird bei der Prüfung wiederverwendet.
|
||||
- Datenpuffer passend zur Dateigröße bzw. Prüflänge, höchstens 4 MiB je Puffer.
|
||||
- `AT_STATX_DONT_SYNC` nur für unveränderliche Snapshotpfade; Live-Zielpfade behalten normale Synchronisationssemantik. Cephs eigener [Mirror verwendet denselben Snapshot-Zugriff](https://github.com/ceph/ceph/blob/main/src/tools/cephfs_mirror/PeerReplayer.cc).
|
||||
- A complete local path inventory of the immutable source snapshot for pruning and the check for surplus paths; repeated source `stat` calls per target path are gone. Incomplete inventories prevent pruning.
|
||||
- No repeated index write transactions for identical inode rows.
|
||||
- No repeated `setattr` calls for already identical owner, mode and mtime; the target stat is reused during verification.
|
||||
- Data buffers sized to the file size or verification length, at most 4 MiB per buffer.
|
||||
- `AT_STATX_DONT_SYNC` only for immutable snapshot paths; live target paths keep normal synchronization semantics. Ceph's own [mirror uses the same snapshot access](https://github.com/ceph/ceph/blob/main/src/tools/cephfs_mirror/PeerReplayer.cc).
|
||||
|
||||
## Grenzen und Reproduktion
|
||||
## Limits and reproduction
|
||||
|
||||
MDS-Anfragen sind keine physisch gemessenen Datenträger-IOPS. Die Läufe sind einzelne Messungen auf einem gemeinsam genutzten Host, ohne zugesicherte Cache-Bedingungen. Es bleiben vollständige Metadatendurchläufe; für 200 Millionen Dateien ist weiterhin ein Änderungsplan nötig, der unveränderte Teilbäume überspringt. Die Ergebnisse sind keine Freigabe für diese Größenordnung.
|
||||
In the lab, the single OSD per cluster limits the tests, not the copier. During an aborted 100,000-file run in December 2026, writing one small file took about 50 ms, mostly OSD write latency (`op_w` about 32 ms) plus MDS journal latency (about 20 ms). Each cluster has only one OSD, both share one host disk (encrypted with LUKS), and they run without replication. More workers therefore hardly shorten the runs. The durations measured here say little about a production cluster with many OSDs.
|
||||
|
||||
MDS requests are not physically measured disk IOPS. The runs are single measurements on a shared host, without guaranteed cache conditions. Full metadata passes remain; 200 million files still need change planning that skips unchanged subtrees. A first attempt based on inode version and `ceph.dir.rctime` missed changes and was removed (see [metadata scan](migration.md#metadata-scan)). The results are no release for that scale.
|
||||
|
||||
```sh
|
||||
make dev-smallfiles-test
|
||||
# kleinerer Test mit MDS-Zählern:
|
||||
# smaller test with MDS counters:
|
||||
FILES=2000 REPORT_DIR=/tmp/cephmig-smallfiles-report make dev-smallfiles-test
|
||||
```
|
||||
|
||||
Die Testprogramme bereinigen bei Erfolg ihre eigenen Subvolumes, Snapshots, Claims und lokalen Zustandsdateien. Ceph kann freigewordenen Platz verzögert zurückmelden. Rohdaten, Binär-Hashes und Details stehen in [smallfiles-local.json](smallfiles-local.json).
|
||||
On success, the test programs remove their own subvolumes, snapshots, claims and local state files. Ceph may report freed space with a delay. Raw data, binary hashes and details are in [smallfiles-local.json](smallfiles-local.json).
|
||||
|
||||
Zusätzlich bestanden die Go-Tests mit Race Detector und `go vet` für den nativen Build sowie der vollständige native Funktionstest mit großen/Sparse-Dateien, Blockdiff, historischen Snapshots, ACLs, Quotas, Hardlinks auf Symlinks/FIFOs, Abbruch und SIGKILL-Wiederaufnahme. Die erfolgreichen Test-Fixtures wurden entfernt.
|
||||
In addition, the Go tests with the race detector and `go vet` for the native build passed, as did the complete native functional test with large/sparse files, blockdiff, historical snapshots, ACLs, quotas, hardlinks to symlinks/FIFOs, cancellation and SIGKILL resume. The fixtures of the successful run were removed.
|
||||
@@ -0,0 +1,135 @@
|
||||
# Concept: full content verification after the cutover
|
||||
|
||||
Status: proposal, not implemented.
|
||||
|
||||
## Motivation
|
||||
|
||||
`finalize` verifies the metadata and the hardlink topology of every entry,
|
||||
but compares file contents only where something changed since the previous
|
||||
round. Unchanged bytes were compared in full in an earlier round and are
|
||||
trusted since then. That holds only as long as nobody but cephmig writes to
|
||||
the target (see [Resumption and verification](migration.md#resumption-and-verification)).
|
||||
A process that changes the target on the side would not be reliably detected
|
||||
in unchanged ranges.
|
||||
|
||||
A complete comparison of all contents before the cutover would make the
|
||||
write stop as long as reading the whole subvolume twice. The proposal moves
|
||||
it to after the cutover.
|
||||
|
||||
## Idea
|
||||
|
||||
A new read-only command compares the final source snapshot with the final
|
||||
target snapshot completely:
|
||||
|
||||
```text
|
||||
cephmig verify --config FILE --state FILE
|
||||
```
|
||||
|
||||
Both snapshots are immutable. The comparison can therefore run while the
|
||||
application already works on the target, and its result describes exactly
|
||||
the state that was handed over at the cutover. It must run before
|
||||
`cleanup`, which deletes the final snapshots.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor Op as Operator
|
||||
participant M as cephmig
|
||||
participant J as Journal
|
||||
participant S as Source cluster
|
||||
participant T as Target cluster
|
||||
|
||||
Op->>M: finalize --writers-stopped
|
||||
M-->>Op: ready-for-cutover
|
||||
Note over Op,T: clients switched, application writes to the target
|
||||
Op->>M: verify
|
||||
M->>J: check phase and final snapshot F
|
||||
par read both snapshots
|
||||
M->>S: walk and read snapshot F
|
||||
and
|
||||
M->>T: walk and read snapshot F
|
||||
end
|
||||
M->>J: record result, verified_at
|
||||
M-->>Op: report as JSON
|
||||
Op->>M: cleanup
|
||||
M->>J: require a passed verify
|
||||
M->>S: remove snapshot F
|
||||
M->>T: remove snapshot F
|
||||
```
|
||||
|
||||
## What is compared
|
||||
|
||||
Everything the migration promises, without relying on earlier rounds:
|
||||
|
||||
- the set of entries in both directions: missing and surplus paths
|
||||
- the type of every entry, symlink text, device numbers of special files
|
||||
- **every byte of every regular file**, read on both sides
|
||||
- owner, mode, POSIX ACLs, portable xattrs, directory quotas
|
||||
- mtime, btime and ctime (with the rule ctime ≥ mtime); atime as well,
|
||||
because reading a snapshot does not change it
|
||||
- the hardlink topology in both directions, with an on-disk index as today
|
||||
- the custom metadata of the final snapshot and of the subvolume as it was
|
||||
at `finalize` (the journal holds the values)
|
||||
|
||||
The journal and the native base index are not used: the point is an
|
||||
independent check.
|
||||
|
||||
## Preconditions and behaviour
|
||||
|
||||
- The job is in phase `ready-for-cutover`, and the final snapshot exists at
|
||||
source and target and is not marked `removed`.
|
||||
- Read-only on both clusters. No claim lock is needed for reading, but the
|
||||
local journal lock prevents a parallel `cleanup`.
|
||||
- Snapshot paths are read with `AT_STATX_DONT_SYNC`, as in the copier.
|
||||
- `workers` and `bandwidth_kib` from the configuration bound the parallelism
|
||||
and the read rate, so the comparison does not slow down the application.
|
||||
- **Resumable:** progress is written to a local checkpoint next to the
|
||||
journal (last completed path in walk order, the hardlink index). An
|
||||
interrupted `verify` continues there; `--restart` starts over.
|
||||
- **Result:** a JSON report with the counts of compared entries and bytes and
|
||||
the list of differences (path and attribute, no file contents). The journal
|
||||
records `verify` with time, snapshot name and result.
|
||||
- **Exit code** 0 only if no difference was found.
|
||||
|
||||
## Interaction with cleanup
|
||||
|
||||
`cleanup` refuses to delete the final snapshot unless the journal records a
|
||||
passed `verify` for it. `cleanup --skip-verify` overrides that for operators
|
||||
who accept the risk; the journal records the override.
|
||||
|
||||
## When verify finds a difference
|
||||
|
||||
At that point the application already writes to the target, so cephmig must
|
||||
not repair anything on its own. The report names the affected paths. The
|
||||
operator decides per path, typically by restoring it from the final source
|
||||
snapshot (which still exists, because `cleanup` has not run). A later
|
||||
extension could offer `verify --repair PATH…` that copies listed paths from
|
||||
the source snapshot after explicit confirmation; that is out of scope here.
|
||||
|
||||
## Cost
|
||||
|
||||
- **Reads:** the full data of the subvolume once on each cluster. At the
|
||||
target size of 200 TB and an assumed 2.5 GB/s per side, that is roughly
|
||||
22 hours; the real rate depends on OSDs, network and the limit set.
|
||||
- **Metadata:** one walk of each snapshot, comparable to a full round.
|
||||
- **Space:** while the final snapshot exists, the target keeps the old
|
||||
blocks of everything the application overwrites or deletes. Longer
|
||||
verification means more extra space until `cleanup`.
|
||||
- **Source:** the source cluster and its final snapshot must stay available
|
||||
until `verify` is done.
|
||||
|
||||
## Tests
|
||||
|
||||
- Unit tests with fake file systems: every kind of difference is reported,
|
||||
checkpoint and resume, refusal outside `ready-for-cutover`.
|
||||
- Lab: in a catch-up round, change one byte of an unchanged file in the
|
||||
target through a test hook, so that the final target snapshot contains it
|
||||
while `finalize` passes. Expect `verify` to report exactly that file, and
|
||||
`cleanup` to refuse until a passed `verify` or `--skip-verify`.
|
||||
|
||||
## Open questions
|
||||
|
||||
- Should `cleanup` require `verify` by default, as proposed, or only warn?
|
||||
- Is a sample mode useful (for example a random fraction of the files) for a
|
||||
quick check before the full run?
|
||||
- Should the report be kept as a file next to the journal in addition to
|
||||
standard output?
|
||||
@@ -6,41 +6,179 @@ package cephfsnative
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE
|
||||
#cgo LDFLAGS: -lcephfs
|
||||
#cgo LDFLAGS: -lcephfs -ldl
|
||||
#include <dlfcn.h>
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/xattr.h>
|
||||
#include <time.h>
|
||||
#include <cephfs/libcephfs.h>
|
||||
|
||||
static int cm_stat(struct ceph_mount_info *m, const char *p, struct ceph_statx *s,int flags) {
|
||||
return ceph_statx(m,p,s,CEPH_STATX_BASIC_STATS|CEPH_STATX_VERSION,flags);
|
||||
// Change-time control.
|
||||
//
|
||||
// The MDS derives an inode's ctime from the time stamp the client sends with
|
||||
// each request; libcephfs takes it from clock_gettime(CLOCK_REALTIME) in the
|
||||
// calling thread. Measured on Ceph 21.2.0: setattr and cap flushes only move
|
||||
// the ctime forward, while link, unlink, rename and xattr requests set it to
|
||||
// max(stamp, mtime), also backwards.
|
||||
//
|
||||
// The definition below overrides clock_gettime for the whole process, but
|
||||
// changes the result only in a thread that set cm_clock, and only for the
|
||||
// duration of one call. Every modifying call runs with the stamp
|
||||
// 1970-01-01T00:00:01Z, so it never raises a ctime. cm_attr ends with an xattr
|
||||
// request stamped with the source ctime, which sets the ctime exactly. The Go
|
||||
// runtime reads the clock through the vDSO and is not affected.
|
||||
static __thread struct timespec cm_clock;
|
||||
static int (*cm_real_clock_gettime)(clockid_t, struct timespec *);
|
||||
|
||||
int clock_gettime(clockid_t clk, struct timespec *ts)
|
||||
{
|
||||
if (cm_clock.tv_sec && (clk == CLOCK_REALTIME || clk == CLOCK_REALTIME_COARSE)) {
|
||||
*ts = cm_clock;
|
||||
return 0;
|
||||
}
|
||||
if (!cm_real_clock_gettime)
|
||||
cm_real_clock_gettime = dlsym(RTLD_NEXT, "clock_gettime");
|
||||
return cm_real_clock_gettime(clk, ts);
|
||||
}
|
||||
static int cm_attr(struct ceph_mount_info *m,const char *p,unsigned mode,unsigned uid,
|
||||
unsigned gid,long sec,long nsec) {
|
||||
|
||||
#define CM_ANCIENT(call) ({ \
|
||||
cm_clock.tv_sec = 1; \
|
||||
cm_clock.tv_nsec = 0; \
|
||||
__typeof__(call) cm_ret = (call); \
|
||||
cm_clock.tv_sec = 0; \
|
||||
cm_ret; \
|
||||
})
|
||||
|
||||
static int cm_stat(struct ceph_mount_info *m, const char *p, struct ceph_statx *s, int flags)
|
||||
{
|
||||
return ceph_statx(m, p, s, CEPH_STATX_BASIC_STATS | CEPH_STATX_VERSION | CEPH_STATX_BTIME, flags);
|
||||
}
|
||||
|
||||
// cm_attr sets owner, mode, the access, modification and birth times and, last,
|
||||
// the change time. t holds seconds and nanoseconds for atime, mtime, btime and
|
||||
// ctime in this order. A zero ctime leaves the change time alone.
|
||||
//
|
||||
// The ctime step creates and removes the xattr user.cephmig.ctime with the
|
||||
// clock set to the wanted ctime. The MDS then sets ctime = max(wanted, mtime).
|
||||
// It must be the last change to the inode: later links, unlinks, renames or
|
||||
// xattr changes reset the ctime to the mtime.
|
||||
static int cm_attr(struct ceph_mount_info *m, const char *p, unsigned mode, unsigned uid,
|
||||
unsigned gid, const long *t)
|
||||
{
|
||||
struct ceph_statx s = {0};
|
||||
s.stx_mode=mode; s.stx_uid=uid; s.stx_gid=gid;
|
||||
s.stx_mtime.tv_sec=sec; s.stx_mtime.tv_nsec=nsec;
|
||||
int mask=CEPH_SETATTR_UID|CEPH_SETATTR_GID|CEPH_SETATTR_MTIME;
|
||||
if ((mode&S_IFMT)!=S_IFLNK) mask|=CEPH_SETATTR_MODE;
|
||||
return ceph_setattrx(m,p,&s,mask,AT_SYMLINK_NOFOLLOW);
|
||||
s.stx_mode = mode;
|
||||
s.stx_uid = uid;
|
||||
s.stx_gid = gid;
|
||||
s.stx_atime.tv_sec = t[0];
|
||||
s.stx_atime.tv_nsec = t[1];
|
||||
s.stx_mtime.tv_sec = t[2];
|
||||
s.stx_mtime.tv_nsec = t[3];
|
||||
s.stx_btime.tv_sec = t[4];
|
||||
s.stx_btime.tv_nsec = t[5];
|
||||
|
||||
int mask = CEPH_SETATTR_UID | CEPH_SETATTR_GID | CEPH_SETATTR_ATIME |
|
||||
CEPH_SETATTR_MTIME | CEPH_SETATTR_BTIME;
|
||||
if ((mode & S_IFMT) != S_IFLNK)
|
||||
mask |= CEPH_SETATTR_MODE;
|
||||
int ret = CM_ANCIENT(ceph_setattrx(m, p, &s, mask, AT_SYMLINK_NOFOLLOW));
|
||||
if (ret < 0 || (t[6] == 0 && t[7] == 0))
|
||||
return ret;
|
||||
|
||||
cm_clock.tv_sec = t[6];
|
||||
cm_clock.tv_nsec = t[7];
|
||||
ret = ceph_lsetxattr(m, p, "user.cephmig.ctime", "", 0, XATTR_CREATE);
|
||||
if (ret == 0)
|
||||
ret = ceph_lremovexattr(m, p, "user.cephmig.ctime");
|
||||
cm_clock.tv_sec = 0;
|
||||
return ret;
|
||||
}
|
||||
|
||||
// ceph_link resolves a symbolic-link source. Use inode-based linking so the
|
||||
// link itself, including a dangling symlink, is shared instead of its referent.
|
||||
static int cm_link_nofollow(struct ceph_mount_info *m,const char *oldpath,
|
||||
const char *newparent,const char *name) {
|
||||
const UserPerm *perms=ceph_mount_perms(m);
|
||||
Inode *in=NULL,*parent=NULL;
|
||||
struct ceph_statx s={0};
|
||||
int ret=ceph_ll_walk(m,oldpath,&in,&s,CEPH_STATX_BASIC_STATS,AT_SYMLINK_NOFOLLOW,perms);
|
||||
if (ret<0) return ret;
|
||||
ret=ceph_ll_walk(m,newparent,&parent,&s,CEPH_STATX_BASIC_STATS,0,perms);
|
||||
if (ret==0) ret=ceph_ll_link(m,in,parent,name,perms);
|
||||
if (parent) ceph_ll_put(m,parent);
|
||||
ceph_ll_put(m,in);
|
||||
static int cm_link_nofollow(struct ceph_mount_info *m, const char *oldpath,
|
||||
const char *newparent, const char *name)
|
||||
{
|
||||
const UserPerm *perms = ceph_mount_perms(m);
|
||||
Inode *in = NULL, *parent = NULL;
|
||||
struct ceph_statx s = {0};
|
||||
|
||||
int ret = ceph_ll_walk(m, oldpath, &in, &s, CEPH_STATX_BASIC_STATS, AT_SYMLINK_NOFOLLOW, perms);
|
||||
if (ret < 0)
|
||||
return ret;
|
||||
ret = ceph_ll_walk(m, newparent, &parent, &s, CEPH_STATX_BASIC_STATS, 0, perms);
|
||||
if (ret == 0)
|
||||
ret = ceph_ll_link(m, in, parent, name, perms);
|
||||
if (parent)
|
||||
ceph_ll_put(m, parent);
|
||||
ceph_ll_put(m, in);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int cm_open(struct ceph_mount_info *m, const char *p, int flags, mode_t mode)
|
||||
{
|
||||
if ((flags & O_ACCMODE) == O_RDONLY && !(flags & (O_CREAT | O_TRUNC)))
|
||||
return ceph_open(m, p, flags, mode);
|
||||
return CM_ANCIENT(ceph_open(m, p, flags, mode));
|
||||
}
|
||||
|
||||
static int cm_close(struct ceph_mount_info *m, int fd) { return CM_ANCIENT(ceph_close(m, fd)); }
|
||||
static int cm_fsync(struct ceph_mount_info *m, int fd) { return CM_ANCIENT(ceph_fsync(m, fd, 0)); }
|
||||
static int cm_sync_fs(struct ceph_mount_info *m) { return CM_ANCIENT(ceph_sync_fs(m)); }
|
||||
|
||||
static int cm_write(struct ceph_mount_info *m, int fd, const char *b, int64_t n, int64_t off)
|
||||
{
|
||||
return CM_ANCIENT(ceph_write(m, fd, b, n, off));
|
||||
}
|
||||
|
||||
static int cm_ftruncate(struct ceph_mount_info *m, int fd, int64_t n)
|
||||
{
|
||||
return CM_ANCIENT(ceph_ftruncate(m, fd, n));
|
||||
}
|
||||
|
||||
static int cm_fallocate(struct ceph_mount_info *m, int fd, int mode, int64_t off, int64_t n)
|
||||
{
|
||||
return CM_ANCIENT(ceph_fallocate(m, fd, mode, off, n));
|
||||
}
|
||||
|
||||
static int cm_mkdir(struct ceph_mount_info *m, const char *p, mode_t mode)
|
||||
{
|
||||
return CM_ANCIENT(ceph_mkdir(m, p, mode));
|
||||
}
|
||||
|
||||
static int cm_unlink(struct ceph_mount_info *m, const char *p) { return CM_ANCIENT(ceph_unlink(m, p)); }
|
||||
static int cm_rmdir(struct ceph_mount_info *m, const char *p) { return CM_ANCIENT(ceph_rmdir(m, p)); }
|
||||
|
||||
static int cm_rename(struct ceph_mount_info *m, const char *a, const char *b)
|
||||
{
|
||||
return CM_ANCIENT(ceph_rename(m, a, b));
|
||||
}
|
||||
|
||||
static int cm_link(struct ceph_mount_info *m, const char *a, const char *parent, const char *name)
|
||||
{
|
||||
return CM_ANCIENT(cm_link_nofollow(m, a, parent, name));
|
||||
}
|
||||
|
||||
static int cm_symlink(struct ceph_mount_info *m, const char *a, const char *b)
|
||||
{
|
||||
return CM_ANCIENT(ceph_symlink(m, a, b));
|
||||
}
|
||||
|
||||
static int cm_mknod(struct ceph_mount_info *m, const char *p, mode_t mode, dev_t dev)
|
||||
{
|
||||
return CM_ANCIENT(ceph_mknod(m, p, mode, dev));
|
||||
}
|
||||
|
||||
static int cm_setxattr(struct ceph_mount_info *m, const char *p, const char *k, const void *v, size_t n)
|
||||
{
|
||||
return CM_ANCIENT(ceph_lsetxattr(m, p, k, v, n, 0));
|
||||
}
|
||||
|
||||
static int cm_removexattr(struct ceph_mount_info *m, const char *p, const char *k)
|
||||
{
|
||||
return CM_ANCIENT(ceph_lremovexattr(m, p, k));
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
@@ -65,8 +203,10 @@ func errno(ret C.int) error {
|
||||
if ret < 0 {
|
||||
return syscall.Errno(-ret)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func str(s string) (*C.char, func()) {
|
||||
p := C.CString(s)
|
||||
return p, func() { C.free(unsafe.Pointer(p)) }
|
||||
@@ -80,24 +220,29 @@ func Open(o storage.Options) (*Client, error) {
|
||||
if user == "" {
|
||||
user = "admin"
|
||||
}
|
||||
|
||||
id, free := str(user)
|
||||
defer free()
|
||||
if err := errno(C.ceph_create(&c.mount, id)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
failed := true
|
||||
defer func() {
|
||||
if failed {
|
||||
c.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
conf, release := str(o.Config)
|
||||
defer release()
|
||||
if err := errno(C.ceph_conf_read_file(c.mount, conf)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
settings := map[string]string{"keyring": o.Keyring, "client_mount_timeout": "30",
|
||||
"client_acl_type": "posix_acl", "client_oc": "false"}
|
||||
|
||||
for k, v := range settings {
|
||||
key, fk := str(k)
|
||||
value, fv := str(v)
|
||||
@@ -108,16 +253,19 @@ func Open(o storage.Options) (*Client, error) {
|
||||
return nil, fmt.Errorf("Ceph option %s: %w", k, err)
|
||||
}
|
||||
}
|
||||
|
||||
fs, ff := str(o.Filesystem)
|
||||
defer ff()
|
||||
if err := errno(C.ceph_select_filesystem(c.mount, fs)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
root, fr := str("/")
|
||||
defer fr()
|
||||
if err := errno(C.ceph_mount(c.mount, root)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
failed = false
|
||||
return c, nil
|
||||
}
|
||||
@@ -128,13 +276,20 @@ func (c *Client) Close() error {
|
||||
C.ceph_shutdown(c.mount)
|
||||
c.mount = nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func node(s C.struct_ceph_statx) storage.Node {
|
||||
return storage.Node{Mode: uint32(s.stx_mode), Inode: uint64(s.stx_ino),
|
||||
Version: uint64(s.stx_version), Nlink: uint64(s.stx_nlink), Size: uint64(s.stx_size),
|
||||
Rdev: uint64(s.stx_rdev), UID: uint32(s.stx_uid), GID: uint32(s.stx_gid),
|
||||
Mtime: time.Unix(int64(s.stx_mtime.tv_sec), int64(s.stx_mtime.tv_nsec))}
|
||||
Atime: timespec(s.stx_atime), Mtime: timespec(s.stx_mtime),
|
||||
Ctime: timespec(s.stx_ctime), Btime: timespec(s.stx_btime)}
|
||||
}
|
||||
|
||||
func timespec(t C.struct_timespec) time.Time {
|
||||
return time.Unix(int64(t.tv_sec), int64(t.tv_nsec))
|
||||
}
|
||||
|
||||
// Stat returns the attributes of path without following a final symlink.
|
||||
@@ -154,6 +309,7 @@ func nativeStatFlags(path string) C.int {
|
||||
if strings.Contains(path, "/.snap/") {
|
||||
flags |= C.AT_STATX_DONT_SYNC
|
||||
}
|
||||
|
||||
return flags
|
||||
}
|
||||
|
||||
@@ -161,10 +317,11 @@ func nativeStatFlags(path string) C.int {
|
||||
func (c *Client) Open(path string, flags int, mode uint32) (storage.File, error) {
|
||||
p, f := str(path)
|
||||
defer f()
|
||||
ret := C.ceph_open(c.mount, p, C.int(flags), C.mode_t(mode))
|
||||
ret := C.cm_open(c.mount, p, C.int(flags), C.mode_t(mode))
|
||||
if err := errno(ret); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &file{client: c, fd: ret}, nil
|
||||
}
|
||||
|
||||
@@ -178,44 +335,57 @@ func (f *file) Close() error {
|
||||
if f.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
f.closed = true
|
||||
return errno(C.ceph_close(f.client.mount, f.fd))
|
||||
return errno(C.cm_close(f.client.mount, f.fd))
|
||||
}
|
||||
|
||||
func (f *file) ReadAt(b []byte, off int64) (int, error) {
|
||||
if len(b) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
n := C.ceph_read(f.client.mount, f.fd, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(len(b)), C.int64_t(off))
|
||||
if err := errno(n); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if int(n) < len(b) {
|
||||
return int(n), io.EOF
|
||||
}
|
||||
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
func (f *file) WriteAt(b []byte, off int64) (int, error) {
|
||||
if len(b) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
n := C.ceph_write(f.client.mount, f.fd, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(len(b)), C.int64_t(off))
|
||||
|
||||
n := C.cm_write(f.client.mount, f.fd, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(len(b)), C.int64_t(off))
|
||||
if err := errno(n); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if int(n) != len(b) {
|
||||
return int(n), io.ErrShortWrite
|
||||
}
|
||||
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
func (f *file) Truncate(n int64) error {
|
||||
return errno(C.ceph_ftruncate(f.client.mount, f.fd, C.int64_t(n)))
|
||||
return errno(C.cm_ftruncate(f.client.mount, f.fd, C.int64_t(n)))
|
||||
}
|
||||
func (f *file) Sync() error { return errno(C.ceph_fsync(f.client.mount, f.fd, 0)) }
|
||||
|
||||
func (f *file) Sync() error { return errno(C.cm_fsync(f.client.mount, f.fd)) }
|
||||
|
||||
func (f *file) Lock(owner uint64) error {
|
||||
return errno(C.ceph_flock(f.client.mount, f.fd, C.LOCK_EX|C.LOCK_NB, C.uint64_t(owner)))
|
||||
}
|
||||
|
||||
func (f *file) PunchHole(off, length int64) error {
|
||||
return errno(C.ceph_fallocate(f.client.mount, f.fd, 3, C.int64_t(off), C.int64_t(length)))
|
||||
return errno(C.cm_fallocate(f.client.mount, f.fd, 3, C.int64_t(off), C.int64_t(length)))
|
||||
}
|
||||
|
||||
type dir struct {
|
||||
@@ -233,48 +403,55 @@ func (c *Client) OpenDir(path string) (storage.DirectoryStream, error) {
|
||||
if err := errno(C.ceph_opendir(c.mount, p, &d.handle)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *dir) Next() (*storage.Entry, error) {
|
||||
for {
|
||||
var entry C.struct_dirent
|
||||
var s C.struct_ceph_statx
|
||||
ret := C.ceph_readdirplus_r(d.client.mount, d.handle, &entry, &s,
|
||||
C.CEPH_STATX_BASIC_STATS|C.CEPH_STATX_VERSION, C.uint(d.flags), nil)
|
||||
C.CEPH_STATX_BASIC_STATS|C.CEPH_STATX_VERSION|C.CEPH_STATX_BTIME, C.uint(d.flags), nil)
|
||||
|
||||
if err := errno(ret); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if ret == 0 {
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
name := C.GoString(&entry.d_name[0])
|
||||
if name == "." || name == ".." || name == ".snap" {
|
||||
continue
|
||||
}
|
||||
|
||||
return &storage.Entry{Name: name, Node: node(s)}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d *dir) Close() error { return errno(C.ceph_closedir(d.client.mount, d.handle)) }
|
||||
|
||||
// Mkdir creates a directory.
|
||||
func (c *Client) Mkdir(path string, mode uint32) error {
|
||||
p, f := str(path)
|
||||
defer f()
|
||||
return errno(C.ceph_mkdir(c.mount, p, C.mode_t(mode)))
|
||||
return errno(C.cm_mkdir(c.mount, p, C.mode_t(mode)))
|
||||
}
|
||||
|
||||
// Unlink removes a non-directory entry.
|
||||
func (c *Client) Unlink(path string) error {
|
||||
p, f := str(path)
|
||||
defer f()
|
||||
return errno(C.ceph_unlink(c.mount, p))
|
||||
return errno(C.cm_unlink(c.mount, p))
|
||||
}
|
||||
|
||||
// Rmdir removes an empty directory.
|
||||
func (c *Client) Rmdir(path string) error {
|
||||
p, f := str(path)
|
||||
defer f()
|
||||
return errno(C.ceph_rmdir(c.mount, p))
|
||||
return errno(C.cm_rmdir(c.mount, p))
|
||||
}
|
||||
|
||||
// Rename renames a to b.
|
||||
@@ -283,7 +460,7 @@ func (c *Client) Rename(a, b string) error {
|
||||
defer f()
|
||||
q, g := str(b)
|
||||
defer g()
|
||||
return errno(C.ceph_rename(c.mount, p, q))
|
||||
return errno(C.cm_rename(c.mount, p, q))
|
||||
}
|
||||
|
||||
// Link creates the hard link b to a without following a symlink at a.
|
||||
@@ -294,7 +471,7 @@ func (c *Client) Link(a, b string) error {
|
||||
defer g()
|
||||
name, h := str(path.Base(b))
|
||||
defer h()
|
||||
return errno(C.cm_link_nofollow(c.mount, p, q, name))
|
||||
return errno(C.cm_link(c.mount, p, q, name))
|
||||
}
|
||||
|
||||
// Symlink creates the symbolic link b pointing to a.
|
||||
@@ -303,14 +480,14 @@ func (c *Client) Symlink(a, b string) error {
|
||||
defer f()
|
||||
q, g := str(b)
|
||||
defer g()
|
||||
return errno(C.ceph_symlink(c.mount, p, q))
|
||||
return errno(C.cm_symlink(c.mount, p, q))
|
||||
}
|
||||
|
||||
// Mknod creates a special file.
|
||||
func (c *Client) Mknod(path string, mode uint32, dev uint64) error {
|
||||
p, f := str(path)
|
||||
defer f()
|
||||
return errno(C.ceph_mknod(c.mount, p, C.mode_t(mode), C.dev_t(dev)))
|
||||
return errno(C.cm_mknod(c.mount, p, C.mode_t(mode), C.dev_t(dev)))
|
||||
}
|
||||
|
||||
// Readlink returns the target of a symbolic link.
|
||||
@@ -323,18 +500,31 @@ func (c *Client) Readlink(path string) (string, error) {
|
||||
if err := errno(n); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if int(n) < size {
|
||||
return string(b[:int(n)]), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", errors.New("symlink target exceeds 1 MiB")
|
||||
}
|
||||
|
||||
// SetAttr sets numeric owner, mode and mtime without following symlinks.
|
||||
// SetAttr sets numeric owner, mode, atime, mtime and btime without following
|
||||
// symlinks, then sets the ctime to max(n.Ctime, n.Mtime) (see cm_attr). It
|
||||
// must be the last change to the entry in a round.
|
||||
func (c *Client) SetAttr(path string, n storage.Node) error {
|
||||
p, f := str(path)
|
||||
defer f()
|
||||
return errno(C.cm_attr(c.mount, p, C.uint(n.Mode), C.uint(n.UID), C.uint(n.GID), C.long(n.Mtime.Unix()), C.long(n.Mtime.Nanosecond())))
|
||||
times := [8]C.long{
|
||||
C.long(n.Atime.Unix()), C.long(n.Atime.Nanosecond()),
|
||||
C.long(n.Mtime.Unix()), C.long(n.Mtime.Nanosecond()),
|
||||
C.long(n.Btime.Unix()), C.long(n.Btime.Nanosecond()),
|
||||
}
|
||||
if !n.Ctime.IsZero() {
|
||||
times[6], times[7] = C.long(n.Ctime.Unix()), C.long(n.Ctime.Nanosecond())
|
||||
}
|
||||
|
||||
return errno(C.cm_attr(c.mount, p, C.uint(n.Mode), C.uint(n.UID), C.uint(n.GID), ×[0]))
|
||||
}
|
||||
|
||||
// GetXattr returns the value of an extended attribute.
|
||||
@@ -349,11 +539,14 @@ func (c *Client) GetXattr(path, key string) ([]byte, error) {
|
||||
if ret == -C.ERANGE {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := errno(ret); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b[:int(ret)], nil
|
||||
}
|
||||
|
||||
return nil, errors.New("xattr exceeds 1 MiB")
|
||||
}
|
||||
|
||||
@@ -367,17 +560,21 @@ func (c *Client) ListXattr(path string) ([]string, error) {
|
||||
if ret == -C.ERANGE {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := errno(ret); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var names []string
|
||||
for _, s := range strings.Split(string(b[:int(ret)]), "\x00") {
|
||||
if s != "" {
|
||||
names = append(names, s)
|
||||
}
|
||||
}
|
||||
|
||||
return names, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("xattr list exceeds 1 MiB")
|
||||
}
|
||||
|
||||
@@ -391,7 +588,8 @@ func (c *Client) SetXattr(path, key string, b []byte) error {
|
||||
if len(b) > 0 {
|
||||
ptr = unsafe.Pointer(&b[0])
|
||||
}
|
||||
return errno(C.ceph_lsetxattr(c.mount, p, k, ptr, C.size_t(len(b)), 0))
|
||||
|
||||
return errno(C.cm_setxattr(c.mount, p, k, ptr, C.size_t(len(b))))
|
||||
}
|
||||
|
||||
// RemoveXattr removes an extended attribute.
|
||||
@@ -400,11 +598,11 @@ func (c *Client) RemoveXattr(path, key string) error {
|
||||
defer f()
|
||||
k, g := str(key)
|
||||
defer g()
|
||||
return errno(C.ceph_lremovexattr(c.mount, p, k))
|
||||
return errno(C.cm_removexattr(c.mount, p, k))
|
||||
}
|
||||
|
||||
// Sync flushes all dirty data and metadata of the filesystem.
|
||||
func (c *Client) Sync() error { return errno(C.ceph_sync_fs(c.mount)) }
|
||||
func (c *Client) Sync() error { return errno(C.cm_sync_fs(c.mount)) }
|
||||
|
||||
type snapDiff struct{ info C.struct_ceph_snapdiff_info }
|
||||
|
||||
@@ -423,8 +621,10 @@ func (c *Client) SnapDiff(root, rel, a, b string) (storage.DiffStream, error) {
|
||||
if err := errno(C.ceph_open_snapdiff(c.mount, p, q, x, y, &s.info)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *snapDiff) Next() (string, error) {
|
||||
for {
|
||||
var entry C.struct_ceph_snapdiff_entry_t
|
||||
@@ -432,16 +632,20 @@ func (s *snapDiff) Next() (string, error) {
|
||||
if err := errno(ret); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if ret == 0 {
|
||||
return "", io.EOF
|
||||
}
|
||||
|
||||
name := C.GoString(&entry.dir_entry.d_name[0])
|
||||
if name == "." || name == ".." || name == ".snap" {
|
||||
continue
|
||||
}
|
||||
|
||||
return name, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *snapDiff) Close() error { return errno(C.ceph_close_snapdiff(&s.info)) }
|
||||
|
||||
type blockDiff struct {
|
||||
@@ -464,27 +668,34 @@ func (c *Client) BlockDiff(root, rel, a, b string) (storage.BlockStream, error)
|
||||
if err := errno(C.ceph_file_blockdiff_init(c.mount, p, q, x, y, &s.info)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *blockDiff) Next() ([]storage.Extent, error) {
|
||||
if s.done {
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
var blocks C.struct_ceph_file_blockdiff_changedblocks
|
||||
ret := C.ceph_file_blockdiff(&s.info, &blocks)
|
||||
if err := errno(ret); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer C.ceph_free_file_blockdiff_buffer(&blocks)
|
||||
s.done = ret == 0
|
||||
if uint64(blocks.num_blocks) > 1<<20 {
|
||||
return nil, errors.New("blockdiff batch exceeds supported bound")
|
||||
}
|
||||
|
||||
cblocks := unsafe.Slice(blocks.b, int(blocks.num_blocks))
|
||||
out := make([]storage.Extent, len(cblocks))
|
||||
for i, b := range cblocks {
|
||||
out[i] = storage.Extent{Offset: uint64(b.offset), Length: uint64(b.len)}
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *blockDiff) Close() error { return errno(C.ceph_file_blockdiff_finish(&s.info)) }
|
||||
@@ -2,6 +2,7 @@ package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
@@ -12,6 +13,7 @@ func nativePath(p string) (string, error) {
|
||||
if !strings.HasPrefix(p, "/") || path.Clean(p) != p || p == "/" {
|
||||
return "", fmt.Errorf("invalid Ceph data path %q", p)
|
||||
}
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
@@ -23,43 +25,27 @@ type Access interface {
|
||||
Prepare(context.Context, string, string, string) error
|
||||
Apply(context.Context, string, string) error
|
||||
Verify(context.Context, string, string, string) error
|
||||
// Release deletes the claim of job id, and the claim directories if
|
||||
// they are empty. A missing claim is not an error.
|
||||
Release(context.Context, Config, string, string) error
|
||||
}
|
||||
|
||||
type mountedAccess struct{}
|
||||
|
||||
func (mountedAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspection, error) {
|
||||
return inspectMounted(ctx, c, x)
|
||||
}
|
||||
func (mountedAccess) Empty(_ context.Context, p string) error { return emptyDirectory(p) }
|
||||
func (mountedAccess) Claim(_ context.Context, c Config, fsid, id string) (io.Closer, error) {
|
||||
return claimTarget(c.Target.Mount, fsid, c.Target, id)
|
||||
}
|
||||
func (mountedAccess) Prepare(ctx context.Context, src, dst, scratch string) error {
|
||||
if err := clearQuotas(ctx, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
return hardlinkTopology(ctx, src, dst, scratch, true)
|
||||
}
|
||||
func (mountedAccess) Apply(ctx context.Context, src, dst string) error {
|
||||
return quotas(ctx, src, dst, false)
|
||||
}
|
||||
func (mountedAccess) Verify(ctx context.Context, src, dst, scratch string) error {
|
||||
if err := hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
|
||||
return err
|
||||
}
|
||||
return quotas(ctx, src, dst, true)
|
||||
}
|
||||
func (e Engine) access() Access {
|
||||
if e.Access != nil {
|
||||
return e.Access
|
||||
}
|
||||
return mountedAccess{}
|
||||
}
|
||||
func (e Engine) access() Access { return e.Access }
|
||||
|
||||
// Inspect checks both endpoints without changing them and reports what a
|
||||
// migration would transfer.
|
||||
func (e Engine) Inspect(ctx context.Context, c Config) (*Inspection, error) {
|
||||
return e.access().Inspect(ctx, c, e.Exec)
|
||||
if e.Access == nil {
|
||||
return nil, errors.New("missing access")
|
||||
}
|
||||
|
||||
return e.Access.Inspect(ctx, c, e.Exec)
|
||||
}
|
||||
|
||||
// Transport copies a source tree to the target and verifies the copy.
|
||||
type Transport interface {
|
||||
Copy(context.Context, string, string) error
|
||||
Verify(context.Context, string, string) error
|
||||
}
|
||||
|
||||
// Round describes one snapshot transfer handed to a RoundTransport.
|
||||
@@ -90,17 +76,14 @@ type TransferStats struct {
|
||||
BytesVerified int64 `json:"bytes_verified"`
|
||||
BlockDiffFiles int64 `json:"blockdiff_files"`
|
||||
SnapDiffEntries int64 `json:"snapdiff_entries"`
|
||||
// Seconds is the duration of the round from its start to the commit,
|
||||
// including verification and snapshot creation.
|
||||
Seconds float64 `json:"seconds"`
|
||||
}
|
||||
|
||||
// NewEngine returns an Engine for c.Backend and a Closer that releases its
|
||||
// connections. It never silently falls back from native I/O to mounted/rsync I/O.
|
||||
// NewEngine returns an Engine with the native libcephfs backend and a Closer
|
||||
// that releases its connections. Builds without the build tag ceph return an
|
||||
// error.
|
||||
func NewEngine(ctx context.Context, c Config, x Executor, log io.Writer) (Engine, io.Closer, error) {
|
||||
if c.Backend == "native" {
|
||||
return openNativeEngine(ctx, c, x, log)
|
||||
}
|
||||
return Engine{Exec: x, Log: log, Transport: Rsync{Exec: x, Log: log, BandwidthKiB: c.BandwidthKiB}}, nopCloser{}, nil
|
||||
}
|
||||
|
||||
type nopCloser struct{}
|
||||
|
||||
func (nopCloser) Close() error { return nil }
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
type ceph struct {
|
||||
endpoint Endpoint
|
||||
exec Executor
|
||||
native bool
|
||||
}
|
||||
|
||||
func (c ceph) call(ctx context.Context, args ...string) ([]byte, error) {
|
||||
@@ -23,124 +22,151 @@ func (c ceph) call(ctx context.Context, args ...string) ([]byte, error) {
|
||||
if c.endpoint.User != "" {
|
||||
flags = append(flags, "--name", c.endpoint.User)
|
||||
}
|
||||
|
||||
b, err := output(ctx, c.exec, "ceph", append(flags, args...)...)
|
||||
if err != nil {
|
||||
// The first three tokens identify the operation; omit names and metadata
|
||||
// values, which can contain confidential application information.
|
||||
return nil, fmt.Errorf("Ceph %s: %w", strings.Join(args[:min(3, len(args))], " "), err)
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (c ceph) sub(ctx context.Context, op string, extra ...string) ([]byte, error) {
|
||||
args := []string{"fs", "subvolume", op, c.endpoint.Filesystem, c.endpoint.Subvolume}
|
||||
args = append(args, extra...)
|
||||
if c.endpoint.Group != "" {
|
||||
args = append(args, "--group_name", c.endpoint.Group)
|
||||
}
|
||||
|
||||
return c.call(ctx, args...)
|
||||
}
|
||||
|
||||
func (c ceph) snap(ctx context.Context, op, name string, extra ...string) ([]byte, error) {
|
||||
args := []string{"fs", "subvolume", "snapshot", op, c.endpoint.Filesystem, c.endpoint.Subvolume}
|
||||
if name != "" {
|
||||
args = append(args, name)
|
||||
}
|
||||
|
||||
args = append(args, extra...)
|
||||
if c.endpoint.Group != "" {
|
||||
args = append(args, "--group_name", c.endpoint.Group)
|
||||
}
|
||||
|
||||
return c.call(ctx, args...)
|
||||
}
|
||||
|
||||
func (c ceph) snapshotPath(ctx context.Context, name string) (string, error) {
|
||||
b, err := c.snap(ctx, "getpath", name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := strings.TrimSpace(string(b))
|
||||
if c.native {
|
||||
return nativePath(p)
|
||||
}
|
||||
return dataPath(c.endpoint.Mount, p)
|
||||
|
||||
return nativePath(strings.TrimSpace(string(b)))
|
||||
}
|
||||
|
||||
func (c ceph) names(ctx context.Context) ([]string, error) {
|
||||
b, err := c.snap(ctx, "ls", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var list []struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(b, &list); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(list))
|
||||
for _, s := range list {
|
||||
if !validName(s.Name) {
|
||||
return nil, fmt.Errorf("unsupported snapshot name %q", s.Name)
|
||||
}
|
||||
|
||||
names = append(names, s.Name)
|
||||
}
|
||||
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (c ceph) metadata(ctx context.Context, snapshot string) (map[string]string, error) {
|
||||
args := []string{"fs", "subvolume"}
|
||||
if snapshot != "" {
|
||||
args = append(args, "snapshot")
|
||||
}
|
||||
|
||||
args = append(args, "metadata", "ls", c.endpoint.Filesystem, c.endpoint.Subvolume)
|
||||
if snapshot != "" {
|
||||
args = append(args, snapshot)
|
||||
}
|
||||
|
||||
if c.endpoint.Group != "" {
|
||||
args = append(args, "--group_name", c.endpoint.Group)
|
||||
}
|
||||
|
||||
b, err := c.call(ctx, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var m map[string]string
|
||||
err = json.Unmarshal(b, &m)
|
||||
return m, err
|
||||
}
|
||||
|
||||
func (c ceph) setMetadata(ctx context.Context, snapshot string, m map[string]string) error {
|
||||
// Remove obsolete keys too, including keys removed during a catch-up round.
|
||||
old, err := c.metadata(ctx, snapshot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for k := range old {
|
||||
if _, exists := m[k]; exists {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := c.metadataCommand(ctx, snapshot, "rm", k, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for k, v := range m {
|
||||
if ov, ok := old[k]; ok && ov == v {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := c.metadataCommand(ctx, snapshot, "set", k, v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c ceph) metadataCommand(ctx context.Context, snapshot, op, key, value string) error {
|
||||
args := []string{"fs", "subvolume"}
|
||||
if snapshot != "" {
|
||||
args = append(args, "snapshot")
|
||||
}
|
||||
|
||||
args = append(args, "metadata", op, c.endpoint.Filesystem, c.endpoint.Subvolume)
|
||||
if snapshot != "" {
|
||||
args = append(args, snapshot)
|
||||
}
|
||||
|
||||
args = append(args, "--key_name="+key)
|
||||
if op == "set" {
|
||||
args = append(args, "--value="+value)
|
||||
}
|
||||
|
||||
if c.endpoint.Group != "" {
|
||||
args = append(args, "--group_name", c.endpoint.Group)
|
||||
}
|
||||
|
||||
_, err := c.call(ctx, args...)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// removeOwnedSnapshots deletes the completed snapshots that cephmig created
|
||||
// itself, except keep, at source and target. Snapshots of the application
|
||||
// are never touched.
|
||||
//
|
||||
// Every snapshot is first marked Removed in the journal and deleted after
|
||||
// that, so an interrupted run finishes the deletion next time instead of
|
||||
// reporting a vanished snapshot.
|
||||
func removeOwnedSnapshots(ctx context.Context, src, dst ceph, statePath string, s *State, keep string) error {
|
||||
marked := false
|
||||
for i := range s.Snapshots {
|
||||
snap := &s.Snapshots[i]
|
||||
if snap.Owned && snap.Done && !snap.Removed && snap.Name != keep {
|
||||
snap.Removed = true
|
||||
marked = true
|
||||
}
|
||||
}
|
||||
|
||||
if marked {
|
||||
if err := SaveState(statePath, s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, side := range []ceph{dst, src} {
|
||||
names, err := side.names(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, snap := range s.Snapshots {
|
||||
if !snap.Removed || !slices.Contains(names, snap.Name) {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, err = side.snap(ctx, "rm", snap.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cleanup deletes all snapshots cephmig created, at source and target, after
|
||||
// the job is ready for cutover. Afterwards the subvolumes hold only the
|
||||
// snapshots of the application. This includes the final round snapshot, so
|
||||
// run it only after the cutover has been checked.
|
||||
func (e Engine) Cleanup(ctx context.Context, c Config, statePath string) error {
|
||||
if err := c.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if e.Exec == nil {
|
||||
return errors.New("missing executor")
|
||||
}
|
||||
|
||||
abs, err := filepath.Abs(statePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
lock, err := lockFile(abs + ".lock")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer lock.Close()
|
||||
s, err := LoadState(abs)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return errors.New("no migration state; nothing to clean up")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.Phase != "ready-for-cutover" {
|
||||
return fmt.Errorf("cleanup requires phase ready-for-cutover, not %q; run finalize first", s.Phase)
|
||||
}
|
||||
|
||||
inspection, err := e.Inspect(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !sameMigrationIdentity(s.Config, c) || s.SourceFSID != inspection.SourceFSID || s.TargetFSID != inspection.TargetFSID ||
|
||||
s.SourcePath != inspection.SourcePath || s.TargetPath != inspection.TargetPath {
|
||||
return errors.New("config or cluster identity changed; refusing to use migration state")
|
||||
}
|
||||
|
||||
// A completed cleanup has released the claim; do not create it again.
|
||||
if !cleanedUp(s) {
|
||||
claim, err := e.access().Claim(ctx, c, s.TargetFSID, s.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer claim.Close()
|
||||
}
|
||||
|
||||
src, dst := ceph{endpoint: c.Source, exec: e.Exec}, ceph{endpoint: c.Target, exec: e.Exec}
|
||||
s.LiveSnapshot = ""
|
||||
if err = removeOwnedSnapshots(ctx, src, dst, abs, s, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = SaveState(abs, s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Last step: the job no longer protects the target.
|
||||
if err = e.access().Release(ctx, c, s.TargetFSID, s.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.log("cleanup: removed cephmig snapshots and the target claim; state=%s", abs)
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanedUp reports whether Cleanup completed its snapshot removal for s.
|
||||
func cleanedUp(s *State) bool {
|
||||
if s.Phase != "ready-for-cutover" || s.LiveSnapshot != "" {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, snap := range s.Snapshots {
|
||||
if snap.Owned && !snap.Removed {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// snapshotCeph fakes "ceph fs subvolume snapshot ls|rm" for two clusters,
|
||||
// told apart by the --conf argument.
|
||||
type snapshotCeph struct {
|
||||
snaps map[string][]string
|
||||
failRm string
|
||||
removed []string
|
||||
}
|
||||
|
||||
func (f *snapshotCeph) Exec(_ context.Context, out io.Writer, _ string, args ...string) error {
|
||||
conf := args[1]
|
||||
i := slices.Index(args, "snapshot")
|
||||
switch args[i+1] {
|
||||
case "ls":
|
||||
var list []map[string]string
|
||||
for _, n := range f.snaps[conf] {
|
||||
list = append(list, map[string]string{"name": n})
|
||||
}
|
||||
|
||||
return json.NewEncoder(out).Encode(list)
|
||||
case "rm":
|
||||
name := args[i+4]
|
||||
if name == f.failRm {
|
||||
return errors.New("injected failure")
|
||||
}
|
||||
|
||||
f.snaps[conf] = slices.DeleteFunc(f.snaps[conf], func(n string) bool { return n == name })
|
||||
f.removed = append(f.removed, conf+":"+name)
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("unexpected command")
|
||||
}
|
||||
|
||||
func TestRemoveOwnedSnapshots(t *testing.T) {
|
||||
all := []string{"app-1", "cephmig-a", "cephmig-b", "cephmig-c"}
|
||||
newState := func() *State {
|
||||
s := testState()
|
||||
for _, n := range all {
|
||||
s.Snapshots = append(s.Snapshots, Snapshot{Name: n, Owned: n != "app-1", Done: true,
|
||||
CreatedAt: "2026-01-01 00:00:00", TargetCreatedAt: "2026-01-01 00:00:01"})
|
||||
}
|
||||
|
||||
s.LiveSnapshot = "cephmig-c"
|
||||
return s
|
||||
}
|
||||
|
||||
statePath := filepath.Join(t.TempDir(), "state.json")
|
||||
f := &snapshotCeph{snaps: map[string][]string{"src.conf": slices.Clone(all), "dst.conf": slices.Clone(all)}}
|
||||
src := ceph{endpoint: Endpoint{Config: "src.conf", Filesystem: "fs", Subvolume: "v"}, exec: f}
|
||||
dst := ceph{endpoint: Endpoint{Config: "dst.conf", Filesystem: "fs", Subvolume: "v"}, exec: f}
|
||||
|
||||
// An interrupted run leaves the journal marked, and the retry finishes.
|
||||
s := newState()
|
||||
f.failRm = "cephmig-b"
|
||||
if err := removeOwnedSnapshots(context.Background(), src, dst, statePath, s, s.LiveSnapshot); err == nil {
|
||||
t.Fatal("injected failure not reported")
|
||||
}
|
||||
|
||||
loaded, err := LoadState(statePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !loaded.Snapshots[1].Removed || !loaded.Snapshots[2].Removed || loaded.Snapshots[3].Removed || loaded.Snapshots[0].Removed {
|
||||
t.Fatalf("journal marks: %+v", loaded.Snapshots)
|
||||
}
|
||||
|
||||
f.failRm = ""
|
||||
if err := removeOwnedSnapshots(context.Background(), src, dst, statePath, loaded, loaded.LiveSnapshot); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for conf, names := range f.snaps {
|
||||
if !slices.Equal(names, []string{"app-1", "cephmig-c"}) {
|
||||
t.Fatalf("%s keeps %v", conf, names)
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup removes the base too, but never application snapshots.
|
||||
loaded.LiveSnapshot = ""
|
||||
if err := removeOwnedSnapshots(context.Background(), src, dst, statePath, loaded, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for conf, names := range f.snaps {
|
||||
if !slices.Equal(names, []string{"app-1"}) {
|
||||
t.Fatalf("%s keeps %v", conf, names)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := LoadState(statePath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateRejectsInvalidRemoval(t *testing.T) {
|
||||
done := Snapshot{Name: "a", Owned: true, Done: true, Removed: true, CreatedAt: "x", TargetCreatedAt: "y"}
|
||||
for name, modify := range map[string]func(*State){
|
||||
"application snapshot": func(s *State) { d := done; d.Owned = false; s.Snapshots = []Snapshot{d} },
|
||||
"incomplete": func(s *State) { s.Snapshots = []Snapshot{{Name: "a", Owned: true, Removed: true}} },
|
||||
"removed live base": func(s *State) { s.Snapshots = []Snapshot{done}; s.LiveSnapshot = "a" },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "state.json")
|
||||
s := testState()
|
||||
modify(s)
|
||||
if err := SaveState(p, s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := LoadState(p); err == nil {
|
||||
t.Fatal("accepted invalid removal")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanedUp(t *testing.T) {
|
||||
s := testState()
|
||||
s.Phase = "ready-for-cutover"
|
||||
s.Snapshots = []Snapshot{{Name: "app", Done: true}, {Name: "cephmig-x", Owned: true, Done: true, Final: true}}
|
||||
s.LiveSnapshot = "cephmig-x"
|
||||
if cleanedUp(s) {
|
||||
t.Fatal("ready job reported as cleaned up")
|
||||
}
|
||||
|
||||
s.LiveSnapshot = ""
|
||||
s.Snapshots[1].Removed = true
|
||||
if !cleanedUp(s) {
|
||||
t.Fatal("cleaned job not recognized")
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// Endpoint describes how to reach one side of a migration: the Ceph
|
||||
// client identity and configuration, the subvolume and, for the rsync
|
||||
// backend, the local mount of the CephFS filesystem root.
|
||||
// client identity and configuration and the subvolume.
|
||||
type Endpoint struct {
|
||||
User string `json:"user,omitempty"`
|
||||
Config string `json:"config"`
|
||||
@@ -20,11 +19,10 @@ type Endpoint struct {
|
||||
Filesystem string `json:"filesystem"`
|
||||
Group string `json:"group"`
|
||||
Subvolume string `json:"subvolume"`
|
||||
Mount string `json:"mount,omitempty"`
|
||||
}
|
||||
|
||||
// Config is the JSON migration configuration read by ReadConfig.
|
||||
// Backend selects "native" (libcephfs) or "rsync" (the default).
|
||||
// Backend is optional; the only backend is "native" (libcephfs).
|
||||
type Config struct {
|
||||
Backend string `json:"backend,omitempty"`
|
||||
Workers int `json:"workers,omitempty"`
|
||||
@@ -41,22 +39,27 @@ func ReadConfig(path string) (Config, error) {
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
|
||||
defer f.Close()
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
|
||||
if !st.Mode().IsRegular() || st.Size() > 1<<20 {
|
||||
return c, errors.New("config must be a regular file of at most 1 MiB")
|
||||
}
|
||||
|
||||
dec := json.NewDecoder(io.LimitReader(f, 1<<20))
|
||||
dec.DisallowUnknownFields()
|
||||
if err = dec.Decode(&c); err != nil {
|
||||
return c, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
|
||||
if err = dec.Decode(new(any)); !errors.Is(err, io.EOF) {
|
||||
return c, errors.New("config must contain exactly one JSON object")
|
||||
}
|
||||
|
||||
return c, c.Validate()
|
||||
}
|
||||
|
||||
@@ -68,12 +71,14 @@ func validName(s string) bool {
|
||||
// Validate checks names, paths, worker and bandwidth limits and reports
|
||||
// the first problem found.
|
||||
func (c Config) Validate() error {
|
||||
if c.Backend != "" && c.Backend != "rsync" && c.Backend != "native" {
|
||||
return errors.New("backend must be native or rsync")
|
||||
if c.Backend != "" && c.Backend != "native" {
|
||||
return errors.New(`backend must be "native"; the rsync backend was removed`)
|
||||
}
|
||||
|
||||
if c.Workers < 0 || c.Workers > 64 {
|
||||
return errors.New("workers must be between 0 and 64 (0 selects the default)")
|
||||
}
|
||||
|
||||
for _, p := range []struct {
|
||||
name string
|
||||
e Endpoint
|
||||
@@ -81,59 +86,27 @@ func (c Config) Validate() error {
|
||||
if p.e.User != "" && (!strings.HasPrefix(p.e.User, "client.") || !validName(p.e.User)) {
|
||||
return fmt.Errorf("%s: user must be a client identity", p.name)
|
||||
}
|
||||
|
||||
for _, s := range []string{p.e.Filesystem, p.e.Subvolume} {
|
||||
if !validName(s) {
|
||||
return fmt.Errorf("%s: invalid filesystem or subvolume name", p.name)
|
||||
}
|
||||
}
|
||||
|
||||
if p.e.Group != "" && !validName(p.e.Group) {
|
||||
return fmt.Errorf("%s: invalid group", p.name)
|
||||
}
|
||||
paths := []string{p.e.Config, p.e.Keyring}
|
||||
if c.Backend != "native" || p.e.Mount != "" {
|
||||
paths = append(paths, p.e.Mount)
|
||||
}
|
||||
for _, path := range paths {
|
||||
|
||||
for _, path := range []string{p.e.Config, p.e.Keyring} {
|
||||
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
|
||||
return fmt.Errorf("%s: paths must be absolute and clean: %q", p.name, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if c.BandwidthKiB < 0 || c.BandwidthKiB > (1<<63-1)/1024 {
|
||||
return errors.New("bandwidth_kib must be nonnegative and fit in bytes per second")
|
||||
}
|
||||
if c.Backend != "native" && overlaps(c.Source.Mount, c.Target.Mount) {
|
||||
return errors.New("source and target mounts must not overlap")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func beneath(root, path string) bool {
|
||||
rel, err := filepath.Rel(root, path)
|
||||
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
|
||||
}
|
||||
func overlaps(a, b string) bool { return beneath(a, b) || beneath(b, a) }
|
||||
|
||||
// dataPath resolves cephPath to a real directory below the filesystem mount
|
||||
// root. No symlink component is permitted, including in the mount path.
|
||||
func dataPath(root, cephPath string) (string, error) {
|
||||
if !filepath.IsAbs(cephPath) || filepath.Clean(cephPath) != cephPath || cephPath == "/" {
|
||||
return "", fmt.Errorf("invalid Ceph path %q", cephPath)
|
||||
}
|
||||
p := filepath.Join(root, strings.TrimPrefix(cephPath, "/"))
|
||||
resolved, err := filepath.EvalSymlinks(p)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if resolved != p || !beneath(root, p) {
|
||||
return "", fmt.Errorf("path escapes mount or contains symlinks: %q", p)
|
||||
}
|
||||
st, err := os.Stat(p)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !st.IsDir() {
|
||||
return "", fmt.Errorf("not a directory: %s", p)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
@@ -9,14 +9,15 @@ import (
|
||||
)
|
||||
|
||||
func testConfig() Config {
|
||||
return Config{Source: Endpoint{Config: "/clusters/a/ceph.conf", Keyring: "/clusters/a/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "source", Mount: "/mnt/a"},
|
||||
Target: Endpoint{Config: "/clusters/b/ceph.conf", Keyring: "/clusters/b/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "target", Mount: "/mnt/b"}}
|
||||
return Config{Source: Endpoint{Config: "/clusters/a/ceph.conf", Keyring: "/clusters/a/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "source"},
|
||||
Target: Endpoint{Config: "/clusters/b/ceph.conf", Keyring: "/clusters/b/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "target"}}
|
||||
}
|
||||
|
||||
func TestConfigRejectsUnsafePathsAndNames(t *testing.T) {
|
||||
for name, modify := range map[string]func(*Config){
|
||||
"overlap": func(c *Config) { c.Target.Mount = "/mnt/a/nested" },
|
||||
"relative": func(c *Config) { c.Source.Mount = "relative" },
|
||||
"unclean": func(c *Config) { c.Source.Mount = "/mnt/a/../a" },
|
||||
"relative": func(c *Config) { c.Source.Config = "relative" },
|
||||
"unclean": func(c *Config) { c.Target.Keyring = "/clusters/b/../b/keyring" },
|
||||
"rsync-backend": func(c *Config) { c.Backend = "rsync" },
|
||||
"flag-name": func(c *Config) { c.Target.Subvolume = "--force" },
|
||||
"traversal": func(c *Config) { c.Source.Group = "../outside" },
|
||||
"negative-rate": func(c *Config) { c.BandwidthKiB = -1 },
|
||||
@@ -33,6 +34,7 @@ func TestConfigRejectsUnsafePathsAndNames(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if err := testConfig().Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -41,20 +43,28 @@ func TestConfigRejectsUnsafePathsAndNames(t *testing.T) {
|
||||
func TestNativeConfigAndResumeSettings(t *testing.T) {
|
||||
c := testConfig()
|
||||
c.Backend = "native"
|
||||
c.Source.Mount, c.Target.Mount = "", ""
|
||||
if err := c.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
implicit := c
|
||||
implicit.Backend = ""
|
||||
if !sameMigrationIdentity(c, implicit) {
|
||||
t.Fatal(`backend "" and "native" differ in resume identity`)
|
||||
}
|
||||
|
||||
changed := c
|
||||
changed.Workers, changed.BandwidthKiB = 32, 100000
|
||||
if !sameMigrationIdentity(c, changed) {
|
||||
t.Fatal("runtime settings invalidated resume identity")
|
||||
}
|
||||
|
||||
changed.Target.Subvolume = "another"
|
||||
if sameMigrationIdentity(c, changed) {
|
||||
t.Fatal("accepted a different target")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrictJSONConfig(t *testing.T) {
|
||||
b, _ := json.Marshal(testConfig())
|
||||
for name, data := range map[string]string{"unknown": strings.TrimSuffix(string(b), "}") + ", \"typo\": true}", "trailing": string(b) + " {}", "truncated": string(b[:len(b)-2])} {
|
||||
@@ -63,37 +73,24 @@ func TestStrictJSONConfig(t *testing.T) {
|
||||
if err := os.WriteFile(p, []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := ReadConfig(p); err == nil {
|
||||
t.Fatal("accepted invalid JSON config")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestDataPathRejectsEscapeAndSymlink(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(root, "real"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(t.TempDir(), filepath.Join(root, "link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{"/../escape", "/real/../real", "relative", "/link", "/"} {
|
||||
if _, err := dataPath(root, path); err == nil {
|
||||
t.Fatalf("accepted %q", path)
|
||||
}
|
||||
}
|
||||
if got, err := dataPath(root, "/real"); err != nil || got != filepath.Join(root, "real") {
|
||||
t.Fatalf("got %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateDirectoriesNeverFollowsSymlink(t *testing.T) {
|
||||
root, outside := t.TempDir(), t.TempDir()
|
||||
if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := privateDirectories(filepath.Join(root, "link", "new")); err == nil {
|
||||
t.Fatal("followed symlink")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(outside, "new")); !os.IsNotExist(err) {
|
||||
t.Fatal("created directory through symlink")
|
||||
}
|
||||
|
||||
@@ -4,6 +4,6 @@
|
||||
// A migration is a sequence of rounds. Each round creates or picks a source
|
||||
// snapshot, copies it with a Transport, verifies the target and publishes a
|
||||
// target snapshot of the same name. Progress is recorded in a State journal so
|
||||
// that every step can be resumed. Two backends exist: rsync over mounted
|
||||
// filesystems and a native libcephfs transport (build tag ceph).
|
||||
// that every step can be resumed. Data moves through libcephfs (build tag
|
||||
// ceph); no mount and no rsync are needed.
|
||||
package migration
|
||||
+121
-130
@@ -15,12 +15,11 @@ import (
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Engine runs the snapshot-based migration workflow. Transport moves the
|
||||
// data; Access, if nil, defaults to mounted filesystem access.
|
||||
// data; Access reaches both clusters for everything else. Both are required.
|
||||
type Engine struct {
|
||||
Exec Executor
|
||||
Transport Transport
|
||||
@@ -66,80 +65,26 @@ func queryEndpoint(ctx context.Context, c ceph) (string, endpointInfo, error) {
|
||||
if err != nil {
|
||||
return "", info, err
|
||||
}
|
||||
|
||||
fsid := strings.TrimSpace(string(b))
|
||||
if len(fsid) != 36 {
|
||||
return "", info, errors.New("invalid cluster FSID")
|
||||
}
|
||||
|
||||
b, err = c.sub(ctx, "info")
|
||||
if err != nil {
|
||||
return "", info, err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(b, &info); err != nil {
|
||||
return "", info, err
|
||||
}
|
||||
|
||||
if info.State != "complete" || !info.CaseSensitive || info.Normalization != "none" || info.Encryption != "" || info.Earmark != "" {
|
||||
return "", info, errors.New("subvolume must be complete, case-sensitive, unencrypted, without normalization or earmark")
|
||||
}
|
||||
return fsid, info, nil
|
||||
}
|
||||
func endpoint(ctx context.Context, c ceph) (string, endpointInfo, string, error) {
|
||||
fsid, info, err := queryEndpoint(ctx, c)
|
||||
if err != nil {
|
||||
return "", info, "", err
|
||||
}
|
||||
path, err := dataPath(c.endpoint.Mount, info.Path)
|
||||
if err != nil {
|
||||
return "", info, "", err
|
||||
}
|
||||
mountedFSID, err := xattr(path, "ceph.cluster_fsid")
|
||||
if err != nil {
|
||||
return "", info, "", fmt.Errorf("cannot verify mount FSID: %w", err)
|
||||
}
|
||||
if string(mountedFSID) != fsid {
|
||||
return "", info, "", fmt.Errorf("mount belongs to a different cluster than the configured Ceph endpoint")
|
||||
}
|
||||
return fsid, info, path, err
|
||||
}
|
||||
|
||||
func inspectMounted(ctx context.Context, c Config, x Executor) (*Inspection, error) {
|
||||
if err := c.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := checkMount(c.Source.Mount, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := checkMount(c.Target.Mount, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
src, dst := ceph{endpoint: c.Source, exec: x}, ceph{endpoint: c.Target, exec: x}
|
||||
sf, si, sp, err := endpoint(ctx, src)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("source: %w", err)
|
||||
}
|
||||
tf, _, tp, err := endpoint(ctx, dst)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("target: %w", err)
|
||||
}
|
||||
if sf == tf {
|
||||
return nil, errors.New("source and target must be different clusters")
|
||||
}
|
||||
var ss, ts syscall.Stat_t
|
||||
if err = syscall.Stat(sp, &ss); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = syscall.Stat(tp, &ts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ss.Dev == ts.Dev {
|
||||
return nil, errors.New("source and target are on the same mounted filesystem")
|
||||
}
|
||||
names, err := src.names(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inspection := &Inspection{SourceFSID: sf, TargetFSID: tf, SourcePath: sp, TargetPath: tp, SourceBytes: si.BytesUsed, SourceSnapshots: names}
|
||||
inspection.Notes = []string{SnapshotIdentityNote}
|
||||
return inspection, nil
|
||||
return fsid, info, nil
|
||||
}
|
||||
|
||||
func newID() (string, error) {
|
||||
@@ -147,73 +92,15 @@ func newID() (string, error) {
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
func emptyDirectory(path string) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
entries, err := f.ReadDir(1)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return err
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
return fmt.Errorf("new migration requires empty target subvolume: %s", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimTarget locks the target subvolume for the job id. The claim is outside
|
||||
// the migrated tree and survives deletion of the local journal. O_EXCL prevents two different jobs from adopting the same target.
|
||||
func claimTarget(root, fsid string, ep Endpoint, id string) (*os.File, error) {
|
||||
// claimName is the file name of the claim for the target subvolume ep in
|
||||
// the cluster fsid, below .cephmig/claims at the file system root.
|
||||
func claimName(fsid string, ep Endpoint) string {
|
||||
key := sha256.Sum256([]byte(fsid + "\x00" + ep.Filesystem + "\x00" + ep.Group + "\x00" + ep.Subvolume))
|
||||
dir := filepath.Join(root, ".cephmig", "claims")
|
||||
if err := privateDirectories(dir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(dir)
|
||||
if err != nil || resolved != dir {
|
||||
return nil, errors.New("claim directory contains symlinks")
|
||||
}
|
||||
path := filepath.Join(dir, hex.EncodeToString(key[:]))
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
|
||||
if err == nil {
|
||||
if _, err = f.WriteString(id + "\n"); err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
if closeErr := f.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrExist) {
|
||||
return nil, err
|
||||
}
|
||||
st, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !st.Mode().IsRegular() {
|
||||
return nil, errors.New("target claim is not a regular file")
|
||||
}
|
||||
f, err = os.OpenFile(path, os.O_RDWR|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("target is being migrated by another process: %w", err)
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(f, 256))
|
||||
if err != nil || string(b) != id+"\n" {
|
||||
f.Close()
|
||||
return nil, errors.New("target is claimed by a different job or claim is incomplete; preserve the original state file")
|
||||
}
|
||||
return f, nil
|
||||
return hex.EncodeToString(key[:])
|
||||
}
|
||||
|
||||
func snapshotDetails(ctx context.Context, src ceph, name string) (Snapshot, error) {
|
||||
@@ -223,15 +110,19 @@ func snapshotDetails(ctx context.Context, src ceph, name string) (Snapshot, erro
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
|
||||
var info struct {
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(b, &info); err != nil {
|
||||
return s, err
|
||||
}
|
||||
|
||||
if _, err = time.Parse("2006-01-02 15:04:05.999999999", info.CreatedAt); err != nil {
|
||||
return s, fmt.Errorf("invalid creation time for %s: %w", name, err)
|
||||
}
|
||||
|
||||
s.CreatedAt = info.CreatedAt
|
||||
s.Metadata, err = src.metadata(ctx, name)
|
||||
return s, err
|
||||
@@ -245,79 +136,103 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
|
||||
if err := c.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.log("note: %s", SnapshotIdentityNote)
|
||||
if os.Geteuid() != 0 {
|
||||
return errors.New("migration requires root for numeric ownership, ACLs and xattrs")
|
||||
}
|
||||
if e.Exec == nil || e.Transport == nil {
|
||||
return errors.New("missing executor or transport")
|
||||
|
||||
if e.Exec == nil || e.Transport == nil || e.Access == nil {
|
||||
return errors.New("missing executor, transport or access")
|
||||
}
|
||||
|
||||
abs, err := filepath.Abs(statePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Backend != "native" && (overlaps(filepath.Dir(abs), c.Source.Mount) || overlaps(filepath.Dir(abs), c.Target.Mount)) {
|
||||
return errors.New("state directory must be outside the CephFS mounts")
|
||||
}
|
||||
|
||||
if err = privateDirectories(filepath.Dir(abs)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resolved, err := filepath.EvalSymlinks(filepath.Dir(abs))
|
||||
if err != nil || resolved != filepath.Dir(abs) {
|
||||
return errors.New("state directory must not contain symlinks")
|
||||
}
|
||||
|
||||
lock, err := lockFile(abs + ".lock")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer lock.Close()
|
||||
inspection, err := e.Inspect(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
src, dst := ceph{endpoint: c.Source, exec: e.Exec, native: c.Backend == "native"}, ceph{endpoint: c.Target, exec: e.Exec, native: c.Backend == "native"}
|
||||
|
||||
src, dst := ceph{endpoint: c.Source, exec: e.Exec}, ceph{endpoint: c.Target, exec: e.Exec}
|
||||
s, err := LoadState(abs)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if err = e.access().Empty(ctx, inspection.TargetPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
names, err := dst.names(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(names) != 0 {
|
||||
return errors.New("new migration requires a target without snapshots")
|
||||
}
|
||||
|
||||
metadata, err := dst.metadata(ctx, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(metadata) != 0 {
|
||||
return errors.New("new migration requires a target without custom metadata")
|
||||
}
|
||||
|
||||
id, err := newID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s = &State{
|
||||
Version: stateVersion, ID: id, Config: c,
|
||||
SourceFSID: inspection.SourceFSID, TargetFSID: inspection.TargetFSID,
|
||||
SourcePath: inspection.SourcePath, TargetPath: inspection.TargetPath,
|
||||
Phase: "syncing", Notes: []string{SnapshotIdentityNote},
|
||||
}
|
||||
|
||||
if err = SaveState(abs, s); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !sameMigrationIdentity(s.Config, c) || s.SourceFSID != inspection.SourceFSID || s.TargetFSID != inspection.TargetFSID || s.SourcePath != inspection.SourcePath || s.TargetPath != inspection.TargetPath {
|
||||
return errors.New("config or cluster identity changed; refusing to reuse migration state")
|
||||
}
|
||||
|
||||
if cleanedUp(s) {
|
||||
if final {
|
||||
e.log("job is cleaned up; nothing to do")
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("job is cleaned up; sync is no longer allowed")
|
||||
}
|
||||
|
||||
claim, err := e.access().Claim(ctx, c, s.TargetFSID, s.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer claim.Close()
|
||||
s.Config = c
|
||||
if !slices.Contains(s.Notes, SnapshotIdentityNote) {
|
||||
@@ -326,16 +241,20 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if s.Phase == "ready-for-cutover" {
|
||||
if !final {
|
||||
return errors.New("job is ready for cutover; sync is no longer allowed")
|
||||
}
|
||||
|
||||
e.log("already ready for cutover; no new source snapshot created")
|
||||
return nil
|
||||
}
|
||||
|
||||
if s.Phase != "syncing" {
|
||||
return fmt.Errorf("unsupported job phase %q", s.Phase)
|
||||
}
|
||||
|
||||
known := make(map[string]bool, len(s.Snapshots))
|
||||
finalPending := false
|
||||
for _, snap := range s.Snapshots {
|
||||
@@ -344,133 +263,178 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
|
||||
finalPending = true
|
||||
}
|
||||
}
|
||||
|
||||
if finalPending && !final {
|
||||
return errors.New("a final round is pending; resume using finalize while writers remain stopped")
|
||||
}
|
||||
|
||||
targetNames, err := dst.names(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, name := range targetNames {
|
||||
if !known[name] {
|
||||
return fmt.Errorf("unowned target snapshot %q; refusing to overwrite target", name)
|
||||
}
|
||||
}
|
||||
|
||||
// Discover newly created application snapshots on every invocation.
|
||||
var discovered []Snapshot
|
||||
for _, name := range inspection.SourceSnapshots {
|
||||
if known[name] {
|
||||
continue
|
||||
}
|
||||
|
||||
snap, err := snapshotDetails(ctx, src, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
discovered = append(discovered, snap)
|
||||
}
|
||||
|
||||
sort.Slice(discovered, func(i, j int) bool {
|
||||
if discovered[i].CreatedAt == discovered[j].CreatedAt {
|
||||
return discovered[i].Name < discovered[j].Name
|
||||
}
|
||||
|
||||
return discovered[i].CreatedAt < discovered[j].CreatedAt
|
||||
})
|
||||
|
||||
s.Snapshots = append(s.Snapshots, discovered...)
|
||||
if err = SaveState(abs, s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Resume all intent records before capturing another live snapshot.
|
||||
for i := range s.Snapshots {
|
||||
if s.Snapshots[i].Removed {
|
||||
continue
|
||||
}
|
||||
|
||||
if s.Snapshots[i].Done {
|
||||
snap := &s.Snapshots[i]
|
||||
if !slices.Contains(targetNames, snap.Name) {
|
||||
return fmt.Errorf("completed target snapshot %q disappeared", snap.Name)
|
||||
}
|
||||
|
||||
info, err := snapshotDetails(ctx, dst, snap.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.CreatedAt != snap.TargetCreatedAt {
|
||||
return fmt.Errorf("completed target snapshot %q was replaced", snap.Name)
|
||||
}
|
||||
|
||||
if slices.Contains(inspection.SourceSnapshots, snap.Name) {
|
||||
info, err = snapshotDetails(ctx, src, snap.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.CreatedAt != snap.CreatedAt {
|
||||
return fmt.Errorf("completed source snapshot %q was replaced", snap.Name)
|
||||
}
|
||||
|
||||
if err = dst.setMetadata(ctx, snap.Name, info.Metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
snap.Metadata = info.Metadata
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if err := e.transfer(ctx, src, dst, inspection.TargetPath, abs, s, i); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
id, err := newID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.Snapshots = append(s.Snapshots, Snapshot{Name: "cephmig-" + s.ID[:12] + "-" + id[:12], Owned: true, Final: final})
|
||||
if err = SaveState(abs, s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = e.transfer(ctx, src, dst, inspection.TargetPath, abs, s, len(s.Snapshots)-1); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Only the newest round snapshot serves as base for the next round.
|
||||
if err = removeOwnedSnapshots(ctx, src, dst, abs, s, s.LiveSnapshot); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
metadata, err := src.metadata(ctx, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = dst.setMetadata(ctx, "", metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if final {
|
||||
// Every source snapshot visible at finalization must have a completed record.
|
||||
names, err := src.names(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
completed := map[string]bool{}
|
||||
for _, snap := range s.Snapshots {
|
||||
if snap.Done {
|
||||
completed[snap.Name] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range names {
|
||||
if !completed[name] {
|
||||
return fmt.Errorf("source snapshot inventory changed during finalization (%s); retry finalize", name)
|
||||
}
|
||||
}
|
||||
|
||||
last := s.Snapshots[len(s.Snapshots)-1]
|
||||
if !last.Final {
|
||||
return errors.New("final snapshot is not the last transferred snapshot; retry requires operator review")
|
||||
}
|
||||
|
||||
path, err := src.snapshotPath(ctx, last.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = e.Transport.Verify(ctx, path, inspection.TargetPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = e.access().Verify(ctx, path, inspection.TargetPath, filepath.Dir(abs)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.Phase = "ready-for-cutover"
|
||||
}
|
||||
|
||||
if err = SaveState(abs, s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.log("phase=%s snapshots=%d state=%s", s.Phase, len(s.Snapshots), abs)
|
||||
return nil
|
||||
}
|
||||
|
||||
func sameMigrationIdentity(a, b Config) bool {
|
||||
a.Workers, b.Workers = 0, 0
|
||||
a.BandwidthKiB, b.BandwidthKiB = 0, 0
|
||||
// "" and "native" select the same backend.
|
||||
a.Backend, b.Backend = "", ""
|
||||
return reflect.DeepEqual(a, b)
|
||||
}
|
||||
|
||||
@@ -481,33 +445,41 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !slices.Contains(names, snap.Name) {
|
||||
if !snap.Owned || snap.CreatedAt != "" {
|
||||
return fmt.Errorf("source snapshot %q disappeared before transfer", snap.Name)
|
||||
}
|
||||
|
||||
if _, err = src.snap(ctx, "create", snap.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
details, err := snapshotDetails(ctx, src, snap.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if snap.CreatedAt != "" && snap.CreatedAt != details.CreatedAt {
|
||||
return fmt.Errorf("source snapshot %q was replaced", snap.Name)
|
||||
}
|
||||
|
||||
snap.CreatedAt, snap.Metadata = details.CreatedAt, details.Metadata
|
||||
if err = SaveState(statePath, s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
from, err := src.snapshotPath(ctx, snap.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetNames, err := dst.names(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
aware, isNative := e.Transport.(RoundTransport)
|
||||
existed := slices.Contains(targetNames, snap.Name)
|
||||
if isNative {
|
||||
@@ -518,10 +490,12 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err = aware.BeginRound(ctx, round); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
created := false
|
||||
if !existed || isNative {
|
||||
// Clearing this durable marker before any target mutation makes interrupted
|
||||
@@ -530,65 +504,82 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s
|
||||
if err = SaveState(statePath, s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.log("snapshot=%s: copying", snap.Name)
|
||||
if err = e.access().Prepare(ctx, from, target, filepath.Dir(statePath)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = e.Transport.Copy(ctx, from, target); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = e.access().Apply(ctx, from, target); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.log("snapshot=%s: verifying before publication", snap.Name)
|
||||
if err = e.Transport.Verify(ctx, from, target); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = e.access().Verify(ctx, from, target, filepath.Dir(statePath)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !existed {
|
||||
if _, err = dst.snap(ctx, "create", snap.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
created = true
|
||||
}
|
||||
}
|
||||
|
||||
// A crash may have occurred between snapshot creation and the state commit.
|
||||
// Never trust an existing snapshot solely because its name matches.
|
||||
to, err := dst.snapshotPath(ctx, snap.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if isNative && created {
|
||||
aware.Published(to)
|
||||
}
|
||||
|
||||
if err = e.Transport.Verify(ctx, from, to); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = e.access().Verify(ctx, from, to, filepath.Dir(statePath)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = dst.setMetadata(ctx, snap.Name, snap.Metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetInfo, err := snapshotDetails(ctx, dst, snap.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
snap.TargetCreatedAt = targetInfo.CreatedAt
|
||||
if isNative {
|
||||
if err = aware.Commit(ctx, snap.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stats := aware.Statistics()
|
||||
snap.Stats = &stats
|
||||
}
|
||||
|
||||
snap.Done = true
|
||||
s.LiveSnapshot = snap.Name
|
||||
if err = SaveState(statePath, s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.log("snapshot=%s: verified and committed", snap.Name)
|
||||
return nil
|
||||
}
|
||||
@@ -2,14 +2,6 @@ package migration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
bolt "go.etcd.io/bbolt"
|
||||
@@ -27,11 +19,13 @@ func openLinkIndex(path string) (*linkIndex, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tx, err := db.Begin(true)
|
||||
if err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, name := range []string{"source", "target"} {
|
||||
if _, err = tx.CreateBucket([]byte(name)); err != nil {
|
||||
tx.Rollback()
|
||||
@@ -39,14 +33,18 @@ func openLinkIndex(path string) (*linkIndex, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &linkIndex{db: db, tx: tx}, nil
|
||||
}
|
||||
|
||||
func (x *linkIndex) close() error {
|
||||
if x.tx != nil {
|
||||
_ = x.tx.Rollback()
|
||||
}
|
||||
|
||||
return x.db.Close()
|
||||
}
|
||||
|
||||
func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) {
|
||||
b := x.tx.Bucket([]byte(bucket))
|
||||
old := b.Get(key[:])
|
||||
@@ -58,6 +56,7 @@ func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) {
|
||||
} else {
|
||||
same = bytes.Equal(old, value[:])
|
||||
}
|
||||
|
||||
x.observations++
|
||||
// Limit dirty transaction state; the complete relation stays on disk.
|
||||
if x.observations%4096 == 0 {
|
||||
@@ -66,121 +65,12 @@ func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) {
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
x.tx, err = x.db.Begin(true)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
return same, nil
|
||||
}
|
||||
func inodeIdentity(info os.FileInfo) ([16]byte, uint64, error) {
|
||||
var key [16]byte
|
||||
st, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return key, 0, errors.New("missing Linux inode information")
|
||||
}
|
||||
binary.BigEndian.PutUint64(key[:8], uint64(st.Dev))
|
||||
binary.BigEndian.PutUint64(key[8:], st.Ino)
|
||||
return key, uint64(st.Nlink), nil
|
||||
}
|
||||
|
||||
// hardlinkTopology compares the hard-link groups of src and dst.
|
||||
// In repair mode it removes only excess target hardlinks. Missing paths are then
|
||||
// recreated by the copy backend. In verification mode check both directions:
|
||||
// source groups must stay joined, and unrelated source files must stay separate.
|
||||
func hardlinkTopology(ctx context.Context, src, dst, scratchParent string, repair bool) (result error) {
|
||||
scratch, err := os.MkdirTemp(scratchParent, ".cephmig-links-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(scratch)
|
||||
index, err := openLinkIndex(filepath.Join(scratch, "index.bolt"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if err := index.close(); result == nil {
|
||||
result = err
|
||||
}
|
||||
}()
|
||||
targetPath := func(path string) (string, error) {
|
||||
rel, err := filepath.Rel(src, path)
|
||||
if err != nil || !beneath(src, path) {
|
||||
return "", fmt.Errorf("hardlink path outside source: %s", path)
|
||||
}
|
||||
return filepath.Join(dst, rel), nil
|
||||
}
|
||||
visitDir := func(path string) error {
|
||||
target, err := targetPath(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Lstat(target)
|
||||
if repair && (errors.Is(err, os.ErrNotExist) || (err == nil && !st.IsDir())) {
|
||||
// Never follow a target symlink directory, even when its referent exists.
|
||||
return fs.SkipDir
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !st.IsDir() {
|
||||
return fmt.Errorf("target directory changed type: %s", target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
visitFile := func(path string, sourceInfo os.FileInfo) error {
|
||||
if !sourceInfo.Mode().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
target, err := targetPath(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targetInfo, err := os.Lstat(target)
|
||||
if repair && errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !targetInfo.Mode().IsRegular() {
|
||||
if repair {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("hardlink target is not a regular file: %s", target)
|
||||
}
|
||||
sourceKey, sourceLinks, err := inodeIdentity(sourceInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targetKey, targetLinks, err := inodeIdentity(targetInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !repair && sourceLinks > 1 {
|
||||
same, err := index.observe("source", sourceKey, targetKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !same {
|
||||
return fmt.Errorf("source hardlink group was split at %s", target)
|
||||
}
|
||||
}
|
||||
if targetLinks > 1 {
|
||||
same, err := index.observe("target", targetKey, sourceKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !same {
|
||||
if !repair {
|
||||
return fmt.Errorf("unrelated source files became hardlinked at %s", target)
|
||||
}
|
||||
if err := os.Remove(target); err != nil {
|
||||
return fmt.Errorf("break obsolete target hardlink: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return walkTree(ctx, src, visitDir, visitFile)
|
||||
}
|
||||
@@ -1,126 +1,17 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func mustWrite(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte("identical contents"), 0640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func TestHardlinkTopologyHandlesSplitAndRejoin(t *testing.T) {
|
||||
if _, err := exec.LookPath("rsync"); err != nil {
|
||||
t.Skip("rsync is not installed")
|
||||
}
|
||||
ctx := context.Background()
|
||||
src, dst, scratch := t.TempDir(), t.TempDir(), t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(src, "d"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, b := filepath.Join(src, "a"), filepath.Join(src, "d", "b")
|
||||
mustWrite(t, a)
|
||||
if err := os.Link(a, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := Rsync{Exec: Process{Stderr: io.Discard}, Log: io.Discard}
|
||||
if err := r.Copy(ctx, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Break one source link without changing bytes, mode or mtime. Rsync -H
|
||||
// alone can leave an extra target link in this exact case.
|
||||
old, err := os.Stat(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.Remove(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mustWrite(t, b)
|
||||
if err = os.Chtimes(b, old.ModTime(), old.ModTime()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = hardlinkTopology(ctx, src, dst, scratch, false); err == nil {
|
||||
t.Fatal("extra destination hardlink was missed")
|
||||
}
|
||||
if err = hardlinkTopology(ctx, src, dst, scratch, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = r.Copy(ctx, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
x, _ := os.Stat(filepath.Join(dst, "a"))
|
||||
y, _ := os.Stat(filepath.Join(dst, "d", "b"))
|
||||
if os.SameFile(x, y) {
|
||||
t.Fatal("split source files remained linked")
|
||||
}
|
||||
if err = os.Remove(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.Link(a, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = hardlinkTopology(ctx, src, dst, scratch, false); err == nil {
|
||||
t.Fatal("missing target hardlink was missed")
|
||||
}
|
||||
if err = hardlinkTopology(ctx, src, dst, scratch, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = r.Copy(ctx, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := os.ReadDir(scratch)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("scratch indexes were not removed")
|
||||
}
|
||||
}
|
||||
func TestHardlinkRepairDoesNotFollowTargetSymlinkDirectories(t *testing.T) {
|
||||
src, dst, outside, scratch := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(src, "d"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mustWrite(t, filepath.Join(src, "d", "a"))
|
||||
mustWrite(t, filepath.Join(src, "d", "b"))
|
||||
mustWrite(t, filepath.Join(outside, "a"))
|
||||
if err := os.Link(filepath.Join(outside, "a"), filepath.Join(outside, "b")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(dst, "d")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := hardlinkTopology(context.Background(), src, dst, scratch, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, err := os.Stat(filepath.Join(outside, "a"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.Stat(filepath.Join(outside, "b"))
|
||||
if err != nil || !os.SameFile(a, b) {
|
||||
t.Fatal("repair touched files outside the target tree")
|
||||
}
|
||||
}
|
||||
func TestHardlinkDiskIndexSurvivesBatchBoundaries(t *testing.T) {
|
||||
x, err := openLinkIndex(filepath.Join(t.TempDir(), "index"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer x.close()
|
||||
for i := uint64(0); i < 5000; i++ {
|
||||
var key, value [16]byte
|
||||
@@ -131,11 +22,13 @@ func TestHardlinkDiskIndexSurvivesBatchBoundaries(t *testing.T) {
|
||||
t.Fatalf("insert %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
var key, value [16]byte
|
||||
binary.BigEndian.PutUint64(value[:8], 1)
|
||||
if same, err := x.observe("target", key, value); err != nil || !same {
|
||||
t.Fatalf("committed entry lost: %v", err)
|
||||
}
|
||||
|
||||
value[15] = 1
|
||||
if same, err := x.observe("target", key, value); err != nil || same {
|
||||
t.Fatalf("conflict missed: %v", err)
|
||||
|
||||
+5
-199
@@ -3,232 +3,38 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func unescapeMount(s string) string {
|
||||
return strings.NewReplacer("\\040", " ", "\\011", "\t", "\\012", "\n", "\\134", "\\").Replace(s)
|
||||
}
|
||||
|
||||
func privateDirectories(path string) error {
|
||||
if !filepath.IsAbs(path) {
|
||||
return errors.New("directory path must be absolute")
|
||||
}
|
||||
|
||||
current := "/"
|
||||
for _, component := range strings.Split(strings.TrimPrefix(filepath.Clean(path), "/"), "/") {
|
||||
if component == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
current = filepath.Join(current, component)
|
||||
if err := os.Mkdir(current, 0700); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
|
||||
st, err := os.Lstat(current)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !st.IsDir() {
|
||||
return fmt.Errorf("directory contains a symlink or non-directory: %s", current)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
func checkMount(root string, writable bool) error {
|
||||
f, err := os.Open("/proc/self/mountinfo")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
scan := bufio.NewScanner(f)
|
||||
found := false
|
||||
for scan.Scan() {
|
||||
parts := strings.SplitN(scan.Text(), " - ", 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
fields, after := strings.Fields(parts[0]), strings.Fields(parts[1])
|
||||
if len(fields) < 6 || len(after) < 2 {
|
||||
continue
|
||||
}
|
||||
mount := unescapeMount(fields[4])
|
||||
if mount == root {
|
||||
if after[0] != "ceph" && after[0] != "fuse.ceph-fuse" {
|
||||
return fmt.Errorf("%s is not a CephFS mount", root)
|
||||
}
|
||||
if writable && !strings.Contains(","+fields[5]+",", ",rw,") {
|
||||
return fmt.Errorf("target %s must be mounted read-write", root)
|
||||
}
|
||||
found = true
|
||||
} else if beneath(root, mount) {
|
||||
return fmt.Errorf("nested mount %s below %s is unsupported", mount, root)
|
||||
}
|
||||
}
|
||||
if err := scan.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("%s must be a dedicated CephFS filesystem-root mount", root)
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resolved != root {
|
||||
return errors.New("mount path must not contain symlinks")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func xattr(path, key string) ([]byte, error) {
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
n, err := syscall.Getxattr(path, key, nil)
|
||||
if errors.Is(err, syscall.ENODATA) {
|
||||
return []byte("0"), nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n > 1<<20 {
|
||||
return nil, fmt.Errorf("xattr too large: %s", key)
|
||||
}
|
||||
b := make([]byte, n)
|
||||
n, err = syscall.Getxattr(path, key, b)
|
||||
if errors.Is(err, syscall.ERANGE) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b[:n], nil
|
||||
}
|
||||
return nil, errors.New("xattr changed repeatedly")
|
||||
}
|
||||
|
||||
var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"}
|
||||
|
||||
// walkDirectories calls visit for every directory below root.
|
||||
func walkDirectories(ctx context.Context, root string, visit func(string) error) error {
|
||||
return walkTree(ctx, root, visit, nil)
|
||||
}
|
||||
|
||||
// walkTree walks root depth-first, skipping .snap. ReadDir batches keep a
|
||||
// single very large directory from exhausting memory.
|
||||
func walkTree(ctx context.Context, root string, visitDir func(string) error, visitFile func(string, os.FileInfo) error) error {
|
||||
var walk func(string, int) error
|
||||
walk = func(path string, depth int) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if depth > 128 {
|
||||
return errors.New("directory depth exceeds supported limit (128)")
|
||||
}
|
||||
if visitDir != nil {
|
||||
if err := visitDir(path); errors.Is(err, fs.SkipDir) {
|
||||
return nil
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
for {
|
||||
batch, readErr := f.ReadDir(128)
|
||||
for _, e := range batch {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Name() == ".snap" {
|
||||
continue
|
||||
}
|
||||
child := filepath.Join(path, e.Name())
|
||||
if e.IsDir() {
|
||||
if err := walk(child, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if visitFile != nil {
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = visitFile(child, info); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.Is(readErr, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
}
|
||||
}
|
||||
return walk(root, 0)
|
||||
}
|
||||
|
||||
func clearQuotas(ctx context.Context, root string) error {
|
||||
return walkDirectories(ctx, root, func(path string) error {
|
||||
for _, key := range quotaKeys {
|
||||
old, err := xattr(path, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read quota %s: %w", path, err)
|
||||
}
|
||||
if string(old) == "0" {
|
||||
continue
|
||||
}
|
||||
if err := syscall.Setxattr(path, key, []byte("0"), 0); err != nil {
|
||||
return fmt.Errorf("clear quota %s: %w", path, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func quotas(ctx context.Context, src, dst string, verify bool) error {
|
||||
return walkDirectories(ctx, src, func(path string) error {
|
||||
rel, err := filepath.Rel(src, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target := filepath.Join(dst, rel)
|
||||
st, err := os.Lstat(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !st.IsDir() {
|
||||
return fmt.Errorf("quota target is not a real directory: %s", target)
|
||||
}
|
||||
for _, key := range quotaKeys {
|
||||
value, err := xattr(path, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("source quota %s %s: %w", path, key, err)
|
||||
}
|
||||
actual, err := xattr(target, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("target quota %s %s: %w", target, key, err)
|
||||
}
|
||||
if string(value) == string(actual) {
|
||||
continue
|
||||
}
|
||||
if verify {
|
||||
return fmt.Errorf("quota mismatch: %s %s", rel, key)
|
||||
}
|
||||
if err := syscall.Setxattr(target, key, value, 0); err != nil {
|
||||
return fmt.Errorf("set quota %s %s: %w", target, key, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -22,17 +22,21 @@ func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspe
|
||||
if err := c.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sf, si, err := queryEndpoint(ctx, ceph{endpoint: c.Source, exec: x, native: true})
|
||||
|
||||
sf, si, err := queryEndpoint(ctx, ceph{endpoint: c.Source, exec: x})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tf, ti, err := queryEndpoint(ctx, ceph{endpoint: c.Target, exec: x, native: true})
|
||||
|
||||
tf, ti, err := queryEndpoint(ctx, ceph{endpoint: c.Target, exec: x})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if sf == tf {
|
||||
return nil, errors.New("native source and target must be different clusters")
|
||||
}
|
||||
|
||||
for _, p := range []struct {
|
||||
fs storage.FS
|
||||
path, fsid string
|
||||
@@ -40,34 +44,42 @@ func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspe
|
||||
if _, err := nativePath(p.path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateNativeDirectory(p.fs, p.path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
id, err := p.fs.GetXattr(p.path, "ceph.cluster_fsid")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if string(id) != p.fsid {
|
||||
return nil, errors.New("native connection belongs to the wrong cluster")
|
||||
}
|
||||
}
|
||||
names, err := (ceph{endpoint: c.Source, exec: x, native: true}).names(ctx)
|
||||
|
||||
names, err := (ceph{endpoint: c.Source, exec: x}).names(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fingerprint := sha256.Sum256([]byte(sf + "\x00" + tf + "\x00" + si.Path + "\x00" + ti.Path))
|
||||
a.backend.identity = hex.EncodeToString(fingerprint[:])
|
||||
return &Inspection{SourceFSID: sf, TargetFSID: tf, SourcePath: si.Path, TargetPath: ti.Path,
|
||||
SourceBytes: si.BytesUsed, SourceSnapshots: names, Notes: []string{SnapshotIdentityNote}}, nil
|
||||
}
|
||||
|
||||
func (a nativeAccess) Empty(ctx context.Context, p string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d, err := a.backend.target.OpenDir(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer d.Close()
|
||||
_, err = d.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
@@ -76,13 +88,47 @@ func (a nativeAccess) Empty(ctx context.Context, p string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return errors.New("new native migration requires an empty target subvolume")
|
||||
}
|
||||
|
||||
func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.Closer, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fs := a.backend.target
|
||||
|
||||
if a.backend.openTarget == nil {
|
||||
return claimNative(a.backend.target, c, fsid, id)
|
||||
}
|
||||
|
||||
// The lock lives as long as this client; Verify replaces target.
|
||||
client, err := a.backend.openTarget()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("native claim client: %w", err)
|
||||
}
|
||||
|
||||
f, err := claimNative(client, c, fsid, id)
|
||||
if err != nil {
|
||||
client.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nativeClaim{file: f, client: client}, nil
|
||||
}
|
||||
|
||||
// nativeClaim is a claim lock held through a client of its own.
|
||||
type nativeClaim struct {
|
||||
file storage.File
|
||||
client storage.FS
|
||||
}
|
||||
|
||||
func (c nativeClaim) Close() error {
|
||||
return errors.Join(c.file.Close(), c.client.Close())
|
||||
}
|
||||
|
||||
// claimNative creates the claim file for id if needed, locks it through fs
|
||||
// and checks that it names id. The returned file holds the lock.
|
||||
func claimNative(fs storage.FS, c Config, fsid, id string) (storage.File, error) {
|
||||
current := "/"
|
||||
for _, component := range []string{".cephmig", "claims"} {
|
||||
current = path.Join(current, component)
|
||||
@@ -91,22 +137,25 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.
|
||||
if err = fs.Mkdir(current, 0700); err != nil && !errors.Is(err, syscall.EEXIST) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
n, err = fs.Stat(current)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if n.Kind() != storage.Directory {
|
||||
return nil, errors.New("native claim directory contains a symlink or non-directory")
|
||||
}
|
||||
}
|
||||
sum := sha256.Sum256([]byte(fsid + "\x00" + c.Target.Filesystem + "\x00" + c.Target.Group + "\x00" + c.Target.Subvolume))
|
||||
p := path.Join(current, hex.EncodeToString(sum[:]))
|
||||
|
||||
p := path.Join(current, claimName(fsid, c.Target))
|
||||
f, err := fs.Open(p, syscall.O_CREAT|syscall.O_EXCL|syscall.O_RDWR|syscall.O_NOFOLLOW, 0600)
|
||||
if err == nil {
|
||||
if err = writeNativeAt(f, []byte(id+"\n"), 0); err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
|
||||
closeErr := f.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
@@ -117,36 +166,85 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.
|
||||
} else if !errors.Is(err, syscall.EEXIST) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
n, err := fs.Stat(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if n.Kind() != storage.Regular {
|
||||
return nil, errors.New("native target claim is not a regular file")
|
||||
}
|
||||
|
||||
f, err = fs.Open(p, syscall.O_RDWR|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = f.Lock(1); err != nil {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("native target is locked: %w", err)
|
||||
}
|
||||
|
||||
b := make([]byte, 256)
|
||||
count, readErr := f.ReadAt(b, 0)
|
||||
if readErr != nil && !errors.Is(readErr, io.EOF) {
|
||||
f.Close()
|
||||
return nil, readErr
|
||||
}
|
||||
|
||||
if string(b[:count]) != id+"\n" {
|
||||
f.Close()
|
||||
return nil, errors.New("native target belongs to a different job")
|
||||
}
|
||||
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (a nativeAccess) Release(ctx context.Context, c Config, fsid, id string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fs := a.backend.target
|
||||
dir := "/.cephmig/claims"
|
||||
p := path.Join(dir, claimName(fsid, c.Target))
|
||||
f, err := fs.Open(p, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if errors.Is(err, syscall.ENOENT) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := make([]byte, 256)
|
||||
n, err := f.ReadAt(b, 0)
|
||||
f.Close()
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return err
|
||||
}
|
||||
|
||||
if string(b[:n]) != id+"\n" {
|
||||
return errors.New("native target claim belongs to a different job; not removed")
|
||||
}
|
||||
|
||||
if err = fs.Unlink(p); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, d := range []string{dir, "/.cephmig"} {
|
||||
if err := fs.Rmdir(d); err != nil && !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.ENOTEMPTY) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a nativeAccess) Prepare(ctx context.Context, _, target, _ string) error {
|
||||
return clearNativeQuotas(ctx, a.backend.target, target)
|
||||
}
|
||||
|
||||
func (a nativeAccess) Apply(context.Context, string, string) error { return a.backend.target.Sync() }
|
||||
func (a nativeAccess) Verify(context.Context, string, string, string) error { return nil } // Transport verifies all native metadata and links.
|
||||
|
||||
@@ -160,14 +258,21 @@ func osNativeVerifyIndex(parent string) (*nativeVerifyIndex, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
index, err := openLinkIndex(filepath.Join(dir, "links.bolt"))
|
||||
if err != nil {
|
||||
os.RemoveAll(dir)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &nativeVerifyIndex{index: index, dir: dir}, nil
|
||||
}
|
||||
func (i *nativeVerifyIndex) cleanup() { _ = i.index.close(); _ = os.RemoveAll(i.dir) }
|
||||
|
||||
func (i *nativeVerifyIndex) cleanup() {
|
||||
_ = i.index.close()
|
||||
_ = os.RemoveAll(i.dir)
|
||||
}
|
||||
|
||||
func options(ep Endpoint) storage.Options {
|
||||
return storage.Options{Config: ep.Config, Keyring: ep.Keyring, User: strings.TrimPrefix(ep.User, "client."), Filesystem: ep.Filesystem}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/Sebi/CephfsMig/internal/storage"
|
||||
)
|
||||
|
||||
// rootFS is a storage.FS rooted at a local directory, with real flock
|
||||
// locks, for the claim operations.
|
||||
type rootFS struct {
|
||||
storage.FS
|
||||
root string
|
||||
}
|
||||
|
||||
func (f rootFS) path(p string) string { return filepath.Join(f.root, p) }
|
||||
|
||||
func (f rootFS) Stat(p string) (storage.Node, error) { return diskFS{}.Stat(f.path(p)) }
|
||||
func (f rootFS) Mkdir(p string, mode uint32) error { return os.Mkdir(f.path(p), os.FileMode(mode)) }
|
||||
func (f rootFS) Unlink(p string) error { return syscall.Unlink(f.path(p)) }
|
||||
func (f rootFS) Rmdir(p string) error { return syscall.Rmdir(f.path(p)) }
|
||||
func (f rootFS) Close() error { return nil }
|
||||
|
||||
func (f rootFS) Open(p string, flags int, mode uint32) (storage.File, error) {
|
||||
file, err := os.OpenFile(f.path(p), flags, os.FileMode(mode))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return lockingFile{diskFile{file}}, nil
|
||||
}
|
||||
|
||||
type lockingFile struct{ diskFile }
|
||||
|
||||
func (f lockingFile) Lock(uint64) error {
|
||||
return syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
}
|
||||
|
||||
func claimAccess(root string) nativeAccess {
|
||||
fs := rootFS{root: root}
|
||||
return nativeAccess{&nativeTransport{target: fs, openTarget: func() (storage.FS, error) { return fs, nil }}}
|
||||
}
|
||||
|
||||
func TestNativeClaimExcludesOtherJobsAndSurvivesStateLoss(t *testing.T) {
|
||||
ctx, c := context.Background(), testConfig()
|
||||
a := claimAccess(t.TempDir())
|
||||
first, err := a.Claim(ctx, c, "fsid", "job-one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if second, err := a.Claim(ctx, c, "fsid", "job-one"); err == nil {
|
||||
second.Close()
|
||||
t.Fatal("concurrent use allowed")
|
||||
}
|
||||
|
||||
if err := first.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if other, err := a.Claim(ctx, c, "fsid", "job-two"); err == nil {
|
||||
other.Close()
|
||||
t.Fatal("different job stole target")
|
||||
}
|
||||
|
||||
resumed, err := a.Claim(ctx, c, "fsid", "job-one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
resumed.Close()
|
||||
}
|
||||
|
||||
func TestNativeReleaseRemovesOnlyOwnClaim(t *testing.T) {
|
||||
ctx, root := context.Background(), t.TempDir()
|
||||
a := claimAccess(root)
|
||||
c := testConfig()
|
||||
other := c
|
||||
other.Target.Subvolume = "other"
|
||||
for _, x := range []struct {
|
||||
c Config
|
||||
id string
|
||||
}{{c, "job-one"}, {other, "job-two"}} {
|
||||
f, err := a.Claim(ctx, x.c, "fsid", x.id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f.Close()
|
||||
}
|
||||
|
||||
if err := a.Release(ctx, c, "fsid", "job-two"); err == nil {
|
||||
t.Fatal("removed the claim of a different job")
|
||||
}
|
||||
|
||||
if err := a.Release(ctx, c, "fsid", "job-one"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
claims := filepath.Join(root, ".cephmig", "claims")
|
||||
if _, err := os.Stat(filepath.Join(claims, claimName("fsid", c.Target))); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("own claim still present: %v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(claims, claimName("fsid", other.Target))); err != nil {
|
||||
t.Fatalf("claim of another job removed: %v", err)
|
||||
}
|
||||
|
||||
if err := a.Release(ctx, other, "fsid", "job-two"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(root, ".cephmig")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("empty claim directories kept: %v", err)
|
||||
}
|
||||
|
||||
// Releasing again is a no-op.
|
||||
if err := a.Release(ctx, c, "fsid", "job-one"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -19,61 +20,87 @@ func readNativeAt(f storage.File, b []byte, offset int64) error {
|
||||
if err == nil {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeNativeAt(f storage.File, b []byte, offset int64) error {
|
||||
n, err := f.WriteAt(b, offset)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != len(b) {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func allZero(b []byte) bool {
|
||||
for _, v := range b {
|
||||
if v != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// baseTrusted reports whether the base entry previous still describes the
|
||||
// source node n and its target copy, so the copy may be skipped or patched.
|
||||
// A carried entry was written by an earlier version that skipped subtrees;
|
||||
// it may describe an older round and is never trusted.
|
||||
func baseTrusted(previous baseEntry, n, target storage.Node) bool {
|
||||
return !previous.Carried && previous.Inode == n.Inode && previous.TargetInode == target.Inode && previous.Size == target.Size
|
||||
}
|
||||
|
||||
func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
from, to := path.Join(b.round.SourcePath, job.rel), path.Join(b.round.TargetPath, job.rel)
|
||||
target, statErr := b.target.Stat(to)
|
||||
if statErr != nil && !errors.Is(statErr, syscall.ENOENT) {
|
||||
return statErr
|
||||
}
|
||||
|
||||
exists := statErr == nil && target.Kind() == storage.Regular
|
||||
// A newer ctime than the migration set means the file was changed outside
|
||||
// the migration, so a block delta against the previous round would be
|
||||
// wrong. A full copy replaces it with a new inode.
|
||||
replace := exists && target.Ctime.After(wantedCtime(job.node))
|
||||
var previous baseEntry
|
||||
trusted := false
|
||||
if b.delta && exists {
|
||||
if b.delta && exists && !replace {
|
||||
var ok bool
|
||||
var err error
|
||||
previous, ok, err = b.base.entry(job.rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
trusted = ok && previous.Inode == job.node.Inode && previous.TargetInode == target.Inode && previous.Size == target.Size
|
||||
|
||||
trusted = ok && baseTrusted(previous, job.node, target)
|
||||
}
|
||||
|
||||
changed := true
|
||||
if trusted && job.node.Version != 0 && job.node.Version == previous.Version && job.node.Size == previous.Size {
|
||||
changedBytes, err := b.pending.get("changed", nativeInodeKey(job.node.Inode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
changed = changedBytes != nil
|
||||
}
|
||||
|
||||
if changed {
|
||||
usedBlockDiff := false
|
||||
if trusted && job.node.Size >= nativeBlockThreshold {
|
||||
@@ -85,6 +112,7 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error
|
||||
if err = b.copyBlocks(ctx, job, stream); err != nil {
|
||||
return fmt.Errorf("native blockdiff %s: %w", job.rel, err)
|
||||
}
|
||||
|
||||
b.blockFiles.Add(1)
|
||||
} else if !errors.Is(err, syscall.ENOSYS) && !errors.Is(err, syscall.EOPNOTSUPP) && !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.EINVAL) {
|
||||
return err
|
||||
@@ -93,23 +121,29 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if !usedBlockDiff {
|
||||
if err := b.copyFull(ctx, job); err != nil {
|
||||
return fmt.Errorf("native full copy %s: %w", job.rel, err)
|
||||
}
|
||||
|
||||
if err := b.pending.put("full", []byte(job.rel), []byte{1}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
b.copied.Add(1)
|
||||
}
|
||||
|
||||
if err := syncNativeMetadata(b.source, b.target, from, to, job.node, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
current, err := b.target.Stat(to)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return b.pending.put("paths", []byte(job.rel), encodeEntry(baseEntry{Inode: job.node.Inode, Version: job.node.Version, Size: job.node.Size, TargetInode: current.Inode}))
|
||||
}
|
||||
|
||||
@@ -119,93 +153,115 @@ func (b *nativeTransport) copyFull(ctx context.Context, job nativeJob) (result e
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer source.Close()
|
||||
old, err := b.target.Stat(to)
|
||||
if err != nil && !errors.Is(err, syscall.ENOENT) {
|
||||
return err
|
||||
}
|
||||
|
||||
if err == nil && old.Kind() == storage.Directory {
|
||||
if err = removeNative(ctx, b.target, to); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
id, err := newID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
temporary := path.Join(path.Dir(to), ".cephmig-file-"+id)
|
||||
target, err := b.target.Open(temporary, syscall.O_CREAT|syscall.O_EXCL|syscall.O_RDWR|syscall.O_NOFOLLOW, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if target != nil {
|
||||
if err := target.Close(); result == nil {
|
||||
result = err
|
||||
}
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
_ = b.target.Unlink(temporary)
|
||||
}
|
||||
}()
|
||||
|
||||
buffer := make([]byte, min(job.node.Size, uint64(nativeChunk)))
|
||||
for off := uint64(0); off < job.node.Size; {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length := min(uint64(len(buffer)), job.node.Size-off)
|
||||
chunk := buffer[:int(length)]
|
||||
if err = readNativeAt(source, chunk, int64(off)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !allZero(chunk) {
|
||||
if err = b.rate(ctx, len(chunk)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = writeNativeAt(target, chunk, int64(off)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.written.Add(int64(length))
|
||||
}
|
||||
|
||||
off += length
|
||||
}
|
||||
|
||||
if err = target.Truncate(int64(job.node.Size)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = target.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = target.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
target = nil
|
||||
return b.target.Rename(temporary, to)
|
||||
}
|
||||
|
||||
func (b *nativeTransport) copyBlocks(ctx context.Context, job nativeJob, blocks storage.BlockStream) (result error) {
|
||||
defer func() {
|
||||
if err := blocks.Close(); result == nil {
|
||||
result = err
|
||||
}
|
||||
}()
|
||||
|
||||
source, err := b.source.Open(path.Join(b.round.SourcePath, job.rel), syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer source.Close()
|
||||
target, err := b.target.Open(path.Join(b.round.TargetPath, job.rel), syscall.O_RDWR|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err := target.Close(); result == nil {
|
||||
result = err
|
||||
}
|
||||
}()
|
||||
|
||||
buffer := make([]byte, nativeChunk)
|
||||
for {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ranges, err := blocks.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
@@ -213,24 +269,29 @@ func (b *nativeTransport) copyBlocks(ctx context.Context, job nativeJob, blocks
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, extent := range ranges {
|
||||
if extent.Offset > job.node.Size {
|
||||
continue
|
||||
}
|
||||
|
||||
length := min(extent.Length, job.node.Size-extent.Offset)
|
||||
if extent.Length > ^uint64(0)-extent.Offset {
|
||||
return errors.New("blockdiff extent overflows")
|
||||
}
|
||||
|
||||
for copied := uint64(0); copied < length; {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
count := min(uint64(len(buffer)), length-copied)
|
||||
chunk := buffer[:int(count)]
|
||||
off := extent.Offset + copied
|
||||
if err = readNativeAt(source, chunk, int64(off)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
punched := false
|
||||
if allZero(chunk) {
|
||||
err = target.PunchHole(int64(off), int64(count))
|
||||
@@ -240,25 +301,32 @@ func (b *nativeTransport) copyBlocks(ctx context.Context, job nativeJob, blocks
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if !punched {
|
||||
if err = b.rate(ctx, len(chunk)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = writeNativeAt(target, chunk, int64(off)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.written.Add(int64(count))
|
||||
}
|
||||
|
||||
if err = b.pending.extent(job.rel, off, count); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
copied += count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err = target.Truncate(int64(job.node.Size)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return target.Sync()
|
||||
}
|
||||
|
||||
@@ -266,16 +334,71 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
|
||||
if b.pending == nil || from != b.round.SourcePath {
|
||||
return errors.New("native verification round is not initialized")
|
||||
}
|
||||
|
||||
if err := b.pending.requireInventory(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if b.openTarget != nil {
|
||||
// Replace the writing client before reading the target. Its cache
|
||||
// may hold a ctime that differs from the MDS, and the MDS would have
|
||||
// to recall its caps on every entry it wrote last, which in the lab
|
||||
// cost about five seconds per lookup. Closing it returns all caps at
|
||||
// once. The engine calls transport methods one at a time, and the
|
||||
// claim lock is held by a client of its own.
|
||||
v, err := b.openTarget()
|
||||
if err != nil {
|
||||
return fmt.Errorf("native verification client: %w", err)
|
||||
}
|
||||
|
||||
err = b.target.Close()
|
||||
b.target = v
|
||||
if err != nil {
|
||||
return fmt.Errorf("close native writing client: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
skipData := b.verified[to]
|
||||
scratch, err := osNativeVerifyIndex(b.workspace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer scratch.cleanup()
|
||||
index := scratch.index
|
||||
v := &nativeVerification{b: b, to: to, skipData: skipData, index: scratch.index}
|
||||
|
||||
// The walk and the directories stay serial; every other entry is checked by
|
||||
// one of the workers.
|
||||
ctx, cancel := context.WithCancelCause(ctx)
|
||||
defer cancel(nil)
|
||||
workers := b.config.Workers
|
||||
if workers == 0 {
|
||||
workers = 8
|
||||
}
|
||||
|
||||
type entry struct {
|
||||
p, rel string
|
||||
n storage.Node
|
||||
}
|
||||
|
||||
jobs := make(chan entry, workers*4)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for job := range jobs {
|
||||
if ctx.Err() != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := v.entry(ctx, job.p, job.rel, job.n); err != nil {
|
||||
cancel(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
lastProgress := time.Now()
|
||||
var verifiedPaths uint64
|
||||
err = walkNative(ctx, b.source, from, func(p string, n storage.Node, _ int) error {
|
||||
@@ -284,53 +407,114 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
|
||||
fmt.Fprintf(b.log, "native verifying paths=%d target=%s\n", verifiedPaths, to)
|
||||
lastProgress = time.Now()
|
||||
}
|
||||
|
||||
rel, err := relativeNative(from, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targetPath := path.Join(to, rel)
|
||||
|
||||
if n.Kind() == storage.Directory {
|
||||
return v.entry(ctx, p, rel, n)
|
||||
}
|
||||
|
||||
select {
|
||||
case jobs <- entry{p: p, rel: rel, n: n}:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return context.Cause(ctx)
|
||||
}
|
||||
})
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
if cause := context.Cause(ctx); cause != nil && (err == nil || errors.Is(err, context.Canceled)) {
|
||||
err = cause
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = b.verifyInventory(ctx, to); err == nil {
|
||||
b.verified[to] = true
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// nativeVerification holds the state of one Verify call that its workers
|
||||
// share.
|
||||
type nativeVerification struct {
|
||||
b *nativeTransport
|
||||
to string
|
||||
skipData bool
|
||||
mu sync.Mutex // guards index, which holds one write transaction
|
||||
index *linkIndex
|
||||
}
|
||||
|
||||
// observe records a hardlink relation in the scratch index.
|
||||
func (v *nativeVerification) observe(bucket string, key, value [16]byte) (bool, error) {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
return v.index.observe(bucket, key, value)
|
||||
}
|
||||
|
||||
// entry checks one source entry p against its target copy. It is safe for
|
||||
// concurrent use.
|
||||
func (v *nativeVerification) entry(ctx context.Context, p, rel string, n storage.Node) error {
|
||||
b := v.b
|
||||
targetPath := path.Join(v.to, rel)
|
||||
target, err := b.target.Stat(targetPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = syncNativeMetadataKnown(b.source, b.target, p, targetPath, n, target, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if n.Kind() != storage.Directory {
|
||||
|
||||
if n.Kind() == storage.Directory {
|
||||
return nil
|
||||
}
|
||||
|
||||
if n.Nlink > 1 {
|
||||
same, err := index.observe("source", nodeKey(n.Inode), nodeKey(target.Inode))
|
||||
same, err := v.observe("source", nodeKey(n.Inode), nodeKey(target.Inode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !same {
|
||||
return fmt.Errorf("native hardlink group was split at %s", rel)
|
||||
}
|
||||
}
|
||||
|
||||
if target.Nlink > 1 {
|
||||
same, err := index.observe("target", nodeKey(target.Inode), nodeKey(n.Inode))
|
||||
same, err := v.observe("target", nodeKey(target.Inode), nodeKey(n.Inode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !same {
|
||||
return fmt.Errorf("native unrelated files became hardlinked at %s", rel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch n.Kind() {
|
||||
case storage.Directory:
|
||||
case storage.Regular:
|
||||
if n.Size != target.Size {
|
||||
return fmt.Errorf("native size mismatch at %s", targetPath)
|
||||
}
|
||||
|
||||
canonical, err := b.pending.get("groups", nativeInodeKey(n.Inode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !skipData && string(canonical) == rel {
|
||||
|
||||
if !v.skipData && string(canonical) == rel {
|
||||
full, err := b.pending.get("full", []byte(rel))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if full != nil {
|
||||
if err = b.compareRange(ctx, p, targetPath, 0, n.Size); err != nil {
|
||||
return err
|
||||
@@ -341,42 +525,41 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only live target identities may be reused as the next blockdiff base.
|
||||
if to == b.round.TargetPath && !skipData {
|
||||
if v.to == b.round.TargetPath && !v.skipData {
|
||||
return b.pending.putEntryIfChanged(rel, baseEntry{Inode: n.Inode, Version: n.Version, Size: n.Size, TargetInode: target.Inode})
|
||||
}
|
||||
|
||||
case storage.Symlink:
|
||||
a, err := b.source.Readlink(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v, err := b.target.Readlink(targetPath)
|
||||
|
||||
t, err := b.target.Readlink(targetPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a != v {
|
||||
|
||||
if a != t {
|
||||
return fmt.Errorf("native symlink mismatch at %s", rel)
|
||||
}
|
||||
|
||||
default:
|
||||
if n.Rdev != target.Rdev {
|
||||
return fmt.Errorf("native device mismatch at %s", rel)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = b.verifyInventory(ctx, to); err == nil {
|
||||
b.verified[to] = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error {
|
||||
if err := b.pending.requireInventory(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The source snapshot is immutable. Check the complete local inventory,
|
||||
// including aliases/directories/special files, rather than stat every source
|
||||
// path again. Target traversal still detects every unexpected entry.
|
||||
@@ -385,29 +568,36 @@ func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
present, err := b.pending.containsPath(rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !present {
|
||||
return fmt.Errorf("unexpected native target entry %s", rel)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (b *nativeTransport) compareRange(ctx context.Context, from, to string, offset, length uint64) error {
|
||||
if length == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
source, err := b.source.Open(from, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer source.Close()
|
||||
target, err := b.target.Open(to, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer target.Close()
|
||||
bufferSize := min(length, uint64(nativeChunk))
|
||||
a, v := make([]byte, bufferSize), make([]byte, bufferSize)
|
||||
@@ -415,18 +605,23 @@ func (b *nativeTransport) compareRange(ctx context.Context, from, to string, off
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
count := min(uint64(len(a)), length-done)
|
||||
if err = readNativeAt(source, a[:int(count)], int64(offset+done)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = readNativeAt(target, v[:int(count)], int64(offset+done)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !bytes.Equal(a[:int(count)], v[:int(count)]) {
|
||||
return fmt.Errorf("native content mismatch at %s offset %d", to, offset+done)
|
||||
}
|
||||
|
||||
b.checked.Add(int64(count))
|
||||
done += count
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -7,21 +7,34 @@ import (
|
||||
"io"
|
||||
|
||||
"git.zb-server.de/Sebi/CephfsMig/internal/cephfsnative"
|
||||
"git.zb-server.de/Sebi/CephfsMig/internal/storage"
|
||||
)
|
||||
|
||||
func openNativeEngine(ctx context.Context, c Config, x Executor, log io.Writer) (Engine, io.Closer, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Engine{}, nil, err
|
||||
}
|
||||
|
||||
source, err := cephfsnative.Open(options(c.Source))
|
||||
if err != nil {
|
||||
return Engine{}, nil, err
|
||||
}
|
||||
|
||||
target, err := cephfsnative.Open(options(c.Target))
|
||||
if err != nil {
|
||||
source.Close()
|
||||
return Engine{}, nil, err
|
||||
}
|
||||
backend := &nativeTransport{source: source, target: target, config: c, log: log}
|
||||
|
||||
openTarget := func() (storage.FS, error) {
|
||||
v, err := cephfsnative.Open(options(c.Target))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return v, nil
|
||||
}
|
||||
|
||||
backend := &nativeTransport{source: source, target: target, config: c, log: log, openTarget: openTarget}
|
||||
return Engine{Exec: x, Log: log, Transport: backend, Access: nativeAccess{backend}}, backend, nil
|
||||
}
|
||||
@@ -9,29 +9,38 @@ import (
|
||||
"path"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/CephfsMig/internal/storage"
|
||||
)
|
||||
|
||||
// quotaKeys are the directory quota xattrs that the migration copies.
|
||||
var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"}
|
||||
|
||||
func walkNative(ctx context.Context, fs storage.FS, root string, visit func(string, storage.Node, int) error) error {
|
||||
var walk func(string, storage.Node, int) error
|
||||
walk = func(p string, n storage.Node, depth int) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if depth > 128 {
|
||||
return errors.New("native directory depth exceeds 128")
|
||||
}
|
||||
|
||||
if err := visit(p, n, depth); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n.Kind() != storage.Directory {
|
||||
return nil
|
||||
}
|
||||
|
||||
dir, err := fs.OpenDir(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer dir.Close()
|
||||
for {
|
||||
e, err := dir.Next()
|
||||
@@ -41,24 +50,30 @@ func walkNative(ctx context.Context, fs storage.FS, root string, visit func(stri
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if e == nil || e.Name == "" || strings.ContainsAny(e.Name, "/\x00") || e.Name == "." || e.Name == ".." || e.Name == ".snap" {
|
||||
return errors.New("invalid native directory entry")
|
||||
}
|
||||
|
||||
if err = walk(path.Join(p, e.Name), e.Node, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
n, err := fs.Stat(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return walk(root, n, 0)
|
||||
}
|
||||
|
||||
func removeNative(ctx context.Context, fs storage.FS, p string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
n, err := fs.Stat(p)
|
||||
if errors.Is(err, syscall.ENOENT) {
|
||||
return nil
|
||||
@@ -66,13 +81,16 @@ func removeNative(ctx context.Context, fs storage.FS, p string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n.Kind() != storage.Directory {
|
||||
return fs.Unlink(p)
|
||||
}
|
||||
|
||||
d, err := fs.OpenDir(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Re-open after each bounded batch, so deleting while iterating does not skip
|
||||
// entries on directory streams whose offsets change after removal.
|
||||
for {
|
||||
@@ -86,179 +104,297 @@ func removeNative(ctx context.Context, fs storage.FS, p string) error {
|
||||
d.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
names = append(names, e.Name)
|
||||
}
|
||||
|
||||
if err = d.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(names) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
for _, s := range names {
|
||||
if err = removeNative(ctx, fs, path.Join(p, s)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
d, err = fs.OpenDir(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return fs.Rmdir(p)
|
||||
}
|
||||
|
||||
func nativeQuota(fs storage.FS, p, key string) ([]byte, error) {
|
||||
b, err := fs.GetXattr(p, key)
|
||||
if errors.Is(err, syscall.ENODATA) {
|
||||
return []byte("0"), nil
|
||||
}
|
||||
|
||||
return b, err
|
||||
}
|
||||
|
||||
func clearNativeQuotas(ctx context.Context, fs storage.FS, root string) error {
|
||||
return walkNative(ctx, fs, root, func(p string, n storage.Node, _ int) error {
|
||||
if n.Kind() != storage.Directory {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, key := range quotaKeys {
|
||||
b, err := nativeQuota(fs, p, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if string(b) != "0" {
|
||||
if err = fs.SetXattr(p, key, []byte("0")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func portableXattr(s string) bool {
|
||||
return !strings.HasPrefix(s, "ceph.") && (!strings.HasPrefix(s, "system.") || s == "system.posix_acl_access" || s == "system.posix_acl_default")
|
||||
}
|
||||
|
||||
func nativeAttrs(fs storage.FS, p string) (map[string][]byte, error) {
|
||||
names, err := fs.ListXattr(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attrs := make(map[string][]byte, len(names))
|
||||
for _, key := range names {
|
||||
if !portableXattr(key) {
|
||||
continue
|
||||
}
|
||||
|
||||
value, err := fs.GetXattr(p, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attrs[key] = value
|
||||
}
|
||||
|
||||
return attrs, nil
|
||||
}
|
||||
|
||||
// syncNativeMetadata makes the metadata of the target path to equal the source
|
||||
// node n, or with verify set only checks it.
|
||||
func syncNativeMetadata(src, dst storage.FS, from, to string, n storage.Node, verify bool) error {
|
||||
target, err := dst.Stat(to)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return syncNativeMetadataKnown(src, dst, from, to, n, target, verify)
|
||||
}
|
||||
|
||||
// Reuse a no-follow stat just read by the caller. No other writer is permitted
|
||||
// in the target while a migration owns it.
|
||||
// wantedCtime is the change time the target can reach: the MDS keeps the
|
||||
// ctime at or above the mtime.
|
||||
func wantedCtime(n storage.Node) time.Time {
|
||||
if n.Mtime.After(n.Ctime) {
|
||||
return n.Mtime
|
||||
}
|
||||
|
||||
return n.Ctime
|
||||
}
|
||||
|
||||
// syncNativeMetadataKnown reuses a no-follow stat just read by the caller.
|
||||
// No other writer is permitted in the target while a migration owns it.
|
||||
//
|
||||
// Extended attributes and quotas are written first and SetAttr last, because
|
||||
// SetAttr sets the ctime and every later change would reset it.
|
||||
func syncNativeMetadataKnown(src, dst storage.FS, from, to string, n, target storage.Node, verify bool) error {
|
||||
if n.Kind() != target.Kind() {
|
||||
return fmt.Errorf("native type mismatch at %s", to)
|
||||
}
|
||||
different := n.Mode != target.Mode || n.UID != target.UID || n.GID != target.GID || !n.Mtime.Equal(target.Mtime)
|
||||
if different {
|
||||
if verify {
|
||||
return fmt.Errorf("native metadata mismatch at %s", to)
|
||||
|
||||
diff := metadataDiff(n, target)
|
||||
different := diff != ""
|
||||
if different && verify {
|
||||
return fmt.Errorf("native metadata mismatch at %s:%s", to, diff)
|
||||
}
|
||||
|
||||
changed, err := syncNativeXattrs(src, dst, from, to, n, verify)
|
||||
if err != nil || verify || !(different || changed) {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := dst.SetAttr(to, n); err != nil {
|
||||
return fmt.Errorf("native setattr %s: %w", to, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// restoreNativeMetadata copies xattrs and quotas and then always calls
|
||||
// SetAttr. Use it where the target was changed after its last SetAttr, since
|
||||
// the cached stat of this client may not show that.
|
||||
func restoreNativeMetadata(src, dst storage.FS, from, to string, n storage.Node) error {
|
||||
if _, err := syncNativeXattrs(src, dst, from, to, n, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := dst.SetAttr(to, n); err != nil {
|
||||
return fmt.Errorf("native setattr %s: %w", to, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// metadataDiff lists the attributes in which target differs from the source
|
||||
// node n, or returns "" if none does.
|
||||
func metadataDiff(n, target storage.Node) string {
|
||||
var b strings.Builder
|
||||
if n.Mode != target.Mode {
|
||||
fmt.Fprintf(&b, " mode %o != %o", n.Mode, target.Mode)
|
||||
}
|
||||
|
||||
if n.UID != target.UID || n.GID != target.GID {
|
||||
fmt.Fprintf(&b, " owner %d:%d != %d:%d", n.UID, n.GID, target.UID, target.GID)
|
||||
}
|
||||
|
||||
for _, t := range []struct {
|
||||
name string
|
||||
want, actual time.Time
|
||||
}{
|
||||
{"atime", n.Atime, target.Atime},
|
||||
{"mtime", n.Mtime, target.Mtime},
|
||||
{"btime", n.Btime, target.Btime},
|
||||
{"ctime", wantedCtime(n), target.Ctime},
|
||||
} {
|
||||
if !t.want.Equal(t.actual) {
|
||||
fmt.Fprintf(&b, " %s %s != %s", t.name, t.want.UTC().Format(time.RFC3339Nano), t.actual.UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// syncNativeXattrs copies portable xattrs and, for directories, quotas. It
|
||||
// reports whether it changed anything.
|
||||
func syncNativeXattrs(src, dst storage.FS, from, to string, n storage.Node, verify bool) (bool, error) {
|
||||
attrs, err := nativeAttrs(src, from)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
old, err := nativeAttrs(dst, to)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
changed := false
|
||||
for k, v := range old {
|
||||
value, exists := attrs[k]
|
||||
if verify {
|
||||
if !exists || !bytes.Equal(value, v) {
|
||||
return fmt.Errorf("native xattr mismatch at %s: %s", to, k)
|
||||
return false, fmt.Errorf("native xattr mismatch at %s: %s", to, k)
|
||||
}
|
||||
} else if !exists {
|
||||
if err = dst.RemoveXattr(to, k); err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
|
||||
for k, v := range attrs {
|
||||
if verify {
|
||||
if actual, ok := old[k]; !ok || !bytes.Equal(v, actual) {
|
||||
return fmt.Errorf("native xattr mismatch at %s: %s", to, k)
|
||||
return false, fmt.Errorf("native xattr mismatch at %s: %s", to, k)
|
||||
}
|
||||
} else if actual, exists := old[k]; !exists || !bytes.Equal(actual, v) {
|
||||
if err = dst.SetXattr(to, k, v); err != nil {
|
||||
return fmt.Errorf("native setxattr %s: %w", k, err)
|
||||
return false, fmt.Errorf("native setxattr %s: %w", k, err)
|
||||
}
|
||||
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
|
||||
if n.Kind() != storage.Directory {
|
||||
return changed, nil
|
||||
}
|
||||
if n.Kind() == storage.Directory {
|
||||
|
||||
for _, key := range quotaKeys {
|
||||
value, err := nativeQuota(src, from, key)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
actual, err := nativeQuota(dst, to, key)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
if bytes.Equal(value, actual) {
|
||||
continue
|
||||
}
|
||||
|
||||
if verify {
|
||||
return fmt.Errorf("native quota mismatch at %s: %s", to, key)
|
||||
return false, fmt.Errorf("native quota mismatch at %s: %s", to, key)
|
||||
}
|
||||
|
||||
if err = dst.SetXattr(to, key, value); err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
func ensureNativeDirectory(ctx context.Context, fs storage.FS, p string) error {
|
||||
st, err := fs.Stat(p)
|
||||
if err == nil && st.Kind() == storage.Directory {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil && !errors.Is(err, syscall.ENOENT) {
|
||||
return err
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
if err = removeNative(ctx, fs, p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return fs.Mkdir(p, 0700)
|
||||
}
|
||||
|
||||
func validateNativeDirectory(fs storage.FS, p string) error {
|
||||
current := "/"
|
||||
for _, part := range strings.Split(strings.TrimPrefix(p, "/"), "/") {
|
||||
if part == "" || part == "." || part == ".." {
|
||||
return fmt.Errorf("invalid native path %q", p)
|
||||
}
|
||||
|
||||
current = path.Join(current, part)
|
||||
n, err := fs.Stat(current)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n.Kind() != storage.Directory {
|
||||
return fmt.Errorf("native path contains non-directory %s", current)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -11,48 +11,71 @@ import (
|
||||
bolt "go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete"}
|
||||
var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete", "relinked"}
|
||||
|
||||
type nativeIndex struct {
|
||||
db *bolt.DB
|
||||
path string
|
||||
}
|
||||
type baseEntry struct{ Inode, Version, Size, TargetInode uint64 }
|
||||
|
||||
// baseEntry is the inventory record of one source path. Carried marks an
|
||||
// entry that an earlier version took over unexamined when it skipped an
|
||||
// unchanged-looking subtree. Such an entry may describe an older round, so
|
||||
// it is never trusted. Current versions do not write it.
|
||||
type baseEntry struct {
|
||||
Inode, Version, Size, TargetInode uint64
|
||||
Carried bool
|
||||
}
|
||||
|
||||
func encodeEntry(e baseEntry) []byte {
|
||||
b := make([]byte, 32)
|
||||
b := make([]byte, 33)
|
||||
binary.BigEndian.PutUint64(b, e.Inode)
|
||||
binary.BigEndian.PutUint64(b[8:], e.Version)
|
||||
binary.BigEndian.PutUint64(b[16:], e.Size)
|
||||
binary.BigEndian.PutUint64(b[24:], e.TargetInode)
|
||||
if e.Carried {
|
||||
b[32] = 1
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// decodeEntry also accepts the 32-byte records written before Carried existed.
|
||||
func decodeEntry(b []byte) (baseEntry, bool) {
|
||||
if len(b) != 32 {
|
||||
if len(b) != 32 && (len(b) != 33 || b[32] > 1) {
|
||||
return baseEntry{}, false
|
||||
}
|
||||
return baseEntry{binary.BigEndian.Uint64(b), binary.BigEndian.Uint64(b[8:]), binary.BigEndian.Uint64(b[16:]), binary.BigEndian.Uint64(b[24:])}, true
|
||||
|
||||
e := baseEntry{Inode: binary.BigEndian.Uint64(b), Version: binary.BigEndian.Uint64(b[8:]),
|
||||
Size: binary.BigEndian.Uint64(b[16:]), TargetInode: binary.BigEndian.Uint64(b[24:])}
|
||||
e.Carried = len(b) == 33 && b[32] == 1
|
||||
return e, true
|
||||
}
|
||||
|
||||
func createNativeIndex(parent string) (*nativeIndex, error) {
|
||||
f, err := os.CreateTemp(parent, "pending-*.bolt")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p := f.Name()
|
||||
if err = f.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db, err := bolt.Open(p, 0600, &bolt.Options{Timeout: time.Second, NoSync: true})
|
||||
if err != nil {
|
||||
os.Remove(p)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = db.Update(func(tx *bolt.Tx) error {
|
||||
for _, s := range nativeBuckets {
|
||||
if _, err := tx.CreateBucketIfNotExists([]byte(s)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -60,23 +83,29 @@ func createNativeIndex(parent string) (*nativeIndex, error) {
|
||||
os.Remove(p)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &nativeIndex{db: db, path: p}, nil
|
||||
}
|
||||
|
||||
func openNativeIndex(path string) (*nativeIndex, error) {
|
||||
db, err := bolt.Open(path, 0600, &bolt.Options{ReadOnly: true, Timeout: time.Second})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &nativeIndex{db: db, path: path}, nil
|
||||
}
|
||||
|
||||
func (x *nativeIndex) close() error {
|
||||
if x == nil || x.db == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := x.db.Close()
|
||||
x.db = nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (x *nativeIndex) get(bucket string, key []byte) ([]byte, error) {
|
||||
var b []byte
|
||||
err := x.db.View(func(tx *bolt.Tx) error {
|
||||
@@ -84,19 +113,24 @@ func (x *nativeIndex) get(bucket string, key []byte) ([]byte, error) {
|
||||
if k == nil {
|
||||
return errors.New("invalid native index")
|
||||
}
|
||||
|
||||
b = bytes.Clone(k.Get(key))
|
||||
return nil
|
||||
})
|
||||
|
||||
return b, err
|
||||
}
|
||||
|
||||
func (x *nativeIndex) put(bucket string, key, value []byte) error {
|
||||
return x.db.Update(func(tx *bolt.Tx) error { return tx.Bucket([]byte(bucket)).Put(key, value) })
|
||||
}
|
||||
|
||||
func (x *nativeIndex) entry(rel string) (baseEntry, bool, error) {
|
||||
b, err := x.get("paths", []byte(rel))
|
||||
if err != nil {
|
||||
return baseEntry{}, false, err
|
||||
}
|
||||
|
||||
e, ok := decodeEntry(b)
|
||||
return e, ok, nil
|
||||
}
|
||||
@@ -108,9 +142,11 @@ func (x *nativeIndex) containsPath(rel string) (bool, error) {
|
||||
if err != nil || b == nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if _, ok := decodeEntry(b); !ok {
|
||||
return false, errors.New("invalid source inventory entry")
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -119,9 +155,11 @@ func (x *nativeIndex) putEntryIfChanged(rel string, entry baseEntry) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ok && previous == entry {
|
||||
return nil
|
||||
}
|
||||
|
||||
return x.put("paths", []byte(rel), encodeEntry(entry))
|
||||
}
|
||||
|
||||
@@ -130,11 +168,14 @@ func (x *nativeIndex) requireInventory() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !bytes.Equal(complete, []byte{1}) {
|
||||
return errors.New("source inventory is not complete")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *nativeIndex) each(bucket string, reverse bool, visit func([]byte, []byte) error) error {
|
||||
// The read transaction deliberately spans the iteration. Callbacks must not
|
||||
// write to this same DB (which could deadlock a mmap resize).
|
||||
@@ -143,6 +184,7 @@ func (x *nativeIndex) each(bucket string, reverse bool, visit func([]byte, []byt
|
||||
if b == nil {
|
||||
return errors.New("missing native index bucket")
|
||||
}
|
||||
|
||||
c := b.Cursor()
|
||||
var k, v []byte
|
||||
if reverse {
|
||||
@@ -150,19 +192,23 @@ func (x *nativeIndex) each(bucket string, reverse bool, visit func([]byte, []byt
|
||||
} else {
|
||||
k, v = c.First()
|
||||
}
|
||||
|
||||
for k != nil {
|
||||
if err := visit(k, v); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if reverse {
|
||||
k, v = c.Prev()
|
||||
} else {
|
||||
k, v = c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (x *nativeIndex) ranges(rel string, visit func(uint64, uint64) error) error {
|
||||
prefix := append([]byte(rel), 0)
|
||||
return x.db.View(func(tx *bolt.Tx) error {
|
||||
@@ -171,13 +217,16 @@ func (x *nativeIndex) ranges(rel string, visit func(uint64, uint64) error) error
|
||||
if len(k) != len(prefix)+8 || len(v) != 8 {
|
||||
return errors.New("invalid native extent record")
|
||||
}
|
||||
|
||||
if err := visit(binary.BigEndian.Uint64(k[len(prefix):]), binary.BigEndian.Uint64(v)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (x *nativeIndex) extent(rel string, off, length uint64) error {
|
||||
key := make([]byte, len(rel)+1+8)
|
||||
copy(key, rel)
|
||||
@@ -186,44 +235,54 @@ func (x *nativeIndex) extent(rel string, off, length uint64) error {
|
||||
binary.BigEndian.PutUint64(value, length)
|
||||
return x.put("ranges", key, value)
|
||||
}
|
||||
|
||||
func nativeInodeKey(ino uint64) []byte {
|
||||
b := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(b, ino)
|
||||
return b
|
||||
}
|
||||
|
||||
func nativeDirKey(rel string, depth int) []byte {
|
||||
b := make([]byte, 2+len(rel))
|
||||
binary.BigEndian.PutUint16(b, uint16(depth))
|
||||
copy(b[2:], rel)
|
||||
return b
|
||||
}
|
||||
|
||||
func (x *nativeIndex) commit(parent, name string) error {
|
||||
if err := x.put("meta", []byte("snapshot"), []byte(name)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := x.db.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := x.close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
final := filepath.Join(parent, "base.bolt")
|
||||
if err := os.Rename(x.path, final); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d, err := os.Open(parent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = d.Sync()
|
||||
d.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
read, err := openNativeIndex(final)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
x.path, x.db = read.path, read.db
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/Sebi/CephfsMig/internal/storage"
|
||||
)
|
||||
|
||||
func TestEntryEncodingCarriedAndLegacy(t *testing.T) {
|
||||
e := baseEntry{Inode: 1, Version: 2, Size: 3, TargetInode: 4, Carried: true}
|
||||
got, ok := decodeEntry(encodeEntry(e))
|
||||
if !ok || got != e {
|
||||
t.Fatalf("round trip: %+v %v", got, ok)
|
||||
}
|
||||
|
||||
legacy := encodeEntry(baseEntry{Inode: 1, Version: 2, Size: 3, TargetInode: 4})[:32]
|
||||
if got, ok := decodeEntry(legacy); !ok || got.Carried || got.TargetInode != 4 {
|
||||
t.Fatalf("legacy record: %+v %v", got, ok)
|
||||
}
|
||||
|
||||
for _, bad := range [][]byte{make([]byte, 31), append(make([]byte, 32), 2)} {
|
||||
if _, ok := decodeEntry(bad); ok {
|
||||
t.Fatalf("accepted %d-byte record", len(bad))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseTrustRejectsCarriedEntries(t *testing.T) {
|
||||
n := storage.Node{Inode: 1, Size: 3}
|
||||
target := storage.Node{Inode: 4, Size: 3}
|
||||
e := baseEntry{Inode: 1, Version: 2, Size: 3, TargetInode: 4}
|
||||
if !baseTrusted(e, n, target) {
|
||||
t.Fatal("matching entry not trusted")
|
||||
}
|
||||
|
||||
e.Carried = true
|
||||
if baseTrusted(e, n, target) {
|
||||
t.Fatal("carried entry trusted")
|
||||
}
|
||||
|
||||
e.Carried = false
|
||||
target.Inode = 5
|
||||
if baseTrusted(e, n, target) {
|
||||
t.Fatal("entry of a replaced target trusted")
|
||||
}
|
||||
}
|
||||
@@ -31,13 +31,16 @@ func (f inventoryTargetFS) Stat(p string) (storage.Node, error) {
|
||||
return storage.Node{Mode: s.Mode, Inode: s.Ino, Nlink: s.Nlink, Size: uint64(s.Size), UID: s.Uid, GID: s.Gid,
|
||||
Mtime: time.Unix(s.Mtim.Sec, s.Mtim.Nsec)}, err
|
||||
}
|
||||
|
||||
func (f inventoryTargetFS) OpenDir(p string) (storage.DirectoryStream, error) {
|
||||
d, err := os.Open(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &inventoryDir{file: d, path: p}, nil
|
||||
}
|
||||
|
||||
func (inventoryTargetFS) Unlink(p string) error { return syscall.Unlink(p) }
|
||||
func (inventoryTargetFS) Rmdir(p string) error { return syscall.Rmdir(p) }
|
||||
|
||||
@@ -52,11 +55,14 @@ func (d *inventoryDir) Next() (*storage.Entry, error) {
|
||||
if err == nil {
|
||||
err = io.EOF
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
n, err := (inventoryTargetFS{}).Stat(filepath.Join(d.path, es[0].Name()))
|
||||
return &storage.Entry{Name: es[0].Name(), Node: n}, err
|
||||
}
|
||||
|
||||
func (d *inventoryDir) Close() error { return d.file.Close() }
|
||||
|
||||
func TestNativeInventoryPruneAndVerifyWithoutSourceLookups(t *testing.T) {
|
||||
@@ -64,6 +70,7 @@ func TestNativeInventoryPruneAndVerifyWithoutSourceLookups(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer x.close()
|
||||
root, outside := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{"dir", "obsolete"} {
|
||||
@@ -71,59 +78,75 @@ func TestNativeInventoryPruneAndVerifyWithoutSourceLookups(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, rel := range []string{"keep", "dir/file", "obsolete/nested"} {
|
||||
if err := os.WriteFile(filepath.Join(root, rel), []byte("data"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filepath.Join(outside, "sentinel"), []byte("untouched"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, rel := range []string{"link", "obsolete-link"} {
|
||||
if err := os.Symlink(outside, filepath.Join(root, rel)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, rel := range []string{".", "keep", "dir", "dir/file", "link"} {
|
||||
if err := x.put("paths", []byte(rel), encodeEntry(baseEntry{Inode: 1})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
source := &inventorySourceFS{}
|
||||
b := nativeTransport{source: source, target: inventoryTargetFS{}, pending: x, round: Round{SourcePath: "/immutable"}}
|
||||
if err := b.prune(context.Background(), "/immutable", root); err == nil {
|
||||
t.Fatal("pruned without complete inventory")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(root, "obsolete/nested")); err != nil {
|
||||
t.Fatal("incomplete inventory deleted target data")
|
||||
}
|
||||
|
||||
if err := x.put("meta", []byte("inventory_complete"), []byte{1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := b.verifyInventory(context.Background(), root); err == nil {
|
||||
t.Fatal("unexpected entries were not detected")
|
||||
}
|
||||
|
||||
if err := b.prune(context.Background(), "/immutable", root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := b.verifyInventory(context.Background(), root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := os.Lstat(filepath.Join(root, "obsolete")); !os.IsNotExist(err) {
|
||||
t.Fatal("obsolete directory survived", err)
|
||||
}
|
||||
|
||||
if _, err := os.Lstat(filepath.Join(root, "obsolete-link")); !os.IsNotExist(err) {
|
||||
t.Fatal("obsolete symlink survived", err)
|
||||
}
|
||||
|
||||
if data, err := os.ReadFile(filepath.Join(outside, "sentinel")); err != nil || string(data) != "untouched" {
|
||||
t.Fatal("followed symlink outside target")
|
||||
}
|
||||
|
||||
if source.calls != 0 {
|
||||
t.Fatalf("performed %d redundant source stats", source.calls)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filepath.Join(root, "dir/foreign"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := b.verifyInventory(context.Background(), root); err == nil {
|
||||
t.Fatal("extra target path was ignored")
|
||||
}
|
||||
@@ -135,23 +158,29 @@ func TestNativeInventoryRejectsCorruptionAndUnchangedIndexIsReadOnly(t *testing.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer x.close()
|
||||
if err := x.put("paths", []byte("broken"), []byte{1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := x.containsPath("broken"); err == nil {
|
||||
t.Fatal("corrupt source inventory accepted")
|
||||
}
|
||||
|
||||
entry := baseEntry{Inode: 1, Version: 2, Size: 128, TargetInode: 3}
|
||||
if err := x.putEntryIfChanged("file", entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := x.commit(dir, "snapshot"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := x.putEntryIfChanged("file", entry); err != nil {
|
||||
t.Fatal("unchanged entry attempted a write", err)
|
||||
}
|
||||
|
||||
entry.TargetInode++
|
||||
if err := x.putEntryIfChanged("file", entry); err == nil {
|
||||
t.Fatal("changed entry silently ignored on read-only index")
|
||||
|
||||
@@ -49,25 +49,31 @@ func TestNativeBaseTrust(t *testing.T) {
|
||||
if err := b.BeginRound(context.Background(), r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
entry := baseEntry{Inode: 42, Version: 7, Size: 1 << 30, TargetInode: 77}
|
||||
if err := b.pending.put("paths", []byte("file\nname"), encodeEntry(entry)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := b.Commit(context.Background(), "previous"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
b.identity = tc.identity
|
||||
r.Name, r.SourcePath, r.BaseName = "current", "/sub/.snap/current/uuid", tc.journal
|
||||
if err := b.BeginRound(context.Background(), r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer b.pending.close()
|
||||
if b.base != nil {
|
||||
defer b.base.close()
|
||||
}
|
||||
|
||||
if b.delta != tc.wantDelta {
|
||||
t.Fatalf("delta=%v; want %v", b.delta, tc.wantDelta)
|
||||
}
|
||||
|
||||
if b.delta {
|
||||
got, ok, err := b.base.entry("file\nname")
|
||||
if err != nil || !ok || got != entry {
|
||||
@@ -83,6 +89,7 @@ func TestNativeExtentIsolation(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer x.close()
|
||||
for _, e := range []struct {
|
||||
name string
|
||||
@@ -94,6 +101,7 @@ func TestNativeExtentIsolation(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
var got []storage.Extent
|
||||
if err := x.ranges("a", func(off, length uint64) error {
|
||||
got = append(got, storage.Extent{Offset: off, Length: length})
|
||||
@@ -101,6 +109,7 @@ func TestNativeExtentIsolation(t *testing.T) {
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
want := []storage.Extent{{Offset: 0, Length: 4096}, {Offset: 9000, Length: 100}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %v want %v", got, want)
|
||||
@@ -115,25 +124,45 @@ type attrsTestFS struct {
|
||||
}
|
||||
|
||||
func (f *attrsTestFS) Stat(string) (storage.Node, error) { return f.n, nil }
|
||||
func (f *attrsTestFS) SetAttr(_ string, n storage.Node) error { f.setCalls++; f.n = n; return nil }
|
||||
|
||||
// SetAttr, SetXattr and RemoveXattr follow the change-time rules measured on
|
||||
// Ceph 21.2.0: SetAttr sets the ctime to max(Ctime, Mtime), and an xattr
|
||||
// change resets it to the mtime.
|
||||
func (f *attrsTestFS) SetAttr(_ string, n storage.Node) error {
|
||||
f.setCalls++
|
||||
f.n = n
|
||||
f.n.Ctime = wantedCtime(n)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *attrsTestFS) ListXattr(string) ([]string, error) {
|
||||
var keys []string
|
||||
for k := range f.attrs {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (f *attrsTestFS) GetXattr(_, key string) ([]byte, error) {
|
||||
if v, ok := f.attrs[key]; ok {
|
||||
return v, nil
|
||||
}
|
||||
|
||||
return nil, syscall.ENODATA
|
||||
}
|
||||
|
||||
func (f *attrsTestFS) SetXattr(_, key string, value []byte) error {
|
||||
f.attrs[key] = bytes.Clone(value)
|
||||
f.n.Ctime = f.n.Mtime
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *attrsTestFS) RemoveXattr(_, key string) error {
|
||||
delete(f.attrs, key)
|
||||
f.n.Ctime = f.n.Mtime
|
||||
return nil
|
||||
}
|
||||
func (f *attrsTestFS) RemoveXattr(_, key string) error { delete(f.attrs, key); return nil }
|
||||
|
||||
func TestNativeMetadataEmptyXattrAndDeletion(t *testing.T) {
|
||||
n := storage.Node{Mode: storage.Regular | 0640, UID: 123, GID: 456, Mtime: time.Unix(123, 45)}
|
||||
@@ -142,18 +171,23 @@ func TestNativeMetadataEmptyXattrAndDeletion(t *testing.T) {
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, ok := dst.attrs["user.empty"]; !ok {
|
||||
t.Fatal("empty xattr was not created")
|
||||
}
|
||||
|
||||
if _, ok := dst.attrs["user.old"]; ok {
|
||||
t.Fatal("obsolete xattr survived")
|
||||
}
|
||||
|
||||
if string(dst.attrs["ceph.layout"]) != "target-pool" {
|
||||
t.Fatal("source internal Ceph layout leaked into target")
|
||||
}
|
||||
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dst.n.UID++
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err == nil {
|
||||
t.Fatal("owner mismatch not detected")
|
||||
@@ -167,37 +201,54 @@ func TestNativeCancellationAndPaths(t *testing.T) {
|
||||
if err := b.rate(ctx, 4096); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, bad := range []string{"", ".", "..", ".snap", "a/b", "a\x00b"} {
|
||||
if validNativeEntry(bad) {
|
||||
t.Fatalf("accepted %q", bad)
|
||||
}
|
||||
}
|
||||
|
||||
if !validNativeEntry("with spaces\nand newline") {
|
||||
t.Fatal("valid filename rejected")
|
||||
}
|
||||
|
||||
if _, err := relativeNative("/volume", "/volume-other/file"); err == nil {
|
||||
t.Fatal("path escaped subvolume")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeMetadataOnlyWritesChangedAttributes(t *testing.T) {
|
||||
n := storage.Node{Mode: storage.Regular | 0640, UID: 12, GID: 34, Mtime: time.Unix(123, 0)}
|
||||
n := storage.Node{Mode: storage.Regular | 0640, UID: 12, GID: 34, Mtime: time.Unix(123, 0), Ctime: time.Unix(124, 0)}
|
||||
src := &attrsTestFS{n: n, attrs: map[string][]byte{"user.new": []byte("value")}}
|
||||
dst := &attrsTestFS{n: n, attrs: map[string][]byte{"user.old": []byte("remove")}}
|
||||
dst := &attrsTestFS{n: n, attrs: map[string][]byte{"user.new": []byte("value")}}
|
||||
if err := syncNativeMetadata(src, dst, "/source", "/target", n, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if dst.setCalls != 0 {
|
||||
t.Fatal("unchanged ownership, mode and mtime were rewritten")
|
||||
t.Fatal("unchanged metadata was rewritten")
|
||||
}
|
||||
|
||||
// An xattr change resets the ctime, so SetAttr must follow it.
|
||||
dst.attrs = map[string][]byte{"user.old": []byte("remove")}
|
||||
if err := syncNativeMetadata(src, dst, "/source", "/target", n, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(src.attrs, dst.attrs) {
|
||||
t.Fatal("xattrs must still be synchronized")
|
||||
t.Fatal("xattrs must be synchronized")
|
||||
}
|
||||
|
||||
if dst.setCalls != 1 || !dst.n.Ctime.Equal(n.Ctime) {
|
||||
t.Fatalf("ctime not restored after xattr change: calls=%d ctime=%v", dst.setCalls, dst.n.Ctime)
|
||||
}
|
||||
|
||||
dst.n.UID++
|
||||
if err := syncNativeMetadata(src, dst, "/source", "/target", n, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dst.setCalls != 1 || dst.n.UID != n.UID {
|
||||
|
||||
if dst.setCalls != 2 || dst.n.UID != n.UID {
|
||||
t.Fatal("changed ownership was not restored")
|
||||
}
|
||||
}
|
||||
@@ -208,27 +259,121 @@ func TestNativeVerifyCommittedRound(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer index.close()
|
||||
n := storage.Node{Mode: storage.Regular | 0640, Inode: 7, Version: 1, Nlink: 1, Mtime: time.Unix(123, 0)}
|
||||
n := storage.Node{Mode: storage.Regular | 0640, Inode: 7, Version: 1, Nlink: 1,
|
||||
Mtime: time.Unix(123, 0), Ctime: time.Unix(124, 0)}
|
||||
src := &attrsTestFS{n: n, attrs: map[string][]byte{}}
|
||||
dst := &attrsTestFS{n: n, attrs: map[string][]byte{}}
|
||||
if err := index.put("groups", nativeInodeKey(n.Inode), []byte(".")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := index.put("paths", []byte("."), encodeEntry(baseEntry{Inode: n.Inode, Version: n.Version})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := index.put("meta", []byte("inventory_complete"), []byte{1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := index.commit(workspace, "final"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
b := nativeTransport{source: src, target: dst, pending: index, workspace: workspace,
|
||||
round: Round{SourcePath: "/snapshot", TargetPath: "/live"}, verified: map[string]bool{"/live": true}}
|
||||
|
||||
// Finalization repeats metadata/topology verification after the durable base
|
||||
// index has become read-only. It must not rewrite inode records at this stage.
|
||||
if err := b.Verify(context.Background(), "/snapshot", "/live"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeMetadataPreservesAccessAndBirthTime(t *testing.T) {
|
||||
n := storage.Node{Mode: storage.Regular | 0640, UID: 1, GID: 2,
|
||||
Atime: time.Unix(100, 1), Mtime: time.Unix(200, 2), Btime: time.Unix(50, 3)}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
change func(*storage.Node)
|
||||
}{
|
||||
{"atime", func(x *storage.Node) { x.Atime = time.Unix(999, 0) }},
|
||||
{"btime", func(x *storage.Node) { x.Btime = time.Unix(999, 0) }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
target := n
|
||||
tc.change(&target)
|
||||
src := &attrsTestFS{n: n, attrs: map[string][]byte{}}
|
||||
dst := &attrsTestFS{n: target, attrs: map[string][]byte{}}
|
||||
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err == nil {
|
||||
t.Fatal("mismatch not detected")
|
||||
}
|
||||
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if dst.setCalls != 1 || !dst.n.Atime.Equal(n.Atime) || !dst.n.Btime.Equal(n.Btime) {
|
||||
t.Fatalf("times not restored: %+v", dst.n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeMetadataChangeTime(t *testing.T) {
|
||||
n := storage.Node{Mode: storage.Regular | 0640, Mtime: time.Unix(400, 0), Ctime: time.Unix(500, 5)}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
targetCtime time.Time
|
||||
sourceAttrs map[string][]byte
|
||||
}{
|
||||
{"older target is raised", time.Unix(1, 0), nil},
|
||||
{"newer target is lowered", time.Unix(900, 0), nil},
|
||||
{"set after xattr changes", n.Ctime, map[string][]byte{"user.new": []byte("v")}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
target := n
|
||||
target.Ctime = tc.targetCtime
|
||||
attrs := tc.sourceAttrs
|
||||
if attrs == nil {
|
||||
attrs = map[string][]byte{}
|
||||
}
|
||||
|
||||
src := &attrsTestFS{n: n, attrs: attrs}
|
||||
dst := &attrsTestFS{n: target, attrs: map[string][]byte{}}
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err == nil {
|
||||
t.Fatal("mismatch not detected")
|
||||
}
|
||||
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !dst.n.Ctime.Equal(n.Ctime) {
|
||||
t.Fatalf("ctime %v; want %v", dst.n.Ctime, n.Ctime)
|
||||
}
|
||||
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("ctime below mtime", func(t *testing.T) {
|
||||
future := n
|
||||
future.Mtime = time.Unix(800, 0) // mtime set into the future
|
||||
src := &attrsTestFS{n: future, attrs: map[string][]byte{}}
|
||||
dst := &attrsTestFS{n: n, attrs: map[string][]byte{}}
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", future, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := syncNativeMetadata(src, dst, "/src", "/dst", future, true); err != nil {
|
||||
t.Fatalf("closest reachable ctime rejected: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -25,17 +25,29 @@ const nativeBlockThreshold = 16 << 20
|
||||
type nativeTransport struct {
|
||||
source, target storage.FS
|
||||
config Config
|
||||
|
||||
// openTarget opens another client of the target. Claim holds its lock
|
||||
// through one, so that Verify can replace the writing client: Verify
|
||||
// closes the writer, which returns all its caps, and continues with a
|
||||
// fresh client. Nil means Verify and Claim use target as it is.
|
||||
openTarget func() (storage.FS, error)
|
||||
|
||||
log io.Writer
|
||||
identity string
|
||||
|
||||
// State of the current round.
|
||||
round Round
|
||||
workspace string
|
||||
pending, base *nativeIndex
|
||||
delta bool
|
||||
snapRoot, snapRel string
|
||||
verified map[string]bool
|
||||
visited, copied, written, checked, blockFiles, diffEntries atomic.Int64
|
||||
rateBytes atomic.Int64
|
||||
started time.Time
|
||||
|
||||
// Counters reported by Statistics and used for rate limiting.
|
||||
visited, copied, written atomic.Int64
|
||||
checked, blockFiles atomic.Int64
|
||||
diffEntries, rateBytes atomic.Int64
|
||||
}
|
||||
|
||||
func (b *nativeTransport) Close() error {
|
||||
@@ -43,50 +55,62 @@ func (b *nativeTransport) Close() error {
|
||||
if b.pending != nil {
|
||||
errs = append(errs, b.pending.close())
|
||||
}
|
||||
|
||||
if b.base != nil {
|
||||
errs = append(errs, b.base.close())
|
||||
}
|
||||
|
||||
errs = append(errs, b.source.Close(), b.target.Close())
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error {
|
||||
if b.pending != nil {
|
||||
if err := b.pending.close(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if b.base != nil {
|
||||
if err := b.base.close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.base = nil
|
||||
}
|
||||
|
||||
b.round = r
|
||||
b.workspace = r.StatePath + ".native"
|
||||
if err := privateDirectories(b.workspace); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
files, err := os.ReadDir(b.workspace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
if strings.HasPrefix(f.Name(), "pending-") && strings.HasSuffix(f.Name(), ".bolt") {
|
||||
if !f.Type().IsRegular() {
|
||||
return errors.New("native scratch path is not a regular file")
|
||||
}
|
||||
|
||||
if err = os.Remove(filepath.Join(b.workspace, f.Name())); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
b.pending, err = createNativeIndex(b.workspace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = b.pending.put("meta", []byte("identity"), []byte(b.identity)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.delta = false
|
||||
b.verified = map[string]bool{}
|
||||
b.visited.Store(0)
|
||||
@@ -102,11 +126,13 @@ func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error {
|
||||
if at < 0 {
|
||||
return errors.New("native source snapshot path does not contain its snapshot name")
|
||||
}
|
||||
|
||||
b.snapRoot = r.SourcePath[:at]
|
||||
b.snapRel = r.SourcePath[at+len(marker):]
|
||||
if b.snapRel == "" {
|
||||
b.snapRel = "/"
|
||||
}
|
||||
|
||||
if r.BaseName != "" {
|
||||
base, err := openNativeIndex(filepath.Join(b.workspace, "base.bolt"))
|
||||
if err == nil {
|
||||
@@ -122,29 +148,36 @@ func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error {
|
||||
fmt.Fprintf(b.log, "native base index unavailable; rebuilding full snapshot: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
if b.delta {
|
||||
if err := b.collectChanges(ctx, b.snapRel, r.SourcePath, 0); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
b.delta = false
|
||||
if b.log != nil {
|
||||
fmt.Fprintf(b.log, "native snapdiff unavailable for this pair; full reconstruction: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if b.log != nil {
|
||||
fmt.Fprintf(b.log, "native snapshot=%s mode=%s\n", r.Name, b.Statistics().Mode)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *nativeTransport) collectChanges(ctx context.Context, rel, current string, depth int) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if depth > 128 {
|
||||
return errors.New("snapdiff depth exceeds 128")
|
||||
}
|
||||
|
||||
d, err := b.source.SnapDiff(b.snapRoot, rel, b.round.BaseName, b.round.Name)
|
||||
if errors.Is(err, syscall.ENOENT) {
|
||||
return nil
|
||||
@@ -152,11 +185,13 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer d.Close()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
name, err := d.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
@@ -164,9 +199,11 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !validNativeEntry(name) {
|
||||
return fmt.Errorf("invalid snapdiff entry %q", name)
|
||||
}
|
||||
|
||||
b.diffEntries.Add(1)
|
||||
child := path.Join(current, name)
|
||||
n, err := b.source.Stat(child)
|
||||
@@ -176,6 +213,7 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n.Kind() == storage.Directory {
|
||||
if err = b.collectChanges(ctx, path.Join(rel, name), child, depth+1); err != nil {
|
||||
return err
|
||||
@@ -187,16 +225,20 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validNativeEntry(name string) bool {
|
||||
return name != "" && name != "." && name != ".." && name != ".snap" && !strings.ContainsAny(name, "/\x00")
|
||||
}
|
||||
|
||||
func relativeNative(root, p string) (string, error) {
|
||||
if p == root {
|
||||
return ".", nil
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(p, root+"/") {
|
||||
return "", fmt.Errorf("native path escapes root: %s", p)
|
||||
}
|
||||
|
||||
return strings.TrimPrefix(p, root+"/"), nil
|
||||
}
|
||||
|
||||
@@ -210,12 +252,14 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
if b.pending == nil || from != b.round.SourcePath || to != b.round.TargetPath {
|
||||
return errors.New("native copy round is not initialized")
|
||||
}
|
||||
|
||||
copyCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
workers := b.config.Workers
|
||||
if workers == 0 {
|
||||
workers = 8
|
||||
}
|
||||
|
||||
jobs := make(chan nativeJob, workers*2)
|
||||
errorsOut := make(chan error, 1)
|
||||
var wg sync.WaitGroup
|
||||
@@ -229,11 +273,13 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
case errorsOut <- err:
|
||||
default:
|
||||
}
|
||||
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
lastProgress := time.Now()
|
||||
walkErr := walkNative(copyCtx, b.source, from, func(p string, n storage.Node, depth int) error {
|
||||
b.visited.Add(1)
|
||||
@@ -241,10 +287,12 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
fmt.Fprintf(b.log, "native copying visited=%d copied=%d bytes_written=%d\n", b.visited.Load(), b.copied.Load(), b.written.Load())
|
||||
lastProgress = time.Now()
|
||||
}
|
||||
|
||||
rel, err := relativeNative(from, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
target := path.Join(to, rel)
|
||||
// Record every immutable source entry before dispatching work. This local
|
||||
// inventory replaces source path lookups during pruning and verification.
|
||||
@@ -253,6 +301,7 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
})); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// POSIX hardlinks can also refer to symlinks and special files. Track all
|
||||
// non-directory inodes, then create their aliases after canonical entries.
|
||||
if n.Kind() != storage.Directory {
|
||||
@@ -260,106 +309,144 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if first != nil {
|
||||
return b.pending.put("aliases", []byte(rel), first)
|
||||
}
|
||||
|
||||
if err = b.pending.put("groups", nativeInodeKey(n.Inode), []byte(rel)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
switch n.Kind() {
|
||||
case storage.Directory:
|
||||
if err = ensureNativeDirectory(copyCtx, b.target, target); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return b.pending.put("dirs", nativeDirKey(rel, depth), []byte(rel))
|
||||
|
||||
case storage.Regular:
|
||||
if n.Size > math.MaxInt64 {
|
||||
return errors.New("file exceeds supported signed offset range")
|
||||
}
|
||||
|
||||
select {
|
||||
case jobs <- nativeJob{rel, n}:
|
||||
return nil
|
||||
|
||||
case <-copyCtx.Done():
|
||||
return copyCtx.Err()
|
||||
}
|
||||
|
||||
case storage.Symlink, storage.FIFO, storage.Socket, storage.CharDevice, storage.BlockDevice:
|
||||
return b.copySpecial(copyCtx, rel, n)
|
||||
|
||||
default:
|
||||
return fmt.Errorf("unsupported native file type %o at %s", n.Mode, p)
|
||||
}
|
||||
})
|
||||
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
select {
|
||||
case err := <-errorsOut:
|
||||
return err
|
||||
|
||||
default:
|
||||
}
|
||||
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
|
||||
if err = b.pending.put("meta", []byte("inventory_complete"), []byte{1}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Complete links only after every canonical file is durable.
|
||||
if err = b.pending.each("aliases", false, func(k, v []byte) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dst, canonical := path.Join(to, string(k)), path.Join(to, string(v))
|
||||
a, err := b.target.Stat(canonical)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
old, err := b.target.Stat(dst)
|
||||
if err == nil && old.Kind() == a.Kind() && old.Inode == a.Inode {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil && !errors.Is(err, syscall.ENOENT) {
|
||||
return err
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
if err = removeNative(ctx, b.target, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := b.target.Link(canonical, dst); err != nil {
|
||||
return fmt.Errorf("native hardlink %s -> %s: %w", string(k), string(v), err)
|
||||
}
|
||||
return nil
|
||||
|
||||
// Linking resets the ctime of the inode; set it again.
|
||||
src := path.Join(from, string(k))
|
||||
n, err := b.source.Stat(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return restoreNativeMetadata(b.source, b.target, src, dst, n)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = b.prune(ctx, from, to); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Child creation/deletion has finished; restore directory metadata last.
|
||||
// Creating or removing a child sets the ctime of its directory on the
|
||||
// MDS, while the cache of this client may keep the old value, so the
|
||||
// cached stat cannot tell whether a directory is current.
|
||||
if err = b.pending.each("dirs", true, func(_, v []byte) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rel := string(v)
|
||||
src, dst := path.Join(from, rel), path.Join(to, rel)
|
||||
n, err := b.source.Stat(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return syncNativeMetadata(b.source, b.target, src, dst, n, false)
|
||||
|
||||
return restoreNativeMetadata(b.source, b.target, src, dst, n)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return b.target.Sync()
|
||||
}
|
||||
|
||||
func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage.Node) error {
|
||||
src, dst := path.Join(b.round.SourcePath, rel), path.Join(b.round.TargetPath, rel)
|
||||
_, err := b.target.Stat(dst)
|
||||
if err != nil && !errors.Is(err, syscall.ENOENT) {
|
||||
return err
|
||||
}
|
||||
|
||||
exists := err == nil
|
||||
var text string
|
||||
if n.Kind() == storage.Symlink {
|
||||
@@ -368,6 +455,7 @@ func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Recreate canonical special inodes so previously linked, now independent
|
||||
// source entries cannot remain accidentally linked at the target.
|
||||
if exists {
|
||||
@@ -375,6 +463,7 @@ func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if n.Kind() == storage.Symlink {
|
||||
err = b.target.Symlink(text, dst)
|
||||
} else {
|
||||
@@ -383,51 +472,119 @@ func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return syncNativeMetadata(b.source, b.target, src, dst, n, false)
|
||||
}
|
||||
|
||||
func (b *nativeTransport) prune(ctx context.Context, from, to string) error {
|
||||
if from != b.round.SourcePath {
|
||||
return errors.New("source inventory belongs to a different round")
|
||||
}
|
||||
|
||||
if err := b.pending.requireInventory(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Store deletions on disk and apply after closing the directory streams.
|
||||
err := walkNative(ctx, b.target, to, func(p string, _ storage.Node, _ int) error {
|
||||
err := walkNative(ctx, b.target, to, func(p string, n storage.Node, _ int) error {
|
||||
rel, err := relativeNative(to, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if rel == "." {
|
||||
return nil
|
||||
}
|
||||
|
||||
present, err := b.pending.containsPath(rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !present {
|
||||
return b.pending.put("delete", []byte(rel), []byte{1})
|
||||
}
|
||||
|
||||
if present {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Removing one name of a hardlinked inode resets its ctime; the
|
||||
// remaining names are set again below.
|
||||
if n.Kind() != storage.Directory && n.Nlink > 1 {
|
||||
if err = b.pending.put("relinked", nativeInodeKey(n.Inode), []byte{1}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return b.pending.put("delete", []byte(rel), []byte{1})
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return b.pending.each("delete", true, func(k, _ []byte) error { return removeNative(ctx, b.target, path.Join(to, string(k))) })
|
||||
|
||||
err = b.pending.each("delete", true, func(k, _ []byte) error {
|
||||
return removeNative(ctx, b.target, path.Join(to, string(k)))
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return b.restoreRelinked(from, to)
|
||||
}
|
||||
|
||||
// restoreRelinked sets the metadata of regular files again whose target inode
|
||||
// lost a name during pruning. The source inventory records the target inode
|
||||
// of every regular file copied in this round.
|
||||
func (b *nativeTransport) restoreRelinked(from, to string) error {
|
||||
inodes := map[uint64]bool{}
|
||||
if err := b.pending.each("relinked", false, func(k, _ []byte) error {
|
||||
inodes[binary.BigEndian.Uint64(k)] = true
|
||||
return nil
|
||||
}); err != nil || len(inodes) == 0 {
|
||||
return err
|
||||
}
|
||||
|
||||
var rels []string
|
||||
if err := b.pending.each("paths", false, func(k, v []byte) error {
|
||||
if e, ok := decodeEntry(v); ok && e.TargetInode != 0 && inodes[e.TargetInode] {
|
||||
rels = append(rels, string(k))
|
||||
}
|
||||
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, rel := range rels {
|
||||
src := path.Join(from, rel)
|
||||
n, err := b.source.Stat(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = restoreNativeMetadata(b.source, b.target, src, path.Join(to, rel), n); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *nativeTransport) Published(p string) { b.verified[p] = true }
|
||||
|
||||
func (b *nativeTransport) Commit(ctx context.Context, name string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if b.base != nil {
|
||||
if err := b.base.close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.base = nil
|
||||
}
|
||||
|
||||
return b.pending.commit(b.workspace, name)
|
||||
}
|
||||
|
||||
func (b *nativeTransport) Statistics() TransferStats {
|
||||
mode := "full"
|
||||
base := ""
|
||||
@@ -435,27 +592,38 @@ func (b *nativeTransport) Statistics() TransferStats {
|
||||
mode = "snapdiff"
|
||||
base = b.round.BaseName
|
||||
}
|
||||
|
||||
return TransferStats{Mode: mode, BaseSnapshot: base, FilesVisited: b.visited.Load(),
|
||||
FilesCopied: b.copied.Load(), BytesCopied: b.written.Load(), BytesVerified: b.checked.Load(),
|
||||
BlockDiffFiles: b.blockFiles.Load(), SnapDiffEntries: b.diffEntries.Load()}
|
||||
BlockDiffFiles: b.blockFiles.Load(), SnapDiffEntries: b.diffEntries.Load(),
|
||||
Seconds: math.Round(time.Since(b.started).Seconds()*1000) / 1000}
|
||||
}
|
||||
|
||||
func (b *nativeTransport) rate(ctx context.Context, n int) error {
|
||||
if b.config.BandwidthKiB == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
total := b.rateBytes.Add(int64(n))
|
||||
seconds := float64(total) / float64(b.config.BandwidthKiB*1024)
|
||||
wait := time.Duration(seconds*float64(time.Second)) - time.Since(b.started)
|
||||
if wait <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
timer := time.NewTimer(wait)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
return nil
|
||||
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
func nodeKey(ino uint64) [16]byte { var b [16]byte; binary.BigEndian.PutUint64(b[:], ino); return b }
|
||||
|
||||
func nodeKey(ino uint64) [16]byte {
|
||||
var b [16]byte
|
||||
binary.BigEndian.PutUint64(b[:], ino)
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/CephfsMig/internal/storage"
|
||||
)
|
||||
|
||||
// diskFS is a read-only storage.FS over the local file system. Stat reports
|
||||
// the mtime as ctime and leaves the other times zero, so two copies with
|
||||
// equal mtimes compare as equal metadata. Symlinks report no times.
|
||||
type diskFS struct{ storage.FS }
|
||||
|
||||
func (diskFS) Stat(p string) (storage.Node, error) {
|
||||
var s syscall.Stat_t
|
||||
if err := syscall.Lstat(p, &s); err != nil {
|
||||
return storage.Node{}, err
|
||||
}
|
||||
|
||||
mtime := time.Unix(s.Mtim.Sec, s.Mtim.Nsec)
|
||||
if s.Mode&syscall.S_IFMT == syscall.S_IFLNK {
|
||||
mtime = time.Time{} // os.Chtimes cannot set symlink times.
|
||||
}
|
||||
|
||||
return storage.Node{Mode: s.Mode, Inode: s.Ino, Nlink: uint64(s.Nlink), Size: uint64(s.Size),
|
||||
UID: s.Uid, GID: s.Gid, Mtime: mtime, Ctime: mtime}, nil
|
||||
}
|
||||
|
||||
func (diskFS) OpenDir(p string) (storage.DirectoryStream, error) {
|
||||
d, err := os.Open(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &diskDir{file: d, path: p}, nil
|
||||
}
|
||||
|
||||
func (diskFS) Open(p string, _ int, _ uint32) (storage.File, error) {
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return diskFile{f}, nil
|
||||
}
|
||||
|
||||
func (diskFS) Readlink(p string) (string, error) { return os.Readlink(p) }
|
||||
func (diskFS) ListXattr(string) ([]string, error) { return nil, nil }
|
||||
func (diskFS) GetXattr(string, string) ([]byte, error) { return nil, syscall.ENODATA }
|
||||
|
||||
type diskFile struct{ *os.File }
|
||||
|
||||
func (diskFile) Lock(uint64) error { return nil }
|
||||
func (diskFile) PunchHole(int64, int64) error { return syscall.ENOTSUP }
|
||||
|
||||
type diskDir struct {
|
||||
file *os.File
|
||||
path string
|
||||
}
|
||||
|
||||
func (d *diskDir) Next() (*storage.Entry, error) {
|
||||
es, err := d.file.ReadDir(1)
|
||||
if len(es) == 0 {
|
||||
if err == nil {
|
||||
err = io.EOF
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
n, err := (diskFS{}).Stat(filepath.Join(d.path, es[0].Name()))
|
||||
return &storage.Entry{Name: es[0].Name(), Node: n}, err
|
||||
}
|
||||
|
||||
func (d *diskDir) Close() error { return d.file.Close() }
|
||||
|
||||
// verifyTree builds the same tree under src and dst: files spread over
|
||||
// directories, one hardlink pair and one symlink.
|
||||
func verifyTree(t *testing.T, src, dst string, files int) {
|
||||
t.Helper()
|
||||
stamp := time.Unix(1700000000, 0)
|
||||
for _, root := range []string{src, dst} {
|
||||
for i := 0; i < files; i++ {
|
||||
rel := filepath.Join(fmt.Sprintf("d%02d", i%7), fmt.Sprintf("f%04d", i))
|
||||
if err := os.MkdirAll(filepath.Join(root, filepath.Dir(rel)), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := filepath.Join(root, rel)
|
||||
if err := os.WriteFile(p, []byte(fmt.Sprintf("payload %d", i)), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.Chtimes(p, stamp, stamp.Add(time.Duration(i)*time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.Link(filepath.Join(root, "d00", "f0000"), filepath.Join(root, "hard")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.Symlink("d00/f0000", filepath.Join(root, "soft")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Directory mtimes changed while their entries were created.
|
||||
for _, root := range []string{src, dst} {
|
||||
if err := filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil || !d.IsDir() {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.Chtimes(p, stamp, stamp)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// verifyIndex records the inventory of src in a fresh index, as the copy
|
||||
// phase does: every path, the canonical path of every inode and the files
|
||||
// copied in full.
|
||||
func verifyIndex(t *testing.T, src string) *nativeIndex {
|
||||
t.Helper()
|
||||
x, err := createNativeIndex(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() { x.close() })
|
||||
err = filepath.WalkDir(src, func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rel, err := filepath.Rel(src, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
n, err := (diskFS{}).Stat(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = x.put("paths", []byte(rel), encodeEntry(baseEntry{Inode: n.Inode})); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n.Kind() != storage.Regular {
|
||||
return nil
|
||||
}
|
||||
|
||||
if old, err := x.get("groups", nativeInodeKey(n.Inode)); err != nil || old != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = x.put("groups", nativeInodeKey(n.Inode), []byte(rel)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return x.put("full", []byte(rel), []byte{1})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := x.put("meta", []byte("inventory_complete"), []byte{1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return x
|
||||
}
|
||||
|
||||
func TestNativeVerifyParallel(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
damage func(t *testing.T, dst string)
|
||||
want string
|
||||
}{
|
||||
{"identical", nil, ""},
|
||||
{"content", func(t *testing.T, dst string) {
|
||||
p := filepath.Join(dst, "d03", "f0150")
|
||||
info, err := os.Stat(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(p, []byte("payload 15X"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.Chtimes(p, info.ModTime(), info.ModTime()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.Chtimes(filepath.Dir(p), time.Unix(1700000000, 0), time.Unix(1700000000, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}, "content mismatch"},
|
||||
{"split hardlink", func(t *testing.T, dst string) {
|
||||
p := filepath.Join(dst, "hard")
|
||||
info, err := os.Stat(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.Remove(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(p, data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, x := range []string{p, dst} {
|
||||
mtime := info.ModTime()
|
||||
if x == dst {
|
||||
mtime = time.Unix(1700000000, 0)
|
||||
}
|
||||
|
||||
if err := os.Chtimes(x, mtime, mtime); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}, "hardlink group was split"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
src, dst := t.TempDir(), t.TempDir()
|
||||
verifyTree(t, src, dst, 400)
|
||||
if tc.damage != nil {
|
||||
tc.damage(t, dst)
|
||||
}
|
||||
|
||||
b := nativeTransport{source: diskFS{}, target: diskFS{}, pending: verifyIndex(t, src),
|
||||
workspace: t.TempDir(), config: Config{Workers: 16},
|
||||
round: Round{SourcePath: src, TargetPath: dst}, verified: map[string]bool{}}
|
||||
err := b.Verify(context.Background(), src, dst)
|
||||
if tc.want == "" {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !b.verified[dst] || b.checked.Load() == 0 {
|
||||
t.Fatalf("verified=%v checked=%d", b.verified[dst], b.checked.Load())
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("error %v; want %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// closingFS records whether Close was called.
|
||||
type closingFS struct {
|
||||
diskFS
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (f *closingFS) Close() error { f.closed = true; return nil }
|
||||
|
||||
func TestNativeVerifyReplacesWriter(t *testing.T) {
|
||||
src, dst := t.TempDir(), t.TempDir()
|
||||
verifyTree(t, src, dst, 20)
|
||||
writer := &closingFS{}
|
||||
var opened []*closingFS
|
||||
b := nativeTransport{source: diskFS{}, target: writer, pending: verifyIndex(t, src),
|
||||
workspace: t.TempDir(), round: Round{SourcePath: src, TargetPath: dst}, verified: map[string]bool{},
|
||||
openTarget: func() (storage.FS, error) {
|
||||
f := &closingFS{}
|
||||
opened = append(opened, f)
|
||||
return f, nil
|
||||
}}
|
||||
|
||||
if err := b.Verify(context.Background(), src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !writer.closed || len(opened) != 1 || b.target != storage.FS(opened[0]) || opened[0].closed {
|
||||
t.Fatalf("writer closed=%v, opened=%d, target replaced=%v", writer.closed, len(opened),
|
||||
len(opened) == 1 && b.target == storage.FS(opened[0]))
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,11 @@ func (b *tailBuffer) Write(p []byte) (int, error) {
|
||||
b.data = append(b.data[:0], p[n-limit:]...)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
if len(b.data)+n > limit {
|
||||
b.data = append(b.data[:0], b.data[len(b.data)+n-limit:]...)
|
||||
}
|
||||
|
||||
b.data = append(b.data, p...)
|
||||
return n, nil
|
||||
}
|
||||
@@ -63,6 +65,7 @@ func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...s
|
||||
if p.Stderr != nil {
|
||||
cmd.Stderr = io.MultiWriter(p.Stderr, &diagnostic)
|
||||
}
|
||||
|
||||
cmd.Env = append(os.Environ(), "LC_ALL=C")
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Cancel = func() error {
|
||||
@@ -70,16 +73,20 @@ func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...s
|
||||
if errors.Is(err, syscall.ESRCH) {
|
||||
return os.ErrProcessDone
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.WaitDelay = 5 * time.Second
|
||||
if err := cmd.Run(); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// Do not print arguments: Ceph metadata values may be confidential.
|
||||
return &ProcessError{Name: name, Err: err, Diagnostic: strings.TrimSpace(string(diagnostic.data))}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -92,6 +99,7 @@ func (b *limitedBuffer) Write(p []byte) (int, error) {
|
||||
if len(p) > b.limit-b.Len() {
|
||||
return 0, errors.New("command output exceeds configured limit")
|
||||
}
|
||||
|
||||
return b.Buffer.Write(p)
|
||||
}
|
||||
|
||||
@@ -100,5 +108,6 @@ func output(ctx context.Context, x Executor, name string, args ...string) ([]byt
|
||||
if err := x.Exec(ctx, b, name, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestProcessCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.Canceled {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.DeadlineExceeded {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
|
||||
if time.Since(start) > 2*time.Second {
|
||||
t.Fatal("cancellation was too slow")
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Transport copies a snapshot tree to the target and verifies the result.
|
||||
type Transport interface {
|
||||
Copy(context.Context, string, string) error
|
||||
Verify(context.Context, string, string) error
|
||||
}
|
||||
|
||||
// Rsync is the Transport that copies between mounted CephFS trees with
|
||||
// rsync. BandwidthKiB limits the transfer rate when positive.
|
||||
type Rsync struct {
|
||||
Exec Executor
|
||||
Log io.Writer
|
||||
BandwidthKiB int64
|
||||
}
|
||||
|
||||
func (r Rsync) args(src, dst string) []string {
|
||||
a := []string{"-aHAXS", "--numeric-ids", "--checksum", "--no-whole-file",
|
||||
"--delete-during", "--partial", "--fsync", "--one-file-system",
|
||||
"--filter=- .snap/", "--filter=-x ceph.*", "--filter=-x system.*"}
|
||||
if r.BandwidthKiB > 0 {
|
||||
a = append(a, "--bwlimit="+strconv.FormatInt(r.BandwidthKiB, 10))
|
||||
}
|
||||
return append(a, "--", src+"/", dst+"/")
|
||||
}
|
||||
|
||||
// Copy mirrors src into dst, including hard links, ACLs and xattrs.
|
||||
func (r Rsync) Copy(ctx context.Context, src, dst string) error {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
err := r.Exec.Exec(ctx, r.Log, "rsync", r.args(src, dst)...)
|
||||
var processError *ProcessError
|
||||
var exitError *exec.ExitError
|
||||
// EEXIST was observed on Ceph-FUSE while rsync rebuilt a hardlink group.
|
||||
// One idempotent retry repairs the partial group. All other errors
|
||||
// are returned immediately; publication still requires full verification.
|
||||
if attempt == 0 && errors.As(err, &processError) && errors.As(err, &exitError) && exitError.ExitCode() == 23 && strings.Contains(processError.Diagnostic, "link ") && strings.Contains(processError.Diagnostic, "File exists (17)") {
|
||||
if r.Log != nil {
|
||||
fmt.Fprintln(r.Log, "rsync hardlink EEXIST: retrying once before snapshot verification")
|
||||
}
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
return errors.New("rsync retry limit reached")
|
||||
}
|
||||
|
||||
type differences struct{ n int64 }
|
||||
|
||||
func (d *differences) Write(p []byte) (int, error) { d.n += int64(len(p)); return len(p), nil }
|
||||
|
||||
// Verify runs rsync as a dry run and fails if any difference remains.
|
||||
func (r Rsync) Verify(ctx context.Context, src, dst string) error {
|
||||
args := append([]string{"--dry-run", "--itemize-changes", "--out-format=%i"}, r.args(src, dst)...)
|
||||
var d differences
|
||||
if err := r.Exec.Exec(ctx, &d, "rsync", args...); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.n != 0 {
|
||||
return fmt.Errorf("verification found differences between %s and %s", src, dst)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type executorFunc func(context.Context, io.Writer, string, ...string) error
|
||||
|
||||
func (f executorFunc) Exec(ctx context.Context, out io.Writer, name string, args ...string) error {
|
||||
return f(ctx, out, name, args...)
|
||||
}
|
||||
|
||||
func TestRsyncRetriesOnlyObservedHardlinkEEXIST(t *testing.T) {
|
||||
exitErr := exec.Command("sh", "-c", "exit 23").Run()
|
||||
for name, tc := range map[string]struct {
|
||||
diagnostic string
|
||||
attempts int
|
||||
}{
|
||||
"hardlink": {"link target failed: File exists (17)", 2},
|
||||
"permission": {"Permission denied (13)", 1},
|
||||
"other-eexist": {"mkdir failed: File exists (17)", 1},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
calls := 0
|
||||
x := executorFunc(func(context.Context, io.Writer, string, ...string) error {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return &ProcessError{Name: "rsync", Err: exitErr, Diagnostic: tc.diagnostic}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
err := (Rsync{Exec: x, Log: io.Discard}).Copy(context.Background(), "/a", "/b")
|
||||
if calls != tc.attempts {
|
||||
t.Fatalf("attempts: %d", calls)
|
||||
}
|
||||
if (err == nil) != (tc.attempts == 2) {
|
||||
t.Fatalf("unexpected result: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
calls := 0
|
||||
x := executorFunc(func(context.Context, io.Writer, string, ...string) error { calls++; return context.Canceled })
|
||||
err := (Rsync{Exec: x}).Copy(context.Background(), "/a", "/b")
|
||||
if !errors.Is(err, context.Canceled) || calls != 1 {
|
||||
t.Fatalf("retried cancellation: %v, %d", err, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRsyncDetectsSameSizeSameMtimeAndPreservesLinks(t *testing.T) {
|
||||
if _, err := exec.LookPath("rsync"); err != nil {
|
||||
t.Skip("rsync is not installed")
|
||||
}
|
||||
src, dst := t.TempDir(), t.TempDir()
|
||||
path := filepath.Join(src, "file with spaces\nand newline")
|
||||
if err := os.WriteFile(path, []byte("AAAA"), 0640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(path, filepath.Join(src, "hardlink")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink("nonexistent", filepath.Join(src, "dangling")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := syscall.Setxattr(path, "user.cephmig", []byte("test"), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := Rsync{Exec: Process{Stderr: io.Discard}, Log: io.Discard}
|
||||
ctx := context.Background()
|
||||
if err := r.Copy(ctx, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Verify(ctx, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, _ := os.Stat(filepath.Join(dst, "hardlink"))
|
||||
b, _ := os.Stat(filepath.Join(dst, filepath.Base(path)))
|
||||
if !os.SameFile(a, b) {
|
||||
t.Fatal("hardlinks were split")
|
||||
}
|
||||
st, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.WriteFile(path, []byte("BBBB"), 0640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.Chtimes(path, st.ModTime(), st.ModTime()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = r.Verify(ctx, src, dst); err == nil {
|
||||
t.Fatal("checksum verification missed changed bytes")
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(dst, "obsolete"), []byte("extra"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = r.Copy(ctx, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = r.Verify(ctx, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = os.Stat(filepath.Join(dst, "obsolete")); !os.IsNotExist(err) {
|
||||
t.Fatal("obsolete target file survived")
|
||||
}
|
||||
got, err := xattr(filepath.Join(dst, "hardlink"), "user.cephmig")
|
||||
if err != nil || string(got) != "test" {
|
||||
t.Fatalf("xattr: %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
func TestProcessCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.Canceled {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.DeadlineExceeded {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
if time.Since(start) > 2*time.Second {
|
||||
t.Fatal("cancellation was too slow")
|
||||
}
|
||||
}
|
||||
func TestRsyncUsesIncrementalSafeOptions(t *testing.T) {
|
||||
joined := strings.Join((Rsync{BandwidthKiB: 1024}).args("/source", "/target"), " ")
|
||||
for _, required := range []string{"-aHAXS", "--checksum", "--delete-during", "--no-whole-file", "--fsync", "--bwlimit=1024", "--filter=-x ceph.*"} {
|
||||
if !strings.Contains(joined, required) {
|
||||
t.Fatalf("missing %s", required)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"--inplace", "--delete-before", "--delete-after", "--delay-updates"} {
|
||||
if strings.Contains(joined, bad) {
|
||||
t.Fatalf("unsafe option %s", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,9 @@ type Snapshot struct {
|
||||
Owned bool `json:"owned"`
|
||||
Final bool `json:"final,omitempty"`
|
||||
Done bool `json:"done"`
|
||||
// Removed marks an owned snapshot that is deleted, or is about to be
|
||||
// deleted, at source and target.
|
||||
Removed bool `json:"removed,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
Stats *TransferStats `json:"transfer,omitempty"`
|
||||
}
|
||||
@@ -49,6 +52,7 @@ func LoadState(path string) (*State, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer f.Close()
|
||||
var s State
|
||||
d := json.NewDecoder(f)
|
||||
@@ -56,51 +60,64 @@ func LoadState(path string) (*State, error) {
|
||||
if err := d.Decode(&s); err != nil {
|
||||
return nil, fmt.Errorf("state: %w", err)
|
||||
}
|
||||
|
||||
if err := d.Decode(new(any)); !errors.Is(err, io.EOF) {
|
||||
return nil, errors.New("state must contain exactly one JSON object")
|
||||
}
|
||||
|
||||
id, err := hex.DecodeString(s.ID)
|
||||
if s.Version != stateVersion || err != nil || len(id) != 16 {
|
||||
return nil, errors.New("unsupported or invalid state")
|
||||
}
|
||||
|
||||
if s.Phase != "syncing" && s.Phase != "ready-for-cutover" {
|
||||
return nil, errors.New("invalid state phase")
|
||||
}
|
||||
|
||||
names := map[string]bool{}
|
||||
for _, snap := range s.Snapshots {
|
||||
if !validName(snap.Name) || names[snap.Name] || (snap.Done && (snap.CreatedAt == "" || snap.TargetCreatedAt == "")) {
|
||||
if !validName(snap.Name) || names[snap.Name] || (snap.Done && (snap.CreatedAt == "" || snap.TargetCreatedAt == "")) ||
|
||||
(snap.Removed && (!snap.Owned || !snap.Done)) {
|
||||
return nil, errors.New("invalid snapshot state")
|
||||
}
|
||||
|
||||
names[snap.Name] = true
|
||||
}
|
||||
|
||||
if s.LiveSnapshot != "" {
|
||||
confirmed := false
|
||||
for _, snap := range s.Snapshots {
|
||||
if snap.Name == s.LiveSnapshot && snap.Done {
|
||||
if snap.Name == s.LiveSnapshot && snap.Done && !snap.Removed {
|
||||
confirmed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !confirmed {
|
||||
return nil, errors.New("live base must reference a completed snapshot")
|
||||
}
|
||||
}
|
||||
|
||||
if s.Phase == "ready-for-cutover" {
|
||||
if len(s.Snapshots) == 0 {
|
||||
return nil, errors.New("ready state has no snapshots")
|
||||
}
|
||||
|
||||
for _, snap := range s.Snapshots {
|
||||
if !snap.Done {
|
||||
return nil, errors.New("ready state has incomplete snapshots")
|
||||
}
|
||||
}
|
||||
|
||||
if !s.Snapshots[len(s.Snapshots)-1].Final {
|
||||
return nil, errors.New("ready state has no final snapshot")
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.Config.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("state config: %w", err)
|
||||
}
|
||||
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
@@ -116,6 +133,7 @@ func atomicJSON(path string, v any) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
name := f.Name()
|
||||
defer os.Remove(name)
|
||||
defer f.Close()
|
||||
@@ -124,19 +142,24 @@ func atomicJSON(path string, v any) error {
|
||||
if err = enc.Encode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = f.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = os.Rename(name, path); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d, err := os.Open(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer d.Close()
|
||||
return d.Sync()
|
||||
}
|
||||
@@ -146,9 +169,11 @@ func lockFile(path string) (*os.File, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("another process holds lock %s: %w", path, err)
|
||||
}
|
||||
|
||||
return f, nil
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
func testState() *State {
|
||||
return &State{Version: stateVersion, ID: "1234567890abcdef1234567890abcdef", Config: testConfig(), Phase: "syncing"}
|
||||
}
|
||||
|
||||
func TestStateAtomicAndPrivate(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "state.json")
|
||||
s := testState()
|
||||
@@ -18,10 +19,12 @@ func TestStateAtomicAndPrivate(t *testing.T) {
|
||||
if err := SaveState(p, s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
st, err := os.Stat(p)
|
||||
if err != nil || st.Mode().Perm() != 0600 {
|
||||
t.Fatalf("state permissions: %v, %v", st, err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
@@ -33,20 +36,25 @@ func TestStateAtomicAndPrivate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
got, err := LoadState(p)
|
||||
if err != nil {
|
||||
t.Fatalf("reader observed partial state: %v", err)
|
||||
}
|
||||
|
||||
if got.ID != s.ID {
|
||||
t.Fatal("state identity changed")
|
||||
}
|
||||
|
||||
if len(got.Notes) != 1 || got.Notes[0] != SnapshotIdentityNote {
|
||||
t.Fatal("snapshot identity note was lost")
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestStateRejectsCorruption(t *testing.T) {
|
||||
for name, modify := range map[string]func(*State){
|
||||
"version": func(s *State) { s.Version++ },
|
||||
@@ -68,72 +76,61 @@ func TestStateRejectsCorruption(t *testing.T) {
|
||||
if err := SaveState(p, s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := LoadState(p); err == nil {
|
||||
t.Fatal("accepted corrupt state")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
p := filepath.Join(t.TempDir(), "state.json")
|
||||
b, _ := json.Marshal(testState())
|
||||
if err := os.WriteFile(p, append(b, []byte(" {}")...), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := LoadState(p); err == nil {
|
||||
t.Fatal("accepted trailing data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockExclusionAndRelease(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "lock")
|
||||
first, err := lockFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if second, err := lockFile(p); err == nil {
|
||||
second.Close()
|
||||
t.Fatal("second process acquired lock")
|
||||
}
|
||||
|
||||
first.Close()
|
||||
third, err := lockFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
third.Close()
|
||||
}
|
||||
func TestTargetClaimExcludesOtherJobsAndSurvivesStateLoss(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
c := testConfig()
|
||||
first, err := claimTarget(root, "fsid", c.Target, "job-one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second, err := claimTarget(root, "fsid", c.Target, "job-one"); err == nil {
|
||||
second.Close()
|
||||
t.Fatal("concurrent use allowed")
|
||||
}
|
||||
first.Close()
|
||||
if other, err := claimTarget(root, "fsid", c.Target, "job-two"); err == nil {
|
||||
other.Close()
|
||||
t.Fatal("different job stole target")
|
||||
}
|
||||
resumed, err := claimTarget(root, "fsid", c.Target, "job-one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resumed.Close()
|
||||
}
|
||||
|
||||
func TestStateAndLockRejectSymlinks(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
real := filepath.Join(root, "real")
|
||||
if err := SaveState(real, testState()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
link := filepath.Join(root, "link")
|
||||
if err := os.Symlink(real, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := LoadState(link); err == nil {
|
||||
t.Fatal("followed state symlink")
|
||||
}
|
||||
|
||||
if f, err := lockFile(link); err == nil {
|
||||
f.Close()
|
||||
t.Fatal("followed lock symlink")
|
||||
|
||||
@@ -11,7 +11,10 @@ type Node struct {
|
||||
Mode uint32
|
||||
Inode, Version, Nlink, Size, Rdev uint64
|
||||
UID, GID uint32
|
||||
Mtime time.Time
|
||||
|
||||
// Access, modification, change and birth time. SetAttr sets the change
|
||||
// time to Ctime, but not below Mtime.
|
||||
Atime, Mtime, Ctime, Btime time.Time
|
||||
}
|
||||
|
||||
// File type bits of Node.Mode, as in stat(2).
|
||||
@@ -80,7 +83,7 @@ type FS interface {
|
||||
Symlink(string, string) error
|
||||
Readlink(string) (string, error)
|
||||
Mknod(string, uint32, uint64) error
|
||||
SetAttr(string, Node) error // Numeric owner, mode and mtime; no symlink following.
|
||||
SetAttr(string, Node) error // Numeric owner, mode, all four times; no symlink following.
|
||||
ListXattr(string) ([]string, error)
|
||||
GetXattr(string, string) ([]byte, error)
|
||||
SetXattr(string, string, []byte) error
|
||||
|
||||
Reference in new issue
Block a user