mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Compare commits
84
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7bb77d8d2 | ||
|
|
b9689882e2 | ||
|
|
8f8c8a17c1 | ||
|
|
aa48658739 | ||
|
|
78893d274a | ||
|
|
8c67b75190 | ||
|
|
7a19961074 | ||
|
|
16e66b1bad | ||
|
|
7e809c9991 | ||
|
|
3c17c5146e | ||
|
|
483dd4b12e | ||
|
|
9d1c24d80d | ||
|
|
76ddde6a6d | ||
|
|
0d93dec145 | ||
|
|
d9b69a7f76 | ||
|
|
2b5fdc639f | ||
|
|
d7a02567e3 | ||
|
|
39bc9cd0ef | ||
|
|
f4ef37e752 | ||
|
|
10b0f2b8ad | ||
|
|
eafe79ebff | ||
|
|
562afa8ec9 | ||
|
|
8c1ebbee32 | ||
|
|
c9ade3f9fd | ||
|
|
6c07a5fdd0 | ||
|
|
07da302da0 | ||
|
|
68df7511f6 | ||
|
|
793ce06b10 | ||
|
|
0ca484c354 | ||
|
|
3e679e925e | ||
|
|
52fb9f93ff | ||
|
|
0ff7794c54 | ||
|
|
94edd0a6d4 | ||
|
|
30069f3e45 | ||
|
|
fa77cde7da | ||
|
|
35b090a4df | ||
|
|
1445960f8c | ||
|
|
43abe21ffa | ||
|
|
67034dee12 | ||
|
|
8d97284d0a | ||
|
|
d8f926cf46 | ||
|
|
8a9563e53d | ||
|
|
90f8c4378f | ||
|
|
eeec9ec09a | ||
|
|
7c7834c98e | ||
|
|
2a42d56437 | ||
|
|
164c3db606 | ||
|
|
6f9becaa37 | ||
|
|
3fd5e4c329 | ||
|
|
9d3907e36c | ||
|
|
bd953b0f84 | ||
|
|
7944cb4ba2 | ||
|
|
15d3c65e0c | ||
|
|
fea14c01a7 | ||
|
|
f2498e122a | ||
|
|
62481f1673 | ||
|
|
b8f074b7d3 | ||
|
|
cc1ec48151 | ||
|
|
5ece8dd63c | ||
|
|
67f7fad987 | ||
|
|
2b057eccbf | ||
|
|
8fdcf69eb0 | ||
|
|
988fc4f7ba | ||
|
|
11e8c4c288 | ||
|
|
d3cd061c22 | ||
|
|
895d49b55b | ||
|
|
95e0b74fb6 | ||
|
|
0978e7f833 | ||
|
|
38ce95d960 | ||
|
|
9a454bbe2b | ||
|
|
757917f564 | ||
|
|
a033ab76e5 | ||
|
|
5fcf12c080 | ||
|
|
5da137233d | ||
|
|
62d4f9152a | ||
|
|
a901c1a5e2 | ||
|
|
67b19b2db5 | ||
|
|
c54f1fe69c | ||
|
|
818ff69270 | ||
|
|
db89ed198b | ||
|
|
f7b5ca826b | ||
|
|
878d23b95a | ||
|
|
1e0b243aed | ||
|
|
79e2abdfbf |
No files matched your search
@@ -27,7 +27,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.38.1
|
||||
uses: github/codeql-action/init@v4.38.2
|
||||
# Override language selection by uncommenting this and choosing your languages
|
||||
with:
|
||||
languages: go
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below).
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v4.38.1
|
||||
uses: github/codeql-action/autobuild@v4.38.2
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
@@ -49,4 +49,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4.38.1
|
||||
uses: github/codeql-action/analyze@v4.38.2
|
||||
@@ -156,7 +156,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [amd64, arm64, arm, 386]
|
||||
platform: [amd64, arm64, arm, 386, ppc64le, s390x]
|
||||
variant: ${{ fromJSON(needs.setup.outputs.variants) }}
|
||||
|
||||
steps:
|
||||
@@ -405,7 +405,7 @@ jobs:
|
||||
output: trivy-results.sarif
|
||||
exit-code: '0'
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
uses: github/codeql-action/upload-sarif@v4.38.1
|
||||
uses: github/codeql-action/upload-sarif@v4.38.2
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
@@ -505,7 +505,9 @@ jobs:
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-ppc64le \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-s390x
|
||||
# The copy and the signature below use the digest this run pushed, not whatever the tag points at by then.
|
||||
DIGEST=$(jq -er '."containerimage.descriptor".digest' /tmp/manifest.json)
|
||||
echo "digest=${DIGEST}" >> "$GITHUB_OUTPUT"
|
||||
@@ -549,13 +551,15 @@ jobs:
|
||||
echo "Using skopeo to copy..."
|
||||
retry_with_backoff skopeo copy --all docker://ghcr.io/chrislusf/seaweedfs@${DIGEST} docker://chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}
|
||||
else
|
||||
echo "Using docker buildx imagetools (pulling 4 images from Docker Hub)..."
|
||||
echo "Using docker buildx imagetools (pulling 6 images from Docker Hub)..."
|
||||
# Fallback: create manifest directly on Docker Hub (pulls from Docker Hub - rate limited)
|
||||
retry_with_backoff docker buildx imagetools create -t chrislusf/seaweedfs:${BASE_TAG}${SUFFIX} \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-ppc64le \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-s390x
|
||||
fi
|
||||
|
||||
- name: Sign
|
||||
|
||||
@@ -149,12 +149,16 @@ jobs:
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/arm/v7, arch: armv7, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/386, arch: i386, runner: ubuntu-latest, qemu: false }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/ppc64le, arch: ppc64le, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/s390x, arch: s390x, runner: ubuntu-latest, qemu: true }
|
||||
|
||||
# Large disk - multi-arch
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/arm/v7, arch: armv7, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/386, arch: i386, runner: ubuntu-latest, qemu: false }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/ppc64le, arch: ppc64le, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/s390x, arch: s390x, runner: ubuntu-latest, qemu: true }
|
||||
|
||||
# Full tags - multi-arch
|
||||
- { variant: full, tag_suffix: _full, dockerfile: ./docker/Dockerfile.go_build, build_args: "TAGS=elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb", rust_variant: normal, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
|
||||
@@ -456,7 +460,7 @@ jobs:
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v4.38.1
|
||||
uses: github/codeql-action/upload-sarif@v4.38.2
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
category: trivy-${{ matrix.variant }}
|
||||
|
||||
@@ -116,6 +116,21 @@ jobs:
|
||||
grep -q "security-config" /tmp/security.yaml
|
||||
echo "Security configuration renders correctly"
|
||||
|
||||
echo "=== Testing secure bucket-creation hook certificate mounts ==="
|
||||
helm template test $CHART_DIR \
|
||||
--show-only templates/shared/post-install-bucket-hook.yaml \
|
||||
--set s3.enabled=true \
|
||||
--set 's3.createBuckets[0].name=data' \
|
||||
--set global.seaweedfs.enableSecurity=true \
|
||||
> /tmp/security-bucket-hook.yaml
|
||||
test "$(grep -cE '^[[:space:]]*- name: ca-cert$' /tmp/security-bucket-hook.yaml)" -eq 2
|
||||
test "$(grep -cE '^[[:space:]]*- name: client-cert$' /tmp/security-bucket-hook.yaml)" -eq 2
|
||||
grep -q 'mountPath: /usr/local/share/ca-certificates/ca/' /tmp/security-bucket-hook.yaml
|
||||
grep -q 'mountPath: /usr/local/share/ca-certificates/client/' /tmp/security-bucket-hook.yaml
|
||||
grep -q 'secretName: test-seaweedfs-ca-cert' /tmp/security-bucket-hook.yaml
|
||||
grep -q 'secretName: test-seaweedfs-client-cert' /tmp/security-bucket-hook.yaml
|
||||
echo "Secure bucket-creation hook mounts its CA and client certificate"
|
||||
|
||||
echo ""
|
||||
echo "=== Testing admin.allowInsecureBind satisfies the admin auth render guard ==="
|
||||
helm template test $CHART_DIR --set admin.enabled=true --set admin.allowInsecureBind=true \
|
||||
@@ -718,6 +733,168 @@ jobs:
|
||||
helm template test $CHART_DIR --set cosi.enabled=true > /tmp/cosi.yaml
|
||||
grep -q "seaweedfs-cosi" /tmp/cosi.yaml
|
||||
echo "COSI driver renders correctly"
|
||||
|
||||
echo ""
|
||||
echo "=== Testing configurable pod and container security contexts ==="
|
||||
helm template test $CHART_DIR > /tmp/security-context-defaults.yaml
|
||||
|
||||
security_context_args=()
|
||||
for component in master volume filer s3 sftp admin worker allInOne cosi; do
|
||||
security_context_args+=(
|
||||
--set "$component.podSecurityContext.enabled=true"
|
||||
--set "$component.podSecurityContext.seccompProfile.type=RuntimeDefault"
|
||||
--set "$component.containerSecurityContext.enabled=true"
|
||||
--set "$component.containerSecurityContext.privileged=false"
|
||||
--set "$component.containerSecurityContext.allowPrivilegeEscalation=false"
|
||||
--set "$component.containerSecurityContext.readOnlyRootFilesystem=true"
|
||||
--set "$component.containerSecurityContext.capabilities.drop[0]=ALL"
|
||||
--set "$component.containerSecurityContext.seccompProfile.type=RuntimeDefault"
|
||||
)
|
||||
done
|
||||
|
||||
helm template test $CHART_DIR \
|
||||
"${security_context_args[@]}" \
|
||||
--set s3.enabled=true \
|
||||
--set s3.createBuckets[0].name=test \
|
||||
--set sftp.enabled=true \
|
||||
--set admin.enabled=true \
|
||||
--set admin.secret.adminPassword=ci-admin-password \
|
||||
--set worker.enabled=true \
|
||||
--set volume.idx.type=hostPath \
|
||||
--set volume.idx.hostPathPrefix=/tmp \
|
||||
--set cosi.enabled=true \
|
||||
--set global.seaweedfs.tmpDir.sizeLimit=64Mi > /tmp/security-contexts.yaml
|
||||
helm template test $CHART_DIR \
|
||||
"${security_context_args[@]}" \
|
||||
--set allInOne.enabled=true \
|
||||
--set master.enabled=false \
|
||||
--set volume.enabled=false \
|
||||
--set filer.enabled=false \
|
||||
--set global.seaweedfs.tmpDir.sizeLimit=64Mi > /tmp/security-contexts-aio.yaml
|
||||
python3 - /tmp/security-context-defaults.yaml /tmp/security-contexts.yaml /tmp/security-contexts-aio.yaml <<'PYEOF'
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
errors = []
|
||||
workloads = 0
|
||||
containers = 0
|
||||
chart_managed_init_containers = 0
|
||||
components = set()
|
||||
|
||||
def validate_container(workload_name, container):
|
||||
context = container.get("securityContext", {})
|
||||
prefix = f"{workload_name}/{container['name']}"
|
||||
if "enabled" in context:
|
||||
errors.append(f"{prefix}: internal enabled flag leaked into container securityContext")
|
||||
if context.get("privileged") is not False:
|
||||
errors.append(f"{prefix}: privileged is not false")
|
||||
if context.get("allowPrivilegeEscalation") is not False:
|
||||
errors.append(f"{prefix}: allowPrivilegeEscalation is not false")
|
||||
if context.get("readOnlyRootFilesystem") is not True:
|
||||
errors.append(f"{prefix}: readOnlyRootFilesystem is not true")
|
||||
if context.get("capabilities", {}).get("drop") != ["ALL"]:
|
||||
errors.append(f"{prefix}: capabilities.drop is not exactly [ALL]")
|
||||
if context.get("seccompProfile", {}).get("type") != "RuntimeDefault":
|
||||
errors.append(f"{prefix}: seccompProfile is not RuntimeDefault")
|
||||
mounts = {mount["name"]: mount for mount in container.get("volumeMounts", [])}
|
||||
if mounts.get("seaweedfs-tmp", {}).get("mountPath") != "/tmp":
|
||||
errors.append(f"{prefix}: writable temporary volume is not mounted at /tmp")
|
||||
|
||||
with open(sys.argv[1]) as stream:
|
||||
default_documents = [document for document in yaml.safe_load_all(stream) if document]
|
||||
for document in default_documents:
|
||||
if document.get("kind") not in ("Deployment", "StatefulSet", "Job"):
|
||||
continue
|
||||
name = document["metadata"]["name"]
|
||||
pod = document["spec"]["template"]["spec"]
|
||||
if "securityContext" in pod:
|
||||
errors.append(f"{name}: pod securityContext should be absent by default")
|
||||
if any(volume["name"] == "seaweedfs-tmp" for volume in pod.get("volumes", [])):
|
||||
errors.append(f"{name}: writable /tmp volume should be absent by default")
|
||||
for container in pod.get("containers", []):
|
||||
if "securityContext" in container:
|
||||
errors.append(
|
||||
f"{name}/{container['name']}: container securityContext "
|
||||
f"should be absent by default"
|
||||
)
|
||||
if any(
|
||||
mount["name"] == "seaweedfs-tmp"
|
||||
for mount in container.get("volumeMounts", [])
|
||||
):
|
||||
errors.append(
|
||||
f"{name}/{container['name']}: writable /tmp mount "
|
||||
f"should be absent by default"
|
||||
)
|
||||
|
||||
for path in sys.argv[2:]:
|
||||
with open(path) as stream:
|
||||
documents = [document for document in yaml.safe_load_all(stream) if document]
|
||||
for document in documents:
|
||||
if document.get("kind") not in ("Deployment", "StatefulSet", "Job"):
|
||||
continue
|
||||
workloads += 1
|
||||
name = document["metadata"]["name"]
|
||||
pod = document["spec"]["template"]["spec"]
|
||||
volumes = {volume["name"]: volume for volume in pod.get("volumes", [])}
|
||||
temporary = volumes.get("seaweedfs-tmp", {}).get("emptyDir")
|
||||
if temporary is None:
|
||||
errors.append(f"{name}: writable /tmp emptyDir is missing")
|
||||
elif temporary.get("sizeLimit") != "64Mi":
|
||||
errors.append(f"{name}: temporary volume sizeLimit is not 64Mi")
|
||||
component = document["spec"]["template"]["metadata"]["labels"].get("app.kubernetes.io/component")
|
||||
if component:
|
||||
components.add(component)
|
||||
else:
|
||||
errors.append(f"{name}: app.kubernetes.io/component label is missing")
|
||||
pod_context = pod.get("securityContext", {})
|
||||
if "enabled" in pod_context:
|
||||
errors.append(f"{name}: internal enabled flag leaked into pod securityContext")
|
||||
if pod_context.get("seccompProfile", {}).get("type") != "RuntimeDefault":
|
||||
errors.append(f"{name}: pod seccompProfile is not RuntimeDefault")
|
||||
for container in pod.get("containers", []):
|
||||
containers += 1
|
||||
validate_container(name, container)
|
||||
for container in pod.get("initContainers", []):
|
||||
if container["name"] != "seaweedfs-vol-move-idx":
|
||||
continue
|
||||
chart_managed_init_containers += 1
|
||||
validate_container(name, container)
|
||||
|
||||
expected_components = {
|
||||
"master", "volume", "filer", "s3", "sftp", "admin", "worker",
|
||||
"objectstorage-provisioner", "bucket-hook", "seaweedfs-all-in-one",
|
||||
}
|
||||
if components != expected_components:
|
||||
errors.append(
|
||||
f"security context workload coverage is incomplete: "
|
||||
f"expected {sorted(expected_components)}, got {sorted(components)}"
|
||||
)
|
||||
if workloads != 10 or containers != 12:
|
||||
errors.append(
|
||||
f"expected 10 workloads and 12 containers, got "
|
||||
f"{workloads} workloads and {containers} containers"
|
||||
)
|
||||
if chart_managed_init_containers != 1:
|
||||
errors.append(
|
||||
f"expected one chart-managed seaweedfs-vol-move-idx init container, "
|
||||
f"got {chart_managed_init_containers}"
|
||||
)
|
||||
|
||||
if errors:
|
||||
print("\n".join(f"FAIL: {error}" for error in errors), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(f"Validated security contexts on {workloads} workloads and {containers} containers")
|
||||
PYEOF
|
||||
|
||||
# The resize hook depends on lookup finding a live StatefulSet and
|
||||
# therefore cannot render during helm template. Keep static coverage
|
||||
# for both security-context blocks.
|
||||
grep -Fqx ' securityContext: {{- omit .Values.volume.podSecurityContext "enabled" | toYaml | nindent 8 }}' \
|
||||
"$CHART_DIR/templates/volume/volume-resize-hook.yaml"
|
||||
grep -Fqx ' securityContext: {{- omit .Values.volume.containerSecurityContext "enabled" | toYaml | nindent 12 }}' \
|
||||
"$CHART_DIR/templates/volume/volume-resize-hook.yaml"
|
||||
echo "Volume resize hook security contexts are covered"
|
||||
|
||||
echo ""
|
||||
echo "=== Testing long release name: service names match DNS references ==="
|
||||
@@ -1605,6 +1782,78 @@ jobs:
|
||||
- name: Create kind cluster
|
||||
uses: helm/kind-action@v1.15.0
|
||||
|
||||
- name: Verify volume resize hook security contexts
|
||||
run: |
|
||||
set -e
|
||||
CHART_DIR="k8s/charts/seaweedfs"
|
||||
NS="resize-hook-security"
|
||||
kubectl create namespace "$NS"
|
||||
kubectl apply -n "$NS" -f - <<'EOF'
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: data1-resize-seaweedfs-volume-0
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 1Gi
|
||||
EOF
|
||||
|
||||
helm template resize "$CHART_DIR" -n "$NS" --dry-run=server \
|
||||
--set volume.dataDirs[0].name=data1 \
|
||||
--set volume.dataDirs[0].type=persistentVolumeClaim \
|
||||
--set volume.dataDirs[0].size=2Gi \
|
||||
--set volume.podSecurityContext.enabled=true \
|
||||
--set volume.podSecurityContext.seccompProfile.type=RuntimeDefault \
|
||||
--set volume.containerSecurityContext.enabled=true \
|
||||
--set volume.containerSecurityContext.privileged=false \
|
||||
--set volume.containerSecurityContext.allowPrivilegeEscalation=false \
|
||||
--set volume.containerSecurityContext.readOnlyRootFilesystem=true \
|
||||
--set volume.containerSecurityContext.capabilities.drop[0]=ALL \
|
||||
--set volume.containerSecurityContext.seccompProfile.type=RuntimeDefault \
|
||||
--set global.seaweedfs.tmpDir.sizeLimit=64Mi \
|
||||
> /tmp/security-context-resize-hook.yaml
|
||||
|
||||
python3 - /tmp/security-context-resize-hook.yaml <<'PYEOF'
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
with open(sys.argv[1]) as stream:
|
||||
documents = [document for document in yaml.safe_load_all(stream) if document]
|
||||
|
||||
jobs = [
|
||||
document for document in documents
|
||||
if document.get("kind") == "Job"
|
||||
and document["metadata"]["name"].endswith("-volume-resize-hook")
|
||||
]
|
||||
if len(jobs) != 1:
|
||||
raise AssertionError(f"expected one volume resize hook Job, got {len(jobs)}")
|
||||
|
||||
pod = jobs[0]["spec"]["template"]["spec"]
|
||||
assert pod["securityContext"] == {
|
||||
"seccompProfile": {"type": "RuntimeDefault"},
|
||||
}
|
||||
assert len(pod["containers"]) == 1
|
||||
assert pod["containers"][0]["securityContext"] == {
|
||||
"allowPrivilegeEscalation": False,
|
||||
"capabilities": {"drop": ["ALL"]},
|
||||
"privileged": False,
|
||||
"readOnlyRootFilesystem": True,
|
||||
"seccompProfile": {"type": "RuntimeDefault"},
|
||||
}
|
||||
assert pod["containers"][0]["volumeMounts"] == [
|
||||
{"mountPath": "/tmp", "name": "seaweedfs-tmp"},
|
||||
]
|
||||
assert pod["volumes"] == [
|
||||
{"emptyDir": {"sizeLimit": "64Mi"}, "name": "seaweedfs-tmp"},
|
||||
]
|
||||
PYEOF
|
||||
kubectl delete namespace "$NS"
|
||||
echo "Volume resize hook security contexts render correctly"
|
||||
|
||||
- name: Run chart-testing (install)
|
||||
run: |
|
||||
ct install --target-branch ${{ github.event.repository.default_branch }} --all --chart-dirs k8s/charts \
|
||||
|
||||
@@ -139,7 +139,8 @@ jobs:
|
||||
unit-tests:
|
||||
name: Go Unit Tests (Implicit Directory)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
# Leave time for setup and the focused run before the nine-minute suite.
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
@@ -159,5 +160,5 @@ jobs:
|
||||
- name: Run all S3 API tests
|
||||
run: |
|
||||
cd weed/s3api
|
||||
go test -v -timeout 5m
|
||||
go test -v -timeout 9m
|
||||
|
||||
@@ -289,6 +289,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_object_write_check_etag \
|
||||
s3tests/functional/test_s3.py::test_object_write_cache_control \
|
||||
s3tests/functional/test_s3.py::test_object_write_expires \
|
||||
s3tests/functional/test_s3.py::test_object_content_encoding_aws_chunked \
|
||||
s3tests/functional/test_s3.py::test_object_write_read_update_read_delete \
|
||||
s3tests/functional/test_s3.py::test_object_metadata_replaced_on_put \
|
||||
s3tests/functional/test_s3.py::test_object_write_file \
|
||||
@@ -311,6 +312,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_good \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifunmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_checksum_object_attributes \
|
||||
s3tests/functional/test_s3.py::test_bucket_head \
|
||||
s3tests/functional/test_s3.py::test_bucket_head_notexist \
|
||||
s3tests/functional/test_s3.py::test_object_raw_authenticated \
|
||||
@@ -1149,6 +1151,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_object_write_check_etag \
|
||||
s3tests/functional/test_s3.py::test_object_write_cache_control \
|
||||
s3tests/functional/test_s3.py::test_object_write_expires \
|
||||
s3tests/functional/test_s3.py::test_object_content_encoding_aws_chunked \
|
||||
s3tests/functional/test_s3.py::test_object_write_read_update_read_delete \
|
||||
s3tests/functional/test_s3.py::test_object_metadata_replaced_on_put \
|
||||
s3tests/functional/test_s3.py::test_object_write_file \
|
||||
@@ -1171,6 +1174,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_good \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifunmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_checksum_object_attributes \
|
||||
s3tests/functional/test_s3.py::test_bucket_head \
|
||||
s3tests/functional/test_s3.py::test_bucket_head_notexist \
|
||||
s3tests/functional/test_s3.py::test_object_raw_authenticated \
|
||||
|
||||
@@ -14,7 +14,7 @@ require (
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.7.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/dustin/go-humanize v1.1.0
|
||||
github.com/eapache/go-resiliency v1.6.0 // indirect
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
|
||||
github.com/eapache/queue v1.1.0 // indirect
|
||||
@@ -94,7 +94,7 @@ require (
|
||||
golang.org/x/exp v0.0.0-20260709172345-9ea1abe57597
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.58.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
@@ -111,7 +111,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/kms v1.34.0
|
||||
cloud.google.com/go/kms v1.35.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
@@ -154,7 +154,7 @@ require (
|
||||
github.com/tarantool/go-tarantool/v3 v3.0.2
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/twmb/avro v1.8.0
|
||||
github.com/twmb/avro v1.9.0
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.151.1
|
||||
@@ -302,13 +302,13 @@ require (
|
||||
cloud.google.com/go/iam v1.12.0 // indirect
|
||||
cloud.google.com/go/monitoring v1.30.0 // indirect
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.3.194 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 // indirect
|
||||
|
||||
@@ -298,8 +298,8 @@ cloud.google.com/go/kms v1.4.0/go.mod h1:fajBHndQ+6ubNw6Ss2sSd+SWvjL26RNo/dr7uxs
|
||||
cloud.google.com/go/kms v1.5.0/go.mod h1:QJS2YY0eJGBg3mnDfuaCyLauWwBJiHRboYxJ++1xJNg=
|
||||
cloud.google.com/go/kms v1.6.0/go.mod h1:Jjy850yySiasBUDi6KFUwUv2n1+o7QZFyuUJg6OgjA0=
|
||||
cloud.google.com/go/kms v1.9.0/go.mod h1:qb1tPTgfF9RQP8e1wq4cLFErVuTJv7UsSC915J8dh3w=
|
||||
cloud.google.com/go/kms v1.34.0 h1:mxWcXEiyjxwFH5gclulLx+B8Y2OEpKJRZ5FOF78c2XE=
|
||||
cloud.google.com/go/kms v1.34.0/go.mod h1:FbxZWUiihmyjxlaBha84OK5+fmJHPrS6F5/mBFdJk6A=
|
||||
cloud.google.com/go/kms v1.35.0 h1:nJ/ktaqspx1nPM9vIcO0SHbhqCAm8nvAxL1siuVgKm0=
|
||||
cloud.google.com/go/kms v1.35.0/go.mod h1:0++71pIHvJL+GmMa8K4jOWFq7gNOX3jm2PRMSJwTKJw=
|
||||
cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic=
|
||||
cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI=
|
||||
cloud.google.com/go/language v1.7.0/go.mod h1:DJ6dYN/W+SQOjF8e1hLQXMF21AkH2w9wiPzPCJa2MIE=
|
||||
@@ -553,10 +553,10 @@ gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zum
|
||||
git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0/go.mod h1:q0+UTSRvShwUCrR/s5HtyInYphN7Wvxb7snFM3u+SLA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 h1:zvXfGJCWvywnCA814d8ZiVyt+fm9nnTE8xSb99zRyfo=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 h1:u93s+zU2JD62im61Bm5CZIc1ZrOJaIAWEg0WOrMVkEo=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
|
||||
@@ -577,8 +577,8 @@ github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDP
|
||||
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMslb1sZpAokUt+zTVmue0hKSs2C791hhzU=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 h1:Nljr4q1GRA/5vCrMONS+g4u4LRHNgOXVSh3O43J2CnI=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0/go.mod h1:Y33QHnf0FfdVewFFISOGe20mkZbxX4H839o955/PoeI=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d h1:iG9B49Q218F/XxXNRM7k/vWf7MKmLIS8AcJV9cGN4nA=
|
||||
@@ -953,8 +953,8 @@ github.com/dropbox/dropbox-sdk-go-unofficial/v6 v6.4.0/go.mod h1:gDXhl0OElhzYoDs
|
||||
github.com/dsnet/try v0.0.3 h1:ptR59SsrcFUYbT/FhAbKTV6iLkeD6O18qfIWRml2fqI=
|
||||
github.com/dsnet/try v0.0.3/go.mod h1:WBM8tRpUmnXXhY1U6/S8dt6UWdHTQ7y8A5YSkRCkq40=
|
||||
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30=
|
||||
github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho=
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws=
|
||||
@@ -1965,8 +1965,8 @@ github.com/tsuna/gohbase v0.0.0-20201125011725-348991136365/go.mod h1:zj0GJHGvyf
|
||||
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/twmb/avro v1.8.0 h1:UMWLg+nH4P3yad5Om7yFSohYLy2RG1s7BcFFiOvmK9Q=
|
||||
github.com/twmb/avro v1.8.0/go.mod h1:X0fT1dY2xcbV4YuCE4mYro+qljHl4kUF5uA/2z1rgSk=
|
||||
github.com/twmb/avro v1.9.0 h1:JSiqewo3AANj7vlVCQXBsIZTA3LiiBble7Xp8T4lbtA=
|
||||
github.com/twmb/avro v1.9.0/go.mod h1:X0fT1dY2xcbV4YuCE4mYro+qljHl4kUF5uA/2z1rgSk=
|
||||
github.com/twmb/murmur3 v1.1.8 h1:8Yt9taO/WN3l08xErzjeschgZU2QSrwm1kclYq+0aRg=
|
||||
github.com/twmb/murmur3 v1.1.8/go.mod h1:Qq/R7NUyOfr65zD+6Q5IHKsJLwP7exErjN6lyyq3OSQ=
|
||||
github.com/twpayne/go-geom v1.6.1 h1:iLE+Opv0Ihm/ABIcvQFGIiFBXd76oBIar9drAwHFhR4=
|
||||
@@ -2354,8 +2354,8 @@ golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri
|
||||
golang.org/x/oauth2 v0.4.0/go.mod h1:RznEsdpjGAINPTOF0UH/t+xJ75L18YO3Ho6Pyn+uRec=
|
||||
golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I=
|
||||
golang.org/x/oauth2 v0.6.0/go.mod h1:ycmewcwgD4Rpr3eZJLSB4Kyyljb3qDh40vJ8STE5HKw=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
|
||||
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
|
||||
@@ -3,4 +3,4 @@ description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.48"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.48.0
|
||||
version: 4.48.2
|
||||
@@ -570,6 +570,23 @@ Two things worth knowing before you turn this on:
|
||||
|
||||
The DNS selectors default to CoreDNS as kubeadm, kind and the managed offerings from AWS, Google and Azure install it. On OpenShift, override `egress.dnsNamespaceSelector` and `egress.dnsPodSelector` to match `openshift-dns`; see the comment in `values.yaml`.
|
||||
|
||||
## Pod and container security contexts
|
||||
|
||||
Pod and container security contexts are configurable independently for every built-in workload and remain empty by default for backwards compatibility. The examples in `values.yaml` show how to enable a `RuntimeDefault` seccomp profile, disable privilege escalation and privileged mode, drop all Linux capabilities, and use a read-only root filesystem.
|
||||
|
||||
SeaweedFS uses `/tmp` for Unix sockets, temporary uploads, worker task files, and other runtime data. When `readOnlyRootFilesystem` is enabled for a built-in component, the chart mounts a writable `emptyDir` at `/tmp` for its chart-managed containers. Its optional size limit can be configured globally:
|
||||
|
||||
```yaml
|
||||
global:
|
||||
seaweedfs:
|
||||
tmpDir:
|
||||
sizeLimit: 1Gi
|
||||
```
|
||||
|
||||
The chart does not enable `runAsNonRoot` by default because its default `hostPath` storage may be owned by root. To enforce the Kubernetes `restricted` Pod Security Standard, use storage that is writable by a non-root user and configure `runAsNonRoot` or use the OpenShift overrides below.
|
||||
|
||||
Security contexts configured for a component also apply to the chart-managed helper containers for that component. User-provided init containers and sidecars must define their own container security context and writable mounts.
|
||||
|
||||
## OpenShift Support
|
||||
|
||||
SeaweedFS can be deployed on OpenShift or any cluster enforcing the Kubernetes "restricted" Pod Security Standard. By default, OpenShift blocks containers that run as root or use `hostPath` volumes.
|
||||
@@ -578,6 +595,7 @@ To deploy on OpenShift, use the provided `openshift-values.yaml` which overrides
|
||||
1. Use `PersistentVolumeClaims` instead of `hostPath`.
|
||||
2. Enable `runAsNonRoot` and omit hardcoded UIDs to allow OpenShift to assign valid UIDs automatically.
|
||||
3. Apply appropriate `seccompProfile` and drop capabilities.
|
||||
4. Use a read-only root filesystem with writable temporary storage at `/tmp`.
|
||||
|
||||
Usage:
|
||||
```bash
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
# automatically assign a valid UID from the namespace's allocated range.
|
||||
# 3. Dropping all Linux capabilities and setting allowPrivilegeEscalation: false
|
||||
# 4. Enabling RuntimeDefault seccompProfile
|
||||
# 5. Using a read-only root filesystem with writable temporary storage
|
||||
#
|
||||
# Usage:
|
||||
# helm install seaweedfs seaweedfs/seaweedfs \
|
||||
@@ -49,6 +50,7 @@ master:
|
||||
containerSecurityContext:
|
||||
enabled: true
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
runAsNonRoot: true
|
||||
@@ -76,6 +78,7 @@ volume:
|
||||
containerSecurityContext:
|
||||
enabled: true
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
runAsNonRoot: true
|
||||
@@ -101,6 +104,7 @@ filer:
|
||||
containerSecurityContext:
|
||||
enabled: true
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
runAsNonRoot: true
|
||||
@@ -125,6 +129,7 @@ s3:
|
||||
containerSecurityContext:
|
||||
enabled: true
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
runAsNonRoot: true
|
||||
|
||||
@@ -192,6 +192,7 @@ spec:
|
||||
{{ $arg }}{{- if lt $index (sub (len $.Values.admin.extraArgs) 1) }} \{{ end }}
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.admin.containerSecurityContext (tpl (.Values.admin.extraVolumeMounts | default "") .) (tpl (.Values.admin.extraVolumes | default "") .)) | nindent 12 }}
|
||||
{{- if or (eq .Values.admin.data.type "hostPath") (eq .Values.admin.data.type "persistentVolumeClaim") (eq .Values.admin.data.type "emptyDir") (eq .Values.admin.data.type "existingClaim") }}
|
||||
- name: admin-data
|
||||
mountPath: /data
|
||||
@@ -267,6 +268,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.admin.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.admin.containerSecurityContext (tpl (.Values.admin.extraVolumeMounts | default "") .) (tpl (.Values.admin.extraVolumes | default "") .) false) | nindent 8 }}
|
||||
{{- if eq .Values.admin.data.type "hostPath" }}
|
||||
- name: admin-data
|
||||
hostPath:
|
||||
|
||||
@@ -306,6 +306,7 @@ spec:
|
||||
{{- end }}
|
||||
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.allInOne.containerSecurityContext (tpl (.Values.allInOne.extraVolumeMounts | default "") .) (tpl (.Values.allInOne.extraVolumes | default "") .)) | nindent 12 }}
|
||||
- name: data
|
||||
mountPath: /data
|
||||
{{- if and .Values.allInOne.s3.enabled (or .Values.allInOne.s3.enableAuth .Values.s3.enableAuth .Values.filer.s3.enableAuth) }}
|
||||
@@ -433,6 +434,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.allInOne.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.allInOne.containerSecurityContext (tpl (.Values.allInOne.extraVolumeMounts | default "") .) (tpl (.Values.allInOne.extraVolumes | default "") .) false) | nindent 8 }}
|
||||
{{- include "seaweedfs.licenseVolume" . | nindent 8 }}
|
||||
- name: data
|
||||
{{- if eq .Values.allInOne.data.type "hostPath" }}
|
||||
|
||||
@@ -25,6 +25,10 @@ spec:
|
||||
organizations:
|
||||
- "SeaweedFS CA"
|
||||
dnsNames:
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin'
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}'
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc'
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -113,6 +113,7 @@ spec:
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.cosi.containerSecurityContext (tpl (.Values.cosi.extraVolumeMounts | default "") .) (tpl (.Values.cosi.extraVolumes | default "") .)) | nindent 12 }}
|
||||
- mountPath: /var/lib/cosi
|
||||
name: socket
|
||||
{{- if .Values.cosi.enableAuth }}
|
||||
@@ -148,6 +149,9 @@ spec:
|
||||
resources:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- if .Values.cosi.containerSecurityContext.enabled }}
|
||||
securityContext: {{- omit .Values.cosi.containerSecurityContext "enabled" | toYaml | nindent 12 }}
|
||||
{{- end }}
|
||||
- name: seaweedfs-cosi-sidecar
|
||||
image: "{{ .Values.cosi.sidecar.image }}"
|
||||
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
|
||||
@@ -159,6 +163,7 @@ spec:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.cosi.containerSecurityContext "" "") | nindent 12 }}
|
||||
- mountPath: /var/lib/cosi
|
||||
name: socket
|
||||
{{- with .Values.cosi.sidecar.resources }}
|
||||
@@ -172,6 +177,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.cosi.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.cosi.containerSecurityContext (tpl (.Values.cosi.extraVolumeMounts | default "") .) (tpl (.Values.cosi.extraVolumes | default "") .) true) | nindent 8 }}
|
||||
- name: socket
|
||||
emptyDir: {}
|
||||
{{- if .Values.cosi.enableAuth }}
|
||||
|
||||
@@ -229,6 +229,7 @@ spec:
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.filer.containerSecurityContext (tpl (.Values.filer.extraVolumeMounts | default "") .) (tpl (.Values.filer.extraVolumes | default "") .)) | nindent 12 }}
|
||||
{{- if (or (eq .Values.filer.logs.type "hostPath") (eq .Values.filer.logs.type "persistentVolumeClaim") (eq .Values.filer.logs.type "emptyDir")) }}
|
||||
- name: seaweedfs-filer-log-volume
|
||||
mountPath: "/logs/"
|
||||
@@ -337,6 +338,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.filer.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.filer.containerSecurityContext (tpl (.Values.filer.extraVolumeMounts | default "") .) (tpl (.Values.filer.extraVolumes | default "") .) false) | nindent 8 }}
|
||||
{{- if eq .Values.filer.logs.type "hostPath" }}
|
||||
- name: seaweedfs-filer-log-volume
|
||||
hostPath:
|
||||
|
||||
@@ -179,6 +179,7 @@ spec:
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.master.containerSecurityContext (tpl (.Values.master.extraVolumeMounts | default "") .) (tpl (.Values.master.extraVolumes | default "") .)) | nindent 12 }}
|
||||
- name : data-{{ .Release.Namespace }}
|
||||
mountPath: /data
|
||||
{{- if or (eq .Values.master.logs.type "hostPath") (eq .Values.master.logs.type "persistentVolumeClaim") (eq .Values.master.logs.type "emptyDir") }}
|
||||
@@ -258,6 +259,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.master.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.master.containerSecurityContext (tpl (.Values.master.extraVolumeMounts | default "") .) (tpl (.Values.master.extraVolumes | default "") .) false) | nindent 8 }}
|
||||
{{- include "seaweedfs.licenseVolume" . | nindent 8 }}
|
||||
{{- if eq .Values.master.logs.type "hostPath" }}
|
||||
- name: seaweedfs-master-log-volume
|
||||
|
||||
@@ -157,6 +157,7 @@ spec:
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.s3.containerSecurityContext (tpl (.Values.s3.extraVolumeMounts | default "") .) (tpl (.Values.s3.extraVolumes | default "") .)) | nindent 12 }}
|
||||
{{- if or (eq .Values.s3.logs.type "hostPath") (eq .Values.s3.logs.type "emptyDir") }}
|
||||
- name: logs
|
||||
mountPath: "/logs/"
|
||||
@@ -245,6 +246,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.s3.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.s3.containerSecurityContext (tpl (.Values.s3.extraVolumeMounts | default "") .) (tpl (.Values.s3.extraVolumes | default "") .) false) | nindent 8 }}
|
||||
{{- if .Values.s3.enableAuth }}
|
||||
- name: config-users
|
||||
secret:
|
||||
|
||||
@@ -170,6 +170,7 @@ spec:
|
||||
-userStoreFile=/etc/sw/seaweedfs_sftp_config \
|
||||
-filer={{ include "seaweedfs.componentName" (list . "filer-client") }}.{{ .Release.Namespace }}:{{ .Values.filer.port }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.sftp.containerSecurityContext (tpl (.Values.sftp.extraVolumeMounts | default "") .) (tpl (.Values.sftp.extraVolumes | default "") .)) | nindent 12 }}
|
||||
{{- if or (eq .Values.sftp.logs.type "hostPath") (eq .Values.sftp.logs.type "emptyDir") }}
|
||||
- name: logs
|
||||
mountPath: "/logs/"
|
||||
@@ -249,6 +250,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.sftp.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.sftp.containerSecurityContext (tpl (.Values.sftp.extraVolumeMounts | default "") .) (tpl (.Values.sftp.extraVolumes | default "") .) false) | nindent 8 }}
|
||||
{{- if .Values.sftp.enableAuth }}
|
||||
- name: config-users
|
||||
secret:
|
||||
|
||||
@@ -76,6 +76,43 @@ Inject extra environment vars in the format key:value, if populated
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
Writable temporary directory for containers using a read-only root filesystem.
|
||||
Input: list of the root context, the component container security context, the
|
||||
rendered extraVolumeMounts and extraVolumes, and whether the pod has secondary
|
||||
chart-managed containers that mount seaweedfs-tmp. A user-supplied /tmp mount
|
||||
only covers the main container, so the volume is still emitted for secondaries;
|
||||
a user-supplied seaweedfs-tmp volume is reused rather than duplicated.
|
||||
*/}}
|
||||
{{- define "seaweedfs.tmpDirCovered" -}}
|
||||
{{- regexMatch `(?m)^\s*-?\s*mountPath:\s*['"]?/tmp/?['"]?\s*(#.*)?$` (index . 2) -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "seaweedfs.tmpDirVolume" -}}
|
||||
{{- $root := index . 0 -}}
|
||||
{{- $securityContext := index . 1 -}}
|
||||
{{- if and $securityContext.enabled $securityContext.readOnlyRootFilesystem
|
||||
(or (index . 4) (ne (include "seaweedfs.tmpDirCovered" .) "true"))
|
||||
(not (regexMatch `(?m)^\s*-?\s*name:\s*['"]?seaweedfs-tmp['"]?\s*(#.*)?$` (index . 3))) }}
|
||||
- name: seaweedfs-tmp
|
||||
{{- with $root.Values.global.seaweedfs.tmpDir.sizeLimit }}
|
||||
emptyDir:
|
||||
sizeLimit: {{ . | quote }}
|
||||
{{- else }}
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "seaweedfs.tmpDirVolumeMount" -}}
|
||||
{{- $securityContext := index . 1 -}}
|
||||
{{- if and $securityContext.enabled $securityContext.readOnlyRootFilesystem
|
||||
(ne (include "seaweedfs.tmpDirCovered" .) "true") }}
|
||||
- name: seaweedfs-tmp
|
||||
mountPath: /tmp
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{/* Whether the mysql filer store is selected; a flag the chart cannot read counts as selected. */}}
|
||||
{{- define "seaweedfs.filer.mysqlEnabled" -}}
|
||||
{{- $merged := dict -}}
|
||||
@@ -467,8 +504,9 @@ true
|
||||
{{- $pvcName := printf "%s-%s-%s-%d" $dir.name $seaweedfsName $volumeName $e }}
|
||||
{{- $currentPVC := (lookup "v1" "PersistentVolumeClaim" $.Release.Namespace $pvcName) }}
|
||||
{{- if $currentPVC }}
|
||||
{{- $oldSize := include "seaweedfs.resource-quantity" $currentPVC.spec.resources.requests.storage }}
|
||||
{{- $newSize := include "seaweedfs.resource-quantity" $desiredSize }}
|
||||
{{- /* include returns a string such as "6.442450944e+10"; convert back to a number, or gt compares lexically */}}
|
||||
{{- $oldSize := include "seaweedfs.resource-quantity" $currentPVC.spec.resources.requests.storage | float64 }}
|
||||
{{- $newSize := include "seaweedfs.resource-quantity" $desiredSize | float64 }}
|
||||
{{- if gt $newSize $oldSize }}
|
||||
{{- $commands = append $commands (printf "kubectl patch pvc %s-%s-%s-%d -p '{\"spec\":{\"resources\":{\"requests\":{\"storage\":\"%s\"}}}}'" $dir.name $seaweedfsName $volumeName $e $desiredSize) }}
|
||||
{{- end }}
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
{{- $clusterUpper := upper $clusterAlias }}
|
||||
{{- $clusterMasterKey := printf "WEED_CLUSTER_%s_MASTER" $clusterUpper }}
|
||||
{{- $clusterFilerKey := printf "WEED_CLUSTER_%s_FILER" $clusterUpper }}
|
||||
{{- $podSecurityContext := .Values.filer.podSecurityContext }}
|
||||
{{- $containerSecurityContext := .Values.filer.containerSecurityContext }}
|
||||
{{- if .Values.allInOne.enabled }}
|
||||
{{- $podSecurityContext = .Values.allInOne.podSecurityContext }}
|
||||
{{- $containerSecurityContext = .Values.allInOne.containerSecurityContext }}
|
||||
{{- end }}
|
||||
|
||||
{{- /* Check allInOne mode first */}}
|
||||
{{- if .Values.allInOne.enabled }}
|
||||
@@ -71,8 +77,8 @@ spec:
|
||||
app.kubernetes.io/component: bucket-hook
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
{{- if .Values.filer.podSecurityContext.enabled }}
|
||||
securityContext: {{- omit .Values.filer.podSecurityContext "enabled" | toYaml | nindent 8 }}
|
||||
{{- if $podSecurityContext.enabled }}
|
||||
securityContext: {{- omit $podSecurityContext "enabled" | toYaml | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.imagePullSecrets" $ | nindent 6 }}
|
||||
containers:
|
||||
@@ -202,8 +208,9 @@ spec:
|
||||
/usr/bin/weed shell
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if or $enableAuth (include "seaweedfs.securityConfigEnabled" .) }}
|
||||
{{- if or (and $containerSecurityContext.enabled $containerSecurityContext.readOnlyRootFilesystem) $enableAuth (include "seaweedfs.securityConfigEnabled" .) }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . $containerSecurityContext "" "") | nindent 10 }}
|
||||
{{- if $enableAuth }}
|
||||
- name: config-users
|
||||
mountPath: /etc/sw
|
||||
@@ -215,6 +222,14 @@ spec:
|
||||
mountPath: /etc/seaweedfs/security.toml
|
||||
subPath: security.toml
|
||||
{{- end }}
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
- name: ca-cert
|
||||
readOnly: true
|
||||
mountPath: /usr/local/share/ca-certificates/ca/
|
||||
- name: client-cert
|
||||
readOnly: true
|
||||
mountPath: /usr/local/share/ca-certificates/client/
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.master.port }}
|
||||
@@ -229,11 +244,12 @@ spec:
|
||||
resources:
|
||||
{{- toYaml . | nindent 10 }}
|
||||
{{- end }}
|
||||
{{- if .Values.filer.containerSecurityContext.enabled }}
|
||||
securityContext: {{- omit .Values.filer.containerSecurityContext "enabled" | toYaml | nindent 12 }}
|
||||
{{- if $containerSecurityContext.enabled }}
|
||||
securityContext: {{- omit $containerSecurityContext "enabled" | toYaml | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- if or $enableAuth (include "seaweedfs.securityConfigEnabled" .) }}
|
||||
{{- if or (and $containerSecurityContext.enabled $containerSecurityContext.readOnlyRootFilesystem) $enableAuth (include "seaweedfs.securityConfigEnabled" .) }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . $containerSecurityContext "" "" false) | nindent 8 }}
|
||||
{{- if $enableAuth }}
|
||||
- name: config-users
|
||||
secret:
|
||||
@@ -249,5 +265,13 @@ spec:
|
||||
configMap:
|
||||
name: {{ include "seaweedfs.fullname" . }}-security-config
|
||||
{{- end }}
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
- name: ca-cert
|
||||
secret:
|
||||
secretName: {{ include "seaweedfs.fullname" . }}-ca-cert
|
||||
- name: client-cert
|
||||
secret:
|
||||
secretName: {{ include "seaweedfs.fullname" . }}-client-cert
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -32,13 +32,32 @@ spec:
|
||||
spec:
|
||||
serviceAccountName: {{ $seaweedfsName }}-volume-resize-hook
|
||||
restartPolicy: Never
|
||||
{{- if .Values.volume.podSecurityContext.enabled }}
|
||||
securityContext: {{- omit .Values.volume.podSecurityContext "enabled" | toYaml | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: resize
|
||||
image: {{ .Values.volume.resizeHook.image }}
|
||||
{{- if and .Values.volume.containerSecurityContext.enabled .Values.volume.containerSecurityContext.readOnlyRootFilesystem }}
|
||||
env:
|
||||
- name: HOME
|
||||
value: /tmp
|
||||
{{- end }}
|
||||
command: ["sh", "-xec"]
|
||||
args:
|
||||
- |
|
||||
{{ $commands | indent 14 }}
|
||||
{{- if and .Values.volume.containerSecurityContext.enabled .Values.volume.containerSecurityContext.readOnlyRootFilesystem }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.volume.containerSecurityContext "" "") | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- if .Values.volume.containerSecurityContext.enabled }}
|
||||
securityContext: {{- omit .Values.volume.containerSecurityContext "enabled" | toYaml | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- if and .Values.volume.containerSecurityContext.enabled .Values.volume.containerSecurityContext.readOnlyRootFilesystem }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.volume.containerSecurityContext "" "" false) | nindent 8 }}
|
||||
{{- end }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
|
||||
@@ -104,6 +104,7 @@ spec:
|
||||
fi
|
||||
done
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list $ $volume.containerSecurityContext "" "") | nindent 12 }}
|
||||
- name: idx
|
||||
mountPath: /idx
|
||||
{{- range $dir := $volume.dataDirs }}
|
||||
@@ -224,6 +225,7 @@ spec:
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list $ $volume.containerSecurityContext (tpl (printf "{{ $volumeName := \"%s\" }}%s" $volumeName ($volume.extraVolumeMounts | default "")) $) (tpl ($volume.extraVolumes | default "") $)) | nindent 12 }}
|
||||
{{- range $dir := $volume.dataDirs }}
|
||||
{{- if not ( eq $dir.type "custom" ) }}
|
||||
- name: {{ $dir.name }}
|
||||
@@ -306,6 +308,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" (printf "{{ $volumeName := \"%s\" }}%s" $volumeName $volume.sidecars) "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list $ $volume.containerSecurityContext (tpl (printf "{{ $volumeName := \"%s\" }}%s" $volumeName ($volume.extraVolumeMounts | default "")) $) (tpl ($volume.extraVolumes | default "") $) (and $initContainers_exists $volume.idx)) | nindent 8 }}
|
||||
|
||||
{{- range $dir := $volume.dataDirs }}
|
||||
|
||||
|
||||
@@ -144,6 +144,7 @@ spec:
|
||||
{{ $arg }}{{- if lt $index (sub (len $.Values.worker.extraArgs) 1) }} \{{ end }}
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .)) | nindent 12 }}
|
||||
{{- if or (eq .Values.worker.data.type "hostPath") (eq .Values.worker.data.type "emptyDir") (eq .Values.worker.data.type "existingClaim") }}
|
||||
- name: worker-data
|
||||
mountPath: {{ .Values.worker.workingDir }}
|
||||
@@ -262,15 +263,16 @@ spec:
|
||||
--metrics-ip=0.0.0.0 \
|
||||
{{- end }}
|
||||
--max-concurrency={{ .Values.worker.maxExecute }}
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
volumeMounts:
|
||||
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.worker.containerSecurityContext "" "") | nindent 12 }}
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
- name: ca-cert
|
||||
readOnly: true
|
||||
mountPath: /usr/local/share/ca-certificates/ca/
|
||||
- name: worker-cert
|
||||
readOnly: true
|
||||
mountPath: /usr/local/share/ca-certificates/worker/
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.worker.lanceMetricsPort }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.worker.lanceMetricsPort }}
|
||||
@@ -302,6 +304,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.worker.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.tmpDirVolume" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .) (ne (include "seaweedfs.worker.lanceNamespaceUrl" .) "")) | nindent 8 }}
|
||||
{{- if eq .Values.worker.data.type "hostPath" }}
|
||||
- name: worker-data
|
||||
hostPath:
|
||||
|
||||
@@ -25,6 +25,9 @@ global:
|
||||
imagePullPolicy: IfNotPresent
|
||||
restartPolicy: Always
|
||||
loggingLevel: 1
|
||||
# Writable temporary storage used when containers run with a read-only root filesystem.
|
||||
tmpDir:
|
||||
sizeLimit: ""
|
||||
enableSecurity: false
|
||||
masterServer: null
|
||||
# filerWrite: true mounts security.toml on filer + admin without needing
|
||||
@@ -260,6 +263,8 @@ master:
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
|
||||
# Configure security context for Container
|
||||
@@ -268,7 +273,16 @@ master:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
ingress:
|
||||
@@ -560,6 +574,8 @@ volume:
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
|
||||
# Configure security context for Container
|
||||
@@ -568,7 +584,16 @@ volume:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
# used to configure livenessProbe on volume-server containers
|
||||
@@ -845,6 +870,8 @@ filer:
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
|
||||
# Configure security context for Container
|
||||
@@ -853,7 +880,16 @@ filer:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
ingresses:
|
||||
@@ -1127,6 +1163,8 @@ s3:
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
|
||||
# Configure security context for Container
|
||||
@@ -1135,7 +1173,16 @@ s3:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
# You can also use emptyDir storage:
|
||||
@@ -1287,7 +1334,33 @@ sftp:
|
||||
priorityClassName: ""
|
||||
schedulerName: ""
|
||||
serviceAccountName: ""
|
||||
# Configure security context for Pod
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# podSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
# Configure security context for Container
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
logs:
|
||||
@@ -1434,7 +1507,33 @@ admin:
|
||||
priorityClassName: ""
|
||||
schedulerName: ""
|
||||
serviceAccountName: ""
|
||||
# Configure security context for Pod
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# podSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
# Configure security context for Container
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
extraEnvironmentVars: {}
|
||||
@@ -1591,7 +1690,33 @@ worker:
|
||||
priorityClassName: ""
|
||||
schedulerName: ""
|
||||
serviceAccountName: ""
|
||||
# Configure security context for Pod
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# podSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
# Configure security context for Container
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
extraEnvironmentVars: {}
|
||||
@@ -1851,6 +1976,8 @@ allInOne:
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
|
||||
# Configure security context for Container
|
||||
@@ -1859,7 +1986,16 @@ allInOne:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
# Resource management
|
||||
@@ -1898,7 +2034,33 @@ cosi:
|
||||
# should have a secret key called seaweedfs_s3_config with an inline json configure
|
||||
existingConfigSecret: null
|
||||
|
||||
# Configure security context for Pod
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# podSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 3000
|
||||
# fsGroup: 2000
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
podSecurityContext: {}
|
||||
# Configure security context for Container
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
|
||||
# Example:
|
||||
# containerSecurityContext:
|
||||
# enabled: true
|
||||
# runAsUser: 2000
|
||||
# runAsGroup: 3000
|
||||
# runAsNonRoot: true
|
||||
# privileged: false
|
||||
# allowPrivilegeEscalation: false
|
||||
# readOnlyRootFilesystem: true
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
containerSecurityContext: {}
|
||||
|
||||
# used to assign a custom scheduler to cosi pods
|
||||
|
||||
+1046
-1021
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 54 KiB |
@@ -168,6 +168,7 @@ message VacuumVolumeCheckRequest {
|
||||
}
|
||||
message VacuumVolumeCheckResponse {
|
||||
double garbage_ratio = 1;
|
||||
bool disk_space_low = 4; // the volume is read-only solely because its disk is low on space — a cause compaction itself reclaims
|
||||
}
|
||||
|
||||
message VacuumVolumeCompactRequest {
|
||||
|
||||
@@ -371,6 +371,9 @@ async fn run(
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
},
|
||||
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail_notify: tokio::sync::Notify::new(),
|
||||
});
|
||||
|
||||
// Load persisted state from disk if it exists (matches Go's State.Load on startup)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+1027
-464
File diff suppressed because it is too large.
Load diff
@@ -297,7 +297,7 @@ fn apply_master_volume_options(store: &Store, hb_resp: &master_pb::HeartbeatResp
|
||||
volume_opts_changed = true;
|
||||
}
|
||||
|
||||
volume_opts_changed && store.maybe_adjust_volume_max()
|
||||
volume_opts_changed
|
||||
}
|
||||
|
||||
type EcShardDeltaKey = (u32, String, u32, u32);
|
||||
@@ -373,6 +373,22 @@ fn diff_ec_shard_delta_messages(
|
||||
(new_ec_shards, deleted_ec_shards)
|
||||
}
|
||||
|
||||
/// A volume heartbeat carries no shard list, only the expired shards it
|
||||
/// deleted, so that is all it may take out of the delta baseline.
|
||||
fn forget_reported_ec_deletions(
|
||||
last_ec_shards: &mut HashMap<EcShardDeltaKey, master_pb::VolumeEcShardInformationMessage>,
|
||||
heartbeat: &master_pb::Heartbeat,
|
||||
) {
|
||||
last_ec_shards.retain(|(id, collection, disk_id, shard_id), _| {
|
||||
!heartbeat.deleted_ec_shards.iter().any(|deleted| {
|
||||
deleted.id == *id
|
||||
&& deleted.collection == *collection
|
||||
&& deleted.disk_id == *disk_id
|
||||
&& deleted.ec_index_bits & (1u32 << shard_id) != 0
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/// Perform one heartbeat session with a master server.
|
||||
async fn do_heartbeat(
|
||||
config: &HeartbeatConfig,
|
||||
@@ -393,24 +409,22 @@ async fn do_heartbeat(
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel::<master_pb::Heartbeat>(32);
|
||||
|
||||
// This master may know nothing about this server, and has not yet said
|
||||
// whether it understands digests, so start from the whole list.
|
||||
state.store.read().unwrap().volume_report.reset();
|
||||
|
||||
// Keep track of what we sent, to generate delta updates
|
||||
let (initial_hb, initial_volumes) =
|
||||
off_runtime(config, state, collect_heartbeat_with_snapshot).await?;
|
||||
let (initial_hb, initial_volumes) = off_runtime(config, state, |config, state| {
|
||||
// This master may know nothing about this server, and has not yet said
|
||||
// whether it understands digests, so start from the whole list.
|
||||
state.store.read().unwrap().volume_report.reset();
|
||||
collect_heartbeat_with_snapshot(config, state)
|
||||
})
|
||||
.await?;
|
||||
let mut last_volumes: HashMap<u32, VolumeIdentity> = volume_identities(&initial_volumes);
|
||||
let mut last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
};
|
||||
|
||||
// Send initial heartbeats BEFORE calling send_heartbeat to avoid deadlock:
|
||||
// the server won't send response headers until it receives the first message,
|
||||
// but send_heartbeat().await waits for response headers.
|
||||
tx.send(initial_hb).await?;
|
||||
tx.send(collect_ec_heartbeat(config, state)).await?;
|
||||
let (initial_ec_hb, mut last_ec_shards) = ec_tick_pass(config, state).await?;
|
||||
tx.send(initial_ec_hb).await?;
|
||||
|
||||
let stream = tokio_stream::wrappers::ReceiverStream::new(rx);
|
||||
let mut response_stream = client.send_heartbeat(stream).await?.into_inner();
|
||||
@@ -445,10 +459,11 @@ async fn do_heartbeat(
|
||||
// Match Go ordering: DuplicatedUuids first, then volume
|
||||
// options, then leader redirect.
|
||||
if !hb_resp.duplicated_uuids.is_empty() {
|
||||
let duplicate_dirs = {
|
||||
let store = state.store.read().unwrap();
|
||||
duplicate_directories(&store, &hb_resp.duplicated_uuids)
|
||||
};
|
||||
let uuids = hb_resp.duplicated_uuids.clone();
|
||||
let duplicate_dirs = off_runtime(config, state, move |_, state| {
|
||||
duplicate_directories(&state.store.read().unwrap(), &uuids)
|
||||
})
|
||||
.await?;
|
||||
error!(
|
||||
"Master reported duplicate volume directories: {:?}",
|
||||
duplicate_dirs
|
||||
@@ -459,19 +474,14 @@ async fn do_heartbeat(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let changed = {
|
||||
let s = state.store.read().unwrap();
|
||||
apply_master_volume_options(&s, &hb_resp)
|
||||
};
|
||||
if changed {
|
||||
let options_changed =
|
||||
volume_options_pass(config, state, &hb_resp).await?;
|
||||
if options_changed && maybe_adjust_volume_max(config, state).await? {
|
||||
let (adjusted_hb, adjusted_volumes) =
|
||||
off_runtime(config, state, collect_heartbeat_with_snapshot)
|
||||
.await?;
|
||||
last_volumes = volume_identities(&adjusted_volumes);
|
||||
last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
};
|
||||
forget_reported_ec_deletions(&mut last_ec_shards, &adjusted_hb);
|
||||
if tx.send(adjusted_hb).await.is_err() {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -496,28 +506,19 @@ async fn do_heartbeat(
|
||||
}
|
||||
|
||||
_ = volume_tick.tick() => {
|
||||
{
|
||||
let s = state.store.read().unwrap();
|
||||
s.maybe_adjust_volume_max();
|
||||
}
|
||||
maybe_adjust_volume_max(config, state).await?;
|
||||
let (current_hb, current_volumes) =
|
||||
off_runtime(config, state, collect_heartbeat_with_snapshot).await?;
|
||||
last_volumes = volume_identities(¤t_volumes);
|
||||
last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
};
|
||||
forget_reported_ec_deletions(&mut last_ec_shards, ¤t_hb);
|
||||
if tx.send(current_hb).await.is_err() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
_ = ec_tick.tick() => {
|
||||
let current_ec_hb = collect_ec_heartbeat(config, state);
|
||||
last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
};
|
||||
let (current_ec_hb, current_ec_shards) = ec_tick_pass(config, state).await?;
|
||||
last_ec_shards = current_ec_shards;
|
||||
if tx.send(current_ec_hb).await.is_err() {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -530,12 +531,8 @@ async fn do_heartbeat(
|
||||
info!("Heartbeat stopping");
|
||||
return Ok(None);
|
||||
}
|
||||
let held_volumes = off_runtime(config, state, collect_volume_snapshot).await?;
|
||||
let (held_volumes, current_ec_shards) = notify_pass(config, state).await?;
|
||||
let current_volumes = volume_identities(&held_volumes);
|
||||
let current_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
};
|
||||
|
||||
let mut new_vols = Vec::new();
|
||||
let mut del_vols = Vec::new();
|
||||
@@ -624,30 +621,41 @@ async fn send_deregister_heartbeat(
|
||||
state: &Arc<VolumeServerState>,
|
||||
tx: &tokio::sync::mpsc::Sender<master_pb::Heartbeat>,
|
||||
) {
|
||||
let empty = {
|
||||
let store = state.store.read().unwrap();
|
||||
// Deregister: no effective max computed, fall back to configured max.
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(&store, &[]);
|
||||
master_pb::Heartbeat {
|
||||
id: store.id.clone(),
|
||||
ip: config.ip.clone(),
|
||||
port: config.port as u32,
|
||||
public_url: config.public_url.clone(),
|
||||
max_file_key: 0,
|
||||
data_center: config.data_center.clone(),
|
||||
rack: config.rack.clone(),
|
||||
has_no_volumes: true,
|
||||
has_no_ec_shards: true,
|
||||
grpc_port: config.grpc_port as u32,
|
||||
location_uuids,
|
||||
disk_tags,
|
||||
..Default::default()
|
||||
let empty = match off_runtime(config, state, deregister_heartbeat).await {
|
||||
Ok(empty) => empty,
|
||||
Err(e) => {
|
||||
warn!("Deregistration heartbeat not built: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = tx.send(empty).await;
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
|
||||
fn deregister_heartbeat(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> master_pb::Heartbeat {
|
||||
let store = state.store.read().unwrap();
|
||||
// Deregister: no effective max computed, fall back to configured max.
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(&store, &[]);
|
||||
master_pb::Heartbeat {
|
||||
id: store.id.clone(),
|
||||
ip: config.ip.clone(),
|
||||
port: config.port as u32,
|
||||
public_url: config.public_url.clone(),
|
||||
max_file_key: 0,
|
||||
data_center: config.data_center.clone(),
|
||||
rack: config.rack.clone(),
|
||||
has_no_volumes: true,
|
||||
has_no_ec_shards: true,
|
||||
grpc_port: config.grpc_port as u32,
|
||||
location_uuids,
|
||||
disk_tags,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_metrics_push_settings(
|
||||
state: &VolumeServerState,
|
||||
address: &str,
|
||||
@@ -786,16 +794,88 @@ fn volume_identities(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs a store pass on the blocking pool: it stats every volume's files.
|
||||
/// Runs a store pass on the blocking pool, so waiting for the store lock
|
||||
/// parks no runtime worker.
|
||||
async fn off_runtime<T: Send + 'static>(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
pass: fn(&HeartbeatConfig, &Arc<VolumeServerState>) -> T,
|
||||
pass: impl FnOnce(&HeartbeatConfig, &Arc<VolumeServerState>) -> T + Send + 'static,
|
||||
) -> Result<T, tokio::task::JoinError> {
|
||||
let (config, state) = (config.clone(), state.clone());
|
||||
tokio::task::spawn_blocking(move || pass(&config, &state)).await
|
||||
}
|
||||
|
||||
/// Applies the master's volume options; whether they changed.
|
||||
async fn volume_options_pass(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
hb_resp: &master_pb::HeartbeatResponse,
|
||||
) -> Result<bool, tokio::task::JoinError> {
|
||||
let hb_resp = hb_resp.clone();
|
||||
off_runtime(config, state, move |_, state| {
|
||||
apply_master_volume_options(&state.store.read().unwrap(), &hb_resp)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The held volumes and EC shards a state notification is diffed from.
|
||||
async fn notify_pass(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> Result<
|
||||
(
|
||||
Vec<master_pb::VolumeInformationMessage>,
|
||||
HashMap<EcShardDeltaKey, master_pb::VolumeEcShardInformationMessage>,
|
||||
),
|
||||
tokio::task::JoinError,
|
||||
> {
|
||||
off_runtime(config, state, |config, state| {
|
||||
let volumes = collect_volume_snapshot(config, state);
|
||||
#[cfg(test)]
|
||||
{
|
||||
let store_id = state.store.read().unwrap().id.clone();
|
||||
read_phase_hook::park(read_phase_hook::Point::BeforeNotifyEcRead, &store_id);
|
||||
}
|
||||
let shards = collect_ec_shard_delta_messages(&state.store.read().unwrap());
|
||||
(volumes, shards)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Go's MaybeAdjustVolumeMax: statvfs on every auto-sized disk, a stat per
|
||||
/// writable volume.
|
||||
async fn maybe_adjust_volume_max(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> Result<bool, tokio::task::JoinError> {
|
||||
off_runtime(config, state, |_, state| {
|
||||
state.store.read().unwrap().maybe_adjust_volume_max()
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The EC heartbeat and the shard list later deltas are diffed against,
|
||||
/// under one guard so no mount lands between them unreported.
|
||||
async fn ec_tick_pass(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> Result<
|
||||
(
|
||||
master_pb::Heartbeat,
|
||||
HashMap<EcShardDeltaKey, master_pb::VolumeEcShardInformationMessage>,
|
||||
),
|
||||
tokio::task::JoinError,
|
||||
> {
|
||||
off_runtime(config, state, |config, state| {
|
||||
let store = state.store.read().unwrap();
|
||||
(
|
||||
collect_ec_heartbeat(config, &store),
|
||||
collect_ec_shard_delta_messages(&store),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Collect volume information into a Heartbeat message.
|
||||
fn collect_heartbeat_with_snapshot(
|
||||
config: &HeartbeatConfig,
|
||||
@@ -906,6 +986,8 @@ mod read_phase_hook {
|
||||
BeforeVolumePass,
|
||||
/// Inside the volume pass, holding the store read lock.
|
||||
VolumePass,
|
||||
/// Between the notify branch's volume snapshot and its EC read.
|
||||
BeforeNotifyEcRead,
|
||||
}
|
||||
|
||||
type Park = (Point, String, Sender<()>, Receiver<()>);
|
||||
@@ -1330,12 +1412,8 @@ fn collect_live_ec_shards(
|
||||
}
|
||||
|
||||
/// Collect EC shard information into a Heartbeat message.
|
||||
fn collect_ec_heartbeat(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> master_pb::Heartbeat {
|
||||
let store = state.store.read().unwrap();
|
||||
let ec_shards = collect_live_ec_shards(&store, true);
|
||||
fn collect_ec_heartbeat(config: &HeartbeatConfig, store: &Store) -> master_pb::Heartbeat {
|
||||
let ec_shards = collect_live_ec_shards(store, true);
|
||||
|
||||
let has_no = ec_shards.is_empty();
|
||||
master_pb::Heartbeat {
|
||||
@@ -1430,6 +1508,9 @@ mod tests {
|
||||
security_file: String::new(),
|
||||
cli_white_list: vec![],
|
||||
state_file_path: String::new(),
|
||||
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail_notify: tokio::sync::Notify::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1984,7 +2065,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let state = test_state_with_store(store);
|
||||
let heartbeat = collect_ec_heartbeat(&test_config(), &state);
|
||||
let heartbeat = collect_ec_heartbeat(&test_config(), &state.store.read().unwrap());
|
||||
|
||||
assert_eq!(heartbeat.ec_shards.len(), 1);
|
||||
assert!(!heartbeat.has_no_ec_shards);
|
||||
@@ -2177,6 +2258,225 @@ mod tests {
|
||||
assert_eq!(volumes.len(), 2);
|
||||
}
|
||||
|
||||
/// Holds the store write lock on another thread until `release` is
|
||||
/// dropped, or for 3s so a parked runtime fails the test instead of
|
||||
/// hanging it. The flag turns true just before the lock is let go.
|
||||
fn hold_store_write_lock(
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> (
|
||||
std::sync::mpsc::Sender<()>,
|
||||
Arc<std::sync::atomic::AtomicBool>,
|
||||
std::thread::JoinHandle<()>,
|
||||
) {
|
||||
let (held_tx, held_rx) = std::sync::mpsc::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
|
||||
let released = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let writer = {
|
||||
let (state, released) = (state.clone(), released.clone());
|
||||
std::thread::spawn(move || {
|
||||
let guard = state.store.write().unwrap();
|
||||
held_tx.send(()).unwrap();
|
||||
let _ = release_rx.recv_timeout(Duration::from_secs(3));
|
||||
released.store(true, Ordering::SeqCst);
|
||||
drop(guard);
|
||||
})
|
||||
};
|
||||
held_rx.recv().unwrap();
|
||||
(release_tx, released, writer)
|
||||
}
|
||||
|
||||
// The heartbeat task shares a worker with other tasks; on this
|
||||
// single-threaded runtime, a pass that waits for the store on the worker
|
||||
// stops everything else until the writer lets go.
|
||||
#[tokio::test]
|
||||
async fn test_ec_tick_pass_waits_for_the_store_off_the_runtime() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
let mut store = reporting_store(dir, 0);
|
||||
std::fs::write(format!("{}/ec_tick_off_runtime_41.ec00", dir), b"shard").unwrap();
|
||||
std::fs::write(format!("{}/ec_tick_off_runtime_41.ecx", dir), [0u8; 16]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(VolumeId(41), "ec_tick_off_runtime", &[0], "")
|
||||
.unwrap();
|
||||
let state = test_state_with_store(store);
|
||||
|
||||
let (release, released, writer) = hold_store_write_lock(&state);
|
||||
let pass = {
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move { ec_tick_pass(&test_config(), &state).await })
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
let ran_while_held = !released.load(Ordering::SeqCst);
|
||||
drop(release);
|
||||
writer.join().unwrap();
|
||||
let (heartbeat, shards) = pass.await.unwrap().unwrap();
|
||||
|
||||
assert!(
|
||||
ran_while_held,
|
||||
"the EC pass parked the runtime on the store lock"
|
||||
);
|
||||
assert_eq!(heartbeat.ec_shards.len(), 1);
|
||||
assert_eq!(shards.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_volume_max_adjustment_waits_for_the_store_off_the_runtime() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 1);
|
||||
// Auto-sized, so the adjustment stats the disk and the volume.
|
||||
store.locations[0].original_max_volume_count = 0;
|
||||
store.locations[0]
|
||||
.max_volume_count
|
||||
.store(0, Ordering::Relaxed);
|
||||
store
|
||||
.volume_size_limit
|
||||
.store(1024 * 1024, Ordering::Relaxed);
|
||||
let state = test_state_with_store(store);
|
||||
|
||||
let (release, released, writer) = hold_store_write_lock(&state);
|
||||
let adjust = {
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move { maybe_adjust_volume_max(&test_config(), &state).await })
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
let ran_while_held = !released.load(Ordering::SeqCst);
|
||||
drop(release);
|
||||
writer.join().unwrap();
|
||||
let changed = adjust.await.unwrap().unwrap();
|
||||
|
||||
assert!(
|
||||
ran_while_held,
|
||||
"the adjustment parked the runtime on the store lock"
|
||||
);
|
||||
assert!(changed);
|
||||
assert!(
|
||||
state.store.read().unwrap().locations[0]
|
||||
.max_volume_count
|
||||
.load(Ordering::Relaxed)
|
||||
>= 1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_volume_options_wait_for_the_store_off_the_runtime() {
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
state
|
||||
.store
|
||||
.read()
|
||||
.unwrap()
|
||||
.volume_size_limit
|
||||
.store(1024, Ordering::Relaxed);
|
||||
let hb_resp = master_pb::HeartbeatResponse {
|
||||
volume_size_limit: 2048,
|
||||
preallocate: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (release, released, writer) = hold_store_write_lock(&state);
|
||||
let apply = {
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move { volume_options_pass(&test_config(), &state, &hb_resp).await })
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
let ran_while_held = !released.load(Ordering::SeqCst);
|
||||
drop(release);
|
||||
writer.join().unwrap();
|
||||
let changed = apply.await.unwrap().unwrap();
|
||||
|
||||
assert!(
|
||||
ran_while_held,
|
||||
"applying volume options parked the runtime on the store lock"
|
||||
);
|
||||
assert!(changed);
|
||||
let store = state.store.read().unwrap();
|
||||
assert!(store.get_preallocate());
|
||||
assert_eq!(store.volume_size_limit.load(Ordering::Relaxed), 2048);
|
||||
}
|
||||
|
||||
// The writer arrives between the volume snapshot and the EC read.
|
||||
#[tokio::test]
|
||||
async fn test_state_notification_waits_for_the_store_off_the_runtime() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
let mut store = reporting_store(dir, 1);
|
||||
store.id = "notify-off-runtime".to_string();
|
||||
let state = test_state_with_store(store);
|
||||
mount_test_ec_shard(&state, dir, "notify_off_runtime", 42);
|
||||
|
||||
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
|
||||
let (resume_tx, resume_rx) = std::sync::mpsc::channel::<()>();
|
||||
read_phase_hook::arm(
|
||||
read_phase_hook::Point::BeforeNotifyEcRead,
|
||||
"notify-off-runtime",
|
||||
entered_tx,
|
||||
resume_rx,
|
||||
);
|
||||
let (held_tx, held_rx) = tokio::sync::oneshot::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
|
||||
let released = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let writer = {
|
||||
let (state, released) = (state.clone(), released.clone());
|
||||
std::thread::spawn(move || {
|
||||
entered_rx.blocking_recv().unwrap();
|
||||
let guard = state.store.write().unwrap();
|
||||
drop(resume_tx);
|
||||
held_tx.send(()).unwrap();
|
||||
let _ = release_rx.recv_timeout(Duration::from_secs(3));
|
||||
released.store(true, Ordering::SeqCst);
|
||||
drop(guard);
|
||||
})
|
||||
};
|
||||
let pass = {
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move { notify_pass(&test_config(), &state).await })
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(10), held_rx)
|
||||
.await
|
||||
.expect("the notify pass never reached its EC read")
|
||||
.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
let ran_while_held = !released.load(Ordering::SeqCst);
|
||||
drop(release_tx);
|
||||
writer.join().unwrap();
|
||||
let (volumes, shards) = pass.await.unwrap().unwrap();
|
||||
|
||||
assert!(
|
||||
ran_while_held,
|
||||
"the notify pass parked the runtime on the store lock"
|
||||
);
|
||||
assert_eq!(volumes.len(), 1);
|
||||
assert_eq!(shards.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_deregister_heartbeat_waits_for_the_store_off_the_runtime() {
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store.id = "deregister-off-runtime".to_string();
|
||||
let state = test_state_with_store(store);
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
|
||||
|
||||
let (release, released, writer) = hold_store_write_lock(&state);
|
||||
let deregister = {
|
||||
let state = state.clone();
|
||||
tokio::spawn(
|
||||
async move { send_deregister_heartbeat(&test_config(), &state, &tx).await },
|
||||
)
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
let ran_while_held = !released.load(Ordering::SeqCst);
|
||||
drop(release);
|
||||
writer.join().unwrap();
|
||||
deregister.await.unwrap();
|
||||
let heartbeat = rx.recv().await.unwrap();
|
||||
|
||||
assert!(
|
||||
ran_while_held,
|
||||
"the deregistration heartbeat parked the runtime on the store lock"
|
||||
);
|
||||
assert_eq!(heartbeat.id, "deregister-off-runtime");
|
||||
assert!(heartbeat.has_no_volumes && heartbeat.has_no_ec_shards);
|
||||
}
|
||||
|
||||
// What the read pass decided on can go stale before the write lock is
|
||||
// taken: each action must re-check its target, not act on whatever now
|
||||
// holds the id.
|
||||
@@ -2321,6 +2621,96 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn mount_test_ec_shard(state: &VolumeServerState, dir: &str, collection: &str, id: u32) {
|
||||
std::fs::write(format!("{}/{}_{}.ec00", dir, collection, id), b"shard").unwrap();
|
||||
std::fs::write(format!("{}/{}_{}.ecx", dir, collection, id), [0u8; 16]).unwrap();
|
||||
state.store.write().unwrap().locations[0]
|
||||
.mount_ec_shards(VolumeId(id), collection, &[0], "")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// One pass of the loop's volume tick, then of its notify branch: the
|
||||
/// EC delta the notify branch would send.
|
||||
fn ec_delta_after_volume_tick(
|
||||
state: &Arc<VolumeServerState>,
|
||||
last_ec_shards: &mut HashMap<EcShardDeltaKey, master_pb::VolumeEcShardInformationMessage>,
|
||||
) -> (
|
||||
master_pb::Heartbeat,
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
) {
|
||||
let (heartbeat, _) = collect_heartbeat_with_snapshot(&test_config(), state);
|
||||
forget_reported_ec_deletions(last_ec_shards, &heartbeat);
|
||||
let current = collect_ec_shard_delta_messages(&state.store.read().unwrap());
|
||||
let (new_ec_shards, deleted_ec_shards) =
|
||||
diff_ec_shard_delta_messages(last_ec_shards, ¤t);
|
||||
(heartbeat, new_ec_shards, deleted_ec_shards)
|
||||
}
|
||||
|
||||
// A volume heartbeat carries no shard list, so a mount or unmount it
|
||||
// collects past must still go out as the notify branch's delta.
|
||||
#[test]
|
||||
fn test_ec_shard_change_before_a_volume_heartbeat_still_goes_out_as_a_delta() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
let state = test_state_with_store(reporting_store(dir, 1));
|
||||
mount_test_ec_shard(&state, dir, "ec_delta_kept", 91);
|
||||
mount_test_ec_shard(&state, dir, "ec_delta_unmounted", 92);
|
||||
let mut last_ec_shards = collect_ec_shard_delta_messages(&state.store.read().unwrap());
|
||||
|
||||
mount_test_ec_shard(&state, dir, "ec_delta_mounted", 93);
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.unmount_ec_shards(VolumeId(92), &[0]);
|
||||
let (heartbeat, new_ec_shards, deleted_ec_shards) =
|
||||
ec_delta_after_volume_tick(&state, &mut last_ec_shards);
|
||||
|
||||
assert!(heartbeat.ec_shards.is_empty() && !heartbeat.has_no_ec_shards);
|
||||
assert_eq!(
|
||||
new_ec_shards.iter().map(|s| s.id).collect::<Vec<_>>(),
|
||||
vec![93],
|
||||
"a mount collected past by the volume heartbeat was never sent"
|
||||
);
|
||||
assert_eq!(
|
||||
deleted_ec_shards.iter().map(|s| s.id).collect::<Vec<_>>(),
|
||||
vec![92],
|
||||
"an unmount collected past by the volume heartbeat was never sent"
|
||||
);
|
||||
}
|
||||
|
||||
// The volume heartbeat already told the master about the expired EC
|
||||
// volume it destroyed; the next delta must not repeat it.
|
||||
#[test]
|
||||
fn test_ec_volume_expired_by_a_volume_heartbeat_is_not_deleted_again() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
let state = test_state_with_store(reporting_store(dir, 0));
|
||||
mount_test_ec_shard(&state, dir, "ec_delta_kept", 94);
|
||||
mount_test_ec_shard(&state, dir, "ec_delta_expired", 95);
|
||||
let mut last_ec_shards = collect_ec_shard_delta_messages(&state.store.read().unwrap());
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.find_ec_volume_mut(VolumeId(95))
|
||||
.unwrap()
|
||||
.expire_at_sec = 1;
|
||||
|
||||
let (heartbeat, new_ec_shards, deleted_ec_shards) =
|
||||
ec_delta_after_volume_tick(&state, &mut last_ec_shards);
|
||||
|
||||
assert_eq!(heartbeat.deleted_ec_shards.len(), 1);
|
||||
assert_eq!(heartbeat.deleted_ec_shards[0].id, 95);
|
||||
assert!(new_ec_shards.is_empty());
|
||||
assert!(
|
||||
deleted_ec_shards.is_empty(),
|
||||
"an expired EC volume was reported deleted twice"
|
||||
);
|
||||
assert_eq!(last_ec_shards.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expired_ec_volume_gone_before_removal_is_not_reported_deleted() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
@@ -2532,7 +2922,7 @@ mod tests {
|
||||
|
||||
assert!(store.get_preallocate());
|
||||
assert_eq!(store.volume_size_limit.load(Ordering::Relaxed), 2048);
|
||||
assert!(!changed);
|
||||
assert!(changed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,7 +27,9 @@ impl From<VolumeError> for Status {
|
||||
VolumeError::NotFound
|
||||
| VolumeError::VolumeNotFound(_)
|
||||
| VolumeError::Tier(TierError::NotFound(_)) => Status::not_found(message),
|
||||
VolumeError::ReadOnly | VolumeError::NotEmpty => Status::failed_precondition(message),
|
||||
VolumeError::ReadOnly(_) | VolumeError::NotEmpty => {
|
||||
Status::failed_precondition(message)
|
||||
}
|
||||
VolumeError::InsufficientSpace { .. } => Status::resource_exhausted(message),
|
||||
VolumeError::AlreadyExists => Status::already_exists(message),
|
||||
_ => Status::internal(message),
|
||||
@@ -69,7 +71,14 @@ mod tests {
|
||||
Code::NotFound
|
||||
);
|
||||
assert_eq!(code(VolumeError::NotFound), Code::NotFound);
|
||||
assert_eq!(code(VolumeError::ReadOnly), Code::FailedPrecondition);
|
||||
assert_eq!(
|
||||
code(VolumeError::ReadOnly(VolumeId(7))),
|
||||
Code::FailedPrecondition
|
||||
);
|
||||
assert_eq!(
|
||||
VolumeError::ReadOnly(VolumeId(7)).to_string(),
|
||||
"volume 7 is read only"
|
||||
);
|
||||
assert_eq!(
|
||||
code(VolumeError::InsufficientSpace {
|
||||
vid: VolumeId(7),
|
||||
|
||||
@@ -95,20 +95,41 @@ struct Snapshot {
|
||||
encode_ts_ns: i64,
|
||||
}
|
||||
|
||||
/// Top-level entry point. Returns `Ok(None)` for "not found" (matches
|
||||
/// Go's `ReadEcShardNeedle`); errors propagate as `io::Error`.
|
||||
/// Why a distributed EC read has no needle to return.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EcMiss {
|
||||
NotFound,
|
||||
/// Tombstoned in the local `.ecx`/`.ecj`, or reported deleted by a peer.
|
||||
Deleted,
|
||||
VolumeNotFound,
|
||||
}
|
||||
|
||||
/// Top-level entry point. Returns `Ok(None)` for any miss — absent,
|
||||
/// deleted, or volume gone; errors propagate as `io::Error`.
|
||||
pub async fn read_ec_shard_needle_distributed(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) -> io::Result<Option<Needle>> {
|
||||
Ok(read_ec_shard_needle_or_miss(state, vid, needle_id)
|
||||
.await?
|
||||
.ok())
|
||||
}
|
||||
|
||||
/// Like `read_ec_shard_needle_distributed`, but says why there is no needle,
|
||||
/// as Go's `ReadEcShardNeedle` tells `ErrorDeleted` from not-found.
|
||||
pub async fn read_ec_shard_needle_or_miss(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) -> io::Result<Result<Needle, EcMiss>> {
|
||||
// Phase A — under the Store read lock, locate the needle, compute
|
||||
// intervals, and read any locally-mounted shard intervals. We must
|
||||
// not `.await` while holding this guard (std::sync::RwLockReadGuard
|
||||
// is !Send).
|
||||
let mut snapshot = match snapshot_under_lock(state, vid, needle_id)? {
|
||||
Some(s) => s,
|
||||
None => return Ok(None),
|
||||
Ok(s) => s,
|
||||
Err(miss) => return Ok(Err(miss)),
|
||||
};
|
||||
|
||||
// Phase B — refresh the shard_locations cache from the master if
|
||||
@@ -210,17 +231,11 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
let mut assembled: Vec<Vec<u8>> = Vec::with_capacity(fetched.len());
|
||||
for res in fetched {
|
||||
let (buf, is_deleted) = res?;
|
||||
// A peer reports the needle deleted (a cross-server window where the
|
||||
// local index still shows it live): treat as not-found rather than
|
||||
// serving zeros, mirroring Go's ErrorDeleted.
|
||||
if is_deleted {
|
||||
return Ok(None);
|
||||
}
|
||||
assembled.push(buf);
|
||||
}
|
||||
// A peer reports the needle deleted (a cross-server window where the
|
||||
// local index still shows it live): answer deleted rather than serving zeros.
|
||||
let Some(assembled) = gather_intervals(fetched)? else {
|
||||
return Ok(Err(EcMiss::Deleted));
|
||||
};
|
||||
|
||||
// Phase D — assemble and parse the Needle. Mirrors the tail of
|
||||
// `EcVolume::read_ec_shard_needle`.
|
||||
@@ -252,7 +267,20 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
snapshot.version,
|
||||
)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}", e)))?;
|
||||
Ok(Some(n))
|
||||
Ok(Ok(n))
|
||||
}
|
||||
|
||||
/// `None` when any holder reported the needle deleted. That outranks another
|
||||
/// interval's error: deletes are never invented, so the needle is gone either way.
|
||||
fn gather_intervals(fetched: Vec<io::Result<(Vec<u8>, bool)>>) -> io::Result<Option<Vec<Vec<u8>>>> {
|
||||
if fetched.iter().any(|r| matches!(r, Ok((_, true)))) {
|
||||
return Ok(None);
|
||||
}
|
||||
fetched
|
||||
.into_iter()
|
||||
.map(|r| r.map(|(buf, _)| buf))
|
||||
.collect::<io::Result<_>>()
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// What one EC delete RPC carries — `VolumeEcBlobDeleteRequest` minus tonic.
|
||||
@@ -391,13 +419,24 @@ async fn delete_on_ec_shard_holders(
|
||||
|
||||
let mut last_err = None;
|
||||
if local_shards.contains(&shard_id) {
|
||||
match journal_delete_local(state, target.vid, target.needle_id) {
|
||||
Ok(()) => return Ok(true),
|
||||
// Nothing was committed — the volume unmounted or remounted
|
||||
// without the needle — so it is safe to fall back to other
|
||||
// shard holders, unlike an RPC failure which may have landed.
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(e) => last_err = Some(e),
|
||||
// A decode in its publishing tail must not miss this delete. The
|
||||
// tail membership is verified again under the store write lock
|
||||
// inside journal_delete_local — WouldBlock means the decode claimed
|
||||
// it in the gap after this wait — so wait and retry.
|
||||
loop {
|
||||
crate::server::grpc_server::wait_ec_decode_tail(state, target.vid).await;
|
||||
match journal_delete_local(state, target.vid, target.needle_id) {
|
||||
Ok(()) => return Ok(true),
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
|
||||
// Nothing was committed — the volume unmounted or remounted
|
||||
// without the needle — so it is safe to fall back to other
|
||||
// shard holders, unlike an RPC failure which may have landed.
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(e) => {
|
||||
last_err = Some(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(addrs) = addrs {
|
||||
@@ -459,6 +498,15 @@ fn journal_delete_local(
|
||||
needle_id: NeedleId,
|
||||
) -> io::Result<()> {
|
||||
let mut store = state.store.write().unwrap();
|
||||
// Membership is read under the write lock: a decode can claim the
|
||||
// publishing tail while this call waited for the decoder's read lock,
|
||||
// so a check taken earlier would be stale by commit time.
|
||||
if crate::server::grpc_server::ec_decode_tail_contains(state, vid) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
format!("ec volume {} is in decode publishing tail", vid.0),
|
||||
));
|
||||
}
|
||||
let ecv = store.find_ec_volume_mut(vid).ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
@@ -864,11 +912,10 @@ fn snapshot_under_lock(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) -> io::Result<Option<Snapshot>> {
|
||||
) -> io::Result<Result<Snapshot, EcMiss>> {
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = match store.find_ec_volume(vid) {
|
||||
Some(v) => v,
|
||||
None => return Ok(None),
|
||||
let Some(ecv) = store.find_ec_volume(vid) else {
|
||||
return Ok(Err(EcMiss::VolumeNotFound));
|
||||
};
|
||||
|
||||
// Reuse EcVolume::locate_needle for offset/size resolution AND
|
||||
@@ -876,11 +923,17 @@ fn snapshot_under_lock(
|
||||
// local-only read path uses, so we stay byte-identical on the
|
||||
// shard-size + interval boundaries. locate_needle applies the runtime
|
||||
// delete mask, which is correct for serving reads.
|
||||
let (offset, size, intervals) = match ecv.locate_needle(needle_id)? {
|
||||
Some(v) => v,
|
||||
None => return Ok(None),
|
||||
let Some((offset, size, intervals)) = ecv.locate_needle(needle_id)? else {
|
||||
// locate_needle folds a tombstone into not-found.
|
||||
let deleted =
|
||||
matches!(ecv.find_needle_from_ecx(needle_id)?, Some((_, s)) if s.is_deleted());
|
||||
return Ok(Err(if deleted {
|
||||
EcMiss::Deleted
|
||||
} else {
|
||||
EcMiss::NotFound
|
||||
}));
|
||||
};
|
||||
build_snapshot(ecv, offset, size, &intervals).map(Some)
|
||||
build_snapshot(ecv, offset, size, &intervals).map(Ok)
|
||||
}
|
||||
|
||||
/// Like `snapshot_under_lock`, but locates intervals from the RAW .ecx
|
||||
@@ -1720,7 +1773,7 @@ async fn fetch_ec_index_from_one_peer(
|
||||
.await
|
||||
.map_err(|e| io::Error::other(format!("copy .ecx: {}", e)))?
|
||||
.into_inner();
|
||||
drain_copy_stream(stream, ecx_path, false).await?;
|
||||
drain_copy_stream(stream, ecx_path).await?;
|
||||
|
||||
let meta =
|
||||
fs::metadata(ecx_path).map_err(|e| io::Error::other(format!("stat copied .ecx: {}", e)))?;
|
||||
@@ -1733,15 +1786,30 @@ async fn fetch_ec_index_from_one_peer(
|
||||
)));
|
||||
}
|
||||
|
||||
// .ecj is the source peer's deletion journal (appended); .vif carries EC
|
||||
// params. Both are best-effort: a missing .ecj is recreated at mount and a
|
||||
// missing .vif falls back to default EC parameters. A failed .ecj append
|
||||
// leaves a partial file, so drop it.
|
||||
// .ecj is the source peer's deletion journal; .vif carries EC params. Both
|
||||
// are best-effort: a missing .ecj is recreated at mount and a missing .vif
|
||||
// falls back to default EC parameters. The journal is a *set*: merge the
|
||||
// peer's ids into any local ones as a union instead of appending, so
|
||||
// a volume bounced between servers cannot double its journal. The merge
|
||||
// only appends whole records, so a failure leaves nothing to clean up.
|
||||
match client.copy_file(copy_req(".ecj", true)).await {
|
||||
Ok(resp) => {
|
||||
if let Err(e) = drain_copy_stream(resp.into_inner(), ecj_path, true).await {
|
||||
let mut stream = resp.into_inner();
|
||||
let merged = match crate::server::grpc_server::receive_ecj_ids(&mut stream).await {
|
||||
Ok((ids, true)) => crate::server::grpc_server::merge_ecj_ids(
|
||||
state,
|
||||
m.vid,
|
||||
m.data_dir.clone(),
|
||||
ecj_path.to_string(),
|
||||
ids,
|
||||
)
|
||||
.await
|
||||
.map(|_| ()),
|
||||
Ok((_, false)) => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
if let Err(e) = merged {
|
||||
tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .ecj: {}", e);
|
||||
let _ = fs::remove_file(ecj_path);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .ecj: {}", e),
|
||||
@@ -1749,7 +1817,7 @@ async fn fetch_ec_index_from_one_peer(
|
||||
|
||||
match client.copy_file(copy_req(".vif", true)).await {
|
||||
Ok(resp) => {
|
||||
if let Err(e) = drain_copy_stream(resp.into_inner(), vif_path, false).await {
|
||||
if let Err(e) = drain_copy_stream(resp.into_inner(), vif_path).await {
|
||||
tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .vif: {}", e);
|
||||
}
|
||||
}
|
||||
@@ -1759,22 +1827,14 @@ async fn fetch_ec_index_from_one_peer(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drain a CopyFile stream into a local file, appending or truncating.
|
||||
/// Drain a CopyFile stream into a local file, truncating it first.
|
||||
async fn drain_copy_stream(
|
||||
mut stream: tonic::Streaming<crate::pb::volume_server_pb::CopyFileResponse>,
|
||||
dest_path: &str,
|
||||
append: bool,
|
||||
) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
let mut file = if append {
|
||||
fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(dest_path)
|
||||
} else {
|
||||
fs::File::create(dest_path)
|
||||
}
|
||||
.map_err(|e| io::Error::other(format!("create {}: {}", dest_path, e)))?;
|
||||
let mut file = fs::File::create(dest_path)
|
||||
.map_err(|e| io::Error::other(format!("create {}: {}", dest_path, e)))?;
|
||||
while let Some(chunk) = stream
|
||||
.message()
|
||||
.await
|
||||
@@ -1790,6 +1850,21 @@ async fn drain_copy_stream(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn gather_intervals_puts_a_reported_deletion_ahead_of_errors() {
|
||||
let failed = || Err(io::Error::other("shard unreachable"));
|
||||
assert!(
|
||||
gather_intervals(vec![failed(), Ok((Vec::new(), true))])
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(gather_intervals(vec![failed(), Ok((vec![1], false))]).is_err());
|
||||
assert_eq!(
|
||||
gather_intervals(vec![Ok((vec![1], false)), Ok((vec![2], false))]).unwrap(),
|
||||
Some(vec![vec![1], vec![2]])
|
||||
);
|
||||
}
|
||||
|
||||
fn locations(count: usize) -> HashMap<ShardId, Vec<String>> {
|
||||
(0..count)
|
||||
.map(|sid| (sid as ShardId, vec!["127.0.0.1:8080".to_string()]))
|
||||
|
||||
@@ -114,6 +114,21 @@ pub struct VolumeServerState {
|
||||
pub cli_white_list: Vec<String>,
|
||||
/// Path to state.pb file for persisting VolumeServerState across restarts.
|
||||
pub state_file_path: String,
|
||||
/// Volumes with an EC decode in flight. A dropped request leaves the
|
||||
/// blocking job running; this keeps a retry from racing it on the
|
||||
/// same volume files.
|
||||
pub ec_decodes_in_flight:
|
||||
std::sync::Mutex<std::collections::HashSet<crate::storage::types::VolumeId>>,
|
||||
/// Volumes whose EC decode is in its publishing tail (journal catch-up,
|
||||
/// .idx write, compaction). Local .ecj appenders wait on
|
||||
/// `ec_decode_tail_notify` while their vid is listed, so no committed
|
||||
/// delete falls between the last catch_up and the .cpd/.cpx swap —
|
||||
/// the per-volume slice of Go's EcVolume.ecjFileAccessLock.
|
||||
pub ec_decode_tail:
|
||||
std::sync::Mutex<std::collections::HashSet<crate::storage::types::VolumeId>>,
|
||||
/// Wakes .ecj appenders waiting on `ec_decode_tail` when a decode's
|
||||
/// publishing tail ends.
|
||||
pub ec_decode_tail_notify: tokio::sync::Notify,
|
||||
}
|
||||
|
||||
impl VolumeServerState {
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! Instead of each upload handler directly calling `write_needle`, writes are
|
||||
//! submitted to a queue. A background worker drains the queue in batches (up to
|
||||
//! 128 entries), groups them by volume ID, and processes them together under a
|
||||
//! single store lock. Requests that asked for `fsync` are flushed by
|
||||
//! `write_needle` itself, one flush per durable write.
|
||||
//! single store lock. Durable writes to a volume share their .dat and .idx
|
||||
//! flushes (see `Volume::write_needles_grouped`).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -159,8 +159,12 @@ fn process_batch(state: Arc<VolumeServerState>, batch: Vec<WriteRequest>) {
|
||||
let mut store = state.store.write().unwrap();
|
||||
|
||||
for (vid, entries) in groups {
|
||||
for (mut needle, fsync, response_tx) in entries {
|
||||
let result = store.write_volume_needle(vid, &mut needle, fsync);
|
||||
let (mut writes, senders): (Vec<_>, Vec<_>) = entries
|
||||
.into_iter()
|
||||
.map(|(needle, fsync, response_tx)| ((needle, fsync), response_tx))
|
||||
.unzip();
|
||||
let results = store.write_volume_needles(vid, &mut writes);
|
||||
for (response_tx, result) in senders.into_iter().zip(results) {
|
||||
// Send result back; ignore error if receiver dropped.
|
||||
let _ = response_tx.send(result);
|
||||
}
|
||||
@@ -225,6 +229,9 @@ mod tests {
|
||||
security_file: String::new(),
|
||||
cli_white_list: vec![],
|
||||
state_file_path: String::new(),
|
||||
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail_notify: tokio::sync::Notify::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -312,6 +319,63 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The queue hands a volume's batch to the grouped path, so ten durable
|
||||
/// writes cost one .dat sync and one .idx sync, not ten of each.
|
||||
#[test]
|
||||
fn test_process_batch_group_commits_fsync_writes() {
|
||||
use crate::config::MinFreeSpace;
|
||||
use crate::storage::types::{DiskType, NeedleId};
|
||||
use crate::storage::volume::VolumeSpec;
|
||||
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let state = make_test_state();
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let mut receivers = Vec::new();
|
||||
let batch = (1..=10u64)
|
||||
.map(|id| {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
receivers.push(response_rx);
|
||||
WriteRequest {
|
||||
volume_id: VolumeId(1),
|
||||
needle: Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: 0x1111.into(),
|
||||
data: vec![id as u8; 8],
|
||||
data_size: 8,
|
||||
..Needle::default()
|
||||
},
|
||||
fsync: true,
|
||||
response_tx,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
process_batch(state.clone(), batch);
|
||||
|
||||
for mut rx in receivers {
|
||||
assert!(matches!(rx.try_recv().unwrap(), Ok((_, _, false))));
|
||||
}
|
||||
let store = state.store.read().unwrap();
|
||||
let (_, vol) = store.find_volume(VolumeId(1)).unwrap();
|
||||
assert_eq!(vol.sync_counts_for_test(), (1, 1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_write_queue_dropped_sender() {
|
||||
// When the queue is dropped, subsequent submits should fail gracefully.
|
||||
|
||||
@@ -18,7 +18,9 @@ use crate::storage::erasure_coding::ec_shard::{
|
||||
DATA_SHARDS_COUNT, ERASURE_CODING_LARGE_BLOCK_SIZE, ERASURE_CODING_SMALL_BLOCK_SIZE,
|
||||
EcVolumeShard, ShardId,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_volume::{EcVolume, is_usable_ecx_file};
|
||||
use crate::storage::erasure_coding::ec_volume::{
|
||||
ECJ_COMPACT_TMP_EXT, EcVolume, is_usable_ecx_file,
|
||||
};
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
use crate::storage::types::*;
|
||||
@@ -460,13 +462,16 @@ impl DiskLocation {
|
||||
let idx_base = volume_file_name(&self.idx_directory, collection, vid);
|
||||
const MAX_SHARD_COUNT: usize = 32;
|
||||
|
||||
// Remove index files from idx directory (.ecx, .ecj)
|
||||
// Remove index files from idx directory (.ecx, .ecj, and a compaction
|
||||
// tmp a crash may have left beside the .ecj)
|
||||
rm_if_present(format!("{}.ecx", idx_base))?;
|
||||
rm_if_present(format!("{}.ecj", idx_base))?;
|
||||
rm_if_present(format!("{}{}", idx_base, ECJ_COMPACT_TMP_EXT))?;
|
||||
// Also try data directory in case .ecx/.ecj were created before -dir.idx was configured
|
||||
if self.idx_directory != self.directory {
|
||||
rm_if_present(format!("{}.ecx", base))?;
|
||||
rm_if_present(format!("{}.ecj", base))?;
|
||||
rm_if_present(format!("{}{}", base, ECJ_COMPACT_TMP_EXT))?;
|
||||
}
|
||||
|
||||
// Remove all EC shard files (.ec00 ~ .ec31)
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
//! Rebuilds the original .dat + .idx files from data shards (.ec00-.ec09)
|
||||
//! and the sorted index (.ecx) + deletion journal (.ecj).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
use crate::storage::erasure_coding::ec_shard::*;
|
||||
use crate::storage::erasure_coding::ec_volume::read_ecj_ids;
|
||||
use crate::storage::idx;
|
||||
use crate::storage::needle::needle::get_actual_size;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
@@ -20,18 +22,21 @@ use crate::storage::volume::{fsync_dir, volume_file_name};
|
||||
/// `dir` is used both for reading `.ec00` and `.ecx`. For split-disk
|
||||
/// reconciled volumes call [`find_dat_file_size_with_dirs`] instead.
|
||||
pub fn find_dat_file_size(dir: &str, collection: &str, volume_id: VolumeId) -> io::Result<i64> {
|
||||
find_dat_file_size_with_dirs(dir, dir, collection, volume_id)
|
||||
let deleted = read_ecj_deletions(&[dir], collection, volume_id)?;
|
||||
find_dat_file_size_with_dirs(dir, dir, collection, volume_id, &deleted)
|
||||
}
|
||||
|
||||
/// Like [`find_dat_file_size`] but lets the caller pass separate dirs
|
||||
/// for `.ec00` (the data shard) and `.ecx` (the sealed index). This
|
||||
/// is the form needed when shards are split across data dirs and the
|
||||
/// `.ecx` lives on a sibling disk's idx dir (#9252).
|
||||
/// `.ecx` lives on a sibling disk's idx dir (#9252). Needles in `deleted`
|
||||
/// count as deleted.
|
||||
pub fn find_dat_file_size_with_dirs(
|
||||
ec00_dir: &str,
|
||||
ecx_dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
deleted: &HashSet<NeedleId>,
|
||||
) -> io::Result<i64> {
|
||||
let ec00_base = volume_file_name(ec00_dir, collection, volume_id);
|
||||
let ecx_base = volume_file_name(ecx_dir, collection, volume_id);
|
||||
@@ -53,9 +58,9 @@ pub fn find_dat_file_size_with_dirs(
|
||||
|
||||
for i in 0..entry_count {
|
||||
let start = i * NEEDLE_MAP_ENTRY_SIZE;
|
||||
let (_, offset, size) =
|
||||
let (key, offset, size) =
|
||||
idx_entry_from_bytes(&ecx_data[start..start + NEEDLE_MAP_ENTRY_SIZE]);
|
||||
if size.is_deleted() {
|
||||
if size.is_deleted() || deleted.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
let entry_stop = offset.to_actual_offset() + get_actual_size(size, version);
|
||||
@@ -67,6 +72,124 @@ pub fn find_dat_file_size_with_dirs(
|
||||
Ok(dat_size)
|
||||
}
|
||||
|
||||
/// Whether the `.ecx` in `ecx_dir` indexes a needle deleted neither there nor
|
||||
/// in `deleted`.
|
||||
pub fn has_live_needles(
|
||||
ecx_dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
deleted: &HashSet<NeedleId>,
|
||||
) -> io::Result<bool> {
|
||||
let ecx_base = volume_file_name(ecx_dir, collection, volume_id);
|
||||
let ecx_data = std::fs::read(format!("{}.ecx", ecx_base))?;
|
||||
let (entries, _) = ecx_data.as_chunks::<NEEDLE_MAP_ENTRY_SIZE>();
|
||||
Ok(entries.iter().any(|entry| {
|
||||
let (key, _, size) = idx_entry_from_bytes(entry);
|
||||
!size.is_deleted() && !deleted.contains(&key)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Distinct needle ids journaled in the `.ecj` of any of `dirs`. Go folds the
|
||||
/// journal into the `.ecx` (RebuildEcxFile) before a decode; reading it leaves
|
||||
/// the sealed index untouched. Only NotFound means "no journal".
|
||||
pub fn read_ecj_deletions(
|
||||
dirs: &[&str],
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
) -> io::Result<HashSet<NeedleId>> {
|
||||
Ok(EcjDeletions::read(dirs, collection, volume_id)?.ids)
|
||||
}
|
||||
|
||||
/// The ids [`read_ecj_deletions`] returns, plus how far each journal was read
|
||||
/// so that ids journaled later can be added.
|
||||
pub struct EcjDeletions {
|
||||
pub ids: HashSet<NeedleId>,
|
||||
/// Each distinct journal path and the whole-record length read so far.
|
||||
journals: Vec<(String, u64)>,
|
||||
}
|
||||
|
||||
impl EcjDeletions {
|
||||
pub fn read(dirs: &[&str], collection: &str, volume_id: VolumeId) -> io::Result<Self> {
|
||||
let mut journals: Vec<(String, u64)> = Vec::new();
|
||||
for dir in dirs {
|
||||
let path = format!("{}.ecj", volume_file_name(dir, collection, volume_id));
|
||||
if !journals.iter().any(|(p, _)| *p == path) {
|
||||
journals.push((path, 0));
|
||||
}
|
||||
}
|
||||
let mut deletions = EcjDeletions {
|
||||
ids: HashSet::new(),
|
||||
journals,
|
||||
};
|
||||
deletions.catch_up()?;
|
||||
Ok(deletions)
|
||||
}
|
||||
|
||||
/// Adds the ids appended to each journal since the last read. A journal
|
||||
/// that shrank is read again from the start — and the whole set rebuilt,
|
||||
/// since ids already folded in from the truncated tail may have been a
|
||||
/// rolled-back append. Non-regular journals (the FIFOs the tests stand
|
||||
/// in for a blocking disk) stat empty and cannot be rolled back, so they
|
||||
/// never count as shrunk.
|
||||
pub fn catch_up(&mut self) -> io::Result<()> {
|
||||
let mut shrank = false;
|
||||
for (path, read_to) in &self.journals {
|
||||
if *read_to == 0 {
|
||||
continue;
|
||||
}
|
||||
match std::fs::metadata(path) {
|
||||
Ok(m) => {
|
||||
if m.is_file() && m.len() < *read_to {
|
||||
shrank = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// A journal that was read before and is now gone shrank to
|
||||
// nothing (e.g. the volume was destroyed mid-scan) — the ids
|
||||
// read from it no longer reflect committed content.
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
shrank = true;
|
||||
break;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
if shrank {
|
||||
self.ids.clear();
|
||||
for (_, read_to) in &mut self.journals {
|
||||
*read_to = 0;
|
||||
}
|
||||
}
|
||||
for (path, read_to) in &mut self.journals {
|
||||
let file = match File::open(&*path) {
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let len = file.metadata()?.len();
|
||||
if len < *read_to {
|
||||
*read_to = 0;
|
||||
}
|
||||
read_ecj_ids(&file, *read_to, len, &mut self.ids)?;
|
||||
*read_to = len - len % NEEDLE_ID_SIZE as u64;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clears the set and re-reads every journal from the start. Run under
|
||||
/// the caller's store read lock (no append in flight): the result is
|
||||
/// then exactly the committed content — an earlier unlocked read may
|
||||
/// have folded in bytes a rolled-back append later truncated, or missed
|
||||
/// a record re-appended to the very offset a rollback freed.
|
||||
pub fn rescan(&mut self) -> io::Result<()> {
|
||||
self.ids.clear();
|
||||
for (_, read_to) in &mut self.journals {
|
||||
*read_to = 0;
|
||||
}
|
||||
self.catch_up()
|
||||
}
|
||||
}
|
||||
|
||||
/// What it takes to rebuild a volume's .dat from its EC data shards.
|
||||
///
|
||||
/// Mirrors Go's `WriteDatFile(baseFileName, datFileSize,
|
||||
@@ -265,53 +388,87 @@ pub fn write_dat_file_from_shards(spec: &DatRebuild<'_>) -> io::Result<()> {
|
||||
write_result
|
||||
}
|
||||
|
||||
/// Fails when the decoded `.dat` in `dat_dir` is shorter than the
|
||||
/// `dat_file_size` bytes its EC index references: the caller deletes the
|
||||
/// shards next, and they are the only other copy of the needles past the cut.
|
||||
/// A longer file passes.
|
||||
pub fn verify_decoded_dat_file(
|
||||
dat_dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
dat_file_size: i64,
|
||||
) -> io::Result<()> {
|
||||
let dat_path = format!("{}.dat", volume_file_name(dat_dir, collection, volume_id));
|
||||
let size = std::fs::metadata(&dat_path)?.len();
|
||||
if (size as i64) < dat_file_size {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
format!(
|
||||
"decoded {} is {} bytes, short of the {} its ec index references",
|
||||
dat_path, size, dat_file_size
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write .idx file from .ecx index + .ecj deletion journal.
|
||||
///
|
||||
/// Copies sorted .ecx entries to .idx, then appends tombstones for
|
||||
/// deleted needles from .ecj.
|
||||
/// See [`write_idx_file_from_ec_index_with_dirs`]; everything lives in `dir`.
|
||||
pub fn write_idx_file_from_ec_index(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
) -> io::Result<()> {
|
||||
let base = volume_file_name(dir, collection, volume_id);
|
||||
let ecx_path = format!("{}.ecx", base);
|
||||
let ecj_path = format!("{}.ecj", base);
|
||||
let idx_path = format!("{}.idx", base);
|
||||
let deleted = read_ecj_deletions(&[dir], collection, volume_id)?;
|
||||
let dat_file_size = find_dat_file_size_with_dirs(dir, dir, collection, volume_id, &deleted)?;
|
||||
write_idx_file_from_ec_index_with_dirs(dir, dir, collection, volume_id, &deleted, dat_file_size)
|
||||
}
|
||||
|
||||
/// Write the `.idx` for a `.dat` decoded to `dat_file_size` bytes, from the
|
||||
/// `.ecx` in `ecx_dir`, into `idx_dir`.
|
||||
///
|
||||
/// Copies the `.ecx` rows, then appends one tombstone per row whose needle is
|
||||
/// in `deleted`. A deleted needle at or past `dat_file_size` was cut from the
|
||||
/// `.dat`, so its row is dropped: a row pointing past the end of the `.dat`
|
||||
/// makes the volume load read-only.
|
||||
pub fn write_idx_file_from_ec_index_with_dirs(
|
||||
ecx_dir: &str,
|
||||
idx_dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
deleted: &HashSet<NeedleId>,
|
||||
dat_file_size: i64,
|
||||
) -> io::Result<()> {
|
||||
let ecx_path = format!("{}.ecx", volume_file_name(ecx_dir, collection, volume_id));
|
||||
let idx_path = format!("{}.idx", volume_file_name(idx_dir, collection, volume_id));
|
||||
// Write to a temp file and atomically rename into place, so a crash
|
||||
// mid-write never leaves a partial .idx at the final name beside the
|
||||
// source shards.
|
||||
let tmp_path = format!("{}.tmp", idx_path);
|
||||
|
||||
let write_result = (|| -> io::Result<()> {
|
||||
// Copy .ecx to the temp .idx
|
||||
std::fs::copy(&ecx_path, &tmp_path)?;
|
||||
|
||||
// Append deletions from .ecj as tombstones. Read the journal directly
|
||||
// and treat only NotFound as "no journal": Path::exists would also
|
||||
// swallow a permission/IO error and silently skip deletions, which
|
||||
// would resurrect deleted needles as live.
|
||||
let mut idx_file = std::fs::OpenOptions::new().append(true).open(&tmp_path)?;
|
||||
match std::fs::read(&ecj_path) {
|
||||
Ok(ecj_data) => {
|
||||
let count = ecj_data.len() / NEEDLE_ID_SIZE;
|
||||
for i in 0..count {
|
||||
let start = i * NEEDLE_ID_SIZE;
|
||||
let needle_id = NeedleId::from_bytes(&ecj_data[start..start + NEEDLE_ID_SIZE]);
|
||||
idx::write_index_entry(
|
||||
&mut idx_file,
|
||||
needle_id,
|
||||
Offset::default(),
|
||||
TOMBSTONE_FILE_SIZE,
|
||||
)?;
|
||||
}
|
||||
let mut ecx_file = File::open(&ecx_path)?;
|
||||
let mut idx_file = io::BufWriter::new(File::create(&tmp_path)?);
|
||||
let mut tombstoned = Vec::new();
|
||||
idx::walk_index_file(&mut ecx_file, 0, |key, offset, size| {
|
||||
let is_deleted = size.is_deleted() || deleted.contains(&key);
|
||||
if is_deleted && offset.to_actual_offset() >= dat_file_size {
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e),
|
||||
idx::write_index_entry(&mut idx_file, key, offset, size)?;
|
||||
if !size.is_deleted() && deleted.contains(&key) {
|
||||
tombstoned.push(key);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
for key in tombstoned {
|
||||
idx::write_index_entry(&mut idx_file, key, Offset::default(), TOMBSTONE_FILE_SIZE)?;
|
||||
}
|
||||
|
||||
// fsync, rename, then fsync the dir so the decoded .idx is durable and
|
||||
// atomically published before the caller deletes the source shards.
|
||||
let idx_file = idx_file.into_inner().map_err(|e| e.into_error())?;
|
||||
idx_file.sync_all()?;
|
||||
drop(idx_file);
|
||||
// Windows rename does not replace an existing file on every version;
|
||||
@@ -694,4 +851,116 @@ mod tests {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// A journal many chunks long that repeats a few ids reads back as those
|
||||
/// ids, from each dir once, whatever its length.
|
||||
#[test]
|
||||
fn test_read_ecj_deletions_collects_distinct_ids_across_dirs() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let data = tmp.path().join("data");
|
||||
let idx = tmp.path().join("idx");
|
||||
let missing = tmp.path().join("missing");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::create_dir_all(&idx).unwrap();
|
||||
let (data, idx, missing) = (
|
||||
data.to_str().unwrap(),
|
||||
idx.to_str().unwrap(),
|
||||
missing.to_str().unwrap(),
|
||||
);
|
||||
|
||||
let entry = |id: u64| {
|
||||
let mut buf = [0u8; NEEDLE_ID_SIZE];
|
||||
NeedleId(id).to_bytes(&mut buf);
|
||||
buf
|
||||
};
|
||||
// Past two load chunks of three repeating ids, then an id only in the
|
||||
// last chunk and a torn trailing record.
|
||||
let mut ecj = Vec::new();
|
||||
while ecj.len() <= 2 * (1 << 20) {
|
||||
for id in [1, 2, 3] {
|
||||
ecj.extend_from_slice(&entry(id));
|
||||
}
|
||||
}
|
||||
ecj.extend_from_slice(&entry(7));
|
||||
ecj.extend_from_slice(&entry(8)[..3]);
|
||||
std::fs::write(format!("{idx}/1.ecj"), &ecj).unwrap();
|
||||
std::fs::write(format!("{data}/1.ecj"), entry(9)).unwrap();
|
||||
|
||||
let ids = read_ecj_deletions(&[data, idx, idx, missing], "", VolumeId(1)).unwrap();
|
||||
let expected: HashSet<NeedleId> = [1, 2, 3, 7, 9].into_iter().map(NeedleId).collect();
|
||||
assert_eq!(ids, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_decoded_dat_file_rejects_a_short_dat() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let dat_path = format!("{dir}/1.dat");
|
||||
|
||||
let err = verify_decoded_dat_file(dir, "", VolumeId(1), 100).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::NotFound);
|
||||
|
||||
std::fs::write(&dat_path, vec![0u8; 99]).unwrap();
|
||||
let err = verify_decoded_dat_file(dir, "", VolumeId(1), 100).unwrap_err();
|
||||
assert!(err.to_string().contains("short of the 100"), "{err}");
|
||||
|
||||
std::fs::write(&dat_path, vec![0u8; 100]).unwrap();
|
||||
verify_decoded_dat_file(dir, "", VolumeId(1), 100).unwrap();
|
||||
std::fs::write(&dat_path, vec![0u8; 101]).unwrap();
|
||||
verify_decoded_dat_file(dir, "", VolumeId(1), 100).unwrap();
|
||||
}
|
||||
|
||||
/// Ids appended after the first read, including the rest of a record torn
|
||||
/// at that point, are picked up; a journal that shrank is read again.
|
||||
#[test]
|
||||
fn test_ecj_deletions_catch_up_reads_appended_ids() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let ecj_path = format!("{dir}/1.ecj");
|
||||
let entry = |id: u64| {
|
||||
let mut buf = [0u8; NEEDLE_ID_SIZE];
|
||||
NeedleId(id).to_bytes(&mut buf);
|
||||
buf
|
||||
};
|
||||
let append = |bytes: &[u8]| {
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&ecj_path)
|
||||
.unwrap();
|
||||
f.write_all(bytes).unwrap();
|
||||
};
|
||||
let ids = |d: &EcjDeletions| {
|
||||
let mut ids: Vec<u64> = d.ids.iter().map(|id| id.0).collect();
|
||||
ids.sort();
|
||||
ids
|
||||
};
|
||||
|
||||
// No journal yet.
|
||||
let mut deletions = EcjDeletions::read(&[dir, dir], "", VolumeId(1)).unwrap();
|
||||
assert!(deletions.ids.is_empty());
|
||||
|
||||
append(&entry(1));
|
||||
append(&entry(2)[..3]);
|
||||
deletions.catch_up().unwrap();
|
||||
assert_eq!(ids(&deletions), [1]);
|
||||
|
||||
append(&entry(2)[3..]);
|
||||
append(&entry(3));
|
||||
deletions.catch_up().unwrap();
|
||||
assert_eq!(ids(&deletions), [1, 2, 3]);
|
||||
|
||||
// A shrunk journal is rebuilt from its surviving content: ids folded
|
||||
// in from the truncated tail may have been rolled back and must not
|
||||
// linger as phantom tombstones.
|
||||
std::fs::write(&ecj_path, entry(9)).unwrap();
|
||||
deletions.catch_up().unwrap();
|
||||
assert_eq!(ids(&deletions), [9]);
|
||||
|
||||
// A journal removed since it was read is the extreme shrink: its
|
||||
// earlier ids must go with it, not linger.
|
||||
std::fs::remove_file(&ecj_path).unwrap();
|
||||
deletions.catch_up().unwrap();
|
||||
assert!(deletions.ids.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -813,7 +813,7 @@ impl EncodeRun<'_> {
|
||||
// explicitly.
|
||||
for (i, buf) in self.buffers[..self.data_shards].iter_mut().enumerate() {
|
||||
let read_offset = offset + (i * block_size) as u64;
|
||||
let n = read_at_most(self.dat_file, buf, read_offset)?;
|
||||
let n = crate::storage::io::read_full_at(self.dat_file, buf, read_offset)?;
|
||||
buf[n..].fill(0);
|
||||
}
|
||||
|
||||
@@ -834,19 +834,6 @@ impl EncodeRun<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read into `buf` at `offset` until it is full or EOF; returns bytes read.
|
||||
fn read_at_most(dat_file: &File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
|
||||
let mut n = 0;
|
||||
while n < buf.len() {
|
||||
let r = crate::storage::io::read_at(dat_file, &mut buf[n..], offset + n as u64)?;
|
||||
if r == 0 {
|
||||
break;
|
||||
}
|
||||
n += r;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -87,14 +87,14 @@ impl EcVolumeShard {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read data at a specific offset.
|
||||
/// Read data at a specific offset, filling `buf` unless the shard ends first.
|
||||
pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
|
||||
let file = self
|
||||
.ecd_file
|
||||
.as_ref()
|
||||
.ok_or_else(|| io::Error::other("shard file not open"))?;
|
||||
|
||||
crate::storage::io::read_at(file, buf, offset)
|
||||
crate::storage::io::read_full_at(file, buf, offset)
|
||||
}
|
||||
|
||||
/// Write data to the shard file (appends).
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,290 @@
|
||||
//! Set-union merge of `.ecj` deletion journals for EC shard copy / index
|
||||
//! recovery. Mirrors Go's `weed/storage/erasure_coding/ecj_merge.go`.
|
||||
//!
|
||||
//! An EC volume's deletion journal (`<vid>.ecj`) is a *set* of deleted needle
|
||||
//! ids stored as 8-byte big-endian records. Shard copy and index recovery fold
|
||||
//! a peer's journal into the local one; they must append only the ids the
|
||||
//! local journal lacks, or every `ec_balance` round trip doubles the file.
|
||||
//!
|
||||
//! The journal is only ever appended to, never replaced: a mounted `EcVolume`
|
||||
//! holds it open, and a rename would leave that handle writing to an unlinked
|
||||
//! inode, losing every later delete at the next mount. A mounted volume merges
|
||||
//! through [`EcVolume::merge_journal`](super::ec_volume::EcVolume::merge_journal);
|
||||
//! [`append_ecj_ids`] is for a journal no volume has open.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::{self, Read, Seek, SeekFrom, Write};
|
||||
use std::path::Path;
|
||||
|
||||
use crate::storage::types::{NEEDLE_ID_SIZE, NeedleId};
|
||||
use crate::storage::volume::fsync_dir;
|
||||
use crate::storage::volume_open::open_volume_file;
|
||||
|
||||
/// Bytes per read when scanning a journal; a multiple of `NEEDLE_ID_SIZE`.
|
||||
const ECJ_READ_CHUNK_BYTES: usize = 1 << 20;
|
||||
|
||||
/// Decodes `.ecj` records from a byte stream split at arbitrary boundaries (a
|
||||
/// CopyFile stream, chunked reads), collecting the distinct ids. Memory
|
||||
/// follows the number of distinct ids, not the journal's length. A trailing
|
||||
/// partial record is never decoded.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct EcjIdDecoder {
|
||||
ids: HashSet<NeedleId>,
|
||||
partial: [u8; NEEDLE_ID_SIZE],
|
||||
pending: usize,
|
||||
}
|
||||
|
||||
impl EcjIdDecoder {
|
||||
pub(crate) fn push(&mut self, mut bytes: &[u8]) {
|
||||
if self.pending > 0 {
|
||||
let n = (NEEDLE_ID_SIZE - self.pending).min(bytes.len());
|
||||
self.partial[self.pending..self.pending + n].copy_from_slice(&bytes[..n]);
|
||||
self.pending += n;
|
||||
bytes = &bytes[n..];
|
||||
if self.pending < NEEDLE_ID_SIZE {
|
||||
return;
|
||||
}
|
||||
self.ids.insert(NeedleId::from_bytes(&self.partial));
|
||||
self.pending = 0;
|
||||
}
|
||||
let mut records = bytes.chunks_exact(NEEDLE_ID_SIZE);
|
||||
for record in &mut records {
|
||||
self.ids.insert(NeedleId::from_bytes(record));
|
||||
}
|
||||
let rest = records.remainder();
|
||||
self.partial[..rest.len()].copy_from_slice(rest);
|
||||
self.pending = rest.len();
|
||||
}
|
||||
|
||||
pub(crate) fn into_ids(self) -> HashSet<NeedleId> {
|
||||
self.ids
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the distinct ids of the journal at `path` in bounded chunks. A missing
|
||||
/// file reads as empty. Also returns the whole-record length read; a torn
|
||||
/// trailing partial record is excluded from it.
|
||||
pub(crate) fn read_ecj_ids(path: &str) -> io::Result<(HashSet<NeedleId>, u64)> {
|
||||
let mut file = match fs::File::open(path) {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok((HashSet::new(), 0)),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let len = file.metadata()?.len();
|
||||
let size = len - len % NEEDLE_ID_SIZE as u64;
|
||||
let mut decoder = EcjIdDecoder::default();
|
||||
let mut buf = vec![0u8; (ECJ_READ_CHUNK_BYTES as u64).min(size) as usize];
|
||||
let mut off = 0u64;
|
||||
while off < size {
|
||||
let want = (buf.len() as u64).min(size - off) as usize;
|
||||
file.read_exact(&mut buf[..want])?;
|
||||
decoder.push(&buf[..want]);
|
||||
off += want as u64;
|
||||
}
|
||||
Ok((decoder.into_ids(), size))
|
||||
}
|
||||
|
||||
/// The ids of `incoming` that `has` does not report, ascending, so a merge
|
||||
/// appends deterministic output.
|
||||
pub(crate) fn ecj_delta(
|
||||
incoming: &HashSet<NeedleId>,
|
||||
has: impl Fn(&NeedleId) -> bool,
|
||||
) -> Vec<NeedleId> {
|
||||
let mut delta: Vec<NeedleId> = incoming.iter().copied().filter(|id| !has(id)).collect();
|
||||
delta.sort_unstable();
|
||||
delta
|
||||
}
|
||||
|
||||
pub(crate) fn encode_ecj_ids(ids: &[NeedleId]) -> Vec<u8> {
|
||||
let mut buf = vec![0u8; ids.len() * NEEDLE_ID_SIZE];
|
||||
for (record, id) in buf.chunks_exact_mut(NEEDLE_ID_SIZE).zip(ids) {
|
||||
id.to_bytes(record);
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
/// Append to the journal at `path` the ids of `incoming` that `local` lacks,
|
||||
/// in one write and one fsync, returning how many were added. `local` and
|
||||
/// `size` come from [`read_ecj_ids`] on the same path: if the journal's
|
||||
/// whole-record length is no longer `size`, returns `Ok(None)` so the caller
|
||||
/// re-reads. A torn tail past `size` is truncated first so the new records
|
||||
/// stay aligned.
|
||||
pub(crate) fn append_ecj_ids(
|
||||
path: &str,
|
||||
local: &HashSet<NeedleId>,
|
||||
incoming: &HashSet<NeedleId>,
|
||||
size: u64,
|
||||
) -> io::Result<Option<usize>> {
|
||||
let delta = ecj_delta(incoming, |id| local.contains(id));
|
||||
if delta.is_empty() {
|
||||
return Ok(Some(0));
|
||||
}
|
||||
let created = !Path::new(path).exists();
|
||||
let mut file = open_volume_file(OpenOptions::new().read(true).write(true).create(true), path)?;
|
||||
let len = file.metadata()?.len();
|
||||
if len - len % NEEDLE_ID_SIZE as u64 != size {
|
||||
return Ok(None);
|
||||
}
|
||||
if len != size {
|
||||
file.set_len(size)?;
|
||||
}
|
||||
let appended = file
|
||||
.seek(SeekFrom::Start(size))
|
||||
.and_then(|_| file.write_all(&encode_ecj_ids(&delta)))
|
||||
.and_then(|_| file.sync_all());
|
||||
if let Err(e) = appended {
|
||||
let _ = file.set_len(size);
|
||||
return Err(e);
|
||||
}
|
||||
if created {
|
||||
fsync_dir(path)?;
|
||||
}
|
||||
Ok(Some(delta.len()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ids(v: &[u64]) -> HashSet<NeedleId> {
|
||||
v.iter().map(|&id| NeedleId(id)).collect()
|
||||
}
|
||||
|
||||
fn bytes(v: &[u64]) -> Vec<u8> {
|
||||
encode_ecj_ids(&v.iter().map(|&id| NeedleId(id)).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn records(path: &str) -> Vec<u64> {
|
||||
let data = fs::read(path).expect("read ecj");
|
||||
assert_eq!(data.len() % NEEDLE_ID_SIZE, 0, "journal must stay aligned");
|
||||
data.chunks_exact(NEEDLE_ID_SIZE)
|
||||
.map(|c| NeedleId::from_bytes(c).0)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Run the unmounted merge the way the server does: read, then append.
|
||||
fn merge_file(path: &str, incoming: &HashSet<NeedleId>) -> usize {
|
||||
let (local, size) = read_ecj_ids(path).expect("read");
|
||||
append_ecj_ids(path, &local, incoming, size)
|
||||
.expect("append")
|
||||
.expect("journal unchanged")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_handles_records_split_across_chunks() {
|
||||
let mut stream = bytes(&[1, 2, 3, 2, 0x0102030405060708]);
|
||||
stream.extend_from_slice(&[9, 9, 9]);
|
||||
for chunk in 1..=stream.len() {
|
||||
let mut d = EcjIdDecoder::default();
|
||||
for piece in stream.chunks(chunk) {
|
||||
d.push(piece);
|
||||
}
|
||||
assert_eq!(
|
||||
d.into_ids(),
|
||||
ids(&[1, 2, 3, 0x0102030405060708]),
|
||||
"chunk {}",
|
||||
chunk
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_ecj_ids_dedups_and_ignores_torn_tail() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let missing = dir.path().join("missing.ecj");
|
||||
let (got, size) = read_ecj_ids(missing.to_str().unwrap()).expect("read");
|
||||
assert!(got.is_empty());
|
||||
assert_eq!(size, 0);
|
||||
|
||||
let torn = dir.path().join("torn.ecj");
|
||||
let mut data = bytes(&[1, 2, 1]);
|
||||
data.extend_from_slice(&[7, 7, 7]);
|
||||
fs::write(&torn, data).unwrap();
|
||||
let (got, size) = read_ecj_ids(torn.to_str().unwrap()).expect("read");
|
||||
assert_eq!(got, ids(&[1, 2]));
|
||||
assert_eq!(size, 3 * NEEDLE_ID_SIZE as u64);
|
||||
|
||||
// A bloated journal repeating a few ids across several read chunks
|
||||
// keeps only the distinct ids.
|
||||
let bloated = dir.path().join("bloated.ecj");
|
||||
let data: Vec<u8> = (0..300_000u64).flat_map(|i| bytes(&[i % 3])).collect();
|
||||
fs::write(&bloated, &data).unwrap();
|
||||
let (got, size) = read_ecj_ids(bloated.to_str().unwrap()).expect("read");
|
||||
assert_eq!(got, ids(&[0, 1, 2]));
|
||||
assert_eq!(size, data.len() as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appends_only_missing_ids() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("vol.ecj");
|
||||
let path = path.to_str().unwrap();
|
||||
fs::write(path, bytes(&[1, 2, 3])).unwrap();
|
||||
assert_eq!(merge_file(path, &ids(&[3, 4])), 1);
|
||||
assert_eq!(records(path), vec![1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_stays_constant() {
|
||||
// A->B->A->B 20 times: the old append path doubled the journal each trip.
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let a = dir.path().join("a.ecj");
|
||||
let b = dir.path().join("b.ecj");
|
||||
let (a, b) = (a.to_str().unwrap(), b.to_str().unwrap());
|
||||
fs::write(a, bytes(&[1, 2])).unwrap();
|
||||
fs::write(b, bytes(&[2, 3])).unwrap();
|
||||
for i in 0..20 {
|
||||
let (src, dst) = if i % 2 == 0 { (a, b) } else { (b, a) };
|
||||
let (incoming, _) = read_ecj_ids(src).expect("read");
|
||||
merge_file(dst, &incoming);
|
||||
}
|
||||
for path in [a, b] {
|
||||
let mut got = records(path);
|
||||
got.sort_unstable();
|
||||
assert_eq!(got, vec![1, 2, 3]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_new_leaves_journal_alone() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let missing = dir.path().join("missing.ecj");
|
||||
assert_eq!(merge_file(missing.to_str().unwrap(), &ids(&[])), 0);
|
||||
assert!(
|
||||
!missing.exists(),
|
||||
"an empty merge must not create a journal"
|
||||
);
|
||||
|
||||
let path = dir.path().join("vol.ecj");
|
||||
let path = path.to_str().unwrap();
|
||||
fs::write(path, bytes(&[1, 2])).unwrap();
|
||||
assert_eq!(merge_file(path, &ids(&[2, 1])), 0);
|
||||
assert_eq!(records(path), vec![1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repairs_torn_tail() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("vol.ecj");
|
||||
let path = path.to_str().unwrap();
|
||||
let mut data = bytes(&[1, 2]);
|
||||
data.extend_from_slice(&[9, 9, 9]);
|
||||
fs::write(path, data).unwrap();
|
||||
assert_eq!(merge_file(path, &ids(&[3])), 1);
|
||||
assert_eq!(records(path), vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_changed_journal() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("vol.ecj");
|
||||
let path = path.to_str().unwrap();
|
||||
fs::write(path, bytes(&[1])).unwrap();
|
||||
let (local, size) = read_ecj_ids(path).expect("read");
|
||||
fs::write(path, bytes(&[1, 5])).unwrap();
|
||||
let outcome = append_ecj_ids(path, &local, &ids(&[2]), size).expect("append");
|
||||
assert_eq!(outcome, None);
|
||||
assert_eq!(records(path), vec![1, 5]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Process-wide coordination of everything that touches one `.ecj` path.
|
||||
//!
|
||||
//! Mount-time compaction replaces a deletion journal with a new inode. That is
|
||||
//! only safe while nothing else in this process can write the old one:
|
||||
//!
|
||||
//! - **Holders** are mounted `EcVolume`s with an append handle on the path. A
|
||||
//! store holds one `EcVolume` per disk location, and a shard mount or a
|
||||
//! cross-disk reconcile can point one disk's volume at another disk's
|
||||
//! `.ecj`, so several holders of one path are normal. A holder that keeps
|
||||
//! appending to a replaced inode acknowledges deletes that are gone at the
|
||||
//! next mount.
|
||||
//! - **Writers** append to or replace the path by name without holding it
|
||||
//! open across calls: `ReceiveFile` of an EC `.ecj`, and the unmounted
|
||||
//! append in `merge_ec_journal`, which `VolumeEcShardsCopy` and EC index
|
||||
//! recovery funnel a peer's journal through. Bytes they write after the
|
||||
//! compactor sized the journal would be dropped by the rename.
|
||||
//!
|
||||
//! Compaction therefore runs only while its caller is the sole holder and no
|
||||
//! writer is active, and while it runs no holder may open the path and no
|
||||
//! writer may start. Both wait instead; a compaction rewrites only the distinct
|
||||
//! id set, so the wait is short.
|
||||
//!
|
||||
//! No writer active at the reservation is not enough: one that ran while the
|
||||
//! holder loaded the journal, or after, and has finished may have rewritten it
|
||||
//! in place to the same length (`ReceiveFile` truncates and refills), which
|
||||
//! the inode-and-size re-check cannot see. So each writer bumps the path's
|
||||
//! write generation as it starts, and a holder may compact only if no writer
|
||||
//! was active when it registered and the generation has not moved since.
|
||||
//!
|
||||
//! Paths are keyed by their canonical parent directory, so two disk locations
|
||||
//! that spell one directory differently still meet here.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Condvar, LazyLock, Mutex, MutexGuard};
|
||||
|
||||
#[derive(Default)]
|
||||
struct PathState {
|
||||
holders: usize,
|
||||
writers: usize,
|
||||
compacting: bool,
|
||||
/// Writers that have started on the path. Lives as long as the entry,
|
||||
/// which a registered holder keeps.
|
||||
write_gen: u64,
|
||||
}
|
||||
|
||||
impl PathState {
|
||||
fn idle(&self) -> bool {
|
||||
self.holders == 0 && self.writers == 0 && !self.compacting
|
||||
}
|
||||
}
|
||||
|
||||
struct Registry {
|
||||
paths: Mutex<HashMap<PathBuf, PathState>>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
|
||||
paths: Mutex::new(HashMap::new()),
|
||||
changed: Condvar::new(),
|
||||
});
|
||||
|
||||
fn lock() -> MutexGuard<'static, HashMap<PathBuf, PathState>> {
|
||||
// The critical sections only adjust counters and cannot panic midway, so
|
||||
// a poisoned lock still guards consistent state.
|
||||
REGISTRY.paths.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Canonical key for `path`: its resolved parent directory joined with the
|
||||
/// file name. The file itself may not exist yet (a copy creates it), so only
|
||||
/// the directory is resolved.
|
||||
fn key_for(path: &str) -> PathBuf {
|
||||
let p = Path::new(path);
|
||||
let (Some(parent), Some(name)) = (p.parent(), p.file_name()) else {
|
||||
return std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
};
|
||||
let parent = if parent.as_os_str().is_empty() {
|
||||
Path::new(".")
|
||||
} else {
|
||||
parent
|
||||
};
|
||||
let dir = std::fs::canonicalize(parent)
|
||||
.or_else(|_| std::path::absolute(parent))
|
||||
.unwrap_or_else(|_| parent.to_path_buf());
|
||||
dir.join(name)
|
||||
}
|
||||
|
||||
/// Block until no compaction is running on `key`, then apply `f` to its state.
|
||||
fn update_when_not_compacting<R>(key: &Path, f: impl FnOnce(&mut PathState) -> R) -> R {
|
||||
let mut paths = lock();
|
||||
while paths.get(key).is_some_and(|s| s.compacting) {
|
||||
paths = REGISTRY
|
||||
.changed
|
||||
.wait(paths)
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
f(paths.entry(key.to_path_buf()).or_default())
|
||||
}
|
||||
|
||||
fn release(key: &Path, f: impl FnOnce(&mut PathState)) {
|
||||
let mut paths = lock();
|
||||
if let Some(state) = paths.get_mut(key) {
|
||||
f(state);
|
||||
if state.idle() {
|
||||
paths.remove(key);
|
||||
}
|
||||
}
|
||||
drop(paths);
|
||||
REGISTRY.changed.notify_all();
|
||||
}
|
||||
|
||||
/// A mounted `EcVolume`'s registration as a holder of its `.ecj`. Taken before
|
||||
/// the journal is opened and released when dropped.
|
||||
pub(crate) struct EcjHold {
|
||||
key: PathBuf,
|
||||
/// The path's write generation when the hold was taken, and whether a
|
||||
/// writer was active then. Taken before the journal is opened and loaded,
|
||||
/// so they cover every write the load might have missed.
|
||||
write_gen: u64,
|
||||
writer_at_start: bool,
|
||||
}
|
||||
|
||||
impl EcjHold {
|
||||
/// Register as a holder of `ecj_path`, first waiting out any compaction in
|
||||
/// progress so the handle opened afterwards is on the final inode.
|
||||
pub(crate) fn acquire(ecj_path: &str) -> Self {
|
||||
let key = key_for(ecj_path);
|
||||
let (write_gen, writer_at_start) = update_when_not_compacting(&key, |s| {
|
||||
s.holders += 1;
|
||||
(s.write_gen, s.writers > 0)
|
||||
});
|
||||
EcjHold {
|
||||
key,
|
||||
write_gen,
|
||||
writer_at_start,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reserve the path for a compaction, or `None` when another holder or an
|
||||
/// active writer could still reach the current inode, or when a writer
|
||||
/// has run on the path since the hold was taken, so the journal may no
|
||||
/// longer be what the holder loaded.
|
||||
pub(crate) fn try_begin_compaction(&self) -> Option<EcjCompaction> {
|
||||
let mut paths = lock();
|
||||
let state = paths.get_mut(&self.key)?;
|
||||
if state.holders != 1 || state.writers != 0 || state.compacting {
|
||||
return None;
|
||||
}
|
||||
if self.writer_at_start || state.write_gen != self.write_gen {
|
||||
return None;
|
||||
}
|
||||
state.compacting = true;
|
||||
Some(EcjCompaction {
|
||||
key: self.key.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EcjHold {
|
||||
fn drop(&mut self) {
|
||||
release(&self.key, |s| s.holders = s.holders.saturating_sub(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exclusive reservation of a `.ecj` path for compaction. Holders and
|
||||
/// writers wait until it is dropped.
|
||||
pub(crate) struct EcjCompaction {
|
||||
key: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for EcjCompaction {
|
||||
fn drop(&mut self) {
|
||||
release(&self.key, |s| s.compacting = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// An out-of-band writer (shard copy, index recovery, `ReceiveFile`) on a
|
||||
/// `.ecj` path.
|
||||
/// Compaction does not start while one is alive.
|
||||
pub(crate) struct EcjWrite {
|
||||
key: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for EcjWrite {
|
||||
fn drop(&mut self) {
|
||||
release(&self.key, |s| s.writers = s.writers.saturating_sub(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// Register as a writer of `ecj_path`, waiting out any compaction in progress.
|
||||
/// Blocks; async callers use [`begin_ecj_write_async`].
|
||||
pub(crate) fn begin_ecj_write(ecj_path: &str) -> EcjWrite {
|
||||
let key = key_for(ecj_path);
|
||||
update_when_not_compacting(&key, |s| {
|
||||
s.writers += 1;
|
||||
s.write_gen += 1;
|
||||
});
|
||||
EcjWrite { key }
|
||||
}
|
||||
|
||||
/// [`begin_ecj_write`] for async handlers: the wait runs on the blocking pool
|
||||
/// so a compaction in progress never stalls a runtime worker.
|
||||
pub(crate) async fn begin_ecj_write_async(ecj_path: &str) -> EcjWrite {
|
||||
let path = ecj_path.to_string();
|
||||
match tokio::task::spawn_blocking(move || begin_ecj_write(&path)).await {
|
||||
Ok(write) => write,
|
||||
// Only a panic inside the registry lands here, and it leaves no count
|
||||
// behind; registering inline is still correct, merely blocking.
|
||||
Err(_) => begin_ecj_write(ecj_path),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn ecj(dir: &TempDir) -> String {
|
||||
dir.path().join("1.ecj").to_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sole_holder_may_compact() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let hold = EcjHold::acquire(&ecj(&dir));
|
||||
assert!(hold.try_begin_compaction().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_holder_blocks_compaction() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let a = EcjHold::acquire(&ecj(&dir));
|
||||
let b = EcjHold::acquire(&ecj(&dir));
|
||||
assert!(a.try_begin_compaction().is_none());
|
||||
drop(b);
|
||||
assert!(a.try_begin_compaction().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_writer_blocks_compaction() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let hold = EcjHold::acquire(&ecj(&dir));
|
||||
let w = begin_ecj_write(&ecj(&dir));
|
||||
assert!(hold.try_begin_compaction().is_none());
|
||||
drop(w);
|
||||
// This hold loaded before the write; a later one may compact.
|
||||
drop(hold);
|
||||
let hold = EcjHold::acquire(&ecj(&dir));
|
||||
assert!(hold.try_begin_compaction().is_some());
|
||||
}
|
||||
|
||||
/// A writer that ran after the hold was taken, or was already running
|
||||
/// then, may have changed the journal the holder loaded, even though it
|
||||
/// has finished by the time compaction asks.
|
||||
#[test]
|
||||
fn finished_writer_since_hold_blocks_compaction() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let path = ecj(&dir);
|
||||
|
||||
let hold = EcjHold::acquire(&path);
|
||||
drop(begin_ecj_write(&path));
|
||||
assert!(
|
||||
hold.try_begin_compaction().is_none(),
|
||||
"a writer that started after the hold",
|
||||
);
|
||||
drop(hold);
|
||||
|
||||
let w = begin_ecj_write(&path);
|
||||
let hold = EcjHold::acquire(&path);
|
||||
drop(w);
|
||||
assert!(
|
||||
hold.try_begin_compaction().is_none(),
|
||||
"a writer active when the hold was taken",
|
||||
);
|
||||
drop(hold);
|
||||
|
||||
let hold = EcjHold::acquire(&path);
|
||||
assert!(
|
||||
hold.try_begin_compaction().is_some(),
|
||||
"no writer since the hold",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn differently_spelled_paths_share_one_key() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
std::fs::create_dir(dir.path().join("sub")).unwrap();
|
||||
let plain = ecj(&dir);
|
||||
let dotted = dir
|
||||
.path()
|
||||
.join("sub")
|
||||
.join("..")
|
||||
.join("1.ecj")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let a = EcjHold::acquire(&plain);
|
||||
let _b = EcjHold::acquire(&dotted);
|
||||
assert!(a.try_begin_compaction().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_waits_for_compaction_to_finish() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let path = ecj(&dir);
|
||||
let hold = EcjHold::acquire(&path);
|
||||
let compaction = hold.try_begin_compaction().unwrap();
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let p = path.clone();
|
||||
let t = std::thread::spawn(move || {
|
||||
let _w = begin_ecj_write(&p);
|
||||
tx.send(()).unwrap();
|
||||
});
|
||||
assert!(
|
||||
rx.recv_timeout(Duration::from_millis(100)).is_err(),
|
||||
"a writer must not start while a compaction holds the path",
|
||||
);
|
||||
drop(compaction);
|
||||
rx.recv_timeout(Duration::from_secs(5))
|
||||
.expect("writer must proceed once the compaction ends");
|
||||
t.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ pub mod ec_encoder;
|
||||
pub mod ec_locate;
|
||||
pub mod ec_shard;
|
||||
pub mod ec_volume;
|
||||
pub mod ecj_merge;
|
||||
pub(crate) mod ecj_registry;
|
||||
|
||||
pub use ec_shard::{
|
||||
DATA_SHARDS_COUNT, EcVolumeShard, MAX_SHARD_COUNT, MIN_TOTAL_DISKS, PARITY_SHARDS_COUNT,
|
||||
|
||||
@@ -36,23 +36,11 @@ pub(crate) fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> io::Res
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::FileExt;
|
||||
let mut filled = 0;
|
||||
let mut at = offset;
|
||||
while filled < buf.len() {
|
||||
let n = match file.seek_read(&mut buf[filled..], at) {
|
||||
Ok(n) => n,
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if n == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"unexpected EOF in seek_read",
|
||||
));
|
||||
}
|
||||
filled += n;
|
||||
at += n as u64;
|
||||
if read_full_at(file, buf, offset)? < buf.len() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"unexpected EOF in seek_read",
|
||||
));
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
@@ -84,9 +72,34 @@ pub(crate) fn read_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<us
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads into `buf` at `offset` until it is full or the file ends, retrying
|
||||
/// interrupted reads; returns how many bytes were read.
|
||||
///
|
||||
/// Unlike [`read_at`], a count below `buf.len()` always means end of file.
|
||||
pub(crate) fn read_full_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
|
||||
fill_at(|b, at| read_at(file, b, at), buf, offset)
|
||||
}
|
||||
|
||||
fn fill_at(
|
||||
mut read: impl FnMut(&mut [u8], u64) -> io::Result<usize>,
|
||||
buf: &mut [u8],
|
||||
offset: u64,
|
||||
) -> io::Result<usize> {
|
||||
let mut filled = 0;
|
||||
while filled < buf.len() {
|
||||
match read(&mut buf[filled..], offset + filled as u64) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => filled += n,
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{read_at, read_exact_at};
|
||||
use super::{fill_at, read_at, read_exact_at, read_full_at};
|
||||
use std::io::{ErrorKind, Write};
|
||||
|
||||
fn temp_file(bytes: &[u8]) -> tempfile::NamedTempFile {
|
||||
@@ -139,4 +152,57 @@ mod tests {
|
||||
let n = read_at(f.as_file(), &mut buf, 10).expect("read");
|
||||
assert_eq!(n, 0);
|
||||
}
|
||||
|
||||
/// A source that returns at most `chunk` bytes per call and fails with
|
||||
/// `Interrupted` on its first call, like a network mount under a signal.
|
||||
fn chunked(src: &[u8], chunk: usize) -> impl FnMut(&mut [u8], u64) -> std::io::Result<usize> {
|
||||
let mut interrupted = false;
|
||||
move |buf, at| {
|
||||
if !interrupted {
|
||||
interrupted = true;
|
||||
return Err(ErrorKind::Interrupted.into());
|
||||
}
|
||||
let at = (at as usize).min(src.len());
|
||||
let n = buf.len().min(chunk).min(src.len() - at);
|
||||
buf[..n].copy_from_slice(&src[at..at + n]);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_at_fills_across_short_and_interrupted_reads() {
|
||||
let src: Vec<u8> = (0..=255).collect();
|
||||
let mut buf = [0u8; 100];
|
||||
let n = fill_at(chunked(&src, 7), &mut buf, 50).expect("read");
|
||||
assert_eq!(n, buf.len());
|
||||
assert_eq!(&buf[..], &src[50..150]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_at_stops_at_end_of_source() {
|
||||
let src: Vec<u8> = (0..=255).collect();
|
||||
let mut buf = [0u8; 100];
|
||||
let n = fill_at(chunked(&src, 7), &mut buf, 200).expect("read");
|
||||
assert_eq!(n, 56);
|
||||
assert_eq!(&buf[..n], &src[200..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_at_propagates_other_errors() {
|
||||
let mut buf = [0u8; 8];
|
||||
let err = fill_at(|_, _| Err(ErrorKind::PermissionDenied.into()), &mut buf, 0)
|
||||
.expect_err("error");
|
||||
assert_eq!(err.kind(), ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_full_at_returns_the_short_count_only_at_eof() {
|
||||
let f = temp_file(b"0123456789");
|
||||
let mut buf = [0u8; 8];
|
||||
assert_eq!(read_full_at(f.as_file(), &mut buf, 0).expect("read"), 8);
|
||||
assert_eq!(&buf, b"01234567");
|
||||
assert_eq!(read_full_at(f.as_file(), &mut buf, 6).expect("read"), 4);
|
||||
assert_eq!(&buf[..4], b"6789");
|
||||
assert_eq!(read_full_at(f.as_file(), &mut buf, 10).expect("read"), 0);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::io;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
/// Consecutive storage-media errors allowed before the volume is quarantined.
|
||||
pub(crate) const IO_ERROR_TOLERANCE: i32 = 3;
|
||||
@@ -34,10 +34,30 @@ pub(crate) fn is_storage_io_error(e: &io::Error) -> bool {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IoErrorTracker {
|
||||
last: Mutex<Option<String>>,
|
||||
count: AtomicI32,
|
||||
/// The consecutive error count in the low 32 bits and, in the high 32,
|
||||
/// how many times it has been cleared. They share one word so that
|
||||
/// `record_success_at` updates both in one step: reads record their
|
||||
/// outcomes here without the volume's write lock.
|
||||
streak: AtomicU64,
|
||||
quarantined: AtomicBool,
|
||||
}
|
||||
|
||||
const STREAK_COUNT_BITS: u64 = 0xffff_ffff;
|
||||
|
||||
fn streak_count(streak: u64) -> i32 {
|
||||
(streak & STREAK_COUNT_BITS) as i32
|
||||
}
|
||||
|
||||
/// `streak` with its count cleared and one more clear on record.
|
||||
fn streak_cleared(streak: u64) -> u64 {
|
||||
(streak >> 32).wrapping_add(1) << 32
|
||||
}
|
||||
|
||||
/// A point in the error streak, taken where a write landed whose success
|
||||
/// is only recorded later. See `IoErrorTracker::record_success_at`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct StreakMark(u64);
|
||||
|
||||
impl IoErrorTracker {
|
||||
/// `Some(e)` records a failure, `None` a success. Only storage-media
|
||||
/// failures count; every other outcome clears the count and last error.
|
||||
@@ -45,14 +65,22 @@ impl IoErrorTracker {
|
||||
if let Some(e) = err
|
||||
&& is_storage_io_error(e)
|
||||
{
|
||||
self.count.fetch_add(1, Ordering::Relaxed);
|
||||
self.streak.fetch_add(1, Ordering::Relaxed);
|
||||
if let Ok(mut guard) = self.last.lock() {
|
||||
*guard = Some(e.to_string());
|
||||
}
|
||||
crate::metrics::STORAGE_IO_ERROR_COUNTER.inc();
|
||||
return;
|
||||
}
|
||||
self.count.store(0, Ordering::Relaxed);
|
||||
self.clear_count();
|
||||
self.clear_last();
|
||||
}
|
||||
|
||||
fn clear_count(&self) {
|
||||
self.update_streak(|streak| Some(streak_cleared(streak)));
|
||||
}
|
||||
|
||||
fn clear_last(&self) {
|
||||
if let Ok(mut guard) = self.last.lock()
|
||||
&& guard.is_some()
|
||||
{
|
||||
@@ -60,17 +88,58 @@ impl IoErrorTracker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply `f` to the streak atomically; `None` leaves it as it is.
|
||||
/// Returns the streak `f` produced, if any.
|
||||
fn update_streak(&self, mut f: impl FnMut(u64) -> Option<u64>) -> Option<u64> {
|
||||
let mut updated = None;
|
||||
let _ = self
|
||||
.streak
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |streak| {
|
||||
updated = f(streak);
|
||||
updated
|
||||
});
|
||||
updated
|
||||
}
|
||||
|
||||
pub(crate) fn mark(&self) -> StreakMark {
|
||||
StreakMark(self.streak.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Record a success as if it had come at `mark`: the errors counted
|
||||
/// before the mark are cleared and the ones counted since still stand,
|
||||
/// as they would had each outcome been recorded in order. A streak
|
||||
/// cleared since the mark is left as it is.
|
||||
pub(crate) fn record_success_at(&self, mark: StreakMark) {
|
||||
let before = streak_count(mark.0);
|
||||
let updated = self.update_streak(|streak| {
|
||||
if streak >> 32 != mark.0 >> 32 {
|
||||
return None;
|
||||
}
|
||||
if streak_count(streak) <= before {
|
||||
return Some(streak_cleared(streak));
|
||||
}
|
||||
Some(streak - before as u64)
|
||||
});
|
||||
// The last error stays when one counted since the mark is left.
|
||||
if updated.is_some_and(|streak| streak_count(streak) == 0) {
|
||||
self.clear_last();
|
||||
}
|
||||
}
|
||||
|
||||
/// The last recorded error, the consecutive count, and the quarantine flag.
|
||||
pub(crate) fn get_io_error_state(&self) -> (Option<String>, i32, bool) {
|
||||
let err = self.last.lock().ok().and_then(|g| g.clone());
|
||||
let count = self.count.load(Ordering::Relaxed);
|
||||
let count = self.count();
|
||||
let quarantined = self.quarantined.load(Ordering::Relaxed);
|
||||
(err, count, quarantined)
|
||||
}
|
||||
|
||||
fn count(&self) -> i32 {
|
||||
streak_count(self.streak.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
pub(crate) fn should_quarantine(&self) -> bool {
|
||||
self.quarantined.load(Ordering::Relaxed)
|
||||
|| self.count.load(Ordering::Relaxed) >= IO_ERROR_TOLERANCE
|
||||
self.quarantined.load(Ordering::Relaxed) || self.count() >= IO_ERROR_TOLERANCE
|
||||
}
|
||||
|
||||
pub(crate) fn mark_io_quarantined(&self) {
|
||||
@@ -78,7 +147,7 @@ impl IoErrorTracker {
|
||||
}
|
||||
|
||||
pub(crate) fn reset_io_error_state(&self) {
|
||||
self.count.store(0, Ordering::Relaxed);
|
||||
self.clear_count();
|
||||
self.quarantined.store(false, Ordering::Relaxed);
|
||||
if let Ok(mut guard) = self.last.lock() {
|
||||
*guard = None;
|
||||
@@ -91,9 +160,11 @@ impl IoErrorTracker {
|
||||
*guard = err.map(|value| value.to_string());
|
||||
}
|
||||
if err.is_some() {
|
||||
self.count.store(IO_ERROR_TOLERANCE, Ordering::Relaxed);
|
||||
self.update_streak(|streak| {
|
||||
Some((streak & !STREAK_COUNT_BITS) | IO_ERROR_TOLERANCE as u64)
|
||||
});
|
||||
} else {
|
||||
self.count.store(0, Ordering::Relaxed);
|
||||
self.clear_count();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,6 +242,87 @@ mod tests {
|
||||
assert!(tracker.should_quarantine());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_at_a_mark_keeps_only_the_errors_after_it() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.record_success_at(mark);
|
||||
|
||||
assert_eq!(
|
||||
tracker.get_io_error_state(),
|
||||
(Some(media_error().to_string()), 1, false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_at_a_mark_with_nothing_after_it_clears_the_streak() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
tracker.record_success_at(mark);
|
||||
|
||||
assert_eq!(tracker.get_io_error_state(), (None, 0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_at_a_mark_leaves_a_streak_cleared_since() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
tracker.check_read_write_error(None);
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.record_success_at(mark);
|
||||
|
||||
assert_eq!(
|
||||
tracker.get_io_error_state(),
|
||||
(Some(media_error().to_string()), 1, false)
|
||||
);
|
||||
}
|
||||
|
||||
/// Reads update the tracker without the volume's write lock, so a
|
||||
/// success replayed at a mark must not lose the errors they record
|
||||
/// while it runs.
|
||||
#[test]
|
||||
fn success_at_a_mark_keeps_concurrent_errors() {
|
||||
use std::sync::{Arc, Barrier};
|
||||
const READERS: i32 = 4;
|
||||
const ERRORS: i32 = 200;
|
||||
|
||||
for _ in 0..500 {
|
||||
let tracker = Arc::new(IoErrorTracker::default());
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
let start = Arc::new(Barrier::new(READERS as usize + 1));
|
||||
let readers: Vec<_> = (0..READERS)
|
||||
.map(|_| {
|
||||
let (tracker, start) = (tracker.clone(), start.clone());
|
||||
std::thread::spawn(move || {
|
||||
start.wait();
|
||||
for _ in 0..ERRORS {
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
start.wait();
|
||||
while tracker.get_io_error_state().1 < 2 + READERS * ERRORS / 2 {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
tracker.record_success_at(mark);
|
||||
for reader in readers {
|
||||
reader.join().unwrap();
|
||||
}
|
||||
// The two errors before the mark are cleared; every error the
|
||||
// readers recorded after it stands.
|
||||
assert_eq!(tracker.get_io_error_state().1, READERS * ERRORS);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_io_error_state_lifts_the_quarantine() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
|
||||
@@ -6,6 +6,7 @@ pub(crate) mod io_error;
|
||||
pub mod needle;
|
||||
pub mod needle_map;
|
||||
pub mod store;
|
||||
pub mod store_ec_journal;
|
||||
pub mod store_ec_mirror;
|
||||
pub mod store_ec_reconcile;
|
||||
pub mod super_block;
|
||||
|
||||
@@ -195,7 +195,12 @@ impl NeedleMapKind {
|
||||
// ============================================================================
|
||||
|
||||
/// Trait for appending to an index file.
|
||||
pub trait IdxFileWriter: Write + Send + Sync {
|
||||
///
|
||||
/// The file is opened without append mode and each row is written at the
|
||||
/// current `idx_file_offset` — the same positioned-write model the Go
|
||||
/// server uses — because an append-mode handle cannot truncate on Windows,
|
||||
/// where the std library keeps it strictly append-only.
|
||||
pub trait IdxFileWriter: Write + Seek + Send + Sync {
|
||||
fn sync_all(&self) -> io::Result<()>;
|
||||
/// Truncate the file to `len` bytes. Used to remove an orphan .idx row
|
||||
/// left by a failed redb commit so `idx_file_offset` stays a contiguous
|
||||
@@ -224,6 +229,9 @@ pub struct CompactNeedleMap {
|
||||
metric: NeedleMapMetric,
|
||||
idx_file: Option<Box<dyn IdxFileWriter>>,
|
||||
idx_file_offset: u64,
|
||||
/// The file holds bytes past `idx_file_offset` that must be trimmed
|
||||
/// before another row can land aligned.
|
||||
idx_torn: bool,
|
||||
}
|
||||
|
||||
impl Default for CompactNeedleMap {
|
||||
@@ -240,6 +248,7 @@ impl CompactNeedleMap {
|
||||
metric: NeedleMapMetric::default(),
|
||||
idx_file: None,
|
||||
idx_file_offset: 0,
|
||||
idx_torn: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,6 +273,7 @@ impl CompactNeedleMap {
|
||||
pub fn set_idx_file(&mut self, file: Box<dyn IdxFileWriter>, offset: u64) {
|
||||
self.idx_file = Some(file);
|
||||
self.idx_file_offset = offset;
|
||||
self.idx_torn = false;
|
||||
}
|
||||
|
||||
/// True when an .idx file writer is attached. A read-only load leaves
|
||||
@@ -278,8 +288,8 @@ impl CompactNeedleMap {
|
||||
/// Insert or update an entry. Appends to .idx file if present.
|
||||
pub fn put(&mut self, key: NeedleId, offset: Offset, size: Size) -> io::Result<()> {
|
||||
// Persist to idx file BEFORE mutating in-memory state for crash consistency
|
||||
if let Some(ref mut idx_file) = self.idx_file {
|
||||
idx::write_index_entry(idx_file, key, offset, size)?;
|
||||
self.append_to_index_file(key, offset, size)?;
|
||||
if self.idx_file.is_some() {
|
||||
self.idx_file_offset += NEEDLE_MAP_ENTRY_SIZE as u64;
|
||||
}
|
||||
|
||||
@@ -289,6 +299,41 @@ impl CompactNeedleMap {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write one row to the .idx file at `idx_file_offset`. A row left
|
||||
/// half-written by a failed write is trimmed back to the offset so the
|
||||
/// next row still lands aligned; while the trim keeps failing no row is
|
||||
/// written at all, or it would sit off alignment and parse as garbage on
|
||||
/// load. The offset itself is advanced by the caller once the row counts.
|
||||
fn append_to_index_file(
|
||||
&mut self,
|
||||
key: NeedleId,
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
) -> io::Result<()> {
|
||||
let Some(idx_file) = self.idx_file.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.idx_torn {
|
||||
match idx_file.truncate_to(self.idx_file_offset) {
|
||||
Ok(()) => self.idx_torn = false,
|
||||
Err(e) => {
|
||||
return Err(io::Error::other(format!(
|
||||
"index file still holds a torn row: {e}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
idx_file.seek(io::SeekFrom::Start(self.idx_file_offset))?;
|
||||
if let Err(e) = idx::write_index_entry(idx_file, key, offset, size) {
|
||||
if let Err(te) = idx_file.truncate_to(self.idx_file_offset) {
|
||||
self.idx_torn = true;
|
||||
tracing::warn!("failed to trim torn .idx row: {}", te);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Look up a needle.
|
||||
pub fn get(&self, key: NeedleId) -> Option<NeedleValue> {
|
||||
self.map.get(key)
|
||||
@@ -313,8 +358,8 @@ impl CompactNeedleMap {
|
||||
}
|
||||
|
||||
// Always write tombstone to idx file (matching Go)
|
||||
if let Some(ref mut idx_file) = self.idx_file {
|
||||
idx::write_index_entry(idx_file, key, offset, TOMBSTONE_FILE_SIZE)?;
|
||||
self.append_to_index_file(key, offset, TOMBSTONE_FILE_SIZE)?;
|
||||
if self.idx_file.is_some() {
|
||||
self.idx_file_offset += NEEDLE_MAP_ENTRY_SIZE as u64;
|
||||
}
|
||||
|
||||
@@ -464,6 +509,9 @@ pub struct RedbNeedleMap {
|
||||
metric: NeedleMapMetric,
|
||||
idx_file: Option<Box<dyn IdxFileWriter>>,
|
||||
idx_file_offset: u64,
|
||||
/// The file holds bytes past `idx_file_offset` that must be trimmed
|
||||
/// before another row can land aligned.
|
||||
idx_torn: bool,
|
||||
/// Puts/deletes since the last durable checkpoint.
|
||||
writes_since_checkpoint: u32,
|
||||
}
|
||||
@@ -570,6 +618,7 @@ impl RedbNeedleMap {
|
||||
metric: NeedleMapMetric::default(),
|
||||
idx_file: None,
|
||||
idx_file_offset: 0,
|
||||
idx_torn: false,
|
||||
writes_since_checkpoint: 0,
|
||||
})
|
||||
}
|
||||
@@ -667,6 +716,7 @@ impl RedbNeedleMap {
|
||||
metric: NeedleMapMetric::default(),
|
||||
idx_file: None,
|
||||
idx_file_offset: 0,
|
||||
idx_torn: false,
|
||||
writes_since_checkpoint: 0,
|
||||
};
|
||||
|
||||
@@ -858,6 +908,7 @@ impl RedbNeedleMap {
|
||||
pub fn set_idx_file(&mut self, file: Box<dyn IdxFileWriter>, offset: u64) {
|
||||
self.idx_file = Some(file);
|
||||
self.idx_file_offset = offset;
|
||||
self.idx_torn = false;
|
||||
}
|
||||
|
||||
/// True when an .idx file writer is attached. See CompactNeedleMap.
|
||||
@@ -874,9 +925,7 @@ impl RedbNeedleMap {
|
||||
// commit leaves an orphan row in .idx that redb doesn't reflect, and
|
||||
// advancing the offset here would let a later checkpoint record it as
|
||||
// reflected, making the reload skip it permanently.
|
||||
if let Some(ref mut idx_file) = self.idx_file {
|
||||
idx::write_index_entry(idx_file, key, offset, size)?;
|
||||
}
|
||||
self.append_to_index_file(key, offset, size)?;
|
||||
|
||||
let key_u64: u64 = key.into();
|
||||
let packed = pack_needle_value(&NeedleValue { offset, size });
|
||||
@@ -947,6 +996,41 @@ impl RedbNeedleMap {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write one row to the .idx file at `idx_file_offset`. A row left
|
||||
/// half-written by a failed write is trimmed back to the offset so the
|
||||
/// next row still lands aligned; while the trim keeps failing no row is
|
||||
/// written at all, or it would sit off alignment and parse as garbage on
|
||||
/// load. The offset itself is advanced by the caller once the row counts.
|
||||
fn append_to_index_file(
|
||||
&mut self,
|
||||
key: NeedleId,
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
) -> io::Result<()> {
|
||||
let Some(idx_file) = self.idx_file.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.idx_torn {
|
||||
match idx_file.truncate_to(self.idx_file_offset) {
|
||||
Ok(()) => self.idx_torn = false,
|
||||
Err(e) => {
|
||||
return Err(io::Error::other(format!(
|
||||
"index file still holds a torn row: {e}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
idx_file.seek(io::SeekFrom::Start(self.idx_file_offset))?;
|
||||
if let Err(e) = idx::write_index_entry(idx_file, key, offset, size) {
|
||||
if let Err(te) = idx_file.truncate_to(self.idx_file_offset) {
|
||||
self.idx_torn = true;
|
||||
tracing::warn!("failed to trim torn .idx row: {}", te);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Look up a needle. A redb failure is an ERROR, not an absent needle:
|
||||
/// answering "not found" would turn a database problem into a read miss
|
||||
/// and let a delete report success without recording a tombstone.
|
||||
@@ -993,9 +1077,7 @@ impl RedbNeedleMap {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
if let Some(ref mut idx_file) = self.idx_file {
|
||||
idx::write_index_entry(idx_file, key, offset, TOMBSTONE_FILE_SIZE)?;
|
||||
}
|
||||
self.append_to_index_file(key, offset, TOMBSTONE_FILE_SIZE)?;
|
||||
|
||||
let deleted_nv = NeedleValue {
|
||||
offset: old.offset,
|
||||
@@ -1085,10 +1167,13 @@ impl RedbNeedleMap {
|
||||
/// a failed redb commit. Without this the next successful write appends
|
||||
/// after the orphan, `idx_file_offset` advances past it, and a later
|
||||
/// checkpoint records an offset that makes the reload skip the orphan.
|
||||
/// When the trim fails the file is latched torn so no later row lands
|
||||
/// after bytes the map does not reflect.
|
||||
fn truncate_idx_to_offset(&mut self) {
|
||||
if let Some(ref mut idx_file) = self.idx_file
|
||||
&& let Err(e) = idx_file.truncate_to(self.idx_file_offset)
|
||||
{
|
||||
self.idx_torn = true;
|
||||
tracing::warn!("failed to truncate orphan .idx row: {}", e);
|
||||
}
|
||||
}
|
||||
@@ -1139,6 +1224,7 @@ impl RedbNeedleMap {
|
||||
self.db = reopened.db;
|
||||
self.metric = reopened.metric;
|
||||
self.idx_file_offset = actual_idx_size;
|
||||
self.idx_torn = reopened.idx_torn;
|
||||
// The reopen replayed all rows since the last durable checkpoint
|
||||
// non-durably; start the counter fresh.
|
||||
self.writes_since_checkpoint = 0;
|
||||
@@ -1691,7 +1777,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let writer = std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.write(true)
|
||||
.open(&idx_path)
|
||||
.unwrap();
|
||||
nm.set_idx_file(Box::new(writer), idx_size);
|
||||
|
||||
@@ -13,12 +13,44 @@ use crate::config::MinFreeSpace;
|
||||
use crate::pb::master_pb;
|
||||
use crate::storage::disk_location::DiskLocation;
|
||||
use crate::storage::erasure_coding::ec_shard::{EcVolumeShard, MAX_SHARD_COUNT, ShardId};
|
||||
use crate::storage::erasure_coding::ec_volume::{EcVolume, is_usable_ecx_file};
|
||||
use crate::storage::needle::needle::Needle;
|
||||
use crate::storage::erasure_coding::ec_volume::{
|
||||
ECJ_COMPACT_TMP_EXT, EcVolume, is_usable_ecx_file,
|
||||
};
|
||||
use crate::storage::needle::needle::{Needle, get_actual_size};
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE};
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume::{CompactionJob, VifVolumeInfo, VolumeError, VolumeSpec};
|
||||
use crate::storage::volume::{CompactionJob, VifVolumeInfo, Volume, VolumeError, VolumeSpec};
|
||||
|
||||
/// Mirrors Go's ensureCompactVolumeSpace, per filesystem: the new .dat lands
|
||||
/// next to the old one and the new .idx next to the old index, so when the
|
||||
/// index directory is on another filesystem each disk answers for its own
|
||||
/// share, while two directories on one filesystem must cover the sum.
|
||||
fn ensure_compact_volume_space(v: &Volume, preallocate: u64) -> Result<(), VolumeError> {
|
||||
let (data_bytes, index_bytes) = compaction_space_needed(v, preallocate);
|
||||
let (dir, dir_idx) = (v.dir(), v.dir_idx());
|
||||
let check = |dir: &str, needed: u64| -> Result<(), VolumeError> {
|
||||
let (_, free) = crate::storage::disk_location::get_disk_stats(dir);
|
||||
if free < needed {
|
||||
return Err(VolumeError::InsufficientSpace {
|
||||
vid: v.id,
|
||||
required: needed,
|
||||
free,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
if dir_idx.is_empty() || dir_idx == dir {
|
||||
check(dir, data_bytes + index_bytes)
|
||||
} else if !same_filesystem(dir, dir_idx) {
|
||||
check(dir, data_bytes)?;
|
||||
check(dir_idx, index_bytes)
|
||||
} else {
|
||||
check(dir, data_bytes + index_bytes)?;
|
||||
check(dir_idx, index_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Top-level storage manager containing all disk locations and their volumes.
|
||||
pub struct Store {
|
||||
@@ -726,17 +758,6 @@ impl Store {
|
||||
vol.needle_read_plan(id, read_deleted)
|
||||
}
|
||||
|
||||
/// Re-lookup a needle's data-file offset after compaction may have moved it.
|
||||
/// Returns `(new_data_file_offset, current_compaction_revision)`.
|
||||
pub fn re_lookup_needle_data_offset(
|
||||
&self,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) -> Result<(u64, u16), VolumeError> {
|
||||
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
|
||||
vol.re_lookup_needle_data_offset(needle_id)
|
||||
}
|
||||
|
||||
/// Write a needle to a volume. With `fsync` the volume flushes its .dat
|
||||
/// before returning, so the caller can ack a durable write.
|
||||
pub fn write_volume_needle(
|
||||
@@ -745,6 +766,30 @@ impl Store {
|
||||
n: &mut Needle,
|
||||
fsync: bool,
|
||||
) -> Result<(u64, Size, bool), VolumeError> {
|
||||
self.writable_volume_mut(vid)?.write_needle(n, true, fsync)
|
||||
}
|
||||
|
||||
/// Write a batch of needles to one volume, sharing the syncs of its
|
||||
/// durable writes. See `Volume::write_needles_grouped`.
|
||||
pub fn write_volume_needles(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
writes: &mut [(Needle, bool)],
|
||||
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
|
||||
match self.writable_volume_mut(vid) {
|
||||
Ok(vol) => vol.write_needles_grouped(writes),
|
||||
// The lookup fails only with NotFound or the disk-space ReadOnly.
|
||||
Err(e) => writes
|
||||
.iter()
|
||||
.map(|_| match e {
|
||||
VolumeError::ReadOnly(vid) => Err(VolumeError::ReadOnly(vid)),
|
||||
_ => Err(VolumeError::NotFound),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn writable_volume_mut(&mut self, vid: VolumeId) -> Result<&mut Volume, VolumeError> {
|
||||
// Check disk space on the location containing this volume.
|
||||
// We do this before the mutable borrow to avoid borrow conflicts.
|
||||
let loc_idx = self
|
||||
@@ -755,11 +800,11 @@ impl Store {
|
||||
.is_disk_space_low
|
||||
.load(Ordering::Relaxed)
|
||||
{
|
||||
return Err(VolumeError::ReadOnly);
|
||||
return Err(VolumeError::ReadOnly(vid));
|
||||
}
|
||||
|
||||
let (_, vol) = self.find_volume_mut(vid).ok_or(VolumeError::NotFound)?;
|
||||
vol.write_needle(n, true, fsync)
|
||||
Ok(vol)
|
||||
}
|
||||
|
||||
/// Delete a needle from a volume.
|
||||
@@ -771,7 +816,7 @@ impl Store {
|
||||
// Match Go's DeleteVolumeNeedle: check noWriteOrDelete before proceeding.
|
||||
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
|
||||
if vol.is_no_write_or_delete() {
|
||||
return Err(VolumeError::ReadOnly);
|
||||
return Err(VolumeError::ReadOnly(vid));
|
||||
}
|
||||
|
||||
let (_, vol) = self.find_volume_mut(vid).ok_or(VolumeError::NotFound)?;
|
||||
@@ -1216,6 +1261,7 @@ impl Store {
|
||||
found_vol.map(|v| (v, dirs))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn delete_expired_ec_volumes(
|
||||
&mut self,
|
||||
) -> (
|
||||
@@ -1301,6 +1347,7 @@ impl Store {
|
||||
}
|
||||
|
||||
/// Remove an EC volume from whichever location has it.
|
||||
#[cfg(test)]
|
||||
pub fn remove_ec_volume(&mut self, vid: VolumeId) -> Option<EcVolume> {
|
||||
for loc in &mut self.locations {
|
||||
if let Some(ecv) = loc.remove_ec_volume(vid) {
|
||||
@@ -1419,10 +1466,12 @@ impl Store {
|
||||
crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
|
||||
let _ = std::fs::remove_file(format!("{}.ecx", idx_base));
|
||||
let _ = std::fs::remove_file(format!("{}.ecj", idx_base));
|
||||
let _ = std::fs::remove_file(format!("{}{}", idx_base, ECJ_COMPACT_TMP_EXT));
|
||||
// Also try data directory in case .ecx/.ecj were created before -dir.idx
|
||||
if loc.idx_directory != loc.directory {
|
||||
let _ = std::fs::remove_file(format!("{}.ecx", data_base));
|
||||
let _ = std::fs::remove_file(format!("{}.ecj", data_base));
|
||||
let _ = std::fs::remove_file(format!("{}{}", data_base, ECJ_COMPACT_TMP_EXT));
|
||||
}
|
||||
// A shard-only disk also drops its stale .vif (Go
|
||||
// removeEcSharedIndexFiles): a live .idx means this disk still
|
||||
@@ -1538,25 +1587,10 @@ impl Store {
|
||||
vid: VolumeId,
|
||||
preallocate: u64,
|
||||
) -> Result<Option<CompactionJob>, VolumeError> {
|
||||
// Required space matches Go's CompactVolume check: the larger of the
|
||||
// requested preallocation and the estimated volume size.
|
||||
let (loc_idx, space_needed) = {
|
||||
let (loc_idx, v) = self
|
||||
.find_volume(vid)
|
||||
.ok_or(VolumeError::VolumeNotFound(vid))?;
|
||||
let estimated = v.dat_file_size().unwrap_or(0) + v.idx_file_size();
|
||||
(loc_idx, std::cmp::max(preallocate, estimated))
|
||||
};
|
||||
|
||||
let dir = self.locations[loc_idx].directory.clone();
|
||||
let (_, free) = crate::storage::disk_location::get_disk_stats(&dir);
|
||||
if free < space_needed {
|
||||
return Err(VolumeError::InsufficientSpace {
|
||||
vid,
|
||||
required: space_needed,
|
||||
free,
|
||||
});
|
||||
}
|
||||
let (_, v) = self
|
||||
.find_volume(vid)
|
||||
.ok_or(VolumeError::VolumeNotFound(vid))?;
|
||||
ensure_compact_volume_space(v, preallocate)?;
|
||||
|
||||
let (_, v) = self
|
||||
.find_volume_mut(vid)
|
||||
@@ -1564,6 +1598,37 @@ impl Store {
|
||||
v.begin_compact_by_index()
|
||||
}
|
||||
|
||||
/// Rewrite the volume in `dir`/`dir_idx`, which is not mounted, with its
|
||||
/// live needles only. Go's `Store.CompactVolumeFiles`.
|
||||
pub fn compact_volume_files(
|
||||
dir: &str,
|
||||
dir_idx: &str,
|
||||
collection: &str,
|
||||
vid: VolumeId,
|
||||
needle_map_kind: NeedleMapKind,
|
||||
) -> Result<(), VolumeError> {
|
||||
let spec = VolumeSpec {
|
||||
collection,
|
||||
..VolumeSpec::default()
|
||||
};
|
||||
let mut v = Volume::new(dir, dir_idx, vid, needle_map_kind, &spec)?;
|
||||
let mut compact = || -> Result<(), VolumeError> {
|
||||
ensure_compact_volume_space(&v, 0)?;
|
||||
v.compact_by_index(0, 0, |_| true)?;
|
||||
v.commit_compact()
|
||||
};
|
||||
let result = compact();
|
||||
if result.is_err() {
|
||||
// A failed commit may have swapped only one of .dat/.idx;
|
||||
// reconcile rolls a decided swap forward or removes orphan
|
||||
// temp files before this volume can mount a mismatched pair.
|
||||
let _ = v.reconcile_compact_state();
|
||||
let _ = v.cleanup_compact();
|
||||
}
|
||||
v.close();
|
||||
result
|
||||
}
|
||||
|
||||
/// Commit a completed compaction: swap files and reload.
|
||||
pub fn commit_compact_volume(&mut self, vid: VolumeId) -> Result<(bool, u64), VolumeError> {
|
||||
let (_, v) = self
|
||||
@@ -1728,6 +1793,65 @@ fn owned_ec_shard_count(loc: &DiskLocation, vid: VolumeId, shard_ids: &[ShardId]
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Mirrors Go's compactionSpaceNeeded: what compaction will write, split into
|
||||
/// the new .dat and rebuilt .idx shares, each capped at its current file.
|
||||
fn compaction_space_needed(v: &Volume, preallocate: u64) -> (u64, u64) {
|
||||
let mut data_bytes = v.current_dat_file_size().unwrap_or(0);
|
||||
let mut index_bytes = v.idx_file_size();
|
||||
|
||||
let live_count = v.file_count() - v.deleted_count();
|
||||
let live_content = v.content_size() as i64 - v.deleted_size() as i64;
|
||||
// Unknown or inconsistent deleted sizes: the whole volume stays the
|
||||
// estimate.
|
||||
let deleted_size_known = v.deleted_count() == 0 || v.deleted_size() > 0;
|
||||
if deleted_size_known && live_count >= 0 && live_content >= 0 {
|
||||
// Empty-needle framing plus a padding unit covers the worst case.
|
||||
let per_needle =
|
||||
(get_actual_size(Size(0), v.version()) + NEEDLE_PADDING_SIZE as i64) as u64;
|
||||
let estimate = with_headroom(
|
||||
SUPER_BLOCK_SIZE as u64 + live_content as u64 + live_count as u64 * per_needle,
|
||||
);
|
||||
if estimate < data_bytes {
|
||||
data_bytes = estimate;
|
||||
}
|
||||
let estimate = with_headroom(live_count as u64 * NEEDLE_MAP_ENTRY_SIZE as u64);
|
||||
if estimate < index_bytes {
|
||||
index_bytes = estimate;
|
||||
}
|
||||
}
|
||||
if preallocate > data_bytes {
|
||||
data_bytes = preallocate;
|
||||
}
|
||||
(data_bytes, index_bytes)
|
||||
}
|
||||
|
||||
/// Headroom for Bloom-filter false positives in the live/deleted counters.
|
||||
fn with_headroom(estimate: u64) -> u64 {
|
||||
estimate + estimate / 16
|
||||
}
|
||||
|
||||
/// Whether two directories draw on the same free-space pool; in doubt, yes.
|
||||
fn same_filesystem(a: &str, b: &str) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
same_filesystem_impl(a, b)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn same_filesystem_impl(a: &str, b: &str) -> bool {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
match (std::fs::metadata(a), std::fs::metadata(b)) {
|
||||
(Ok(ma), Ok(mb)) => ma.dev() == mb.dev(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn same_filesystem_impl(_a: &str, _b: &str) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Tests
|
||||
// ============================================================================
|
||||
@@ -2449,6 +2573,52 @@ mod tests {
|
||||
assert_eq!(selected, Some(0));
|
||||
}
|
||||
|
||||
// VolumeCopy picks a disk before deleting the replica it replaces, so only
|
||||
// the location actually holding that replica may count its slot as free.
|
||||
#[test]
|
||||
fn test_find_free_location_predicate_credits_only_the_holding_location() {
|
||||
let tmp1 = TempDir::new().unwrap();
|
||||
let dir1 = tmp1.path().to_str().unwrap();
|
||||
let tmp2 = TempDir::new().unwrap();
|
||||
let dir2 = tmp2.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
for dir in [dir1, dir2] {
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
1,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
for vid in [81, 82] {
|
||||
store
|
||||
.add_volume(VolumeId(vid), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
}
|
||||
let loc_of = |vid| store.find_volume(VolumeId(vid)).unwrap().0;
|
||||
assert_ne!(loc_of(81), loc_of(82), "fixture must fill both locations");
|
||||
|
||||
let hdd = |loc: &DiskLocation| loc.disk_type == DiskType::HardDrive;
|
||||
assert_eq!(store.find_free_location_predicate(hdd, None), None);
|
||||
assert_eq!(
|
||||
store.find_free_location_predicate(hdd, Some(VolumeId(99))),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
store.find_free_location_predicate(hdd, Some(VolumeId(81))),
|
||||
Some(loc_of(81))
|
||||
);
|
||||
assert_eq!(
|
||||
store.find_free_location_predicate(hdd, Some(VolumeId(82))),
|
||||
Some(loc_of(82))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delete_expired_ec_volumes_removes_expired_entries() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
//! Merging a peer's `.ecj` deletion ids into a local EC journal. Mirrors Go's
|
||||
//! `Store.MergeEcJournal` (`weed/storage/store_ec_journal.go`).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use crate::storage::erasure_coding::ecj_merge::{append_ecj_ids, read_ecj_ids};
|
||||
use crate::storage::store::Store;
|
||||
use crate::storage::types::{NeedleId, VolumeId};
|
||||
|
||||
/// How often an unmounted merge re-reads a journal that changed under it. Only
|
||||
/// a mount-delete-unmount or a concurrent merge between the read and the
|
||||
/// append changes it, so one retry is nearly always enough.
|
||||
const ECJ_MERGE_ATTEMPTS: usize = 5;
|
||||
|
||||
/// Fold a peer's deletion `ids` into the local journal of EC volume `vid` on
|
||||
/// the receiving disk, the one whose data directory is `data_dir`; `ecj_path`
|
||||
/// is that journal's path in the disk's index directory. Appends only the ids
|
||||
/// the journal lacks and returns how many it added. Blocking: call it from
|
||||
/// `spawn_blocking`.
|
||||
///
|
||||
/// A mounted volume owns its journal: the merge goes through its open handle
|
||||
/// and in-memory set. That is the receiving disk's own runtime for `vid`,
|
||||
/// wherever its journal lives (it may sit in the data dir rather than
|
||||
/// `ecj_path`'s index dir), else a sibling runtime journaling into `ecj_path`
|
||||
/// itself: disks sharing one index directory, or reconciliation mounting `vid`
|
||||
/// on a disk that journals into another's (#9212). Otherwise `ecj_path` is
|
||||
/// appended to under the store write lock, which mounts take, so no mount can
|
||||
/// open it mid-append. The read that computes the delta runs outside the lock,
|
||||
/// and a journal that changed in between — including by a concurrent merge —
|
||||
/// is re-read.
|
||||
pub fn merge_ec_journal(
|
||||
store: &RwLock<Store>,
|
||||
vid: VolumeId,
|
||||
data_dir: &str,
|
||||
ecj_path: &str,
|
||||
ids: &HashSet<NeedleId>,
|
||||
) -> io::Result<usize> {
|
||||
merge_ec_journal_with(store, vid, data_dir, ecj_path, ids, read_ecj_ids)
|
||||
}
|
||||
|
||||
/// `merge_ec_journal` with the unlocked journal read injected, so a test can
|
||||
/// mount the volume between that read and the append.
|
||||
fn merge_ec_journal_with(
|
||||
store: &RwLock<Store>,
|
||||
vid: VolumeId,
|
||||
data_dir: &str,
|
||||
ecj_path: &str,
|
||||
ids: &HashSet<NeedleId>,
|
||||
mut read: impl FnMut(&str) -> io::Result<(HashSet<NeedleId>, u64)>,
|
||||
) -> io::Result<usize> {
|
||||
for _ in 0..ECJ_MERGE_ATTEMPTS {
|
||||
{
|
||||
let mut store = store
|
||||
.write()
|
||||
.map_err(|_| io::Error::other("store lock poisoned"))?;
|
||||
if let Some(primary) = mounted_ec_journal(&store, vid, data_dir, ecj_path)? {
|
||||
let ecv = store.locations[primary]
|
||||
.find_ec_volume_mut(vid)
|
||||
.expect("mounted journal runtime");
|
||||
let journal_path = ecv.ecj_file_name();
|
||||
let added = ecv.merge_journal(ids)?;
|
||||
// Publish to the holders of the file the merge wrote to — the
|
||||
// picked runtime's journal may live outside ecj_path, and a
|
||||
// holder of a different file must not claim ids it lacks.
|
||||
publish_to_journal_siblings(&store, primary, vid, &journal_path, ids);
|
||||
return Ok(added);
|
||||
}
|
||||
}
|
||||
let (local, size) = read(ecj_path)?;
|
||||
let mut store = store
|
||||
.write()
|
||||
.map_err(|_| io::Error::other("store lock poisoned"))?;
|
||||
if let Some(primary) = mounted_ec_journal(&store, vid, data_dir, ecj_path)? {
|
||||
// Mounted since the read: its handle owns the journal now.
|
||||
let ecv = store.locations[primary]
|
||||
.find_ec_volume_mut(vid)
|
||||
.expect("mounted journal runtime");
|
||||
let journal_path = ecv.ecj_file_name();
|
||||
let added = ecv.merge_journal(ids)?;
|
||||
publish_to_journal_siblings(&store, primary, vid, &journal_path, ids);
|
||||
return Ok(added);
|
||||
}
|
||||
// The path append registers as a writer so a mount compacting this
|
||||
// journal cannot swap its inode underneath it (the write itself is
|
||||
// already serialized with mounts by the store lock).
|
||||
let _ecj_write =
|
||||
crate::storage::erasure_coding::ecj_registry::begin_ecj_write(ecj_path);
|
||||
if let Some(added) = append_ecj_ids(ecj_path, &local, ids, size)? {
|
||||
return Ok(added);
|
||||
}
|
||||
}
|
||||
Err(io::Error::other(format!(
|
||||
"ec volume {}: journal {} kept changing during merge",
|
||||
vid.0, ecj_path
|
||||
)))
|
||||
}
|
||||
|
||||
/// The disk index of the runtime holding `ecj_path` open, if any: the disk at
|
||||
/// `data_dir`'s own, else the first sibling journaling into it.
|
||||
fn mounted_ec_journal(
|
||||
store: &Store,
|
||||
vid: VolumeId,
|
||||
data_dir: &str,
|
||||
ecj_path: &str,
|
||||
) -> io::Result<Option<usize>> {
|
||||
let owner = store
|
||||
.locations
|
||||
.iter()
|
||||
.position(|loc| Path::new(&loc.directory) == Path::new(data_dir))
|
||||
.ok_or_else(|| {
|
||||
io::Error::other(format!(
|
||||
"ec volume {}: no disk at {} owns journal {}",
|
||||
vid.0, data_dir, ecj_path
|
||||
))
|
||||
})?;
|
||||
let runtime = if store.locations[owner].has_ec_volume(vid) {
|
||||
Some(owner)
|
||||
} else {
|
||||
store.locations.iter().position(|loc| {
|
||||
loc.find_ec_volume(vid)
|
||||
.is_some_and(|ecv| Path::new(&ecv.ecj_file_name()) == Path::new(ecj_path))
|
||||
})
|
||||
};
|
||||
Ok(runtime)
|
||||
}
|
||||
|
||||
/// Publishes merged ids into every other runtime journaling into `ecj_path`.
|
||||
fn publish_to_journal_siblings(
|
||||
store: &Store,
|
||||
primary: usize,
|
||||
vid: VolumeId,
|
||||
ecj_path: &str,
|
||||
ids: &HashSet<NeedleId>,
|
||||
) {
|
||||
for (i, loc) in store.locations.iter().enumerate() {
|
||||
if i == primary {
|
||||
continue;
|
||||
}
|
||||
if let Some(ecv) = loc.find_ec_volume(vid) {
|
||||
if Path::new(&ecv.ecj_file_name()) == Path::new(ecj_path) {
|
||||
ecv.publish_merged_ids(ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::MinFreeSpace;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::types::DiskType;
|
||||
use crate::storage::volume::{VifEcShardConfig, VifVolumeInfo};
|
||||
use tempfile::TempDir;
|
||||
|
||||
const COLLECTION: &str = "c";
|
||||
const VID: VolumeId = VolumeId(9);
|
||||
|
||||
/// A store with one disk per entry of `data`, all sharing `idx` when given,
|
||||
/// else each indexing into its own data dir.
|
||||
fn make_store(tmp: &TempDir, data: &[&str], idx: Option<&str>) -> RwLock<Store> {
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
for d in data {
|
||||
let dir = tmp.path().join(d).to_string_lossy().into_owned();
|
||||
let idx_dir = idx
|
||||
.map(|i| tmp.path().join(i).to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| dir.clone());
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(&idx_dir).unwrap();
|
||||
store
|
||||
.add_location(
|
||||
&dir,
|
||||
&idx_dir,
|
||||
100,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
RwLock::new(store)
|
||||
}
|
||||
|
||||
fn dir(tmp: &TempDir, d: &str) -> String {
|
||||
tmp.path().join(d).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn records(ids: &[u64]) -> Vec<u8> {
|
||||
let ids: Vec<NeedleId> = ids.iter().copied().map(NeedleId).collect();
|
||||
crate::storage::erasure_coding::ecj_merge::encode_ecj_ids(&ids)
|
||||
}
|
||||
|
||||
fn id_set(ids: &[u64]) -> HashSet<NeedleId> {
|
||||
ids.iter().copied().map(NeedleId).collect()
|
||||
}
|
||||
|
||||
/// Shard 0 of `VID` and its `.vif` in `data_dir`.
|
||||
fn write_shard0(data_dir: &str) {
|
||||
let base = format!("{}/{}_{}", data_dir, COLLECTION, VID.0);
|
||||
std::fs::write(format!("{}.ec00", base), b"shard data nonempty").unwrap();
|
||||
let vif = VifVolumeInfo {
|
||||
version: 3,
|
||||
ec_shard_config: Some(VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
std::fs::write(
|
||||
format!("{}.vif", base),
|
||||
serde_json::to_string(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// `VID`'s `.ecx` and a `.ecj` holding `deleted` in `dir`; returns the
|
||||
/// journal path.
|
||||
fn write_index(dir: &str, deleted: &[u64]) -> String {
|
||||
let base = format!("{}/{}_{}", dir, COLLECTION, VID.0);
|
||||
std::fs::write(format!("{}.ecx", base), vec![0u8; 16]).unwrap();
|
||||
let ecj = format!("{}.ecj", base);
|
||||
std::fs::write(&ecj, records(deleted)).unwrap();
|
||||
ecj
|
||||
}
|
||||
|
||||
fn deleted_on(store: &RwLock<Store>, disk: usize, id: u64) -> bool {
|
||||
store.read().unwrap().locations[disk]
|
||||
.find_ec_volume(VID)
|
||||
.expect("mounted")
|
||||
.is_needle_deleted(NeedleId(id))
|
||||
}
|
||||
|
||||
/// Disks sharing one index directory all hold the same journal path.
|
||||
/// Copying shards onto a disk that has not mounted `vid` must still reach
|
||||
/// the sibling runtime holding that journal open.
|
||||
#[test]
|
||||
fn shared_index_dir_reaches_sibling_mount() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let store = make_store(&tmp, &["d0", "d1"], Some("idx"));
|
||||
write_shard0(&dir(&tmp, "d0"));
|
||||
let ecj = write_index(&dir(&tmp, "idx"), &[1]);
|
||||
store.write().unwrap().locations[0]
|
||||
.mount_ec_shards(VID, COLLECTION, &[0], "")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
store.read().unwrap().locations[0]
|
||||
.find_ec_volume(VID)
|
||||
.unwrap()
|
||||
.ecj_file_name(),
|
||||
ecj
|
||||
);
|
||||
|
||||
let added =
|
||||
merge_ec_journal(&store, VID, &dir(&tmp, "d1"), &ecj, &id_set(&[1, 2])).unwrap();
|
||||
assert_eq!(added, 1);
|
||||
assert!(
|
||||
deleted_on(&store, 0, 2),
|
||||
"the mounted sibling must see id 2"
|
||||
);
|
||||
assert_eq!(std::fs::read(&ecj).unwrap(), records(&[1, 2]));
|
||||
}
|
||||
|
||||
/// Every runtime holding the journal open must see merged ids in memory.
|
||||
#[test]
|
||||
fn shared_journal_reaches_every_holder() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let store = make_store(&tmp, &["d0", "d1"], Some("idx"));
|
||||
write_shard0(&dir(&tmp, "d0"));
|
||||
write_shard0(&dir(&tmp, "d1"));
|
||||
let ecj = write_index(&dir(&tmp, "idx"), &[1]);
|
||||
for i in 0..2 {
|
||||
store.write().unwrap().locations[i]
|
||||
.mount_ec_shards(VID, COLLECTION, &[0], "")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let added =
|
||||
merge_ec_journal(&store, VID, &dir(&tmp, "d1"), &ecj, &id_set(&[1, 2])).unwrap();
|
||||
assert_eq!(added, 1);
|
||||
assert!(
|
||||
deleted_on(&store, 0, 2) && deleted_on(&store, 1, 2),
|
||||
"every journal holder must see the merged id"
|
||||
);
|
||||
assert_eq!(std::fs::read(&ecj).unwrap(), records(&[1, 2]));
|
||||
}
|
||||
|
||||
/// The picked runtime may journal to a different file than the copied
|
||||
/// one — its index lives in its data directory while a sibling's lives
|
||||
/// in the index directory. The ids must be published only to holders of
|
||||
/// the file they were written to.
|
||||
#[test]
|
||||
fn publishes_to_actual_journal_holders() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let store = make_store(&tmp, &["d0", "d1"], Some("idx"));
|
||||
write_shard0(&dir(&tmp, "d0"));
|
||||
write_shard0(&dir(&tmp, "d1"));
|
||||
let data_ecj = write_index(&dir(&tmp, "d0"), &[1]);
|
||||
let idx_ecj = write_index(&dir(&tmp, "idx"), &[1]);
|
||||
for i in 0..2 {
|
||||
store.write().unwrap().locations[i]
|
||||
.mount_ec_shards(VID, COLLECTION, &[0], "")
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
store.read().unwrap().locations[0]
|
||||
.find_ec_volume(VID)
|
||||
.unwrap()
|
||||
.ecj_file_name(),
|
||||
data_ecj
|
||||
);
|
||||
|
||||
let added =
|
||||
merge_ec_journal(&store, VID, &dir(&tmp, "d0"), &idx_ecj, &id_set(&[1, 2])).unwrap();
|
||||
assert_eq!(added, 1);
|
||||
assert_eq!(std::fs::read(&data_ecj).unwrap(), records(&[1, 2]));
|
||||
assert_eq!(std::fs::read(&idx_ecj).unwrap(), records(&[1]));
|
||||
assert!(deleted_on(&store, 0, 2));
|
||||
assert!(
|
||||
!deleted_on(&store, 1, 2),
|
||||
"a different journal's holder must not claim the merged id"
|
||||
);
|
||||
}
|
||||
|
||||
/// A sibling disk can mount `vid` from the receiving disk's index (#9212)
|
||||
/// while the merge reads the journal unlocked. The merge must go through
|
||||
/// that mount and report what it added.
|
||||
#[test]
|
||||
fn mount_during_read_is_merged_through_and_counted() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let store = make_store(&tmp, &["d0", "d1"], None);
|
||||
let owner = dir(&tmp, "d0");
|
||||
let ecj = write_index(&owner, &[1]);
|
||||
write_shard0(&dir(&tmp, "d1"));
|
||||
|
||||
let mut mounted = false;
|
||||
let read = |path: &str| {
|
||||
let read = read_ecj_ids(path);
|
||||
if !mounted {
|
||||
store.write().unwrap().locations[1]
|
||||
.mount_ec_shards_with_idx_dir(VID, COLLECTION, &[0], &owner, "")
|
||||
.unwrap();
|
||||
mounted = true;
|
||||
}
|
||||
read
|
||||
};
|
||||
let added =
|
||||
merge_ec_journal_with(&store, VID, &owner, &ecj, &id_set(&[1, 2, 3]), read).unwrap();
|
||||
assert_eq!(added, 2, "the ids merged through the new mount are counted");
|
||||
assert!(deleted_on(&store, 1, 2) && deleted_on(&store, 1, 3));
|
||||
assert_eq!(std::fs::read(&ecj).unwrap(), records(&[1, 2, 3]));
|
||||
}
|
||||
|
||||
/// An unmounted journal is merged on disk and a repeat adds nothing; a
|
||||
/// data dir that is no disk is refused.
|
||||
#[test]
|
||||
fn unmounted_journal_is_idempotent() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let store = make_store(&tmp, &["d0"], Some("idx"));
|
||||
let ecj = write_index(&dir(&tmp, "idx"), &[1, 2]);
|
||||
let d0 = dir(&tmp, "d0");
|
||||
for want in [2, 0, 0] {
|
||||
let added = merge_ec_journal(&store, VID, &d0, &ecj, &id_set(&[2, 3, 4])).unwrap();
|
||||
assert_eq!(added, want);
|
||||
}
|
||||
assert_eq!(std::fs::read(&ecj).unwrap(), records(&[1, 2, 3, 4]));
|
||||
assert!(
|
||||
merge_ec_journal(&store, VID, &dir(&tmp, "elsewhere"), &ecj, &id_set(&[1])).is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -108,6 +108,9 @@ fn build_test_state(
|
||||
file_size_limit_bytes: 0,
|
||||
maintenance_byte_per_second: 0,
|
||||
is_heartbeating: std::sync::atomic::AtomicBool::new(true),
|
||||
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
|
||||
ec_decode_tail_notify: tokio::sync::Notify::new(),
|
||||
has_master: false,
|
||||
pre_stop_seconds: 0,
|
||||
volume_state_notify: tokio::sync::Notify::new(),
|
||||
@@ -477,6 +480,74 @@ async fn delete_then_get_returns_404() {
|
||||
);
|
||||
}
|
||||
|
||||
// Go answers both with 500 and an error containing "volume N is read only"
|
||||
// (the write behind "failed to write to local disk: ").
|
||||
#[tokio::test]
|
||||
async fn write_and_delete_on_read_only_volume_say_is_read_only() {
|
||||
let (state, _tmp) = test_state();
|
||||
let uri = "/1,01637037d6";
|
||||
|
||||
let request = |method: &str, body: &[u8]| {
|
||||
Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.body(Body::from(body.to_vec()))
|
||||
.unwrap()
|
||||
};
|
||||
let error_of = |body: Vec<u8>| -> String {
|
||||
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
json["error"].as_str().unwrap_or_default().to_string()
|
||||
};
|
||||
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("POST", b"written before read-only"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::CREATED);
|
||||
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.find_volume_mut(VolumeId(1))
|
||||
.unwrap()
|
||||
.1
|
||||
.set_no_write_or_delete(true);
|
||||
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("POST", b"refused"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
let error = error_of(body_bytes(response).await);
|
||||
assert!(error.contains("volume 1 is read only"), "{error}");
|
||||
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("DELETE", b""))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert_eq!(
|
||||
error_of(body_bytes(response).await),
|
||||
"Deletion Failed: volume 1 is read only"
|
||||
);
|
||||
|
||||
// The needle is still there to delete once the volume is writable again.
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.find_volume_mut(VolumeId(1))
|
||||
.unwrap()
|
||||
.1
|
||||
.set_no_write_or_delete(false);
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("DELETE", b""))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::ACCEPTED);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 6. HEAD returns headers without body
|
||||
// ============================================================================
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<scala.binary.version>2.12</scala.binary.version>
|
||||
<junit.version>4.13.2</junit.version>
|
||||
<seaweedfs.hadoop3.client.version>4.00</seaweedfs.hadoop3.client.version>
|
||||
<jackson.version>2.22.1</jackson.version> <!-- Upgraded from 2.15.3 -->
|
||||
<jackson.version>2.22.3</jackson.version> <!-- Upgraded from 2.15.3 -->
|
||||
<!-- jackson-annotations dropped the patch digit in 2.20; matches jackson.version's major.minor -->
|
||||
<jackson.annotations.version>2.22</jackson.annotations.version>
|
||||
<netty.version>4.2.16.Final</netty.version> <!-- Upgraded to 4.1.125.Final for security fixes (CVE in netty-codec < 4.1.125.Final, netty-codec-http2 <= 4.1.123.Final) -->
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
webIdentityAudience = "web-identity-api-test"
|
||||
webIdentitySubject = "spiffe://example.org/ns/app/sa/app"
|
||||
)
|
||||
|
||||
// webIdentityIssuer is an OIDC issuer served by the test: discovery document
|
||||
// and JWKS for one RSA key, so the server under test fetches real keys.
|
||||
type webIdentityIssuer struct {
|
||||
server *httptest.Server
|
||||
key *rsa.PrivateKey
|
||||
}
|
||||
|
||||
func newWebIdentityIssuer(t *testing.T) *webIdentityIssuer {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err)
|
||||
issuer := &webIdentityIssuer{key: key}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"issuer": issuer.server.URL,
|
||||
"jwks_uri": issuer.server.URL + "/keys",
|
||||
"id_token_signing_alg_values_supported": []string{"RS256"},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/keys", func(w http.ResponseWriter, _ *http.Request) {
|
||||
b64 := func(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]any{
|
||||
"kty": "RSA", "kid": "k1", "use": "sig", "alg": "RS256",
|
||||
"n": b64(key.PublicKey.N.Bytes()), "e": b64(big.NewInt(int64(key.PublicKey.E)).Bytes()),
|
||||
}}})
|
||||
})
|
||||
issuer.server = httptest.NewServer(mux)
|
||||
t.Cleanup(issuer.server.Close)
|
||||
return issuer
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) claims(sub string) jwt.MapClaims {
|
||||
now := time.Now()
|
||||
return jwt.MapClaims{"iss": i.server.URL, "sub": sub, "aud": webIdentityAudience,
|
||||
"iat": now.Unix(), "exp": now.Add(10 * time.Minute).Unix()}
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) token(t *testing.T, sub string, key *rsa.PrivateKey) string {
|
||||
t.Helper()
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, i.claims(sub))
|
||||
tok.Header["kid"] = "k1"
|
||||
signed, err := tok.SignedString(key)
|
||||
require.NoError(t, err)
|
||||
return signed
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) tokenForAudience(t *testing.T, sub, aud string) string {
|
||||
t.Helper()
|
||||
claims := i.claims(sub)
|
||||
claims["aud"] = aud
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
tok.Header["kid"] = "k1"
|
||||
signed, err := tok.SignedString(i.key)
|
||||
require.NoError(t, err)
|
||||
return signed
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) unsignedToken(t *testing.T, sub string) string {
|
||||
t.Helper()
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodNone, i.claims(sub)).SignedString(jwt.UnsafeAllowNoneSignatureType)
|
||||
require.NoError(t, err)
|
||||
return signed
|
||||
}
|
||||
|
||||
func trustPolicyFor(issuerURL, sub string) string {
|
||||
doc, _ := json.Marshal(map[string]any{"Version": "2012-10-17", "Statement": []any{map[string]any{
|
||||
"Effect": "Allow", "Principal": map[string]any{"Federated": issuerURL},
|
||||
"Action": []string{"sts:AssumeRoleWithWebIdentity"},
|
||||
"Condition": map[string]any{"StringEquals": map[string]any{"oidc:sub": sub}},
|
||||
}}})
|
||||
return string(doc)
|
||||
}
|
||||
|
||||
// assumeWithWebIdentity returns session credentials, or nil and the error body.
|
||||
func assumeWithWebIdentity(t *testing.T, roleArn, token string) (*credentials.Credentials, string) {
|
||||
t.Helper()
|
||||
resp, err := callSTSAPI(t, url.Values{
|
||||
"Action": {"AssumeRoleWithWebIdentity"}, "Version": {"2011-06-15"},
|
||||
"RoleArn": {roleArn}, "RoleSessionName": {"web-identity-api"}, "WebIdentityToken": {token},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, string(body)
|
||||
}
|
||||
var out AssumeRoleWithWebIdentityTestResponse
|
||||
require.NoError(t, xml.Unmarshal(body, &out), "body: %s", body)
|
||||
c := out.Result.Credentials
|
||||
return credentials.NewStaticCredentials(c.AccessKeyId, c.SecretAccessKey, c.SessionToken), ""
|
||||
}
|
||||
|
||||
func s3ClientWith(t *testing.T, creds *credentials.Credentials) *s3.S3 {
|
||||
t.Helper()
|
||||
sess, err := session.NewSession(&aws.Config{
|
||||
Region: aws.String(TestRegion), Endpoint: aws.String(TestS3Endpoint),
|
||||
Credentials: creds, S3ForcePathStyle: aws.Bool(true), DisableSSL: aws.Bool(true),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return s3.New(sess)
|
||||
}
|
||||
|
||||
// TestWebIdentityWithProviderAndRoleManagedThroughIAMAPI configures STS
|
||||
// federation entirely at runtime — an OIDC provider, a managed policy and a role
|
||||
// created through the IAM API, with no static configuration — and checks that
|
||||
// the role admits exactly the subject its trust policy names, with exactly the
|
||||
// permissions of its attached policy.
|
||||
func TestWebIdentityWithProviderAndRoleManagedThroughIAMAPI(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
if !isSTSEndpointRunning(t) {
|
||||
t.Fatal("SeaweedFS STS endpoint is not running at", TestSTSEndpoint, "- please run 'make setup-all-tests' first")
|
||||
}
|
||||
|
||||
framework := NewS3IAMTestFramework(t)
|
||||
defer framework.Cleanup()
|
||||
admin, err := framework.CreateIAMClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
adminS3, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
|
||||
issuer := newWebIdentityIssuer(t)
|
||||
bucket := framework.GenerateUniqueBucketName("web-identity")
|
||||
require.NoError(t, framework.CreateBucketWithCleanup(adminS3, bucket))
|
||||
|
||||
provider, err := admin.CreateOpenIDConnectProvider(&iam.CreateOpenIDConnectProviderInput{
|
||||
Url: aws.String(issuer.server.URL),
|
||||
ClientIDList: []*string{aws.String(webIdentityAudience)},
|
||||
// Required by this SDK version; pinning only applies to a TLS issuer,
|
||||
// and the test issuer is plain HTTP.
|
||||
ThumbprintList: []*string{aws.String("0000000000000000000000000000000000000000")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer admin.DeleteOpenIDConnectProvider(&iam.DeleteOpenIDConnectProviderInput{OpenIDConnectProviderArn: provider.OpenIDConnectProviderArn})
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]any{"Version": "2012-10-17", "Statement": []any{map[string]any{
|
||||
"Effect": "Allow", "Action": []string{"s3:*"},
|
||||
"Resource": []string{"arn:aws:s3:::" + bucket, "arn:aws:s3:::" + bucket + "/*"},
|
||||
}}})
|
||||
policy, err := admin.CreatePolicy(&iam.CreatePolicyInput{
|
||||
PolicyName: aws.String(bucket + "-rw"), PolicyDocument: aws.String(string(policyDoc)),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer admin.DeletePolicy(&iam.DeletePolicyInput{PolicyArn: policy.Policy.Arn})
|
||||
|
||||
// Role names are at most 64 characters; the bucket name is longer.
|
||||
roleName := "web-identity-" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
role, err := admin.CreateRole(&iam.CreateRoleInput{
|
||||
RoleName: aws.String(roleName),
|
||||
AssumeRolePolicyDocument: aws.String(trustPolicyFor(issuer.server.URL, webIdentitySubject)),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer admin.DeleteRole(&iam.DeleteRoleInput{RoleName: aws.String(roleName)})
|
||||
_, err = admin.AttachRolePolicy(&iam.AttachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
require.NoError(t, err)
|
||||
defer admin.DetachRolePolicy(&iam.DetachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
roleArn := aws.StringValue(role.Role.Arn)
|
||||
|
||||
t.Run("the trusted subject gets credentials scoped to the attached policy", func(t *testing.T) {
|
||||
creds, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
require.NotNil(t, creds, "AssumeRoleWithWebIdentity refused the trusted subject: %s", failure)
|
||||
client := s3ClientWith(t, creds)
|
||||
_, err := client.PutObject(&s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("federated.txt")})
|
||||
assert.NoError(t, err, "the session cannot write the bucket its policy grants")
|
||||
_, err = client.CreateBucket(&s3.CreateBucketInput{Bucket: aws.String(bucket + "-other")})
|
||||
assert.Error(t, err, "the session created a bucket its policy does not grant")
|
||||
})
|
||||
|
||||
refusals := map[string]string{
|
||||
"another subject": issuer.token(t, "spiffe://example.org/ns/other/sa/other", issuer.key),
|
||||
"a token signed by another key": func() string {
|
||||
other, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err)
|
||||
return issuer.token(t, webIdentitySubject, other)
|
||||
}(),
|
||||
"an unsigned token": issuer.unsignedToken(t, webIdentitySubject),
|
||||
// The provider accepts only its registered client IDs as audiences.
|
||||
"a token issued for another audience": issuer.tokenForAudience(t, webIdentitySubject, "some-other-service"),
|
||||
}
|
||||
for name, token := range refusals {
|
||||
t.Run("refuses "+name, func(t *testing.T) {
|
||||
creds, _ := assumeWithWebIdentity(t, roleArn, token)
|
||||
assert.Nil(t, creds, "AssumeRoleWithWebIdentity issued credentials for %s", name)
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("an updated trust policy takes effect", func(t *testing.T) {
|
||||
moved := "spiffe://example.org/ns/app/sa/moved"
|
||||
_, err := admin.UpdateAssumeRolePolicy(&iam.UpdateAssumeRolePolicyInput{
|
||||
RoleName: aws.String(roleName), PolicyDocument: aws.String(trustPolicyFor(issuer.server.URL, moved)),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
creds, _ := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
assert.Nil(t, creds, "the subject removed from the trust policy still assumes the role")
|
||||
creds, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, moved, issuer.key))
|
||||
assert.NotNil(t, creds, "the subject added to the trust policy was refused: %s", failure)
|
||||
})
|
||||
|
||||
t.Run("a session does not survive its role being deleted and created again", func(t *testing.T) {
|
||||
trust := trustPolicyFor(issuer.server.URL, webIdentitySubject)
|
||||
_, err := admin.UpdateAssumeRolePolicy(&iam.UpdateAssumeRolePolicyInput{RoleName: aws.String(roleName), PolicyDocument: aws.String(trust)})
|
||||
require.NoError(t, err)
|
||||
before, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
require.NotNil(t, before, "precondition: %s", failure)
|
||||
|
||||
_, err = admin.DetachRolePolicy(&iam.DetachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
require.NoError(t, err)
|
||||
_, err = admin.DeleteRole(&iam.DeleteRoleInput{RoleName: aws.String(roleName)})
|
||||
require.NoError(t, err)
|
||||
recreated, err := admin.CreateRole(&iam.CreateRoleInput{RoleName: aws.String(roleName), AssumeRolePolicyDocument: aws.String(trust)})
|
||||
require.NoError(t, err)
|
||||
_, err = admin.AttachRolePolicy(&iam.AttachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, aws.StringValue(role.Role.RoleId), aws.StringValue(recreated.Role.RoleId), "the recreated role reuses the deleted role's ID")
|
||||
|
||||
_, err = s3ClientWith(t, before).PutObject(&s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("revived.txt")})
|
||||
assert.Error(t, err, "a session of the deleted role works again under the new role of the same name")
|
||||
after, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
require.NotNil(t, after, "the new role refuses its trusted subject: %s", failure)
|
||||
_, err = s3ClientWith(t, after).PutObject(&s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("fresh.txt")})
|
||||
assert.NoError(t, err, "a session of the new role cannot use its policy")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package remote_cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
evictRemoteS3 = "http://localhost:28334"
|
||||
evictRemoteMaster = "30334"
|
||||
evictRemoteFiler = "28889"
|
||||
evictRemoteVolume = "30341"
|
||||
evictRemoteWebdav = "27334"
|
||||
evictRemoteMetrics = "30326"
|
||||
|
||||
evictPrimaryS3 = "http://localhost:28333"
|
||||
evictPrimaryMaster = "30333"
|
||||
evictPrimaryFiler = "28887"
|
||||
evictPrimaryVolume = "30340"
|
||||
evictPrimaryWebdav = "27333"
|
||||
evictPrimaryMetrics = "30327"
|
||||
|
||||
evictBucket = "evictsrc"
|
||||
evictMount = "evictmnt"
|
||||
)
|
||||
|
||||
var miniLogPaths []string
|
||||
|
||||
func startMini(t *testing.T, dir string, args ...string) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(dir, 0755))
|
||||
logPath := filepath.Join(dir, "weed.log")
|
||||
logFile, err := os.Create(logPath)
|
||||
require.NoError(t, err)
|
||||
miniLogPaths = append(miniLogPaths, logPath)
|
||||
cmd := exec.Command(weedBinary, append([]string{"mini",
|
||||
"-dir=" + dir,
|
||||
"-s3.config=s3_config.json",
|
||||
"-s3.allowDeleteBucketNotEmpty=true",
|
||||
"-ip=127.0.0.1", "-ip.bind=127.0.0.1",
|
||||
}, args...)...)
|
||||
cmd.Stdout = logFile
|
||||
cmd.Stderr = logFile
|
||||
require.NoError(t, cmd.Start())
|
||||
t.Cleanup(func() {
|
||||
cmd.Process.Kill()
|
||||
cmd.Wait()
|
||||
logFile.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func waitForHTTP(t *testing.T, url string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if resp, err := http.Get(url); err == nil {
|
||||
resp.Body.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
for _, p := range miniLogPaths {
|
||||
if data, err := os.ReadFile(p); err == nil {
|
||||
lines := strings.Split(string(data), "\n")
|
||||
if len(lines) > 30 {
|
||||
lines = lines[len(lines)-30:]
|
||||
}
|
||||
t.Logf("last lines of %s:\n%s", p, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
t.Fatalf("timed out waiting for %s", url)
|
||||
}
|
||||
|
||||
func shellOn(t *testing.T, masterPort, command string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command(weedBinary, "shell", "-master=localhost:"+masterPort)
|
||||
cmd.Stdin = strings.NewReader(command + "\nexit\n")
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoErrorf(t, err, "shell %q failed: %s", command, out)
|
||||
return stripLogs(string(out))
|
||||
}
|
||||
|
||||
func chunkCountOn(t *testing.T, masterPort, path string) string {
|
||||
meta := shellOn(t, masterPort, "fs.meta.cat "+path)
|
||||
idx := strings.LastIndex(meta, "chunks ")
|
||||
require.GreaterOrEqualf(t, idx, 0, "no chunk count in %s", meta)
|
||||
return strings.Fields(meta[idx+len("chunks "):])[0]
|
||||
}
|
||||
|
||||
func volumeStats(t *testing.T, volumePort string) (size, garbage uint64) {
|
||||
t.Helper()
|
||||
resp, err := http.Get("http://localhost:" + volumePort + "/status")
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
var status struct {
|
||||
Volumes []struct {
|
||||
Size uint64 `json:"Size"`
|
||||
DeletedByteCount uint64 `json:"DeletedByteCount"`
|
||||
} `json:"Volumes"`
|
||||
}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&status))
|
||||
for _, v := range status.Volumes {
|
||||
size += v.Size
|
||||
garbage += v.DeletedByteCount
|
||||
}
|
||||
return size, garbage
|
||||
}
|
||||
|
||||
func readViaFiler(t *testing.T, filerPort, path string) []byte {
|
||||
t.Helper()
|
||||
resp, err := http.Get("http://localhost:" + filerPort + path)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "read %s", path)
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return data
|
||||
}
|
||||
|
||||
// TestRemoteCacheEvictUnderPressure fills a cache constrained to two small
|
||||
// volumes with remote-mounted objects until writes fail, then verifies the
|
||||
// filer evicts the oldest synced entry, vacuums the garbage, and a later read
|
||||
// caches again.
|
||||
func TestRemoteCacheEvictUnderPressure(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("spawns two weed mini clusters")
|
||||
}
|
||||
if _, err := os.Stat(weedBinary); err != nil {
|
||||
t.Skipf("weed binary not found at %s; run make build-weed", weedBinary)
|
||||
}
|
||||
if isServerRunning(evictRemoteS3) || isServerRunning(evictPrimaryS3) {
|
||||
t.Skip("eviction test ports are already in use")
|
||||
}
|
||||
|
||||
tmp := t.TempDir()
|
||||
startMini(t, filepath.Join(tmp, "remote"),
|
||||
"-s3.port=28334", "-master.port="+evictRemoteMaster,
|
||||
"-filer.port="+evictRemoteFiler, "-volume.port="+evictRemoteVolume,
|
||||
"-webdav.port="+evictRemoteWebdav, "-metricsPort="+evictRemoteMetrics)
|
||||
waitForHTTP(t, evictRemoteS3)
|
||||
startMini(t, filepath.Join(tmp, "primary"),
|
||||
"-s3.port=28333", "-master.port="+evictPrimaryMaster,
|
||||
"-filer.port="+evictPrimaryFiler, "-volume.port="+evictPrimaryVolume,
|
||||
"-webdav.port="+evictPrimaryWebdav, "-metricsPort="+evictPrimaryMetrics,
|
||||
"-volume.allowUntrustedRemoteEndpoints", "-filer.allowUntrustedRemoteEndpoints",
|
||||
"-s3.allowUntrustedRemoteEndpoints",
|
||||
"-master.volumeSizeLimitMB=32", "-volume.max=2",
|
||||
"-filer.remoteCacheEvictThreshold=0.99")
|
||||
waitForHTTP(t, evictPrimaryS3)
|
||||
|
||||
remote := createS3Client(evictRemoteS3)
|
||||
_, err := remote.CreateBucket(&s3.CreateBucketInput{Bucket: aws.String(evictBucket)})
|
||||
require.NoError(t, err)
|
||||
for i := 0; i < 5; i++ {
|
||||
data := make([]byte, 16*1024*1024)
|
||||
for j := range data {
|
||||
data[j] = byte(i + j%251)
|
||||
}
|
||||
_, err = remote.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(evictBucket),
|
||||
Key: aws.String(fmt.Sprintf("obj%d.bin", i)),
|
||||
Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
shellOn(t, evictPrimaryMaster, fmt.Sprintf(
|
||||
"remote.configure -name=evictremote -type=s3 -s3.access_key=%s -s3.secret_key=%s -s3.endpoint=%s -s3.region=us-east-1",
|
||||
accessKey, secretKey, evictRemoteS3))
|
||||
shellOn(t, evictPrimaryMaster, fmt.Sprintf(
|
||||
"remote.mount -dir=/buckets/%s -remote=evictremote/%s -nonempty", evictMount, evictBucket))
|
||||
shellOn(t, evictPrimaryMaster, fmt.Sprintf("remote.meta.sync -dir=/buckets/%s", evictMount))
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
mount := "/buckets/" + evictMount
|
||||
|
||||
// obj0 caches alone so it is the oldest evictable entry.
|
||||
first := readViaFiler(t, evictPrimaryFiler, mount+"/obj0.bin")
|
||||
require.Len(t, first, 16*1024*1024)
|
||||
require.NotEqual(t, "0", chunkCountOn(t, evictPrimaryMaster, mount+"/obj0.bin"), "obj0 should be cached")
|
||||
|
||||
// 4 x 16MB against ~64MB of capacity: the fills overrun, hit the
|
||||
// capacity error path, and trigger eviction + vacuum.
|
||||
var wg sync.WaitGroup
|
||||
for i := 1; i <= 4; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
data := readViaFiler(t, evictPrimaryFiler, fmt.Sprintf("%s/obj%d.bin", mount, i))
|
||||
assert.Len(t, data, 16*1024*1024)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Eviction must have dropped obj0's local chunks and vacuumed the
|
||||
// tombstoned bytes, leaving only live data within the two volumes.
|
||||
require.True(t, waitForCondition(t, func() bool {
|
||||
size, garbage := volumeStats(t, evictPrimaryVolume)
|
||||
return garbage == 0 && size <= 72*1024*1024
|
||||
}, 2*time.Minute, "volumes to be reclaimed by eviction+vacuum"),
|
||||
"evicted chunks were not reclaimed")
|
||||
|
||||
assert.Equal(t, "0", chunkCountOn(t, evictPrimaryMaster, mount+"/obj0.bin"),
|
||||
"oldest cached entry should be evicted back to remote-only")
|
||||
|
||||
// The cache self-heals: reading the evicted object re-caches it. Fills
|
||||
// still running from the concurrent wave may evict it again, so retry
|
||||
// the read until a commit sticks.
|
||||
var again []byte
|
||||
require.True(t, waitForCondition(t, func() bool {
|
||||
again = readViaFiler(t, evictPrimaryFiler, mount+"/obj0.bin")
|
||||
return chunkCountOn(t, evictPrimaryMaster, mount+"/obj0.bin") != "0"
|
||||
}, 2*time.Minute, "obj0 to re-cache"),
|
||||
"evicted object did not re-cache on read")
|
||||
assert.Equal(t, first, again)
|
||||
}
|
||||
@@ -895,7 +895,7 @@ func (cp *ConfigPersistence) ListTaskDetails() ([]string, error) {
|
||||
return taskIDs, nil
|
||||
}
|
||||
|
||||
// CleanupCompletedTasks removes old completed tasks beyond the retention limit
|
||||
// CleanupCompletedTasks removes old terminal task files beyond the retention limit
|
||||
func (cp *ConfigPersistence) CleanupCompletedTasks() error {
|
||||
cp.tasksMu.Lock()
|
||||
defer cp.tasksMu.Unlock()
|
||||
@@ -914,10 +914,10 @@ func (cp *ConfigPersistence) CleanupCompletedTasks() error {
|
||||
return fmt.Errorf("failed to load tasks for cleanup: %w", err)
|
||||
}
|
||||
|
||||
// Filter completed and failed tasks, sort by completion time
|
||||
var completedTasks []*maintenance.MaintenanceTask
|
||||
for _, task := range allTasks {
|
||||
if (task.Status == maintenance.TaskStatusCompleted || task.Status == maintenance.TaskStatusFailed) && task.CompletedAt != nil {
|
||||
switch task.Status {
|
||||
case maintenance.TaskStatusCompleted, maintenance.TaskStatusFailed, maintenance.TaskStatusCancelled:
|
||||
completedTasks = append(completedTasks, task)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/maintenance"
|
||||
)
|
||||
|
||||
func countTaskStateFiles(t *testing.T, dir string) int {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(filepath.Join(dir, TasksSubdir))
|
||||
if os.IsNotExist(err) {
|
||||
return 0
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("read tasks dir: %v", err)
|
||||
}
|
||||
count := 0
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && filepath.Ext(entry.Name()) == ".pb" {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// TestCancelledTaskFilesDoNotAccumulate reproduces issue #11595: every scan
|
||||
// cycle cancels pending tasks of each detected type and re-detects them, so a
|
||||
// cancelled task file per candidate volume accumulates on disk forever.
|
||||
func TestCancelledTaskFilesDoNotAccumulate(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
|
||||
queue := maintenance.NewMaintenanceQueue(nil)
|
||||
queue.SetPersistence(cp)
|
||||
|
||||
for cycle := 0; cycle < 3; cycle++ {
|
||||
queue.AddTask(&maintenance.MaintenanceTask{
|
||||
ID: fmt.Sprintf("ec_vol_%d_cycle_%d", cycle, cycle),
|
||||
Type: "erasure_coding",
|
||||
VolumeID: uint32(cycle + 1),
|
||||
Server: "server1",
|
||||
})
|
||||
if cancelled := queue.CancelPendingTasksByType("erasure_coding"); cancelled != 1 {
|
||||
t.Fatalf("cycle %d: cancelled %d tasks, want 1", cycle, cancelled)
|
||||
}
|
||||
}
|
||||
|
||||
if n := countTaskStateFiles(t, dir); n != 0 {
|
||||
t.Errorf("%d task files on disk after %d cancel cycles, want 0", n, 3)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManuallyCancelledTaskFileIsRemoved covers the CancelTask path used by
|
||||
// the UI: a cancelled pending task must not leave its file behind, where a
|
||||
// restart would resurrect it as pending.
|
||||
func TestManuallyCancelledTaskFileIsRemoved(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
|
||||
manager := maintenance.NewMaintenanceManager(nil, nil, cp)
|
||||
queue := manager.GetQueue()
|
||||
queue.SetPersistence(cp)
|
||||
|
||||
queue.AddTask(&maintenance.MaintenanceTask{
|
||||
ID: "manual_1",
|
||||
Type: "vacuum",
|
||||
VolumeID: 7,
|
||||
Server: "server1",
|
||||
})
|
||||
if n := countTaskStateFiles(t, dir); n != 1 {
|
||||
t.Fatalf("%d task files after AddTask, want 1", n)
|
||||
}
|
||||
|
||||
if err := manager.CancelTask("manual_1"); err != nil {
|
||||
t.Fatalf("CancelTask: %v", err)
|
||||
}
|
||||
if n := countTaskStateFiles(t, dir); n != 0 {
|
||||
t.Errorf("%d task files on disk after CancelTask, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCleanupCompletedTasksBoundsCancelledFiles checks retention covers
|
||||
// cancelled files, e.g. ones written by older versions.
|
||||
func TestCleanupCompletedTasksBoundsCancelledFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
|
||||
for i := 0; i < MaxCompletedTasks+5; i++ {
|
||||
if err := cp.SaveTaskState(&maintenance.MaintenanceTask{
|
||||
ID: fmt.Sprintf("old_cancelled_%02d", i),
|
||||
Type: "erasure_coding",
|
||||
Status: maintenance.TaskStatusCancelled,
|
||||
}); err != nil {
|
||||
t.Fatalf("save task state: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := cp.CleanupCompletedTasks(); err != nil {
|
||||
t.Fatalf("CleanupCompletedTasks: %v", err)
|
||||
}
|
||||
if n := countTaskStateFiles(t, dir); n > MaxCompletedTasks {
|
||||
t.Errorf("%d task files after cleanup, want at most %d", n, MaxCompletedTasks)
|
||||
}
|
||||
}
|
||||
@@ -452,6 +452,7 @@ func (mm *MaintenanceManager) performCleanup() {
|
||||
|
||||
removedTasks := mm.queue.CleanupOldTasks(taskRetention)
|
||||
removedWorkers := mm.queue.RemoveStaleWorkers(workerTimeout)
|
||||
mm.queue.cleanupCompletedTasks()
|
||||
|
||||
// Clean up stale pending operations (operations running for more than 4 hours)
|
||||
staleOperationTimeout := 4 * time.Hour
|
||||
@@ -616,37 +617,48 @@ func (mm *MaintenanceManager) saveTaskConfigsFromPolicy(policy *worker_pb.Mainte
|
||||
// CancelTask cancels a pending task
|
||||
func (mm *MaintenanceManager) CancelTask(taskID string) error {
|
||||
mm.queue.mutex.Lock()
|
||||
defer mm.queue.mutex.Unlock()
|
||||
|
||||
task, exists := mm.queue.tasks[taskID]
|
||||
if !exists {
|
||||
mm.queue.mutex.Unlock()
|
||||
return fmt.Errorf("task %s not found", taskID)
|
||||
}
|
||||
|
||||
if task.Status == TaskStatusPending {
|
||||
task.Status = TaskStatusCancelled
|
||||
task.CompletedAt = &[]time.Time{time.Now()}[0]
|
||||
|
||||
// Remove from pending tasks
|
||||
for i, pendingTask := range mm.queue.pendingTasks {
|
||||
if pendingTask.ID == taskID {
|
||||
mm.queue.pendingTasks = append(mm.queue.pendingTasks[:i], mm.queue.pendingTasks[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Notify ActiveTopology to release capacity
|
||||
if mm.scanner != nil && mm.scanner.integration != nil {
|
||||
if at := mm.scanner.integration.GetActiveTopology(); at != nil {
|
||||
_ = at.CompleteTask(taskID)
|
||||
}
|
||||
}
|
||||
|
||||
glog.V(2).Infof("Cancelled task %s", taskID)
|
||||
return nil
|
||||
if task.Status != TaskStatusPending {
|
||||
status := task.Status
|
||||
mm.queue.mutex.Unlock()
|
||||
return fmt.Errorf("task %s cannot be cancelled (status: %s)", taskID, status)
|
||||
}
|
||||
|
||||
return fmt.Errorf("task %s cannot be cancelled (status: %s)", taskID, task.Status)
|
||||
task.Status = TaskStatusCancelled
|
||||
completedTime := time.Now()
|
||||
task.CompletedAt = &completedTime
|
||||
cancelledSnapshot := snapshotTask(task)
|
||||
|
||||
// Remove from pending tasks
|
||||
for i, pendingTask := range mm.queue.pendingTasks {
|
||||
if pendingTask.ID == taskID {
|
||||
mm.queue.pendingTasks = append(mm.queue.pendingTasks[:i], mm.queue.pendingTasks[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Notify ActiveTopology to release capacity
|
||||
if mm.scanner != nil && mm.scanner.integration != nil {
|
||||
if at := mm.scanner.integration.GetActiveTopology(); at != nil {
|
||||
_ = at.CompleteTask(taskID)
|
||||
}
|
||||
}
|
||||
mm.queue.mutex.Unlock()
|
||||
|
||||
if mm.queue.persistence != nil {
|
||||
mm.queue.persistMu.Lock()
|
||||
if mm.queue.deleteTaskStateLocked(taskID) != nil {
|
||||
mm.queue.saveTaskStateLocked(cancelledSnapshot)
|
||||
}
|
||||
mm.queue.persistMu.Unlock()
|
||||
}
|
||||
glog.V(2).Infof("Cancelled task %s", taskID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegisterWorker registers a new worker
|
||||
|
||||
@@ -97,21 +97,53 @@ func (mq *MaintenanceQueue) LoadTasksFromPersistence() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// saveTaskState saves a task to persistent storage
|
||||
// isTerminalStatus reports whether the status is a terminal task state.
|
||||
func isTerminalStatus(status MaintenanceTaskStatus) bool {
|
||||
return status == TaskStatusCompleted || status == TaskStatusFailed || status == TaskStatusCancelled
|
||||
}
|
||||
|
||||
// saveTaskState saves a task to persistent storage. persistMu orders the
|
||||
// status check and the write against the cancel paths' deletes, so a stale
|
||||
// non-terminal file cannot resurrect the task on the next restart.
|
||||
func (mq *MaintenanceQueue) saveTaskState(task *MaintenanceTask) {
|
||||
if mq.persistence != nil {
|
||||
if err := mq.persistence.SaveTaskState(task); err != nil {
|
||||
glog.Errorf("Failed to save task state for %s: %v", task.ID, err)
|
||||
}
|
||||
if mq.persistence == nil {
|
||||
return
|
||||
}
|
||||
mq.persistMu.Lock()
|
||||
defer mq.persistMu.Unlock()
|
||||
mq.saveTaskStateLocked(task)
|
||||
}
|
||||
|
||||
// saveTaskStateLocked must be called with persistMu held.
|
||||
func (mq *MaintenanceQueue) saveTaskStateLocked(task *MaintenanceTask) {
|
||||
mq.mutex.RLock()
|
||||
live, ok := mq.tasks[task.ID]
|
||||
stale := !isTerminalStatus(task.Status) && (!ok || isTerminalStatus(live.Status))
|
||||
mq.mutex.RUnlock()
|
||||
if stale {
|
||||
return
|
||||
}
|
||||
if err := mq.persistence.SaveTaskState(task); err != nil {
|
||||
glog.Errorf("Failed to save task state for %s: %v", task.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (mq *MaintenanceQueue) deleteTaskState(taskID string) {
|
||||
if mq.persistence != nil {
|
||||
if err := mq.persistence.DeleteTaskState(taskID); err != nil {
|
||||
glog.V(2).Infof("Failed to delete task state for %s: %v", taskID, err)
|
||||
}
|
||||
func (mq *MaintenanceQueue) deleteTaskState(taskID string) error {
|
||||
if mq.persistence == nil {
|
||||
return nil
|
||||
}
|
||||
mq.persistMu.Lock()
|
||||
defer mq.persistMu.Unlock()
|
||||
return mq.deleteTaskStateLocked(taskID)
|
||||
}
|
||||
|
||||
// deleteTaskStateLocked must be called with persistMu held.
|
||||
func (mq *MaintenanceQueue) deleteTaskStateLocked(taskID string) error {
|
||||
if err := mq.persistence.DeleteTaskState(taskID); err != nil {
|
||||
glog.Warningf("Failed to delete task state for %s: %v", taskID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanupCompletedTasks removes old completed tasks beyond the retention limit
|
||||
@@ -297,9 +329,18 @@ func (mq *MaintenanceQueue) CancelPendingTasksByType(taskType MaintenanceTaskTyp
|
||||
mq.pendingTasks = remaining
|
||||
mq.mutex.Unlock()
|
||||
|
||||
// Persist cancelled state outside the lock to avoid blocking
|
||||
for _, snapshot := range cancelledSnapshots {
|
||||
mq.saveTaskState(snapshot)
|
||||
// Cancelled is terminal: drop the file like CompleteTask does instead of
|
||||
// leaving one orphaned .pb per cancelled task per scan cycle. If removal
|
||||
// fails, persist the cancelled state so a restart drops it instead of
|
||||
// re-queueing it.
|
||||
if mq.persistence != nil {
|
||||
mq.persistMu.Lock()
|
||||
for _, snapshot := range cancelledSnapshots {
|
||||
if mq.deleteTaskStateLocked(snapshot.ID) != nil {
|
||||
mq.saveTaskStateLocked(snapshot)
|
||||
}
|
||||
}
|
||||
mq.persistMu.Unlock()
|
||||
}
|
||||
return cancelled
|
||||
}
|
||||
@@ -922,7 +963,7 @@ func generateTaskID() string {
|
||||
return fmt.Sprintf("%s-%04d", string(b), timestamp)
|
||||
}
|
||||
|
||||
// CleanupOldTasks removes old completed and failed tasks
|
||||
// CleanupOldTasks removes old terminal tasks from memory
|
||||
func (mq *MaintenanceQueue) CleanupOldTasks(retention time.Duration) int {
|
||||
mq.mutex.Lock()
|
||||
defer mq.mutex.Unlock()
|
||||
@@ -931,7 +972,7 @@ func (mq *MaintenanceQueue) CleanupOldTasks(retention time.Duration) int {
|
||||
removed := 0
|
||||
|
||||
for id, task := range mq.tasks {
|
||||
if (task.Status == TaskStatusCompleted || task.Status == TaskStatusFailed) &&
|
||||
if (task.Status == TaskStatusCompleted || task.Status == TaskStatusFailed || task.Status == TaskStatusCancelled) &&
|
||||
task.CompletedAt != nil &&
|
||||
task.CompletedAt.Before(cutoff) {
|
||||
delete(mq.tasks, id)
|
||||
|
||||
@@ -218,6 +218,10 @@ type MaintenanceQueue struct {
|
||||
policy *MaintenancePolicy
|
||||
integration *MaintenanceIntegration
|
||||
persistence TaskPersistence // Interface for task persistence
|
||||
// persistMu serializes the check+write in saveTaskState against the
|
||||
// deletes in the cancel paths, so a stale pending save cannot land on
|
||||
// disk after the task's file was removed.
|
||||
persistMu sync.Mutex
|
||||
}
|
||||
|
||||
// MaintenanceScanner analyzes the cluster and generates maintenance tasks
|
||||
|
||||
@@ -32,6 +32,7 @@ var Commands = []*Command{
|
||||
cmdFix,
|
||||
cmdFuse,
|
||||
cmdIam,
|
||||
cmdImage,
|
||||
cmdMaster,
|
||||
cmdMasterFollower,
|
||||
cmdMini,
|
||||
|
||||
+14
-1
@@ -23,6 +23,7 @@ import (
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/credential/postgres"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
@@ -89,6 +90,7 @@ type FilerOptions struct {
|
||||
s3ConfigFile *string // optional path to static S3 identity config
|
||||
|
||||
allowUntrustedRemoteEndpoints *bool
|
||||
remoteCacheEvictThreshold *float64
|
||||
// shutdownCtx, when non-nil, tells startFiler to gracefully shut down its
|
||||
// HTTP/gRPC servers once the ctx is cancelled. Used by integration tests
|
||||
// and by weed mini; nil for standalone weed filer.
|
||||
@@ -134,6 +136,7 @@ func init() {
|
||||
f.tusMaxSizeMB = cmdFiler.Flag.Int("tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB")
|
||||
f.tusSessionExpiry = cmdFiler.Flag.Duration("tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration, e.g. \"48h\", \"7h30m\"")
|
||||
f.allowUntrustedRemoteEndpoints = cmdFiler.Flag.Bool("allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
f.remoteCacheEvictThreshold = cmdFiler.Flag.Float64("remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
|
||||
// start s3 on filer
|
||||
filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway")
|
||||
@@ -407,6 +410,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
CredentialManager: credentialManager,
|
||||
|
||||
AllowUntrustedRemoteEndpoints: *fo.allowUntrustedRemoteEndpoints,
|
||||
RemoteCacheEvictThreshold: *fo.remoteCacheEvictThreshold,
|
||||
})
|
||||
if nfs_err != nil {
|
||||
glog.Fatalf("Filer startup error: %v", nfs_err)
|
||||
@@ -472,9 +476,18 @@ func (fo *FilerOptions) startFiler() {
|
||||
if credentialManager != nil {
|
||||
adminSigningKey := security.SigningKey(util.GetViper().GetString("jwt.filer_signing.key"))
|
||||
iamGrpcServer := weed_server.NewIamGrpcServer(credentialManager, adminSigningKey)
|
||||
// The OIDC provider and role RPCs write where S3 servers configured with
|
||||
// filer-typed "oidcProviderStore" and "roleStore" read: this filer, at
|
||||
// the stores' default base paths.
|
||||
selfAddress := func() string { return string(filerAddress) }
|
||||
if roleStore, err := integration.NewFilerRoleStore(nil, selfAddress); err != nil {
|
||||
glog.Warningf("IAM gRPC: role RPCs disabled: %v", err)
|
||||
} else {
|
||||
iamGrpcServer.SetSTSStores(integration.NewFilerOIDCProviderStore(nil, selfAddress), roleStore)
|
||||
}
|
||||
iam_pb.RegisterSeaweedIdentityAccessManagementServer(grpcS, iamGrpcServer)
|
||||
if len(adminSigningKey) == 0 {
|
||||
glog.V(0).Info("Registered IAM gRPC service on filer (unauthenticated; set jwt.filer_signing.key in security.toml to require admin Bearer token)")
|
||||
glog.Warning("IAM gRPC service on filer is UNAUTHENTICATED: anyone who can reach this port can create users and policies, and its OIDC provider and role RPCs are refused; set jwt.filer_signing.key in security.toml to require an admin Bearer token")
|
||||
} else {
|
||||
glog.V(0).Info("Registered IAM gRPC service on filer (admin Bearer token required)")
|
||||
}
|
||||
|
||||
@@ -64,6 +64,10 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
StartTsNs: lastOffsetTs.UnixNano(),
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return processor.processedTsWatermark.Load()
|
||||
},
|
||||
Resubscribe: processor.ResubscribeCh(),
|
||||
}
|
||||
|
||||
return pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -75,6 +76,10 @@ func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *sour
|
||||
StartTsNs: lastOffsetTs.UnixNano(),
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return processor.processedTsWatermark.Load()
|
||||
},
|
||||
Resubscribe: processor.ResubscribeCh(),
|
||||
}
|
||||
|
||||
return pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
@@ -171,7 +176,6 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, *option.storageClass))
|
||||
}
|
||||
glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, *option.storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
@@ -191,20 +195,7 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
if filer_pb.IsDelete(resp) {
|
||||
// Skip deletion of internal version files; individual version
|
||||
// deletes should not propagate to the remote object
|
||||
if isVersionedPath(resp.Directory, message.OldEntry.Name, message.OldEntry.IsDirectory) {
|
||||
glog.V(2).Infof("skipping delete of internal version path: %s/%s", resp.Directory, message.OldEntry.Name)
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("delete: %+v", resp)
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
|
||||
if message.OldEntry.IsDirectory {
|
||||
glog.V(0).Infof("rmdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.RemoveDirectory(dest)
|
||||
}
|
||||
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
|
||||
return client.DeleteFile(dest)
|
||||
return processDeleteEvent(client, mountedDir, remoteStorageMountLocation, resp)
|
||||
}
|
||||
if message.OldEntry != nil && message.NewEntry != nil {
|
||||
return processUpdateEvent(option, filerSource, *option.storageClass, client, mountedDir, remoteStorageMountLocation, resp)
|
||||
@@ -215,6 +206,45 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
return eachEntryFunc, nil
|
||||
}
|
||||
|
||||
// processDeleteEvent removes the remote object an entry mapped to. A remote
|
||||
// object that is already absent counts as deleted: the entry was never
|
||||
// uploaded (created and deleted faster than the sync ran, or a replay of an
|
||||
// event the inline delete already handled), and GCS reports that case as
|
||||
// ErrRemoteObjectNotFound where S3 and Azure answer an idempotent success.
|
||||
// Returning the error would pin the sync offset on an event that has nothing
|
||||
// left to do.
|
||||
func processDeleteEvent(
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
resp *filer_pb.SubscribeMetadataResponse,
|
||||
) error {
|
||||
message := resp.EventNotification
|
||||
// Skip deletion of internal version files; individual version
|
||||
// deletes should not propagate to the remote object
|
||||
if isVersionedPath(resp.Directory, message.OldEntry.Name, message.OldEntry.IsDirectory) {
|
||||
glog.V(2).Infof("skipping delete of internal version path: %s/%s", resp.Directory, message.OldEntry.Name)
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("delete: %+v", resp)
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
|
||||
if message.OldEntry.IsDirectory {
|
||||
glog.V(0).Infof("rmdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.RemoveDirectory(dest)
|
||||
}
|
||||
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
|
||||
return deleteRemoteFile(client, dest)
|
||||
}
|
||||
|
||||
// deleteRemoteFile deletes the object and treats an already-absent object as
|
||||
// deleted.
|
||||
func deleteRemoteFile(client remote_storage.RemoteStorageClient, dest *remote_pb.RemoteStorageLocation) error {
|
||||
if err := client.DeleteFile(dest); err != nil && !errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func processUpdateEvent(
|
||||
filerClient filer_pb.FilerClient,
|
||||
filerSource filer_pb.FilerClient,
|
||||
@@ -256,12 +286,22 @@ func processUpdateEvent(
|
||||
}
|
||||
glog.V(0).Infof("never replicated, uploading %s", remote_storage.FormatLocation(dest))
|
||||
}
|
||||
if !proto.Equal(oldDest, dest) && !filer.HasData(message.NewEntry) && message.NewEntry.IsInRemoteOnly() {
|
||||
glog.V(0).Infof("skip uploading renamed remote-only entry %s: content is only on the deleted remote object", remote_storage.FormatLocation(dest))
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("update: %+v", resp)
|
||||
if !proto.Equal(oldDest, dest) {
|
||||
// A renamed entry that holds no local data now (the snapshot was
|
||||
// remote-only, or remote.uncache ran since) has its content only as a
|
||||
// remote object. Remote-only reads resolve by the entry's own path, so
|
||||
// the rename completes only once the destination object holds it. The
|
||||
// filer's current state decides, not the snapshot: an entry rewritten
|
||||
// since the event has local data again, and the rewrite's bytes are
|
||||
// what the destination must hold.
|
||||
current, err := currentEntry(filerSource, message.NewParentPath, message.NewEntry.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isRemoteOnly(current) {
|
||||
return completeRemoteOnlyRename(filerClient, client, message.NewParentPath, current, oldDest, dest, storageClass)
|
||||
}
|
||||
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
|
||||
if err := client.DeleteFile(oldDest); err != nil {
|
||||
if isMultipartUploadFile(resp.Directory, message.OldEntry.Name) {
|
||||
@@ -275,6 +315,9 @@ func processUpdateEvent(
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
if !proto.Equal(oldDest, dest) {
|
||||
return uploadCurrentEntry(filerClient, filerSource, client, message.NewParentPath, message.NewEntry.Name, oldDest, dest, storageClass)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
@@ -283,6 +326,128 @@ func processUpdateEvent(
|
||||
return updateLocalEntry(filerClient, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
|
||||
// currentEntry returns what the filer holds at dir/name now, nil when the
|
||||
// entry is gone.
|
||||
func currentEntry(filerSource filer_pb.FilerClient, dir, name string) (*filer_pb.Entry, error) {
|
||||
current, _, _, err := filer_pb.GetEntry(context.Background(), filerSource, util.NewFullPath(dir, name))
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
// isRemoteOnly reports an entry whose content exists only as its remote
|
||||
// object: no local data, a RemoteEntry with a size.
|
||||
func isRemoteOnly(entry *filer_pb.Entry) bool {
|
||||
return entry != nil && !filer.HasData(entry) && entry.IsInRemoteOnly()
|
||||
}
|
||||
|
||||
// completeRemoteOnlyRename finishes a rename whose content exists only on the
|
||||
// remote. When the destination object already holds what the entry's stamp
|
||||
// describes (the rename ran before, its offset was not persisted, and
|
||||
// remote.uncache followed), the old key goes. Otherwise the old object is
|
||||
// copied over the destination, the entry is stamped with the copy, and the
|
||||
// old key goes. With neither object present the content is lost: the event
|
||||
// fails and holds the offset for recovery.
|
||||
func completeRemoteOnlyRename(filerClient filer_pb.FilerClient, client remote_storage.RemoteStorageClient, dir string, current *filer_pb.Entry, oldDest, dest *remote_pb.RemoteStorageLocation, storageClass string) error {
|
||||
if existing, err := client.StatFile(dest); err == nil {
|
||||
if describes(current.RemoteEntry, existing) {
|
||||
glog.V(0).Infof("%s already holds the renamed content", remote_storage.FormatLocation(dest))
|
||||
return deleteRemoteFile(client, oldDest)
|
||||
}
|
||||
glog.V(0).Infof("%s holds an object the entry does not describe (size %d, want %d); replacing it from %s", remote_storage.FormatLocation(dest), existing.RemoteSize, current.RemoteEntry.RemoteSize, remote_storage.FormatLocation(oldDest))
|
||||
} else if !errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
|
||||
return err
|
||||
}
|
||||
stat, err := client.StatFile(oldDest)
|
||||
if errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
|
||||
return fmt.Errorf("%s: content is on neither %s nor %s", util.NewFullPath(dir, current.Name), remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(dest))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reader, err := openRemoteObject(client, oldDest, stat.RemoteSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
glog.V(0).Infof("copy %s -> %s", remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(dest))
|
||||
remoteEntry, err := client.WriteFile(dest, remoteWriteEntry(current, storageClass), reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := updateLocalEntry(filerClient, dir, current, remoteEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
return deleteRemoteFile(client, oldDest)
|
||||
}
|
||||
|
||||
// describes reports whether the object a stat returned is the one the entry's
|
||||
// stamp describes: same size, and the same ETag when both sides carry one (a
|
||||
// copy written as one stream can legitimately carry a different ETag from a
|
||||
// multipart original).
|
||||
func describes(stamp, object *filer_pb.RemoteEntry) bool {
|
||||
if stamp == nil || object == nil || stamp.RemoteSize != object.RemoteSize {
|
||||
return false
|
||||
}
|
||||
return stamp.RemoteETag == "" || object.RemoteETag == "" || stamp.RemoteETag == object.RemoteETag
|
||||
}
|
||||
|
||||
// openRemoteObject streams the object when the client can, and reads it whole
|
||||
// otherwise.
|
||||
func openRemoteObject(client remote_storage.RemoteStorageClient, loc *remote_pb.RemoteStorageLocation, size int64) (io.ReadCloser, error) {
|
||||
if streamer, ok := client.(remote_storage.RemoteStorageStreamReader); ok {
|
||||
return streamer.ReadFileAsStream(context.Background(), loc, 0, size)
|
||||
}
|
||||
data, err := client.ReadFile(loc, 0, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(data)), nil
|
||||
}
|
||||
|
||||
// uploadCurrentEntry uploads what the filer holds at dir/name now, when the
|
||||
// event that superseded this rename will not. A rename whose snapshot is
|
||||
// superseded has already deleted the old key; the rewrite behind it in the
|
||||
// log uploads the destination itself unless shouldSendToRemote skips it on
|
||||
// the inherited RemoteEntry, whose RemoteMtime can equal the rewrite's mtime
|
||||
// within the same second. Only that case uploads here, so the content goes
|
||||
// up once. A remote-only entry is finished the way completeRemoteOnlyRename
|
||||
// finishes a rename: its stamp can already describe the destination (a sync
|
||||
// plus remote.uncache in the meantime), and only then is it complete.
|
||||
func uploadCurrentEntry(filerClient filer_pb.FilerClient, filerSource filer_pb.FilerClient, client remote_storage.RemoteStorageClient, dir, name string, oldDest, dest *remote_pb.RemoteStorageLocation, storageClass string) error {
|
||||
current, _, _, err := filer_pb.GetEntry(context.Background(), filerSource, util.NewFullPath(dir, name))
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.IsDirectory {
|
||||
return nil
|
||||
}
|
||||
if isRemoteOnly(current) {
|
||||
return completeRemoteOnlyRename(filerClient, client, dir, current, oldDest, dest, storageClass)
|
||||
}
|
||||
if shouldSendToRemote(current) {
|
||||
glog.V(0).Infof("leaving %s to the rewrite that superseded the rename", remote_storage.FormatLocation(dest))
|
||||
return nil
|
||||
}
|
||||
glog.V(0).Infof("uploading the current %s in place of the superseded rename", remote_storage.FormatLocation(dest))
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, dir, remoteWriteEntry(current, storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
return updateLocalEntry(filerClient, dir, current, remoteEntry)
|
||||
}
|
||||
|
||||
// isSuperseded reports whether the filer has moved past the entry an event
|
||||
// described: it is deleted, or it no longer references every chunk the event
|
||||
// named. Those are the chunks the filer deletes when an entry is updated, so
|
||||
@@ -304,6 +469,12 @@ func isSuperseded(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !filer.HasData(entry) && filer.HasData(current) {
|
||||
// The event described an entry without data (remote-only, or empty);
|
||||
// the filer has written to it since. Uploading the snapshot would put
|
||||
// an empty object where the write belongs.
|
||||
return true
|
||||
}
|
||||
if len(entry.Content) > 0 || len(current.Content) > 0 {
|
||||
return !bytes.Equal(entry.Content, current.Content)
|
||||
}
|
||||
@@ -314,11 +485,18 @@ func isSuperseded(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.
|
||||
// moved past (isSuperseded). The caller skips the event instead of failing it.
|
||||
var errSuperseded = errors.New("deleted or rewritten since the event was logged")
|
||||
|
||||
// retriedWriteFile uploads the entry, retrying transient failures. Every failed
|
||||
// attempt first asks the filer whether the entry is superseded, and stops at
|
||||
// once when it is: a dead chunk reads as a transient "RequestError" from the
|
||||
// SDK, and waiting out the backoff on it buys nothing.
|
||||
// retriedWriteFile uploads the entry, retrying transient failures. The filer is
|
||||
// asked whether the entry is superseded before the first attempt and after
|
||||
// every failed one, and the upload stops at once when it is. Before: a backlog
|
||||
// (a restart resuming from an old offset) carries every intermediate version
|
||||
// of a hot file, and uploading each one in turn is wasted bandwidth that can
|
||||
// trip the remote's per-object mutation rate limit; only the version the filer
|
||||
// still holds is worth sending. After: a dead chunk reads as a transient
|
||||
// "RequestError" from the SDK, and waiting out the backoff on it buys nothing.
|
||||
func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource filer_pb.FilerClient, dir string, newEntry *filer_pb.Entry, dest *remote_pb.RemoteStorageLocation) (remoteEntry *filer_pb.RemoteEntry, err error) {
|
||||
if isSuperseded(filerSource, dir, newEntry) {
|
||||
return nil, fmt.Errorf("%s %w", util.NewFullPath(dir, newEntry.Name), errSuperseded)
|
||||
}
|
||||
err = util.RetryOnError("writeFile", func(err error) bool {
|
||||
return !errors.Is(err, errSuperseded) && util.IsTransientError(err)
|
||||
}, func() error {
|
||||
@@ -362,6 +540,11 @@ func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc
|
||||
}
|
||||
} else {
|
||||
lastOffsetTs = time.Now().Add(-timeAgo)
|
||||
if lastOffsetTsNs, err := remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir); err == nil && lastOffsetTsNs > 0 {
|
||||
if savedOffsetTs := time.Unix(0, lastOffsetTsNs); savedOffsetTs.Before(lastOffsetTs) {
|
||||
lastOffsetTs = savedOffsetTs
|
||||
}
|
||||
}
|
||||
}
|
||||
return lastOffsetTs
|
||||
}
|
||||
@@ -453,9 +636,29 @@ func updateLocalEntry(filerClient filer_pb.FilerClient, dir string, entry *filer
|
||||
glog.Errorf("skipping stale stamp of %s: %v", util.NewFullPath(dir, entry.Name), err)
|
||||
return nil
|
||||
}
|
||||
if isEntryGone(err) {
|
||||
glog.Errorf("skipping stamp of %s: deleted since the event was logged: %v", util.NewFullPath(dir, entry.Name), err)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// isEntryGone reports an UpdateEntry the filer refused because the entry no
|
||||
// longer exists: a delete that followed the event superseded the stamp, and
|
||||
// the delete's own event follows in the log. A filer with the typed answer
|
||||
// returns codes.NotFound; an older filer returns a plain error of the form
|
||||
// "not found <path>: <cause>", so the cause (the message's tail, never the
|
||||
// path) is matched against filer_pb.ErrNotFound's text.
|
||||
func isEntryGone(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if st, ok := status.FromError(err); ok && st.Code() == codes.NotFound {
|
||||
return true
|
||||
}
|
||||
return strings.HasSuffix(strings.TrimSpace(err.Error()), filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
|
||||
// ifEntryEqual builds the precondition that the stored entry still equals the
|
||||
// one the event described: chunk fids, inline content, and metadata alike.
|
||||
func ifEntryEqual(entry *filer_pb.Entry) *filer_pb.WriteCondition {
|
||||
@@ -501,7 +704,7 @@ func syncDeleteMarker(
|
||||
dest *remote_pb.RemoteStorageLocation,
|
||||
) error {
|
||||
glog.V(0).Infof("delete (marker) %s", remote_storage.FormatLocation(dest))
|
||||
if err := client.DeleteFile(dest); err != nil {
|
||||
if err := deleteRemoteFile(client, dest); err != nil {
|
||||
return err
|
||||
}
|
||||
return updateLocalEntry(filerClient, message.NewParentPath, message.NewEntry, &filer_pb.RemoteEntry{
|
||||
|
||||
@@ -415,9 +415,11 @@ func TestIsMetadataOnlyUpdate(t *testing.T) {
|
||||
// every lookup instead.
|
||||
type stubFilerClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
entry *filer_pb.Entry
|
||||
err error
|
||||
lookups int
|
||||
entry *filer_pb.Entry
|
||||
err error
|
||||
updateErr error
|
||||
lookups int
|
||||
updates int
|
||||
}
|
||||
|
||||
func (c *stubFilerClient) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest, ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
@@ -429,6 +431,10 @@ func (c *stubFilerClient) LookupDirectoryEntry(context.Context, *filer_pb.Lookup
|
||||
}
|
||||
|
||||
func (c *stubFilerClient) UpdateEntry(context.Context, *filer_pb.UpdateEntryRequest, ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
|
||||
c.updates++
|
||||
if c.updateErr != nil {
|
||||
return &filer_pb.UpdateEntryResponse{}, c.updateErr
|
||||
}
|
||||
return &filer_pb.UpdateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
@@ -549,6 +555,23 @@ func TestIsSuperseded(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("written since: the event described an entry without data", func(t *testing.T) {
|
||||
remoteOnly := entryWith("video.mp4", &filer_pb.RemoteEntry{StorageName: "b2", RemoteSize: 20971520, RemoteMtime: 1786096669})
|
||||
if !isSuperseded(&stubFilerClient{entry: entryWith("video.mp4", remoteOnly.RemoteEntry, chunk("3,09", "e9"))}, dir, remoteOnly) {
|
||||
t.Error("isSuperseded = false, want true: the filer wrote local data to a remote-only entry")
|
||||
}
|
||||
if isSuperseded(&stubFilerClient{entry: entryWith("video.mp4", remoteOnly.RemoteEntry)}, dir, remoteOnly) {
|
||||
t.Error("isSuperseded = true, want false: the entry is still remote-only")
|
||||
}
|
||||
empty := &filer_pb.Entry{Name: "touch.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
if !isSuperseded(&stubFilerClient{entry: &filer_pb.Entry{Name: "touch.txt", Content: []byte("now")}}, dir, empty) {
|
||||
t.Error("isSuperseded = false, want true: the empty file was written to")
|
||||
}
|
||||
if isSuperseded(&stubFilerClient{entry: &filer_pb.Entry{Name: "touch.txt"}}, dir, empty) {
|
||||
t.Error("isSuperseded = true, want false: the file is still empty")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("inline content rewritten since", func(t *testing.T) {
|
||||
event := &filer_pb.Entry{Name: "note.txt", Content: []byte("v1")}
|
||||
if !isSuperseded(&stubFilerClient{entry: &filer_pb.Entry{Name: "note.txt", Content: []byte("v2")}}, dir, event) {
|
||||
@@ -584,7 +607,7 @@ func TestRetriedWriteFileStopsWhenSuperseded(t *testing.T) {
|
||||
// "requesterror" makes IsTransientError retry it to exhaustion.
|
||||
deadChunk := errors.New("RequestError: send request failed\ncaused by: Put \"https://s3.example.com/tier/x\": http://volume:8444/3,01?readDeleted=true: 404 Not Found: not found")
|
||||
|
||||
t.Run("superseded, one attempt", func(t *testing.T) {
|
||||
t.Run("superseded before the first attempt, no write", func(t *testing.T) {
|
||||
remote := &failingRemote{err: deadChunk}
|
||||
filerClient := &stubFilerClient{}
|
||||
start := time.Now()
|
||||
@@ -592,17 +615,32 @@ func TestRetriedWriteFileStopsWhenSuperseded(t *testing.T) {
|
||||
if !errors.Is(err, errSuperseded) {
|
||||
t.Errorf("err = %v, want errSuperseded", err)
|
||||
}
|
||||
if remote.writes != 0 {
|
||||
t.Errorf("wrote %d times, want 0: a superseded version is not worth uploading", remote.writes)
|
||||
}
|
||||
if filerClient.lookups != 1 {
|
||||
t.Errorf("looked up the filer %d times, want 1", filerClient.lookups)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 500*time.Millisecond {
|
||||
t.Errorf("took %v, want no backoff", elapsed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("superseded during the attempt, one write", func(t *testing.T) {
|
||||
remote := &failingRemote{err: deadChunk}
|
||||
filerClient := &supersedingFilerClient{live: entryWith(event.Name, nil, chunk("3,01", "e1"))}
|
||||
_, err := retriedWriteFile(remote, filerClient, dir, event, dest)
|
||||
if !errors.Is(err, errSuperseded) {
|
||||
t.Errorf("err = %v, want errSuperseded", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "404 Not Found") {
|
||||
t.Errorf("err = %v, want it to keep the write failure", err)
|
||||
}
|
||||
if remote.writes != 1 {
|
||||
t.Errorf("wrote %d times, want 1: retrying a dead chunk cannot succeed", remote.writes)
|
||||
}
|
||||
if filerClient.lookups != 1 {
|
||||
t.Errorf("looked up the filer %d times, want 1", filerClient.lookups)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 500*time.Millisecond {
|
||||
t.Errorf("took %v, want no backoff", elapsed)
|
||||
if filerClient.lookups != 2 {
|
||||
t.Errorf("looked up the filer %d times, want one before the attempt and one after it failed", filerClient.lookups)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -619,8 +657,8 @@ func TestRetriedWriteFileStopsWhenSuperseded(t *testing.T) {
|
||||
if remote.writes != 2 {
|
||||
t.Errorf("wrote %d times, want 2: a transient failure on a live entry is still retried", remote.writes)
|
||||
}
|
||||
if filerClient.lookups != 2 {
|
||||
t.Errorf("looked up the filer %d times, want one per failed attempt", filerClient.lookups)
|
||||
if filerClient.lookups != 3 {
|
||||
t.Errorf("looked up the filer %d times, want one before the first attempt and one per failed attempt", filerClient.lookups)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -639,16 +677,51 @@ func TestRetriedWriteFileStopsWhenSuperseded(t *testing.T) {
|
||||
|
||||
type recordingRemote struct {
|
||||
remote_storage.RemoteStorageClient
|
||||
deletes []*remote_pb.RemoteStorageLocation
|
||||
writes []*remote_pb.RemoteStorageLocation
|
||||
deleteErr error
|
||||
deletes []*remote_pb.RemoteStorageLocation
|
||||
writes []*remote_pb.RemoteStorageLocation
|
||||
written [][]byte
|
||||
// chunk ids of each written entry: which version of the file went up
|
||||
writtenChunks [][]string
|
||||
deleteErr error
|
||||
// objects present on the remote, by path: StatFile and ReadFile answer
|
||||
// from it, everything else is ErrRemoteObjectNotFound.
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func (r *recordingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, _ io.Reader) (*filer_pb.RemoteEntry, error) {
|
||||
func (r *recordingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) {
|
||||
r.writes = append(r.writes, loc)
|
||||
var ids []string
|
||||
for _, c := range entry.GetChunks() {
|
||||
ids = append(ids, c.GetFileIdString())
|
||||
}
|
||||
r.writtenChunks = append(r.writtenChunks, ids)
|
||||
// A chunked upload's reader walks volume servers the stub filer cannot
|
||||
// name, so it is not read; the copy path hands over the old object's
|
||||
// stream for a chunkless entry, which is drained.
|
||||
var body []byte
|
||||
if rc, ok := reader.(io.ReadCloser); ok && len(entry.GetChunks()) == 0 && r.objects != nil {
|
||||
body, _ = io.ReadAll(rc)
|
||||
}
|
||||
r.written = append(r.written, body)
|
||||
return &filer_pb.RemoteEntry{StorageName: loc.Name, RemoteETag: "etag", RemoteSize: int64(len(entry.Content)), RemoteMtime: entry.Attributes.GetMtime()}, nil
|
||||
}
|
||||
|
||||
func (r *recordingRemote) StatFile(loc *remote_pb.RemoteStorageLocation) (*filer_pb.RemoteEntry, error) {
|
||||
body, ok := r.objects[loc.Path]
|
||||
if !ok {
|
||||
return nil, remote_storage.ErrRemoteObjectNotFound
|
||||
}
|
||||
return &filer_pb.RemoteEntry{StorageName: loc.Name, RemoteSize: int64(len(body))}, nil
|
||||
}
|
||||
|
||||
func (r *recordingRemote) ReadFile(loc *remote_pb.RemoteStorageLocation, offset int64, size int64) ([]byte, error) {
|
||||
body, ok := r.objects[loc.Path]
|
||||
if !ok {
|
||||
return nil, remote_storage.ErrRemoteObjectNotFound
|
||||
}
|
||||
return body[offset : offset+size], nil
|
||||
}
|
||||
|
||||
func (r *recordingRemote) DeleteFile(loc *remote_pb.RemoteStorageLocation) error {
|
||||
r.deletes = append(r.deletes, loc)
|
||||
return r.deleteErr
|
||||
@@ -685,7 +758,8 @@ func TestRenameWithInheritedRemoteEntryWritesNewKey(t *testing.T) {
|
||||
}
|
||||
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{}
|
||||
// the filer still holds the renamed entry as the event described it
|
||||
filerClient := &stubFilerClient{entry: newEntry}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -801,7 +875,8 @@ func TestRenameDeleteOldKeyNotFoundStillWrites(t *testing.T) {
|
||||
}
|
||||
|
||||
remote := &recordingRemote{deleteErr: remote_storage.ErrRemoteObjectNotFound}
|
||||
filerClient := &stubFilerClient{}
|
||||
// the filer still holds the renamed entry as the event described it
|
||||
filerClient := &stubFilerClient{entry: newEntry}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil: an already-deleted old key must not block the write", err)
|
||||
}
|
||||
@@ -880,3 +955,336 @@ func TestIsFailedPrecondition(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// supersedingFilerClient answers the first lookup with the live entry and
|
||||
// every later one with "not found": the entry is deleted while the upload is
|
||||
// in flight.
|
||||
type supersedingFilerClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
live *filer_pb.Entry
|
||||
lookups int
|
||||
}
|
||||
|
||||
func (c *supersedingFilerClient) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest, ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
c.lookups++
|
||||
if c.lookups == 1 {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: c.live}, nil
|
||||
}
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
func (c *supersedingFilerClient) WithFilerClient(_ bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return fn(c)
|
||||
}
|
||||
|
||||
func (c *supersedingFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url }
|
||||
|
||||
func (c *supersedingFilerClient) GetDataCenter() string { return "" }
|
||||
|
||||
// TestDeleteEventAbsentRemoteObjectIsSuccess: an entry created and deleted
|
||||
// before the sync uploaded it has no remote object. GCS reports the delete as
|
||||
// ErrRemoteObjectNotFound; the event has nothing left to do, so it must not
|
||||
// fail (a failed event pins the sync offset and is replayed on every restart).
|
||||
func TestDeleteEventAbsentRemoteObjectIsSuccess(t *testing.T) {
|
||||
const mountedDir = "/buckets"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/"}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/b/vol",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "state.db.tmp", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}},
|
||||
DeleteChunks: true,
|
||||
},
|
||||
}
|
||||
wantDelete := &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/b/vol/state.db.tmp"}
|
||||
|
||||
t.Run("absent object", func(t *testing.T) {
|
||||
remote := &recordingRemote{deleteErr: remote_storage.ErrRemoteObjectNotFound}
|
||||
if err := processDeleteEvent(remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil: deleting an absent object is complete", err)
|
||||
}
|
||||
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], wantDelete) {
|
||||
t.Errorf("deletes = %+v, want %s", remote.deletes, remote_storage.FormatLocation(wantDelete))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("other failure still fails", func(t *testing.T) {
|
||||
remote := &recordingRemote{deleteErr: errors.New("AccessDenied: Access Denied")}
|
||||
if err := processDeleteEvent(remote, mountedDir, mountLoc, resp); err == nil {
|
||||
t.Fatal("err = nil, want the delete failure")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("delete marker, absent object", func(t *testing.T) {
|
||||
remote := &recordingRemote{deleteErr: remote_storage.ErrRemoteObjectNotFound}
|
||||
filerClient := &stubFilerClient{}
|
||||
markerDelete := &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/b/vol/state.db"}
|
||||
message := &filer_pb.EventNotification{
|
||||
NewParentPath: "/buckets/b/vol",
|
||||
NewEntry: &filer_pb.Entry{Name: "state.db", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}},
|
||||
}
|
||||
if err := syncDeleteMarker(remote, filerClient, message, markerDelete); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], markerDelete) {
|
||||
t.Errorf("deletes = %+v, want %s", remote.deletes, remote_storage.FormatLocation(markerDelete))
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("stamped %d times, want 1: the marker is recorded locally so a replay is a no-op", filerClient.updates)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestUpdateLocalEntrySkipsDeletedEntry: the stamp that follows an upload lands
|
||||
// on an entry a later event already deleted. The filer answers "not found"; the
|
||||
// delete's own event follows in the log, so the stamp is skipped rather than
|
||||
// failed.
|
||||
func TestUpdateLocalEntrySkipsDeletedEntry(t *testing.T) {
|
||||
const dir = "/buckets/b/vol"
|
||||
remoteEntry := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteSize: 7}
|
||||
|
||||
t.Run("plain not found from the filer", func(t *testing.T) {
|
||||
filerClient := &stubFilerClient{updateErr: fmt.Errorf("not found %s: %w", dir+"/state.db", filer_pb.ErrNotFound)}
|
||||
if err := updateLocalEntry(filerClient, dir, entryWith("state.db", nil, chunk("3,01", "e1")), remoteEntry); err != nil {
|
||||
t.Errorf("err = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("not found over grpc", func(t *testing.T) {
|
||||
filerClient := &stubFilerClient{updateErr: status.Error(codes.Unknown, "not found "+dir+"/state.db: "+filer_pb.ErrNotFound.Error())}
|
||||
if err := updateLocalEntry(filerClient, dir, entryWith("state.db", nil, chunk("3,01", "e1")), remoteEntry); err != nil {
|
||||
t.Errorf("err = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("typed not found from the filer", func(t *testing.T) {
|
||||
filerClient := &stubFilerClient{updateErr: status.Errorf(codes.NotFound, "not found %s/state.db: %v", dir, filer_pb.ErrNotFound)}
|
||||
if err := updateLocalEntry(filerClient, dir, entryWith("state.db", nil, chunk("3,01", "e1")), remoteEntry); err != nil {
|
||||
t.Errorf("err = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the sentinel inside the path is not a missing entry", func(t *testing.T) {
|
||||
name := filer_pb.ErrNotFound.Error()
|
||||
filerClient := &stubFilerClient{updateErr: status.Error(codes.Unknown, "not found "+dir+"/"+name+": database unavailable")}
|
||||
if err := updateLocalEntry(filerClient, dir, entryWith(name, nil, chunk("3,01", "e1")), remoteEntry); err == nil {
|
||||
t.Error("err = nil, want the store failure: the stamp must be retried, not dropped")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("other failure still fails", func(t *testing.T) {
|
||||
filerClient := &stubFilerClient{updateErr: status.Error(codes.Unavailable, "filer is shutting down")}
|
||||
if err := updateLocalEntry(filerClient, dir, entryWith("state.db", nil, chunk("3,01", "e1")), remoteEntry); err == nil {
|
||||
t.Error("err = nil, want the update failure")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestSupersededRenameUploadsCurrentEntry: a rename A -> B queued behind a
|
||||
// rewrite of B. The rename's snapshot is superseded (B's chunks changed) and
|
||||
// the old key A is already deleted. The rewrite's own event uploads B unless
|
||||
// shouldSendToRemote skips it on the inherited RemoteEntry (same-second
|
||||
// mtimes); only then does the rename upload what the filer holds now, so the
|
||||
// content goes up exactly once.
|
||||
func TestSupersededRenameUploadsCurrentEntry(t *testing.T) {
|
||||
const mountedDir = "/buckets"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/"}
|
||||
eventEntry := entryWith("b.txt", nil, chunk("3,01", "e1"))
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/b/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: entryWith("a.txt", nil, chunk("3,01", "e1")),
|
||||
NewParentPath: "/buckets/b/dir",
|
||||
NewEntry: eventEntry,
|
||||
},
|
||||
}
|
||||
wantDelete := &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/b/dir/a.txt"}
|
||||
wantWrite := &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/b/dir/b.txt"}
|
||||
|
||||
t.Run("rewrite hidden by the inherited stamp: upload once here", func(t *testing.T) {
|
||||
// RemoteMtime inherited from a.txt equals the rewrite's mtime.
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 1024}, chunk("3,02", "e2"))
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], wantDelete) {
|
||||
t.Errorf("deletes = %+v, want the old key %s deleted", remote.deletes, remote_storage.FormatLocation(wantDelete))
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Fatalf("writes = %+v, want the new key %s written once with the current entry", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("stamped %d times, want 1: the current entry is stamped", filerClient.updates)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rewrite newer than the stamp: its own event uploads, not this one", func(t *testing.T) {
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096000, RemoteSize: 1024}, chunk("3,02", "e2"))
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.deletes) != 1 {
|
||||
t.Errorf("deletes = %+v, want the old key deleted", remote.deletes)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none: the rewrite event behind this one uploads b.txt", remote.writes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("deleted meanwhile: nothing to upload", func(t *testing.T) {
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none: the delete event follows", remote.writes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("uncached meanwhile, old object present: copied to the destination, stamped, old key deleted", func(t *testing.T) {
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) || string(remote.written[0]) != "payload" {
|
||||
t.Fatalf("writes = %+v (%q), want the old object's bytes written at %s", remote.writes, remote.written, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("stamped %d times, want 1: the entry now points at the destination object", filerClient.updates)
|
||||
}
|
||||
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], wantDelete) {
|
||||
t.Errorf("deletes = %+v, want the old key deleted after the copy", remote.deletes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("uncached after an earlier run completed the rename: destination present, old key deleted, nothing written", func(t *testing.T) {
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload"), "/b/dir/b.txt": []byte("payload")}}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil: the replayed rename is already complete", err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none", remote.writes)
|
||||
}
|
||||
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], wantDelete) {
|
||||
t.Errorf("deletes = %+v, want the old key deleted", remote.deletes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("uncached and neither object exists: the event fails and holds the offset", func(t *testing.T) {
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp)
|
||||
if err == nil || !strings.Contains(err.Error(), "neither") {
|
||||
t.Fatalf("err = %v, want the lost-content failure", err)
|
||||
}
|
||||
if len(remote.writes) != 0 || len(remote.deletes) != 0 {
|
||||
t.Errorf("writes = %+v deletes = %+v, want none", remote.writes, remote.deletes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("destination holds an object of another size: replaced from the old key", func(t *testing.T) {
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload"), "/b/dir/b.txt": []byte("something else")}}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.writes) != 1 || string(remote.written[0]) != "payload" {
|
||||
t.Fatalf("writes = %+v (%q), want the old object copied over the destination", remote.writes, remote.written)
|
||||
}
|
||||
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], wantDelete) {
|
||||
t.Errorf("deletes = %+v, want the old key deleted after the copy", remote.deletes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("snapshot remote-only but rewritten since: the rewrite's bytes go up, nothing is copied", func(t *testing.T) {
|
||||
remoteOnly := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
|
||||
snapshot := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/b/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: entryWith("a.txt", remoteOnly),
|
||||
NewParentPath: "/buckets/b/dir",
|
||||
NewEntry: entryWith("b.txt", remoteOnly),
|
||||
},
|
||||
}
|
||||
// rewritten with the inherited stamp still hiding it from shouldSendToRemote
|
||||
current := entryWith("b.txt", remoteOnly, chunk("3,09", "e9"))
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, snapshot); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Fatalf("writes = %+v, want one upload of the rewritten b.txt", remote.writes)
|
||||
}
|
||||
if len(remote.writtenChunks[0]) != 1 || remote.writtenChunks[0][0] != "3,09" {
|
||||
t.Errorf("uploaded chunks = %v, want the rewrite's chunk 3,09, not the chunkless snapshot", remote.writtenChunks[0])
|
||||
}
|
||||
if string(remote.written[0]) == "payload" {
|
||||
t.Error("the old object's bytes were copied over a rewritten entry")
|
||||
}
|
||||
if len(remote.deletes) != 1 {
|
||||
t.Errorf("deletes = %+v, want the old key deleted", remote.deletes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("snapshot already remote-only: completed the same way", func(t *testing.T) {
|
||||
remoteOnly := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
|
||||
snapshot := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/b/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: entryWith("a.txt", remoteOnly),
|
||||
NewParentPath: "/buckets/b/dir",
|
||||
NewEntry: entryWith("b.txt", remoteOnly),
|
||||
},
|
||||
}
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}
|
||||
filerClient := &stubFilerClient{entry: entryWith("b.txt", remoteOnly)}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, snapshot); err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
if len(remote.writes) != 1 || string(remote.written[0]) != "payload" {
|
||||
t.Errorf("writes = %+v (%q), want the old object copied to the destination", remote.writes, remote.written)
|
||||
}
|
||||
if len(remote.deletes) != 1 {
|
||||
t.Errorf("deletes = %+v, want the old key deleted after the copy", remote.deletes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("uncached after the old key was deleted: the event fails and holds the offset", func(t *testing.T) {
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 1024})
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", wantDelete, wantWrite, "")
|
||||
if err == nil || !strings.Contains(err.Error(), "neither") {
|
||||
t.Errorf("err = %v, want the lost-content failure", err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none", remote.writes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("uncached with the destination already synced: complete without a write", func(t *testing.T) {
|
||||
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/b.txt": []byte("payload")}}
|
||||
filerClient := &stubFilerClient{entry: current}
|
||||
if err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", wantDelete, wantWrite, ""); err != nil {
|
||||
t.Fatalf("err = %v, want nil: the destination object matches the entry's stamp", err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none", remote.writes)
|
||||
}
|
||||
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], wantDelete) {
|
||||
t.Errorf("deletes = %+v, want the old key deleted", remote.deletes)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -174,17 +174,24 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
|
||||
// per-cluster HTTPS clients for volume server connections
|
||||
var httpClientA, httpClientB *util_http_client.HTTPClient
|
||||
var jwtForFilerA, jwtForFilerB security.FilerJwtProvider
|
||||
if *syncOptions.aSecurity != "" {
|
||||
var err error
|
||||
if httpClientA, err = security.LoadHTTPClientFromFile(*syncOptions.aSecurity); err != nil {
|
||||
glog.Fatalf("load HTTPS client config for filer A: %v", err)
|
||||
}
|
||||
if jwtForFilerA, err = security.LoadFilerJwtFromFile(*syncOptions.aSecurity); err != nil {
|
||||
glog.Fatalf("load filer JWT config for filer A: %v", err)
|
||||
}
|
||||
}
|
||||
if *syncOptions.bSecurity != "" {
|
||||
var err error
|
||||
if httpClientB, err = security.LoadHTTPClientFromFile(*syncOptions.bSecurity); err != nil {
|
||||
glog.Fatalf("load HTTPS client config for filer B: %v", err)
|
||||
}
|
||||
if jwtForFilerB, err = security.LoadFilerJwtFromFile(*syncOptions.bSecurity); err != nil {
|
||||
glog.Fatalf("load filer JWT config for filer B: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
grace.SetupProfiling(*syncCpuProfile, *syncMemProfile)
|
||||
@@ -263,7 +270,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
bFilerSignature,
|
||||
&syncStateA2B,
|
||||
httpClientA,
|
||||
httpClientB)
|
||||
httpClientB,
|
||||
jwtForFilerA,
|
||||
jwtForFilerB)
|
||||
if err != nil {
|
||||
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
|
||||
time.Sleep(1747 * time.Millisecond)
|
||||
@@ -306,7 +315,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
aFilerSignature,
|
||||
&syncStateB2A,
|
||||
httpClientB,
|
||||
httpClientA)
|
||||
httpClientA,
|
||||
jwtForFilerB,
|
||||
jwtForFilerA)
|
||||
if err != nil {
|
||||
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
|
||||
time.Sleep(2147 * time.Millisecond)
|
||||
@@ -336,7 +347,8 @@ func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAdd
|
||||
|
||||
func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceExcludePaths []string, sourceReadChunkFromFiler bool, targetGrpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, targetPath string,
|
||||
replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, chunkConcurrency int, doDeleteFiles bool, sourceFilerSignature int32, targetFilerSignature int32, statePtr *atomic.Pointer[syncState],
|
||||
sourceHttpClient *util_http_client.HTTPClient, sinkHttpClient *util_http_client.HTTPClient) error {
|
||||
sourceHttpClient *util_http_client.HTTPClient, sinkHttpClient *util_http_client.HTTPClient,
|
||||
sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider) error {
|
||||
|
||||
// if first time, start from now
|
||||
// if has previously synced, resume from that point of time
|
||||
@@ -357,12 +369,18 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
if sourceHttpClient != nil {
|
||||
filerSource.SetHttpClient(sourceHttpClient)
|
||||
}
|
||||
if sourceJwtProvider != nil {
|
||||
filerSource.SetFilerJwtProvider(sourceJwtProvider)
|
||||
}
|
||||
filerSink := &filersink.FilerSink{}
|
||||
filerSink.DoInitialize(targetFiler.ToHttpAddress(), targetFiler.ToGrpcAddress(), targetPath, replicationStr, collection, ttlSec, diskType, targetGrpcDialOption, sinkWriteChunkByFiler)
|
||||
filerSink.SetChunkConcurrency(chunkConcurrency)
|
||||
if sinkHttpClient != nil {
|
||||
filerSink.SetUploader(operation.NewUploaderWithHttpClient(sinkHttpClient))
|
||||
}
|
||||
if sinkJwtProvider != nil {
|
||||
filerSink.SetFilerJwtProvider(sinkJwtProvider)
|
||||
}
|
||||
filerSink.SetSourceFiler(filerSource)
|
||||
|
||||
persistEventFn := genProcessFunction(sourcePath, targetPath, sourceExcludePaths, nil, nil, nil, filerSink, doDeleteFiles, debug)
|
||||
@@ -475,6 +493,10 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
StartTsNs: sourceFilerOffsetTsNs,
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return processor.processedTsWatermark.Load()
|
||||
},
|
||||
Resubscribe: processor.ResubscribeCh(),
|
||||
// While the source has only read activity it emits no metadata events, so
|
||||
// the watermark above never advances and sync_offset would look stuck.
|
||||
// The idle heartbeat moves the gauge to the source's current time once we
|
||||
|
||||
+160
-23
@@ -16,6 +16,11 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// maxFailedSyncEvents bounds the failedTs ledger. A destination rejecting
|
||||
// every event would otherwise add an entry per source event for the life of
|
||||
// the processor.
|
||||
var maxFailedSyncEvents = 1 << 16
|
||||
|
||||
// tsMinHeap implements heap.Interface for int64 timestamps.
|
||||
type tsMinHeap []int64
|
||||
|
||||
@@ -60,6 +65,16 @@ type syncJobPaths struct {
|
||||
dataSize int64
|
||||
}
|
||||
|
||||
// failedEventKey identifies an event for the failure ledger. A timestamp alone
|
||||
// is not unique across events, so a success for one event must not clear an
|
||||
// unresolved failure recorded for a different event at the same TsNs.
|
||||
type failedEventKey struct {
|
||||
tsNs int64
|
||||
path util.FullPath
|
||||
newPath util.FullPath
|
||||
kind jobKind
|
||||
}
|
||||
|
||||
// syncStreamMetrics holds the metric children for one sync stream, curried
|
||||
// once so per-event updates skip the label lookup.
|
||||
type syncStreamMetrics struct {
|
||||
@@ -74,12 +89,18 @@ type syncStreamMetrics struct {
|
||||
}
|
||||
|
||||
type MetadataProcessor struct {
|
||||
activeJobs map[int64]*syncJobPaths
|
||||
// activeJobCount is the number of in-flight jobs and activeJobTs counts
|
||||
// them per event timestamp. Several events can share a TsNs — batched
|
||||
// writes log together — so a single slot per TsNs would drain early and
|
||||
// let the resubscribe or the watermark outrun a sibling still running.
|
||||
activeJobCount int
|
||||
activeJobTs map[int64]int
|
||||
activeJobsLock sync.Mutex
|
||||
activeJobsCond *sync.Cond
|
||||
concurrencyLimit int
|
||||
fn pb.ProcessMetadataFunc
|
||||
processedTsWatermark atomic.Int64
|
||||
filteredTsNs int64
|
||||
|
||||
// Indexes for O(depth) conflict detection, replacing O(n) linear scan.
|
||||
// activeFilePaths counts active file jobs at each exact path.
|
||||
@@ -105,12 +126,35 @@ type MetadataProcessor struct {
|
||||
// used for O(log n) amortized watermark tracking.
|
||||
tsHeap tsMinHeap
|
||||
|
||||
// oldestFailedTsNs is the timestamp of the oldest event whose job returned
|
||||
// an error, or 0 when none has. The watermark is never advanced to it or
|
||||
// past it, so the persisted sync offset stays behind the failure and a
|
||||
// restart replays the event instead of skipping it forever.
|
||||
// failedTs records every event whose job returned an error and has not
|
||||
// since completed, and oldestFailedTsNs caches its minimum (0 when empty).
|
||||
// The watermark is never advanced to it or past it, so the persisted sync
|
||||
// offset stays behind the failure and a restart replays the event instead
|
||||
// of skipping it forever. Past maxFailedSyncEvents the set collapses to a
|
||||
// sticky pin at the smallest failure seen: replay from the oldest failure
|
||||
// still works, but individual recoveries no longer unpin until a restart.
|
||||
failedTs map[failedEventKey]struct{}
|
||||
failedSticky bool
|
||||
oldestFailedTsNs int64
|
||||
|
||||
// resubscribeCh closes once a failure has stopped the processor and all
|
||||
// in-flight jobs have drained, asking the metadata follower to drop the
|
||||
// stream so the caller's reconnect replays the pinned events in order —
|
||||
// and never races the replay against work still running in this abandoned
|
||||
// processor.
|
||||
resubscribeCh chan struct{}
|
||||
resubscribeOnce sync.Once
|
||||
|
||||
// stopped latches when a job failure pins the watermark. Admission then
|
||||
// drops new events instead of queueing them into a processor that is about
|
||||
// to be abandoned: every skipped event replays from the pinned watermark
|
||||
// after the reconnect, and on a stream that never goes quiet the drain —
|
||||
// and with it the replay — would otherwise never come. The cond broadcast
|
||||
// releases a blocked AddSyncJob. A redelivery of an event still in
|
||||
// failedTs is the one exception: it may run so its success shrinks the
|
||||
// replay.
|
||||
stopped bool
|
||||
|
||||
// metrics is nil for callers that do not report per-event metrics.
|
||||
metrics *syncStreamMetrics
|
||||
}
|
||||
@@ -118,12 +162,14 @@ type MetadataProcessor struct {
|
||||
func NewMetadataProcessor(fn pb.ProcessMetadataFunc, concurrency int, offsetTsNs int64) *MetadataProcessor {
|
||||
t := &MetadataProcessor{
|
||||
fn: fn,
|
||||
activeJobs: make(map[int64]*syncJobPaths),
|
||||
activeJobTs: make(map[int64]int),
|
||||
concurrencyLimit: concurrency,
|
||||
activeFilePaths: make(map[util.FullPath]int),
|
||||
activeBarrierDirPaths: make(map[util.FullPath]int),
|
||||
activeNonBarrierDirPaths: make(map[util.FullPath]int),
|
||||
descendantCount: make(map[util.FullPath]int),
|
||||
failedTs: make(map[failedEventKey]struct{}),
|
||||
resubscribeCh: make(chan struct{}),
|
||||
}
|
||||
t.processedTsWatermark.Store(offsetTsNs)
|
||||
t.activeJobsCond = sync.NewCond(&t.activeJobsLock)
|
||||
@@ -153,6 +199,13 @@ func (t *MetadataProcessor) OldestFailedTsNs() int64 {
|
||||
return t.oldestFailedTsNs
|
||||
}
|
||||
|
||||
// ResubscribeCh closes once a job failure has stopped the processor and its
|
||||
// in-flight jobs have drained, signaling the metadata follower to drop the
|
||||
// stream so a reconnect replays what the watermark still covers.
|
||||
func (t *MetadataProcessor) ResubscribeCh() <-chan struct{} {
|
||||
return t.resubscribeCh
|
||||
}
|
||||
|
||||
// pathAncestors returns all proper ancestor directories of p.
|
||||
// For "/a/b/c", returns ["/a/b", "/a", "/"].
|
||||
func pathAncestors(p util.FullPath) []util.FullPath {
|
||||
@@ -281,29 +334,65 @@ func (t *MetadataProcessor) conflictsWith(resp *filer_pb.SubscribeMetadataRespon
|
||||
|
||||
func (t *MetadataProcessor) AddSyncJob(resp *filer_pb.SubscribeMetadataResponse) {
|
||||
if filer_pb.IsEmpty(resp) {
|
||||
// A filtered-progress marker means the source skipped everything below
|
||||
// it for us; once all earlier work has finished, the watermark can move
|
||||
// to it so idle stretches still advance the resume point.
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
if resp.TsNs > t.filteredTsNs {
|
||||
t.filteredTsNs = resp.TsNs
|
||||
}
|
||||
if t.activeJobCount == 0 && resp.TsNs > t.processedTsWatermark.Load() &&
|
||||
(t.oldestFailedTsNs == 0 || resp.TsNs < t.oldestFailedTsNs) {
|
||||
t.processedTsWatermark.Store(resp.TsNs)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
dataSize := eventDataSize(resp)
|
||||
|
||||
// counted before the admission wait: received-processed-failed is the
|
||||
// number of events read off the stream but not yet done
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
|
||||
p, newPath, kind := extractJobInfo(resp)
|
||||
eventKey := failedEventKey{tsNs: resp.TsNs, path: p, newPath: newPath, kind: kind}
|
||||
|
||||
for t.activeJobCount >= t.concurrencyLimit || t.conflictsWith(resp) {
|
||||
// A stopped processor never queues: an event that cannot start drops
|
||||
// and replays in order after the resubscribe.
|
||||
if t.stopped {
|
||||
return
|
||||
}
|
||||
t.activeJobsCond.Wait()
|
||||
}
|
||||
if t.stopped {
|
||||
select {
|
||||
case <-t.resubscribeCh:
|
||||
// Already drained and signaled: nothing may start now, or it would
|
||||
// race the replay the signal just asked for.
|
||||
return
|
||||
default:
|
||||
}
|
||||
// The one event still worth running is a failure still pinning the
|
||||
// watermark, redelivered on this stream: its success clears the ledger
|
||||
// entry and shrinks the replay. Everything else replays anyway.
|
||||
if _, pinned := t.failedTs[eventKey]; !pinned {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// counted once admitted: received-processed-failed is the number of events
|
||||
// this processor read but has not finished. A dropped event is not counted
|
||||
// here — the replay's own admission counts it.
|
||||
if t.metrics != nil {
|
||||
t.metrics.received.Inc()
|
||||
t.metrics.receivedBytes.Add(float64(dataSize))
|
||||
}
|
||||
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
|
||||
for len(t.activeJobs) >= t.concurrencyLimit || t.conflictsWith(resp) {
|
||||
t.activeJobsCond.Wait()
|
||||
}
|
||||
|
||||
p, newPath, kind := extractJobInfo(resp)
|
||||
jobPaths := &syncJobPaths{path: p, newPath: newPath, kind: kind, dataSize: dataSize}
|
||||
|
||||
t.activeJobs[resp.TsNs] = jobPaths
|
||||
t.activeJobCount++
|
||||
t.activeJobTs[resp.TsNs]++
|
||||
t.addPathToIndex(p, kind)
|
||||
if newPath != "" {
|
||||
t.addPathToIndex(newPath, kind)
|
||||
@@ -327,16 +416,55 @@ func (t *MetadataProcessor) AddSyncJob(resp *filer_pb.SubscribeMetadataResponse)
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
|
||||
failedKey := failedEventKey{tsNs: resp.TsNs, path: jobPaths.path, newPath: jobPaths.newPath, kind: jobPaths.kind}
|
||||
if jobErr != nil {
|
||||
if t.oldestFailedTsNs == 0 || resp.TsNs < t.oldestFailedTsNs {
|
||||
t.oldestFailedTsNs = resp.TsNs
|
||||
glog.Errorf("process %v: %v; holding sync offset at %v so this event is replayed on restart", resp, jobErr, time.Unix(0, resp.TsNs))
|
||||
} else {
|
||||
// Latch the stop the moment a failure lands: events behind the pin
|
||||
// replay after the resubscribe anyway, and a stream that never goes
|
||||
// quiet would otherwise keep the active count above zero so the
|
||||
// failure stays pinned until an unrelated reconnect — the wait this
|
||||
// whole mechanism exists to remove.
|
||||
t.stopped = true
|
||||
t.activeJobsCond.Broadcast()
|
||||
if t.failedSticky {
|
||||
if resp.TsNs < t.oldestFailedTsNs {
|
||||
t.oldestFailedTsNs = resp.TsNs
|
||||
}
|
||||
glog.Errorf("process %v: %v", resp, jobErr)
|
||||
} else if _, recorded := t.failedTs[failedKey]; !recorded {
|
||||
if len(t.failedTs) >= maxFailedSyncEvents {
|
||||
t.failedSticky = true
|
||||
t.failedTs = nil
|
||||
if resp.TsNs < t.oldestFailedTsNs {
|
||||
t.oldestFailedTsNs = resp.TsNs
|
||||
}
|
||||
glog.Warningf("process %v: %v; over %d unresolved failures, pinning sync offset at %v until restart", resp, jobErr, maxFailedSyncEvents, time.Unix(0, t.oldestFailedTsNs))
|
||||
} else {
|
||||
t.failedTs[failedKey] = struct{}{}
|
||||
if t.oldestFailedTsNs == 0 || resp.TsNs < t.oldestFailedTsNs {
|
||||
t.oldestFailedTsNs = resp.TsNs
|
||||
glog.Errorf("process %v: %v; holding sync offset at %v so this event is replayed on restart", resp, jobErr, time.Unix(0, resp.TsNs))
|
||||
} else {
|
||||
glog.Errorf("process %v: %v", resp, jobErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if _, recorded := t.failedTs[failedKey]; recorded {
|
||||
delete(t.failedTs, failedKey)
|
||||
if resp.TsNs == t.oldestFailedTsNs {
|
||||
t.oldestFailedTsNs = 0
|
||||
for k := range t.failedTs {
|
||||
if t.oldestFailedTsNs == 0 || k.tsNs < t.oldestFailedTsNs {
|
||||
t.oldestFailedTsNs = k.tsNs
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delete(t.activeJobs, resp.TsNs)
|
||||
t.activeJobCount--
|
||||
t.activeJobTs[resp.TsNs]--
|
||||
if t.activeJobTs[resp.TsNs] == 0 {
|
||||
delete(t.activeJobTs, resp.TsNs)
|
||||
}
|
||||
t.removePathFromIndex(jobPaths.path, jobPaths.kind)
|
||||
if jobPaths.newPath != "" {
|
||||
t.removePathFromIndex(jobPaths.newPath, jobPaths.kind)
|
||||
@@ -356,7 +484,7 @@ func (t *MetadataProcessor) AddSyncJob(resp *filer_pb.SubscribeMetadataResponse)
|
||||
// Lazy-clean stale entries from heap top (already-completed jobs).
|
||||
// Each entry is pushed once and popped once: O(log n) amortized.
|
||||
for t.tsHeap.Len() > 0 {
|
||||
if _, active := t.activeJobs[t.tsHeap[0]]; active {
|
||||
if t.activeJobTs[t.tsHeap[0]] > 0 {
|
||||
break
|
||||
}
|
||||
heap.Pop(&t.tsHeap)
|
||||
@@ -369,6 +497,15 @@ func (t *MetadataProcessor) AddSyncJob(resp *filer_pb.SubscribeMetadataResponse)
|
||||
t.processedTsWatermark.Store(resp.TsNs)
|
||||
}
|
||||
}
|
||||
if t.activeJobCount == 0 && t.filteredTsNs > t.processedTsWatermark.Load() &&
|
||||
(t.oldestFailedTsNs == 0 || t.filteredTsNs < t.oldestFailedTsNs) {
|
||||
t.processedTsWatermark.Store(t.filteredTsNs)
|
||||
}
|
||||
// Signal once the stop has drained: even if a redelivery cleared the
|
||||
// pin, events dropped while stopped still have to replay.
|
||||
if t.stopped && t.activeJobCount == 0 {
|
||||
t.resubscribeOnce.Do(func() { close(t.resubscribeCh) })
|
||||
}
|
||||
t.activeJobsCond.Signal()
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -94,8 +94,8 @@ func TestFileVsFileConflict(t *testing.T) {
|
||||
|
||||
// Add a file job
|
||||
active := makeResp("/dir1", "file.txt", false, 1, true)
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// Same file should conflict
|
||||
@@ -125,8 +125,8 @@ func TestFileUnderActiveDirConflict(t *testing.T) {
|
||||
|
||||
// Add a directory job at /dir1
|
||||
active := makeResp("/", "dir1", true, 1, true)
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// File under /dir1 should conflict
|
||||
@@ -163,8 +163,8 @@ func TestDirWithActiveFileUnder(t *testing.T) {
|
||||
|
||||
// Add file jobs under /dir1
|
||||
f1 := makeResp("/dir1/sub", "file.txt", false, 1, true)
|
||||
path, newPath, kind := extractJobInfo(f1)
|
||||
p.activeJobs[f1.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(f1)
|
||||
p.activeJobTs[f1.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// Directory /dir1 should conflict (has active file under it)
|
||||
@@ -187,8 +187,8 @@ func TestDirVsDirConflict(t *testing.T) {
|
||||
|
||||
// Add directory job at /a/b
|
||||
active := makeResp("/a", "b", true, 1, true)
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// /a/b/c (descendant) should conflict
|
||||
@@ -224,8 +224,8 @@ func TestRenameConflict(t *testing.T) {
|
||||
|
||||
// Add file job at /dir1/file.txt
|
||||
f1 := makeResp("/dir1", "file.txt", false, 1, true)
|
||||
path, newPath, kind := extractJobInfo(f1)
|
||||
p.activeJobs[f1.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(f1)
|
||||
p.activeJobTs[f1.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// Rename from /dir2/a.txt to /dir1/file.txt should conflict (newPath matches)
|
||||
@@ -255,7 +255,7 @@ func TestActiveRenameConflict(t *testing.T) {
|
||||
// Add active rename job: /dir1/old.txt -> /dir2/new.txt
|
||||
rename := makeRenameResp("/dir1", "old.txt", "/dir2", "new.txt", false, 1)
|
||||
path, newPath, kind := extractJobInfo(rename)
|
||||
p.activeJobs[rename.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
p.activeJobTs[rename.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
if newPath != "" {
|
||||
p.addPathToIndex(newPath, kind)
|
||||
@@ -289,8 +289,8 @@ func TestRootDirConflict(t *testing.T) {
|
||||
// Note: a dir entry at "/" would be created as FullPath("/").Child("somedir")
|
||||
// But let's test what happens with an active dir at /some/path and check root
|
||||
active := makeResp("/some", "dir", true, 1, true)
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// Root dir should conflict because active dir /some/dir is under /
|
||||
@@ -334,7 +334,7 @@ func TestWatermarkWithHeap(t *testing.T) {
|
||||
// Simulate adding jobs in order
|
||||
for _, ts := range []int64{10, 20, 30} {
|
||||
jobPath := util.FullPath("/file" + string(rune('0'+ts/10)))
|
||||
p.activeJobs[ts] = &syncJobPaths{path: jobPath, kind: kindFile}
|
||||
p.activeJobTs[ts] = 1
|
||||
p.addPathToIndex(jobPath, kindFile)
|
||||
heap.Push(&p.tsHeap, ts)
|
||||
}
|
||||
@@ -344,11 +344,11 @@ func TestWatermarkWithHeap(t *testing.T) {
|
||||
}
|
||||
|
||||
// Remove non-oldest (ts=20) — heap top should stay 10
|
||||
delete(p.activeJobs, 20)
|
||||
delete(p.activeJobTs, 20)
|
||||
p.removePathFromIndex("/file2", kindFile)
|
||||
// Lazy clean: top is 10 which is still active, so no pop
|
||||
for p.tsHeap.Len() > 0 {
|
||||
if _, active := p.activeJobs[p.tsHeap[0]]; active {
|
||||
if p.activeJobTs[p.tsHeap[0]] > 0 {
|
||||
break
|
||||
}
|
||||
heap.Pop(&p.tsHeap)
|
||||
@@ -358,10 +358,10 @@ func TestWatermarkWithHeap(t *testing.T) {
|
||||
}
|
||||
|
||||
// Remove oldest (ts=10) — lazy clean should find 30
|
||||
delete(p.activeJobs, 10)
|
||||
delete(p.activeJobTs, 10)
|
||||
p.removePathFromIndex("/file1", kindFile)
|
||||
for p.tsHeap.Len() > 0 {
|
||||
if _, active := p.activeJobs[p.tsHeap[0]]; active {
|
||||
if p.activeJobTs[p.tsHeap[0]] > 0 {
|
||||
break
|
||||
}
|
||||
heap.Pop(&p.tsHeap)
|
||||
@@ -383,11 +383,11 @@ func TestNonBarrierDirUpdateDoesNotBlockDescendants(t *testing.T) {
|
||||
|
||||
// Active non-barrier: attribute update on /dir1.
|
||||
active := makeDirUpdateResp("/", "dir1", 1)
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
path, _, kind := extractJobInfo(active)
|
||||
if kind != kindNonBarrierDir {
|
||||
t.Fatalf("expected kindNonBarrierDir for dir attribute update, got %v", kind)
|
||||
}
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// File under /dir1 should NOT conflict with the attribute update.
|
||||
@@ -407,11 +407,11 @@ func TestNonBarrierDirUpdateDoesNotBlockDescendants(t *testing.T) {
|
||||
p := NewMetadataProcessor(noop, 100, 0)
|
||||
|
||||
active := makeResp("/", "dir1", true, 1, true) // create
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
path, _, kind := extractJobInfo(active)
|
||||
if kind != kindBarrierDir {
|
||||
t.Fatalf("expected kindBarrierDir for dir create, got %v", kind)
|
||||
}
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
under := makeResp("/dir1", "file.txt", false, 2, true)
|
||||
@@ -425,8 +425,8 @@ func TestNonBarrierDirUpdateDoesNotBlockDescendants(t *testing.T) {
|
||||
|
||||
// Active file under /dir1.
|
||||
f := makeResp("/dir1", "file.txt", false, 1, true)
|
||||
path, newPath, kind := extractJobInfo(f)
|
||||
p.activeJobs[f.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(f)
|
||||
p.activeJobTs[f.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// Incoming barrier delete on /dir1 should still wait for the
|
||||
@@ -442,8 +442,8 @@ func TestNonBarrierDirUpdateDoesNotBlockDescendants(t *testing.T) {
|
||||
|
||||
// Active non-barrier dir update at /a/b.
|
||||
upd := makeDirUpdateResp("/a", "b", 1)
|
||||
path, newPath, kind := extractJobInfo(upd)
|
||||
p.activeJobs[upd.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(upd)
|
||||
p.activeJobTs[upd.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// A barrier delete on /a (the ancestor) should wait for it.
|
||||
@@ -464,8 +464,8 @@ func TestSamePathBarrierSerialization(t *testing.T) {
|
||||
t.Run("barrier dir at p blocks same-path file", func(t *testing.T) {
|
||||
p := NewMetadataProcessor(noop, 100, 0)
|
||||
active := makeResp("/", "dir1", true, 1, true) // dir create
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
file := makeResp("/", "dir1", false, 2, true)
|
||||
@@ -477,8 +477,8 @@ func TestSamePathBarrierSerialization(t *testing.T) {
|
||||
t.Run("barrier dir at p blocks another same-path barrier dir", func(t *testing.T) {
|
||||
p := NewMetadataProcessor(noop, 100, 0)
|
||||
active := makeResp("/", "dir1", true, 1, true) // dir create
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
del := makeResp("/", "dir1", true, 2, false) // dir delete, same path
|
||||
@@ -490,8 +490,8 @@ func TestSamePathBarrierSerialization(t *testing.T) {
|
||||
t.Run("barrier dir at p blocks non-barrier update at same path", func(t *testing.T) {
|
||||
p := NewMetadataProcessor(noop, 100, 0)
|
||||
active := makeResp("/", "dir1", true, 1, true) // dir create
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
upd := makeDirUpdateResp("/", "dir1", 2)
|
||||
@@ -503,8 +503,8 @@ func TestSamePathBarrierSerialization(t *testing.T) {
|
||||
t.Run("file at p blocks same-path barrier dir", func(t *testing.T) {
|
||||
p := NewMetadataProcessor(noop, 100, 0)
|
||||
active := makeResp("/", "thing", false, 1, true) // file create at /thing
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// Barrier dir at /thing (e.g. a file→dir promotion) must wait.
|
||||
@@ -520,11 +520,11 @@ func TestSamePathBarrierSerialization(t *testing.T) {
|
||||
// delete/rename/create on /dir1.
|
||||
p := NewMetadataProcessor(noop, 100, 0)
|
||||
active := makeDirUpdateResp("/", "dir1", 1)
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
path, _, kind := extractJobInfo(active)
|
||||
if kind != kindNonBarrierDir {
|
||||
t.Fatalf("expected kindNonBarrierDir, got %v", kind)
|
||||
}
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
del := makeResp("/", "dir1", true, 2, false) // dir delete
|
||||
@@ -541,8 +541,8 @@ func TestSamePathBarrierSerialization(t *testing.T) {
|
||||
t.Run("non-barrier update at p does NOT block same-path non-barrier update", func(t *testing.T) {
|
||||
p := NewMetadataProcessor(noop, 100, 0)
|
||||
active := makeDirUpdateResp("/", "dir1", 1)
|
||||
path, newPath, kind := extractJobInfo(active)
|
||||
p.activeJobs[active.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(active)
|
||||
p.activeJobTs[active.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
|
||||
// Concurrent attribute bumps are allowed: last writer wins.
|
||||
@@ -569,8 +569,8 @@ func BenchmarkConflictCheck(b *testing.B) {
|
||||
dir := fmt.Sprintf("/dir%d/sub%d", i/100, i%100)
|
||||
name := fmt.Sprintf("file%d.txt", i)
|
||||
resp := makeResp(dir, name, false, int64(i+1), true)
|
||||
path, newPath, kind := extractJobInfo(resp)
|
||||
p.activeJobs[resp.TsNs] = &syncJobPaths{path: path, newPath: newPath, kind: kind}
|
||||
path, _, kind := extractJobInfo(resp)
|
||||
p.activeJobTs[resp.TsNs] = 1
|
||||
p.addPathToIndex(path, kind)
|
||||
}
|
||||
|
||||
@@ -586,40 +586,13 @@ func BenchmarkConflictCheck(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMetadataProcessorEmptyMarkerKeepsWatermarkStale: the MaxUnsyncedEvents
|
||||
// marker (empty EventNotification, fresh timestamp) is dropped by AddSyncJob and
|
||||
// does NOT advance processedTsWatermark, so offsetFunc keeps publishing the stale
|
||||
// offset. This is why the client must not drive sync_offset off the watermark
|
||||
// for these markers.
|
||||
func TestMetadataProcessorEmptyMarkerKeepsWatermarkStale(t *testing.T) {
|
||||
const staleOffset = int64(1_000_000_000)
|
||||
freshTs := staleOffset + int64(time.Hour) // a "now"-ish source timestamp
|
||||
|
||||
p := NewMetadataProcessor(func(*filer_pb.SubscribeMetadataResponse) error { return nil }, 4, staleOffset)
|
||||
|
||||
marker := &filer_pb.SubscribeMetadataResponse{
|
||||
TsNs: freshTs,
|
||||
EventNotification: &filer_pb.EventNotification{},
|
||||
}
|
||||
if !filer_pb.IsEmpty(marker) {
|
||||
t.Fatal("marker should be IsEmpty")
|
||||
}
|
||||
|
||||
p.AddSyncJob(marker)
|
||||
|
||||
if got := p.processedTsWatermark.Load(); got != staleOffset {
|
||||
t.Fatalf("empty marker advanced watermark to %d; want it to stay stale at %d", got, staleOffset)
|
||||
}
|
||||
t.Logf("marker carried fresh ts %d but watermark stayed stale at %d", freshTs, staleOffset)
|
||||
}
|
||||
|
||||
// waitForJobsToDrain blocks until every job goroutine has finished bookkeeping.
|
||||
func waitForJobsToDrain(t *testing.T, p *MetadataProcessor) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
p.activeJobsLock.Lock()
|
||||
remaining := len(p.activeJobs)
|
||||
remaining := p.activeJobCount
|
||||
p.activeJobsLock.Unlock()
|
||||
if remaining == 0 {
|
||||
return
|
||||
@@ -651,35 +624,54 @@ func TestFailedJobHoldsWatermark(t *testing.T) {
|
||||
t.Fatalf("watermark = %d after a successful job, want 100", got)
|
||||
}
|
||||
|
||||
p.AddSyncJob(makeResp("/dir", "b.txt", false, failedTsNs, true))
|
||||
waitForJobsToDrain(t, p)
|
||||
if got := p.processedTsWatermark.Load(); got != 100 {
|
||||
t.Fatalf("watermark = %d after a failed job, want it held at 100", got)
|
||||
// a later event still in flight when the failure lands finishes fine, but
|
||||
// the offset stays behind the failure
|
||||
release := make(chan struct{})
|
||||
slowFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if resp.TsNs == 300 {
|
||||
<-release
|
||||
}
|
||||
return fn(resp)
|
||||
}
|
||||
|
||||
// later events keep flowing, but the offset stays behind the failure
|
||||
p.AddSyncJob(makeResp("/dir", "c.txt", false, 300, true))
|
||||
waitForJobsToDrain(t, p)
|
||||
if got := p.processedTsWatermark.Load(); got != 100 {
|
||||
p2 := NewMetadataProcessor(slowFn, 10, 0)
|
||||
// admit the slow job first so it is in flight when the failure lands
|
||||
p2.AddSyncJob(makeResp("/dir", "c.txt", false, 300, true))
|
||||
p2.AddSyncJob(makeResp("/dir", "a.txt", false, 100, true))
|
||||
p2.AddSyncJob(makeResp("/dir", "b.txt", false, failedTsNs, true))
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for p2.OldestFailedTsNs() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if p2.OldestFailedTsNs() != failedTsNs {
|
||||
t.Fatalf("oldest failed = %d, want the pin at %d", p2.OldestFailedTsNs(), failedTsNs)
|
||||
}
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p2)
|
||||
if got := p2.processedTsWatermark.Load(); got != 100 {
|
||||
t.Fatalf("watermark = %d after a later success, want it held at 100", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailedJobHoldsWatermarkAtOldestFailure verifies that the watermark is
|
||||
// pinned by the oldest failure, not the most recent one.
|
||||
// pinned by the oldest failure, not the most recent one. Once the processor
|
||||
// drains it stops accepting events for the resubscribe, so both failures have
|
||||
// to be in the same drained batch.
|
||||
func TestFailedJobHoldsWatermarkAtOldestFailure(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
fn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
<-release
|
||||
if resp.TsNs == 200 || resp.TsNs == 400 {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
p := NewMetadataProcessor(fn, 1, 0)
|
||||
p := NewMetadataProcessor(fn, 10, 0)
|
||||
|
||||
for _, ts := range []int64{100, 200, 300, 400, 500} {
|
||||
p.AddSyncJob(makeResp("/dir", fmt.Sprintf("f%d.txt", ts), false, ts, true))
|
||||
waitForJobsToDrain(t, p)
|
||||
}
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
|
||||
if got := p.processedTsWatermark.Load(); got != 100 {
|
||||
t.Fatalf("watermark = %d, want it held at 100 by the failure at 200", got)
|
||||
@@ -692,14 +684,18 @@ func TestFailedJobHoldsWatermarkAtOldestFailure(t *testing.T) {
|
||||
// update's new 60-byte chunk but not its shared one, and nothing for the
|
||||
// delete despite its chunk.
|
||||
func TestSyncStreamMetrics(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
fn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
<-release
|
||||
if resp.TsNs == 2 {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
p := NewMetadataProcessor(fn, 100, 0)
|
||||
p.SetMetrics("srcFiler", "dstFiler", "TestSyncStreamMetrics", "/")
|
||||
// the counters are process-global: a unique client name keeps repeated
|
||||
// runs (-count>1) from accumulating into each other
|
||||
p.SetMetrics("srcFiler", "dstFiler", fmt.Sprintf("TestSyncStreamMetrics-%d", time.Now().UnixNano()), "/")
|
||||
|
||||
create := makeResp("/dir1", "a.txt", false, 1, true)
|
||||
create.EventNotification.NewEntry.Chunks = []*filer_pb.FileChunk{{FileId: "1,a0", Size: 100}}
|
||||
@@ -721,6 +717,7 @@ func TestSyncStreamMetrics(t *testing.T) {
|
||||
for _, resp := range []*filer_pb.SubscribeMetadataResponse{create, failing, update, del} {
|
||||
p.AddSyncJob(resp)
|
||||
}
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
|
||||
for _, tc := range []struct {
|
||||
@@ -742,3 +739,337 @@ func TestSyncStreamMetrics(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailedJobReplaySuccessClearsPin verifies that when the failed event is
|
||||
// redelivered while the processor is still alive and succeeds this time, the
|
||||
// failure pin clears and the watermark can move again. It is the one event a
|
||||
// stopped processor still runs. The resubscribe still signals once the jobs
|
||||
// drain: anything dropped after the stop has to replay too.
|
||||
func TestFailedJobReplaySuccessClearsPin(t *testing.T) {
|
||||
failed := true
|
||||
release := make(chan struct{})
|
||||
fn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if resp.TsNs == 300 {
|
||||
<-release
|
||||
}
|
||||
if resp.TsNs == 200 && failed {
|
||||
failed = false
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
p := NewMetadataProcessor(fn, 10, 0)
|
||||
|
||||
// the slow job is admitted first so the processor has in-flight work when
|
||||
// the failure lands, keeping the drain — and the resubscribe — open
|
||||
p.AddSyncJob(makeResp("/dir", "c.txt", false, 300, true))
|
||||
p.AddSyncJob(makeResp("/dir", "b.txt", false, 200, true))
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() != 200 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if got := p.OldestFailedTsNs(); got != 200 {
|
||||
t.Fatalf("oldest failed = %d, want 200", got)
|
||||
}
|
||||
|
||||
// once stopped, a new event drops instead of queueing into a processor
|
||||
// that is about to be abandoned — it replays after the resubscribe
|
||||
p.AddSyncJob(makeResp("/dir", "d.txt", false, 400, true))
|
||||
p.activeJobsLock.Lock()
|
||||
dropped := p.activeJobTs[400] == 0
|
||||
p.activeJobsLock.Unlock()
|
||||
if !dropped {
|
||||
t.Fatal("new event admitted after the failure stopped the processor")
|
||||
}
|
||||
|
||||
// the redelivery is the exception: it runs and its success clears the pin
|
||||
p.AddSyncJob(makeResp("/dir", "b.txt", false, 200, true))
|
||||
deadline = time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() != 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if got := p.OldestFailedTsNs(); got != 0 {
|
||||
t.Fatalf("oldest failed = %d after a successful replay, want 0", got)
|
||||
}
|
||||
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
select {
|
||||
case <-p.ResubscribeCh():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("resubscribe never signaled after the stopped processor drained")
|
||||
}
|
||||
if got := p.processedTsWatermark.Load(); got != 300 {
|
||||
t.Fatalf("watermark = %d after recovery, want 300", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFilteredMarkerAdvancesWatermark verifies that a filtered-progress marker
|
||||
// (empty event with a timestamp) moves the watermark once all earlier work has
|
||||
// finished, but never past an in-flight job or an unresolved failure.
|
||||
func TestFilteredMarkerAdvancesWatermark(t *testing.T) {
|
||||
marker := func(ts int64) *filer_pb.SubscribeMetadataResponse {
|
||||
return &filer_pb.SubscribeMetadataResponse{TsNs: ts, EventNotification: &filer_pb.EventNotification{}}
|
||||
}
|
||||
|
||||
t.Run("idle", func(t *testing.T) {
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error { return nil }, 100, 50)
|
||||
p.AddSyncJob(marker(90))
|
||||
if got := p.processedTsWatermark.Load(); got != 90 {
|
||||
t.Fatalf("watermark = %d after marker, want 90", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("behind in-flight job", func(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
<-release
|
||||
return nil
|
||||
}, 100, 50)
|
||||
p.AddSyncJob(makeResp("/dir", "f.txt", false, 60, true))
|
||||
p.AddSyncJob(marker(80))
|
||||
if got := p.processedTsWatermark.Load(); got != 50 {
|
||||
t.Fatalf("watermark = %d with a job in flight, want 50", got)
|
||||
}
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
if got := p.processedTsWatermark.Load(); got != 80 {
|
||||
t.Fatalf("watermark = %d after drain, want the retained marker at 80", got)
|
||||
}
|
||||
p.AddSyncJob(marker(90))
|
||||
if got := p.processedTsWatermark.Load(); got != 90 {
|
||||
t.Fatalf("watermark = %d after drain and marker, want 90", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("behind a failure", func(t *testing.T) {
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}, 100, 50)
|
||||
p.AddSyncJob(makeResp("/dir", "f.txt", false, 100, true))
|
||||
waitForJobsToDrain(t, p)
|
||||
p.AddSyncJob(marker(200))
|
||||
if got := p.processedTsWatermark.Load(); got != 50 {
|
||||
t.Fatalf("watermark = %d past a failure pin, want 50", got)
|
||||
}
|
||||
p.AddSyncJob(marker(70))
|
||||
if got := p.processedTsWatermark.Load(); got != 70 {
|
||||
t.Fatalf("watermark = %d behind the pin, want 70", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFailedLedgerCapsAndStaysPinned verifies that a sustained run of distinct
|
||||
// failures cannot grow failedTs without bound: past maxFailedSyncEvents the
|
||||
// ledger collapses to a sticky pin at the oldest failure, so the watermark
|
||||
// still replays from it while memory stays bounded.
|
||||
func TestFailedLedgerCapsAndStaysPinned(t *testing.T) {
|
||||
defer func(old int) { maxFailedSyncEvents = old }(maxFailedSyncEvents)
|
||||
maxFailedSyncEvents = 4
|
||||
|
||||
fail := true
|
||||
release := make(chan struct{})
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
<-release
|
||||
if fail {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
return nil
|
||||
}, 100, 0)
|
||||
for i := int64(1); i <= 10; i++ {
|
||||
p.AddSyncJob(makeResp("/dir", fmt.Sprintf("f%d.txt", i), false, i*100, true))
|
||||
}
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
|
||||
if !p.failedSticky {
|
||||
t.Fatal("ledger did not collapse past the cap")
|
||||
}
|
||||
if got := p.OldestFailedTsNs(); got != 100 {
|
||||
t.Fatalf("oldest failed = %d, want the pin at the oldest failure 100", got)
|
||||
}
|
||||
if got := p.processedTsWatermark.Load(); got != 0 {
|
||||
t.Fatalf("watermark = %d, want it pinned at 0", got)
|
||||
}
|
||||
|
||||
fail = false
|
||||
p.AddSyncJob(makeResp("/dir", "f1.txt", false, 100, true))
|
||||
waitForJobsToDrain(t, p)
|
||||
if got := p.OldestFailedTsNs(); got != 100 {
|
||||
t.Fatalf("oldest failed = %d after a collapsed replay, want the pin held at 100", got)
|
||||
}
|
||||
if got := p.processedTsWatermark.Load(); got != 0 {
|
||||
t.Fatalf("watermark = %d after a collapsed replay, want it still pinned at 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailedLedgerDistinguishesEventsAtSameTs verifies that a success for one
|
||||
// event does not clear the pin recorded for a different event that happened to
|
||||
// share its timestamp — the ledger keys on event identity, not just TsNs. A
|
||||
// slow job holds the drain open so the redelivery still lands on this
|
||||
// processor generation.
|
||||
func TestFailedLedgerDistinguishesEventsAtSameTs(t *testing.T) {
|
||||
fail := true
|
||||
release := make(chan struct{})
|
||||
hold := make(chan struct{})
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if resp.EventNotification.NewEntry.GetName() == "slow.txt" {
|
||||
<-hold
|
||||
} else {
|
||||
<-release
|
||||
}
|
||||
if resp.EventNotification.NewEntry.GetName() == "bad.txt" && fail {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
return nil
|
||||
}, 100, 0)
|
||||
|
||||
// both same-ts events admit before either resolves, so the success lands
|
||||
// while the failure is already pinned
|
||||
p.AddSyncJob(makeResp("/dir", "slow.txt", false, 900, true))
|
||||
p.AddSyncJob(makeResp("/dir", "bad.txt", false, 200, true))
|
||||
p.AddSyncJob(makeResp("/dir", "good.txt", false, 200, true))
|
||||
close(release)
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() != 200 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if got := p.OldestFailedTsNs(); got != 200 {
|
||||
t.Fatalf("oldest failed = %d, want the other event's pin held at 200", got)
|
||||
}
|
||||
if got := p.processedTsWatermark.Load(); got != 0 {
|
||||
t.Fatalf("watermark = %d, want it still pinned at 0", got)
|
||||
}
|
||||
|
||||
// redelivering the failed event itself is what clears the pin — and it is
|
||||
// the one event a stopped processor still admits
|
||||
fail = false
|
||||
p.AddSyncJob(makeResp("/dir", "bad.txt", false, 200, true))
|
||||
deadline = time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() != 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
close(hold)
|
||||
waitForJobsToDrain(t, p)
|
||||
if got := p.OldestFailedTsNs(); got != 0 {
|
||||
t.Fatalf("oldest failed = %d after the failed event itself recovered, want 0", got)
|
||||
}
|
||||
if got := p.processedTsWatermark.Load(); got != 900 {
|
||||
t.Fatalf("watermark = %d after the pin cleared and the rest drained, want 900", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailedJobSignalsResubscribe verifies that a job exhausting its retries
|
||||
// closes ResubscribeCh so the follower drops the stream and the reconnect
|
||||
// replays the pinned event — the path that used to wait for a restart.
|
||||
func TestFailedJobSignalsResubscribe(t *testing.T) {
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}, 100, 0)
|
||||
|
||||
p.AddSyncJob(makeResp("/dir", "a.txt", false, 100, true))
|
||||
waitForJobsToDrain(t, p)
|
||||
|
||||
select {
|
||||
case <-p.ResubscribeCh():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("resubscribe channel never closed after the failure pinned the watermark")
|
||||
}
|
||||
if got := p.OldestFailedTsNs(); got != 100 {
|
||||
t.Fatalf("oldest failed = %d, want 100", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResubscribeWaitsForInFlightJobs verifies the signal stays open while
|
||||
// jobs admitted before the failure are still running — replaying behind them
|
||||
// could restore older state over their writes — and closes once they drain.
|
||||
// An event arriving after the stop drops instead of keeping the drain open,
|
||||
// so a busy stream cannot starve the replay.
|
||||
func TestResubscribeWaitsForInFlightJobs(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if resp.TsNs == 100 {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
<-release
|
||||
return nil
|
||||
}, 100, 0)
|
||||
|
||||
// the slow job admits first so it is in flight when the failure lands
|
||||
p.AddSyncJob(makeResp("/dir", "b.txt", false, 200, true))
|
||||
p.AddSyncJob(makeResp("/dir", "a.txt", false, 100, true))
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if p.OldestFailedTsNs() != 100 {
|
||||
t.Fatalf("oldest failed = %d, want the pin at 100", p.OldestFailedTsNs())
|
||||
}
|
||||
select {
|
||||
case <-p.ResubscribeCh():
|
||||
t.Fatal("resubscribe signaled while an in-flight job could still race the replay")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
|
||||
// the processor stopped on the failure, so this event drops — it replays
|
||||
// after the resubscribe — instead of starving the drain
|
||||
p.AddSyncJob(makeResp("/dir", "c.txt", false, 300, true))
|
||||
p.activeJobsLock.Lock()
|
||||
dropped := p.activeJobTs[300] == 0
|
||||
p.activeJobsLock.Unlock()
|
||||
if !dropped {
|
||||
t.Fatal("event admitted after the processor stopped")
|
||||
}
|
||||
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
select {
|
||||
case <-p.ResubscribeCh():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("resubscribe channel never closed after the in-flight jobs drained")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResubscribeWaitsForSameTsSibling guards the per-timestamp job
|
||||
// counting: events in one batch can share a TsNs, and the failed job must
|
||||
// not free the bookkeeping of a sibling still running at that timestamp.
|
||||
// Otherwise its completion could report the processor drained and the
|
||||
// resubscribe would replay over the sibling's writes.
|
||||
func TestResubscribeWaitsForSameTsSibling(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if resp.EventNotification.NewEntry.GetName() == "bad.txt" {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
<-release
|
||||
return nil
|
||||
}, 100, 0)
|
||||
|
||||
// the slow job admits first so it is in flight when the same-ts failure lands
|
||||
p.AddSyncJob(makeResp("/dir", "slow.txt", false, 200, true))
|
||||
p.AddSyncJob(makeResp("/dir", "bad.txt", false, 200, true))
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if p.OldestFailedTsNs() != 200 {
|
||||
t.Fatalf("oldest failed = %d, want the pin at 200", p.OldestFailedTsNs())
|
||||
}
|
||||
select {
|
||||
case <-p.ResubscribeCh():
|
||||
t.Fatal("resubscribe signaled while a same-ts job was still running")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
select {
|
||||
case <-p.ResubscribeCh():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("resubscribe channel never closed after the same-ts jobs drained")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/images/gateway"
|
||||
)
|
||||
|
||||
var cmdImage = &Command{
|
||||
UsageLine: "image -source=http://localhost:8333/public-bucket -imgproxy=http://localhost:8080",
|
||||
Short: "Start an on-demand gateway for public images",
|
||||
Long: `Run an optional image gateway in front of public S3 objects. x-oss-process
|
||||
supports aspect-preserving downscaling, absolute quality,Q_85, and JPEG/PNG/WebP.
|
||||
Source access is checked before every cache read. Processed images remain in a
|
||||
bounded memory cache and are never written to S3 or the Filer.
|
||||
Encoding runs in a separate imgproxy service; configure its pixel, file size,
|
||||
and process resource limits. This public endpoint does not accept S3 signatures
|
||||
or read private objects.`,
|
||||
}
|
||||
|
||||
var imageOptions struct {
|
||||
source, imgproxy, bind *string
|
||||
port, concurrency, maxDimension *int
|
||||
cacheMB, sourceMB, resultMB *int64
|
||||
timeout *time.Duration
|
||||
}
|
||||
|
||||
// init registers the optional endpoint without changing S3, Filer, or Volume services.
|
||||
func init() {
|
||||
cmdImage.Run = runImage
|
||||
imageOptions.source = cmdImage.Flag.String("source", "", "Fixed anonymous S3 HTTP(S) source URL, optionally with a bucket path")
|
||||
imageOptions.imgproxy = cmdImage.Flag.String("imgproxy", "", "Separate imgproxy HTTP(S) service URL")
|
||||
imageOptions.bind = cmdImage.Flag.String("ip.bind", "127.0.0.1", "Listen address")
|
||||
imageOptions.port = cmdImage.Flag.Int("port", 8334, "HTTP port")
|
||||
imageOptions.concurrency = cmdImage.Flag.Int("concurrency", 8, "Maximum concurrent requests and encoding jobs; excess requests return 429")
|
||||
imageOptions.maxDimension = cmdImage.Flag.Int("maxDimension", 4096, "Maximum output dimension")
|
||||
imageOptions.cacheMB = cmdImage.Flag.Int64("cacheCapacityMB", 64, "Processed image memory cache in MiB; 0 disables caching")
|
||||
imageOptions.sourceMB = cmdImage.Flag.Int64("maxSourceMB", 25, "Maximum source image size in MiB")
|
||||
imageOptions.resultMB = cmdImage.Flag.Int64("maxResultMB", 10, "Maximum processed image size in MiB")
|
||||
imageOptions.timeout = cmdImage.Flag.Duration("timeout", 15*time.Second, "Separate timeout budgets for source metadata, shared encoding, and client writes")
|
||||
}
|
||||
|
||||
// runImage starts the gateway, reading signing material from the environment rather than process arguments.
|
||||
func runImage(cmd *Command, args []string) bool {
|
||||
if *imageOptions.cacheMB < 0 || *imageOptions.cacheMB > 1<<20 ||
|
||||
*imageOptions.sourceMB < 1 || *imageOptions.sourceMB > 1024 ||
|
||||
*imageOptions.resultMB < 1 || *imageOptions.resultMB > 1024 {
|
||||
glog.Errorf("Invalid image gateway capacity options")
|
||||
return false
|
||||
}
|
||||
handler, err := gateway.New(gateway.Config{
|
||||
Source: *imageOptions.source, Imgproxy: *imageOptions.imgproxy,
|
||||
Key: os.Getenv("IMGPROXY_KEY"), Salt: os.Getenv("IMGPROXY_SALT"),
|
||||
Concurrency: *imageOptions.concurrency, MaxDimension: *imageOptions.maxDimension,
|
||||
CacheBytes: *imageOptions.cacheMB << 20, MaxSourceBytes: *imageOptions.sourceMB << 20,
|
||||
MaxResultBytes: *imageOptions.resultMB << 20, Timeout: *imageOptions.timeout,
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("Invalid image gateway configuration: %v", err)
|
||||
return false
|
||||
}
|
||||
if *imageOptions.port < 1 || *imageOptions.port > 65535 {
|
||||
glog.Errorf("Invalid image gateway port")
|
||||
return false
|
||||
}
|
||||
// Bound the initial source check, shared encoding, and response write phases.
|
||||
// ReadTimeout also limits draining of ignored request bodies after the handler returns.
|
||||
server := &http.Server{
|
||||
Addr: net.JoinHostPort(*imageOptions.bind, strconv.Itoa(*imageOptions.port)), Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 3 * *imageOptions.timeout,
|
||||
IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10,
|
||||
}
|
||||
glog.V(0).Infof("Image gateway listening on %s", server.Addr)
|
||||
if err = server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
glog.Errorf("Image gateway failed: %v", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -467,6 +467,7 @@ func initMiniFilerFlags() {
|
||||
miniFilerOptions.tusMaxSizeMB = cmdMini.Flag.Int("filer.tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB")
|
||||
miniFilerOptions.tusSessionExpiry = cmdMini.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration")
|
||||
miniFilerOptions.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
miniFilerOptions.remoteCacheEvictThreshold = cmdMini.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
}
|
||||
|
||||
// initMiniVolumeFlags initializes Volume server flag options
|
||||
|
||||
@@ -16,6 +16,13 @@ recursive_delete = false
|
||||
# for S3: how long to wait before deleting an empty folder.
|
||||
# increase this if using tools like Spark that create temporary directories.
|
||||
#s3.empty_folder_cleanup_delay = "2m"
|
||||
# where the filer's internal system metadata log chunks are stored.
|
||||
# By default the log follows the filer's -collection flag; set this to keep
|
||||
# the internal log in its own collection, out of the default one.
|
||||
# Keep the target stable: log chunks written under an older value are not
|
||||
# moved, and old log entries keep referencing that collection's volumes.
|
||||
#metaLog.collection = "filer-meta"
|
||||
#metaLog.replication = ""
|
||||
|
||||
####################################################
|
||||
# The following are filer store options
|
||||
|
||||
@@ -136,6 +136,7 @@ func init() {
|
||||
filerOptions.tusMaxSizeMB = cmdServer.Flag.Int("filer.tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB")
|
||||
filerOptions.tusSessionExpiry = cmdServer.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration, e.g. \"48h\", \"7h30m\"")
|
||||
filerOptions.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
filerOptions.remoteCacheEvictThreshold = cmdServer.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
|
||||
serverOptions.v.port = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
|
||||
serverOptions.v.portGrpc = cmdServer.Flag.Int("volume.port.grpc", 0, "volume server grpc listen port")
|
||||
|
||||
@@ -240,7 +240,7 @@ func (group *ChunkGroup) SetChunks(chunks []*filer_pb.FileChunk) error {
|
||||
continue
|
||||
}
|
||||
|
||||
resolvedChunks, err := resolveOneChunkManifest(context.Background(), group.lookupFn, chunk, group.cacheInvalidator, group.manifestCache)
|
||||
resolvedChunks, err := resolveOneChunkManifest(context.Background(), group.lookupFn, chunk, group.cacheInvalidator, group.manifestCache, nil)
|
||||
if err != nil {
|
||||
group.resolveErr = err
|
||||
return err
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
@@ -55,7 +56,16 @@ func SeparateManifestChunks(chunks []*filer_pb.FileChunk) (manifestChunks, nonMa
|
||||
}
|
||||
|
||||
func ResolveChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, startOffset, stopOffset int64, invalidator CacheInvalidator) (dataChunks, manifestChunks []*filer_pb.FileChunk, manifestResolveErr error) {
|
||||
resolver := newChunkManifestResolver(ctx, lookupFileIdFn, invalidator)
|
||||
resolver := newChunkManifestResolver(ctx, lookupFileIdFn, invalidator, nil)
|
||||
defer resolver.close()
|
||||
return resolver.resolve(chunks, startOffset, stopOffset)
|
||||
}
|
||||
|
||||
// ResolveChunkManifestWithFilerJwt is ResolveChunkManifest that signs proxied
|
||||
// manifest downloads with filerJwtFn instead of the process-wide filer read
|
||||
// key, for readers carrying per-source credentials.
|
||||
func ResolveChunkManifestWithFilerJwt(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, filerJwtFn security.FilerJwtProvider, chunks []*filer_pb.FileChunk, startOffset, stopOffset int64, invalidator CacheInvalidator) (dataChunks, manifestChunks []*filer_pb.FileChunk, manifestResolveErr error) {
|
||||
resolver := newChunkManifestResolver(ctx, lookupFileIdFn, invalidator, filerJwtFn)
|
||||
defer resolver.close()
|
||||
return resolver.resolve(chunks, startOffset, stopOffset)
|
||||
}
|
||||
@@ -81,6 +91,7 @@ type chunkManifestResolver struct {
|
||||
cancel context.CancelFunc
|
||||
lookupFileIdFn wdclient.LookupFileIdFunctionType
|
||||
invalidator CacheInvalidator
|
||||
filerJwtFn security.FilerJwtProvider
|
||||
jobs chan chunkManifestResolveJob
|
||||
overflowSem chan struct{}
|
||||
workers sync.WaitGroup
|
||||
@@ -88,7 +99,7 @@ type chunkManifestResolver struct {
|
||||
started bool
|
||||
}
|
||||
|
||||
func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator CacheInvalidator) *chunkManifestResolver {
|
||||
func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator CacheInvalidator, filerJwtFn security.FilerJwtProvider) *chunkManifestResolver {
|
||||
workCtx, cancel := context.WithCancel(ctx)
|
||||
resolver := &chunkManifestResolver{
|
||||
ctx: workCtx,
|
||||
@@ -96,6 +107,7 @@ func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.Looku
|
||||
cancel: cancel,
|
||||
lookupFileIdFn: lookupFileIdFn,
|
||||
invalidator: invalidator,
|
||||
filerJwtFn: filerJwtFn,
|
||||
jobs: make(chan chunkManifestResolveJob, chunkManifestResolveJobBufferSize),
|
||||
overflowSem: make(chan struct{}, maxChunkManifestResolveWorkers),
|
||||
}
|
||||
@@ -103,7 +115,7 @@ func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.Looku
|
||||
}
|
||||
|
||||
func (r *chunkManifestResolver) executeJob(job chunkManifestResolveJob) {
|
||||
job.result.chunks, job.result.err = ResolveOneChunkManifest(job.batchCtx, r.lookupFileIdFn, job.chunk, r.invalidator)
|
||||
job.result.chunks, job.result.err = resolveOneChunkManifest(job.batchCtx, r.lookupFileIdFn, job.chunk, r.invalidator, nil, r.filerJwtFn)
|
||||
if job.result.err != nil && r.parentCtx.Err() == nil {
|
||||
if job.batchCtx.Err() != nil && errors.Is(job.result.err, context.Canceled) {
|
||||
job.result.internalCancel = true
|
||||
@@ -293,14 +305,23 @@ func (r *chunkManifestResolver) resolve(chunks []*filer_pb.FileChunk, startOffse
|
||||
// Keeping this signature stable preserves the existing four-argument contract
|
||||
// for external callers.
|
||||
func ResolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunk *filer_pb.FileChunk, invalidator CacheInvalidator) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
|
||||
return resolveOneChunkManifest(ctx, lookupFileIdFn, chunk, invalidator, nil)
|
||||
return resolveOneChunkManifest(ctx, lookupFileIdFn, chunk, invalidator, nil, nil)
|
||||
}
|
||||
|
||||
// ResolveOneChunkManifestWithFilerJwt is ResolveOneChunkManifest that signs
|
||||
// proxied manifest downloads with filerJwtFn instead of the process-wide
|
||||
// filer read key, for readers carrying per-source credentials.
|
||||
func ResolveOneChunkManifestWithFilerJwt(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, filerJwtFn security.FilerJwtProvider, chunk *filer_pb.FileChunk, invalidator CacheInvalidator) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
|
||||
return resolveOneChunkManifest(ctx, lookupFileIdFn, chunk, invalidator, nil, filerJwtFn)
|
||||
}
|
||||
|
||||
// resolveOneChunkManifest is the cache-aware implementation. cache may be nil,
|
||||
// in which case the manifest is fetched and validated on every call, matching
|
||||
// the historical uncached behavior. A non-nil cache is owned by a single mount
|
||||
// (WFS) and coalesces concurrent cold misses via singleflight.
|
||||
func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunk *filer_pb.FileChunk, invalidator CacheInvalidator, cache *ChunkManifestCache) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
|
||||
// (WFS) and coalesces concurrent cold misses via singleflight. filerJwtFn
|
||||
// overrides the filer read credential for proxied downloads; nil means the
|
||||
// process-wide key.
|
||||
func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunk *filer_pb.FileChunk, invalidator CacheInvalidator, cache *ChunkManifestCache, filerJwtFn security.FilerJwtProvider) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
|
||||
if !chunk.IsChunkManifest {
|
||||
return
|
||||
}
|
||||
@@ -318,7 +339,7 @@ func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.Lookup
|
||||
bytesBuffer := bytesBufferPool.Get().(*bytes.Buffer)
|
||||
bytesBuffer.Reset()
|
||||
defer bytesBufferPool.Put(bytesBuffer)
|
||||
if err := fetchWholeChunk(ctx, bytesBuffer, lookupFileIdFn, key.fileID, chunk.CipherKey, chunk.IsCompressed, invalidator); err != nil {
|
||||
if err := fetchWholeChunk(ctx, bytesBuffer, lookupFileIdFn, key.fileID, chunk.CipherKey, chunk.IsCompressed, invalidator, filerJwtFn); err != nil {
|
||||
return nil, fmt.Errorf("fail to read manifest %s: %w", key.fileID, err)
|
||||
}
|
||||
// Copy before the buffer returns to the pool so concurrent callers
|
||||
@@ -357,13 +378,18 @@ func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.Lookup
|
||||
return m.Chunks, nil
|
||||
}
|
||||
|
||||
func fetchWholeChunk(ctx context.Context, bytesBuffer *bytes.Buffer, lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool, invalidator CacheInvalidator) error {
|
||||
func fetchWholeChunk(ctx context.Context, bytesBuffer *bytes.Buffer, lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool, invalidator CacheInvalidator, filerJwtFn security.FilerJwtProvider) error {
|
||||
urlStrings, err := lookupFileIdFn(ctx, fileId)
|
||||
if err != nil {
|
||||
glog.ErrorfCtx(ctx, "operation LookupFileId %s failed, err: %v", fileId, err)
|
||||
return err
|
||||
}
|
||||
jwt := ChunkReadJwt(urlStrings, fileId)
|
||||
var jwt string
|
||||
if filerJwtFn != nil && len(urlStrings) > 0 && util_http.IsProxyChunkUrl(urlStrings[0]) {
|
||||
jwt = string(filerJwtFn(false))
|
||||
} else {
|
||||
jwt = ChunkReadJwt(urlStrings, fileId)
|
||||
}
|
||||
if _, err = retriedStreamFetchChunkData(ctx, bytesBuffer, urlStrings, jwt, cipherKey, isGzipped, true, 0, 0, refreshUrls(ctx, invalidator, lookupFileIdFn, fileId)); err == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -380,15 +406,6 @@ func fetchWholeChunk(ctx context.Context, bytesBuffer *bytes.Buffer, lookupFileI
|
||||
})
|
||||
}
|
||||
|
||||
func fetchChunkRange(ctx context.Context, buffer []byte, lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool, offset int64, refreshUrls util_http.RefreshUrlsFunc) (int, error) {
|
||||
urlStrings, err := lookupFileIdFn(ctx, fileId)
|
||||
if err != nil {
|
||||
glog.ErrorfCtx(ctx, "operation LookupFileId %s failed, err: %v", fileId, err)
|
||||
return 0, err
|
||||
}
|
||||
return util_http.RetriedFetchChunkData(ctx, buffer, urlStrings, cipherKey, isGzipped, false, offset, fileId, refreshUrls)
|
||||
}
|
||||
|
||||
// retriedStreamFetchChunkData streams a chunk from the first location that
|
||||
// answers. refreshUrls may be nil; when a location failed and a later one
|
||||
// answered, it is called so the reads that follow start from a fresh list.
|
||||
|
||||
@@ -23,7 +23,7 @@ func BenchmarkManifestResolutionRepeatedOpen(b *testing.B) {
|
||||
}
|
||||
chunk := newManifestCacheTestChunk("benchmark-cached")
|
||||
cache := NewChunkManifestCache(MaxMountChunkManifestCacheEntries, MaxMountChunkManifestCacheBytes)
|
||||
_, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache)
|
||||
_, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache, nil)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func BenchmarkManifestResolutionRepeatedOpen(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if _, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache); err != nil {
|
||||
if _, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache, nil); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,7 +258,7 @@ func TestResolveOneChunkManifestHonorsCanceledContextOnCacheHit(t *testing.T) {
|
||||
return nil, errors.New("lookup should not be called")
|
||||
}
|
||||
|
||||
_, err := resolveOneChunkManifest(ctx, lookup, chunk, nil, cache)
|
||||
_, err := resolveOneChunkManifest(ctx, lookup, chunk, nil, cache, nil)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
require.False(t, lookupCalled, "a canceled cache hit must not issue a lookup")
|
||||
}
|
||||
@@ -278,7 +278,7 @@ func TestResolveOneChunkManifestCanceledWaiterReturnsDuringCoalescedMiss(t *test
|
||||
defer leaderCancel()
|
||||
leaderDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := resolveOneChunkManifest(leaderCtx, fixture.lookup, chunk, nil, cache)
|
||||
_, err := resolveOneChunkManifest(leaderCtx, fixture.lookup, chunk, nil, cache, nil)
|
||||
leaderDone <- err
|
||||
}()
|
||||
|
||||
@@ -287,7 +287,7 @@ func TestResolveOneChunkManifestCanceledWaiterReturnsDuringCoalescedMiss(t *test
|
||||
// for the leader's result.
|
||||
waiterCtx, waiterCancel := context.WithCancel(context.Background())
|
||||
waiterCancel()
|
||||
_, err := resolveOneChunkManifest(waiterCtx, fixture.lookup, chunk, nil, cache)
|
||||
_, err := resolveOneChunkManifest(waiterCtx, fixture.lookup, chunk, nil, cache, nil)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
|
||||
// The leader must still complete successfully and populate the cache.
|
||||
|
||||
@@ -13,9 +13,12 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
func TestDoMaybeManifestize(t *testing.T) {
|
||||
@@ -621,7 +624,7 @@ func TestFetchWholeChunkRetriesFreshLocations(t *testing.T) {
|
||||
inv := &countingInvalidator{}
|
||||
bytesBuffer := fetchManifestBuffer(t)
|
||||
|
||||
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,stale", nil, false, inv))
|
||||
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,stale", nil, false, inv, nil))
|
||||
assert.Equal(t, int32(1), inv.invalidations.Load())
|
||||
assert.Equal(t, int32(2), lookup.calls.Load())
|
||||
|
||||
@@ -655,7 +658,7 @@ func TestFetchWholeChunkRefreshesLocationsAfterPartialFailure(t *testing.T) {
|
||||
inv := &countingInvalidator{}
|
||||
bytesBuffer := fetchManifestBuffer(t)
|
||||
|
||||
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,abc", nil, false, inv))
|
||||
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,abc", nil, false, inv, nil))
|
||||
assert.Equal(t, int32(1), inv.invalidations.Load())
|
||||
assert.Equal(t, int32(2), lookup.calls.Load())
|
||||
decoded := &filer_pb.FileChunkManifest{}
|
||||
@@ -676,7 +679,7 @@ func TestFetchWholeChunkWithoutInvalidator(t *testing.T) {
|
||||
freshUrls: []string{"http://unused:8080/5,abc"},
|
||||
}
|
||||
|
||||
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, nil))
|
||||
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, nil, nil))
|
||||
assert.Equal(t, int32(1), lookup.calls.Load())
|
||||
}
|
||||
|
||||
@@ -694,7 +697,7 @@ func TestFetchWholeChunkUnchangedLocations(t *testing.T) {
|
||||
}
|
||||
inv := &countingInvalidator{}
|
||||
|
||||
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv))
|
||||
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv, nil))
|
||||
assert.Equal(t, int32(2), lookup.calls.Load())
|
||||
assert.Equal(t, int32(1), inv.invalidations.Load())
|
||||
}
|
||||
@@ -711,7 +714,7 @@ func TestFetchWholeChunkCancelledKeepsLocations(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
err := fetchWholeChunk(ctx, fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv)
|
||||
err := fetchWholeChunk(ctx, fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv, nil)
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
assert.Equal(t, int32(0), inv.invalidations.Load())
|
||||
assert.Equal(t, int32(1), lookup.calls.Load())
|
||||
@@ -730,3 +733,51 @@ func TestFetchWholeChunkCancelledKeepsLocations(t *testing.T) {
|
||||
})
|
||||
assert.ErrorIs(t, noInvalidator, context.Canceled)
|
||||
}
|
||||
|
||||
// TestFetchWholeChunkUsesProvidedFilerJwt covers a replicating reader whose
|
||||
// source filer authenticates proxied downloads with its own read key: the
|
||||
// supplied provider's token must reach the server, not the process-wide one.
|
||||
func TestFetchWholeChunkUsesProvidedFilerJwt(t *testing.T) {
|
||||
manifestBytes, err := proto.Marshal(&filer_pb.FileChunkManifest{
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: "100,abc", Offset: 0, Size: 8}},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
gotAuth := make(chan string, 1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
select {
|
||||
case gotAuth <- r.Header.Get("Authorization"):
|
||||
default:
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(manifestBytes)))
|
||||
w.Write(manifestBytes)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
lookup := func(ctx context.Context, fileId string) ([]string, error) {
|
||||
return []string{srv.URL + "/?" + util_http.ProxyChunkIdParam + "=" + fileId}, nil
|
||||
}
|
||||
jwtFn := func(isWrite bool) security.EncodedJwt {
|
||||
assert.False(t, isWrite)
|
||||
return "side-read-jwt"
|
||||
}
|
||||
bytesBuffer := fetchManifestBuffer(t)
|
||||
require.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup, "5,abc", nil, false, nil, jwtFn))
|
||||
select {
|
||||
case auth := <-gotAuth:
|
||||
assert.Equal(t, security.BearerPrefix+"side-read-jwt", auth)
|
||||
default:
|
||||
t.Fatal("the proxied fetch never reached the handler")
|
||||
}
|
||||
|
||||
// non-proxy URLs keep the volume-server credential and never call the provider
|
||||
volumeURL := manifestServer(t, manifestBytes).URL + "/5,abc"
|
||||
volumeLookup := func(ctx context.Context, fileId string) ([]string, error) {
|
||||
return []string{volumeURL}, nil
|
||||
}
|
||||
bytesBuffer.Reset()
|
||||
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, volumeLookup, "5,abc", nil, false, nil, func(bool) security.EncodedJwt {
|
||||
t.Fatal("provider must not be consulted for a volume url")
|
||||
return ""
|
||||
}))
|
||||
}
|
||||
@@ -185,6 +185,15 @@ func (cv *ChunkView) IsFullChunk() bool {
|
||||
return cv.OffsetInChunk == 0 && cv.ViewSize == cv.ChunkSize
|
||||
}
|
||||
|
||||
// CanRangeFetch reports whether fetching just the view's byte range avoids
|
||||
// reading more than the view needs. Ciphered and compressed chunks are
|
||||
// stored and served whole — a range on either still costs a full read plus
|
||||
// decrypt or decompress on the volume server — so partial views of them
|
||||
// take the shared whole-chunk path instead.
|
||||
func (cv *ChunkView) CanRangeFetch() bool {
|
||||
return cv.CipherKey == nil && !cv.IsGzipped
|
||||
}
|
||||
|
||||
func ViewFromChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, offset int64, size int64) (chunkViews *IntervalList[*ChunkView]) {
|
||||
|
||||
visibles, _ := NonOverlappingVisibleIntervals(ctx, lookupFileIdFn, chunks, offset, offset+size)
|
||||
|
||||
+83
-15
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -23,6 +24,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -45,17 +47,22 @@ var (
|
||||
)
|
||||
|
||||
type Filer struct {
|
||||
UniqueFilerId int32
|
||||
UniqueFilerEpoch int32
|
||||
Store VirtualFilerStore
|
||||
MasterClient *wdclient.MasterClient
|
||||
FileIdDeletionQueue *util.UnboundedQueue
|
||||
GrpcDialOption grpc.DialOption
|
||||
DirBucketsPath string
|
||||
Cipher bool
|
||||
LocalMetaLogBuffer *log_buffer.LogBuffer
|
||||
metaLogCollection string
|
||||
metaLogReplication string
|
||||
UniqueFilerId int32
|
||||
UniqueFilerEpoch int32
|
||||
Store VirtualFilerStore
|
||||
MasterClient *wdclient.MasterClient
|
||||
FileIdDeletionQueue *util.UnboundedQueue
|
||||
GrpcDialOption grpc.DialOption
|
||||
DirBucketsPath string
|
||||
Cipher bool
|
||||
LocalMetaLogBuffer *log_buffer.LogBuffer
|
||||
metaLogCollection string
|
||||
metaLogReplication string
|
||||
// Override where system metadata-log chunks are assigned, keeping the
|
||||
// internal log out of the default collection; empty keeps today's
|
||||
// behaviour. Set via viper: filer.options.metaLog.collection / .replication.
|
||||
metaLogTargetCollection string
|
||||
metaLogTargetReplication string
|
||||
DefaultDiskType string
|
||||
MetaAggregator *MetaAggregator
|
||||
Signature int32
|
||||
@@ -79,6 +86,30 @@ type Filer struct {
|
||||
// rebuild finishes; lazy remote reads wait on it so a pending delete
|
||||
// cannot resurrect in the gap.
|
||||
remoteTombstonesDone atomic.Pointer[chan struct{}]
|
||||
|
||||
// Durable deletion ledger (see filer_deletion_persist.go). The set of
|
||||
// fileIds that still need deleting but are not yet confirmed gone, mirrored
|
||||
// to the store so a restart does not leak chunks. Guarded by
|
||||
// deletionLedgerLock; nil-safe for Filer literals in tests.
|
||||
// pendingDeletions maps each id to its enqueue epoch so an expiry-forget
|
||||
// cannot erase a re-queued id.
|
||||
deletionLedgerLock sync.Mutex
|
||||
pendingDeletions map[string]uint64
|
||||
deletionSeq uint64
|
||||
deletionLedgerDirty bool
|
||||
deletionLedgerParts int
|
||||
deletionLedgerGen int
|
||||
// deletionLedgerStale holds orphan part keys from abandoned multipart
|
||||
// writes, retried on the next snapshot.
|
||||
deletionLedgerStale []string
|
||||
// deletionSnapshotLock serializes ledger writes in copy order so an
|
||||
// in-flight timer snapshot cannot overwrite a newer shutdown snapshot.
|
||||
deletionSnapshotLock sync.Mutex
|
||||
// deletionLedgerBlocked is set when the startup ledger read fails: the
|
||||
// persisted set is then unknown, so snapshots retry the read instead of
|
||||
// overwriting the unread ledger with a partial set.
|
||||
deletionLedgerBlocked atomic.Bool
|
||||
deletionLedgerFlush chan struct{}
|
||||
}
|
||||
|
||||
func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerHost pb.ServerAddress, filerGroup string, collection string, replication string, dataCenter string, maxFilenameLength uint32, notifyFn func()) *Filer {
|
||||
@@ -92,6 +123,7 @@ func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerH
|
||||
Dlm: lock_manager.NewDistributedLockManager(filerHost),
|
||||
MaxFilenameLength: maxFilenameLength,
|
||||
deletionQuit: make(chan struct{}),
|
||||
deletionLedgerFlush: make(chan struct{}, 1),
|
||||
DeletionRetryQueue: NewDeletionRetryQueue(),
|
||||
persistedLogCache: newPersistedLogCache(persistedLogCacheMaxBytes),
|
||||
remoteTombstones: newRemoteDeletionTombstones(),
|
||||
@@ -110,6 +142,19 @@ func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerH
|
||||
f.metaLogCollection = collection
|
||||
f.metaLogReplication = replication
|
||||
|
||||
// Optional override for where the system metadata-log chunks land, so
|
||||
// operators can keep internal log volumes out of the default collection.
|
||||
// Unset (""), this changes nothing: meta logs keep following the filer
|
||||
// default exactly as before.
|
||||
v := util.GetViper()
|
||||
v.SetDefault("filer.options.metaLog.collection", "")
|
||||
v.SetDefault("filer.options.metaLog.replication", "")
|
||||
f.metaLogTargetCollection = v.GetString("filer.options.metaLog.collection")
|
||||
f.metaLogTargetReplication = v.GetString("filer.options.metaLog.replication")
|
||||
if f.metaLogTargetCollection != "" {
|
||||
glog.V(0).Infof("system metadata logs will be stored in collection %q", f.metaLogTargetCollection)
|
||||
}
|
||||
|
||||
if newPlacementOverlay != nil {
|
||||
f.placementOverlay = newPlacementOverlay(f)
|
||||
}
|
||||
@@ -209,7 +254,16 @@ func (f *Filer) ListExistingPeerUpdates(ctx context.Context) (existingNodes []*m
|
||||
func (f *Filer) SetStore(store FilerStore) (isFresh bool) {
|
||||
f.Store = NewFilerStoreWrapper(store)
|
||||
|
||||
return f.setOrLoadFilerStoreSignature(store)
|
||||
isFresh = f.setOrLoadFilerStoreSignature(store)
|
||||
|
||||
// Recover deletions that were pending when a previous process died, and keep
|
||||
// the durable ledger snapshotted while running (see filer_deletion_persist.go).
|
||||
// A failed ledger read leaves writes blocked until a snapshot retries and
|
||||
// the read succeeds, so the unread ledger is never overwritten.
|
||||
f.reloadDeletionLedger()
|
||||
f.startDeletionLedgerSnapshotter()
|
||||
|
||||
return isFresh
|
||||
}
|
||||
|
||||
func (f *Filer) setOrLoadFilerStoreSignature(store FilerStore) (isFresh bool) {
|
||||
@@ -327,7 +381,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
return fmt.Errorf("%s: %w", entry.FullPath, filer_pb.ErrEntryAlreadyExists)
|
||||
}
|
||||
glog.V(4).InfofCtx(ctx, "UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
|
||||
if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
|
||||
if err := f.UpdateEntry(ctx, oldEntry, entry, isFromOtherCluster); err != nil {
|
||||
if errors.Is(err, filer_pb.ErrExistingIsDirectory) || errors.Is(err, filer_pb.ErrExistingIsFile) {
|
||||
glog.V(2).InfofCtx(ctx, "update entry %s: %v", entry.FullPath, err)
|
||||
} else {
|
||||
@@ -482,7 +536,7 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath,
|
||||
narrowed := existing.ShallowClone()
|
||||
narrowed.Mode = existing.Mode&^restorableModeBits | kept
|
||||
glog.V(1).InfofCtx(ctx, "restore directory %s: narrowing %v to %v", dirPath, existing.Mode, narrowed.Mode)
|
||||
if err := f.UpdateEntry(ctx, existing, narrowed); err != nil {
|
||||
if err := f.UpdateEntry(ctx, existing, narrowed, false); err != nil {
|
||||
return err
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, existing, narrowed, false, false, nil)
|
||||
@@ -515,7 +569,7 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
|
||||
func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry, isFromOtherCluster bool) (err error) {
|
||||
if oldEntry != nil {
|
||||
entry.Attr.Crtime = oldEntry.Attr.Crtime
|
||||
if oldEntry.Attr.Inode != 0 {
|
||||
@@ -535,6 +589,17 @@ func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err er
|
||||
glog.V(2).InfofCtx(ctx, "existing %s is a file", oldEntry.FullPath)
|
||||
return fmt.Errorf("%s: %w", oldEntry.FullPath, filer_pb.ErrExistingIsFile)
|
||||
}
|
||||
// A local write to a remote-backed entry leaves the copy on remote
|
||||
// stale until a sync re-uploads it. Content changes that arrive
|
||||
// without a fresh sync stamp are unsynced; clear the stamp so nothing
|
||||
// mistakes the still-local chunks for a re-fetchable cache copy.
|
||||
// Replicated updates carry the writer's authoritative stamp.
|
||||
if !isFromOtherCluster && oldEntry.Remote != nil && entry.Remote != nil &&
|
||||
oldEntry.Remote.LastLocalSyncTsNs == entry.Remote.LastLocalSyncTsNs &&
|
||||
!chunksEqual(oldEntry.Chunks, entry.Chunks) {
|
||||
entry.Remote = proto.Clone(entry.Remote).(*filer_pb.RemoteEntry)
|
||||
entry.Remote.LastLocalSyncTsNs = 0
|
||||
}
|
||||
}
|
||||
if entry.Attr.Atime.IsZero() {
|
||||
entry.Attr.Atime = entryInitialAtime(entry.Attr)
|
||||
@@ -746,6 +811,9 @@ func (f *Filer) Shutdown() {
|
||||
f.LocalMetaLogBuffer.ShutdownLogBuffer()
|
||||
// The final metadata-log flush still needs the store to append its entry.
|
||||
f.LocalMetaLogBuffer.WaitForShutdown()
|
||||
// Persist the deletion ledger one last time before the store closes, so a
|
||||
// clean shutdown leaves the recovery set exactly consistent with reality.
|
||||
f.snapshotDeletionLedger()
|
||||
f.Store.Shutdown()
|
||||
}
|
||||
|
||||
|
||||
@@ -262,8 +262,9 @@ func TestClearReadOnly(t *testing.T) {
|
||||
type fakeFilerConfClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
|
||||
mu sync.Mutex
|
||||
entries map[string]*filer_pb.Entry // key: dir+"/"+name
|
||||
mu sync.Mutex
|
||||
entries map[string]*filer_pb.Entry // key: dir+"/"+name
|
||||
updateCalls int
|
||||
}
|
||||
|
||||
func newFakeFilerConfClient() *fakeFilerConfClient {
|
||||
@@ -310,6 +311,7 @@ func (c *fakeFilerConfClient) CreateEntry(_ context.Context, in *filer_pb.Create
|
||||
func (c *fakeFilerConfClient) UpdateEntry(_ context.Context, in *filer_pb.UpdateEntryRequest, _ ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.updateCalls++
|
||||
key := c.key(in.Directory, in.Entry.Name)
|
||||
if !conditionHoldsLocked(in.Condition, c.entries[key]) {
|
||||
return nil, errors.New("precondition failed")
|
||||
|
||||
@@ -72,9 +72,12 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
if isDeleteCollection {
|
||||
collectionName = f.bucketCollection(ctx, entry.Name())
|
||||
}
|
||||
// A preserved collection outlives the bucket, so its chunks are collected
|
||||
// per entry rather than dropped wholesale with it.
|
||||
dropsCollection := isDeleteCollection && collectionName != ""
|
||||
if entry.IsDirectory() {
|
||||
// delete the folder children, not including the folder itself
|
||||
err = f.doBatchDeleteFolderMetaAndData(ctx, entry, isRecursive, ignoreRecursiveError, shouldDeleteChunks && !isDeleteCollection, isDeleteCollection, isFromOtherCluster, signatures, func(hardLinkIds []HardLinkId) error {
|
||||
err = f.doBatchDeleteFolderMetaAndData(ctx, entry, isRecursive, ignoreRecursiveError, shouldDeleteChunks && !dropsCollection, isDeleteCollection && (dropsCollection || !shouldDeleteChunks), isFromOtherCluster, signatures, func(hardLinkIds []HardLinkId) error {
|
||||
// A case not handled:
|
||||
// what if the chunk is in a different collection?
|
||||
if shouldDeleteChunks {
|
||||
@@ -97,7 +100,7 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
return fmt.Errorf("delete file %s: %v", p, err)
|
||||
}
|
||||
|
||||
if shouldDeleteChunks && !isDeleteCollection {
|
||||
if shouldDeleteChunks && !dropsCollection {
|
||||
if len(entry.HardLinkId) != 0 && entry.HardLinkCounter > 1 {
|
||||
// if the file is a hard link and there are other hard links, do not delete the chunks
|
||||
} else {
|
||||
@@ -261,10 +264,17 @@ func (f *Filer) bucketCollection(ctx context.Context, bucket string) (collection
|
||||
collection = resolve(bucketDir, bucket)
|
||||
|
||||
// Rule-less writes outside buckets fall back to the filer's default
|
||||
// collection, so a bucket resolving there shares it with them.
|
||||
// collection, so a bucket resolving there shares it with them. The
|
||||
// system metadata-log collection (when explicitly redirected via
|
||||
// filer.options.metaLog.collection) is in the same boat: it backs internal
|
||||
// log volumes, so a bucket that resolves there must never drop it
|
||||
// either.
|
||||
if collection == f.metaLogCollection {
|
||||
return ""
|
||||
}
|
||||
if f.metaLogTargetCollection != "" && collection == f.metaLogTargetCollection {
|
||||
return ""
|
||||
}
|
||||
|
||||
// A rule whose prefix escapes the bucket can route other paths into the
|
||||
// same collection, including prefixes nested under surviving buckets.
|
||||
|
||||
@@ -66,8 +66,9 @@ type DeletionRetryItem struct {
|
||||
RetryCount int
|
||||
NextRetryAt time.Time
|
||||
LastError string
|
||||
heapIndex int // index in the heap (for heap.Interface)
|
||||
inFlight bool // true when item is being processed, prevents duplicate additions
|
||||
ledgerEpoch uint64 // pendingDeletions epoch when the item was queued; expiry forgets only a matching epoch
|
||||
heapIndex int // index in the heap (for heap.Interface)
|
||||
inFlight bool // true when item is being processed, prevents duplicate additions
|
||||
}
|
||||
|
||||
// retryHeap implements heap.Interface for DeletionRetryItem
|
||||
@@ -163,7 +164,7 @@ func calculateBackoff(retryCount int) time.Duration {
|
||||
|
||||
// AddOrUpdate adds a new failed deletion or updates an existing one
|
||||
// Time complexity: O(log N) for insertion/update
|
||||
func (q *DeletionRetryQueue) AddOrUpdate(fileId string, errorMsg string) {
|
||||
func (q *DeletionRetryQueue) AddOrUpdate(fileId string, errorMsg string, ledgerEpoch uint64) {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
@@ -173,6 +174,13 @@ func (q *DeletionRetryQueue) AddOrUpdate(fileId string, errorMsg string) {
|
||||
// The existing retry schedule should proceed.
|
||||
// RetryCount is only incremented in RequeueForRetry when an actual retry is performed.
|
||||
item.LastError = errorMsg
|
||||
// Keep the recorded epoch while the item is in flight: an expiry or
|
||||
// permanent outcome from that attempt must forget only the record it
|
||||
// started with, not a newer enqueue for the same id. This also keeps
|
||||
// the field immutable once the worker can read it without the lock.
|
||||
if !item.inFlight {
|
||||
item.ledgerEpoch = ledgerEpoch
|
||||
}
|
||||
if item.inFlight {
|
||||
glog.V(2).Infof("retry for %s in-flight: attempt %d, will preserve retry state", fileId, item.RetryCount)
|
||||
} else {
|
||||
@@ -188,6 +196,7 @@ func (q *DeletionRetryQueue) AddOrUpdate(fileId string, errorMsg string) {
|
||||
RetryCount: 1,
|
||||
NextRetryAt: time.Now().Add(delay),
|
||||
LastError: errorMsg,
|
||||
ledgerEpoch: ledgerEpoch,
|
||||
inFlight: false,
|
||||
}
|
||||
heap.Push(&q.heap, item)
|
||||
@@ -216,18 +225,19 @@ func (q *DeletionRetryQueue) RequeueForRetry(item *DeletionRetryItem, errorMsg s
|
||||
heap.Push(&q.heap, item)
|
||||
}
|
||||
|
||||
// GetReadyItems returns items that are ready to be retried and marks them as in-flight
|
||||
// GetReadyItems returns items that are ready to be retried and marks them as in-flight.
|
||||
// Expired reports fileIds dropped for exceeding MaxRetryAttempts — permanent
|
||||
// dropouts the caller must also forget in the durable deletion ledger.
|
||||
// Time complexity: O(K log N) where K is the number of ready items
|
||||
// Items are processed in order of NextRetryAt (earliest first)
|
||||
func (q *DeletionRetryQueue) GetReadyItems(maxItems int) []*DeletionRetryItem {
|
||||
func (q *DeletionRetryQueue) GetReadyItems(maxItems int) (ready []*DeletionRetryItem, expired []*DeletionRetryItem) {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
var readyItems []*DeletionRetryItem
|
||||
|
||||
// Peek at items from the top of the heap (earliest NextRetryAt)
|
||||
for len(q.heap) > 0 && len(readyItems) < maxItems {
|
||||
for len(q.heap) > 0 && len(ready) < maxItems {
|
||||
item := q.heap[0]
|
||||
|
||||
// If the earliest item is not ready yet, no other items are ready either
|
||||
@@ -240,15 +250,16 @@ func (q *DeletionRetryQueue) GetReadyItems(maxItems int) []*DeletionRetryItem {
|
||||
|
||||
if item.RetryCount <= MaxRetryAttempts {
|
||||
item.inFlight = true // Mark as being processed
|
||||
readyItems = append(readyItems, item)
|
||||
ready = append(ready, item)
|
||||
} else {
|
||||
// Max attempts reached, log and discard completely
|
||||
delete(q.itemIndex, item.FileId)
|
||||
expired = append(expired, item)
|
||||
glog.Warningf("max retry attempts (%d) reached for %s, last error: %s", MaxRetryAttempts, item.FileId, item.LastError)
|
||||
}
|
||||
}
|
||||
|
||||
return readyItems
|
||||
return ready, expired
|
||||
}
|
||||
|
||||
// Remove removes an item from the queue (called when deletion succeeds or fails permanently)
|
||||
@@ -306,24 +317,29 @@ func (f *Filer) loopProcessingDeletion() {
|
||||
glog.V(0).Infof("deletion processor shutting down")
|
||||
return
|
||||
case <-ticker.C:
|
||||
f.FileIdDeletionQueue.Consume(func(fileIds []string) {
|
||||
for i := 0; i < len(fileIds); i += DeletionBatchSize {
|
||||
end := i + DeletionBatchSize
|
||||
if end > len(fileIds) {
|
||||
end = len(fileIds)
|
||||
}
|
||||
toDeleteFileIds := fileIds[i:end]
|
||||
f.processDeletionBatch(toDeleteFileIds, lookupFunc)
|
||||
}
|
||||
})
|
||||
f.FlushFileIdDeletionQueue(context.Background(), lookupFunc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) FlushFileIdDeletionQueue(ctx context.Context, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) (consumed []string) {
|
||||
f.FileIdDeletionQueue.Consume(func(fileIds []string) {
|
||||
consumed = fileIds
|
||||
for i := 0; i < len(fileIds); i += DeletionBatchSize {
|
||||
end := i + DeletionBatchSize
|
||||
if end > len(fileIds) {
|
||||
end = len(fileIds)
|
||||
}
|
||||
f.processDeletionBatch(ctx, fileIds[i:end], lookupFunc)
|
||||
}
|
||||
})
|
||||
return consumed
|
||||
}
|
||||
|
||||
// processDeletionBatch handles deletion of a batch of file IDs and processes results.
|
||||
// It classifies errors into retryable and permanent categories, adds retryable failures
|
||||
// to the retry queue, and logs appropriate messages.
|
||||
func (f *Filer) processDeletionBatch(toDeleteFileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) {
|
||||
func (f *Filer) processDeletionBatch(ctx context.Context, toDeleteFileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) {
|
||||
// Deduplicate file IDs to prevent incorrect retry count increments for the same file ID within a single batch.
|
||||
uniqueFileIdsSlice := make([]string, 0, len(toDeleteFileIds))
|
||||
processed := make(map[string]struct{}, len(toDeleteFileIds))
|
||||
@@ -338,8 +354,15 @@ func (f *Filer) processDeletionBatch(toDeleteFileIds []string, lookupFunc func([
|
||||
return
|
||||
}
|
||||
|
||||
// Remember each id's ledger epoch before the remote deletes run: a
|
||||
// permanent outcome below must not erase a record re-queued mid-flight.
|
||||
epochs := make(map[string]uint64, len(uniqueFileIdsSlice))
|
||||
for _, fileId := range uniqueFileIdsSlice {
|
||||
epochs[fileId] = f.deletionEpoch(fileId)
|
||||
}
|
||||
|
||||
// Delete files and classify outcomes
|
||||
outcomes := deleteFilesAndClassify(f.GrpcDialOption, uniqueFileIdsSlice, lookupFunc)
|
||||
outcomes := deleteFilesAndClassify(ctx, f.GrpcDialOption, uniqueFileIdsSlice, lookupFunc)
|
||||
|
||||
// Process outcomes
|
||||
var successCount, notFoundCount, retryableErrorCount, permanentErrorCount int
|
||||
@@ -351,16 +374,21 @@ func (f *Filer) processDeletionBatch(toDeleteFileIds []string, lookupFunc func([
|
||||
switch outcome.status {
|
||||
case deletionOutcomeSuccess:
|
||||
successCount++
|
||||
f.forgetDeletion(fileId) // confirmed gone: drop from durable ledger
|
||||
case deletionOutcomeNotFound:
|
||||
notFoundCount++
|
||||
f.forgetDeletion(fileId) // already gone: drop from durable ledger
|
||||
case deletionOutcomeRetryable, deletionOutcomeNoResult:
|
||||
retryableErrorCount++
|
||||
f.DeletionRetryQueue.AddOrUpdate(fileId, outcome.errorMsg)
|
||||
// Keep in the durable ledger: not confirmed, must survive restarts.
|
||||
f.DeletionRetryQueue.AddOrUpdate(fileId, outcome.errorMsg, f.deletionEpoch(fileId))
|
||||
if len(errorDetails) < MaxLoggedErrorDetails {
|
||||
errorDetails = append(errorDetails, fileId+": "+outcome.errorMsg+" (will retry)")
|
||||
}
|
||||
case deletionOutcomePermanent:
|
||||
permanentErrorCount++
|
||||
// gave up: drop the record, unless the id was re-queued meanwhile
|
||||
f.forgetDeletionEpoch(fileId, epochs[fileId])
|
||||
if len(errorDetails) < MaxLoggedErrorDetails {
|
||||
errorDetails = append(errorDetails, fileId+": "+outcome.errorMsg+" (permanent)")
|
||||
}
|
||||
@@ -405,9 +433,9 @@ type deletionOutcome struct {
|
||||
}
|
||||
|
||||
// deleteFilesAndClassify performs deletion and classifies outcomes for a list of file IDs
|
||||
func deleteFilesAndClassify(grpcDialOption grpc.DialOption, fileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) map[string]deletionOutcome {
|
||||
func deleteFilesAndClassify(ctx context.Context, grpcDialOption grpc.DialOption, fileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) map[string]deletionOutcome {
|
||||
// Perform deletion
|
||||
results := operation.DeleteFileIdsWithLookupVolumeId(grpcDialOption, fileIds, lookupFunc)
|
||||
results := operation.DeleteFileIdsWithLookupVolumeId(ctx, grpcDialOption, fileIds, lookupFunc)
|
||||
|
||||
// Group results by file ID to handle multiple results for replicated volumes
|
||||
resultsByFileId := make(map[string][]*volume_server_pb.DeleteResult)
|
||||
@@ -518,7 +546,16 @@ func (f *Filer) loopProcessingDeletionRetry(lookupFunc func([]string) (map[strin
|
||||
// Process all ready items in batches until queue is empty
|
||||
totalProcessed := 0
|
||||
for {
|
||||
readyItems := f.DeletionRetryQueue.GetReadyItems(DeletionRetryBatchSize)
|
||||
readyItems, expired := f.DeletionRetryQueue.GetReadyItems(DeletionRetryBatchSize)
|
||||
for _, item := range expired {
|
||||
// Permanently discarded — drop the ledger record, but only
|
||||
// if the id was not re-queued after this retry item was
|
||||
// recorded. A surviving newer record still needs work, so
|
||||
// it goes back through the hot queue.
|
||||
if !f.forgetDeletionEpoch(item.FileId, item.ledgerEpoch) {
|
||||
f.queueDeletions(item.FileId)
|
||||
}
|
||||
}
|
||||
if len(readyItems) == 0 {
|
||||
break
|
||||
}
|
||||
@@ -545,7 +582,7 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
|
||||
}
|
||||
|
||||
// Delete files and classify outcomes
|
||||
outcomes := deleteFilesAndClassify(f.GrpcDialOption, fileIds, lookupFunc)
|
||||
outcomes := deleteFilesAndClassify(context.Background(), f.GrpcDialOption, fileIds, lookupFunc)
|
||||
|
||||
// Process outcomes - iterate over readyItems to ensure all items are accounted for
|
||||
var successCount, notFoundCount, retryCount, permanentErrorCount int
|
||||
@@ -556,19 +593,27 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
|
||||
case deletionOutcomeSuccess:
|
||||
successCount++
|
||||
f.DeletionRetryQueue.Remove(item) // Remove from queue (success)
|
||||
f.forgetDeletion(item.FileId) // confirmed gone: drop from durable ledger
|
||||
glog.V(2).Infof("retry successful for %s after %d attempts", item.FileId, item.RetryCount)
|
||||
case deletionOutcomeNotFound:
|
||||
notFoundCount++
|
||||
f.DeletionRetryQueue.Remove(item) // Remove from queue (already deleted)
|
||||
f.forgetDeletion(item.FileId) // already gone: drop from durable ledger
|
||||
case deletionOutcomeRetryable, deletionOutcomeNoResult:
|
||||
retryCount++
|
||||
if outcome.status == deletionOutcomeNoResult {
|
||||
glog.Warningf("no deletion result for retried file %s, re-queuing to avoid loss", item.FileId)
|
||||
}
|
||||
// Keep in the durable ledger: still not confirmed.
|
||||
f.DeletionRetryQueue.RequeueForRetry(item, outcome.errorMsg)
|
||||
case deletionOutcomePermanent:
|
||||
permanentErrorCount++
|
||||
f.DeletionRetryQueue.Remove(item) // Remove from queue (permanent failure)
|
||||
// gave up: drop the record, unless the id was re-queued meanwhile
|
||||
// — a surviving newer record goes back through the hot queue.
|
||||
if !f.forgetDeletionEpoch(item.FileId, item.ledgerEpoch) {
|
||||
f.queueDeletions(item.FileId)
|
||||
}
|
||||
glog.Warningf("permanent error on retry for %s after %d attempts: %s", item.FileId, item.RetryCount, outcome.errorMsg)
|
||||
}
|
||||
}
|
||||
@@ -599,7 +644,7 @@ func (f *Filer) DeleteChunks(ctx context.Context, fullpath util.FullPath, chunks
|
||||
func (f *Filer) doDeleteChunks(ctx context.Context, chunks []*filer_pb.FileChunk) {
|
||||
for _, chunk := range chunks {
|
||||
if !chunk.IsChunkManifest {
|
||||
f.FileIdDeletionQueue.EnQueue(chunk.GetFileIdString())
|
||||
f.queueDeletions(chunk.GetFileIdString())
|
||||
continue
|
||||
}
|
||||
dataChunks, manifestResolveErr := ResolveOneChunkManifest(ctx, f.MasterClient.LookupFileId, chunk, f.MasterClient)
|
||||
@@ -607,15 +652,15 @@ func (f *Filer) doDeleteChunks(ctx context.Context, chunks []*filer_pb.FileChunk
|
||||
glog.V(0).InfofCtx(ctx, "failed to resolve manifest %s: %v", chunk.FileId, manifestResolveErr)
|
||||
}
|
||||
for _, dChunk := range dataChunks {
|
||||
f.FileIdDeletionQueue.EnQueue(dChunk.GetFileIdString())
|
||||
f.queueDeletions(dChunk.GetFileIdString())
|
||||
}
|
||||
f.FileIdDeletionQueue.EnQueue(chunk.GetFileIdString())
|
||||
f.queueDeletions(chunk.GetFileIdString())
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) DeleteChunksNotRecursive(chunks []*filer_pb.FileChunk) {
|
||||
for _, chunk := range chunks {
|
||||
f.FileIdDeletionQueue.EnQueue(chunk.GetFileIdString())
|
||||
f.queueDeletions(chunk.GetFileIdString())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,758 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Persistent deletion ledger.
|
||||
//
|
||||
// Background: the in-memory FileIdDeletionQueue and DeletionRetryQueue lose every
|
||||
// queued-but-unconfirmed deletion when the filer process restarts (the upstream
|
||||
// TODO in filer_deletion.go notes this and proposes exactly the "periodic snapshot
|
||||
// with recovery on startup" strategy implemented here). Because a delete only ever
|
||||
// enters the pipeline through the queue, a crash between enqueue and the volume
|
||||
// actually confirming the delete leaks the chunk: nothing remembers it, so it
|
||||
// becomes an orphan the next fsck sees as 100% orphaned and a later
|
||||
// meta-replay from a lagging peer can "resurrect" as if it were live data.
|
||||
//
|
||||
// The ledger is a KV entry per filer (KvKeyDeletionLedger suffixed with this
|
||||
// filer's address, so filers sharing one store never overwrite each other's
|
||||
// pending sets) holding the fileIds that still need to be deleted but have not
|
||||
// yet been confirmed gone. It is:
|
||||
// - additive: every EnQueue also records the fileId here,
|
||||
// - subtractive: only terminal outcomes (success / not-found / permanent)
|
||||
// remove it; retryable failures keep it,
|
||||
// - snapshotted when it changes, on a timer, and on Shutdown, so a crash
|
||||
// loses only ids queued in the last in-flight write — recovery re-enqueues
|
||||
// the whole pending set and the idempotent volume delete absorbs anything
|
||||
// that actually completed before the crash.
|
||||
//
|
||||
// Stores that cap value size (FoundationDB at 100KB) get the set split into
|
||||
// part keys when one value would exceed deletionLedgerPartSize. Multipart
|
||||
// snapshots write each generation under generation-scoped part keys and
|
||||
// publish only the manifest last, so a crash mid-write leaves the previous
|
||||
// generation intact; orphaned parts from abandoned generations are tracked in
|
||||
// deletionLedgerStale and retried on the next write.
|
||||
//
|
||||
// Safety on a lagging peer (the resurrection case): recovered entries are replayed
|
||||
// into the queue only after a grace window (DeletionRecoveryGrace), long enough for
|
||||
// the initial peer meta-aggregation to settle so we don't purge a chunk that a
|
||||
// peer is about to re-reference as live. New live deletes are never gated.
|
||||
const (
|
||||
// KvKeyDeletionLedger is the reserved store key prefix for the persisted
|
||||
// ledger, namespaced next to FilerStoreId so it never collides with user
|
||||
// data. The full key is this prefix plus the filer's own address.
|
||||
KvKeyDeletionLedger = "filer.deleteQueue.ledger.v1"
|
||||
|
||||
// KvKeyDeletionLedgerIndex lists the scoped ledger keys in the store so a
|
||||
// filer that restarts under a different advertised address can still find
|
||||
// and claim the ledger it left behind.
|
||||
KvKeyDeletionLedgerIndex = KvKeyDeletionLedger + ".index"
|
||||
|
||||
// deletionLedgerPartSize bounds one ledger value; stores with a value cap
|
||||
// reject anything larger, which would strand a big backlog in memory only.
|
||||
deletionLedgerPartSize = 64 * 1024
|
||||
|
||||
// Defaults; all three overridable via viper (filer.deleteQueue.*).
|
||||
defaultDeletionPersistInterval = 10 * time.Second
|
||||
defaultDeletionRecoveryGrace = 30 * time.Second
|
||||
)
|
||||
|
||||
// deletionPersistEnabled reports whether ledger persistence is on.
|
||||
// Read from viper with a default of true so a plain `weed filer` gets the
|
||||
// durability guarantee without extra flags.
|
||||
func deletionPersistEnabled() bool {
|
||||
v := util.GetViper()
|
||||
v.SetDefault("filer.deleteQueue.persist", true)
|
||||
return v.GetBool("filer.deleteQueue.persist")
|
||||
}
|
||||
|
||||
func deletionPersistInterval() time.Duration {
|
||||
v := util.GetViper()
|
||||
v.SetDefault("filer.deleteQueue.persistInterval", defaultDeletionPersistInterval)
|
||||
d := v.GetDuration("filer.deleteQueue.persistInterval")
|
||||
if d <= 0 {
|
||||
return defaultDeletionPersistInterval
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func deletionRecoveryGrace() time.Duration {
|
||||
v := util.GetViper()
|
||||
v.SetDefault("filer.deleteQueue.recoveryGrace", defaultDeletionRecoveryGrace)
|
||||
d := v.GetDuration("filer.deleteQueue.recoveryGrace")
|
||||
if d < 0 {
|
||||
return 0
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// deletionLedgerKey scopes the ledger to this filer so several filers sharing
|
||||
// one metadata store do not overwrite each other's pending sets. A filer
|
||||
// literal without an advertised address (tests) falls back to the base key.
|
||||
func (f *Filer) deletionLedgerKey() string {
|
||||
if f.Dlm != nil && f.Dlm.Host != "" {
|
||||
return KvKeyDeletionLedger + "." + f.Dlm.Host.ToHttpAddress()
|
||||
}
|
||||
return KvKeyDeletionLedger
|
||||
}
|
||||
|
||||
func deletionLedgerPartKey(key string, part int) []byte {
|
||||
return []byte(fmt.Sprintf("%s.part.%05d", key, part))
|
||||
}
|
||||
|
||||
// deletionLedgerGenPartKey returns the part key for one generation. Generation
|
||||
// 0 keeps the original format so ledgers written before generation publishing
|
||||
// still decode.
|
||||
func deletionLedgerGenPartKey(key string, gen, part int) []byte {
|
||||
if gen == 0 {
|
||||
return deletionLedgerPartKey(key, part)
|
||||
}
|
||||
return []byte(fmt.Sprintf("%s.g%06d.part.%05d", key, gen, part))
|
||||
}
|
||||
|
||||
// startDeletionLedgerSnapshotter periodically flushes the pending deletion set
|
||||
// to durable storage. It also wakes on deletionLedgerFlush so a queued id is
|
||||
// persisted within milliseconds instead of a full interval. Started from
|
||||
// SetStore only after the ledger read succeeded.
|
||||
func (f *Filer) startDeletionLedgerSnapshotter() {
|
||||
go func() {
|
||||
ticker := time.NewTicker(deletionPersistInterval())
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-f.deletionQuit:
|
||||
return
|
||||
case <-ticker.C:
|
||||
case <-f.deletionLedgerFlush:
|
||||
}
|
||||
// A close of deletionQuit may be concurrent with this wake; the
|
||||
// final snapshot in Shutdown covers whatever the loop left dirty.
|
||||
select {
|
||||
case <-f.deletionQuit:
|
||||
return
|
||||
default:
|
||||
}
|
||||
f.snapshotDeletionLedger()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// signalLedgerFlush wakes the snapshotter without blocking the caller.
|
||||
func (f *Filer) signalLedgerFlush() {
|
||||
f.deletionLedgerLock.Lock()
|
||||
if f.deletionLedgerFlush == nil {
|
||||
f.deletionLedgerFlush = make(chan struct{}, 1)
|
||||
}
|
||||
ch := f.deletionLedgerFlush
|
||||
f.deletionLedgerLock.Unlock()
|
||||
select {
|
||||
case ch <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// queueDeletions is the single entry point for adding fileIds to the deletion
|
||||
// pipeline. It keeps the in-memory hot queue AND the durable ledger in sync.
|
||||
// Safe on a zero-value Filer (tests build struct literals without NewFiler):
|
||||
// the map is lazily created and the mutex is zero-value friendly.
|
||||
func (f *Filer) queueDeletions(fileIds ...string) {
|
||||
if len(fileIds) == 0 {
|
||||
return
|
||||
}
|
||||
// Hot path: existing in-memory queue, unchanged.
|
||||
f.FileIdDeletionQueue.EnQueue(fileIds...)
|
||||
|
||||
// Durable ledger: record what still needs deleting. Every enqueue bumps the
|
||||
// id's epoch so an expiry-forget carrying an older epoch cannot erase the
|
||||
// re-queued intent.
|
||||
f.deletionLedgerLock.Lock()
|
||||
if f.pendingDeletions == nil {
|
||||
f.pendingDeletions = make(map[string]uint64, len(fileIds))
|
||||
}
|
||||
for _, id := range fileIds {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
_, exists := f.pendingDeletions[id]
|
||||
f.deletionSeq++
|
||||
f.pendingDeletions[id] = f.deletionSeq
|
||||
if !exists {
|
||||
f.deletionLedgerDirty = true
|
||||
}
|
||||
}
|
||||
f.deletionLedgerLock.Unlock()
|
||||
f.signalLedgerFlush()
|
||||
}
|
||||
|
||||
// pendingDeletionCount returns the number of fileIds still tracked as needing
|
||||
// deletion in the durable ledger. Handy for diagnostics and tests; 0 when the
|
||||
// map was never initialised.
|
||||
func (f *Filer) pendingDeletionCount() int {
|
||||
f.deletionLedgerLock.Lock()
|
||||
defer f.deletionLedgerLock.Unlock()
|
||||
return len(f.pendingDeletions)
|
||||
}
|
||||
|
||||
// deletionEpoch returns the pending record's current epoch for fileId.
|
||||
func (f *Filer) deletionEpoch(fileId string) uint64 {
|
||||
f.deletionLedgerLock.Lock()
|
||||
defer f.deletionLedgerLock.Unlock()
|
||||
return f.pendingDeletions[fileId]
|
||||
}
|
||||
|
||||
// forgetDeletion removes a fileId from the ledger once its deletion is terminal
|
||||
// (deleted or already absent: the chunks are gone, so any pending record — even
|
||||
// a re-queued one — refers to work that no longer exists). Non-terminal
|
||||
// outcomes must NOT call this so the entry survives until confirmed.
|
||||
func (f *Filer) forgetDeletion(fileId string) {
|
||||
if fileId == "" {
|
||||
return
|
||||
}
|
||||
f.deletionLedgerLock.Lock()
|
||||
if _, exists := f.pendingDeletions[fileId]; exists {
|
||||
delete(f.pendingDeletions, fileId)
|
||||
f.deletionLedgerDirty = true
|
||||
}
|
||||
f.deletionLedgerLock.Unlock()
|
||||
f.signalLedgerFlush()
|
||||
}
|
||||
|
||||
// forgetDeletionEpoch removes the ledger record only when its epoch still
|
||||
// matches the one captured when the deletion attempt began. A mismatch means
|
||||
// the id was re-queued meanwhile, so the newer record wins. Reports whether
|
||||
// the record was removed.
|
||||
func (f *Filer) forgetDeletionEpoch(fileId string, epoch uint64) bool {
|
||||
if fileId == "" {
|
||||
return false
|
||||
}
|
||||
removed := false
|
||||
f.deletionLedgerLock.Lock()
|
||||
if cur, exists := f.pendingDeletions[fileId]; exists && cur == epoch {
|
||||
delete(f.pendingDeletions, fileId)
|
||||
f.deletionLedgerDirty = true
|
||||
removed = true
|
||||
}
|
||||
f.deletionLedgerLock.Unlock()
|
||||
if removed {
|
||||
f.signalLedgerFlush()
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
// snapshotDeletionLedger serialises the current pending set to the store.
|
||||
// Only writes when something changed since the last snapshot to keep KV churn low.
|
||||
// Writes serialize on deletionSnapshotLock so a snapshot in flight when Shutdown
|
||||
// starts cannot overwrite the final one with an older copy.
|
||||
func (f *Filer) snapshotDeletionLedger() {
|
||||
if !deletionPersistEnabled() || f.Store == nil {
|
||||
return
|
||||
}
|
||||
f.deletionSnapshotLock.Lock()
|
||||
defer f.deletionSnapshotLock.Unlock()
|
||||
|
||||
if f.deletionLedgerBlocked.Load() && !f.tryUnblockDeletionLedger() {
|
||||
return
|
||||
}
|
||||
|
||||
f.deletionLedgerLock.Lock()
|
||||
if !f.deletionLedgerDirty {
|
||||
hasStale := len(f.deletionLedgerStale) > 0
|
||||
f.deletionLedgerLock.Unlock()
|
||||
if !hasStale {
|
||||
return
|
||||
}
|
||||
// Nothing to republish, but orphaned part keys still need cleanup.
|
||||
ctx := context.Background()
|
||||
f.flushStaleLedgerParts(ctx)
|
||||
f.persistStaleLedgerParts(ctx, f.deletionLedgerKey())
|
||||
return
|
||||
}
|
||||
// Take a stable copy under lock; marshal + KV write happen outside it.
|
||||
ids := make([]string, 0, len(f.pendingDeletions))
|
||||
for id := range f.pendingDeletions {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
f.deletionLedgerDirty = false
|
||||
f.deletionLedgerLock.Unlock()
|
||||
|
||||
if err := f.writeDeletionLedger(ids); err != nil {
|
||||
glog.Warningf("failed to persist deletion ledger (%d ids): %v", len(ids), err)
|
||||
f.deletionLedgerLock.Lock()
|
||||
f.deletionLedgerDirty = true
|
||||
f.deletionLedgerLock.Unlock()
|
||||
return
|
||||
}
|
||||
glog.V(3).Infof("persisted deletion ledger: %d pending deletions", len(ids))
|
||||
}
|
||||
|
||||
// tryUnblockDeletionLedger retries the ledger reload that originally failed.
|
||||
// Once the read succeeds the persisted ids merge back into the pending set and
|
||||
// snapshots resume; until then nothing is written so the unread ledger cannot
|
||||
// be overwritten.
|
||||
func (f *Filer) tryUnblockDeletionLedger() bool {
|
||||
f.reloadDeletionLedger()
|
||||
return !f.deletionLedgerBlocked.Load()
|
||||
}
|
||||
|
||||
// writeDeletionLedger persists the id set. A single value is published
|
||||
// atomically; a multipart set writes a new generation's part keys first and
|
||||
// only then the manifest, so a crash or failed write leaves the previously
|
||||
// published generation readable. Orphaned parts are retried on the next write.
|
||||
func (f *Filer) writeDeletionLedger(ids []string) error {
|
||||
ctx := context.Background()
|
||||
key := f.deletionLedgerKey()
|
||||
|
||||
f.deletionLedgerLock.Lock()
|
||||
prevGen, prevParts := f.deletionLedgerGen, f.deletionLedgerParts
|
||||
f.deletionLedgerLock.Unlock()
|
||||
|
||||
f.flushStaleLedgerParts(ctx)
|
||||
|
||||
var parts [][]byte
|
||||
var batch []string
|
||||
size := 2 // "[]"
|
||||
flush := func() error {
|
||||
if batch == nil {
|
||||
batch = []string{}
|
||||
}
|
||||
payload, err := json.Marshal(batch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts = append(parts, payload)
|
||||
batch = nil
|
||||
size = 2
|
||||
return nil
|
||||
}
|
||||
for _, id := range ids {
|
||||
if need := len(id) + 3; len(batch) > 0 && size+need > deletionLedgerPartSize {
|
||||
if err := flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
batch = append(batch, id)
|
||||
size += len(id) + 3
|
||||
}
|
||||
if len(batch) > 0 || len(parts) == 0 {
|
||||
if err := flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(parts) == 1 {
|
||||
if err := f.Store.KvPut(ctx, []byte(key), parts[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
f.deleteLedgerParts(ctx, key, prevGen, prevParts)
|
||||
f.deletionLedgerLock.Lock()
|
||||
f.deletionLedgerGen, f.deletionLedgerParts = 0, 0
|
||||
f.deletionLedgerLock.Unlock()
|
||||
} else {
|
||||
gen := prevGen + 1
|
||||
wrote := 0
|
||||
for i, payload := range parts {
|
||||
if err := f.Store.KvPut(ctx, deletionLedgerGenPartKey(key, gen, i), payload); err != nil {
|
||||
f.markStaleLedgerParts(key, gen, wrote)
|
||||
return err
|
||||
}
|
||||
wrote++
|
||||
}
|
||||
manifest, _ := json.Marshal(struct {
|
||||
Parts int `json:"parts"`
|
||||
Gen int `json:"gen,omitempty"`
|
||||
}{len(parts), gen})
|
||||
if err := f.Store.KvPut(ctx, []byte(key), manifest); err != nil {
|
||||
f.markStaleLedgerParts(key, gen, wrote)
|
||||
return err
|
||||
}
|
||||
f.deleteLedgerParts(ctx, key, prevGen, prevParts)
|
||||
f.deletionLedgerLock.Lock()
|
||||
f.deletionLedgerGen, f.deletionLedgerParts = gen, len(parts)
|
||||
f.deletionLedgerLock.Unlock()
|
||||
}
|
||||
f.persistStaleLedgerParts(ctx, key)
|
||||
f.touchLedgerIndex(ctx, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteLedgerParts removes a published generation's part keys; failures are
|
||||
// tracked as stale so the next snapshot retries them.
|
||||
func (f *Filer) deleteLedgerParts(ctx context.Context, key string, gen, parts int) {
|
||||
for i := 0; i < parts; i++ {
|
||||
if err := f.Store.KvDelete(ctx, deletionLedgerGenPartKey(key, gen, i)); err != nil {
|
||||
f.deletionLedgerLock.Lock()
|
||||
f.deletionLedgerStale = append(f.deletionLedgerStale, string(deletionLedgerGenPartKey(key, gen, i)))
|
||||
f.deletionLedgerLock.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// markStaleLedgerParts remembers parts of an abandoned generation so they are
|
||||
// deleted by a later snapshot instead of leaking store space.
|
||||
func (f *Filer) markStaleLedgerParts(key string, gen, wrote int) {
|
||||
if wrote == 0 {
|
||||
return
|
||||
}
|
||||
f.deletionLedgerLock.Lock()
|
||||
for i := 0; i < wrote; i++ {
|
||||
f.deletionLedgerStale = append(f.deletionLedgerStale, string(deletionLedgerGenPartKey(key, gen, i)))
|
||||
}
|
||||
f.deletionLedgerLock.Unlock()
|
||||
}
|
||||
|
||||
func (f *Filer) flushStaleLedgerParts(ctx context.Context) {
|
||||
f.deletionLedgerLock.Lock()
|
||||
stale := f.deletionLedgerStale
|
||||
f.deletionLedgerStale = nil
|
||||
f.deletionLedgerLock.Unlock()
|
||||
|
||||
var keep []string
|
||||
for _, k := range stale {
|
||||
if err := f.Store.KvDelete(ctx, []byte(k)); err != nil {
|
||||
keep = append(keep, k)
|
||||
}
|
||||
}
|
||||
if len(keep) > 0 {
|
||||
f.deletionLedgerLock.Lock()
|
||||
f.deletionLedgerStale = append(keep, f.deletionLedgerStale...)
|
||||
f.deletionLedgerLock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// persistStaleLedgerParts mirrors the stale-part list under a sidecar key so a
|
||||
// crash between manifest publication and part cleanup can retry after restart
|
||||
// instead of orphaning the part keys.
|
||||
func (f *Filer) persistStaleLedgerParts(ctx context.Context, key string) {
|
||||
f.deletionLedgerLock.Lock()
|
||||
stale := append([]string(nil), f.deletionLedgerStale...)
|
||||
f.deletionLedgerLock.Unlock()
|
||||
staleKey := []byte(key + ".stale")
|
||||
if len(stale) == 0 {
|
||||
_ = f.Store.KvDelete(ctx, staleKey)
|
||||
return
|
||||
}
|
||||
payload, _ := json.Marshal(stale)
|
||||
_ = f.Store.KvPut(ctx, staleKey, payload)
|
||||
}
|
||||
|
||||
// loadStaleLedgerParts seeds the stale-part list left by a previous run.
|
||||
func (f *Filer) loadStaleLedgerParts(ctx context.Context, key string) {
|
||||
payload, err := f.Store.KvGet(ctx, []byte(key+".stale"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var stale []string
|
||||
if json.Unmarshal(payload, &stale) != nil {
|
||||
return
|
||||
}
|
||||
f.deletionLedgerLock.Lock()
|
||||
f.deletionLedgerStale = append(f.deletionLedgerStale, stale...)
|
||||
f.deletionLedgerLock.Unlock()
|
||||
}
|
||||
|
||||
// touchLedgerIndex records this filer's scoped key in the shared index so the
|
||||
// ledger remains discoverable if the filer restarts under a new address. The
|
||||
// index is a read-modify-write list with no CAS, so the write is verified and
|
||||
// retried: a peer's concurrent update must not drop this key.
|
||||
func (f *Filer) touchLedgerIndex(ctx context.Context, key string) {
|
||||
if key == KvKeyDeletionLedger {
|
||||
return
|
||||
}
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
keys, err := f.readLedgerIndex(ctx)
|
||||
if err != nil {
|
||||
// Only a genuinely absent index means "empty"; a store error must
|
||||
// not let us write a one-key list that drops every peer entry.
|
||||
if err != ErrKvNotFound {
|
||||
glog.V(1).Infof("deletion ledger index unreadable, skipping update: %v", err)
|
||||
return
|
||||
}
|
||||
keys = nil
|
||||
}
|
||||
found := false
|
||||
for _, k := range keys {
|
||||
if k == key {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if found {
|
||||
return
|
||||
}
|
||||
payload, _ := json.Marshal(append(keys, key))
|
||||
if err := f.Store.KvPut(ctx, []byte(KvKeyDeletionLedgerIndex), payload); err != nil {
|
||||
glog.V(1).Infof("failed to update deletion ledger index: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
glog.V(1).Infof("deletion ledger index lost %q to a concurrent update; retrying on the next snapshot", key)
|
||||
}
|
||||
|
||||
func (f *Filer) readLedgerIndex(ctx context.Context) ([]string, error) {
|
||||
payload, err := f.Store.KvGet(ctx, []byte(KvKeyDeletionLedgerIndex))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var keys []string
|
||||
if err := json.Unmarshal(payload, &keys); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (f *Filer) pruneLedgerIndex(ctx context.Context, key string) {
|
||||
keys, err := f.readLedgerIndex(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
kept := keys[:0]
|
||||
for _, k := range keys {
|
||||
if k != key {
|
||||
kept = append(kept, k)
|
||||
}
|
||||
}
|
||||
payload, _ := json.Marshal(kept)
|
||||
_ = f.Store.KvPut(ctx, []byte(KvKeyDeletionLedgerIndex), payload)
|
||||
}
|
||||
|
||||
// readDeletionLedger reads the manifest key: a JSON array is the whole set; a
|
||||
// {"parts":N,"gen":G} manifest points at that generation's part keys. A part
|
||||
// the manifest references but the store lacks is corruption, not absence, so
|
||||
// it surfaces as a wrapped error rather than ErrKvNotFound.
|
||||
func (f *Filer) readDeletionLedger(key string) (ids []string, gen, parts int, err error) {
|
||||
ctx := context.Background()
|
||||
|
||||
payload, err := f.Store.KvGet(ctx, []byte(key))
|
||||
if err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
if !bytes.HasPrefix(bytes.TrimSpace(payload), []byte("{")) {
|
||||
if err := json.Unmarshal(payload, &ids); err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
return ids, 0, 0, nil
|
||||
}
|
||||
var manifest struct {
|
||||
Parts int `json:"parts"`
|
||||
Gen int `json:"gen,omitempty"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &manifest); err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
for i := 0; i < manifest.Parts; i++ {
|
||||
partPayload, err := f.Store.KvGet(ctx, deletionLedgerGenPartKey(key, manifest.Gen, i))
|
||||
if err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("deletion ledger part %d of %s unreadable: %w", i, key, err)
|
||||
}
|
||||
var part []string
|
||||
if err := json.Unmarshal(partPayload, &part); err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("deletion ledger part %d of %s corrupt: %w", i, key, err)
|
||||
}
|
||||
ids = append(ids, part...)
|
||||
}
|
||||
return ids, manifest.Gen, manifest.Parts, nil
|
||||
}
|
||||
|
||||
// recoverForeignDeletionLedgers runs when the scoped key is absent: the ledger
|
||||
// may sit under the pre-scoping base key, or under a scoped key belonging to an
|
||||
// earlier incarnation of this filer whose advertised address changed. Every
|
||||
// discovered set is published under this filer's key first and the source keys
|
||||
// deleted only after that write succeeds. A live peer's ledger claimed here is
|
||||
// rewritten by the peer's next snapshot, so the ids only get processed twice —
|
||||
// deletions are not owner-specific.
|
||||
func (f *Filer) recoverForeignDeletionLedgers(key string) (ids []string, err error) {
|
||||
ctx := context.Background()
|
||||
|
||||
claimed := map[string]ledgerClaim{} // source key -> what was read
|
||||
lIds, lGen, lParts, lErr := f.readDeletionLedger(KvKeyDeletionLedger)
|
||||
switch {
|
||||
case lErr == nil:
|
||||
ids = append(ids, lIds...)
|
||||
claimed[KvKeyDeletionLedger] = ledgerClaim{lIds, lGen, lParts}
|
||||
f.loadStaleLedgerParts(ctx, KvKeyDeletionLedger)
|
||||
case lErr != ErrKvNotFound:
|
||||
return nil, lErr
|
||||
}
|
||||
|
||||
// Any read failure aborts the whole claim so reload retries: skipping an
|
||||
// unreadable source would strand it, since a successful claim here means
|
||||
// the index is never searched again.
|
||||
indexKeys, idxErr := f.readLedgerIndex(ctx)
|
||||
if idxErr != nil && idxErr != ErrKvNotFound {
|
||||
return nil, idxErr
|
||||
}
|
||||
for _, other := range indexKeys {
|
||||
if other == key {
|
||||
continue
|
||||
}
|
||||
oIds, oGen, oParts, oErr := f.readDeletionLedger(other)
|
||||
if oErr == ErrKvNotFound {
|
||||
f.pruneLedgerIndex(ctx, other)
|
||||
continue
|
||||
}
|
||||
if oErr != nil {
|
||||
return nil, fmt.Errorf("deletion ledger %s unreadable: %w", other, oErr)
|
||||
}
|
||||
ids = append(ids, oIds...)
|
||||
claimed[other] = ledgerClaim{oIds, oGen, oParts}
|
||||
f.loadStaleLedgerParts(ctx, other)
|
||||
}
|
||||
|
||||
if len(claimed) == 0 {
|
||||
return nil, ErrKvNotFound
|
||||
}
|
||||
if err := f.writeDeletionLedger(ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mergedMore := false
|
||||
for src, claim := range claimed {
|
||||
// A source republished since we read it belongs to a live filer
|
||||
// (or a racing claimer): merge the newer ids and leave it in place.
|
||||
curIds, curGen, curParts, rerr := f.readDeletionLedger(src)
|
||||
if rerr != nil || curGen != claim.gen || curParts != claim.parts || !sameStringSet(curIds, claim.ids) {
|
||||
if rerr == nil {
|
||||
for _, id := range curIds {
|
||||
if !containsId(ids, id) {
|
||||
ids = append(ids, id)
|
||||
mergedMore = true
|
||||
}
|
||||
}
|
||||
}
|
||||
glog.V(0).Infof("deletion ledger %s changed while claiming; leaving it for its owner", src)
|
||||
continue
|
||||
}
|
||||
f.deleteLedgerParts(ctx, src, claim.gen, claim.parts)
|
||||
_ = f.Store.KvDelete(ctx, []byte(src))
|
||||
_ = f.Store.KvDelete(ctx, []byte(src+".stale"))
|
||||
f.pruneLedgerIndex(ctx, src)
|
||||
}
|
||||
if mergedMore {
|
||||
// Ids from a changed source are durable only under that source's key;
|
||||
// rewrite our ledger so they survive under ours too.
|
||||
if err := f.writeDeletionLedger(ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func containsId(ids []string, id string) bool {
|
||||
for _, s := range ids {
|
||||
if s == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ledgerClaim struct {
|
||||
ids []string
|
||||
gen int
|
||||
parts int
|
||||
}
|
||||
|
||||
func sameStringSet(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
seen := make(map[string]struct{}, len(a))
|
||||
for _, s := range a {
|
||||
seen[s] = struct{}{}
|
||||
}
|
||||
for _, s := range b {
|
||||
if _, ok := seen[s]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// reloadDeletionLedger re-enqueues any pending deletions found in the store after
|
||||
// a restart, so a crash that killed the in-memory queues does not leak chunks.
|
||||
// Recovered ids join the pending set immediately so snapshots rewrite the full
|
||||
// ledger; only the re-queue waits out DeletionRecoveryGrace.
|
||||
//
|
||||
// It reports whether the ledger is usable. A read error or an unparseable
|
||||
// payload leaves the persisted set unknown, so snapshots retry the read rather
|
||||
// than overwrite the unread ledger with a partial set.
|
||||
//
|
||||
// Safe to call on a Filer with a nil Store (no-op). Idempotent for the volume
|
||||
// side: a chunk that was actually deleted before the crash re-deletes as not-found.
|
||||
func (f *Filer) reloadDeletionLedger() bool {
|
||||
if !deletionPersistEnabled() || f.Store == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
key := f.deletionLedgerKey()
|
||||
ids, gen, parts, err := f.readDeletionLedger(key)
|
||||
stateWritten := false
|
||||
if err == ErrKvNotFound && key != KvKeyDeletionLedger {
|
||||
ids, err = f.recoverForeignDeletionLedgers(key)
|
||||
stateWritten = err == nil
|
||||
}
|
||||
if err != nil {
|
||||
if err == ErrKvNotFound {
|
||||
f.deletionLedgerBlocked.Store(false)
|
||||
return true
|
||||
}
|
||||
f.deletionLedgerBlocked.Store(true)
|
||||
glog.Warningf("failed to read persisted deletion ledger; persistence disabled until it reads: %v", err)
|
||||
return false
|
||||
}
|
||||
f.deletionLedgerBlocked.Store(false)
|
||||
f.loadStaleLedgerParts(context.Background(), key)
|
||||
|
||||
// Merge into the pending set now so an early snapshot rewrites the
|
||||
// recovered ids instead of overwriting the ledger with only new ones.
|
||||
f.deletionLedgerLock.Lock()
|
||||
if len(ids) > 0 {
|
||||
if f.pendingDeletions == nil {
|
||||
f.pendingDeletions = make(map[string]uint64, len(ids))
|
||||
}
|
||||
for _, id := range ids {
|
||||
if id != "" {
|
||||
if _, exists := f.pendingDeletions[id]; !exists {
|
||||
f.deletionSeq++
|
||||
f.pendingDeletions[id] = f.deletionSeq
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !stateWritten {
|
||||
f.deletionLedgerGen = gen
|
||||
f.deletionLedgerParts = parts
|
||||
}
|
||||
f.deletionLedgerLock.Unlock()
|
||||
|
||||
if len(ids) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
grace := deletionRecoveryGrace()
|
||||
glog.V(0).Infof("recovered %d pending deletions from ledger, applying in %v", len(ids), grace)
|
||||
|
||||
go func() {
|
||||
timer := time.NewTimer(grace)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-f.deletionQuit:
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
// The ids are already in the pending set; only the queue push waits
|
||||
// for peer meta-aggregation to settle. The ledger is deliberately NOT
|
||||
// cleared here: it shrinks only as the delete pipeline confirms each
|
||||
// id terminal, so a second crash mid-recovery replays everything.
|
||||
f.queueDeletions(ids...)
|
||||
glog.V(0).Infof("re-queued %d recovered pending deletions", len(ids))
|
||||
}()
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// readPersistedLedger pulls the persisted ledger payload straight from the store
|
||||
// the filer is wired to, the same way a restarting filer would.
|
||||
func readPersistedLedger(t *testing.T, f *Filer) ([]string, bool) {
|
||||
t.Helper()
|
||||
raw, err := f.Store.KvGet(context.Background(), []byte(f.deletionLedgerKey()))
|
||||
if err != nil {
|
||||
if err == ErrKvNotFound {
|
||||
return nil, false
|
||||
}
|
||||
t.Fatalf("unexpected error reading ledger: %v", err)
|
||||
}
|
||||
var ids []string
|
||||
if err := json.Unmarshal(raw, &ids); err != nil {
|
||||
t.Fatalf("persisted payload not valid JSON: %v", err)
|
||||
}
|
||||
return ids, true
|
||||
}
|
||||
|
||||
// withPersistedConfig pins the ledger knobs at viper's override tier so the test
|
||||
// sees deterministic semantics regardless of global SetDefault ordering (the
|
||||
// production getters SetDefault(true), which would otherwise win the tier race).
|
||||
// The overrides are restored on cleanup so later tests see production defaults.
|
||||
func withPersistedConfig(t *testing.T, enabled bool) {
|
||||
t.Helper()
|
||||
v := util.GetViper()
|
||||
v.Set("filer.deleteQueue.persist", enabled)
|
||||
v.Set("filer.deleteQueue.recoveryGrace", defaultDeletionRecoveryGrace)
|
||||
t.Cleanup(func() {
|
||||
v.Set("filer.deleteQueue.persist", true)
|
||||
v.Set("filer.deleteQueue.recoveryGrace", defaultDeletionRecoveryGrace)
|
||||
})
|
||||
}
|
||||
|
||||
// newLedgerTestFiler builds a Filer with the pieces the ledger touches, backed by
|
||||
// a real (stub) store, bypassing NewFiler's master/aggregator wiring.
|
||||
func newLedgerTestFiler(store FilerStore) *Filer {
|
||||
return &Filer{
|
||||
FileIdDeletionQueue: util.NewUnboundedQueue(),
|
||||
DeletionRetryQueue: NewDeletionRetryQueue(),
|
||||
deletionQuit: make(chan struct{}),
|
||||
Store: NewFilerStoreWrapper(store),
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletionLedgerSnapshotAndRecover is the core guarantee: enqueued-but-
|
||||
// unconfirmed deletions survive a simulated process restart and land back in the
|
||||
// hot queue (minus whatever was confirmed terminal in the meantime).
|
||||
func TestDeletionLedgerSnapshotAndRecover(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
|
||||
f.queueDeletions("1,01", "1,02", "1,03")
|
||||
f.snapshotDeletionLedger()
|
||||
|
||||
persisted, ok := readPersistedLedger(t, f)
|
||||
if !ok {
|
||||
t.Fatalf("expected persisted ledger under %q", KvKeyDeletionLedger)
|
||||
}
|
||||
if len(persisted) != 3 {
|
||||
t.Fatalf("expected 3 persisted ids, got %d: %v", len(persisted), persisted)
|
||||
}
|
||||
for _, want := range []string{"1,01", "1,02", "1,03"} {
|
||||
if !contains(persisted, want) {
|
||||
t.Errorf("expected %q in persisted ledger, got %v", want, persisted)
|
||||
}
|
||||
}
|
||||
|
||||
// Confirmed-gone for one id, then snapshot again.
|
||||
f.forgetDeletion("1,02")
|
||||
f.snapshotDeletionLedger()
|
||||
persisted, _ = readPersistedLedger(t, f)
|
||||
if len(persisted) != 2 {
|
||||
t.Fatalf("expected 2 persisted ids after forget, got %d: %v", len(persisted), persisted)
|
||||
}
|
||||
if contains(persisted, "1,02") {
|
||||
t.Errorf("forgotten id still in persisted ledger: %v", persisted)
|
||||
}
|
||||
|
||||
// --- simulated restart: a fresh Filer with NO ledger in memory must
|
||||
// recover the still-pending ids from the store and re-queue them. ---
|
||||
f2 := newLedgerTestFiler(store)
|
||||
// recoveryGrace 0 so the background re-enqueue is near-instant.
|
||||
util.GetViper().Set("filer.deleteQueue.recoveryGrace", time.Duration(0))
|
||||
f2.reloadDeletionLedger()
|
||||
|
||||
// Wait for the async recovery goroutine to drain into the hot queue.
|
||||
seen := make(map[string]bool)
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
f2.FileIdDeletionQueue.Consume(func(ids []string) {
|
||||
for _, id := range ids {
|
||||
seen[id] = true
|
||||
}
|
||||
})
|
||||
if len(seen) >= 2 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
if !seen["1,01"] || !seen["1,03"] {
|
||||
t.Fatalf("expected recovered ids 1,01 and 1,03 back in hot queue, got %v", seen)
|
||||
}
|
||||
if seen["1,02"] {
|
||||
t.Errorf("forgotten id 1,02 must NOT come back: %v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletionLedgerRetryKeepsEntry pins the key semantic: a non-terminal
|
||||
// (retryable) failure must keep the entry persisted, so a crash mid-retry does
|
||||
// not orphan the chunk. This is the whole reason forgetDeletion is only called on
|
||||
// success / not-found / permanent.
|
||||
func TestDeletionLedgerRetryKeepsEntry(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
|
||||
f.queueDeletions("9,01")
|
||||
f.snapshotDeletionLedger()
|
||||
|
||||
// A retryable outcome deliberately does NOT call forgetDeletion, so the id
|
||||
// must still be in the durable ledger.
|
||||
persisted, ok := readPersistedLedger(t, f)
|
||||
if !ok {
|
||||
t.Fatalf("ledger missing — retryable ids must remain persisted")
|
||||
}
|
||||
if len(persisted) != 1 || persisted[0] != "9,01" {
|
||||
t.Fatalf("retryable id must stay in ledger, got %v", persisted)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletionLedgerDisabled verifies the kill switch: with persist off, nothing
|
||||
// reaches KV, and reload refuses to recover even if a ledger exists in the store
|
||||
// (so an operator turning the feature off never resurrects a stale ledger).
|
||||
func TestDeletionLedgerDisabled(t *testing.T) {
|
||||
// First, with persistence ON, put a real ledger into the store.
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
fOn := newLedgerTestFiler(store)
|
||||
fOn.queueDeletions("5,01")
|
||||
fOn.snapshotDeletionLedger()
|
||||
if _, ok := readPersistedLedger(t, fOn); !ok {
|
||||
t.Fatalf("setup: expected a persisted ledger with persist enabled")
|
||||
}
|
||||
|
||||
// Now flip the switch OFF and check the contract.
|
||||
withPersistedConfig(t, false)
|
||||
|
||||
// 1. Snapshot does not touch KV (no new writes, no clear).
|
||||
f := newLedgerTestFiler(store)
|
||||
f.queueDeletions("6,01") // in-memory only
|
||||
f.snapshotDeletionLedger()
|
||||
persisted, ok := readPersistedLedger(t, f)
|
||||
if !ok {
|
||||
t.Fatalf("setup: ledger should still exist from the enabled phase")
|
||||
}
|
||||
// The enabled-phase ledger had "5,01"; disabled phase must not have added "6,01".
|
||||
if contains(persisted, "6,01") {
|
||||
t.Errorf("persist disabled but snapshot wrote 6,01: %v", persisted)
|
||||
}
|
||||
|
||||
// 2. Reload with the switch off must NOT recover, even though a ledger exists.
|
||||
f2 := newLedgerTestFiler(store)
|
||||
f2.reloadDeletionLedger()
|
||||
if f2.pendingDeletionCount() != 0 {
|
||||
t.Fatalf("reload must be a no-op when disabled, got %d pending", f2.pendingDeletionCount())
|
||||
}
|
||||
}
|
||||
|
||||
// Filers sharing one metadata store must not overwrite each other's ledgers:
|
||||
// each filer keys its ledger by its own address.
|
||||
func TestDeletionLedgerScopedPerFiler(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
fA := newLedgerTestFiler(store)
|
||||
fA.Dlm = lock_manager.NewDistributedLockManager("filer-a:8888")
|
||||
fB := newLedgerTestFiler(store)
|
||||
fB.Dlm = lock_manager.NewDistributedLockManager("filer-b:8888")
|
||||
|
||||
fA.queueDeletions("1,01")
|
||||
fB.queueDeletions("2,02")
|
||||
fA.snapshotDeletionLedger()
|
||||
fB.snapshotDeletionLedger()
|
||||
|
||||
idsA, okA := readPersistedLedger(t, fA)
|
||||
idsB, okB := readPersistedLedger(t, fB)
|
||||
if !okA || !okB {
|
||||
t.Fatalf("both filers must have their own ledger, got %v %v", idsA, idsB)
|
||||
}
|
||||
if !contains(idsA, "1,01") || contains(idsA, "2,02") {
|
||||
t.Fatalf("filer A ledger wrong: %v", idsA)
|
||||
}
|
||||
if !contains(idsB, "2,02") || contains(idsB, "1,01") {
|
||||
t.Fatalf("filer B ledger wrong: %v", idsB)
|
||||
}
|
||||
|
||||
// A restarted filer on B's address recovers only B's pending deletions.
|
||||
fB2 := newLedgerTestFiler(store)
|
||||
fB2.Dlm = lock_manager.NewDistributedLockManager("filer-b:8888")
|
||||
if !fB2.reloadDeletionLedger() {
|
||||
t.Fatalf("reload should succeed")
|
||||
}
|
||||
if fB2.pendingDeletionCount() != 1 {
|
||||
t.Fatalf("B's restart should recover exactly its own id, got %d", fB2.pendingDeletionCount())
|
||||
}
|
||||
}
|
||||
|
||||
// A ledger bigger than one store value must still persist: it splits into part
|
||||
// keys under a manifest, and shrinking below the part size removes the parts.
|
||||
func TestDeletionLedgerChunked(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
|
||||
var ids []string
|
||||
for i := 0; i < 4000; i++ {
|
||||
ids = append(ids, fmt.Sprintf("7,%08xbeefcafe", i))
|
||||
}
|
||||
f.queueDeletions(ids...)
|
||||
f.snapshotDeletionLedger()
|
||||
|
||||
raw, err := f.Store.KvGet(context.Background(), []byte(f.deletionLedgerKey()))
|
||||
if err != nil || len(raw) == 0 || raw[0] != '{' {
|
||||
t.Fatalf("expected a chunked manifest, got %v %q", err, raw)
|
||||
}
|
||||
|
||||
f2 := newLedgerTestFiler(store)
|
||||
if !f2.reloadDeletionLedger() {
|
||||
t.Fatalf("chunked ledger should reload")
|
||||
}
|
||||
if got := f2.pendingDeletionCount(); got != len(ids) {
|
||||
t.Fatalf("recovered %d ids, want %d", got, len(ids))
|
||||
}
|
||||
|
||||
// Forget everything; the next snapshot is a single value again and the
|
||||
// part keys are removed.
|
||||
for _, id := range ids {
|
||||
f2.forgetDeletion(id)
|
||||
}
|
||||
f2.snapshotDeletionLedger()
|
||||
raw, err = f.Store.KvGet(context.Background(), []byte(f2.deletionLedgerKey()))
|
||||
if err != nil || len(raw) == 0 || raw[0] != '[' {
|
||||
t.Fatalf("expected single-value ledger after shrink, got %v %q", err, raw)
|
||||
}
|
||||
if _, err := f.Store.KvGet(context.Background(), deletionLedgerPartKey(f2.deletionLedgerKey(), 0)); err != ErrKvNotFound {
|
||||
t.Fatalf("stale part key must be removed, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A startup ledger read that fails for a reason other than not-found must not
|
||||
// let snapshots overwrite the unread ledger with a partial set.
|
||||
func TestDeletionLedgerReadFailureBlocksPersistence(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
store.kvGetErr = errors.New("kv read down")
|
||||
|
||||
if f.reloadDeletionLedger() {
|
||||
t.Fatalf("reload should report the ledger as unusable")
|
||||
}
|
||||
|
||||
f.queueDeletions("1,01")
|
||||
f.snapshotDeletionLedger()
|
||||
if len(store.kv) != 0 {
|
||||
t.Fatalf("snapshot must not overwrite a ledger that was never read, wrote %v", store.kv)
|
||||
}
|
||||
|
||||
// The block is not permanent: once the store reads again, persistence
|
||||
// resumes — a transient failure must not disable the ledger for the life
|
||||
// of the process.
|
||||
store.kvGetErr = nil
|
||||
f.snapshotDeletionLedger()
|
||||
persisted, ok := readPersistedLedger(t, f)
|
||||
if !ok || len(persisted) != 1 || persisted[0] != "1,01" {
|
||||
t.Fatalf("persistence should resume once the ledger reads, got %v", persisted)
|
||||
}
|
||||
}
|
||||
|
||||
// Recovered ids join the pending set immediately — before the grace delay — so
|
||||
// an early snapshot rewrites the recovered ids instead of dropping them.
|
||||
func TestDeletionLedgerRecoveryKeepsIdsPending(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
f.queueDeletions("1,01", "1,02")
|
||||
f.snapshotDeletionLedger()
|
||||
|
||||
util.GetViper().Set("filer.deleteQueue.recoveryGrace", time.Hour)
|
||||
f2 := newLedgerTestFiler(store)
|
||||
if !f2.reloadDeletionLedger() {
|
||||
t.Fatalf("reload should succeed")
|
||||
}
|
||||
// Still inside the grace window, but the ids are already pending.
|
||||
if f2.pendingDeletionCount() != 2 {
|
||||
t.Fatalf("recovered ids must be pending immediately, got %d", f2.pendingDeletionCount())
|
||||
}
|
||||
// And an early shutdown snapshot keeps them.
|
||||
f2.snapshotDeletionLedger()
|
||||
persisted, ok := readPersistedLedger(t, f2)
|
||||
if !ok || len(persisted) != 2 {
|
||||
t.Fatalf("snapshot during grace must carry recovered ids, got %v", persisted)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletionLedgerZeroValueFiler proves nil-map safety for the struct literals
|
||||
// used across the test suite (they never call NewFiler).
|
||||
func TestDeletionLedgerZeroValueFiler(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
f := &Filer{
|
||||
FileIdDeletionQueue: util.NewUnboundedQueue(),
|
||||
DeletionRetryQueue: NewDeletionRetryQueue(),
|
||||
deletionQuit: make(chan struct{}),
|
||||
}
|
||||
f.queueDeletions("0,01")
|
||||
if f.pendingDeletionCount() != 1 {
|
||||
t.Fatalf("zero-value filer should lazily init the ledger, got %d", f.pendingDeletionCount())
|
||||
}
|
||||
f.forgetDeletion("0,01")
|
||||
if f.pendingDeletionCount() != 0 {
|
||||
t.Fatalf("forget on zero-value filer failed, got %d", f.pendingDeletionCount())
|
||||
}
|
||||
}
|
||||
|
||||
// A manifest that references a part the store cannot return is corruption, not
|
||||
// absence: reload must report failure and nothing may overwrite the surviving
|
||||
// manifest with only the in-memory set.
|
||||
func TestDeletionLedgerMissingPartBlocks(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
|
||||
key := f.deletionLedgerKey()
|
||||
store.kv[key] = []byte(`{"parts":2,"gen":4}`)
|
||||
store.kv[string(deletionLedgerGenPartKey(key, 4, 0))] = []byte(`["1,01"]`)
|
||||
// Part 1 of generation 4 is missing.
|
||||
|
||||
if f.reloadDeletionLedger() {
|
||||
t.Fatalf("a manifest referencing a missing part is corrupt, not absent")
|
||||
}
|
||||
f.queueDeletions("9,99")
|
||||
f.snapshotDeletionLedger()
|
||||
if got := string(store.kv[key]); got != `{"parts":2,"gen":4}` {
|
||||
t.Fatalf("unread ledger must not be overwritten, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A filer restarting under a new advertised address must still find its
|
||||
// previous ledger: the index lists scoped keys, the ids are published under
|
||||
// the new key first, and only then is the stranded key removed.
|
||||
func TestDeletionLedgerAddressChangeClaim(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
fOld := newLedgerTestFiler(store)
|
||||
fOld.Dlm = lock_manager.NewDistributedLockManager("filer-old:8888")
|
||||
fOld.queueDeletions("1,01", "1,02")
|
||||
fOld.snapshotDeletionLedger()
|
||||
|
||||
fNew := newLedgerTestFiler(store)
|
||||
fNew.Dlm = lock_manager.NewDistributedLockManager("filer-new:9999")
|
||||
if !fNew.reloadDeletionLedger() {
|
||||
t.Fatalf("reload should claim the stranded ledger")
|
||||
}
|
||||
if fNew.pendingDeletionCount() != 2 {
|
||||
t.Fatalf("expected 2 claimed ids, got %d", fNew.pendingDeletionCount())
|
||||
}
|
||||
if _, err := store.KvGet(context.Background(), []byte(fOld.deletionLedgerKey())); err != ErrKvNotFound {
|
||||
t.Fatalf("stranded ledger must be removed after claim, got %v", err)
|
||||
}
|
||||
persisted, ok := readPersistedLedger(t, fNew)
|
||||
if !ok || len(persisted) != 2 {
|
||||
t.Fatalf("claimed ids must be durably stored under the new key, got %v", persisted)
|
||||
}
|
||||
indexKeys, _ := fNew.readLedgerIndex(context.Background())
|
||||
if contains(indexKeys, fOld.deletionLedgerKey()) {
|
||||
t.Fatalf("claimed key must leave the index, got %v", indexKeys)
|
||||
}
|
||||
}
|
||||
|
||||
// Every multipart snapshot writes a fresh generation's part keys and publishes
|
||||
// the manifest only after all parts land, so the committed generation is never
|
||||
// overwritten. The previous generation is removed after publication.
|
||||
func TestDeletionLedgerGenerationPublish(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
|
||||
var ids []string
|
||||
for i := 0; i < 4000; i++ {
|
||||
ids = append(ids, fmt.Sprintf("7,%08xbeefcafe", i))
|
||||
}
|
||||
f.queueDeletions(ids...)
|
||||
f.snapshotDeletionLedger()
|
||||
key := f.deletionLedgerKey()
|
||||
if _, err := store.KvGet(context.Background(), deletionLedgerGenPartKey(key, 1, 0)); err != nil {
|
||||
t.Fatalf("generation 1 part must exist, got %v", err)
|
||||
}
|
||||
|
||||
f.queueDeletions("8,08")
|
||||
f.snapshotDeletionLedger()
|
||||
if _, err := store.KvGet(context.Background(), deletionLedgerGenPartKey(key, 2, 0)); err != nil {
|
||||
t.Fatalf("generation 2 part must exist, got %v", err)
|
||||
}
|
||||
if _, err := store.KvGet(context.Background(), deletionLedgerGenPartKey(key, 1, 0)); err != ErrKvNotFound {
|
||||
t.Fatalf("generation 1 part must be cleaned after publication, got %v", err)
|
||||
}
|
||||
var manifest struct {
|
||||
Parts int `json:"parts"`
|
||||
Gen int `json:"gen"`
|
||||
}
|
||||
raw, _ := store.KvGet(context.Background(), []byte(key))
|
||||
if err := json.Unmarshal(raw, &manifest); err != nil || manifest.Gen != 2 {
|
||||
t.Fatalf("manifest must publish generation 2, got %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed cleanup of a superseded generation is retried by the next snapshot
|
||||
// instead of leaking the part keys.
|
||||
func TestDeletionLedgerStalePartsRetried(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
f := newLedgerTestFiler(store)
|
||||
|
||||
var ids []string
|
||||
for i := 0; i < 4000; i++ {
|
||||
ids = append(ids, fmt.Sprintf("7,%08xbeefcafe", i))
|
||||
}
|
||||
f.queueDeletions(ids...)
|
||||
f.snapshotDeletionLedger()
|
||||
key := f.deletionLedgerKey()
|
||||
|
||||
store.kvDeleteErr = errors.New("delete down")
|
||||
f.queueDeletions("8,08")
|
||||
f.snapshotDeletionLedger()
|
||||
if len(f.deletionLedgerStale) == 0 {
|
||||
t.Fatalf("failed part deletes must be tracked for retry")
|
||||
}
|
||||
store.kvDeleteErr = nil
|
||||
f.queueDeletions("8,09")
|
||||
f.snapshotDeletionLedger()
|
||||
if len(f.deletionLedgerStale) != 0 {
|
||||
t.Fatalf("stale parts must flush once deletes work, got %v", f.deletionLedgerStale)
|
||||
}
|
||||
if _, err := store.KvGet(context.Background(), deletionLedgerGenPartKey(key, 1, 0)); err != ErrKvNotFound {
|
||||
t.Fatalf("stale generation part must be deleted, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A pre-scoping ledger under the base key must migrate only after the scoped
|
||||
// copy is durable: the recovered ids are written under the scoped key first,
|
||||
// then the base key is removed.
|
||||
func TestDeletionLedgerLegacyMigrationDurable(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
store.kv[KvKeyDeletionLedger] = []byte(`["1,01","1,02"]`)
|
||||
|
||||
f := newLedgerTestFiler(store)
|
||||
f.Dlm = lock_manager.NewDistributedLockManager("filer-new:9999")
|
||||
if !f.reloadDeletionLedger() {
|
||||
t.Fatalf("reload should migrate the legacy ledger")
|
||||
}
|
||||
persisted, ok := readPersistedLedger(t, f)
|
||||
if !ok || len(persisted) != 2 {
|
||||
t.Fatalf("legacy ids must land under the scoped key first, got %v", persisted)
|
||||
}
|
||||
if _, err := store.KvGet(context.Background(), []byte(KvKeyDeletionLedger)); err != ErrKvNotFound {
|
||||
t.Fatalf("legacy key must be removed once the scoped write is durable, got %v", err)
|
||||
}
|
||||
if f.pendingDeletionCount() != 2 {
|
||||
t.Fatalf("migrated ids must join the pending set, got %d", f.pendingDeletionCount())
|
||||
}
|
||||
}
|
||||
|
||||
// An indexed ledger that cannot be read must not be skipped: claiming the
|
||||
// readable ones and leaving the unreadable one behind would strand it, since
|
||||
// the index is only searched while the filer's own key is absent. The claim
|
||||
// aborts so the reload is retried.
|
||||
func TestDeletionLedgerUnreadableForeignBlocks(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
stranded := KvKeyDeletionLedger + ".filer-old:8888"
|
||||
store.kv[stranded] = []byte(`{"parts":2,"gen":1}`) // manifest without parts = corrupt
|
||||
index, _ := json.Marshal([]string{stranded})
|
||||
store.kv[KvKeyDeletionLedgerIndex] = index
|
||||
|
||||
f := newLedgerTestFiler(store)
|
||||
f.Dlm = lock_manager.NewDistributedLockManager("filer-new:9999")
|
||||
if f.reloadDeletionLedger() {
|
||||
t.Fatalf("an unreadable indexed ledger must fail the reload")
|
||||
}
|
||||
if _, err := store.KvGet(context.Background(), []byte(stranded)); err != nil {
|
||||
t.Fatalf("unreadable ledger must be left untouched, got %v", err)
|
||||
}
|
||||
if _, ok := readPersistedLedger(t, f); ok {
|
||||
t.Fatalf("no scoped ledger may be written while a claim source is unreadable")
|
||||
}
|
||||
}
|
||||
|
||||
// A live filer's ledger is not deleted when it republished between the claim's
|
||||
// read and cleanup: the source stays and its newer ids merge into the claim.
|
||||
// The hook swaps the source content on its second read — the claim's first
|
||||
// read sees the old set, the verification read sees the republished one,
|
||||
// exactly like a peer snapshot landing mid-claim.
|
||||
func TestDeletionLedgerClaimKeepsChangedSource(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
store := newStubFilerStore()
|
||||
srcKey := KvKeyDeletionLedger + ".filer-old:8888"
|
||||
store.kv[srcKey] = []byte(`["1,01","1,02"]`)
|
||||
index, _ := json.Marshal([]string{srcKey})
|
||||
store.kv[KvKeyDeletionLedgerIndex] = index
|
||||
|
||||
srcReads := 0
|
||||
store.kvGetHook = func(key []byte) {
|
||||
if string(key) == srcKey {
|
||||
srcReads++
|
||||
if srcReads == 2 {
|
||||
store.kv[srcKey] = []byte(`["1,01","1,02","1,03"]`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
f := newLedgerTestFiler(store)
|
||||
f.Dlm = lock_manager.NewDistributedLockManager("filer-new:9999")
|
||||
if !f.reloadDeletionLedger() {
|
||||
t.Fatalf("claim should succeed")
|
||||
}
|
||||
if got := string(store.kv[srcKey]); got != `["1,01","1,02","1,03"]` {
|
||||
t.Fatalf("republished source must be left intact, got %q", got)
|
||||
}
|
||||
if f.pendingDeletionCount() != 3 {
|
||||
t.Fatalf("republished ids must merge into the pending set, got %d", f.pendingDeletionCount())
|
||||
}
|
||||
persisted, ok := readPersistedLedger(t, f)
|
||||
if !ok || len(persisted) != 3 {
|
||||
t.Fatalf("merged ids must be durable under our key, got %v", persisted)
|
||||
}
|
||||
}
|
||||
|
||||
// An expired retry item must not erase a newer enqueue for the same file id:
|
||||
// expiry forgets only the epoch the retry item recorded.
|
||||
func TestForgetDeletionEpochSkipsNewer(t *testing.T) {
|
||||
withPersistedConfig(t, true)
|
||||
f := newLedgerTestFiler(newStubFilerStore())
|
||||
|
||||
f.queueDeletions("1,01")
|
||||
oldEpoch := f.deletionEpoch("1,01")
|
||||
f.queueDeletions("1,01") // re-enqueue bumps the epoch
|
||||
newEpoch := f.deletionEpoch("1,01")
|
||||
if oldEpoch == newEpoch {
|
||||
t.Fatalf("re-enqueue must bump the epoch")
|
||||
}
|
||||
|
||||
f.forgetDeletionEpoch("1,01", oldEpoch)
|
||||
if f.pendingDeletionCount() != 1 {
|
||||
t.Fatalf("stale expiry must not erase a newer enqueue")
|
||||
}
|
||||
f.forgetDeletionEpoch("1,01", newEpoch)
|
||||
if f.pendingDeletionCount() != 0 {
|
||||
t.Fatalf("matching expiry must forget the id")
|
||||
}
|
||||
}
|
||||
|
||||
func contains(haystack []string, needle string) bool {
|
||||
for _, s := range haystack {
|
||||
if s == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -10,15 +10,15 @@ func TestDeletionRetryQueue_AddAndRetrieve(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Add items
|
||||
queue.AddOrUpdate("file1", "is read only")
|
||||
queue.AddOrUpdate("file2", "connection reset")
|
||||
queue.AddOrUpdate("file1", "is read only", 0)
|
||||
queue.AddOrUpdate("file2", "connection reset", 0)
|
||||
|
||||
if queue.Size() != 2 {
|
||||
t.Errorf("Expected queue size 2, got %d", queue.Size())
|
||||
}
|
||||
|
||||
// Items not ready yet (initial delay is 5 minutes)
|
||||
readyItems := queue.GetReadyItems(10)
|
||||
readyItems, _ := queue.GetReadyItems(10)
|
||||
if len(readyItems) != 0 {
|
||||
t.Errorf("Expected 0 ready items, got %d", len(readyItems))
|
||||
}
|
||||
@@ -104,7 +104,7 @@ func TestDeletionRetryQueue_MaxAttemptsReached(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Add item
|
||||
queue.AddOrUpdate("file1", "error")
|
||||
queue.AddOrUpdate("file1", "error", 0)
|
||||
|
||||
// Manually set retry count to max
|
||||
queue.lock.Lock()
|
||||
@@ -119,7 +119,7 @@ func TestDeletionRetryQueue_MaxAttemptsReached(t *testing.T) {
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Try to get ready items - should be returned for the last retry (attempt #10)
|
||||
readyItems := queue.GetReadyItems(10)
|
||||
readyItems, _ := queue.GetReadyItems(10)
|
||||
if len(readyItems) != 1 {
|
||||
t.Fatalf("Expected 1 item for last retry, got %d", len(readyItems))
|
||||
}
|
||||
@@ -139,7 +139,7 @@ func TestDeletionRetryQueue_MaxAttemptsReached(t *testing.T) {
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Now it should be discarded (retry count is 11, exceeds max of 10)
|
||||
readyItems = queue.GetReadyItems(10)
|
||||
readyItems, _ = queue.GetReadyItems(10)
|
||||
if len(readyItems) != 0 {
|
||||
t.Errorf("Expected 0 items (max attempts exceeded), got %d", len(readyItems))
|
||||
}
|
||||
@@ -248,7 +248,7 @@ func TestDeletionRetryQueue_HeapOrdering(t *testing.T) {
|
||||
queue.lock.Unlock()
|
||||
|
||||
// GetReadyItems should return in NextRetryAt order
|
||||
readyItems := queue.GetReadyItems(10)
|
||||
readyItems, _ := queue.GetReadyItems(10)
|
||||
expectedOrder := []string{"file1", "file2", "file3"}
|
||||
|
||||
if len(readyItems) != 3 {
|
||||
@@ -266,7 +266,7 @@ func TestDeletionRetryQueue_DuplicateFileIds(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Add same file ID twice with retryable error - simulates duplicate in batch
|
||||
queue.AddOrUpdate("file1", "timeout error")
|
||||
queue.AddOrUpdate("file1", "timeout error", 0)
|
||||
|
||||
// Verify only one item exists in queue
|
||||
if queue.Size() != 1 {
|
||||
@@ -284,7 +284,7 @@ func TestDeletionRetryQueue_DuplicateFileIds(t *testing.T) {
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Add same file ID again - should NOT increment retry count (just update error)
|
||||
queue.AddOrUpdate("file1", "timeout error again")
|
||||
queue.AddOrUpdate("file1", "timeout error again", 0)
|
||||
|
||||
// Verify still only one item exists in queue (not duplicated)
|
||||
if queue.Size() != 1 {
|
||||
@@ -306,3 +306,27 @@ func TestDeletionRetryQueue_DuplicateFileIds(t *testing.T) {
|
||||
t.Errorf("Expected LastError to be updated to 'timeout error again', got %q", item2.LastError)
|
||||
}
|
||||
}
|
||||
|
||||
// AddOrUpdate must not overwrite the ledger epoch on an in-flight item: the
|
||||
// worker that popped it reads that field without the queue lock, and its
|
||||
// expiry/permanent-forget must only match the record the attempt started with.
|
||||
func TestDeletionRetryQueue_InFlightKeepsEpoch(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
queue.AddOrUpdate("file1", "timeout", 7)
|
||||
|
||||
queue.lock.Lock()
|
||||
item := queue.itemIndex["file1"]
|
||||
item.NextRetryAt = time.Now().Add(-time.Second)
|
||||
heap.Init(&queue.heap)
|
||||
queue.lock.Unlock()
|
||||
|
||||
ready, _ := queue.GetReadyItems(1)
|
||||
if len(ready) != 1 {
|
||||
t.Fatalf("expected the item ready, got %d", len(ready))
|
||||
}
|
||||
|
||||
queue.AddOrUpdate("file1", "newer error", 42)
|
||||
if got := ready[0].ledgerEpoch; got != 7 {
|
||||
t.Fatalf("in-flight epoch must stay 7, got %d", got)
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ func (f *Filer) ensureEntryInode(entry *Entry) {
|
||||
entry.Attr.Crtime = time.Now()
|
||||
}
|
||||
if len(entry.HardLinkId) > 0 {
|
||||
entry.Attr.Inode = uint64(util.HashStringToLong(string(entry.HardLinkId)))
|
||||
entry.Attr.Inode = util.NormalizeInode(uint64(util.HashStringToLong(string(entry.HardLinkId))))
|
||||
return
|
||||
}
|
||||
entry.Attr.Inode = entry.FullPath.AsInode(entry.Attr.Crtime.Unix())
|
||||
|
||||
@@ -3,6 +3,8 @@ package filer
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -51,10 +53,56 @@ func TestEnsureEntryInodeSharesAcrossHardLinks(t *testing.T) {
|
||||
|
||||
// Every link to the same target resolves to one inode, independent of path
|
||||
// or creation time.
|
||||
assert.Equal(t, uint64(util.HashStringToLong(string(hardLinkId))), a.Attr.Inode)
|
||||
assert.Equal(t, util.NormalizeInode(uint64(util.HashStringToLong(string(hardLinkId)))), a.Attr.Inode)
|
||||
assert.Equal(t, a.Attr.Inode, b.Attr.Inode)
|
||||
}
|
||||
|
||||
// TestEnsureEntryInodeFitsSignedLong pins the invariant that every generated
|
||||
// inode is storable: the filer hands Attr.Inode to the backing store verbatim,
|
||||
// and the Elasticsearch store indexes it as a signed `long`. Roughly half of
|
||||
// the unsigned hash space sits above math.MaxInt64, so a store that rejects
|
||||
// those values used to fail the metadata write for half of all entries.
|
||||
func TestEnsureEntryInodeFitsSignedLong(t *testing.T) {
|
||||
f := &Filer{}
|
||||
crtime := time.Unix(1700000000, 0)
|
||||
|
||||
seen := make(map[uint64]string)
|
||||
for i := 0; i < 5000; i++ {
|
||||
fullPath := util.FullPath(fmt.Sprintf("/topics/.system/log/2026-10-02/entry-%d", i))
|
||||
entry := &Entry{FullPath: fullPath, Attr: Attr{Crtime: crtime}}
|
||||
f.ensureEntryInode(entry)
|
||||
|
||||
if entry.Attr.Inode > math.MaxInt64 {
|
||||
t.Fatalf("ensureEntryInode(%q) = %d, above math.MaxInt64", fullPath, entry.Attr.Inode)
|
||||
}
|
||||
// Folding must not collapse distinct paths onto one inode.
|
||||
if other, ok := seen[entry.Attr.Inode]; ok {
|
||||
t.Fatalf("ensureEntryInode(%q) collided with %q on inode %d", fullPath, other, entry.Attr.Inode)
|
||||
}
|
||||
seen[entry.Attr.Inode] = string(fullPath)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnsureEntryInodeHardLinkFitsSignedLong covers the hard-link branch, which
|
||||
// hashes HardLinkId instead of the path and so has no path-derived crtime term.
|
||||
func TestEnsureEntryInodeHardLinkFitsSignedLong(t *testing.T) {
|
||||
f := &Filer{}
|
||||
crtime := time.Unix(1700000000, 0)
|
||||
|
||||
for i := 0; i < 5000; i++ {
|
||||
entry := &Entry{
|
||||
FullPath: util.FullPath(fmt.Sprintf("/links/target-%d.txt", i)),
|
||||
Attr: Attr{Crtime: crtime},
|
||||
HardLinkId: NewHardLinkId(),
|
||||
}
|
||||
f.ensureEntryInode(entry)
|
||||
|
||||
if entry.Attr.Inode > math.MaxInt64 {
|
||||
t.Fatalf("ensureEntryInode(%q) = %d, above math.MaxInt64", entry.FullPath, entry.Attr.Inode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newTestFilerWithStubStore() (*Filer, *stubFilerStore) {
|
||||
store := newStubFilerStore()
|
||||
f := NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
|
||||
@@ -173,7 +221,7 @@ func TestUpdateEntryPreservesExistingInode(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
err := f.UpdateEntry(context.Background(), original, updated)
|
||||
err := f.UpdateEntry(context.Background(), original, updated, false)
|
||||
require.Error(t, err)
|
||||
|
||||
updated = &Entry{
|
||||
@@ -182,7 +230,7 @@ func TestUpdateEntryPreservesExistingInode(t *testing.T) {
|
||||
Mode: 0o600,
|
||||
},
|
||||
}
|
||||
err = f.UpdateEntry(context.Background(), original, updated)
|
||||
err = f.UpdateEntry(context.Background(), original, updated, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
stored, findErr := store.FindEntry(context.Background(), original.FullPath)
|
||||
@@ -208,7 +256,7 @@ func TestUpdateEntryBackfillsMissingLegacyInode(t *testing.T) {
|
||||
Mode: 0o640,
|
||||
},
|
||||
}
|
||||
err := f.UpdateEntry(context.Background(), original, updated)
|
||||
err := f.UpdateEntry(context.Background(), original, updated, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
stored, findErr := store.FindEntry(context.Background(), original.FullPath)
|
||||
|
||||
@@ -35,6 +35,9 @@ type stubFilerStore struct {
|
||||
kv map[string][]byte
|
||||
insertErr error
|
||||
findErr error
|
||||
kvGetErr error
|
||||
kvDeleteErr error
|
||||
kvGetHook func(key []byte)
|
||||
deleteErrByPath map[string]error
|
||||
}
|
||||
|
||||
@@ -63,6 +66,12 @@ func (s *stubFilerStore) KvPut(_ context.Context, key []byte, value []byte) erro
|
||||
func (s *stubFilerStore) KvGet(_ context.Context, key []byte) ([]byte, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.kvGetHook != nil {
|
||||
s.kvGetHook(key)
|
||||
}
|
||||
if s.kvGetErr != nil {
|
||||
return nil, s.kvGetErr
|
||||
}
|
||||
value, found := s.kv[string(key)]
|
||||
if !found {
|
||||
return nil, ErrKvNotFound
|
||||
@@ -72,6 +81,9 @@ func (s *stubFilerStore) KvGet(_ context.Context, key []byte) ([]byte, error) {
|
||||
func (s *stubFilerStore) KvDelete(_ context.Context, key []byte) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.kvDeleteErr != nil {
|
||||
return s.kvDeleteErr
|
||||
}
|
||||
delete(s.kv, string(key))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -59,13 +59,24 @@ func (f *Filer) resolveMetadataLogAssignDiskType(targetFile string) (string, *fi
|
||||
return util.Nvl(rule.DiskType, f.DefaultDiskType), rule
|
||||
}
|
||||
|
||||
// metaLogCollectionFor resolves the system metadata log's collection: the
|
||||
// filer.options.metaLog.collection override, then the filer default, then the
|
||||
// matched storage rule.
|
||||
func (f *Filer) metaLogCollectionFor(ruleCollection string) string {
|
||||
return util.Nvl(f.metaLogTargetCollection, f.metaLogCollection, ruleCollection)
|
||||
}
|
||||
|
||||
func (f *Filer) metaLogReplicationFor(ruleReplication string) string {
|
||||
return util.Nvl(f.metaLogTargetReplication, f.metaLogReplication, ruleReplication)
|
||||
}
|
||||
|
||||
func (f *Filer) assignAndUpload(targetFile string, data []byte) (*operation.AssignResult, *operation.UploadResult, error) {
|
||||
// assign a volume location
|
||||
diskType, rule := f.resolveMetadataLogAssignDiskType(targetFile)
|
||||
assignRequest := &operation.VolumeAssignRequest{
|
||||
Count: 1,
|
||||
Collection: util.Nvl(f.metaLogCollection, rule.Collection),
|
||||
Replication: util.Nvl(f.metaLogReplication, rule.Replication),
|
||||
Collection: f.metaLogCollectionFor(rule.Collection),
|
||||
Replication: f.metaLogReplicationFor(rule.Replication),
|
||||
DiskType: diskType,
|
||||
WritableVolumeCount: rule.VolumeGrowthCount,
|
||||
ExpectedDataSize: uint64(len(data)),
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func chunksEqual(a, b []*filer_pb.FileChunk) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i].GetFileIdString() != b[i].GetFileIdString() ||
|
||||
a[i].Size != b[i].Size ||
|
||||
a[i].Offset != b[i].Offset ||
|
||||
a[i].ModifiedTsNs != b[i].ModifiedTsNs {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// IsEvictableRemoteEntry reports whether an entry's local chunks are backed by
|
||||
// a synchronized remote copy, mirroring the checks remote.uncache applies:
|
||||
// remote-backed, chunks present, and not ahead of the remote version.
|
||||
func IsEvictableRemoteEntry(entry *Entry) bool {
|
||||
if entry.IsDirectory() || entry.Remote == nil {
|
||||
return false
|
||||
}
|
||||
if entry.Remote.LastLocalSyncTsNs <= 0 || len(entry.GetChunks()) == 0 {
|
||||
return false
|
||||
}
|
||||
if entry.Remote.LastLocalSyncTsNs < entry.Mtime.UnixNano() {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ListEvictableRemoteEntries walks every mounted directory and returns
|
||||
// synchronized remote entries holding local chunks, oldest cached first.
|
||||
func (f *Filer) ListEvictableRemoteEntries(ctx context.Context, mounts []util.FullPath, minCacheAge time.Duration) (out []*Entry) {
|
||||
cutoffNs := time.Now().UnixNano() - minCacheAge.Nanoseconds()
|
||||
for _, dir := range mounts {
|
||||
if err := f.collectEvictableRemoteEntries(ctx, dir, cutoffNs, &out); err != nil {
|
||||
glog.WarningfCtx(ctx, "list evictable remote entries under %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
return out[i].Remote.LastLocalSyncTsNs < out[j].Remote.LastLocalSyncTsNs
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func (f *Filer) collectEvictableRemoteEntries(ctx context.Context, dir util.FullPath, cutoffNs int64, out *[]*Entry) error {
|
||||
startFileName := ""
|
||||
for {
|
||||
var subDirs []util.FullPath
|
||||
lastFileName, err := f.Store.ListDirectoryEntries(ctx, dir, startFileName, false, 1024, func(entry *Entry) (bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if entry.IsDirectory() {
|
||||
subDirs = append(subDirs, entry.FullPath)
|
||||
return true, nil
|
||||
}
|
||||
if entry.Remote != nil && entry.Remote.LastLocalSyncTsNs > 0 && entry.Remote.LastLocalSyncTsNs <= cutoffNs && IsEvictableRemoteEntry(entry) {
|
||||
*out = append(*out, entry)
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, subDir := range subDirs {
|
||||
if err := f.collectEvictableRemoteEntries(ctx, subDir, cutoffNs, out); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if lastFileName == "" {
|
||||
return nil
|
||||
}
|
||||
startFileName = lastFileName
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func remoteCachedEntry(path string, syncTsNs int64, mtime time.Time, chunks int) *Entry {
|
||||
entry := &Entry{
|
||||
FullPath: util.FullPath(path),
|
||||
Attr: Attr{
|
||||
Mtime: mtime,
|
||||
Crtime: mtime,
|
||||
Mode: 0644,
|
||||
Uid: 1,
|
||||
Gid: 1,
|
||||
Mime: "application/octet-stream",
|
||||
Md5: nil,
|
||||
FileSize: 0,
|
||||
},
|
||||
Remote: &filer_pb.RemoteEntry{
|
||||
RemoteMtime: mtime.Unix(),
|
||||
LastLocalSyncTsNs: syncTsNs,
|
||||
RemoteETag: "etag",
|
||||
RemoteSize: 100,
|
||||
},
|
||||
}
|
||||
for i := 0; i < chunks; i++ {
|
||||
entry.Chunks = append(entry.Chunks, &filer_pb.FileChunk{FileId: "1,01637037d6", Size: 100})
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestIsEvictableRemoteEntry(t *testing.T) {
|
||||
now := time.Now()
|
||||
synced := now.Add(-time.Hour).UnixNano()
|
||||
mtime := now.Add(-time.Hour)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
entry *Entry
|
||||
expected bool
|
||||
}{
|
||||
{"directory", &Entry{FullPath: "/d", Attr: Attr{Mode: os.ModeDir | 0755}}, false},
|
||||
{"local only, no remote", &Entry{FullPath: "/f", Attr: Attr{Mtime: mtime, Mode: 0644}}, false},
|
||||
{"remote only, never cached", remoteCachedEntry("/f", 0, mtime, 0), false},
|
||||
{"remote, chunks cleared", remoteCachedEntry("/f", synced, mtime, 0), false},
|
||||
{"dirty, newer than remote", remoteCachedEntry("/f", synced, now, 1), false},
|
||||
{"same-second write after sync", remoteCachedEntry("/f",
|
||||
now.Truncate(time.Second).Add(100*time.Millisecond).UnixNano(),
|
||||
now.Truncate(time.Second).Add(900*time.Millisecond), 1), false},
|
||||
{"same-second sync after write", remoteCachedEntry("/f",
|
||||
now.Truncate(time.Second).Add(900*time.Millisecond).UnixNano(),
|
||||
now.Truncate(time.Second).Add(100*time.Millisecond), 1), true},
|
||||
{"synced and cached", remoteCachedEntry("/f", synced, mtime, 1), true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
assert.Equal(t, tt.expected, IsEvictableRemoteEntry(tt.entry), tt.name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListEvictableRemoteEntries(t *testing.T) {
|
||||
now := time.Now()
|
||||
mtime := now.Add(-2 * time.Hour)
|
||||
oldSync := now.Add(-time.Hour).UnixNano()
|
||||
newSync := now.Add(-time.Second).UnixNano()
|
||||
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
mounts := []util.FullPath{"/buckets/mybucket"}
|
||||
|
||||
seed := func(e *Entry) {
|
||||
require.NoError(t, f.CreateEntry(context.Background(), e, nil, false, false, nil, false, 255))
|
||||
}
|
||||
seed(remoteCachedEntry("/buckets/mybucket/old.bin", oldSync, mtime, 1))
|
||||
seed(remoteCachedEntry("/buckets/mybucket/fresh.bin", newSync, mtime, 1))
|
||||
seed(remoteCachedEntry("/buckets/mybucket/remoteonly.bin", 0, mtime, 0))
|
||||
seed(remoteCachedEntry("/buckets/mybucket/dirty.bin", oldSync, now, 1))
|
||||
seed(&Entry{FullPath: "/buckets/mybucket/plain.bin", Attr: Attr{Mtime: mtime, Mode: 0644}})
|
||||
|
||||
store.entries["/buckets/mybucket/sub"] = &Entry{
|
||||
FullPath: "/buckets/mybucket/sub",
|
||||
Attr: Attr{Mode: os.ModeDir | 0755, Mtime: mtime},
|
||||
}
|
||||
seed(remoteCachedEntry("/buckets/mybucket/sub/nested.bin", oldSync-1000, mtime, 1))
|
||||
|
||||
got := f.ListEvictableRemoteEntries(context.Background(), mounts, 0)
|
||||
var paths []string
|
||||
for _, e := range got {
|
||||
paths = append(paths, string(e.FullPath))
|
||||
}
|
||||
assert.Equal(t, []string{
|
||||
"/buckets/mybucket/sub/nested.bin",
|
||||
"/buckets/mybucket/old.bin",
|
||||
"/buckets/mybucket/fresh.bin",
|
||||
}, paths, "oldest LastLocalSyncTsNs first; remote-only, dirty, local entries skipped")
|
||||
|
||||
got = f.ListEvictableRemoteEntries(context.Background(), mounts, 30*time.Second)
|
||||
paths = paths[:0]
|
||||
for _, e := range got {
|
||||
paths = append(paths, string(e.FullPath))
|
||||
}
|
||||
assert.Equal(t, []string{
|
||||
"/buckets/mybucket/sub/nested.bin",
|
||||
"/buckets/mybucket/old.bin",
|
||||
}, paths, "minCacheAge excludes freshly cached entries")
|
||||
}
|
||||
|
||||
func TestUpdateEntryInvalidatesStaleSyncStamp(t *testing.T) {
|
||||
now := time.Now()
|
||||
synced := now.Add(-time.Hour).UnixNano()
|
||||
mtime := now.Add(-time.Hour)
|
||||
path := "/buckets/mybucket/a.bin"
|
||||
|
||||
newFiler := func() *Filer {
|
||||
f := newTestFiler(t, newStubFilerStore(), NewFilerRemoteStorage())
|
||||
require.NoError(t, f.CreateEntry(context.Background(), remoteCachedEntry(path, synced, mtime, 1), nil, false, false, nil, false, 255))
|
||||
return f
|
||||
}
|
||||
syncStamp := func(f *Filer) int64 {
|
||||
entry, err := f.FindEntry(context.Background(), util.FullPath(path))
|
||||
require.NoError(t, err)
|
||||
return entry.Remote.LastLocalSyncTsNs
|
||||
}
|
||||
|
||||
t.Run("local chunk change clears stamp", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, synced, mtime, 1)
|
||||
update.Chunks[0].FileId = "2,01637037d6"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, false, nil, false, 255))
|
||||
assert.Zero(t, syncStamp(f))
|
||||
})
|
||||
|
||||
t.Run("metadata-only update keeps stamp", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, synced, mtime, 1)
|
||||
update.Attr.Mime = "text/plain"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, false, nil, false, 255))
|
||||
assert.Equal(t, synced, syncStamp(f))
|
||||
})
|
||||
|
||||
t.Run("fresh sync stamp survives chunk change", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, now.UnixNano(), mtime, 1)
|
||||
update.Chunks[0].FileId = "2,01637037d6"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, false, nil, false, 255))
|
||||
assert.Equal(t, now.UnixNano(), syncStamp(f))
|
||||
})
|
||||
|
||||
t.Run("replicated update keeps authoritative stamp", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, synced, mtime, 1)
|
||||
update.Chunks[0].FileId = "2,01637037d6"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, true, nil, false, 255))
|
||||
assert.Equal(t, synced, syncStamp(f))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// The metadata log's collection resolution must let operators redirect the
|
||||
// internal /topics/.system/log chunks into their own collection without
|
||||
// touching where user data goes, and must be strictly backward compatible
|
||||
// when the override is unset.
|
||||
|
||||
func TestMetaLogCollectionResolution(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
target string // filer.options.metaLog.collection override
|
||||
filerDefault string // -collection flag value
|
||||
ruleCollection string // storage rule matched on the log path
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "no override: filer default wins (today's behaviour)",
|
||||
target: "",
|
||||
filerDefault: "mydata",
|
||||
ruleCollection: "",
|
||||
want: "mydata",
|
||||
},
|
||||
{
|
||||
name: "no override anywhere: still empty (default collection)",
|
||||
target: "",
|
||||
filerDefault: "",
|
||||
ruleCollection: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "override wins over filer default",
|
||||
target: "filer-meta",
|
||||
filerDefault: "mydata",
|
||||
ruleCollection: "",
|
||||
want: "filer-meta",
|
||||
},
|
||||
{
|
||||
name: "override wins over matched rule",
|
||||
target: "filer-meta",
|
||||
filerDefault: "",
|
||||
ruleCollection: "rulecol",
|
||||
want: "filer-meta",
|
||||
},
|
||||
{
|
||||
name: "no override but rule set: rule used (unchanged fallback chain)",
|
||||
target: "",
|
||||
filerDefault: "",
|
||||
ruleCollection: "rulecol",
|
||||
want: "rulecol",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Drive the same setter a running filer would use post-construction.
|
||||
f := &Filer{}
|
||||
f.metaLogTargetCollection = tc.target
|
||||
f.metaLogCollection = tc.filerDefault
|
||||
if got := f.metaLogCollectionFor(tc.ruleCollection); got != tc.want {
|
||||
t.Errorf("metaLogCollectionFor(%q) = %q, want %q", tc.ruleCollection, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetaLogReplicationResolution(t *testing.T) {
|
||||
f := &Filer{}
|
||||
f.metaLogTargetReplication = "110"
|
||||
f.metaLogReplication = "010"
|
||||
if got := f.metaLogReplicationFor("001"); got != "110" {
|
||||
t.Errorf("override must win, got %q", got)
|
||||
}
|
||||
f.metaLogTargetReplication = ""
|
||||
if got := f.metaLogReplicationFor("001"); got != "010" {
|
||||
t.Errorf("filer replication must win when no override, got %q", got)
|
||||
}
|
||||
f.metaLogReplication = ""
|
||||
if got := f.metaLogReplicationFor("001"); got != "001" {
|
||||
t.Errorf("rule replication must be used last, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestViperReadsMetaLogOverrides proves the exact viper keys the docs promise
|
||||
// are read into the fields a running filer uses.
|
||||
func TestViperReadsMetaLogOverrides(t *testing.T) {
|
||||
v := util.GetViper()
|
||||
v.Set("filer.options.metaLog.collection", "filer-meta")
|
||||
v.Set("filer.options.metaLog.replication", "100")
|
||||
defer func() {
|
||||
// Reset so other tests see the unset default.
|
||||
v.Set("filer.options.metaLog.collection", "")
|
||||
v.Set("filer.options.metaLog.replication", "")
|
||||
}()
|
||||
|
||||
f := NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
|
||||
if got := f.metaLogTargetCollection; got != "filer-meta" {
|
||||
t.Fatalf("NewFiler did not read the collection override: %q", got)
|
||||
}
|
||||
if got := f.metaLogTargetReplication; got != "100" {
|
||||
t.Fatalf("NewFiler did not read the replication override: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBucketCollectionKeepsMetaLogTargetCollection mirrors the guarantee that
|
||||
// protects the filer's default collection: when a bucket resolves to the
|
||||
// collection the system metadata log was redirected to, deleting the bucket
|
||||
// must not drop that collection (it backs internal log volumes).
|
||||
func TestBucketCollectionKeepsMetaLogTargetCollection(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
// Operator redirected the meta log to its own collection...
|
||||
f.metaLogTargetCollection = "filer-meta"
|
||||
// ...and a bucket happens to resolve to that very collection.
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/a",
|
||||
Collection: "filer-meta",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/a"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/a", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
t.Fatalf("the meta-log target collection was deleted by a bucket delete: %q", call.name)
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -190,7 +190,7 @@ func loadLogFileEntries(masterClient *wdclient.MasterClient, chunk *filer_pb.Fil
|
||||
lookupFileIdFn := func(ctx context.Context, fileId string) (targetUrls []string, err error) {
|
||||
return masterClient.LookupFileId(ctx, fileId)
|
||||
}
|
||||
if fetchErr := fetchWholeChunk(context.Background(), bytesBuffer, lookupFileIdFn, chunk.GetFileIdString(), chunk.CipherKey, chunk.IsCompressed, masterClient); fetchErr != nil {
|
||||
if fetchErr := fetchWholeChunk(context.Background(), bytesBuffer, lookupFileIdFn, chunk.GetFileIdString(), chunk.CipherKey, chunk.IsCompressed, masterClient, nil); fetchErr != nil {
|
||||
return nil, false, fetchErr
|
||||
}
|
||||
return decodeLogRecords(bytesBuffer.Bytes())
|
||||
|
||||
@@ -75,6 +75,9 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di
|
||||
})
|
||||
} else if err == nil {
|
||||
entry := resp.Entry
|
||||
if bytes.Equal(entry.Content, content) && bytes.Equal(entry.GetAttributes().GetMd5(), contentMd5[:]) {
|
||||
return nil
|
||||
}
|
||||
entry.Content = content
|
||||
entry.Attributes.Mtime = time.Now().Unix()
|
||||
entry.Attributes.FileSize = uint64(len(content))
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Rewriting identical inline content must not issue UpdateEntry: each one is a
|
||||
// metadata event the local meta log persists to /topics/.system/log, and a
|
||||
// client that rewrites the same config on a timer (e.g. the operator's 5-minute
|
||||
// resync) keeps the volumes growing on an otherwise idle cluster.
|
||||
func TestSaveInsideFilerSkipsIdenticalContent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := newFakeFilerConfClient()
|
||||
|
||||
require.NoError(t, SaveInsideFiler(ctx, client, DirectoryEtcSeaweedFS, "a.json", []byte("v1")))
|
||||
require.Equal(t, 0, client.updateCalls)
|
||||
|
||||
require.NoError(t, SaveInsideFiler(ctx, client, DirectoryEtcSeaweedFS, "a.json", []byte("v1")))
|
||||
assert.Equal(t, 0, client.updateCalls)
|
||||
|
||||
require.NoError(t, SaveInsideFiler(ctx, client, DirectoryEtcSeaweedFS, "a.json", []byte("v2")))
|
||||
assert.Equal(t, 1, client.updateCalls)
|
||||
|
||||
content, err := ReadInsideFiler(ctx, client, DirectoryEtcSeaweedFS, "a.json")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte("v2"), content)
|
||||
}
|
||||
|
||||
// A legacy entry holding identical bytes but no Md5 still gets one write to
|
||||
// stamp the hash that IF_ETAG_MATCH conditional writes key off; later
|
||||
// identical writes skip.
|
||||
func TestSaveInsideFilerStampsMd5OnLegacyEntry(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := newFakeFilerConfClient()
|
||||
client.entries[client.key(DirectoryEtcSeaweedFS, "b.json")] = &filer_pb.Entry{
|
||||
Name: "b.json",
|
||||
Content: []byte("v1"),
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
}
|
||||
|
||||
require.NoError(t, SaveInsideFiler(ctx, client, DirectoryEtcSeaweedFS, "b.json", []byte("v1")))
|
||||
assert.Equal(t, 1, client.updateCalls)
|
||||
|
||||
require.NoError(t, SaveInsideFiler(ctx, client, DirectoryEtcSeaweedFS, "b.json", []byte("v1")))
|
||||
assert.Equal(t, 1, client.updateCalls)
|
||||
}
|
||||
+19
-3
@@ -349,14 +349,23 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
|
||||
|
||||
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
|
||||
|
||||
if c.readerPattern.IsRandomMode() {
|
||||
// A view clipped to part of its chunk (e.g. the edge of a ranged GET,
|
||||
// whose views ViewFromVisibleIntervals clips to the request) only ever
|
||||
// needs that part: fetch it as a range no matter the detected pattern.
|
||||
// Fetching the chunk whole would multiply volume-server reads. Ciphered
|
||||
// and compressed chunks are the exception: the volume server reads the
|
||||
// whole blob to serve a range, so they take the shared whole-chunk path
|
||||
// where one download serves every buffer — unless the whole chunk cannot
|
||||
// even fit the reader budget, in which case a range fetch is the only
|
||||
// way to serve the request.
|
||||
rangeFetch := chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))
|
||||
if rangeFetch && (!chunkView.IsFullChunk() || c.readerPattern.IsRandomMode()) {
|
||||
c.readerCache.releaseStream(&c.stream)
|
||||
n, err := c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
|
||||
if n > 0 {
|
||||
return n, err
|
||||
}
|
||||
return fetchChunkRange(ctx, buffer, c.readerCache.lookupFileIdFn, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset),
|
||||
refreshUrls(ctx, c.readerCache.cacheInvalidator, c.readerCache.lookupFileIdFn, chunkView.FileId))
|
||||
return c.readerCache.fetchChunkRange(ctx, buffer, chunkView, int64(offset))
|
||||
}
|
||||
|
||||
shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache()
|
||||
@@ -380,6 +389,13 @@ func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunk
|
||||
// readChunkSliceAtForParallel is a simplified version for parallel chunk fetching
|
||||
// It doesn't update lastChunkFid or trigger prefetch (handled by the caller)
|
||||
func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer []byte, chunkView *ChunkView, offset uint64) (n int, err error) {
|
||||
if (chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
|
||||
n, err = c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
|
||||
if n > 0 {
|
||||
return n, err
|
||||
}
|
||||
return c.readerCache.fetchChunkRange(ctx, buffer, chunkView, int64(offset))
|
||||
}
|
||||
shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache()
|
||||
return c.readerCache.ReadChunkAt(ctx, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
|
||||
}
|
||||
|
||||
@@ -208,6 +208,201 @@ func TestChunkStreamConcurrentReadsOnOneReader(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type recordedFetch struct {
|
||||
fileId string
|
||||
isFullChunk bool
|
||||
offset int64
|
||||
size int
|
||||
}
|
||||
|
||||
// fetchRecorder stubs the volume fetch and records how each chunk was
|
||||
// requested: isFullChunk=false is a range fetch of just the view's slice,
|
||||
// isFullChunk=true is a whole-chunk download into the shared cache.
|
||||
func fetchRecorder(rc *ReaderCache) (fetches *[]recordedFetch) {
|
||||
var mu sync.Mutex
|
||||
recorded := &[]recordedFetch{}
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, isFullChunk bool, offset int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
mu.Lock()
|
||||
*recorded = append(*recorded, recordedFetch{fileId, isFullChunk, offset, len(buffer)})
|
||||
mu.Unlock()
|
||||
for i := range buffer {
|
||||
buffer[i] = fileId[len(fileId)-1]
|
||||
}
|
||||
return len(buffer), nil
|
||||
}
|
||||
return recorded
|
||||
}
|
||||
|
||||
// A reader whose views are clipped to a request window — how the S3 gateway
|
||||
// builds a ranged GET — must fetch only the covered part of each chunk:
|
||||
// clipped edge views take range fetches, a fully covered chunk keeps the
|
||||
// shared whole-chunk path. This is what keeps a ranged GET larger than a
|
||||
// buffer from multiplying volume-server reads (issue #11564), without giving
|
||||
// up whole-chunk caching where the whole chunk is actually wanted.
|
||||
func TestChunkReadAtClippedViewsFetchOnlyCoveredParts(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
// Window [56KiB, 152KiB): tail of chunk0, all of chunk1, head of
|
||||
// chunk2, head of ciphered chunk3, head of compressed chunk4 (file
|
||||
// chunks need not be aligned).
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: chunkSize - 8<<10,
|
||||
StopOffset: chunkSize,
|
||||
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: chunkSize - 8<<10, ViewSize: 8 << 10, ViewOffset: chunkSize - 8<<10, ChunkSize: chunkSize},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: chunkSize,
|
||||
StopOffset: 2 * chunkSize,
|
||||
Value: &ChunkView{FileId: "chunk1", ViewSize: chunkSize, ViewOffset: chunkSize, ChunkSize: chunkSize},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 2 * chunkSize,
|
||||
StopOffset: 2*chunkSize + 8<<10,
|
||||
Value: &ChunkView{FileId: "chunk2", ViewSize: 8 << 10, ViewOffset: 2 * chunkSize, ChunkSize: chunkSize},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 2*chunkSize + 8<<10,
|
||||
StopOffset: 2*chunkSize + 16<<10,
|
||||
Value: &ChunkView{FileId: "chunk3", ViewSize: 8 << 10, ViewOffset: 2*chunkSize + 8<<10, ChunkSize: chunkSize, CipherKey: []byte("key")},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 2*chunkSize + 16<<10,
|
||||
StopOffset: 2*chunkSize + 24<<10,
|
||||
Value: &ChunkView{FileId: "chunk4", ViewSize: 8 << 10, ViewOffset: 2*chunkSize + 16<<10, ChunkSize: chunkSize, IsGzipped: true},
|
||||
})
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, 4*chunkSize, 0)
|
||||
buf := make([]byte, chunkSize+32<<10)
|
||||
if n, err := reader.ReadAt(buf, chunkSize-8<<10); err != nil || n != len(buf) {
|
||||
t.Fatalf("window read: n=%d err=%v", n, err)
|
||||
}
|
||||
// buf holds [56KiB, 152KiB): chunk0's tail, chunk1, and the heads of
|
||||
// chunk2, chunk3 and chunk4.
|
||||
for i, b := range buf {
|
||||
want := byte('1')
|
||||
if i < 8<<10 {
|
||||
want = '0'
|
||||
} else if i >= 24<<10+chunkSize {
|
||||
want = '4'
|
||||
} else if i >= 16<<10+chunkSize {
|
||||
want = '3'
|
||||
} else if i >= 8<<10+chunkSize {
|
||||
want = '2'
|
||||
}
|
||||
if b != want {
|
||||
t.Fatalf("buf[%d]=%q, want %q", i, b, want)
|
||||
}
|
||||
}
|
||||
|
||||
want := []recordedFetch{
|
||||
{fileId: "chunk0", isFullChunk: false, offset: chunkSize - 8<<10, size: 8 << 10},
|
||||
{fileId: "chunk1", isFullChunk: true, offset: 0, size: chunkSize},
|
||||
{fileId: "chunk2", isFullChunk: false, offset: 0, size: 8 << 10},
|
||||
// partial views, but ciphered and compressed chunks download whole
|
||||
// either way and the shared path decrypts/decompresses once for
|
||||
// every buffer
|
||||
{fileId: "chunk3", isFullChunk: true, offset: 0, size: chunkSize},
|
||||
{fileId: "chunk4", isFullChunk: true, offset: 0, size: chunkSize},
|
||||
}
|
||||
got := map[string]recordedFetch{}
|
||||
for _, f := range *fetches {
|
||||
if _, dup := got[f.fileId]; dup {
|
||||
t.Fatalf("chunk %s fetched more than once: %+v", f.fileId, *fetches)
|
||||
}
|
||||
got[f.fileId] = f
|
||||
}
|
||||
for _, w := range want {
|
||||
if g, ok := got[w.fileId]; !ok {
|
||||
t.Fatalf("chunk %s never fetched: %+v", w.fileId, *fetches)
|
||||
} else if g != w {
|
||||
t.Fatalf("chunk %s fetched as %+v, want %+v", w.fileId, g, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The regression from issue #11564: a ranged GET sitting inside one big
|
||||
// chunk. Every buffer of the request must stay a range fetch — none may
|
||||
// escalate into a whole-chunk download once the reads look sequential.
|
||||
func TestChunkReadAtRangeInsideOneChunkStaysRangeFetch(t *testing.T) {
|
||||
const chunkSize = 1 << 20
|
||||
const sliceSize = 16 << 10
|
||||
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
// Range [32KiB, 96KiB) inside one 1MiB chunk: a single clipped view.
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 32 << 10,
|
||||
StopOffset: 96 << 10,
|
||||
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: 32 << 10, ViewSize: 64 << 10, ViewOffset: 32 << 10, ChunkSize: chunkSize},
|
||||
})
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
||||
for offset := int64(32 << 10); offset < 96<<10; offset += sliceSize {
|
||||
buf := make([]byte, sliceSize)
|
||||
if n, err := reader.ReadAt(buf, offset); err != nil || n != sliceSize {
|
||||
t.Fatalf("read at %d: n=%d err=%v", offset, n, err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(*fetches) != 4 {
|
||||
t.Fatalf("got %d fetches, want 4 range fetches: %+v", len(*fetches), *fetches)
|
||||
}
|
||||
for i, f := range *fetches {
|
||||
wantOffset := int64(32<<10) + int64(i)*sliceSize
|
||||
if f.isFullChunk || f.offset != wantOffset || f.size != sliceSize {
|
||||
t.Fatalf("fetch %d = %+v, want range fetch offset=%d size=%d", i, f, wantOffset, sliceSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A compressed chunk larger than the reader cache budget can never be
|
||||
// downloaded whole — the budget rejects the buffer — so its partial view
|
||||
// must fall back to a range fetch even though each range costs a full
|
||||
// decompress server-side. The alternative is a failed GET.
|
||||
func TestChunkReadAtOversizedCompressedChunkFallsBackToRange(t *testing.T) {
|
||||
const chunkSize = 1 << 20
|
||||
const sliceSize = 16 << 10
|
||||
|
||||
budget := NewReaderCacheBudget(64 << 10) // smaller than the chunk
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil, budget)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 32 << 10,
|
||||
StopOffset: 64 << 10,
|
||||
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: 32 << 10, ViewSize: 32 << 10, ViewOffset: 32 << 10, ChunkSize: chunkSize, IsGzipped: true},
|
||||
})
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
||||
buf := make([]byte, 32<<10)
|
||||
if n, err := reader.ReadAt(buf, 32<<10); err != nil || n != len(buf) {
|
||||
t.Fatalf("read: n=%d err=%v", n, err)
|
||||
}
|
||||
|
||||
if len(*fetches) != 1 {
|
||||
t.Fatalf("got %d fetches, want 1 range fetch: %+v", len(*fetches), *fetches)
|
||||
}
|
||||
if f := (*fetches)[0]; f.isFullChunk || f.offset != 32<<10 || f.size != 32<<10 {
|
||||
t.Fatalf("fetch = %+v, want range fetch offset=%d size=%d", f, 32<<10, 32<<10)
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk a stream is positioned in must outlast downloader-limit eviction:
|
||||
// otherwise a busy cache drops the buffer mid-stream and forces a refetch.
|
||||
func TestChunkReadAtPinnedChunkSurvivesEviction(t *testing.T) {
|
||||
|
||||
@@ -100,6 +100,14 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
|
||||
// abort when slots are filled
|
||||
return
|
||||
}
|
||||
if (chunkView.CanRangeFetch() || !rc.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
|
||||
// the view is clipped to part of the chunk and will be
|
||||
// range-fetched, so prefetching it whole would download bytes
|
||||
// nobody needs; a ciphered or compressed partial view needs
|
||||
// the whole blob anyway and is worth prefetching, but not when
|
||||
// it cannot fit the budget at all
|
||||
continue
|
||||
}
|
||||
|
||||
// glog.V(4).Infof("prefetch %s offset %d", chunkView.FileId, chunkView.ViewOffset)
|
||||
// cache this chunk if not yet
|
||||
@@ -114,6 +122,20 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
|
||||
return
|
||||
}
|
||||
|
||||
// fetchChunkRange downloads only [offset, offset+len(buffer)) of a chunk,
|
||||
// for views clipped to part of their chunk and for random-mode reads. It
|
||||
// goes through fetchChunkDataFn so tests observe range fetches the same way
|
||||
// they observe whole-chunk downloads.
|
||||
func (rc *ReaderCache) fetchChunkRange(ctx context.Context, buffer []byte, chunkView *ChunkView, offset int64) (int, error) {
|
||||
urlStrings, err := rc.lookupFileIdFn(ctx, chunkView.FileId)
|
||||
if err != nil {
|
||||
glog.ErrorfCtx(ctx, "operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
|
||||
return 0, err
|
||||
}
|
||||
return rc.fetchChunkDataFn(ctx, buffer, urlStrings, chunkView.CipherKey, chunkView.IsGzipped, false, offset, chunkView.FileId,
|
||||
refreshUrls(ctx, rc.cacheInvalidator, rc.lookupFileIdFn, chunkView.FileId))
|
||||
}
|
||||
|
||||
// chunkStream is one sequential reader's position in a shared ReaderCache.
|
||||
// The chunk it is reading stays pinned until the stream reads it to the end or
|
||||
// moves elsewhere, so another stream finishing or leaving the same chunk does
|
||||
|
||||
@@ -93,6 +93,13 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error {
|
||||
}
|
||||
}
|
||||
|
||||
// canFit reports whether a whole-chunk buffer of this size can ever be
|
||||
// reserved. A chunk bigger than the budget cannot be read through the
|
||||
// whole-chunk path at all, so callers must fall back to range fetches.
|
||||
func (b *ReaderCacheBudget) canFit(size int) bool {
|
||||
return b == nil || int64(mem.AllocationSize(size)) <= b.limit
|
||||
}
|
||||
|
||||
func (b *ReaderCacheBudget) complete(s *SingleChunkCacher) {
|
||||
if b == nil {
|
||||
return
|
||||
|
||||
@@ -72,7 +72,7 @@ func TestReaderCacheBudgetInFlight(t *testing.T) {
|
||||
return len(buffer), nil
|
||||
}
|
||||
if prefetch {
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ChunkSize: 3 << 10}}, 1)
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewSize: 3 << 10, ChunkSize: 3 << 10}}, 1)
|
||||
} else {
|
||||
readers.Add(1)
|
||||
go func() {
|
||||
@@ -180,7 +180,7 @@ func TestReaderCacheFailedPrefetchReleasesBudget(t *testing.T) {
|
||||
rc.fetchChunkDataFn = func(_ context.Context, _ []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
return 0, fmt.Errorf("fetch failed")
|
||||
}
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "failed", ChunkSize: 1024}}, 1)
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "failed", ViewSize: 1024, ChunkSize: 1024}}, 1)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
rc.Lock()
|
||||
@@ -278,7 +278,7 @@ func TestReaderCachePrefetchBufferDroppedAfterRead(t *testing.T) {
|
||||
buffer[0] = 42
|
||||
return len(buffer), nil
|
||||
}
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ChunkSize: 4 << 10}}, 1)
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewSize: 4 << 10, ChunkSize: 4 << 10}}, 1)
|
||||
|
||||
buf := make([]byte, 4<<10)
|
||||
n, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false)
|
||||
|
||||
@@ -54,10 +54,13 @@ func (rp *ReaderPattern) MonitorReadAt(offset int64, size int) {
|
||||
if counter < ModeChangeLimit {
|
||||
atomic.AddInt64(&rp.isSequentialCounter, 1)
|
||||
}
|
||||
} else if counter <= 0 {
|
||||
// Entering random mode is a strong verdict: drop to the bottom of
|
||||
// the window so the contiguous tail of one ranged request cannot
|
||||
// flip it back on the next buffer read and pay a whole-chunk fetch.
|
||||
atomic.StoreInt64(&rp.isSequentialCounter, -ModeChangeLimit)
|
||||
} else {
|
||||
if counter > -ModeChangeLimit {
|
||||
atomic.AddInt64(&rp.isSequentialCounter, -1)
|
||||
}
|
||||
atomic.AddInt64(&rp.isSequentialCounter, -1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user