Repository navigation
fix(posix): stale metadata cache after 'opencloud posixfs scan' - #962
NickWalters wants to merge 6 commits into
Conversation
|
@pbleser-oc, you reported opencloud-eu/opencloud#3804. Could you review this PR when you have time? It covers your proposed fixes 3 and 4. When the watcher skips an item that the scan already assimilated, it now drops the stale cache. Propagation now reads the tree size from disk under the lock. Scenario A (memory cache without |
|
Hi @NickWalters, thank you for picking this up, and sorry for the wait. I wanted to give it a proper look before answering. I ran the scenarios from opencloud-eu/opencloud#3804 against your branch, and against its base (c7b9e31) for comparison:
Your tests pass, and each of them fails when its fix is taken out. I also like that There's one thing that makes me want to hold off merging for now, though. Dropping the cache entry of a node right after locking it means that more reads go to disk while the lock is held. On posix, a read that misses the cache takes the metadata lock, and that lock is tracked per node object, not per file: when a node is locked through one object and read through another one, the read waits for its own lock. That's also why posix refuses a In a stress test (concurrent uploads, moves and deletes on a few files, plus The upload path where this happens is being reworked right now, and more changes to it are coming in the next days and weeks. Once that has settled, I'll look at your PR again, also with the stress test, and we'll see what's needed to get it in. Most of it may well apply as it is. About the cost with shared stores: your offer to limit the invalidation to process-local stores sounds good to me, since Thanks again, this is a really thorough PR, and opencloud-eu/opencloud#3804 is much better understood thanks to it. |
|
Thanks for the detailed testing. Invalidation now applies only to process-local caches, and stale entries reload under each node’s lock. I also reproduced the cold-cache upload deadlock on main and fixed that path with a lock-aware read. The regression, race-enabled mixed stress runs, lint, and platform vet checks pass. Some concurrent scan errors remain, so I’m not claiming this resolves every concurrency issue. Could you rerun your workload once the upload path rework is done? |
1a17fcf to
601916f
Compare
|
Rebased on main. The conflict came from a6864c7, which removed the legacy upload path and The lock-aware read for an existing upload node moved to
Checked: @butonic could you approve the CI run and take a look? You wrote the coordinator change this builds on. |
|
@NickWalters, thanks for the rebase, and for moving the fix into I opened #1006 for the upload deadlock, since it's a bug on Would you mind adding "Fixes #1006" to the description, so that it gets closed with this PR? Thank you. |
|
One more point, about what
The last one is because the scan process starts with an empty cache, so every changed file finds its entry missing and reloads itself and every parent up to the space root. The parents are shared by many files, so most of those reloads are repeats: about 150,000 instead of 551 here. A suggestion: remember the nodes reloaded during one walk, and stop walking up at the first parent that was already reloaded, since its own parents were reloaded with it. Single watch events, outside of a walk, would behave as now. I tried that on top of your branch, and it brought the same rescan down to 214 s (+14% instead of +39%, 3 rounds each). Vet and the posix tests pass with it. It's only a sketch; feel free to take it, change it, or solve it differently: Patch (made on 1a17fcf, applies cleanly to 601916f)diff --git a/pkg/storage/fs/posix/tree/assimilation.go b/pkg/storage/fs/posix/tree/assimilation.go
index d61670072..bcbc4fc47 100644
--- a/pkg/storage/fs/posix/tree/assimilation.go
+++ b/pkg/storage/fs/posix/tree/assimilation.go
@@ -498,7 +498,7 @@ func (t *Tree) assimilate(item scanItem) error {
return err
}
// another process can have assimilated the item. Reload the stale cache before the code below reads from it.
- t.reloadStaleCache(assimilationNode, mtime)
+ t.reloadStaleCache(assimilationNode, mtime, item.reloaded)
previousPath, err := t.lookup.GetCachedID(context.Background(), spaceID, id)
if previousPath == "" || err != nil {
@@ -916,6 +916,7 @@ assimilate:
// WarmupIDCache warms up the id cache
func (t *Tree) WarmupIDCache(root string, assimilate, onlyDirty bool) error {
root = filepath.Clean(root)
+ reloaded := newReloadedNodes()
spaceID := ""
scopeSpace := func(spaceCandidate string) error {
@@ -1065,7 +1066,7 @@ func (t *Tree) WarmupIDCache(root string, assimilate, onlyDirty bool) error {
if isCopy || (assimilate && (isMove || isChanged || t.metadataIsStale(path))) {
// a copy with a clashing id, a move or a change on disk -> re-assimilate.
// assimilate skips items whose path and mtime still match the metadata
- err := t.assimilate(scanItem{Path: path})
+ err := t.assimilate(scanItem{Path: path, reloaded: reloaded})
if err != nil && !errors.Is(err, _errSkipAlreadyKnown) {
t.log.Error().Err(err).Str("path", path).Msg("could not assimilate item")
}
@@ -1077,7 +1078,7 @@ func (t *Tree) WarmupIDCache(root string, assimilate, onlyDirty bool) error {
}
}
} else if assimilate {
- if err := t.assimilate(scanItem{Path: path}); err != nil {
+ if err := t.assimilate(scanItem{Path: path, reloaded: reloaded}); err != nil {
t.log.Error().Err(err).Str("path", path).Msg("could not assimilate item")
}
}
@@ -1143,7 +1144,9 @@ func (t *Tree) metadataIsStale(path string) bool {
// Another process, e.g. 'opencloud posixfs scan', can assimilate the item with its own cache.
// That process also changes the tree size and tree time of the parents.
// The caller must hold the lock of n.
-func (t *Tree) reloadStaleCache(n *assimilationNode, mtime time.Time) {
+// Within one walk, reloaded remembers the nodes reloaded already: the parents are shared by many
+// items, and a parent reloaded before had its own parents reloaded with it, so the walk up stops there.
+func (t *Tree) reloadStaleCache(n *assimilationNode, mtime time.Time, reloaded *reloadedNodes) {
backend := t.lookup.MetadataBackend()
if cached, ok := backend.GetCached(context.Background(), n, prefixes.MTimeAttr); ok {
if cachedMtime, err := time.Parse(time.RFC3339Nano, string(cached)); err == nil && cachedMtime.Equal(mtime) {
@@ -1154,6 +1157,9 @@ func (t *Tree) reloadStaleCache(n *assimilationNode, mtime time.Time) {
t.log.Debug().Str("path", n.path).Msg("metadata cache is missing or stale, reloading the item and its parents")
an := n
for {
+ if !reloaded.add(an.nodeId) && an != n {
+ return
+ }
if err := t.reloadCache(an); err != nil {
t.log.Warn().Err(err).Str("path", an.path).Msg("could not reload the metadata cache")
}
@@ -1217,3 +1223,27 @@ func (t *Tree) isDirty(path string) (bool, error) {
}
return string(dirtyAttr) == "true", nil
}
+
+// reloadedNodes is the set of nodes whose metadata cache a walk reloaded already.
+type reloadedNodes struct {
+ mu sync.Mutex
+ ids map[string]struct{}
+}
+
+func newReloadedNodes() *reloadedNodes {
+ return &reloadedNodes{ids: map[string]struct{}{}}
+}
+
+// add records id and reports whether it is new. A nil set (outside of a walk) never remembers anything.
+func (r *reloadedNodes) add(id string) bool {
+ if r == nil {
+ return true
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if _, ok := r.ids[id]; ok {
+ return false
+ }
+ r.ids[id] = struct{}{}
+ return true
+}
diff --git a/pkg/storage/fs/posix/tree/tree.go b/pkg/storage/fs/posix/tree/tree.go
index 072c96a9b..44bc2e3cd 100644
--- a/pkg/storage/fs/posix/tree/tree.go
+++ b/pkg/storage/fs/posix/tree/tree.go
@@ -92,6 +92,8 @@ type scanItem struct {
Path string
Recurse bool
RefreshParent bool
+ // reloaded remembers the nodes whose metadata cache a walk reloaded already. Nil outside of a walk.
+ reloaded *reloadedNodes
}
// Tree manages a hierarchical treeWhat remains is the reload of each changed item itself, which comes from treating a missing entry like a stale one. In a process with a cold cache, a missing entry is read from disk anyway, so in principle only a cached entry with a different mtime would need the reload. As far as I can tell, the reload also makes sure the entry is in the cache while the lock is held, so that a later read under the same lock doesn't hit a miss. So I'd leave that as it is for now. I'll also rerun the stress test on the rebased branch and report back. |
|
As promised, the stress test on the rebased branch: opencloud main built against reva main (3acb80d) and against this PR (601916f), single binary, posix with the default
No hang, no panic, no file left in processing, and no difference in latency. On the earlier upload code, the same test left goroutines stuck in About half of the requests got 425, or 500 for COPY (which reports the 425 of a file in processing as 500), on both builds alike: with this many overwrites, the files are almost always in postprocessing. One run each, so small differences are noise. How to run itBuild opencloud against the reva commit to test (e.g. a mkdir run-pr && cp opencloud run-pr/
cat > run-pr/env.sh <<'ENV'
export OC_CONFIG_DIR=$PWD/run-pr/config OC_BASE_DATA_PATH=$PWD/run-pr/data
export OC_URL=https://localhost:9200 OC_INSECURE=true OC_LOG_LEVEL=warn
export STORAGE_USERS_DRIVER=posix PROXY_ENABLE_BASIC_AUTH=true
ENV
(. run-pr/env.sh && IDM_ADMIN_PASSWORD=admin run-pr/opencloud init --insecure true)
DURATION=300 WORKERS=32 ./stress.sh pr plain # or watch; needs k6, and inotifywait for watchThe results, server log and goroutine dumps go to stress.sh#!/usr/bin/env bash
# Stress test for the posix metadata cache and node locks: concurrent
# WebDAV clients on a small set of paths, plus changes on disk and `posixfs scan` runs in a
# process of their own, against a single binary server with the posix driver and the default
# `memory` file metadata cache. Detects a hang (no completed request for HANG_AFTER seconds)
# and takes goroutine dumps (on a hang, and at the end of every run).
#
# The WebDAV clients run in k6 (stress-clients.js next to this script).
# Usage: stress.sh <variant> plain|watch (env: DURATION=300 WORKERS=32 HANG_AFTER=60)
# <variant> a folder run-<variant> next to this script, with the opencloud binary, its
# config from `opencloud init`, and an env.sh with the server settings
# plain watch_fs off: the scan writes metadata the server doesn't know about
# watch watch_fs on, plus a writer that changes files on disk
set -uo pipefail
S=$(cd "$(dirname "$0")" && pwd)
variant=$1 mode=$2
duration=${DURATION:-300} workers=${WORKERS:-32} hang_after=${HANG_AFTER:-60}
d=$S/run-$variant
out=$S/stress-$variant-$mode
. "$d/env.sh"
export STORAGE_USERS_DEBUG_PPROF=true
if [ "$mode" = watch ]; then
export STORAGE_USERS_POSIX_WATCH_FS=true STORAGE_USERS_POSIX_WATCH_TYPE=inotifywait STORAGE_USERS_POSIX_SCAN_DEBOUNCE_DELAY=1s
fi
dav=https://localhost:9200/remote.php/dav/files/admin
pprof=http://127.0.0.1:9159/debug/pprof/goroutine?debug=2
server= pids=()
cleanup() {
for p in "${pids[@]}"; do kill "$p" 2>/dev/null; done
wait "${pids[@]}" 2>/dev/null
pkill -f "k6 run .*stress-clients.js" 2>/dev/null
[ -n "$server" ] && { kill "$server" 2>/dev/null; sleep 2; kill -9 "$server" 2>/dev/null; wait "$server" 2>/dev/null; }
pkill -f "^inotifywait .*$OC_BASE_DATA_PATH" 2>/dev/null
}
trap cleanup EXIT
rm -rf "$out" "$OC_BASE_DATA_PATH"; mkdir -p "$out"
"$d/opencloud" server > "$out/server.log" 2>&1 &
server=$!
for _ in $(seq 1 120); do
[ "$(curl -sk -o /dev/null -w '%{http_code}' -u admin:admin -X PROPFIND "$dav/" || true)" = 207 ] && break
sleep 1
done
dirs=(s s/a s/a/b s/c)
for dir in "${dirs[@]}"; do curl -sk -u admin:admin -X MKCOL "$dav/$dir" -o /dev/null; done
for dir in s/a s/a/b s/c; do
for i in 0 1 2 3 4; do
printf 'initial %s %s\n' "$dir" "$i" > "$out/initial.txt"
curl -sk -u admin:admin -T "$out/initial.txt" "$dav/$dir/f$i.txt" -o /dev/null
done
done
space=$(ls -d "$OC_BASE_DATA_PATH"/storage/users/users/*/ | head -1); space=${space%/}
# the WebDAV clients: k6, one CSV line per metric sample (http_reqs = one per request)
BASE=$dav DURATION=${duration}s WORKERS=$workers OUT=$out/k6-summary.txt \
k6 run -q --out csv="$out/k6.csv" "$S/stress-clients.js" > "$out/k6.log" 2>&1 & pids+=($!)
reqs() { [ -f "$out/k6.csv" ] && awk -F, '$1=="http_reqs"{n++} END{print n+0}' "$out/k6.csv" || echo 0; }
# another process writing metadata: `posixfs scan` of the space, again and again
(
end=$((SECONDS + duration))
while [ $SECONDS -lt $end ]; do
start=$SECONDS
timeout 120 "$d/opencloud" posixfs scan "$space" > /dev/null 2>&1; rc=$?
echo "scan rc=$rc $((SECONDS - start))s" >> "$out/scan.log"
sleep 3
done
) & pids+=($!)
# with watch_fs: changes on disk, outside OpenCloud
if [ "$mode" = watch ]; then
(
end=$((SECONDS + duration))
while [ $SECONDS -lt $end ]; do
f=$space/${dirs[$((RANDOM % 3 + 1))]}/f$((RANDOM % 5)).txt
[ -f "$f" ] && head -c $((RANDOM % 4096 + 1)) /dev/urandom > "$f" 2>/dev/null
sleep 0.2
done
) & pids+=($!)
fi
# watchdog: completed requests every 10 s; a hang is no completed request for hang_after s
hang=no last=-1 still=0 end=$((SECONDS + duration))
while [ $SECONDS -lt $end ]; do
sleep 10
n=$(reqs)
echo "$SECONDS s: $n requests" >> "$out/progress.log"
if [ "$n" -eq "$last" ]; then still=$((still + 10)); else still=0; fi
last=$n
if [ $still -ge "$hang_after" ]; then
hang=yes
curl -s -m 30 "$pprof" > "$out/goroutines-hang.txt"
break
fi
done
curl -s -m 30 "$pprof" > "$out/goroutines-end.txt"
for p in "${pids[@]}"; do kill "$p" 2>/dev/null; done
wait "${pids[@]}" 2>/dev/null
# no load anymore: a goroutine still waiting on a file lock now is stuck
sleep 20
curl -s -m 30 "$pprof" > "$out/goroutines-idle.txt"
# summary
{
echo "### $variant $mode: ${duration}s, $workers clients, hang: $hang"
cat "$out/k6-summary.txt" 2>/dev/null
# status by operation; status 0 = timeout or failed connection
awk -F, 'NR==1{for(i=1;i<=NF;i++)h[$i]=i; next} $1=="http_reqs"{c[$h["method"]" "$h["status"]]++} END{for(k in c) printf " %s: %d\n", k, c[k]}' "$out/k6.csv" | sort
echo "scans: $(wc -l < "$out/scan.log" 2>/dev/null || echo 0), failed: $(grep -vc 'rc=0' "$out/scan.log" 2>/dev/null)"
for g in "$out"/goroutines-*.txt; do
[ -s "$g" ] || continue
echo "$(basename "$g"): $(grep -c '^goroutine ' "$g") goroutines, waiting on a file lock (flock/lockedfile): $(awk 'BEGIN{RS=""} /syscall\.Flock|lockedfile\.|filelock\./{n++} END{print n+0}' "$g")"
done
echo "panics/fatal in the server log: $(grep -ciE 'panic|fatal error|deadlock' "$out/server.log")"
} | tee "$out/summary.txt"stress-clients.js (k6)// WebDAV clients for stress.sh: random operations on a small set of shared paths.
// Env: BASE (WebDAV root of admin's files), DURATION (e.g. 300s), WORKERS (VUs), OUT (summary file)
import http from 'k6/http';
import encoding from 'k6/encoding';
import { randomBytes } from 'k6/crypto';
const base = __ENV.BASE;
const dirs = ['s/a', 's/a/b', 's/c'];
const auth = { Authorization: 'Basic ' + encoding.b64encode('admin:admin') };
export const options = {
vus: Number(__ENV.WORKERS || 32),
duration: __ENV.DURATION || '300s',
insecureSkipTLSVerify: true,
summaryTrendStats: ['med', 'p(95)', 'max'],
// a stuck request shows as a timeout (status 0)
thresholds: {},
};
const pick = (a) => a[Math.floor(Math.random() * a.length)];
const file = () => `${base}/${pick(dirs)}/f${Math.floor(Math.random() * 5)}.txt`;
export default function () {
const r = Math.floor(Math.random() * 10);
const p = { headers: Object.assign({}, auth), timeout: '60s', tags: {} };
let op;
if (r <= 2) {
op = 'PUT';
p.tags.op = op;
http.put(file(), randomBytes(Math.floor(Math.random() * 4096) + 1), p);
} else if (r === 3) {
op = 'GET';
p.tags.op = op;
http.get(file(), p);
} else if (r <= 5) {
op = 'PROPFIND';
p.tags.op = op;
p.headers.Depth = '1';
http.request('PROPFIND', `${base}/${pick(dirs)}/`, null, p);
} else if (r === 6 || r === 7) {
op = r === 6 ? 'MOVE' : 'COPY';
p.tags.op = op;
p.headers.Destination = file();
p.headers.Overwrite = 'T';
http.request(op, file(), null, p);
} else if (r === 8) {
op = 'DELETE';
p.tags.op = op;
http.del(file(), null, p);
} else {
op = 'MKCOL';
p.tags.op = op;
http.request('MKCOL', `${base}/${pick(dirs)}/d${Math.floor(Math.random() * 3)}`, null, p);
}
}
export function handleSummary(data) {
const m = data.metrics;
const d = m.http_req_duration.values;
const lines = [
`requests: ${m.http_reqs.values.count}, failed (status >= 400 or none): ${m.http_req_failed.values.passes}`,
`duration: med ${d.med.toFixed(0)} ms, p95 ${d['p(95)'].toFixed(0)} ms, max ${(d.max / 1000).toFixed(1)} s`,
];
return { [__ENV.OUT]: lines.join('\n') + '\n', stdout: lines.join('\n') + '\n' };
} |
|
The CI run fails in the lint step, on the new branch in With three branches now, gocritic wants a Patch on top of 601916fdiff --git a/pkg/storage/pkg/decomposedfs/prepare_upload.go b/pkg/storage/pkg/decomposedfs/prepare_upload.go
index 8f2bd137a..6afa19fbd 100644
--- a/pkg/storage/pkg/decomposedfs/prepare_upload.go
+++ b/pkg/storage/pkg/decomposedfs/prepare_upload.go
@@ -145,7 +145,8 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
unlock metadata.UnlockFunc
old *node.Node
)
- if create {
+ switch {
+ case create:
// Before the node exists: an upload interrupted while its blob is written
// must not leave a node without metadata behind, which blocks the name.
if inline {
@@ -160,7 +161,7 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
return nil, err
}
purge = true
- } else if info.NodeExisted {
+ case info.NodeExisted:
// read under the lock we take: an unlocked read of a cold cache entry waits for that lock
var unlockOld metadata.UnlockFunc
old, unlockOld, err = node.LockAndReadNode(ctx, fs.lu, n.SpaceID, n.ID, "", false, n.SpaceRoot, false)
@@ -172,7 +173,7 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
n.SetLockHeld(false)
return unlockOld()
}
- } else {
+ default:
unlock, err = fs.lu.MetadataBackend().Lock(n)
if err != nil {
return nil, err |
|
Thanks Pascal. I pushed two commits:
The description now has |
…a cache Callers of LockAndReadNode read, change and write the metadata of the node. With the 'memory' cache another process, e.g. 'opencloud posixfs scan', can have changed the metadata on disk. The propagator then started from the cached tree size and overwrote the one on disk. Add InvalidateCache to the metadata backends and drop the cache entry of the node after it is locked. Part of opencloud-eu/opencloud#3804
…imilated When 'opencloud posixfs scan' assimilates a changed file, it writes the new mtime to disk first. The fs watcher of the server then skips the item as already known and keeps the old size, checksums and etag in its cache. On that skip, compare the cached mtime with the one on disk. If they differ, drop the cache entries of the item and of its parents up to the space root. Part of opencloud-eu/opencloud#3804
The scan can assimilate a change and the file can change again before the server gets the event. The mtimes then differ, so the server takes the update path. It used the previous blob size from the stale cache and counted the change of the scan twice in the tree size of the parents. Drop the stale cache of every known item before the skip check. Also read the old tree size from disk in propagateSizeDiff, give InvalidateCache a context and log its errors at warn level. Part of opencloud-eu/opencloud#3804
Preserve shared cache entries and refresh cached ancestors when a child entry is missing. Read scan size deltas from disk without evicting metadata. Use a lock-aware read for existing upload nodes to avoid self-deadlock on cache misses. Add regression coverage and an opt-in mixed stress test.
gocritic (ifElseChain) fails the lint step on the three-branch if-else.
A scan starts with an empty cache, so every item reloaded all its parents up to the space root. Remember the reloaded nodes for the walk and stop walking up at the first parent that was reloaded already. Co-authored-by: Pascal Bleser <[email protected]>
d406fab to
af3eae7
Compare
|
@pbleser-oc, I rebased on main again because #1019 moved the module path to |
Not up to standards ⛔🔴 Issues
|
| Category | Results |
|---|---|
| Security | 2 critical |
🟢 Metrics 121 complexity · 10 duplication
Metric Results Complexity 121 Duplication 10
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
Part of opencloud-eu/opencloud#3804 (proposed fixes 3 and 4). Fixes #1006.
With the default
memorymetadata cache,opencloud posixfs scanchanges metadata on disk that the running server does not see.LockAndReadNodenow drops the cache entry after it locks the node, andpropagateSizeDiffreads the old tree size from disk.watch_fs, the server skipped a file the scan had assimilated and kept its old size, checksums and etag. The tree now compares the cached mtime of each known item with the one on disk. If they differ, or the entry is missing, it reloads the cache of the item and of its parents. In one scan walk each parent reloads only once (Pascal's patch).PrepareUploadnow reads an existing node under the lock it takes. Before, the read of a cold cache entry waited for that same lock.InvalidateCachedoes nothing fornats-js-kvandredis, because shared stores do not go stale. Pascal measured a full rescan after touching 50,000 files at 214 s, against 188 s on main.Tests:
TestUploadWithColdMetadataCachefor #1006, and "propagates from the tree size on disk" plus the specs under "changed by another process" for the scan. Each fails without its fix.Not fixed: without
watch_fsthe server serves cached reads until the TTL (24h) runs out or it restarts.