chore: import CephMig prototype
Initial import of the existing CephFS subvolume migration prototype, including the native libcephfs transport, rsync backend, local Ceph lab environment and integration tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
7705ed3eaf
58 files changed
+8769
No files matched your search
@@ -0,0 +1,4 @@
|
||||
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
|
||||
@@ -0,0 +1,20 @@
|
||||
ARG CEPH_IMAGE=quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d
|
||||
FROM ${CEPH_IMAGE} AS build
|
||||
RUN dnf install -y gcc golang-1.26.10-1.el10_2 \
|
||||
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 \
|
||||
&& dnf clean all
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||
CGO_ENABLED=1 go test -race -tags ceph ./... \
|
||||
&& CGO_ENABLED=1 go vet -tags ceph ./... \
|
||||
&& CGO_ENABLED=1 go build -buildvcs=false -tags ceph -o /out/native-probe ./cmd/nativeprobe \
|
||||
&& CGO_ENABLED=1 go build -buildvcs=false -tags ceph -o /out/cephmig-native .
|
||||
|
||||
FROM ${CEPH_IMAGE}
|
||||
COPY --from=build /out/ /usr/local/bin/
|
||||
ENTRYPOINT ["/usr/local/bin/cephmig-native"]
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
mkdir -p /mnt/source /mnt/target /mnt/source-fs /mnt/target-fs
|
||||
pids=()
|
||||
cleanup() {
|
||||
trap - EXIT TERM INT
|
||||
umount /mnt/source /mnt/target /mnt/source-fs /mnt/target-fs 2>/dev/null || true
|
||||
if ((${#pids[@]})); then
|
||||
kill "${pids[@]}" 2>/dev/null || true
|
||||
wait "${pids[@]}" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 0' TERM INT
|
||||
for cluster in source target; do
|
||||
ceph-fuse -f -c "/clusters/$cluster/ceph.conf" \
|
||||
-k "/clusters/$cluster/ceph.client.admin.keyring" \
|
||||
--client-fs cephfs -r "$(cat "/clusters/$cluster/subvolume-path")" \
|
||||
"/mnt/$cluster" &
|
||||
pids+=("$!")
|
||||
done
|
||||
# Administrative mount for snapshot getpath results (outside the data UUID).
|
||||
for cluster in source target; do
|
||||
ceph-fuse -f -c "/clusters/$cluster/ceph.conf" \
|
||||
-k "/clusters/$cluster/ceph.client.admin.keyring" --client-fs cephfs "/mnt/$cluster-fs" &
|
||||
pids+=("$!")
|
||||
done
|
||||
wait -n "${pids[@]}"
|
||||
exit 1
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
: "${CLUSTER_NAME:?set CLUSTER_NAME}"
|
||||
CEPHMIG_OSD_GIB=${CEPHMIG_OSD_GIB:-4}
|
||||
if [[ ! $CEPHMIG_OSD_GIB =~ ^[0-9]+$ ]] || ((10#$CEPHMIG_OSD_GIB < 4 || 10#$CEPHMIG_OSD_GIB > 64)); then
|
||||
echo 'CEPHMIG_OSD_GIB must be an integer between 4 and 64' >&2; exit 1
|
||||
fi
|
||||
block_bytes=$((10#$CEPHMIG_OSD_GIB * 1024 * 1024 * 1024))
|
||||
rm -f /run/cephmig-ready
|
||||
mkdir -p /state/{mon,osd,mgr,mds} /etc/ceph /run/ceph
|
||||
pids=()
|
||||
cleanup() {
|
||||
trap - EXIT TERM INT
|
||||
rm -f /run/cephmig-ready
|
||||
if ((${#pids[@]})); then
|
||||
kill "${pids[@]}" 2>/dev/null || true
|
||||
wait "${pids[@]}" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 0' TERM INT
|
||||
start() { "$@" & pids+=("$!"); }
|
||||
retry() {
|
||||
local attempt
|
||||
for ((attempt=0; attempt<90; attempt++)); do
|
||||
if "$@"; then return 0; fi
|
||||
sleep 2
|
||||
done
|
||||
echo "Timeout: $*" >&2
|
||||
return 1
|
||||
}
|
||||
if [[ ! -f /state/fsid ]]; then cat /proc/sys/kernel/random/uuid > /state/fsid; fi
|
||||
ip=$(hostname -i | awk '{print $1}')
|
||||
cat > /etc/ceph/ceph.conf <<EOF
|
||||
[global]
|
||||
fsid = $(cat /state/fsid)
|
||||
mon initial members = a
|
||||
mon host = $CLUSTER_NAME
|
||||
auth cluster required = cephx
|
||||
auth service required = cephx
|
||||
auth client required = cephx
|
||||
auth allow insecure global id reclaim = false
|
||||
log to stderr = true
|
||||
log to file = false
|
||||
mon allow pool size one = true
|
||||
osd pool default size = 1
|
||||
osd pool default min size = 1
|
||||
osd pool default pg num = 8
|
||||
osd pool default pgp num = 8
|
||||
osd crush chooseleaf type = 0
|
||||
osd memory target = 1073741824
|
||||
bluestore block size = $block_bytes
|
||||
bluestore block create = true
|
||||
bluestore block db size = 0
|
||||
bluestore block wal size = 0
|
||||
[client]
|
||||
client acl type = posix_acl
|
||||
[mon.a]
|
||||
mon data = /state/mon
|
||||
[osd.0]
|
||||
osd data = /state/osd
|
||||
[mgr.a]
|
||||
mgr data = /state/mgr
|
||||
[mds.a]
|
||||
mds data = /state/mds
|
||||
mds cache memory limit = ${CEPHMIG_MDS_CACHE_BYTES:-1073741824}
|
||||
EOF
|
||||
if [[ ! -d /state/mon/store.db ]]; then
|
||||
ceph-authtool --create-keyring /state/mon.keyring --gen-key -n mon.
|
||||
ceph-authtool --create-keyring /etc/ceph/ceph.client.admin.keyring \
|
||||
--gen-key -n client.admin --cap mon 'allow *' --cap osd 'allow *' \
|
||||
--cap mds 'allow *' --cap mgr 'allow *'
|
||||
ceph-authtool /state/mon.keyring --import-keyring /etc/ceph/ceph.client.admin.keyring
|
||||
monmaptool --create --clobber --addv a "[v2:$ip:3300,v1:$ip:6789]" --fsid "$(cat /state/fsid)" /state/monmap
|
||||
ceph-mon --mkfs -i a --monmap /state/monmap --keyring /state/mon.keyring
|
||||
else
|
||||
# Compose can assign a different address after down/up.
|
||||
ceph-mon -i a --extract-monmap /run/ceph/monmap
|
||||
monmaptool --rm a /run/ceph/monmap
|
||||
monmaptool --addv a "[v2:$ip:3300,v1:$ip:6789]" /run/ceph/monmap
|
||||
ceph-mon -i a --inject-monmap /run/ceph/monmap
|
||||
fi
|
||||
start ceph-mon -i a -f --public-addr "$ip"
|
||||
retry ceph status
|
||||
ceph auth get-or-create mgr.a mon 'allow profile mgr' osd 'allow *' mds 'allow *' \
|
||||
-o /state/mgr/keyring
|
||||
start ceph-mgr -i a -f
|
||||
if [[ ! -f /state/osd/whoami ]]; then
|
||||
if [[ ! -f /state/osd-uuid ]]; then cat /proc/sys/kernel/random/uuid > /state/osd-uuid; fi
|
||||
ceph osd new "$(cat /state/osd-uuid)" 0
|
||||
ceph-osd -i 0 --mkfs --mkkey --osd-uuid "$(cat /state/osd-uuid)" --no-mon-config
|
||||
fi
|
||||
ceph auth add osd.0 osd 'allow *' mon 'allow profile osd' mgr 'allow profile osd' \
|
||||
-i /state/osd/keyring
|
||||
start ceph-osd -i 0 -f
|
||||
retry bash -c 'ceph osd stat --format json | python3 -c '\''import json,sys; s=json.load(sys.stdin); sys.exit(s["num_up_osds"] != 1)'\'''
|
||||
ceph auth get-or-create mds.a mon 'allow profile mds' mgr 'allow profile mds' \
|
||||
osd 'allow rw tag cephfs *=*' mds 'allow' -o /state/mds/keyring
|
||||
start ceph-mds -i a -f
|
||||
# Explicit PG counts avoid an EINVAL in Umbrella's volume-create pool defaults.
|
||||
retry ceph osd pool create cephfs.cephfs.meta 8
|
||||
retry ceph osd pool create cephfs.cephfs.data 8
|
||||
retry ceph fs new cephfs cephfs.cephfs.meta cephfs.cephfs.data
|
||||
retry ceph fs subvolumegroup create cephfs migration
|
||||
retry ceph fs subvolume create cephfs demo --group_name migration
|
||||
ceph fs subvolume getpath cephfs demo --group_name migration > /etc/ceph/subvolume-path
|
||||
touch /run/cephmig-ready
|
||||
echo "Cluster $CLUSTER_NAME ready"
|
||||
wait -n "${pids[@]}"
|
||||
exit 1
|
||||
@@ -0,0 +1,33 @@
|
||||
# Always run with -p cephmig-million; its volumes are separate from cephmig-dev.
|
||||
services:
|
||||
source:
|
||||
environment:
|
||||
CEPHMIG_OSD_GIB: "24"
|
||||
CEPHMIG_MDS_CACHE_BYTES: "805306368"
|
||||
target:
|
||||
environment:
|
||||
CEPHMIG_OSD_GIB: "24"
|
||||
CEPHMIG_MDS_CACHE_BYTES: "805306368"
|
||||
client:
|
||||
profiles: [fuse]
|
||||
native:
|
||||
profiles: [manual]
|
||||
benchmark:
|
||||
image: cephmig-native:dev
|
||||
init: true
|
||||
entrypoint: [python3, -u, /lab/million.py]
|
||||
networks: [lab]
|
||||
depends_on:
|
||||
source: {condition: service_healthy}
|
||||
target: {condition: service_healthy}
|
||||
mem_limit: 2g
|
||||
stop_grace_period: 45s
|
||||
volumes:
|
||||
- source-config:/clusters/source:ro
|
||||
- target-config:/clusters/target:ro
|
||||
- ./:/lab:ro
|
||||
- migration-state:/state
|
||||
- ../.dev/million:/report
|
||||
logging:
|
||||
driver: json-file
|
||||
options: {max-size: 10m, max-file: '2'}
|
||||
@@ -0,0 +1,89 @@
|
||||
name: cephmig-dev
|
||||
x-ceph: &ceph
|
||||
image: ${CEPH_IMAGE:-quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d}
|
||||
init: true
|
||||
stop_grace_period: 30s
|
||||
networks: [lab]
|
||||
logging:
|
||||
driver: json-file
|
||||
options: {max-size: 10m, max-file: '3'}
|
||||
ulimits:
|
||||
core: 0
|
||||
x-cluster: &cluster
|
||||
<<: *ceph
|
||||
entrypoint: [bash, /lab/cluster.sh]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'test -f /run/cephmig-ready && ceph fs subvolume getpath cephfs demo --group_name migration >/dev/null']
|
||||
interval: 5s
|
||||
timeout: 10s
|
||||
retries: 60
|
||||
mem_limit: 4g
|
||||
services:
|
||||
native:
|
||||
<<: *ceph
|
||||
image: cephmig-native:dev
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: dev/Dockerfile.native
|
||||
args:
|
||||
CEPH_IMAGE: ${CEPH_IMAGE:-quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d}
|
||||
entrypoint: [sleep, infinity]
|
||||
depends_on:
|
||||
source: {condition: service_healthy}
|
||||
target: {condition: service_healthy}
|
||||
volumes:
|
||||
- source-config:/clusters/source:ro
|
||||
- target-config:/clusters/target:ro
|
||||
- ./:/lab:ro
|
||||
- migration-state:/state
|
||||
mem_limit: 2g
|
||||
source:
|
||||
<<: *cluster
|
||||
hostname: source
|
||||
environment: {CLUSTER_NAME: source}
|
||||
volumes:
|
||||
- source-state:/state
|
||||
- source-config:/etc/ceph
|
||||
- ./:/lab:ro
|
||||
target:
|
||||
<<: *cluster
|
||||
hostname: target
|
||||
environment: {CLUSTER_NAME: target}
|
||||
volumes:
|
||||
- target-state:/state
|
||||
- target-config:/etc/ceph
|
||||
- ./:/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]
|
||||
depends_on:
|
||||
source: {condition: service_healthy}
|
||||
target: {condition: service_healthy}
|
||||
volumes:
|
||||
- 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']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
mem_limit: 2g
|
||||
networks:
|
||||
lab: {}
|
||||
volumes:
|
||||
source-state: {}
|
||||
target-state: {}
|
||||
source-config: {}
|
||||
target-config: {}
|
||||
migration-state: {}
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/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'
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"backend": "native",
|
||||
"source": {
|
||||
"config": "/clusters/source/ceph.conf",
|
||||
"keyring": "/clusters/source/ceph.client.admin.keyring",
|
||||
"filesystem": "cephfs",
|
||||
"group": "migration",
|
||||
"subvolume": "demo",
|
||||
"mount": "/mnt/source-fs"
|
||||
},
|
||||
"target": {
|
||||
"config": "/clusters/target/ceph.conf",
|
||||
"keyring": "/clusters/target/ceph.client.admin.keyring",
|
||||
"filesystem": "cephfs",
|
||||
"group": "migration",
|
||||
"subvolume": "demo",
|
||||
"mount": "/mnt/target-fs"
|
||||
},
|
||||
"bandwidth_kib": 0
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Wait for Docker's completion event; no status polling.
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
exit_code=$(docker wait cephmig-million-benchmark-1)
|
||||
if [[ $exit_code != 0 ]]; then
|
||||
echo "Benchmark exited $exit_code; retaining test data and diagnostics." >&2
|
||||
exit 1
|
||||
fi
|
||||
exec bash dev/million-finish.sh
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# Save a completed run, then release only this isolated test project's volumes.
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
compose=(docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml)
|
||||
python3 - <<'PY'
|
||||
import json,pathlib
|
||||
s=json.loads(pathlib.Path('.dev/million/main/status.json').read_text())
|
||||
if s.get('result') != 'PASS':
|
||||
raise SystemExit('Refusing cleanup: independent million-file verification has not passed')
|
||||
PY
|
||||
# PASS is written just before the independent writer shuts down.
|
||||
exit_code=$(docker wait cephmig-million-benchmark-1)
|
||||
[[ $exit_code = 0 ]] || { echo "Benchmark exited $exit_code; retaining diagnostics" >&2; exit 1; }
|
||||
mkdir -p .dev/million/summary
|
||||
for cluster in source target; do
|
||||
"${compose[@]}" exec -T "$cluster" ceph df --format json > ".dev/million/summary/$cluster-capacity.json"
|
||||
"${compose[@]}" exec -T "$cluster" ceph health detail --format json > ".dev/million/summary/$cluster-health.json"
|
||||
"${compose[@]}" exec -T "$cluster" python3 -c '
|
||||
import os,json
|
||||
s=os.stat("/state/osd/block")
|
||||
print(json.dumps(dict(logical_bytes=s.st_size,allocated_bytes=s.st_blocks*512)))' > ".dev/million/summary/$cluster-host-allocation.json"
|
||||
done
|
||||
docker inspect cephmig-million-benchmark-1 --format '{{.Image}}' > .dev/million/native-image.txt
|
||||
python3 - <<'PY'
|
||||
import datetime,json,pathlib
|
||||
root=pathlib.Path('.dev/million/main')
|
||||
def read(name): return json.loads((root/name).read_text())
|
||||
def sample(name): return json.loads((pathlib.Path('.dev/million/summary')/name).read_text())
|
||||
result=dict(status=read('status.json'),migration=read('migration-state.json'),
|
||||
phases={phase:read(phase+'.metrics.json') for phase in ('initial','catchup','final')},
|
||||
ceph_capacity={c:sample(c+'-capacity.json') for c in ('source','target')},
|
||||
ceph_health={c:sample(c+'-health.json') for c in ('source','target')},
|
||||
host_osd_allocation={c:sample(c+'-host-allocation.json') for c in ('source','target')},
|
||||
image=pathlib.Path('.dev/million/native-image.txt').read_text().strip(),
|
||||
recorded_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
|
||||
pathlib.Path('docs/million-local.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('Saved docs/million-local.json')
|
||||
PY
|
||||
"${compose[@]}" down --volumes
|
||||
df -B1 . > .dev/million/host-after-cleanup.txt
|
||||
echo 'PASS: results saved; isolated million-file cluster storage released.'
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
compose=(docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml)
|
||||
# Each sparse OSD can grow to 24 GiB. Leave another 20 GiB for the host.
|
||||
if ! docker volume inspect cephmig-million_source-state >/dev/null 2>&1; then
|
||||
python3 - <<'PY'
|
||||
import os
|
||||
s = os.statvfs('.')
|
||||
available = s.f_bavail * s.f_frsize
|
||||
if available < 68 * 1024**3:
|
||||
raise SystemExit('Need 68 GiB free for two 24 GiB OSDs and a 20 GiB host reserve')
|
||||
print(f'Host free: {available / 1024**3:.1f} GiB')
|
||||
PY
|
||||
fi
|
||||
mkdir -p .dev/million
|
||||
"${compose[@]}" config --quiet
|
||||
"${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 'Logs: docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml logs -f benchmark'
|
||||
+509
@@ -0,0 +1,509 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Persistent, bounded-memory million-file CephFS snapshot migration test.
|
||||
|
||||
The Python SDK acts as application writer and independent verifier. Expected
|
||||
contents and metadata are derived from a deterministic model, not the Go reader.
|
||||
"""
|
||||
import concurrent.futures
|
||||
from collections import deque
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import sqlite3
|
||||
import stat
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
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')
|
||||
REPORT = Path('/report') / RUN_LABEL
|
||||
WORK = Path('/state') / ('million-' + RUN_LABEL)
|
||||
COUNT = int(os.environ.get('FILES', '1000000'))
|
||||
PER_DIR = 1000
|
||||
STAMP = 1700000000
|
||||
STOP = threading.Event()
|
||||
STATUS_LOCK = threading.RLock()
|
||||
state = {}
|
||||
|
||||
|
||||
def atomic_json(path, value):
|
||||
temporary = path.with_suffix(path.suffix + '.tmp')
|
||||
with temporary.open('w') as f:
|
||||
json.dump(value, f, indent=2)
|
||||
f.write('\n')
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
temporary.replace(path)
|
||||
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def progress(**changes):
|
||||
with STATUS_LOCK:
|
||||
state.update(changes)
|
||||
state['updated_at'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
atomic_json(REPORT / 'status.json', state)
|
||||
print(json.dumps(changes), flush=True)
|
||||
|
||||
|
||||
def guard():
|
||||
if STOP.is_set():
|
||||
raise RuntimeError('test stopped')
|
||||
usage = os.statvfs('/state')
|
||||
if usage.f_bavail * usage.f_frsize < 20 * 1024**3:
|
||||
raise RuntimeError('host reserve below 20 GiB; stopping further test writes')
|
||||
memory = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines())
|
||||
if int(memory['MemAvailable'].split()[0]) < 3 * 1024**2:
|
||||
raise RuntimeError('host available memory below 3 GiB')
|
||||
|
||||
|
||||
def space_guard():
|
||||
guard()
|
||||
for cluster in ('source', 'target'):
|
||||
s = json.loads(ceph(cluster, 'df', '--format', 'json'))['stats']
|
||||
if s['total_avail_bytes'] < 3 * 1024**3:
|
||||
raise RuntimeError(f'{cluster} has less than 3 GiB reserve')
|
||||
|
||||
|
||||
class FS:
|
||||
def __init__(self, cluster):
|
||||
self.fs = cephfs.LibCephFS(conffile=f'/clusters/{cluster}/ceph.conf')
|
||||
self.fs.conf_set('keyring', f'/clusters/{cluster}/ceph.client.admin.keyring')
|
||||
self.fs.conf_set('client_acl_type', 'posix_acl')
|
||||
self.fs.conf_set('client_cache_size', '4096')
|
||||
self.fs.conf_set('client_oc', 'false')
|
||||
self.fs.mount()
|
||||
|
||||
def __enter__(self):
|
||||
return self.fs
|
||||
|
||||
def __exit__(self, *_):
|
||||
self.fs.shutdown()
|
||||
|
||||
|
||||
def names(fs, path):
|
||||
d = fs.opendir(path)
|
||||
try:
|
||||
result = set()
|
||||
while entry := fs.readdir(d):
|
||||
name = entry.d_name.decode()
|
||||
if name not in ('.', '..', '.snap'):
|
||||
result.add(name)
|
||||
return result
|
||||
finally:
|
||||
fs.closedir(d)
|
||||
|
||||
|
||||
def mkdir(fs, path):
|
||||
try:
|
||||
fs.mkdir(path, 0o755)
|
||||
except cephfs.ObjectExists:
|
||||
if not stat.S_ISDIR(fs.lstat(path).st_mode):
|
||||
raise
|
||||
|
||||
|
||||
def exists(fs, path):
|
||||
try:
|
||||
fs.lstat(path)
|
||||
return True
|
||||
except cephfs.ObjectNotFound:
|
||||
return False
|
||||
|
||||
|
||||
def relative(i):
|
||||
return f'data/d{i // PER_DIR:04d}/f{i % PER_DIR:06d}'
|
||||
|
||||
|
||||
def object_attrs(i, changed):
|
||||
result = {}
|
||||
if i < COUNT and i // PER_DIR == 0:
|
||||
acl = posix_acl()
|
||||
if changed and i % 100 == 3:
|
||||
# Change the ACL mask to match chmod 0660.
|
||||
import struct
|
||||
acl = bytearray(acl)
|
||||
struct.pack_into('<H', acl, 4 + 3 * 8 + 2, 6)
|
||||
acl = bytes(acl)
|
||||
result['system.posix_acl_access'] = acl
|
||||
if i < COUNT and i % 100 == 4 and not changed:
|
||||
result['user.remove'] = b'original'
|
||||
if i < COUNT and i % 100 == 3 and changed:
|
||||
result['user.generation'] = b'1'
|
||||
return result
|
||||
|
||||
|
||||
def actual_attrs(fs, path):
|
||||
_, buffer = fs.listxattr(path, 256)
|
||||
return {k.decode(): fs.getxattr(path, k, 4096) for k in buffer.split(b'\0') if k and
|
||||
(not k.startswith(b'ceph.'))}
|
||||
|
||||
|
||||
def create_file(fs, root, i, version):
|
||||
path = root + '/' + relative(i)
|
||||
fd = fs.open(path, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o644)
|
||||
try:
|
||||
if fs.write(fd, payload(i, version), 0) != 128:
|
||||
raise RuntimeError(f'short fixture write: {path}')
|
||||
finally:
|
||||
fs.close(fd)
|
||||
fs.utime(path, (STAMP + i, STAMP + i))
|
||||
if i == 0:
|
||||
fs.chown(path, 12345, 23456)
|
||||
if i < COUNT and i % 100 == 4:
|
||||
fs.setxattr(path, b'user.remove', b'original', 0)
|
||||
|
||||
|
||||
def reset_dir_times(fs, root, count):
|
||||
for i in range((count + PER_DIR - 1) // PER_DIR):
|
||||
fs.utime(root + f'/data/d{i:04d}', (STAMP, STAMP))
|
||||
for rel in ('data', 'links', '.'):
|
||||
fs.utime(root + '/' + rel, (STAMP, STAMP))
|
||||
|
||||
|
||||
def prepare():
|
||||
progress(phase='preparing', total_files=COUNT, bytes_per_file=128, layout='1000 files per directory')
|
||||
name = state['name']
|
||||
for cluster in ('source', 'target'):
|
||||
volume(cluster, 'create', 'cephfs', name)
|
||||
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)
|
||||
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']
|
||||
state['root_attrs'] = {key: value.hex() for key, value in actual_attrs(fs, root).items()}
|
||||
mkdir(fs, root + '/data')
|
||||
mkdir(fs, root + '/links')
|
||||
directories = (COUNT + PER_DIR - 1) // PER_DIR
|
||||
for d in range(directories):
|
||||
mkdir(fs, root + f'/data/d{d:04d}')
|
||||
fs.setxattr(root + '/data/d0000', b'system.posix_acl_default', posix_acl(), 0)
|
||||
start = state.get('generated_directories', 0)
|
||||
def generate(d):
|
||||
for i in range(d * PER_DIR, min(COUNT, (d + 1) * PER_DIR)):
|
||||
if STOP.is_set():
|
||||
raise RuntimeError('generation stopped')
|
||||
create_file(fs, root, i, 0)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
for d in range(start, directories, 8):
|
||||
space_guard()
|
||||
list(pool.map(generate, range(d, min(directories, d + 8))))
|
||||
fs.sync_fs()
|
||||
progress(generated_directories=min(directories, d + 8),
|
||||
generated_files=min(COUNT, (d + 8) * PER_DIR))
|
||||
for i in range(100):
|
||||
hard = root + f'/links/hard{i:03d}'
|
||||
soft = root + f'/links/soft{i:03d}'
|
||||
if not exists(fs, hard):
|
||||
fs.link(root + '/' + relative(i), hard)
|
||||
if not exists(fs, soft):
|
||||
fs.symlink('../' + relative(i), soft)
|
||||
state['symlink_times'] = {f'links/soft{i:03d}': fs.lstat(root + f'/links/soft{i:03d}').st_mtime.isoformat()
|
||||
for i in range(100)}
|
||||
fs.setxattr(root, b'ceph.quota.max_files', str(COUNT * 2 + 1000).encode(), 0)
|
||||
fs.setxattr(root, b'ceph.quota.max_bytes', str(COUNT * 256 + 4194304).encode(), 0)
|
||||
reset_dir_times(fs, root, COUNT)
|
||||
fs.sync_fs()
|
||||
if 'baseline' not in {x['name'] for x in json.loads(snap('source', 'ls', 'cephfs', name))}:
|
||||
snap('source', 'create', 'cephfs', name, 'baseline')
|
||||
snap('source', 'metadata', 'set', 'cephfs', name, 'baseline', 'fixture', 'million-v0')
|
||||
progress(prepared=True, phase='prepared')
|
||||
|
||||
|
||||
def mutate():
|
||||
progress(phase='mutating')
|
||||
root = state['roots']['source']
|
||||
with FS('source') as fs:
|
||||
for d in range(COUNT // PER_DIR):
|
||||
guard()
|
||||
for i in range(d * PER_DIR, (d + 1) * PER_DIR):
|
||||
path = root + '/' + relative(i)
|
||||
if i % 100 == 0:
|
||||
fd = fs.open(path, os.O_WRONLY, 0)
|
||||
try:
|
||||
if fs.write(fd, payload(i, 1), 0) != 128:
|
||||
raise RuntimeError('short mutation write')
|
||||
finally:
|
||||
fs.close(fd)
|
||||
fs.utime(path, (STAMP + i, STAMP + i))
|
||||
elif i % 100 == 1:
|
||||
if exists(fs, path): fs.unlink(path)
|
||||
elif i % 100 == 2:
|
||||
if exists(fs, path): fs.rename(path, path + '-renamed')
|
||||
elif i % 100 == 3:
|
||||
fs.chmod(path, 0o660)
|
||||
fs.setxattr(path, b'user.generation', b'1', 0)
|
||||
elif i % 100 == 4:
|
||||
if b'user.remove' in fs.listxattr(path, 256)[1].split(b'\0'):
|
||||
fs.removexattr(path, b'user.remove')
|
||||
if d % 10 == 0:
|
||||
space_guard()
|
||||
progress(mutated_directories=d + 1)
|
||||
end = COUNT + COUNT // 100
|
||||
for d in range(COUNT // PER_DIR, (end + PER_DIR - 1) // PER_DIR):
|
||||
mkdir(fs, root + f'/data/d{d:04d}')
|
||||
for i in range(COUNT, end):
|
||||
create_file(fs, root, i, 2)
|
||||
reset_dir_times(fs, root, end)
|
||||
fs.sync_fs()
|
||||
progress(mutated=True)
|
||||
|
||||
|
||||
def counters(cluster):
|
||||
d = json.loads(ceph(cluster, 'tell', 'mds.a', 'perf', 'dump'))
|
||||
return {'requests': d['mds']['request'], 'getattr': d['mds_server']['req_getattr_latency']['avgcount'],
|
||||
'lookupsnap': d['mds_server']['req_lookupsnap_latency']['avgcount']}
|
||||
|
||||
|
||||
def run_phase(phase):
|
||||
space_guard()
|
||||
attempts = dict(state.get('phase_attempts', {}))
|
||||
attempts[phase] = attempts.get(phase, 0) + 1
|
||||
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',
|
||||
'--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)
|
||||
try:
|
||||
while p.poll() is None:
|
||||
now = time.monotonic()
|
||||
if now - last >= 15:
|
||||
space_guard()
|
||||
try:
|
||||
for line in Path(f'/proc/{p.pid}/status').read_text().splitlines():
|
||||
if line.startswith(('VmRSS:', 'VmHWM:')):
|
||||
peak = max(peak, int(line.split()[1]))
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
with (REPORT / f'{phase}.log').open('rb') as tail:
|
||||
tail.seek(max(0, os.fstat(tail.fileno()).st_size - 2048))
|
||||
lines = tail.read().decode(errors='replace').splitlines()
|
||||
progress(elapsed_seconds=round(now - started, 1), peak_rss_kib=peak,
|
||||
last_engine_message=lines[-1] if lines else 'starting')
|
||||
last = now
|
||||
if STOP.is_set(): raise RuntimeError('migration stopped')
|
||||
if now - started > 48 * 3600: raise RuntimeError('migration phase exceeded 48 hours')
|
||||
time.sleep(1)
|
||||
except BaseException:
|
||||
p.terminate()
|
||||
try: p.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
p.kill(); p.wait()
|
||||
raise
|
||||
if p.returncode:
|
||||
raise RuntimeError(f'{phase} failed ({p.returncode}); see {phase}.log')
|
||||
result = json.loads((WORK / 'job.json').read_text())
|
||||
if not all(s['done'] for s in result['snapshots']): raise RuntimeError('unfinished snapshot')
|
||||
after = {c: counters(c) for c in before}
|
||||
metrics = dict(seconds=time.monotonic() - started, wall_seconds=time.time() - wall_started,
|
||||
peak_rss_kib=peak, snapshots=result['snapshots'],
|
||||
resumed=attempts[phase] > 1,
|
||||
mds={c: {k: after[c][k] - before[c][k] for k in before[c]} for c in before})
|
||||
atomic_json(REPORT / f'{phase}.metrics.json', metrics)
|
||||
atomic_json(REPORT / 'migration-state.json', result)
|
||||
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')
|
||||
completed = {phase + '_complete': True}
|
||||
if phase == 'initial':
|
||||
completed['initial_snapshots'] = [record['name'] for record in result['snapshots']]
|
||||
progress(**completed)
|
||||
|
||||
|
||||
def expected_mode(i, changed):
|
||||
return 0o660 if changed and i < COUNT and i % 100 == 3 else (0o640 if i < PER_DIR else 0o644)
|
||||
|
||||
|
||||
def check_regular(fs, root, rel, i, changed):
|
||||
path = root + '/' + rel
|
||||
s = fs.lstat(path)
|
||||
if s.st_mode != stat.S_IFREG | expected_mode(i, changed) or s.st_size != 128:
|
||||
raise RuntimeError(f'type/mode/size mismatch: {path}')
|
||||
if (s.st_uid, s.st_gid) != ((12345, 23456) if i == 0 else (0, 0)):
|
||||
raise RuntimeError(f'owner mismatch: {path}')
|
||||
if s.st_mtime != datetime.datetime.fromtimestamp(STAMP + i, datetime.timezone.utc).replace(tzinfo=None):
|
||||
raise RuntimeError(f'mtime mismatch: {path}')
|
||||
if actual_attrs(fs, path) != object_attrs(i, changed):
|
||||
raise RuntimeError(f'xattr/ACL mismatch: {path}')
|
||||
version = 2 if i >= COUNT else (1 if changed and i % 100 == 0 else 0)
|
||||
fd = fs.open(path, os.O_RDONLY | os.O_NOFOLLOW, 0)
|
||||
try: data = fs.read(fd, 0, 129)
|
||||
finally: fs.close(fd)
|
||||
if data != payload(i, version): raise RuntimeError(f'content mismatch: {path}')
|
||||
return i, str(s.st_ino)
|
||||
|
||||
|
||||
def verify_view(label, root, changed):
|
||||
if label in state.get('verified_views', []): return
|
||||
progress(phase='verifying', view=label, verified_regular_paths=0)
|
||||
dbpath = WORK / 'verify.sqlite'
|
||||
dbpath.unlink(missing_ok=True)
|
||||
db = sqlite3.connect(dbpath)
|
||||
db.executescript('PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-16384;'
|
||||
'CREATE TABLE links(object_id INTEGER PRIMARY KEY, inode TEXT UNIQUE NOT NULL);')
|
||||
checked, last = 0, time.monotonic()
|
||||
try:
|
||||
with FS('target') as fs, concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
|
||||
if names(fs, root) != {'data', 'links'}: raise RuntimeError('unexpected root entries')
|
||||
for rel in ('.', 'data', 'links'):
|
||||
s = fs.lstat(root + '/' + rel)
|
||||
expected_attrs = ({key: bytes.fromhex(value) for key, value in state['root_attrs'].items()}
|
||||
if rel == '.' else {})
|
||||
if (s.st_mode != (stat.S_IFDIR | 0o755) or s.st_uid or s.st_gid or
|
||||
s.st_mtime != datetime.datetime.utcfromtimestamp(STAMP) or
|
||||
actual_attrs(fs, root + '/' + rel) != expected_attrs):
|
||||
raise RuntimeError(f'root/parent metadata mismatch: {rel}')
|
||||
end = COUNT + COUNT // 100 if changed else COUNT
|
||||
directory_count = (end + PER_DIR - 1) // PER_DIR
|
||||
if names(fs, root + '/data') != {f'd{i:04d}' for i in range(directory_count)}:
|
||||
raise RuntimeError('data directory inventory mismatch')
|
||||
def consume(future):
|
||||
nonlocal checked
|
||||
i, ino = future.result()
|
||||
cursor = db.execute('INSERT OR IGNORE INTO links VALUES(?,?)', (i, ino))
|
||||
if not cursor.rowcount:
|
||||
row = db.execute('SELECT inode FROM links WHERE object_id=?', (i,)).fetchone()
|
||||
if row != (ino,): raise RuntimeError('hardlink group split or unrelated objects merged')
|
||||
checked += 1
|
||||
for d in range(directory_count):
|
||||
guard()
|
||||
expected = {}
|
||||
for i in range(d * PER_DIR, min(end, (d + 1) * PER_DIR)):
|
||||
if changed and i < COUNT and i % 100 == 1: continue
|
||||
rel = relative(i) + ('-renamed' if changed and i < COUNT and i % 100 == 2 else '')
|
||||
expected[rel.rsplit('/', 1)[1]] = (rel, i)
|
||||
path = root + f'/data/d{d:04d}'
|
||||
if names(fs, path) != set(expected): raise RuntimeError(f'inventory mismatch: {path}')
|
||||
s = fs.lstat(path)
|
||||
if s.st_mode != stat.S_IFDIR | 0o755 or s.st_uid or s.st_gid or s.st_mtime != datetime.datetime.utcfromtimestamp(STAMP):
|
||||
raise RuntimeError(f'directory metadata mismatch: {path}')
|
||||
attrs = {'system.posix_acl_default': posix_acl()} if d == 0 else {}
|
||||
if actual_attrs(fs, path) != attrs: raise RuntimeError(f'directory ACL mismatch: {path}')
|
||||
pending = deque()
|
||||
for rel, i in expected.values():
|
||||
pending.append(pool.submit(check_regular, fs, root, rel, i, changed))
|
||||
if len(pending) >= 64: consume(pending.popleft())
|
||||
while pending: consume(pending.popleft())
|
||||
db.commit()
|
||||
if time.monotonic() - last >= 15:
|
||||
progress(view=label, verified_regular_paths=checked)
|
||||
last = time.monotonic()
|
||||
expected_links = {f'{kind}{i:03d}' for kind in ('hard', 'soft') for i in range(100)}
|
||||
if names(fs, root + '/links') != expected_links: raise RuntimeError('link inventory mismatch')
|
||||
for i in range(100):
|
||||
result = check_regular(fs, root, f'links/hard{i:03d}', i, changed)
|
||||
done = concurrent.futures.Future(); done.set_result(result); consume(done)
|
||||
path = root + f'/links/soft{i:03d}'
|
||||
s = fs.lstat(path)
|
||||
if not stat.S_ISLNK(s.st_mode) or s.st_uid or s.st_gid:
|
||||
raise RuntimeError('symlink metadata mismatch')
|
||||
if fs.readlink(path, 4096).decode() != '../' + relative(i): raise RuntimeError('symlink text mismatch')
|
||||
if s.st_mtime.isoformat() != state['symlink_times'][f'links/soft{i:03d}']:
|
||||
raise RuntimeError('symlink mtime mismatch')
|
||||
for key, value in [('ceph.quota.max_files', COUNT * 2 + 1000), ('ceph.quota.max_bytes', COUNT * 256 + 4194304)]:
|
||||
if fs.getxattr(root, key, 128) != str(value).encode(): raise RuntimeError('quota mismatch')
|
||||
if checked != COUNT + 100: raise RuntimeError(f'wrong file count: {checked}')
|
||||
state.setdefault('verified_views', []).append(label)
|
||||
progress(verified_regular_paths=checked)
|
||||
finally:
|
||||
db.close()
|
||||
dbpath.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def other_writer():
|
||||
try:
|
||||
with FS('source') as fs:
|
||||
demo = volume('source', 'getpath', 'cephfs', 'demo')
|
||||
path = demo + '/million-liveness'
|
||||
fd = fs.open(path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||
try:
|
||||
while not STOP.is_set():
|
||||
value = state.get('other_subvolume_writes', 0) + 1
|
||||
fs.write(fd, str(value).encode(), 0)
|
||||
fs.fsync(fd, False)
|
||||
with STATUS_LOCK: state['other_subvolume_writes'] = value
|
||||
STOP.wait(2)
|
||||
finally:
|
||||
fs.close(fd)
|
||||
fs.unlink(path)
|
||||
except BaseException as e:
|
||||
state['other_writer_error'] = str(e)
|
||||
STOP.set()
|
||||
|
||||
|
||||
def main():
|
||||
global state
|
||||
if COUNT < 1000 or COUNT > 1000000 or COUNT % PER_DIR:
|
||||
raise ValueError('FILES must be a multiple of 1000, from 1000 to 1000000')
|
||||
REPORT.mkdir(parents=True, exist_ok=True)
|
||||
WORK.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if (REPORT / 'status.json').exists():
|
||||
state = json.loads((REPORT / 'status.json').read_text())
|
||||
if state.get('total_files') != COUNT: raise RuntimeError('cannot change count on resume')
|
||||
if state.get('result') == 'PASS': return
|
||||
state.pop('result', None)
|
||||
state.pop('error', None)
|
||||
state.pop('other_writer_error', None)
|
||||
else:
|
||||
state = dict(name='million-itest-' + str(uuid.uuid4()), total_files=COUNT,
|
||||
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()
|
||||
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('catchup_complete'): run_phase('catchup')
|
||||
before = state.get('other_subvolume_writes', 0)
|
||||
if not state.get('final_complete'):
|
||||
run_phase('final')
|
||||
if state.get('other_subvolume_writes', 0) <= before:
|
||||
raise RuntimeError('other subvolume did not remain writable during finalization')
|
||||
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']:
|
||||
path = ceph('target', 'fs', 'subvolume', 'snapshot', 'getpath',
|
||||
'cephfs', state['name'], record['name'], 'migration')
|
||||
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 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))
|
||||
finally:
|
||||
STOP.set()
|
||||
thread.join(timeout=30)
|
||||
except BaseException as e:
|
||||
progress(phase='failed', result='FAIL', error=repr(e))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,245 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Independent application-side fixtures; only uses the lab's existing FUSE client."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
def ceph(cluster, *args):
|
||||
return subprocess.check_output([
|
||||
"ceph", "-c", f"/clusters/{cluster}/ceph.conf", "-k",
|
||||
f"/clusters/{cluster}/ceph.client.admin.keyring", *args], text=True).strip()
|
||||
|
||||
|
||||
def volume(cluster, *args):
|
||||
return ceph(cluster, "fs", "subvolume", *args, "--group_name", "migration")
|
||||
|
||||
|
||||
def snapshot(cluster, *args):
|
||||
return volume(cluster, "snapshot", *args)
|
||||
|
||||
|
||||
def acl():
|
||||
entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff),
|
||||
(16, 4, 0xffffffff), (32, 0, 0xffffffff)]
|
||||
return struct.pack("<I", 2) + b"".join(struct.pack("<HHI", *e) for e in entries)
|
||||
|
||||
|
||||
def populate(root):
|
||||
os.mkdir(root + "/d")
|
||||
with open(root + "/large", "wb") as f:
|
||||
# Nonzero data throughout, so sparse-file optimizations cannot hide a full copy.
|
||||
chunk = bytes(range(256)) * 4096
|
||||
for _ in range(64):
|
||||
f.write(chunk)
|
||||
pathlib.Path(root + "/data").write_bytes(b"version-A")
|
||||
os.chown(root + "/data", 12345, 23456)
|
||||
os.chmod(root + "/data", 0o640)
|
||||
os.link(root + "/data", root + "/d/hardlink")
|
||||
pathlib.Path(root + "/split-a").write_bytes(b"unchanged")
|
||||
os.link(root + "/split-a", root + "/d/split-b")
|
||||
os.symlink("../data", root + "/d/symlink")
|
||||
os.symlink("missing", root + "/dangling")
|
||||
os.link(root + "/dangling", root + "/d/symlink-hardlink", follow_symlinks=False)
|
||||
os.symlink("/etc/passwd", root + "/external")
|
||||
os.symlink("data", root + "/transition")
|
||||
os.mkfifo(root + "/fifo", 0o600)
|
||||
os.link(root + "/fifo", root + "/d/fifo-hardlink")
|
||||
with open(root + "/sparse", "wb") as f:
|
||||
f.truncate(16 << 20)
|
||||
pathlib.Path(root + "/deleted-later").write_text("historical")
|
||||
pathlib.Path(root + "/name with spaces\nand newline").write_text("name")
|
||||
os.setxattr(root + "/data", "user.cephmig", b"preserve")
|
||||
os.setxattr(root + "/data", "user.empty", b"")
|
||||
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"268435456")
|
||||
|
||||
|
||||
def edit_large(root, offset, data):
|
||||
p = root + "/large"
|
||||
old = os.stat(p)
|
||||
with open(p, "r+b") as f:
|
||||
f.seek(offset)
|
||||
f.write(data)
|
||||
# Content changes must be detected even when size and mtime are unchanged.
|
||||
os.utime(p, ns=(old.st_atime_ns, old.st_mtime_ns))
|
||||
|
||||
|
||||
def attrs(p):
|
||||
return {k: os.getxattr(p, k, follow_symlinks=False) for k in os.listxattr(p, follow_symlinks=False)
|
||||
if not k.startswith("ceph.")}
|
||||
|
||||
|
||||
def compare(src, dst):
|
||||
source_links, target_links = {}, {}
|
||||
|
||||
def visit(a, b):
|
||||
x, y = os.lstat(a), os.lstat(b)
|
||||
assert (x.st_mode, x.st_uid, x.st_gid, x.st_mtime_ns) == (
|
||||
y.st_mode, y.st_uid, y.st_gid, y.st_mtime_ns), (a, x, y)
|
||||
assert attrs(a) == attrs(b), (a, attrs(a), attrs(b))
|
||||
if not stat.S_ISDIR(x.st_mode):
|
||||
assert source_links.setdefault(x.st_ino, y.st_ino) == y.st_ino, a
|
||||
assert target_links.setdefault(y.st_ino, x.st_ino) == x.st_ino, a
|
||||
if stat.S_ISDIR(x.st_mode):
|
||||
for key in ("ceph.quota.max_bytes", "ceph.quota.max_files"):
|
||||
def quota(p):
|
||||
try:
|
||||
return os.getxattr(p, key)
|
||||
except OSError as e:
|
||||
if e.errno != 61:
|
||||
raise
|
||||
return b"0"
|
||||
assert quota(a) == quota(b), (a, key)
|
||||
names = set(os.listdir(a)) - {".snap"}
|
||||
assert names == set(os.listdir(b)) - {".snap"}, (a, names, os.listdir(b))
|
||||
for name in names:
|
||||
visit(a + "/" + name, b + "/" + name)
|
||||
elif stat.S_ISREG(x.st_mode):
|
||||
assert x.st_size == y.st_size, a
|
||||
def digest(p):
|
||||
h = hashlib.sha256()
|
||||
with open(p, "rb") as f:
|
||||
while chunk := f.read(4 << 20):
|
||||
h.update(chunk)
|
||||
return h.digest()
|
||||
assert digest(a) == digest(b), a
|
||||
elif stat.S_ISLNK(x.st_mode):
|
||||
assert os.readlink(a) == os.readlink(b), a
|
||||
else:
|
||||
assert x.st_rdev == y.st_rdev, a
|
||||
visit(src, dst)
|
||||
|
||||
|
||||
action = sys.argv[1]
|
||||
if action == "setup":
|
||||
name = "native-itest-" + str(uuid.uuid4())
|
||||
else:
|
||||
name = sys.argv[2]
|
||||
assert name.startswith("native-itest-") and len(name) == 49 and "/" not in name
|
||||
work = "/state/" + name
|
||||
state = work + "/job.json"
|
||||
config = work + "/config.json"
|
||||
fixture = work + "/fixture.json"
|
||||
|
||||
if action == "setup":
|
||||
os.mkdir(work, 0o700)
|
||||
for cluster in ("source", "target"):
|
||||
volume(cluster, "create", "cephfs", name)
|
||||
roots = {c: f"/mnt/{c}-fs" + volume(c, "getpath", "cephfs", name)
|
||||
for c in ("source", "target")}
|
||||
pathlib.Path(fixture).write_text(json.dumps(roots))
|
||||
c = json.load(open("/lab/migration.example.json"))
|
||||
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)
|
||||
volume("source", "metadata", "set", "cephfs", name, "owner", "application")
|
||||
snapshot("source", "create", "cephfs", name, "history-1")
|
||||
snapshot("source", "metadata", "set", "cephfs", name, "history-1", "app", "first")
|
||||
edit_large(src, 20 << 20, b"B" * 4096)
|
||||
pathlib.Path(src + "/data").write_bytes(b"version-B")
|
||||
os.unlink(src + "/deleted-later")
|
||||
p = src + "/d/split-b"
|
||||
old = os.stat(p)
|
||||
old_attrs = attrs(p)
|
||||
os.unlink(p)
|
||||
pathlib.Path(p).write_bytes(b"unchanged")
|
||||
for k in attrs(p):
|
||||
if k not in old_attrs:
|
||||
os.removexattr(p, k)
|
||||
for k, v in old_attrs.items():
|
||||
os.setxattr(p, k, v)
|
||||
os.chmod(p, old.st_mode & 0o7777)
|
||||
os.utime(p, ns=(old.st_atime_ns, old.st_mtime_ns))
|
||||
os.unlink(src + "/transition")
|
||||
os.mkdir(src + "/transition")
|
||||
old = os.lstat(src + "/d/fifo-hardlink")
|
||||
os.unlink(src + "/d/fifo-hardlink")
|
||||
os.mkfifo(src + "/d/fifo-hardlink", 0o600)
|
||||
os.utime(src + "/d/fifo-hardlink", ns=(old.st_atime_ns, old.st_mtime_ns))
|
||||
pathlib.Path(src + "/transition/child").write_bytes(b"child")
|
||||
os.setxattr(src + "/d", "ceph.quota.max_bytes", b"50331648")
|
||||
snapshot("source", "create", "cephfs", name, "history-2")
|
||||
snapshot("source", "metadata", "set", "cephfs", name, "history-2", "app", "second")
|
||||
pathlib.Path(src + "/data").write_bytes(b"version-C")
|
||||
os.setxattr(src + "/d", "ceph.quota.max_files", b"2000")
|
||||
print(name)
|
||||
elif action == "unthrottle":
|
||||
c = json.load(open(config))
|
||||
c.update(workers=4, bandwidth_kib=0)
|
||||
pathlib.Path(config).write_text(json.dumps(c))
|
||||
elif action == "mutate":
|
||||
roots = json.load(open(fixture))
|
||||
src, dst = roots["source"], roots["target"]
|
||||
edit_large(src, 20 << 20, bytes(4 << 20))
|
||||
edit_large(src, 70 << 20, b"growth" * 1024)
|
||||
os.setxattr(src + "/data", "user.cephmig", b"updated")
|
||||
os.removexattr(src + "/data", "user.empty")
|
||||
os.chmod(src + "/data", 0o660)
|
||||
os.unlink(src + "/d/split-b")
|
||||
os.link(src + "/split-a", src + "/d/split-b")
|
||||
shutil.rmtree(src + "/transition")
|
||||
os.symlink("data", src + "/transition")
|
||||
pathlib.Path(dst + "/obsolete").write_bytes(b"prune")
|
||||
volume("source", "metadata", "rm", "cephfs", name, "owner")
|
||||
volume("source", "metadata", "set", "cephfs", name, "project", "new-value")
|
||||
elif action in ("verify", "final"):
|
||||
roots = json.load(open(fixture))
|
||||
compare(roots["source"], roots["target"])
|
||||
s = json.load(open(state))
|
||||
for snap in s["snapshots"]:
|
||||
assert snap["done"], snap
|
||||
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 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"]
|
||||
assert h2["mode"] == "snapdiff" and h2["blockdiff_files"] > 0, h2
|
||||
assert h2["bytes_copied"] < 64 << 20, h2
|
||||
assert volume("source", "metadata", "ls", "cephfs", name) == volume(
|
||||
"target", "metadata", "ls", "cephfs", name)
|
||||
if action == "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 == "busy":
|
||||
# An unrelated source subvolume remains writable throughout migration/finalization.
|
||||
p = "/mnt/source/" + name
|
||||
count = 0
|
||||
try:
|
||||
with open(p, "wb", buffering=0) as f:
|
||||
while not os.path.exists(work + "/stop-busy"):
|
||||
f.seek(0)
|
||||
f.write(str(count).encode())
|
||||
os.fsync(f.fileno())
|
||||
count += 1
|
||||
pathlib.Path(work + "/busy-count").write_text(str(count))
|
||||
time.sleep(0.1)
|
||||
finally:
|
||||
os.unlink(p)
|
||||
elif action == "cleanup":
|
||||
for cluster in ("source", "target"):
|
||||
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)
|
||||
shutil.rmtree(work)
|
||||
else:
|
||||
raise ValueError(action)
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
compose=(docker compose -f dev/compose.yaml)
|
||||
fixture() { "${compose[@]}" exec -T client python3 /lab/native-fixture.py "$@"; }
|
||||
name=$(fixture setup)
|
||||
work="/state/$name"
|
||||
state="$work/job.json"
|
||||
config="$work/config.json"
|
||||
binary=/usr/local/bin/cephmig-native
|
||||
completed=false
|
||||
busy_pid=
|
||||
cleanup() {
|
||||
"${compose[@]}" exec -T native touch "$work/stop-busy" || true
|
||||
if [[ -n $busy_pid ]]; then wait "$busy_pid" || true; fi
|
||||
if [[ $completed = true ]]; then
|
||||
fixture cleanup "$name"
|
||||
else
|
||||
echo "FAIL: retained native fixtures subvolume=$name state=$state" >&2
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
fixture busy "$name" &
|
||||
busy_pid=$!
|
||||
"${compose[@]}" exec -T native "$binary" inspect --config "$config"
|
||||
"${compose[@]}" exec -T native bash -s -- "$binary" "$config" "$state" "$work" <<'SH'
|
||||
set -Eeuo pipefail
|
||||
binary=$1 config=$2 state=$3 work=$4
|
||||
test ! -e /dev/fuse
|
||||
! command -v rsync
|
||||
! grep -q 'fuse.ceph' /proc/self/mountinfo
|
||||
"$binary" sync --config "$config" --state "$state" > "$work/interrupted.json" 2> "$work/interrupted.log" &
|
||||
pid=$!
|
||||
for ((i=0; i<300; i++)); do
|
||||
kill -0 "$pid" || { cat "$work/interrupted.log"; exit 1; }
|
||||
if grep -q 'snapshot=history-1: copying' "$work/interrupted.log"; then break; fi
|
||||
sleep 0.1
|
||||
done
|
||||
sleep 1
|
||||
kill -TERM "$pid"
|
||||
if wait "$pid"; then echo 'expected cancellation' >&2; exit 1; fi
|
||||
grep -q 'context canceled' "$work/interrupted.log"
|
||||
python3 - "$state" <<'PY'
|
||||
import json,sys
|
||||
s=json.load(open(sys.argv[1]))
|
||||
assert not s.get("live_snapshot") and not s["snapshots"][0]["done"], s
|
||||
PY
|
||||
SH
|
||||
fixture unthrottle "$name"
|
||||
# Crash after the target snapshot was persisted, before the journal can mark it done.
|
||||
"${compose[@]}" exec -T native bash -s -- "$binary" "$config" "$state" "$work" <<'SH'
|
||||
set -Eeuo pipefail
|
||||
binary=$1 config=$2 state=$3 work=$4
|
||||
mkdir "$work/bin"
|
||||
cat > "$work/bin/ceph" <<'WRAPPER'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [[ -f $CEPHMIG_CRASH_ONCE && " $* " == *'/clusters/target/ceph.conf'* &&
|
||||
" $* " == *' fs subvolume snapshot create '* ]]; then
|
||||
/usr/bin/ceph "$@"
|
||||
rm "$CEPHMIG_CRASH_ONCE"
|
||||
kill -KILL "$PPID"
|
||||
exit 0
|
||||
fi
|
||||
exec /usr/bin/ceph "$@"
|
||||
WRAPPER
|
||||
chmod +x "$work/bin/ceph"
|
||||
export CEPHMIG_CRASH_ONCE="$work/crash"
|
||||
touch "$CEPHMIG_CRASH_ONCE"
|
||||
if PATH="$work/bin:$PATH" "$binary" sync --config "$config" --state "$state" > "$work/crashed.json"; then
|
||||
echo 'expected SIGKILL' >&2; exit 1
|
||||
fi
|
||||
test ! -f "$CEPHMIG_CRASH_ONCE"
|
||||
SH
|
||||
"${compose[@]}" exec -T native "$binary" sync --config "$config" --state "$state"
|
||||
fixture verify "$name"
|
||||
fixture mutate "$name"
|
||||
"${compose[@]}" exec -T native "$binary" sync --config "$config" --state "$state"
|
||||
"${compose[@]}" exec -T native cp "$work/busy-count" "$work/busy-before-final"
|
||||
"${compose[@]}" exec -T native "$binary" finalize --config "$config" --state "$state" --writers-stopped
|
||||
fixture final "$name"
|
||||
"${compose[@]}" exec -T native bash -s -- "$binary" "$config" "$state" "$work" <<'SH'
|
||||
set -Eeuo pipefail
|
||||
cp "$3" "$4/before.json"
|
||||
"$1" finalize --config "$2" --state "$3" --writers-stopped > "$4/idempotent.json"
|
||||
python3 - "$4" <<'PY'
|
||||
import json,pathlib,sys
|
||||
p=pathlib.Path(sys.argv[1])
|
||||
assert json.loads((p/"before.json").read_text()) == json.loads((p/"idempotent.json").read_text())
|
||||
assert int((p/"busy-count").read_text()) > int((p/"busy-before-final").read_text()) > 20
|
||||
PY
|
||||
SH
|
||||
completed=true
|
||||
echo 'PASS: native libcephfs without FUSE/rsync, blockdiff, snapshots, links, ACLs, xattrs, quotas, cancellation, SIGKILL resume, unrelated writers, finalization'
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
compose() { docker compose -f dev/compose.yaml "$@"; }
|
||||
marker=".cephmig-restart-$(cat /proc/sys/kernel/random/uuid)"
|
||||
source_fsid=$(compose exec -T source ceph fsid)
|
||||
target_fsid=$(compose exec -T target ceph fsid)
|
||||
test "$source_fsid" != "$target_fsid"
|
||||
cleanup() {
|
||||
compose exec -T client rm -f "/mnt/source/$marker" "/mnt/target/$marker" || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
compose exec -T client bash -c 'printf source > "/mnt/source/$1"; printf target > "/mnt/target/$1"' bash "$marker"
|
||||
compose down
|
||||
compose up -d --wait --wait-timeout 300
|
||||
test "$(compose exec -T source ceph fsid)" = "$source_fsid"
|
||||
test "$(compose exec -T target ceph fsid)" = "$target_fsid"
|
||||
test "$(compose exec -T client cat "/mnt/source/$marker")" = source
|
||||
test "$(compose exec -T client cat "/mnt/target/$marker")" = target
|
||||
echo 'PASS: cluster identities and subvolume data survive down/up'
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
compose=(docker compose -f dev/compose.yaml)
|
||||
count=${FILES:-10000}
|
||||
report=${REPORT_DIR:-/tmp/cephmig-smallfiles-report}
|
||||
binary=${BINARY:-/usr/local/bin/cephmig-native}
|
||||
mkdir -p "$report"
|
||||
docker inspect cephmig-dev-native-1 --format '{{.Image}}' > "$report/native-image.txt"
|
||||
python3 - "$count" "$binary" "$report/settings.json" <<'PY'
|
||||
import json,sys
|
||||
with open(sys.argv[3],"w") as f: json.dump(dict(files=int(sys.argv[1]),bytes_per_file=128,workers=4,binary=sys.argv[2]),f)
|
||||
PY
|
||||
mds_counters() {
|
||||
"${compose[@]}" exec -T "$1" ceph daemon mds.a perf dump | python3 -c '
|
||||
import json,sys
|
||||
d=json.load(sys.stdin)
|
||||
s=d["mds_server"]
|
||||
print(json.dumps(dict(requests=d["mds"]["request"],**{
|
||||
k:s["req_"+k+"_latency"]["avgcount"] for k in ("getattr","lookup","lookupsnap","setattr","readdir")})))'
|
||||
}
|
||||
df -B1 . > "$report/host-before.txt"
|
||||
"${compose[@]}" exec -T source ceph df --format json > "$report/source-before.json"
|
||||
"${compose[@]}" exec -T target ceph df --format json > "$report/target-before.json"
|
||||
name=$("${compose[@]}" exec -T client python3 /lab/smallfiles.py setup --count "$count")
|
||||
printf '%s\n' "$name" > "$report/fixture-name.txt"
|
||||
completed=false
|
||||
cleanup() {
|
||||
if [[ $completed = true ]]; then
|
||||
"${compose[@]}" exec -T client python3 /lab/smallfiles.py cleanup "$name"
|
||||
else
|
||||
echo "FAIL: retained fixture $name; diagnostics at /state/$name" >&2
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
for phase in initial catchup final; do
|
||||
if [[ $phase = catchup ]]; then
|
||||
"${compose[@]}" exec -T client python3 /lab/smallfiles.py mutate "$name"
|
||||
fi
|
||||
echo "smallfiles: phase=$phase count=$count"
|
||||
for cluster in source target; do
|
||||
mds_counters "$cluster" > "$report/$phase-$cluster-mds-before.json"
|
||||
done
|
||||
"${compose[@]}" exec -T native python3 /lab/smallfiles.py run "$name" --phase "$phase" --binary "$binary" |
|
||||
tee "$report/$phase.json"
|
||||
for cluster in source target; do
|
||||
mds_counters "$cluster" > "$report/$phase-$cluster-mds-after.json"
|
||||
done
|
||||
done
|
||||
"${compose[@]}" exec -T client python3 /lab/smallfiles.py verify "$name" |
|
||||
tee "$report/verification.json"
|
||||
"${compose[@]}" exec -T native du -sk "/state/$name" > "$report/local-state-kib.txt"
|
||||
"${compose[@]}" exec -T source ceph df --format json > "$report/source-after.json"
|
||||
"${compose[@]}" exec -T target ceph df --format json > "$report/target-after.json"
|
||||
df -B1 . > "$report/host-after.txt"
|
||||
completed=true
|
||||
echo "PASS: $count small files, snapshots, same-mtime changes, deletes, renames, metadata, links; report=$report"
|
||||
@@ -0,0 +1,268 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Space-conscious, application-side many-small-files migration benchmark."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
def ceph(cluster, *args):
|
||||
return subprocess.check_output([
|
||||
"ceph", "-c", f"/clusters/{cluster}/ceph.conf", "-k",
|
||||
f"/clusters/{cluster}/ceph.client.admin.keyring", *args], text=True).strip()
|
||||
|
||||
|
||||
def volume(cluster, *args):
|
||||
return ceph(cluster, "fs", "subvolume", *args, "--group_name", "migration")
|
||||
|
||||
|
||||
def snap(cluster, *args):
|
||||
return volume(cluster, "snapshot", *args)
|
||||
|
||||
|
||||
def relative(i, count):
|
||||
return f"flat/f{i:08d}" if i < count // 2 else f"tree/b{i % 50:02d}/f{i:08d}"
|
||||
|
||||
|
||||
def payload(i, version):
|
||||
return hashlib.sha256(f"{i}:{version}".encode()).digest() * 4
|
||||
|
||||
|
||||
def posix_acl():
|
||||
entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff),
|
||||
(16, 4, 0xffffffff), (32, 0, 0xffffffff)]
|
||||
return struct.pack("<I", 2) + b"".join(struct.pack("<HHI", *e) for e in entries)
|
||||
|
||||
|
||||
def stop_child(process):
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
def attrs(p):
|
||||
return {k: os.getxattr(p, k, follow_symlinks=False)
|
||||
for k in os.listxattr(p, follow_symlinks=False) if not k.startswith("ceph.")}
|
||||
|
||||
|
||||
def compare(source, target, label="live"):
|
||||
print(f"verifying {label}", file=sys.stderr, flush=True)
|
||||
forward, backward = {}, {}
|
||||
checked = 0
|
||||
|
||||
def visit(a, b):
|
||||
nonlocal checked
|
||||
x, y = os.lstat(a), os.lstat(b)
|
||||
if (x.st_mode, x.st_uid, x.st_gid, x.st_mtime_ns) != (
|
||||
y.st_mode, y.st_uid, y.st_gid, y.st_mtime_ns):
|
||||
raise AssertionError(f"metadata mismatch: {a}")
|
||||
if attrs(a) != attrs(b):
|
||||
raise AssertionError(f"xattr mismatch: {a}")
|
||||
if stat.S_ISDIR(x.st_mode):
|
||||
with os.scandir(a) as entries:
|
||||
names = {e.name for e in entries if e.name != ".snap"}
|
||||
with os.scandir(b) as entries:
|
||||
other = {e.name for e in entries if e.name != ".snap"}
|
||||
if names != other:
|
||||
raise AssertionError(f"directory inventory mismatch: {a}")
|
||||
for name in names:
|
||||
visit(os.path.join(a, name), os.path.join(b, name))
|
||||
else:
|
||||
if forward.setdefault(x.st_ino, y.st_ino) != y.st_ino:
|
||||
raise AssertionError(f"hardlink split: {a}")
|
||||
if backward.setdefault(y.st_ino, x.st_ino) != x.st_ino:
|
||||
raise AssertionError(f"unrelated files hardlinked: {a}")
|
||||
if stat.S_ISREG(x.st_mode):
|
||||
if x.st_size != y.st_size or x.st_size != 128:
|
||||
raise AssertionError(f"size mismatch: {a}")
|
||||
if Path(a).read_bytes() != Path(b).read_bytes():
|
||||
raise AssertionError(f"content mismatch: {a}")
|
||||
checked += 1
|
||||
elif stat.S_ISLNK(x.st_mode):
|
||||
if os.readlink(a) != os.readlink(b):
|
||||
raise AssertionError(f"symlink mismatch: {a}")
|
||||
else:
|
||||
raise AssertionError(f"unexpected file type: {a}")
|
||||
visit(source, target)
|
||||
print(f"verified {label}: {checked} regular file paths", file=sys.stderr, flush=True)
|
||||
return checked
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("action", choices=["setup", "mutate", "verify", "cleanup", "run"])
|
||||
p.add_argument("name", nargs="?")
|
||||
p.add_argument("--count", type=int, default=10000)
|
||||
p.add_argument("--phase", choices=["initial", "catchup", "final"])
|
||||
p.add_argument("--binary", default=os.environ.get("CEPHMIG_BENCH_BINARY", "/usr/local/bin/cephmig-native"))
|
||||
p.add_argument("--timeout", type=int, default=1800)
|
||||
args = p.parse_args()
|
||||
name = args.name or "smallfiles-" + str(uuid.uuid4())
|
||||
if not name.startswith("smallfiles-") or str(uuid.UUID(name[11:])) != name[11:]:
|
||||
raise ValueError("not a smallfiles fixture name")
|
||||
work = Path("/state") / name
|
||||
config, journal = work / "config.json", work / "job.json"
|
||||
if args.action == "setup":
|
||||
if not 100 <= args.count <= 50000 or args.count % 100:
|
||||
raise ValueError("count must be a multiple of 100, from 100 to 50000")
|
||||
print(f"creating fixture {name}, count={args.count}", file=sys.stderr)
|
||||
# A conservative allowance for object allocation, metadata and snapshot
|
||||
# history, plus an untouched reserve. This is a guard, not a capacity model.
|
||||
required = (1 << 30) + args.count * (64 << 10)
|
||||
for cluster in ("source", "target"):
|
||||
capacity = json.loads(ceph(cluster, "df", "--format", "json"))
|
||||
if capacity["stats"]["total_avail_bytes"] < required:
|
||||
raise RuntimeError(f"{cluster}: insufficient estimated space budget including reserve; "
|
||||
"reduce --count; no fixture created")
|
||||
work.mkdir(mode=0o700)
|
||||
for cluster in ("source", "target"):
|
||||
volume(cluster, "create", "cephfs", name)
|
||||
roots = {c: f"/mnt/{c}-fs" + volume(c, "getpath", "cephfs", name)
|
||||
for c in ("source", "target")}
|
||||
(work / "fixture.json").write_text(json.dumps(dict(roots=roots, count=args.count)))
|
||||
c = json.loads(Path("/lab/migration.example.json").read_text())
|
||||
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()
|
||||
(root / "tree").mkdir()
|
||||
(root / "links").mkdir()
|
||||
for i in range(50):
|
||||
(root / "tree" / f"b{i:02d}").mkdir()
|
||||
os.setxattr(root / "tree" / "b00", "system.posix_acl_default", posix_acl())
|
||||
for i in range(args.count):
|
||||
f = root / relative(i, args.count)
|
||||
f.write_bytes(payload(i, 0))
|
||||
if i == 0:
|
||||
os.chown(f, 12345, 23456)
|
||||
os.setxattr(f, "system.posix_acl_access", posix_acl())
|
||||
if i % 100 == 4:
|
||||
os.setxattr(f, "user.remove", b"original")
|
||||
if i < 100:
|
||||
os.link(f, root / "links" / f"hard{i:03d}")
|
||||
os.symlink("../" + relative(i, args.count), root / "links" / f"soft{i:03d}")
|
||||
snap("source", "create", "cephfs", name, "baseline")
|
||||
print(name)
|
||||
return
|
||||
if args.name is None:
|
||||
raise ValueError("existing fixture name is required")
|
||||
fixture = json.loads((work / "fixture.json").read_text())
|
||||
count, roots = fixture["count"], fixture["roots"]
|
||||
if args.action == "mutate":
|
||||
root = Path(roots["source"])
|
||||
for i in range(count):
|
||||
f = root / relative(i, count)
|
||||
if i % 100 == 0:
|
||||
previous = f.stat()
|
||||
f.write_bytes(payload(i, 1))
|
||||
os.utime(f, ns=(previous.st_atime_ns, previous.st_mtime_ns))
|
||||
elif i % 100 == 1:
|
||||
f.unlink()
|
||||
elif i % 100 == 2:
|
||||
f.rename(f.with_name(f.name + "-renamed"))
|
||||
elif i % 100 == 3:
|
||||
os.chmod(f, 0o640)
|
||||
os.setxattr(f, "user.generation", b"1")
|
||||
elif i % 100 == 4:
|
||||
os.removexattr(f, "user.remove")
|
||||
for i in range(count // 100):
|
||||
(root / "flat" / f"new{i:08d}").write_bytes(payload(i, 2))
|
||||
elif args.action == "run":
|
||||
if args.phase is None:
|
||||
raise ValueError("--phase required")
|
||||
if args.timeout <= 0 or not os.path.isabs(args.binary):
|
||||
raise ValueError("positive timeout and absolute binary path required")
|
||||
command = [args.binary,
|
||||
"finalize" if args.phase == "final" else "sync",
|
||||
"--config", str(config), "--state", str(journal)]
|
||||
if args.phase == "final":
|
||||
command.append("--writers-stopped")
|
||||
started = time.monotonic()
|
||||
wall_started = time.time()
|
||||
last_progress = started
|
||||
peak_rss = 0
|
||||
with (work / f"{args.phase}.stdout.json").open("w") as out, (
|
||||
work / f"{args.phase}.log").open("w") as log:
|
||||
process = subprocess.Popen(command, stdout=out, stderr=log)
|
||||
while process.poll() is None:
|
||||
try:
|
||||
for line in Path(f"/proc/{process.pid}/status").read_text().splitlines():
|
||||
if line.startswith(("VmRSS:", "VmHWM:")):
|
||||
peak_rss = max(peak_rss, int(line.split()[1]))
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
now = time.monotonic()
|
||||
if now - started > args.timeout:
|
||||
stop_child(process)
|
||||
raise RuntimeError("benchmark phase timed out; fixture retained")
|
||||
if abs((time.time() - wall_started) - (now - started)) > 5:
|
||||
stop_child(process)
|
||||
raise RuntimeError("host suspend or clock jump detected; discard timing and rerun")
|
||||
if now - last_progress >= 30:
|
||||
print(f"{args.phase}: elapsed={now - started:.0f}s "
|
||||
f"native_peak_rss={peak_rss / 1024:.1f} MiB",
|
||||
file=sys.stderr, flush=True)
|
||||
last_progress = now
|
||||
time.sleep(0.1)
|
||||
elapsed = time.monotonic() - started
|
||||
if process.returncode:
|
||||
print((work / f"{args.phase}.log").read_text(), file=sys.stderr)
|
||||
raise RuntimeError(f"migration exited {process.returncode}")
|
||||
state = json.loads(journal.read_text())
|
||||
if not all(x["done"] for x in state["snapshots"]):
|
||||
raise AssertionError("unfinished snapshot")
|
||||
if args.phase == "final" and (state["phase"] != "ready-for-cutover" or
|
||||
state["snapshots"][-1]["transfer"]["bytes_copied"] != 0):
|
||||
raise AssertionError("finalization must finish without rewriting unchanged data")
|
||||
result = dict(phase=args.phase, seconds=round(elapsed, 3),
|
||||
native_peak_rss_kib=peak_rss,
|
||||
rounds=[dict(name=x["name"], **x["transfer"]) for x in state["snapshots"]])
|
||||
(work / f"{args.phase}.metrics.json").write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps(result), flush=True)
|
||||
elif args.action == "verify":
|
||||
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:
|
||||
raise AssertionError("unexpected file count or incomplete migration")
|
||||
snapshots = []
|
||||
for s in state["snapshots"]:
|
||||
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"])
|
||||
if snapshot_checked != count + 100:
|
||||
raise AssertionError(f"unexpected snapshot file count: {s['name']}")
|
||||
snapshots.append(dict(name=s["name"], files_checked=snapshot_checked))
|
||||
result = dict(live_files_checked=checked, snapshots=snapshots,
|
||||
seconds=round(time.monotonic() - started, 3))
|
||||
(work / "verification.json").write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps(result))
|
||||
elif args.action == "cleanup":
|
||||
for cluster in ("source", "target"):
|
||||
for s in json.loads(snap(cluster, "ls", "cephfs", name)):
|
||||
snap(cluster, "rm", "cephfs", name, s["name"])
|
||||
volume(cluster, "rm", "cephfs", name, "--force")
|
||||
claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest()
|
||||
try:
|
||||
os.unlink("/mnt/target-fs/.cephmig/claims/" + claim)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
shutil.rmtree(work)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
mountpoint -q /mnt/source
|
||||
mountpoint -q /mnt/target
|
||||
mountpoint -q /mnt/source-fs
|
||||
test_dir=".cephmig-smoke-$(cat /proc/sys/kernel/random/uuid)"
|
||||
source_ceph() {
|
||||
ceph -c /clusters/source/ceph.conf -k /clusters/source/ceph.client.admin.keyring "$@"
|
||||
}
|
||||
snapshot_created=false
|
||||
cleanup() {
|
||||
if [[ $snapshot_created = true ]]; then
|
||||
source_ceph fs subvolume snapshot rm cephfs demo "$test_dir" --group_name migration
|
||||
fi
|
||||
rm -rf "/mnt/source/$test_dir" "/mnt/target/$test_dir"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
mkdir "/mnt/source/$test_dir" "/mnt/target/$test_dir"
|
||||
printf 'cephmig source\n' > "/mnt/source/$test_dir/file"
|
||||
ln "/mnt/source/$test_dir/file" "/mnt/source/$test_dir/hardlink"
|
||||
ln -s file "/mnt/source/$test_dir/symlink"
|
||||
truncate -s 16777216 "/mnt/source/$test_dir/sparse"
|
||||
chmod 0640 "/mnt/source/$test_dir/file"
|
||||
python3 - "/mnt/source/$test_dir/file" <<'PY'
|
||||
import os, struct, sys
|
||||
os.setxattr(sys.argv[1], 'user.cephmig', b'preserve-me')
|
||||
# POSIX ACL: owner rw, named user 12345 r, group ---, mask r, other ---.
|
||||
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(sys.argv[1], 'system.posix_acl_access', acl)
|
||||
PY
|
||||
source_ceph fs subvolume snapshot create cephfs demo "$test_dir" --group_name migration
|
||||
snapshot_created=true
|
||||
snapshot_path=$(source_ceph fs subvolume snapshot getpath cephfs demo "$test_dir" migration)
|
||||
snapshot="/mnt/source-fs$snapshot_path/$test_dir"
|
||||
# Continue writes on the live subvolume while copying its immutable snapshot.
|
||||
printf 'live write after snapshot\n' > "/mnt/source/$test_dir/file"
|
||||
cp -a "$snapshot/." "/mnt/target/$test_dir/"
|
||||
diff -r "$snapshot" "/mnt/target/$test_dir"
|
||||
test "$(cat "/mnt/target/$test_dir/file")" = 'cephmig source'
|
||||
test "$(cat "/mnt/source/$test_dir/file")" = 'live write after snapshot'
|
||||
test "$(stat -c %a "/mnt/target/$test_dir/file")" = 640
|
||||
python3 - "$snapshot/file" "/mnt/target/$test_dir/file" <<'PY'
|
||||
import os, sys
|
||||
assert os.getxattr(sys.argv[2], 'user.cephmig') == b'preserve-me'
|
||||
assert os.getxattr(sys.argv[1], 'system.posix_acl_access') == os.getxattr(sys.argv[2], 'system.posix_acl_access')
|
||||
PY
|
||||
# Quotas belong to directories and need explicit handling beyond file copying.
|
||||
python3 - "/mnt/source/$test_dir" "/mnt/target/$test_dir" <<'PY'
|
||||
import os, sys
|
||||
for path in sys.argv[1:]:
|
||||
os.setxattr(path, 'ceph.quota.max_bytes', b'33554432')
|
||||
assert os.getxattr(path, 'ceph.quota.max_bytes') == b'33554432'
|
||||
os.setxattr(path, 'ceph.quota.max_bytes', b'0')
|
||||
PY
|
||||
test "$(stat -c %i "/mnt/target/$test_dir/file")" = "$(stat -c %i "/mnt/target/$test_dir/hardlink")"
|
||||
test "$(readlink "/mnt/target/$test_dir/symlink")" = file
|
||||
printf 'target only\n' > "/mnt/target/$test_dir/isolated"
|
||||
test ! -e "/mnt/source/$test_dir/isolated"
|
||||
echo 'PASS: independent clusters, snapshot copy with live changes, permissions, POSIX ACL, xattr, quota operations, hardlink, symlink, sparse-file contents'
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only lab probe: compare native snapshot identity across two clusters."""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
import cephfs
|
||||
|
||||
|
||||
def snapshot_identity(endpoint, name):
|
||||
args = ["ceph", "--conf", endpoint["config"], "--keyring", endpoint["keyring"]]
|
||||
user = endpoint.get("user", "client.admin")
|
||||
if user:
|
||||
args += ["--name", user]
|
||||
args += ["fs", "subvolume", "snapshot", "getpath",
|
||||
endpoint["filesystem"], endpoint["subvolume"], name]
|
||||
if endpoint.get("group"):
|
||||
args += ["--group_name", endpoint["group"]]
|
||||
path = subprocess.check_output(args, text=True, timeout=30).strip()
|
||||
fs = cephfs.LibCephFS(conffile=endpoint["config"],
|
||||
auth_id=user.removeprefix("client."))
|
||||
try:
|
||||
fs.conf_set("keyring", endpoint["keyring"])
|
||||
fs.conf_set("client_fs", endpoint["filesystem"])
|
||||
fs.mount()
|
||||
info = fs.snap_info(path)
|
||||
birthtime = fs.getxattr(path, "ceph.snap.btime").decode("ascii")
|
||||
return {"id": info["id"], "birthtime": birthtime}
|
||||
finally:
|
||||
fs.shutdown()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", required=True)
|
||||
parser.add_argument("--snapshot", required=True)
|
||||
args = parser.parse_args()
|
||||
with open(args.config) as f:
|
||||
config = json.load(f)
|
||||
source = snapshot_identity(config["source"], args.snapshot)
|
||||
target = snapshot_identity(config["target"], args.snapshot)
|
||||
print(json.dumps({"snapshot": args.snapshot, "source": source, "target": target,
|
||||
"native_ids_equal": source["id"] == target["id"],
|
||||
"native_birthtimes_equal": source["birthtime"] == target["birthtime"]}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in new issue
Block a user