Compare commits

...
Author SHA1 Message Date
Chris Lu 23ef0a816a mount: size the listing cache through NewMetaCache rather than a second constructor
A NewXWithY alongside NewX is two names for one thing, and the one that
takes the argument is the only one that ever needed to exist. Callers
pass the default explicitly.
2026-08-07 14:14:58 -07:00
Chris Lu 819a39c1f6 mount: raise the listing cache default to a million children
A ceiling rather than a reservation: nothing is held for a directory
never walked, so this only materialises for a mount that really does walk
that many cached children, and one that does wants the speedup. A
chunkless child measured about 480 bytes, so the doc and the flag help
both say what reaching the ceiling costs -- near 450MB -- since that is
the number an operator needs to lower it against.
2026-08-07 14:10:39 -07:00
Chris Lu 55d6f46009 mount: size the directory listing cache with -dirListCacheEntries
Defaults to 200k children, a few tens of megabytes, which covers one very
wide directory. Zero disables it. Least recently used directories are
dropped to stay inside the budget.

A subscription gap means the mount cannot know what it missed, so the
resubscribe path drops every cached listing along with the cached-ness
flags it already resets.
2026-08-07 13:38:47 -07:00
Chris Lu cec7019881 mount: keep a directory listing that has been walked all the way through
Every enumeration re-read the whole directory out of the local store and
decoded it again, so reopening a folder cost exactly what opening it did.
That is most of what a readdir spends: about 90% of the bytes and half
the allocations of a 200k walk.

A walk that covers a directory from its first child to its last now
leaves the decoded entries behind, and the next walk pages through them
in memory. Nothing is cached from a walk that stopped early or started
partway in, so a client reading one page of a huge directory does not pay
for the rest of it.

What makes this safe is that it is not a timer. The cache holds only what
the meta cache holds, so it is void whenever that is: every write goes
through one of four wrappers, each dropping the directory it touched
under the same lock that made the write, and a rebuild drops it at begin
and complete. A walk publishes only if its build is still the live one
for that directory, so a write landing halfway through cannot leave a
stale listing behind.

Expiry is the one thing that changes with no write at all, so it is
applied when serving rather than invalidated for -- a listing must not go
stale just because a child aged out while it sat there.

Only a listing that leaves out chunk lists is cached or served, since
those are the entries the readdir path decodes; an entry from the cache
can never reach a caller that wanted chunks.
2026-08-07 13:38:47 -07:00
Chris Lu 5532a316c5 telemetry: put the version pie back beside the stacked chart (#10626)
* telemetry: put the version pie back, beside the stacked chart

The two answer different questions and the pie was the better answer to one
of them: what the fleet is on right now, at a glance. Restore it under its
old name and give the stack its own card as Versions Over Time, so the pie
is the last day of the chart below it.

* telemetry: draw the distribution pies at the size of their cards

Both pies kept the canvas tag's 2:1 ratio at the card's full width, so they
came out around 560px tall and spilled past the card they sit in. Give them a
height to fill instead, and build every chart after the dashboard is shown: a
canvas in a display:none container measures zero, and a pie sized from that
never grows back.
2026-08-07 12:48:28 -07:00
Chris Lu 553bc5ab90 topology: digest the volumes a master believes each node holds (#10619)
* topology: digest the volumes a master believes each node holds

A volume server resends its whole volume list every heartbeat because that list
is the only way the master can notice a volume that vanished without a delta.
A digest gives the master the same guarantee without the list: the two ends
agree iff the master's copy is current.

VolumeInfo.ReportHash covers every field of VolumeInformationMessage, so a
change the hash misses is a change the master would never hear about. Both ends
run it over the same converted VolumeInfo, so they cannot drift apart.

Disk keeps the xor of its volumes' hashes, which is order-independent and its
own inverse, so add, update and remove each stay O(1) and the running value
needs no per-volume storage.

Nothing reads the digest yet; the heartbeat protocol change comes next.

* topology: test that a changed-volumes-only heartbeat reconciles

The digest is not a change detector -- in a live cluster some volumes always
have changed. It answers whether the master holds what the volume server holds
once the heartbeat's own changes are applied, so reporting three volumes out of
fifty has to reconcile while a volume lost without a delta must not.

* topology: digest the lookup index too, not just the disk maps

The reported digest answers whether the master holds what the volume server
holds. It cannot answer whether the master can serve those volumes: the disk
map and the lookup index are maintained separately, and a disconnect racing a
reconnect drops a volume from the index while leaving it on the node. The
server's report is identical either way, so a digest built from the disk maps
alone matches while the volume answers 'volume id not found'.

Track a second digest over volume ids on both sides of that split, so the
master can see its own indexes disagree without the volume server's help, and
without the O(volumes) scan the full heartbeat currently relies on.

* topology: exclude nodes reporting a duplicate volume id from the digest

A volume id can end up mounted on two disks of one server -- a stale twin
re-attached after a disk repair, which the store handles rather than rejects.
The server reports both copies with different disk ids, but the master keys
volumes by id alone within a disk type and keeps only the last one. Its digest
can then never equal the server's, and no amount of resending the full list
would fix it.

Detect it from the report itself, where deduplicating the ids already tells us
the count, and mark the node. A marked node has to keep sending full lists;
representing both copies is a separate question, and nesting the volume map by
disk id would cost more memory than the digest saves.

* topology: move the lookup digest with the entry, not the node passed in

Two volume servers can hold one address: GetOrCreateDataNode keys on the id a
server reports and refuses to merge a new id onto an address an older node
still claims, while the lookup list keys on address alone. Registering the
second server therefore displaces the first from the entry, and unregistering
through either removes whichever node the entry named.

Crediting the node handed to Set and Remove instead of the one actually
displaced or removed left the digest on the wrong node. A displaced node went
on reporting a consistent index while it could no longer serve the volume,
which is exactly the silent unavailability the digest exists to catch.

Set and Remove now return the node they displaced and removed, so ownership
can be transferred rather than assumed.
2026-08-07 12:42:16 -07:00
Chris Lu 12627d376d mount: fix four readdir pagination bugs (#10624)
* mount: size the direct listing slice from the batch, not the offset

The limit passed here is skipCount+batchSize when a client resumes a
fresh handle partway through a directory, so preallocating for it turns
the client's cookie into an allocation: a readdir at offset 3,000,000
reserves 24MB before the first entry arrives, and an offset near the
uint32 ceiling asks makeslice for ~4.29e9 elements.

* mount: stop replaying a directory that shrank past the resume offset

A client that opens a fresh handle and resumes at a cookie from an
earlier, larger listing gets a preload that cannot reach the entry before
that offset. The resume name was then left empty and the follow-up batch
listed from the directory's first child again, so the client was handed
every name a second time.

The stream always runs from the first child, so failing to reach that
entry means the directory is simply shorter than the offset. That is the
end of it.

* mount: page a directory from where the store reached

The batch loader treated a short batch as the end of the directory, but
the meta cache drops an expired child after the store has already spent
it against the limit, so a batch that filled up could still deliver fewer
entries than asked for. A directory with a handful of expired children
would stop listing early and hide every child behind them; a whole batch
of expired ones truncated the listing to nothing.

ListDirectoryEntries now reports the name the store itself reached. That
is both the sound end-of-directory signal -- the store returning nothing
-- and the right cursor, since resuming from the last visible name would
re-read the dropped children every round and never get past a batch that
was entirely expired.

* mount: drop the entries a directory walk has already passed

entryStreamOffset was only ever written by reset, so the stream a handle
holds grew for the life of the walk and a directory was retained whole
even though nothing could read the entries behind the client's position
again. A 10M-entry walk parked millions of entries per handle, and
NFS-Ganesha opens several on the same directory.

Offsets index into the stream from entryStreamOffset, so advancing the
two together keeps them lined up. One entry is held back because the next
batch resumes from the name immediately before the offset. Seeking back
behind what is still held now restarts the directory, which is what the
offset scheme can honestly support -- it previously returned nothing.
2026-08-07 12:11:27 -07:00
Chris Lu a49cf11e16 telemetry: version distribution over time (#10625)
* telemetry: keep the reported version in the daily history

The version only ever lived on the instance record, which holds a cluster's
latest report, so there was no way to ask what anything ran last Tuesday.
Record it per sample, and let the daily axis carry strings as well as counts.

State written before this has no version on its samples. The newest sample is
the report the instance record itself came from, so fill that one in on load
rather than starting a version series a day late.

* telemetry: serve the fleet's version make-up over time

/api/versions gives how many clusters ran each release per day, on the same
axis and hold-forward rule as the cluster sizes. Releases are ordered by
number rather than by size: the caller stacks them, and a stack whose order
changes with the counts is unreadable over time. The tail past the limit is
summed into "other" so the stack still adds up.

Days with no version are dropped before the axis is built, so the series
spans the days it knows a version for instead of climbing out of blanks.

* telemetry: draw version distribution as a stacked growth chart

The pie only ever showed today. Stacked over 30 days the height is the
confirmed fleet and each band is a release, so one chart carries the growth
and the rollouts at once. Newest release on the floor, so the band being read
is anchored to the axis instead of riding on everything below it.

Eight fixed hues instead of the evenly spaced ones the cluster stacks use:
evenly spaced put a green and a cyan close enough to be hard to tell apart,
which matters for a set you read rather than a wall of anonymous ids.
Versions past the eighth fold into "other", and each band carries its own
number so the chart reads without matching colours against the legend.
2026-08-07 12:08:04 -07:00
Chris Lu b46946ece5 filer: list directories without decoding chunk lists (#10616)
* filer: decode a listed entry without building its chunk list

A readdir reads attributes and never looks at chunks, but decoding an
entry builds the whole chunk list first: four allocations per chunk, all
of it thrown away. On a directory of ordinary 4MB-chunked files that is
most of what listing costs.

DecodeAttributesOnly walks the wire format and hands everything except
the chunks to the generated unmarshaller, so new fields in filer.proto
need no attention here. The chunks are still measured, because the S3
copy and multipart paths deliberately store a zero FileSize and let the
chunk extents define the size, but nothing is allocated to do it.

The blob is only re-encoded once a chunk is actually seen, so an entry
without any -- every directory, for one -- is unmarshalled where it lies
and pays nothing for the walk.

Listings opt in through the context, the way the lazy remote paths
already do; a store that ignores it stays correct.

    chunks   full      attrs-only              allocs
    0        312.8n    310.1n    ~              1 ->  1
    1        686.1n    411.1n    -40.07%        7 ->  1
    4        1.742u    667.4n    -61.69%       24 ->  1
    16       5.770u    1.544u    -73.25%       86 ->  1
    64       25.23u    6.004u    -76.20%      328 ->  1

* mount: list directories with chunk lists omitted

The two meta cache listings behind a readdir are the only callers, and
neither reads a chunk. On 200k single-chunk files one enumeration goes
from 364ms to 277ms and drops a million allocations.

The read-through listing still fetches whole entries from the filer,
which would need the request to say it wants attributes only.

* mount: give the readdir benchmark's entries a chunk

Chunkless entries made the decode look far cheaper than it is, which is
the part of a listing worth measuring.

* filer: let a listing ask for entries without their chunk lists

The read-through readdir fetches whole entries over gRPC, and for a wide
directory the chunk lists are most of what crosses the wire and most of
what the client then unmarshals. A 4MB-chunked file is 113 bytes of
entry against 46 without its chunk.

ListEntriesRequest gains omit_chunks. The size a client needs is already
in the attributes, where the store decode folded the chunk extents in,
so dropping the list costs the client nothing.

The filer still reads the entries whole. A listing is where a TTL-expired
entry gets collected and deleted, and deleting one needs its chunks to
find the data, so omitting them there would leak. Only the response is
trimmed.

The hint moves to filer_pb so one context flag serves both transports:
the gRPC request sets omit_chunks, and a listing served from the local
store skips building the chunks. Cache population is unaffected either
way, since EnsureVisited starts from its own context.

* filer: reject a chunk the full decoder would reject

The walk skipped a chunk's bytes without looking inside them, so a
FileChunk carrying a corrupt nested fid, or a string that is not valid
UTF-8, sailed past the listing decoder while every other read of the same
entry still failed. The file listed with a plausible size and then gave
EIO on open, and corruption that used to fail the listing loudly was
hidden instead.

The chunk bytes are the one part of the blob the generated unmarshaller
never sees, so the two checks it would have made are made here: a
submessage has to parse, and a proto3 string has to be valid UTF-8.
FileChunk's only submessages are FileIds of scalars, so walking them is a
complete check. A descriptor-driven test fails if FileChunk ever gains a
field of either kind that the walk does not know to check, which is the
part that keeps this honest as filer.proto grows.

Taking the scratch buffer lazily, only once a chunk is actually dropped,
also takes the pool out of the path for entries that have none. Those
were measurably slower than the full decoder before; they are now level
with it. Each chunk's length prefix is parsed once rather than twice.

    chunks   full       attrs-only   vs base
    0        171.4n     176.9n       ~ (p=0.670)
    1        366.6n     259.4n       -29.24%
    4        1.034u     500.2n       -51.60%
    16       3.905u     1.464u       -62.52%
    64       13.48u     5.195u       -61.46%

* filer: carry the size before dropping chunks over the wire

Dropping the chunk list assumed every store folds the chunk extents into
FileSize when it decodes. A store that keeps entries as JSON rather than
as an encoded Entry never re-derives it, so an object written with a zero
FileSize kept its real size only in the chunks, and stripping them left
the client reading the file as empty. Stamp the size into the attributes
first, which costs nothing and does not depend on how the store loaded
the entry.

* mount: test that the readdir context reaches the store decode

Everything else exercises the decoder directly, so a refactor that
stopped threading the context would have reverted the whole thing with
every test still passing.

The benchmark's chunks also carried a constant legacy FileId, which
BeforeEntrySerialization reparses over Fid on the way in, so all 200k
entries stored one byte-identical chunk rather than the varying fixture
it looked like.
2026-08-07 12:03:18 -07:00
Chris Lu af7cf6ab8a chore(weed/topology): drop the unused DataNode volume id listing (#10618)
GetVolumeIds ranged over a slice and collected the loop indices, so it reported
0-99 rather than the node's volume ids. Nothing calls it: the disk-level
GetVolumeIds, which ranges over a map and is correct, is what ToDiskInfo and
ToMap use. Its private getVolumes helper went with it, having no other caller.
2026-08-07 01:27:40 -07:00
Chris Lu cce3bab0e2 perf(weed/topology): gather a node's volumes into one slice (#10617)
* perf(weed/topology): preallocate the node's volume concatenation

A node's volumes are gathered per disk and concatenated into a slice grown from
nil, so a server with several disks reallocates and copies its way up. The
writable-volume refresh loop does this for every node every few seconds.

BenchmarkDataNodeGetVolumes/8Disks  322551844 B/op -> 121602326 B/op

* perf(weed/topology): fill one slice across a node's disks

Each disk built its own right-sized copy of its volumes, and the node then
copied all of them again into the combined slice. Appending into the caller's
slice makes it one allocation whatever the disk count, which halves even the
single-disk case.

BenchmarkDataNodeGetVolumes
  1Disks  121602326 B/op 2 allocs/op -> 60801314 B/op 1 allocs/op
  8Disks  121602326 B/op 9 allocs/op -> 60801024 B/op 1 allocs/op
2026-08-07 01:26:54 -07:00
Chris Lu 228e850da1 perf(weed/topology): preallocate the client-facing topology snapshots (#10615)
* perf(weed/topology): preallocate the /dir/status volume list

ToVolumeMap boxes every volume on a node into an []interface{} grown from nil,
so the slice reallocates its way up alongside the boxing. The count is known.

* perf(weed/topology): preallocate the volume id list sent to clients

Every filer, s3 gateway, and mount that connects to the master gets one
VolumeLocation per data node carrying that node's whole volume id list, grown
from nil. The count is known.

The ec ids are left alone: shards of one volume can span disks, so the shard
count is an upper bound on the deduped vid count, not the count itself.
2026-08-07 01:14:34 -07:00
Chris Lu 9f1e21e73f perf(weed/topology): preallocate the per-disk VolumeList payload (#10614)
ToDiskInfo builds a protobuf message per volume and per ec shard on the disk,
growing both lists from nil. Every VolumeList call runs it for every disk in
the cluster, and the admin dashboard, the plugin worker, several shell commands
and the s3 gateway's per-minute bucket metrics all call VolumeList. Both counts
are already in hand.

ToTopologyInfo over 550k volumes  202.2 MB -> 184.6 MB
2026-08-07 01:10:57 -07:00
Chris Lu 0cfca436f1 perf(weed/topology): size the new-volume list from the actual delta (#10613)
A reconnecting volume server reports every volume it has as new, so newVolumes
grew from nil to one entry per volume, reallocating and copying its way there.
Sizing it to len(actualVolumes) instead would allocate the whole list on every
steady-state heartbeat, where nothing is new.

After the deletion pass everything left on the node is also in this heartbeat,
so the difference is exactly what the node is about to gain: all of them on a
reconnect, none in steady state.

First registration of 550k volumes  1041.7 MB -> 667.4 MB
2026-08-07 01:10:11 -07:00
Chris Lu 8aa57bef78 mount: stop churning the inode table on every readdir (#10606)
* mount: readdir enters a child in the inode table only when it takes a reference

Only readdirplus into the kernel takes a reference on the children it
reports, and only that reference brings a FORGET later to take the entry
back out. Every other listing was inserting all its children anyway.

On WinFsp that meant a listing looked each child up, took a reference,
and immediately gave it back, so a walk of a wide directory paid three
write-lock acquisitions per entry to leave the table exactly as it found
it. On a plain kernel readdir nothing gives the entry back at all, so
listing a directory of 200k files grew both maps by 200k entries that
were never reclaimed.

A dirent's inode number is informational either way: the kernel must
LOOKUP before it can use a nodeid, and the WinFsp adapter re-resolves
every operation by path. So report the number and let the mapping be
built when something actually looks the entry up.

* mount: take the readdirplus reference without a second full lookup

The entry has just been resolved a few lines above, so redoing the whole
lookup only rebuilds the child path and walks both maps again to reach a
counter. Bump it directly, falling back to the full lookup if a Forget
removed the entry in between.

* mount: benchmark a readdir over a 200k directory

Drives doReadDirectory against a meta cache holding 200k entries, one
round of 4096 at a time, for the three front ends that behave
differently: a plain kernel readdir, kernel readdirplus, and a WinFsp
listing that gets attributes but never returns a reference. Reports what
each leaves behind in the inode table alongside the usual metrics.

The sink declares TakesLookupRef as an ordinary method rather than
through the interface, so the same file runs unchanged against an older
tree for comparison.

* mount: stamp an inode on the benchmark's entries

The filer stores one on every entry it writes, so a real listing arrives
with an inode and never derives its own. Leaving it zero made every child
in the benchmark fall through to the MD5 in AsInode, work no filer-backed
mount does, and charged it to both sides of the comparison.
2026-08-07 01:03:19 -07:00
Chris Lu ee54fd6c08 perf(weed/storage/super_block): intern the byte-encoded replica placements (#10610)
NewReplicaPlacementFromByte formatted the byte with fmt.Sprintf and parsed the
result back, allocating a string and a ReplicaPlacement every call. The master
calls it once per volume in every heartbeat, and keeps the pointer for the
lifetime of the volume, so a cluster with 1.6M volume replicas carries 1.6M of
these where a handful of distinct values exist.

The table is a flat pointer-free array, so it costs 6KB of static data and no
heap objects however few placements a cluster actually uses.

A byte only ever decodes to a valid placement, so the table is complete and the
error return stays nil.

BenchmarkSyncDataNodeRegistration/100000Volumes  500601 allocs/op -> 300589 allocs/op
2026-08-07 00:53:02 -07:00
Chris Lu 33c36fc7a3 perf(weed/storage/needle): intern the stored ttl values (#10611)
The master decodes a TTL per volume in every heartbeat and keeps it for the
volume's lifetime, so a cluster using TTLs carries one two-byte object per
volume replica where at most 256 counts times 7 units exist. Share them, and
decode the uint32 form directly instead of staging it through a byte slice.

Clusters that set no TTL are unaffected; that path already returned the shared
EMPTY_TTL.

BenchmarkSyncDataNodeRegistration/100000Volumes, volumes carrying a ttl
  600600 allocs/op -> 500597 allocs/op
2026-08-07 00:51:52 -07:00
Chris Luandcoderabbitai[bot] 4f0322af86 perf(weed/topology): log writable-state changes, not every check (#10612)
* perf(weed/topology): log writable-state changes, not every check

ensureCorrectWritables ran its three diagnostics whenever it was asked, so a
volume that had always been read-only re-announced that on every registration.
A volume server reconnecting with 550k read-only volumes made the master format
over a million log lines before it could serve anything, which is exactly when
it is already at its memory peak rebuilding the topology.

removeFromWritable already reports the transition, and only when there is one.
Explain it only then. Dropped the separate 'remove from writable' line, which
said nothing that 'becomes unwritable' does not.

BenchmarkRegisterReadOnlyVolumes, 100k volumes
  285791480 B/op 1902069 allocs/op -> 234592088 B/op 1302572 allocs/op

* Update weed/topology/volume_layout.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-08-07 00:44:30 -07:00
Chris Lu 1d8d9570eb perf(weed/topology): preallocate the disk volume snapshot (#10609)
Disk.GetVolumes copies the disk's whole volume map into a fresh slice, and every
caller that walks a node's volumes goes through it: the writable-volume refresh
loop every few seconds, ToTopologyInfo on each VolumeList, telemetry, and node
unregistration. Growing from nil reallocates and copies about twice the final
size each time, which at 100k volumes per disk is 60MB of garbage per call.

BenchmarkSyncDataNodeRegistration/100000Volumes  199670102 B/op -> 137728051 B/op
2026-08-07 00:30:28 -07:00
Chris Lu 2ec899bdee perf(weed/topology): diff a heartbeat without copying the volume map (#10608)
* perf(weed/topology): keep only volume ids in the heartbeat membership set

The map is used solely to test whether a known volume is still present, but it
copied the whole 152-byte VolumeInfo for every volume in the heartbeat. Presize
it too, since the count is known.

BenchmarkSyncDataNodeRegistration/100000Volumes  199670102 B/op -> 180157310 B/op

* perf(weed/topology): diff a heartbeat without copying the volume map

To find volumes the data node no longer reports, UpdateVolumes copied every
VolumeInfo on the node into a fresh slice, then deleted the missing ones one at
a time. At 100k volumes that is a 15MB copy per heartbeat to usually find
nothing. Scan the disk maps in place instead and return only what was removed.

BenchmarkSyncDataNodeRegistration/100000Volumes  180157310 B/op -> 87806436 B/op
2026-08-07 00:28:32 -07:00
Chris Lu 3fce1a938d perf(weed/topology): preallocate the heartbeat volume conversion slice (#10607)
* test(weed/topology): benchmark the per-heartbeat volume sync

A volume server re-sends its entire volume list every VolumePulsePeriod, so
SyncDataNodeRegistration is the master's steady-state per-server cost. Give it
a benchmark so allocation regressions show up.

* perf(weed/topology): preallocate the heartbeat volume conversion slice

The slice grows to one entry per volume on the data node, so at 100k volumes
the doubling copies allocate 60MB of garbage per heartbeat. The final length is
known up front.

BenchmarkSyncDataNodeRegistration/100000Volumes  199670102 B/op -> 137725872 B/op
2026-08-07 00:21:16 -07:00
Lars Lehtonen 2ff3dda7cd chore(weed/s3api/policy_engine): prune dead code (#10599) 2026-08-06 16:07:59 -07:00
Chris Lu fb92d46e2d helm: enterprise license Secret, and a persistent-claim option for master data (#10601)
* helm: mount an enterprise license Secret into every component

Running the enterprise image under this chart meant hand-rolling
extraVolumes and extraVolumeMounts on every component. Missing one is
easy and quiet: a component without the license silently drops to
community mode, and on the admin that surfaces only as Data Recovery and
Point-in-Time Recovery refusing to enable, with the master looking fine.

Add global.seaweedfs.license.existingSecret. The Secret is mounted
read-only into master, volume, filer, s3, sftp, admin, worker and
all-in-one, and SEAWEED_LICENSE points every process at the file rather
than relying on the binary's search paths, which depend on the working
directory.

The mount is a directory, never a subPath: kubelet refreshes Secret
contents in place, but a subPath is resolved once at container start and
never updates, which would break license renewal. There is deliberately
no checksum annotation on the pod template either — that would roll every
pod on renewal, the opposite of what is wanted. Verified on kind: the
renewed file reached a running master ~70s after the Secret was patched,
same pod UID, restartCount 0.

Also documents that only the master re-reads the license on a timer
today; the other components pick a renewal up on their next restart.

* helm: keep master data on a claim by default

The master's -mdir holds its Raft log and snapshots, and with them the
cluster's topology UUID — the identity an enterprise license is issued
against. It defaulted to a hostPath under /ssd, which does not follow a
rescheduled pod: the master came back with an empty data directory, a
freshly generated cluster UUID, and a license that no longer matched.
With the chart's default of a single master replica there is no peer to
recover the identity from either.

Default master.data.type to persistentVolumeClaim, sized 1Gi (Raft state
is small). hostPath stays available for anyone who wants it.

This is breaking for existing releases: volumeClaimTemplates is immutable,
so helm upgrade on a release installed with the old default fails with
"updates to statefulset spec for fields other than ... are forbidden".
Verified on kind, along with both ways out — pinning
master.data.type=hostPath upgrades cleanly, and the documented migration
(stop the master, pre-seed a claim named after the StatefulSet, upgrade)
preserves the cluster UUID. Seeding has to happen while the master is
stopped; copying into a live pod loses the state, since the running
master rewrites its Raft files before the restart.

* helm: mount the license on masters only

The master is what reads the license file: it validates it, enforces the
capacity limit and binds it to the cluster UUID. Mounting the Secret on
volume, filer, s3, sftp, admin and worker put it in six more containers
that never look at it, so drop it there and keep master plus all-in-one,
which runs `weed server -master`.

Two fixes from review while here:

  - project only the configured key out of the Secret, so an unrelated
    key in the same Secret is not exposed to the container. Verified the
    key-scoped projection still updates in place: patching the Secret
    reached the running master in ~50s, same pod UID, restartCount 0.
  - drop SEAWEED_LICENSE from merged extraEnvironmentVars while a
    license Secret is configured. It used to be possible to render the
    key twice in one container, with the user's value winning over the
    path the chart actually mounts.

CI now pins the scope (master only, all-in-one separately), the
key-scoped projection, readOnly, and that SEAWEED_LICENSE renders once.

* helm: fix the documented master-data migration

The seed pod in the migration never mounted the claim it was supposed to
seed, so following the steps verbatim copied the Raft state onto the
pod's ephemeral filesystem and threw it away with the pod — landing the
reader in exactly the empty-claim, new-cluster-UUID state the section
exists to avoid. Give the pod the volume.

The names were assembled as <release>-seaweedfs-*, which is wrong
whenever the release name already contains the chart name or an override
is set; read the StatefulSet name from the cluster instead and derive the
claim from it. Also scope the procedure to the chart's single-master
default, and create the Secret in the release namespace.

Trims the enterprise prose this section had accumulated: this is the OSS
chart, and the master-data default is a durability fix that stands on its
own.

* helm: quote the projected license key, reserve it on the secret env path

A secretKey that YAML reads as a non-string (123, yes, no) rendered
unquoted into the volume's items, so the projection would not match the
Secret's key. Quote both key and path.

all-in-one renders secretExtraEnvironmentVars itself, outside the merge
helper that already drops SEAWEED_LICENSE, so an entry there could still
render the variable twice. Skip it there too while a license Secret is
configured. The master template has no such block, so this is the only
remaining path.

* helm: correct the license helper comments after scoping to masters

* helm: keep hostPath as the master data default

Defaulting master.data.type to a claim broke every existing release:
volumeClaimTemplates is immutable on a StatefulSet, so helm upgrade
failed with "updates to statefulset spec for fields other than ... are
forbidden" before it changed anything.

Keep hostPath as the default and document the claim as the option to
choose — for a new install, or for an existing one via the migration
already in the README. The chart supported both types all along; only
the default moves back.

Every immutable field of every rendered StatefulSet is now identical to
upstream under default values, so an in-place upgrade cannot trip the
API. Verified on kind: install with the unmodified upstream chart,
upgrade to this branch (ok), upgrade again turning the license Secret on
(ok, volume added in place). A fresh install with
master.data.type=persistentVolumeClaim binds its claim as before.

The whole PR is additive now: nothing renders differently until a value
is set.

* helm: scope the migration's StatefulSet lookup to the release

* helm: trim the comments added by this change
2026-08-06 15:53:49 -07:00
Chris Lu a8c8372b99 rust: stop quarantining v2 volumes, load a disk's volumes concurrently (#10602)
* rust: only compare the .dat tail on v3 volumes

Go's verifyNeedleIntegrity does the "does .dat end exactly at the last
indexed needle" comparison inside its v3 branch -- it rides along with
the v3 append-timestamp read -- so a v1/v2 volume carrying an unindexed
trailing record loads read-write and silent. The Rust check ran it at
every version, so booting the Rust server on a legacy cluster warned on
and quarantined volumes the Go server had been serving happily.

* rust: load a disk's volumes concurrently

Opening a volume is dominated by reading its .idx into the needle map,
and the loader did them one at a time, so a disk holding thousands of
volumes needed thousands of serial index reads before the server came
up. Go's concurrentLoadingVolumes spreads the same work over
max(cores, 10) workers; do the same, keeping the directory pre-pass and
the insert serial so only the open is parallel.

* rust: let a failed volume open fall back to the next candidate

Two collections can name the same volume id on one disk. Deduping the
load queue by id claimed the id for whichever candidate the scan saw
first, so a corrupt one shadowed a good one behind it; the serial loader
this replaced only claimed an id once a volume had actually opened.
Carry every claiming collection per id and try them in scan order until
one loads.

* rust: trim the new comments in the volume loader
2026-08-06 15:35:24 -07:00
Chris Lu 0cf62a921a admin: dashboard counts chunks, not files (#10598)
* admin: count each chunk once in the dashboard total

The dashboard summed file_count from every node's volume list, so a chunk
was counted once per replica and deleted chunks were never subtracted.
Reuse the collection aggregation, which dedupes replicas and EC shard
holders and nets out tombstones.

* admin: the dashboard card counts chunks, so name it that

Volumes store chunks, and a file is split into one or more of them, so
the 'Total Files' card always read far higher than the number of files in
the filer. Rename it to 'Total Chunks' and say so in the tooltip.

* admin: collections pages count chunks once and say so

The collections list and detail pages summed file_count straight off the
topology, so replicas multiplied the count, tombstones stayed in it, and
the detail page ignored EC volumes entirely. Take the numbers from the
shared collection aggregation and label them chunks.

* admin: dedupe replica chunk counts per volume instead of dividing

Dividing each replica's live count by the copy count truncated a chunk
per odd-sized volume, and reported half the count while a volume's
second replica had not checked in yet. Replicas mirror each other's
needles and deletes, so keep the fullest report per volume id.

* admin: fix the collections CSV export column mapping

The exporter read chunks from the EC-volume cell and shifted size and
disk types with it. Read every column the table actually has.
2026-08-06 11:22:06 -07:00
Andrei Stroian aa04889f05 fix(helm): mark filer db-init ConfigMap volume optional (#10596)
The filer StatefulSet declares db-schema-config-volume unconditionally, referencing <release>-seaweedfs-db-init-config. The chart never renders that ConfigMap and the README documents it as operator-supplied, so any deployment that has not pre-created it ends up with a pod spec pointing at a non-existent object. No container mounts the volume, so this is currently inert, but it is misleading and would become a pod-start failure if a volumeMount is ever added.
2026-08-06 10:48:42 -07:00
82 changed files with 4268 additions and 341 deletions

No files matched your search

+174
View File
@@ -1296,6 +1296,180 @@ jobs:
PYEOF
echo "NetworkPolicy rendering tests passed"
echo ""
echo "=== Testing enterprise license mount + master persistence ==="
python3 - "$CHART_DIR" <<'PYEOF'
import subprocess, sys, yaml
chart = sys.argv[1]
def render(values):
args = ["helm", "template", "test", chart]
for k, v in values.items():
args += ["--set", f"{k}={v}"]
return subprocess.check_output(args, text=True)
def workloads(manifest):
for d in yaml.safe_load_all(manifest):
if d and d.get("kind") in ("Deployment", "StatefulSet"):
yield d
ALL_ON = {
"admin.enabled": "true",
"s3.enabled": "true",
"sftp.enabled": "true",
"worker.enabled": "true",
}
failed = []
# Case 1: unconfigured renders nothing, so existing installs are unaffected.
out = render(ALL_ON)
if "SEAWEED_LICENSE" in out or "seaweedfs-license" in out:
failed.append("defaults: license plumbing should not render")
else:
print("defaults: no license volume/env (unchanged)")
# Case 2: only the workloads that run a master carry the license.
LICENSE_PATH = "/etc/seaweedfs/license/seaweed-license.json"
out = render(dict(ALL_ON, **{
"global.seaweedfs.license.existingSecret": "lic",
}))
carrying = set()
for d in workloads(out):
name = d["metadata"]["name"]
pod = d["spec"]["template"]["spec"]
vols = [v for v in pod.get("volumes", []) if v.get("name") == "seaweedfs-license"]
if not vols:
continue
carrying.add(name)
secret = vols[0].get("secret", {})
if secret.get("secretName") != "lic":
failed.append(f"{name}: license volume points at {secret.get('secretName')!r}, not the configured Secret")
items = [i.get("key") for i in secret.get("items", [])]
if items != ["seaweed-license.json"]:
failed.append(f"{name}: license volume projects {items}, expected only the license key")
for c in pod.get("containers", []):
mounts = [m for m in c.get("volumeMounts", []) if m["name"] == "seaweedfs-license"]
if not mounts:
failed.append(f"{name}/{c['name']}: license volume not mounted")
continue
# subPath would freeze the file at container start.
if any("subPath" in m for m in mounts):
failed.append(f"{name}/{c['name']}: license mount uses subPath (renewals would not propagate)")
if not all(m.get("readOnly") for m in mounts):
failed.append(f"{name}/{c['name']}: license mount is not readOnly")
env = {e["name"]: e.get("value") for e in c.get("env", [])}
if env.get("SEAWEED_LICENSE") != LICENSE_PATH:
failed.append(f"{name}/{c['name']}: SEAWEED_LICENSE not set to the mounted file")
if carrying != {"test-seaweedfs-master"}:
failed.append(f"license: expected only the master to carry it, got {sorted(carrying)}")
else:
print("license: master only, key-scoped, readOnly, no subPath, SEAWEED_LICENSE set")
# all-in-one runs `weed server -master`, so it needs the license too.
out = render({
"allInOne.enabled": "true",
"master.enabled": "false",
"volume.enabled": "false",
"filer.enabled": "false",
"global.seaweedfs.license.existingSecret": "lic",
})
aio = [d for d in workloads(out) if d["metadata"]["name"].endswith("-all-in-one")]
if len(aio) != 1:
failed.append(f"all-in-one: expected 1 workload, got {len(aio)}")
else:
pod = aio[0]["spec"]["template"]["spec"]
if not any(v.get("name") == "seaweedfs-license" for v in pod.get("volumes", [])):
failed.append("all-in-one: missing the license volume")
else:
print("all-in-one: carries the license")
# SEAWEED_LICENSE is reserved on both env paths.
out = render({
"global.seaweedfs.license.existingSecret": "lic",
"global.seaweedfs.extraEnvironmentVars.SEAWEED_LICENSE": "/tmp/bogus.json",
})
for d in workloads(out):
if not d["metadata"]["name"].endswith("-master"):
continue
for c in d["spec"]["template"]["spec"].get("containers", []):
names = [e["name"] for e in c.get("env", [])]
if names.count("SEAWEED_LICENSE") != 1:
failed.append(f"SEAWEED_LICENSE rendered {names.count('SEAWEED_LICENSE')} times")
else:
value = next(e.get("value") for e in c["env"] if e["name"] == "SEAWEED_LICENSE")
if value != LICENSE_PATH:
failed.append(f"SEAWEED_LICENSE overridden to {value!r} by extraEnvironmentVars")
else:
print("SEAWEED_LICENSE: reserved, rendered once, points at the mount")
# secretExtraEnvironmentVars is rendered outside the merge helper.
out = render({
"allInOne.enabled": "true",
"master.enabled": "false",
"volume.enabled": "false",
"filer.enabled": "false",
"global.seaweedfs.license.existingSecret": "lic",
"allInOne.secretExtraEnvironmentVars.SEAWEED_LICENSE.secretKeyRef.name": "x",
"allInOne.secretExtraEnvironmentVars.SEAWEED_LICENSE.secretKeyRef.key": "y",
})
for d in workloads(out):
if not d["metadata"]["name"].endswith("-all-in-one"):
continue
for c in d["spec"]["template"]["spec"].get("containers", []):
names = [e["name"] for e in c.get("env", [])]
if names.count("SEAWEED_LICENSE") != 1:
failed.append(f"all-in-one: SEAWEED_LICENSE rendered {names.count('SEAWEED_LICENSE')} times via secretExtraEnvironmentVars")
elif next(e.get("value") for e in c["env"] if e["name"] == "SEAWEED_LICENSE") != LICENSE_PATH:
failed.append("all-in-one: secretExtraEnvironmentVars overrode SEAWEED_LICENSE")
else:
print("all-in-one: SEAWEED_LICENSE reserved on the secret env path too")
# Case 3: the default stays hostPath. volumeClaimTemplates is immutable,
# so growing one here would break helm upgrade on existing releases.
masters = [d for d in workloads(render({})) if d["metadata"]["name"].endswith("-master")]
if len(masters) != 1:
failed.append(f"master: expected 1 StatefulSet by default, got {len(masters)}")
else:
d = masters[0]
claims = [c["metadata"]["name"] for c in d["spec"].get("volumeClaimTemplates", [])]
if any(c.startswith("data-") for c in claims):
failed.append(f"master: default grew a data volumeClaimTemplate ({claims}); "
"that breaks helm upgrade on existing releases")
data_host = [v["name"] for v in d["spec"]["template"]["spec"].get("volumes", [])
if v.get("hostPath") and v["name"].startswith("data-")]
if not data_host:
failed.append("master: default no longer renders a hostPath data volume")
else:
print("master: default still hostPath (upgrade-compatible)")
# Case 4: opting into a claim renders one, with the requested size.
masters = [d for d in workloads(render({"master.data.type": "persistentVolumeClaim"}))
if d["metadata"]["name"].endswith("-master")]
if len(masters) != 1:
failed.append(f"master.data.type=persistentVolumeClaim: expected 1 StatefulSet, got {len(masters)}")
else:
d = masters[0]
claims = {c["metadata"]["name"]: c["spec"]["resources"]["requests"]["storage"]
for c in d["spec"].get("volumeClaimTemplates", [])}
data = {k: v for k, v in claims.items() if k.startswith("data-")}
if not data:
failed.append(f"master.data.type=persistentVolumeClaim: no data claim rendered ({claims})")
elif set(data.values()) != {"1Gi"}:
failed.append(f"master.data.type=persistentVolumeClaim: unexpected size {data}")
else:
print(f"master.data.type=persistentVolumeClaim: renders {sorted(data)} at 1Gi")
if any(v.get("hostPath") and v["name"].startswith("data-")
for v in d["spec"]["template"]["spec"].get("volumes", [])):
failed.append("master.data.type=persistentVolumeClaim: data still on a hostPath")
if failed:
print("\nFAIL:", file=sys.stderr)
for f in failed:
print(f" - {f}", file=sys.stderr)
sys.exit(1)
PYEOF
echo "License + master persistence tests passed"
echo "All template rendering tests passed!"
- name: Create kind cluster
+1 -1
View File
@@ -11,7 +11,6 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/bwmarrin/snowflake v0.3.0
github.com/cenkalti/backoff/v4 v4.3.0
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.6.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
@@ -127,6 +126,7 @@ require (
github.com/aws/aws-sdk-go-v2/config v1.32.33
github.com/aws/aws-sdk-go-v2/credentials v1.19.32
github.com/aws/aws-sdk-go-v2/service/s3 v1.105.2
github.com/cespare/xxhash/v2 v2.3.0
github.com/cognusion/imaging v1.0.4
github.com/fluent/fluent-logger-golang v1.10.1
github.com/getsentry/sentry-go v0.44.1
+149
View File
@@ -107,6 +107,120 @@ https://github.com/rancher/local-path-provisioner
you can use ANY storage class you like, just update the correct storage-class
for your deployment.
### Master data: hostPath vs a claim
The master's `-mdir` holds its Raft log and snapshots, and with them the
cluster's identity (its topology UUID). `master.data.type` defaults to
`hostPath`, which does not follow a pod to another node: a master that is
rescheduled comes back with an empty data directory and a brand new cluster
UUID. With the chart's default of a single master replica there is no peer to
recover the identity from either.
Putting the master's data on a claim avoids that:
```yaml
master:
data:
type: "persistentVolumeClaim"
size: "1Gi"
storageClass: "" # empty uses the cluster's default StorageClass
```
Raft state is small, so a modest claim is enough — sizing matters far more for
volume and filer.
The default is left at `hostPath` for backward compatibility:
`volumeClaimTemplates` is immutable on a StatefulSet, so flipping the type on a
release that already exists fails, whether the chart changes the default or you
change it yourself:
```text
StatefulSet.apps "<release>-seaweedfs-master" is invalid: spec: Forbidden:
updates to statefulset spec for fields other than 'replicas', ... are forbidden
```
New installs can set the claim from the start. To move an **existing** release
onto a claim without losing the cluster UUID, use the migration below. The
claim has to be seeded while the master is stopped: a running master rewrites
its Raft state, so copying into a live pod is silently undone by the next
restart.
The steps below are for the chart's default of a single master
(`master.replicas: 1`). With several master replicas, repeat steps 1, 3 and 4
for every ordinal, or migrate one at a time and let the remaining quorum
re-replicate.
Take the names from the cluster rather than assembling them — the release
name, `nameOverride` and `fullnameOverride` all feed the chart's fullname
helper, so `<release>-seaweedfs` is not always right:
```bash
NS=<namespace>; REL=<release>
# scope by instance as well as component: several releases can share a namespace
STS=$(kubectl -n $NS get sts \
-l app.kubernetes.io/instance=$REL,app.kubernetes.io/component=master \
-o jsonpath='{.items[0].metadata.name}')
POD=$STS-0
# a StatefulSet names its claims <template>-<statefulset>-<ordinal>, and this
# chart's template is data-<namespace>
PVC=data-$NS-$STS-0
# 1. back up the master data directory
kubectl -n $NS cp $POD:/data ./master-backup
# 2. stop the master, leaving the rest of the release running
kubectl -n $NS delete sts $STS --cascade=orphan
kubectl -n $NS delete pod $POD
# 3. create the claim the new StatefulSet will adopt, and seed it through a
# pod that actually mounts it
kubectl -n $NS apply -f - <<EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: $PVC
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
---
apiVersion: v1
kind: Pod
metadata:
name: seed
spec:
containers:
- name: seed
image: alpine:3.20
command: ["sleep", "600"]
volumeMounts:
- name: d
mountPath: /data
volumes:
- name: d
persistentVolumeClaim:
claimName: $PVC
EOF
kubectl -n $NS wait --for=condition=Ready pod/seed --timeout=120s
kubectl -n $NS cp ./master-backup/m9333 seed:/data/
kubectl -n $NS exec seed -- ls /data/m9333 # conf, log, snapshot, state
kubectl -n $NS delete pod seed
# 4. upgrade; the StatefulSet adopts the claim you created
helm upgrade $REL seaweedfs/seaweedfs -n $NS -f values.yaml
```
Confirm the UUID survived — it must match what the cluster reported before the
migration:
```bash
kubectl -n $NS exec $POD -- curl -s localhost:9333/license/status
```
**Or accept a new cluster UUID** and, if you run the enterprise edition, have
the license re-issued against it.
## current instances config (AIO):
1 instance for each type (master/filer+s3/volume)
@@ -426,3 +540,38 @@ helm install seaweedfs seaweedfs/seaweedfs \
For enterprise users, please visit [seaweedfs.com](https://seaweedfs.com) for the SeaweedFS Enterprise Edition,
which has advanced features, including data recovery, self-healing storage, customizable erasure coding, EC vacuum and repair, etc.
To run it, set the image and point the chart at a Secret holding the license
file:
```bash
kubectl create secret generic seaweedfs-license -n <namespace> \
--from-file=seaweed-license.json=/path/to/seaweed-license.json
```
```yaml
global:
seaweedfs:
image:
name: chrislusf/seaweedfs-enterprise
license:
existingSecret: seaweedfs-license
# secretKey: seaweed-license.json # key within the Secret
# mountPath: /etc/seaweedfs/license # directory it is mounted at
```
Set the image globally rather than per component: a per-component
`imageOverride` wins, and a cluster that mixes editions comes up looking
healthy with enterprise features quietly off.
Only the master reads the license, so the Secret is mounted read-only there
and on all-in-one (which runs `weed server -master`). It is mounted as a
directory, not a `subPath`, so a renewed Secret reaches the running master —
which re-reads the file periodically — without a restart.
The license is tied to the cluster UUID kept in the master's Raft state, so put
`master.data` on a claim — a master that restarts onto an empty data directory
generates a new UUID and the license stops matching. See
[Master data](#master-data-hostpath-vs-a-claim). Check the binding with
`kubectl exec <master-pod> -- curl -s localhost:9333/license/status`
(`cluster_uuid` must equal `license_uuid`).
@@ -80,6 +80,7 @@ spec:
image: {{ template "seaweedfs.master.image" . }}
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
env:
{{- include "seaweedfs.licenseEnv" . | nindent 12 }}
{{- /* Determine default cluster alias and the corresponding env var keys to avoid conflicts */}}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.allInOne "target" $mergedExtraEnvironmentVars) }}
@@ -120,11 +121,13 @@ spec:
value: {{ include "seaweedfs.cluster.filerAddress" . | quote }}
{{- if .Values.allInOne.secretExtraEnvironmentVars }}
{{- range $key, $value := .Values.allInOne.secretExtraEnvironmentVars }}
{{- if not (and $key (eq $key "SEAWEED_LICENSE") (include "seaweedfs.licenseEnabled" $)) }}
- name: {{ $key }}
valueFrom:
{{ toYaml $value | nindent 16 }}
{{- end }}
{{- end }}
{{- end }}
command:
- "/bin/sh"
- "-ec"
@@ -352,6 +355,7 @@ spec:
{{- include "seaweedfs.s3.tlsVolumeMount" . | nindent 12 }}
{{- end }}
{{- end }}
{{- include "seaweedfs.licenseVolumeMount" . | nindent 12 }}
{{ tpl .Values.allInOne.extraVolumeMounts . | nindent 12 }}
ports:
- containerPort: {{ .Values.master.port }}
@@ -419,6 +423,7 @@ spec:
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.allInOne.sidecars "context" $) | nindent 8 }}
{{- end }}
volumes:
{{- include "seaweedfs.licenseVolume" . | nindent 8 }}
- name: data
{{- if eq .Values.allInOne.data.type "hostPath" }}
hostPath:
@@ -356,6 +356,7 @@ spec:
- name: db-schema-config-volume
configMap:
name: {{ default (printf "%s-db-init-config" (include "seaweedfs.fullname" .)) .Values.filer.dbInitConfigName }}
optional: true
{{- if and .Values.filer.s3.enabled .Values.filer.s3.enableAuth }}
- name: config-users
secret:
@@ -83,6 +83,7 @@ spec:
image: {{ template "seaweedfs.master.image" . }}
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
env:
{{- include "seaweedfs.licenseEnv" . | nindent 12 }}
- name: POD_IP
valueFrom:
fieldRef:
@@ -211,6 +212,7 @@ spec:
readOnly: true
mountPath: /usr/local/share/ca-certificates/client/
{{- end }}
{{- include "seaweedfs.licenseVolumeMount" . | nindent 12 }}
{{ tpl .Values.master.extraVolumeMounts . | nindent 12 | trim }}
ports:
- containerPort: {{ .Values.master.port }}
@@ -256,6 +258,7 @@ spec:
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.master.sidecars "context" $) | nindent 8 }}
{{- end }}
volumes:
{{- include "seaweedfs.licenseVolume" . | nindent 8 }}
{{- if eq .Values.master.logs.type "hostPath" }}
- name: seaweedfs-master-log-volume
hostPath:
@@ -69,6 +69,11 @@ Inject extra environment vars in the format key:value, if populated
{{- range $key, $value := $component }}
{{- $_ := set $target $key $value }}
{{- end }}
{{/* the license block owns SEAWEED_LICENSE; letting one through here too would
render the key twice in one container */}}
{{- if ((.global | default dict).license | default dict).existingSecret }}
{{- $_ := unset $target "SEAWEED_LICENSE" }}
{{- end }}
{{- end -}}
{{/* Return the proper filer image */}}
@@ -450,6 +455,47 @@ true
{{- end }}
{{- end -}}
{{/* True when an enterprise license Secret is configured. */}}
{{- define "seaweedfs.licenseEnabled" -}}
{{- if ((.Values.global.seaweedfs).license).existingSecret -}}
true
{{- end -}}
{{- end -}}
{{/* Enterprise license volume. Projects just the license key. */}}
{{- define "seaweedfs.licenseVolume" -}}
{{- if include "seaweedfs.licenseEnabled" . -}}
- name: seaweedfs-license
secret:
secretName: {{ .Values.global.seaweedfs.license.existingSecret }}
defaultMode: 0444
items:
- key: {{ .Values.global.seaweedfs.license.secretKey | default "seaweed-license.json" | quote }}
path: {{ .Values.global.seaweedfs.license.secretKey | default "seaweed-license.json" | quote }}
{{- end }}
{{- end -}}
{{/* Enterprise license volume mount. Never a subPath: that is resolved once at
container start, so a renewed Secret would not reach a running master. */}}
{{- define "seaweedfs.licenseVolumeMount" -}}
{{- if include "seaweedfs.licenseEnabled" . -}}
- name: seaweedfs-license
readOnly: true
mountPath: {{ .Values.global.seaweedfs.license.mountPath | default "/etc/seaweedfs/license" | quote }}
{{- end }}
{{- end -}}
{{/* SEAWEED_LICENSE, set explicitly rather than relying on the binary's search
paths, which depend on the working directory. */}}
{{- define "seaweedfs.licenseEnv" -}}
{{- if include "seaweedfs.licenseEnabled" . -}}
- name: SEAWEED_LICENSE
value: {{ printf "%s/%s"
(.Values.global.seaweedfs.license.mountPath | default "/etc/seaweedfs/license")
(.Values.global.seaweedfs.license.secretKey | default "seaweed-license.json") | quote }}
{{- end }}
{{- end -}}
{{/* Generate a compatible trafficDistribution value due to "PreferClose" fast deprecation in k8s v1.35.
Accepts a dict with "value" (the trafficDistribution string) and "Capabilities". */}}
{{- define "seaweedfs.trafficDistribution" -}}
+14
View File
@@ -12,7 +12,16 @@ global:
image:
# if repository is set, it overrides the namespace part of image.name
repository: ""
# chrislusf/seaweedfs-enterprise for the enterprise edition
name: chrislusf/seaweedfs
# Enterprise license file, held in a Secret in the release namespace and
# mounted read-only on the components that run a master. A renewed Secret
# reaches the running master without a restart. SEAWEED_LICENSE is reserved
# while this is set: an extraEnvironmentVars entry of that name is dropped.
license:
existingSecret: ""
secretKey: seaweed-license.json
mountPath: /etc/seaweedfs/license
imagePullPolicy: IfNotPresent
restartPolicy: Always
loggingLevel: 1
@@ -133,8 +142,13 @@ master:
# You can also use emptyDir storage:
# data:
# type: "emptyDir"
# -mdir holds the Raft log and snapshots, and with them the cluster's
# identity (its topology UUID). A hostPath does not follow a rescheduled pod,
# so prefer type "persistentVolumeClaim" for new installs. The default stays
# hostPath so existing releases keep upgrading; see the README to switch one.
data:
type: "hostPath"
size: "1Gi"
storageClass: ""
hostPathPrefix: /ssd
Executable
BIN
View File
Binary file not shown.
@@ -136,6 +136,10 @@ message ListEntriesRequest {
bool inclusiveStartFrom = 4;
uint32 limit = 5;
int64 snapshot_ts_ns = 6;
// Leave the chunk list out of every entry in the response. The attributes
// still carry the file size, so a listing that only reads attributes can
// ask for this and skip the largest part of the payload.
bool omit_chunks = 7;
}
message ListEntriesResponse {
+132 -22
View File
@@ -7,8 +7,8 @@
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tracing::warn;
@@ -122,6 +122,10 @@ impl DiskLocation {
// Scan for .dat files
let entries = fs::read_dir(&self.directory)?;
let mut dat_files: Vec<(String, VolumeId)> = Vec::new();
// Every collection claiming an id, in scan order; open_volumes keeps
// the first that opens.
let mut to_load: Vec<(VolumeId, Vec<String>)> = Vec::new();
let mut queued: HashMap<VolumeId, usize> = HashMap::new();
let mut seen = HashSet::new();
for entry in entries {
@@ -201,6 +205,7 @@ impl DiskLocation {
continue;
}
// Load existing data only; never create a phantom `.dat`. A lone
// `.vif`/`.idx` (e.g. an EC sidecar whose `.ecx` is on a sibling
// disk) would otherwise have Volume::new write an 8-byte stub that
@@ -221,30 +226,22 @@ impl DiskLocation {
continue;
}
match Volume::new(
&self.directory,
&self.idx_directory,
&collection,
vid,
needle_map_kind,
None, // replica placement read from superblock
None, // TTL read from superblock
0, // no preallocate on load
Version::current(),
) {
Ok(mut v) => {
v.location_disk_space_low = self.is_disk_space_low.clone();
crate::metrics::VOLUME_GAUGE
.with_label_values(&[&collection, "volume"])
.inc();
self.volumes.insert(vid, v);
}
Err(e) => {
warn!(volume_id = vid.0, error = %e, "failed to load volume");
match queued.get(&vid) {
Some(&i) => to_load[i].1.push(collection),
None => {
queued.insert(vid, to_load.len());
to_load.push((vid, vec![collection]));
}
}
}
for (collection, vid, v) in self.open_volumes(to_load, needle_map_kind) {
crate::metrics::VOLUME_GAUGE
.with_label_values(&[&collection, "volume"])
.inc();
self.volumes.insert(vid, v);
}
// After regular volumes, auto-discover EC shards on disk so a
// fresh restart picks up shards without an explicit
// VolumeEcShardsMount RPC. Mirrors Go's loadExistingVolumes
@@ -257,6 +254,65 @@ impl DiskLocation {
Ok(())
}
/// Open the volumes the directory scan selected. Opening one is dominated
/// by reading its .idx into the needle map, so a disk holding thousands
/// takes thousands of serial index reads to come up; mirrors Go's
/// concurrentLoadingVolumes down to the max(cores, 10) worker count, whose
/// floor keeps a small-core box off one-at-a-time on IO-bound work.
///
/// An id is only spoken for once a volume actually loads, so a corrupt
/// `colA_5.dat` still leaves `colB_5.dat` a chance.
fn open_volumes(
&self,
to_load: Vec<(VolumeId, Vec<String>)>,
needle_map_kind: NeedleMapKind,
) -> Vec<(String, VolumeId, Volume)> {
if to_load.is_empty() {
return Vec::new();
}
let workers = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
.max(10)
.min(to_load.len());
let next = AtomicUsize::new(0);
let opened = Mutex::new(Vec::with_capacity(to_load.len()));
std::thread::scope(|scope| {
for _ in 0..workers {
scope.spawn(|| loop {
let i = next.fetch_add(1, Ordering::Relaxed);
let Some((vid, collections)) = to_load.get(i) else {
return;
};
for collection in collections {
match Volume::new(
&self.directory,
&self.idx_directory,
collection,
*vid,
needle_map_kind,
None, // replica placement read from superblock
None, // TTL read from superblock
0, // no preallocate on load
Version::current(),
) {
Ok(mut v) => {
v.location_disk_space_low = self.is_disk_space_low.clone();
opened.lock().unwrap().push((collection.clone(), *vid, v));
break;
}
Err(e) => {
warn!(volume_id = vid.0, error = %e, "failed to load volume");
}
}
}
});
}
});
opened.into_inner().unwrap_or_else(|e| e.into_inner())
}
/// Directory pre-pass that recovers interrupted compaction commits. Collects
/// every volume id that still has a .cpc commit marker or a leftover
/// .cpd/.cpx temp file across the data and idx directories, then rolls the
@@ -1493,6 +1549,60 @@ mod tests {
assert!(ids.contains(&VolumeId(2)));
}
// Two collections can name the same volume id on one disk; a candidate
// that fails to open must not shadow a good one behind it.
#[test]
fn test_open_volumes_falls_back_past_a_corrupt_candidate() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
{
let mut loc = DiskLocation::new(
dir,
dir,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
loc.create_volume(
VolumeId(9),
"good",
NeedleMapKind::InMemory,
None,
None,
0,
Version::current(),
)
.unwrap();
loc.close();
}
// Same id under another collection, unopenable.
let mut bad = vec![0u8; 16];
bad[0] = 9; // unsupported version
std::fs::write(format!("{}/bad_9.dat", dir), &bad).unwrap();
let loc = DiskLocation::new(
dir,
dir,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
let opened = loc.open_volumes(
vec![(VolumeId(9), vec!["bad".to_string(), "good".to_string()])],
NeedleMapKind::InMemory,
);
assert_eq!(opened.len(), 1, "the good candidate should still open");
assert_eq!(opened[0].0, "good");
assert_eq!(opened[0].1, VolumeId(9));
}
#[test]
fn test_disk_location_delete_volume() {
let tmp = TempDir::new().unwrap();
+65 -14
View File
@@ -1970,11 +1970,13 @@ impl Volume {
}
/// Verify the live needle at the .dat tail: its header must match the
/// .idx entry and the .dat must end exactly at its on-disk end. Extra
/// bytes mean an unindexed trailing record (a torn append); appending
/// after one would place the next needle at an offset the 8-byte .idx
/// encoding may not represent, so the volume is quarantined read-only
/// instead. Mirrors Go's verifyNeedleIntegrity.
/// .idx entry and, on v3, the .dat must end exactly at its on-disk end.
/// Extra bytes mean an unindexed trailing record (a torn append);
/// appending after one would place the next needle at an offset the
/// 8-byte .idx encoding may not represent, so the volume is quarantined
/// read-only instead. Mirrors Go's verifyNeedleIntegrity, whose tail
/// check is v3-only -- a v1/v2 volume Go serves read-write must not go
/// read-only here.
fn verify_needle_integrity(
&mut self,
actual_offset: i64,
@@ -2013,15 +2015,16 @@ impl Volume {
)));
}
if version == VERSION_3 {
let ts_offset =
checked_offset as u64 + NEEDLE_HEADER_SIZE as u64 + size.0 as u64 + 4; // skip checksum
let mut ts_buf = [0u8; 8];
self.read_exact_at_backend(&mut ts_buf, ts_offset)?;
let ts = u64::from_be_bytes(ts_buf);
if ts > 0 {
self.last_append_at_ns = ts;
}
if version != VERSION_3 {
return Ok(());
}
let ts_offset = checked_offset as u64 + NEEDLE_HEADER_SIZE as u64 + size.0 as u64 + 4; // skip checksum
let mut ts_buf = [0u8; 8];
self.read_exact_at_backend(&mut ts_buf, ts_offset)?;
let ts = u64::from_be_bytes(ts_buf);
if ts > 0 {
self.last_append_at_ns = ts;
}
self.verify_dat_ends_at(checked_offset + get_actual_size(size, version))
@@ -4115,6 +4118,54 @@ mod tests {
);
}
// Go's tail check is v3-only, so it serves a v1/v2 volume with an
// unindexed tail read-write. Checking it here flipped whole legacy disks
// read-only on their first boot under this server.
#[test]
fn test_integrity_skips_dat_tail_check_before_v3() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
{
let mut v = Volume::new(
dir,
dir,
"",
VolumeId(1),
NeedleMapKind::InMemory,
None,
None,
0,
VERSION_2,
)
.unwrap();
for i in 1..=3u64 {
let data = format!("data {}", i);
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: data.as_bytes().to_vec(),
data_size: data.len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
}
v.sync_to_disk().unwrap();
}
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
let mut f = OpenOptions::new().append(true).open(&dat_path).unwrap();
f.write_all(&[0xFFu8; 96]).unwrap();
f.sync_all().unwrap();
drop(f);
let v = reload_volume(dir);
assert_eq!(v.version(), VERSION_2, "volume should reload as v2");
assert!(
!v.is_no_write_or_delete(),
"v2 volume with unindexed .dat tail must stay writable, as in Go"
);
}
// Same torn tail, but with a deletion tombstone as the last indexed
// record — the tombstone path must also verify the .dat ends at it.
#[test]
+4
View File
@@ -184,6 +184,10 @@ GET /api/history?cluster_id=<uuid>&days=90
# Get per-cluster disk usage and volume servers over time, largest first,
# the rest summed as "other"
GET /api/cluster-sizes?days=30&limit=20
# Get how many clusters ran each version over time, oldest version first,
# the rest summed as "other"
GET /api/versions?days=30&limit=8
```
### Monitoring
+24
View File
@@ -174,6 +174,30 @@ func (h *Handler) GetClusterSizes(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(h.storage.GetClusterSizeSeries(days, limit))
}
func (h *Handler) GetVersions(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
days := 30 // default
if daysStr := r.URL.Query().Get("days"); daysStr != "" {
if d, err := strconv.Atoi(daysStr); err == nil && d > 0 && d <= 365 {
days = d
}
}
limit := 8 // default, the number of colours the version stack has
if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 1000 {
limit = l
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(h.storage.GetVersionSeries(days, limit))
}
func (h *Handler) GetHistory(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+122 -19
View File
@@ -143,12 +143,24 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
<div class="chart-container">
<div class="chart-title">Version Distribution</div>
<canvas id="versionChart" width="400" height="200"></canvas>
<div style="position: relative; height: 320px;">
<canvas id="versionChart"></canvas>
</div>
</div>
<div class="chart-container">
<div class="chart-title">Versions Over Time</div>
<div class="chart-subtitle" id="versionSeriesTotal"></div>
<div style="position: relative; height: 420px;">
<canvas id="versionSeriesChart"></canvas>
</div>
</div>
<div class="chart-container">
<div class="chart-title">Operating System Distribution</div>
<canvas id="osChart" width="400" height="200"></canvas>
<div style="position: relative; height: 320px;">
<canvas id="osChart"></canvas>
</div>
</div>
<div class="chart-container">
@@ -197,12 +209,20 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
const sizesResponse = await fetch('/api/cluster-sizes?days=30&limit=20');
const sizes = await sizesResponse.json();
updateStats(stats);
updateCharts(stats);
updateClusterSizes(sizes);
// Load the fleet's version make-up over time
const versionsResponse = await fetch('/api/versions?days=30&limit=8');
const versions = await versionsResponse.json();
// Show the dashboard before drawing into it: a canvas in a
// display:none container measures zero, and a pie sized from
// that never grows back.
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'block';
updateStats(stats);
updateCharts(stats);
updateVersions(versions);
updateClusterSizes(sizes);
} catch (error) {
console.error('Error loading dashboard:', error);
showError('Failed to load telemetry data: ' + error.message);
@@ -246,6 +266,9 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
},
options: {
responsive: true,
// Without this the canvas keeps its 2:1 attribute ratio at
// the card's full width, drawing a pie taller than the card.
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom'
@@ -298,6 +321,76 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
return (unit === 0 ? value : value.toFixed(value >= 100 ? 0 : 1)) + ' ' + units[unit];
}
// Fixed hues rather than the evenly spaced ones the cluster stacks use:
// a handful of versions is a set you read, and evenly spaced hues put
// pairs next to each other that colour-blind readers can't separate.
const versionColors = ['#2a78d6', '#eb6834', '#1baf7a', '#eda100',
'#e87ba4', '#008300', '#4a3aa7', '#e34948'];
// One stacked band per version: the band is how many clusters ran that
// version that day, the top of the stack is the confirmed fleet, so the
// chart shows both how it grows and what it upgrades to. The pie above
// it is the same fleet on the last of these days.
function updateVersions(series) {
const versions = series.versions || [];
const dates = series.dates || [];
const total = series.total_clusters || 0;
document.getElementById('versionSeriesTotal').textContent =
total + ' cluster' + (total === 1 ? '' : 's') + ' on ' + (dates[dates.length - 1] || 'no data');
// Newest release on the floor, oldest on top: the current release
// is the band being read, and one anchored to the baseline reads
// straight off the axis instead of riding on everything below it.
// Colours follow the same order, so a release keeps its colour as
// older ones age out from the top.
const datasets = versions.slice().reverse().map((v, i) =>
band(v.version, v.clusters, '#ffffff', versionColors[i % versionColors.length], 2));
if (series.other) {
datasets.push(band('other (' + series.other.count + ' versions)', series.other.clusters,
'#ffffff', '#9a9a94', 2));
}
stackedArea('versionSeriesChart', dates, datasets, value => value, { plugins: [bandLabels] });
}
// Writes each version into its own band, so the chart reads without
// matching colours against the legend. Bands too thin to hold the text
// keep it, and the halo carries it over whatever it crosses.
const bandLabels = {
id: 'bandLabels',
afterDatasetsDraw(chart) {
const ctx = chart.ctx;
ctx.save();
ctx.font = '600 12px -apple-system, BlinkMacSystemFont, sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineJoin = 'round';
chart.data.datasets.forEach((dataset, d) => {
const meta = chart.getDatasetMeta(d);
if (meta.hidden) return;
// Label where the band is thickest, so the text has room.
let at = -1, thickest = 0;
dataset.data.forEach((value, i) => {
if (value > thickest) {
thickest = value;
at = i;
}
});
const point = at >= 0 && meta.data[at];
if (!point) return;
const below = d === 0 ? chart.scales.y.getPixelForValue(0)
: chart.getDatasetMeta(d - 1).data[at].y;
if (below - point.y < 18) return;
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(255, 255, 255, 0.85)';
ctx.strokeText(dataset.label, point.x, (point.y + below) / 2);
ctx.fillStyle = '#1a1a1a';
ctx.fillText(dataset.label, point.x, (point.y + below) / 2);
});
ctx.restore();
}
};
// Disk usage and volume servers both drawn as one stacked band per
// cluster over time: the band is that cluster's share, the top of the
// stack is the fleet total. Clusters beyond the requested limit are
@@ -337,6 +430,24 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
'#9E9E9E', 'rgba(158, 158, 158, 0.6)'));
}
stackedArea(canvasId, dates, datasets, format, {
onClick: (event, elements) => {
const id = elements.length && clusterSizeIds[elements[0].datasetIndex];
if (id) {
document.getElementById('clusterIdInput').value = id;
loadClusterHistory();
}
},
// The legend shows shortened ids; the tooltip has room for the
// full one to paste into the lookup box.
label: item => (clusterSizeIds[item.datasetIndex] || item.dataset.label) + ': ' + format(item.raw)
});
}
// Draws the bands as one stack, so their heights add up to the day's
// total. hooks.onClick, hooks.label and hooks.plugins are optional.
function stackedArea(canvasId, dates, datasets, format, hooks) {
hooks = hooks || {};
const ctx = document.getElementById(canvasId).getContext('2d');
if (charts[canvasId]) {
charts[canvasId].destroy();
@@ -344,25 +455,17 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
charts[canvasId] = new Chart(ctx, {
type: 'line',
data: { labels: dates, datasets: datasets },
plugins: hooks.plugins,
options: {
responsive: true,
maintainAspectRatio: false,
interaction: { mode: 'band', intersect: false },
onClick: (event, elements) => {
const id = elements.length && clusterSizeIds[elements[0].datasetIndex];
if (id) {
document.getElementById('clusterIdInput').value = id;
loadClusterHistory();
}
},
onClick: hooks.onClick,
plugins: {
legend: { position: 'bottom', labels: { boxWidth: 12, font: { size: 11 } } },
tooltip: {
callbacks: {
label: item => {
const id = clusterSizeIds[item.datasetIndex];
return (id || item.dataset.label) + ': ' + format(item.raw);
}
label: hooks.label || (item => item.dataset.label + ': ' + format(item.raw))
}
}
},
@@ -396,13 +499,13 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
return [];
};
function band(label, data, borderColor, backgroundColor) {
function band(label, data, borderColor, backgroundColor, borderWidth) {
return {
label: label,
data: data,
borderColor: borderColor,
backgroundColor: backgroundColor,
borderWidth: 1,
borderWidth: borderWidth || 1,
pointRadius: 0,
pointHitRadius: 8,
fill: true,
+1
View File
@@ -77,6 +77,7 @@ func main() {
mux.HandleFunc("/api/metrics", corsMiddleware(logMiddleware(apiHandler.GetMetrics)))
mux.HandleFunc("/api/history", corsMiddleware(logMiddleware(apiHandler.GetHistory)))
mux.HandleFunc("/api/cluster-sizes", corsMiddleware(logMiddleware(apiHandler.GetClusterSizes)))
mux.HandleFunc("/api/versions", corsMiddleware(logMiddleware(apiHandler.GetVersions)))
// Dashboard (optional)
if *enableDashboard {
+7 -4
View File
@@ -20,6 +20,7 @@ type HistorySample struct {
TotalDiskBytes uint64 `json:"disk"`
TotalVolumeCount int32 `json:"volumes"`
VolumeServerCount int32 `json:"servers"`
Version string `json:"ver,omitempty"` // empty in samples written before this was recorded
}
// appendHistory records the report as the cluster's sample for the day,
@@ -30,6 +31,7 @@ func (s *PrometheusStorage) appendHistory(data *proto.TelemetryData, receivedAt
TotalDiskBytes: data.TotalDiskBytes,
TotalVolumeCount: data.TotalVolumeCount,
VolumeServerCount: data.VolumeServerCount,
Version: data.Version,
}
h := s.histories[data.TopologyId]
if n := len(h); n > 0 && sameUTCDay(h[n-1].Ts, sample.Ts) {
@@ -110,16 +112,17 @@ func utcDay(ts int64) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
}
func diskBytes(s HistorySample) uint64 { return s.TotalDiskBytes }
func serverCount(s HistorySample) uint64 { return uint64(s.VolumeServerCount) }
func diskBytes(s HistorySample) uint64 { return s.TotalDiskBytes }
func serverCount(s HistorySample) uint64 { return uint64(s.VolumeServerCount) }
func sampleVersion(s HistorySample) string { return s.Version }
// align lays one cluster's history onto the axis, picking `value` out of each
// sample. Clusters report roughly once a day at no fixed hour, so a day without
// a report carries the previous value forward rather than dropping to zero; a
// cluster that stopped reporting altogether ends at its last sample instead of
// holding capacity forever. Reports false when the cluster has nothing in range.
func (d dailySeries) align(history []HistorySample, activeSince int64, value func(HistorySample) uint64) ([]uint64, bool) {
out := make([]uint64, len(d.dates))
func align[T any](d dailySeries, history []HistorySample, activeSince int64, value func(HistorySample) T) ([]T, bool) {
out := make([]T, len(d.dates))
reported := make([]bool, len(d.dates))
first, last := -1, -1
for _, sample := range history {
+11 -2
View File
@@ -44,9 +44,18 @@ func (s *PrometheusStorage) LoadState(path string) (int, error) {
loaded++
}
for id, h := range state.Histories {
if _, ok := s.instances[id]; ok && len(h) > 0 {
s.histories[id] = h
instance, ok := s.instances[id]
if !ok || len(h) == 0 {
continue
}
// State written before versions were recorded carries none on its
// samples. The newest sample is the report the instance record itself
// came from, so that day's version is known and the version series can
// start there rather than a day after the upgrade.
if newest := len(h) - 1; h[newest].Version == "" {
h[newest].Version = instance.TelemetryData.Version
}
s.histories[id] = h
}
s.updateStats()
return loaded, nil
@@ -72,3 +72,38 @@ func TestStateRoundTrip(t *testing.T) {
t.Error("dirty flag set after load")
}
}
// State written before versions were recorded still knows the version of the
// report its newest sample came from: the instance record's.
func TestLoadStateFillsNewestSampleVersion(t *testing.T) {
path := filepath.Join(t.TempDir(), "telemetry-state.json")
s := newPrometheusStorage(prometheus.NewRegistry())
report := &proto.TelemetryData{TopologyId: "test-cluster-1", Version: "4.40", Os: "linux/amd64"}
if err := s.StoreTelemetry(report); err != nil {
t.Fatalf("store: %v", err)
}
yesterday := time.Now().AddDate(0, 0, -1).Unix()
s.histories[report.TopologyId] = []HistorySample{
{Ts: yesterday, TotalDiskBytes: 10},
{Ts: time.Now().Unix(), TotalDiskBytes: 20},
}
if err := s.SaveStateIfDirty(path); err != nil {
t.Fatalf("save: %v", err)
}
s = newPrometheusStorage(prometheus.NewRegistry())
if _, err := s.LoadState(path); err != nil {
t.Fatalf("load: %v", err)
}
loaded := s.histories[report.TopologyId]
if len(loaded) != 2 {
t.Fatalf("history = %+v, want 2 samples", loaded)
}
if loaded[1].Version != report.Version {
t.Errorf("newest sample version = %q, want %q", loaded[1].Version, report.Version)
}
if loaded[0].Version != "" {
t.Errorf("older sample version = %q, want it left unknown", loaded[0].Version)
}
}
+2 -2
View File
@@ -180,12 +180,12 @@ func (s *PrometheusStorage) GetMetrics(days int) (map[string]interface{}, error)
diskUsage := make([]uint64, len(axis.dates))
serverCounts := make([]int64, len(axis.dates))
for _, history := range histories {
if disk, ok := axis.align(history, activeSince, diskBytes); ok {
if disk, ok := align(axis, history, activeSince, diskBytes); ok {
for i, v := range disk {
diskUsage[i] += v
}
}
if servers, ok := axis.align(history, activeSince, serverCount); ok {
if servers, ok := align(axis, history, activeSince, serverCount); ok {
for i, v := range servers {
serverCounts[i] += int64(v)
}
+2 -2
View File
@@ -48,11 +48,11 @@ func (s *PrometheusStorage) GetClusterSizeSeries(days, limit int) ClusterSizeSer
series := ClusterSizeSeries{Dates: axis.dates}
for id, history := range histories {
disk, ok := axis.align(history, activeSince, diskBytes)
disk, ok := align(axis, history, activeSince, diskBytes)
if !ok {
continue
}
servers, _ := axis.align(history, activeSince, serverCount)
servers, _ := align(axis, history, activeSince, serverCount)
series.Clusters = append(series.Clusters, ClusterSeries{ClusterId: id, Disk: disk, Servers: servers})
series.TotalDisk += disk[last]
series.TotalServers += servers[last]
+163
View File
@@ -0,0 +1,163 @@
package storage
import (
"sort"
"strconv"
"strings"
"time"
)
// VersionCounts is how many clusters ran one version per day, aligned to the
// shared date axis of the enclosing VersionSeries.
type VersionCounts struct {
Version string `json:"version"`
Clusters []uint64 `json:"clusters"`
}
// OtherVersions is the versions beyond the caller's limit, summed per day so a
// stacked chart still adds up to the cluster total.
type OtherVersions struct {
Count int `json:"count"`
Clusters []uint64 `json:"clusters"`
}
// VersionSeries is the version make-up of the fleet over time: one cluster
// count per version per day, oldest release first.
type VersionSeries struct {
Dates []string `json:"dates"`
Versions []VersionCounts `json:"versions"`
Other *OtherVersions `json:"other,omitempty"`
TotalClusters uint64 `json:"total_clusters"` // across all versions on the last day
}
// GetVersionSeries returns the last `days` days of per-version cluster counts
// across confirmed clusters. Versions beyond `limit` are folded into Other,
// keeping the ones with the most clusters on the last day.
func (s *PrometheusStorage) GetVersionSeries(days, limit int) VersionSeries {
s.mu.RLock()
defer s.mu.RUnlock()
histories := versionedHistories(s.seriesHistories())
axis := newDailySeries(days, histories)
activeSince := time.Now().UTC().AddDate(0, 0, -activeDays).Unix()
last := len(axis.dates) - 1
series := VersionSeries{Dates: axis.dates}
daily := make(map[string][]uint64)
for _, history := range histories {
versions, ok := align(axis, history, activeSince, sampleVersion)
if !ok {
continue
}
for i, v := range versions {
if v == "" {
continue // before the cluster's first day in the window
}
counts, ok := daily[v]
if !ok {
counts = make([]uint64, len(axis.dates))
daily[v] = counts
}
counts[i]++
}
}
for v, counts := range daily {
series.Versions = append(series.Versions, VersionCounts{Version: v, Clusters: counts})
series.TotalClusters += counts[last]
}
// Ordered by release rather than by size: the caller stacks them, and a
// stack whose order changes with the counts is unreadable over time.
sort.Slice(series.Versions, func(i, j int) bool {
return versionLess(series.Versions[i].Version, series.Versions[j].Version)
})
if limit > 0 && len(series.Versions) > limit {
// Old releases are a long tail of one-cluster bands; keep the versions
// most of the fleet is on now and sum the rest into one band.
ranked := append([]VersionCounts(nil), series.Versions...)
sort.Slice(ranked, func(i, j int) bool {
if ranked[i].Clusters[last] != ranked[j].Clusters[last] {
return ranked[i].Clusters[last] > ranked[j].Clusters[last]
}
return versionLess(ranked[j].Version, ranked[i].Version)
})
other := OtherVersions{Count: len(ranked) - limit, Clusters: make([]uint64, len(axis.dates))}
for _, v := range ranked[limit:] {
for i, c := range v.Clusters {
other.Clusters[i] += c
}
}
kept := make(map[string]bool, limit)
for _, v := range ranked[:limit] {
kept[v.Version] = true
}
versions := series.Versions[:0]
for _, v := range series.Versions {
if kept[v.Version] {
versions = append(versions, v)
}
}
series.Versions = versions
series.Other = &other
}
return series
}
// versionedHistories drops the samples recorded before the reported version was
// kept in history, so the version series spans the days it actually knows a
// version for instead of climbing out of a run of blank days.
func versionedHistories(histories map[string][]HistorySample) map[string][]HistorySample {
out := make(map[string][]HistorySample, len(histories))
for id, history := range histories {
var kept []HistorySample
for _, sample := range history {
if sample.Version != "" {
kept = append(kept, sample)
}
}
if len(kept) > 0 {
out[id] = kept
}
}
return out
}
// versionLess orders release strings like "3.97" and "4.40" by their numeric
// components rather than lexically, which would sort "10.02" before "9.99". A
// build suffix sits next to the release it was built from. Anything that
// doesn't parse, such as the "unknown" a client with no version compiled in
// reports, sorts first.
func versionLess(a, b string) bool {
an, aSuffix, aok := versionParts(a)
bn, bSuffix, bok := versionParts(b)
if aok != bok {
return !aok
}
if !aok {
return a < b
}
for i := 0; i < len(an) && i < len(bn); i++ {
if an[i] != bn[i] {
return an[i] < bn[i]
}
}
if len(an) != len(bn) {
return len(an) < len(bn)
}
return aSuffix < bSuffix
}
func versionParts(v string) ([]int, string, bool) {
number, suffix, _ := strings.Cut(v, "-")
fields := strings.Split(number, ".")
parts := make([]int, 0, len(fields))
for _, field := range fields {
n, err := strconv.Atoi(field)
if err != nil {
return nil, "", false
}
parts = append(parts, n)
}
return parts, suffix, len(parts) > 0
}
+109
View File
@@ -0,0 +1,109 @@
package storage
import (
"testing"
"github.com/prometheus/client_golang/prometheus"
)
func TestVersionSeries(t *testing.T) {
s := newPrometheusStorage(prometheus.NewRegistry())
// Upgraded mid-window: its band leaves the old version for the new one.
seedSamples(s, "upgraded", HistorySample{Version: "4.39"}, -4, -3)
seedSamples(s, "upgraded", HistorySample{Version: "4.40"}, -2, -1, 0)
// Reported every day on the same version.
seedSamples(s, "steady", HistorySample{Version: "4.40"}, -4, -3, -2, -1, 0)
// One day of history only: unconfirmed, so it stays out of the stack.
seedSamples(s, "oneshot", HistorySample{Version: "4.40"}, -1)
// Confirmed, but its samples predate versions being recorded.
seedSamples(s, "versionless", HistorySample{}, -9, -8)
series := s.GetVersionSeries(10, 0)
// The versionless days are dropped before the axis is built, so the chart
// spans the days a version is known for instead of climbing out of blanks.
if len(series.Dates) != 5 {
t.Fatalf("dates = %v, want the 5 days with versions", series.Dates)
}
if len(series.Versions) != 2 ||
series.Versions[0].Version != "4.39" || series.Versions[1].Version != "4.40" {
t.Fatalf("versions = %+v, want 4.39 then 4.40", series.Versions)
}
if got := series.Versions[0].Clusters; !equal(got, []uint64{1, 1, 0, 0, 0}) {
t.Errorf("4.39 = %v, want the upgraded cluster's first two days", got)
}
if got := series.Versions[1].Clusters; !equal(got, []uint64{1, 1, 2, 2, 2}) {
t.Errorf("4.40 = %v, want steady plus upgraded from day 3", got)
}
if series.TotalClusters != 2 {
t.Errorf("total_clusters = %d, want 2", series.TotalClusters)
}
if series.Other != nil {
t.Errorf("other = %+v, want none without a limit", series.Other)
}
}
func TestVersionSeriesHoldsForwardAndLimits(t *testing.T) {
s := newPrometheusStorage(prometheus.NewRegistry())
// Stopped reporting past the active window: its own days only.
seedSamples(s, "gone", HistorySample{Version: "3.97"}, -9, -8)
// Reported every day of the window.
seedSamples(s, "daily", HistorySample{Version: "4.40"}, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0)
// Reported three days ago and not since: still active, so it holds its
// version to the right edge instead of dropping out of the stack.
seedSamples(s, "lagging", HistorySample{Version: "4.30"}, -3, -2)
series := s.GetVersionSeries(10, 0)
if len(series.Dates) != 10 {
t.Fatalf("dates = %v, want 10 days", series.Dates)
}
byVersion := map[string][]uint64{}
for _, v := range series.Versions {
byVersion[v.Version] = v.Clusters
}
if got := byVersion["3.97"]; !equal(got, []uint64{1, 1, 0, 0, 0, 0, 0, 0, 0, 0}) {
t.Errorf("3.97 = %v, want nothing after its last report", got)
}
if got := byVersion["4.30"]; !equal(got, []uint64{0, 0, 0, 0, 0, 0, 1, 1, 1, 1}) {
t.Errorf("4.30 = %v, want carried to the right edge", got)
}
if got := byVersion["4.40"]; !equal(got, []uint64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}) {
t.Errorf("4.40 = %v, want 1 every day", got)
}
if series.TotalClusters != 2 {
t.Errorf("total_clusters = %d, want the 2 clusters still reporting", series.TotalClusters)
}
// Past the limit, the versions the fewest clusters are on are summed into
// one band; ties on the last day keep the newer version.
series = s.GetVersionSeries(10, 1)
if len(series.Versions) != 1 || series.Versions[0].Version != "4.40" {
t.Fatalf("limited versions = %+v, want just 4.40", series.Versions)
}
if series.Other == nil || series.Other.Count != 2 {
t.Fatalf("other = %+v, want 2 versions", series.Other)
}
if !equal(series.Other.Clusters, []uint64{1, 1, 0, 0, 0, 0, 1, 1, 1, 1}) {
t.Errorf("other = %v, want 3.97+4.30 summed per day", series.Other.Clusters)
}
if series.TotalClusters != 2 {
t.Errorf("limit changed total_clusters: %d, want 2", series.TotalClusters)
}
}
func TestVersionLess(t *testing.T) {
// Ordered oldest to newest; every pair must compare in this order.
ordered := []string{"unknown", "3.97", "4.02", "4.30", "4.30-enterprise", "9.99", "10.02"}
for i := 0; i < len(ordered); i++ {
for j := i + 1; j < len(ordered); j++ {
if !versionLess(ordered[i], ordered[j]) {
t.Errorf("versionLess(%q, %q) = false, want true", ordered[i], ordered[j])
}
if versionLess(ordered[j], ordered[i]) {
t.Errorf("versionLess(%q, %q) = true, want false", ordered[j], ordered[i])
}
}
}
}
+2 -2
View File
@@ -23,7 +23,7 @@ const (
type AdminData struct {
Username string `json:"username"`
TotalVolumes int `json:"total_volumes"`
TotalFiles int64 `json:"total_files"`
TotalChunks int64 `json:"total_chunks"`
TotalSize int64 `json:"total_size"`
VolumeSizeLimitMB uint64 `json:"volume_size_limit_mb"`
MasterNodes []MasterNode `json:"master_nodes"`
@@ -199,7 +199,7 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
adminData := AdminData{
Username: username,
TotalVolumes: topology.TotalVolumes,
TotalFiles: topology.TotalFiles,
TotalChunks: topology.TotalChunks,
TotalSize: topology.TotalSize,
VolumeSizeLimitMB: volumeSizeLimitMB,
MasterNodes: masterNodes,
+41 -3
View File
@@ -1928,9 +1928,20 @@ type ecVolumeCounts struct {
deleteCount uint64
}
// volumeLiveCount is the live chunk count of one regular volume. Replicas
// mirror each other's needles and their deletes, so the fullest report is the
// volume's count — dividing each report by the copy count instead would lose
// a chunk to integer truncation and would halve a volume whose second replica
// has not reported yet.
type volumeLiveCount struct {
collection string
live uint64
}
func collectCollectionStats(topologyInfo *master_pb.TopologyInfo) map[string]collectionStats {
collectionMap := make(map[string]collectionStats)
ecVolumeAgg := make(map[uint32]*ecVolumeCounts)
volumeAgg := make(map[uint32]*volumeLiveCount)
for _, dc := range topologyInfo.DataCenterInfos {
for _, rack := range dc.RackInfos {
for _, node := range rack.DataNodeInfos {
@@ -1951,10 +1962,18 @@ func collectCollectionStats(topologyInfo *master_pb.TopologyInfo) map[string]col
if volInfo.Size >= volInfo.DeletedByteCount {
data.LogicalSize += int64(volInfo.Size-volInfo.DeletedByteCount) / replicaCount
}
if volInfo.FileCount >= volInfo.DeleteCount {
data.FileCount += int64(volInfo.FileCount-volInfo.DeleteCount) / replicaCount
}
collectionMap[collection] = data
if volInfo.FileCount >= volInfo.DeleteCount {
agg, ok := volumeAgg[volInfo.Id]
if !ok {
agg = &volumeLiveCount{collection: collection}
volumeAgg[volInfo.Id] = agg
}
if live := volInfo.FileCount - volInfo.DeleteCount; live > agg.live {
agg.live = live
}
}
}
for _, ecShardInfo := range diskInfo.EcShardInfos {
collection := ecShardInfo.Collection
@@ -1987,6 +2006,14 @@ func collectCollectionStats(topologyInfo *master_pb.TopologyInfo) map[string]col
}
}
// Fold the per-volume live counts in, one entry per volume id no matter
// how many replicas reported it.
for _, agg := range volumeAgg {
data := collectionMap[agg.collection]
data.FileCount += int64(agg.live)
collectionMap[agg.collection] = data
}
// Fold EC per-volume counts into the collection totals. fileCount is
// deduped via max across every node reporting shards for the volume;
// deleteCount is summed across the same nodes.
@@ -2004,6 +2031,17 @@ func collectCollectionStats(topologyInfo *master_pb.TopologyInfo) map[string]col
return collectionMap
}
// totalCollectionFileCount is the cluster-wide live chunk count: the sum of
// every collection's deduped count. Volumes and EC volumes are reported by
// each replica or shard holder, so only this aggregation counts a chunk once.
func totalCollectionFileCount(topologyInfo *master_pb.TopologyInfo) int64 {
var total int64
for _, stats := range collectCollectionStats(topologyInfo) {
total += stats.FileCount
}
return total
}
// getCollectionStats returns current collection statistics with caching
func (s *AdminServer) getCollectionStats() (map[string]collectionStats, error) {
now := time.Now()
+6 -31
View File
@@ -124,13 +124,6 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
}
if resp.TopologyInfo != nil {
// Dedupe EC volume file counts across the nodes that report
// shards for the same volume: every shard holder reports the
// same .ecx-derived file_count, so we keep the max and sum
// node-local tombstones.
ecFile := make(map[uint32]uint64)
ecDel := make(map[uint32]uint64)
// Process gRPC response
for _, dc := range resp.TopologyInfo.DataCenterInfos {
dataCenter := DataCenter{
@@ -149,7 +142,6 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
var totalVolumes int64
var totalMaxVolumes int64
var totalSize int64
var totalFiles int64
// Prefer the real physical disk capacity the volume server
// reports per disk; the slot-based estimate overstates capacity
// when maxVolumeCount is configured higher than the disk holds.
@@ -167,23 +159,14 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
// Sum up individual volume information
for _, volInfo := range diskInfo.VolumeInfos {
totalSize += int64(volInfo.Size)
totalFiles += int64(volInfo.FileCount)
}
// Sum up EC shard sizes on this node and collect
// volume-wide file/delete counts for later folding
// into topology.TotalFiles. ShardSizes is local to
// this node, so summing across nodes is correct;
// FileCount/DeleteCount are per-volume and must be
// deduped per volume id.
// ShardSizes is local to this node, so summing
// across nodes gives the physical footprint.
for _, ecShardInfo := range diskInfo.EcShardInfos {
for _, shardSize := range ecShardInfo.ShardSizes {
totalSize += shardSize
}
if ecShardInfo.FileCount > ecFile[ecShardInfo.Id] {
ecFile[ecShardInfo.Id] = ecShardInfo.FileCount
}
ecDel[ecShardInfo.Id] += ecShardInfo.DeleteCount
}
}
@@ -214,7 +197,6 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
rackObj.Nodes = append(rackObj.Nodes, vs)
topology.VolumeServers = append(topology.VolumeServers, vs)
topology.TotalVolumes += vs.Volumes
topology.TotalFiles += totalFiles
topology.TotalSize += totalSize
}
@@ -224,17 +206,10 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
topology.DataCenters = append(topology.DataCenters, dataCenter)
}
// Fold deduped EC file counts into the cluster total so the
// dashboard header does not drop after volumes are converted
// to erasure coding.
for vid, fc := range ecFile {
dc := ecDel[vid]
if fc >= dc {
topology.TotalFiles += int64(fc - dc)
} else {
glog.Warningf("ec volume %d: summed delete_count=%d exceeds file_count=%d; skipping from TotalFiles", vid, dc, fc)
}
}
// Chunk counts come from the shared collection aggregation, which
// nets out tombstones and counts a chunk once no matter how many
// volume replicas or EC shard holders report it.
topology.TotalChunks = totalCollectionFileCount(resp.TopologyInfo)
}
return nil
@@ -235,3 +235,96 @@ func TestCollectCollectionStatsECFileCountMaxDedupe(t *testing.T) {
t.Errorf("FileCount: got %d, want 6 (max across reporters)", got.FileCount)
}
}
// TestTotalCollectionFileCount verifies the cluster-wide chunk count counts a
// chunk once per replicated volume and per EC volume, and nets out deletes.
func TestTotalCollectionFileCount(t *testing.T) {
// Volume 1 has replication 001 (two copies), so both nodes report the same
// 101 chunks with 10 deleted: 91 live chunks in total, not 182 and not the
// 90 that halving each report would give.
replica := func() *master_pb.DiskInfo {
return &master_pb.DiskInfo{
VolumeInfos: []*master_pb.VolumeInformationMessage{
{
Id: 1,
Collection: "bucket-a",
ReplicaPlacement: 1,
FileCount: 101,
DeleteCount: 10,
},
},
}
}
// EC volume 2 has its 20 chunks reported by every shard holder.
ecShards := func(bits uint32, sizes []int64) *master_pb.DiskInfo {
return &master_pb.DiskInfo{
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
{
Id: 2,
Collection: "bucket-b",
EcIndexBits: bits,
ShardSizes: sizes,
FileCount: 20,
},
},
}
}
topo := &master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{
{
RackInfos: []*master_pb.RackInfo{
{
DataNodeInfos: []*master_pb.DataNodeInfo{
{DiskInfos: map[string]*master_pb.DiskInfo{
"disk1": replica(),
"disk2": ecShards((1<<0)|(1<<1), []int64{1, 1}),
}},
{DiskInfos: map[string]*master_pb.DiskInfo{
"disk1": replica(),
"disk2": ecShards((1<<2)|(1<<3), []int64{1, 1}),
}},
},
},
},
},
},
}
if got := totalCollectionFileCount(topo); got != 111 {
t.Errorf("totalCollectionFileCount: got %d, want 111 (91 replicated + 20 EC)", got)
}
}
// TestTotalCollectionFileCountUnderReplicated verifies a volume whose second
// replica has not reported yet still contributes its full live count.
func TestTotalCollectionFileCountUnderReplicated(t *testing.T) {
topo := &master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{
{
RackInfos: []*master_pb.RackInfo{
{
DataNodeInfos: []*master_pb.DataNodeInfo{
{DiskInfos: map[string]*master_pb.DiskInfo{
"disk1": {
VolumeInfos: []*master_pb.VolumeInformationMessage{
{
Id: 1,
Collection: "bucket-a",
ReplicaPlacement: 1,
FileCount: 50,
},
},
},
}},
},
},
},
},
},
}
if got := totalCollectionFileCount(topo); got != 50 {
t.Errorf("totalCollectionFileCount: got %d, want 50 (one replica reporting, not halved)", got)
}
}
+22 -13
View File
@@ -13,7 +13,7 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
var collections []CollectionInfo
var totalVolumes int
var totalEcVolumes int
var totalFiles int64
var totalChunks int64
var totalSize int64
collectionMap := make(map[string]*CollectionInfo)
@@ -46,7 +46,6 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
// Get or create collection info
if collection, exists := collectionMap[collectionName]; exists {
collection.VolumeCount++
collection.FileCount += int64(volInfo.FileCount)
collection.TotalSize += int64(volInfo.Size)
// Update data center if this collection spans multiple DCs
@@ -67,7 +66,6 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
}
totalVolumes++
totalFiles += int64(volInfo.FileCount)
totalSize += int64(volInfo.Size)
} else {
newCollection := CollectionInfo{
@@ -75,13 +73,11 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
DataCenter: dc.Id,
VolumeCount: 1,
EcVolumeCount: 0,
FileCount: int64(volInfo.FileCount),
TotalSize: int64(volInfo.Size),
DiskTypes: []string{diskType},
}
collectionMap[collectionName] = &newCollection
totalVolumes++
totalFiles += int64(volInfo.FileCount)
totalSize += int64(volInfo.Size)
}
}
@@ -133,7 +129,6 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
DataCenter: dc.Id,
VolumeCount: 0,
EcVolumeCount: 1,
FileCount: 0,
TotalSize: 0,
DiskTypes: []string{diskType},
}
@@ -146,6 +141,16 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
}
}
}
// Chunk counts come from the shared collection aggregation, which
// nets out tombstones and counts a chunk once no matter how many
// volume replicas or EC shard holders report it.
for collectionName, stats := range collectCollectionStats(resp.TopologyInfo) {
if collection, exists := collectionMap[collectionName]; exists {
collection.ChunkCount = stats.FileCount
totalChunks += stats.FileCount
}
}
}
return nil
@@ -173,7 +178,7 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
TotalCollections: 0,
TotalVolumes: 0,
TotalEcVolumes: 0,
TotalFiles: 0,
TotalChunks: 0,
TotalSize: 0,
LastUpdated: time.Now(),
}, nil
@@ -184,7 +189,7 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
TotalCollections: len(collections),
TotalVolumes: totalVolumes,
TotalEcVolumes: totalEcVolumes,
TotalFiles: totalFiles,
TotalChunks: totalChunks,
TotalSize: totalSize,
LastUpdated: time.Now(),
}, nil
@@ -208,7 +213,6 @@ func (s *AdminServer) GetCollectionDetails(collectionName string, page int, page
var regularVolumes []VolumeWithTopology
var ecVolumes []EcVolumeWithShards
var totalFiles int64
var totalSize int64
dataCenters := make(map[string]bool)
diskTypes := make(map[string]bool)
@@ -222,10 +226,15 @@ func (s *AdminServer) GetCollectionDetails(collectionName string, page int, page
regularVolumes = regularVolumeData.Volumes
totalSize = regularVolumeData.TotalSize
// Calculate total files from regular volumes
for _, vol := range regularVolumes {
totalFiles += int64(vol.FileCount)
// Chunk counts come from the shared collection aggregation, which nets out
// tombstones and counts a chunk once no matter how many volume replicas or
// EC shard holders report it. Fail rather than render a zero that reads
// like an empty collection.
stats, err := s.getCollectionStats()
if err != nil {
return nil, err
}
totalChunks := stats[collectionName].FileCount
// Collect data centers and disk types from regular volumes
for _, vol := range regularVolumes {
@@ -371,7 +380,7 @@ func (s *AdminServer) GetCollectionDetails(collectionName string, page int, page
EcVolumes: paginatedEcVolumes,
TotalVolumes: len(regularVolumes),
TotalEcVolumes: len(ecVolumes),
TotalFiles: totalFiles,
TotalChunks: totalChunks,
TotalSize: totalSize,
DataCenters: dcList,
DiskTypes: diskTypeList,
+4 -4
View File
@@ -18,7 +18,7 @@ type dashSample struct {
volumes float64
ecShards float64
diskUsed float64
files float64
chunks float64
tasks float64 // pending/assigned/in-progress maintenance tasks
workers float64
}
@@ -33,7 +33,7 @@ type DashboardTrends struct {
// Sparklines (raw <svg>) for the existing summary cards.
Volumes string `json:"-"`
Files string `json:"-"`
Chunks string `json:"-"`
DiskUsed string `json:"-"`
EcShards string `json:"-"`
@@ -61,7 +61,7 @@ func (s *AdminServer) recordDashboardSample() {
volumes: float64(topology.TotalVolumes),
ecShards: float64(ecShards),
diskUsed: float64(topology.TotalSize),
files: float64(topology.TotalFiles),
chunks: float64(topology.TotalChunks),
}
if s.maintenanceManager != nil {
if stats := s.maintenanceManager.GetStats(); stats != nil {
@@ -106,7 +106,7 @@ func (s *AdminServer) GetDashboardTrends() DashboardTrends {
return DashboardTrends{
Samples: len(samples),
Volumes: sparklineSVG(series(func(s dashSample) float64 { return s.volumes }), "#1cc88a"), // success
Files: sparklineSVG(series(func(s dashSample) float64 { return s.files }), "#36b9cc"), // info
Chunks: sparklineSVG(series(func(s dashSample) float64 { return s.chunks }), "#36b9cc"), // info
DiskUsed: sparklineSVG(series(func(s dashSample) float64 { return s.diskUsed }), "#f6c23e"), // warning
EcShards: sparklineSVG(series(func(s dashSample) float64 { return s.ecShards }), "#5a5c69"), // dark
Tasks: sparklineSVG(tasks, "#36b9cc"),
+8 -6
View File
@@ -14,9 +14,11 @@ type ClusterTopology struct {
DataCenters []DataCenter `json:"datacenters"`
VolumeServers []VolumeServer `json:"volume_servers"`
TotalVolumes int `json:"total_volumes"`
TotalFiles int64 `json:"total_files"`
TotalSize int64 `json:"total_size"`
UpdatedAt time.Time `json:"updated_at"`
// TotalChunks counts chunks stored in volumes, not filer entries: a file
// is split into one or more chunks.
TotalChunks int64 `json:"total_chunks"`
TotalSize int64 `json:"total_size"`
UpdatedAt time.Time `json:"updated_at"`
}
type MasterNode struct {
@@ -274,7 +276,7 @@ type CollectionInfo struct {
DataCenter string `json:"datacenter"`
VolumeCount int `json:"volume_count"`
EcVolumeCount int `json:"ec_volume_count"`
FileCount int64 `json:"file_count"`
ChunkCount int64 `json:"chunk_count"`
TotalSize int64 `json:"total_size"`
DiskTypes []string `json:"disk_types"`
}
@@ -285,7 +287,7 @@ type ClusterCollectionsData struct {
TotalCollections int `json:"total_collections"`
TotalVolumes int `json:"total_volumes"`
TotalEcVolumes int `json:"total_ec_volumes"`
TotalFiles int64 `json:"total_files"`
TotalChunks int64 `json:"total_chunks"`
TotalSize int64 `json:"total_size"`
LastUpdated time.Time `json:"last_updated"`
}
@@ -588,7 +590,7 @@ type CollectionDetailsData struct {
EcVolumes []EcVolumeWithShards `json:"ec_volumes"`
TotalVolumes int `json:"total_volumes"`
TotalEcVolumes int `json:"total_ec_volumes"`
TotalFiles int64 `json:"total_files"`
TotalChunks int64 `json:"total_chunks"`
TotalSize int64 `json:"total_size"`
DataCenters []string `json:"data_centers"`
DiskTypes []string `json:"disk_types"`
+1 -1
View File
@@ -577,7 +577,7 @@ func (h *AdminHandlers) getAdminData(r *http.Request) dash.AdminData {
return dash.AdminData{
Username: username,
TotalVolumes: 0,
TotalFiles: 0,
TotalChunks: 0,
TotalSize: 0,
MasterNodes: masterNodes,
VolumeServers: []dash.VolumeServer{},
+5 -5
View File
@@ -50,18 +50,18 @@ templ Admin(data dash.AdminData) {
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-info text-uppercase mb-1">
Total Files
<div class="text-xs font-weight-bold text-info text-uppercase mb-1" title="Chunks stored in volumes. A file is split into one or more chunks, so this is not the number of files.">
Total Chunks
</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">
{formatNumber(data.TotalFiles)}
{formatNumber(data.TotalChunks)}
</div>
</div>
<div class="col-auto">
<i class="fas fa-file fa-2x text-gray-300"></i>
<i class="fas fa-cubes fa-2x text-gray-300"></i>
</div>
</div>
@templ.Raw(data.Trends.Files)
@templ.Raw(data.Trends.Chunks)
</div>
</div>
</div>
+6 -6
View File
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1001
// templ: version: v0.3.1020
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -68,24 +68,24 @@ func Admin(data dash.AdminData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div></div><div class=\"col-xl-3 col-md-6 mb-4\"><div class=\"card border-left-info shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-info text-uppercase mb-1\">Total Files</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div></div><div class=\"col-xl-3 col-md-6 mb-4\"><div class=\"card border-left-info shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-info text-uppercase mb-1\" title=\"Chunks stored in volumes. A file is split into one or more chunks, so this is not the number of files.\">Total Chunks</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(formatNumber(data.TotalFiles))
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(formatNumber(data.TotalChunks))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 57, Col: 66}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 57, Col: 67}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div></div><div class=\"col-auto\"><i class=\"fas fa-file fa-2x text-gray-300\"></i></div></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div></div><div class=\"col-auto\"><i class=\"fas fa-cubes fa-2x text-gray-300\"></i></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.Raw(data.Trends.Files).Render(ctx, templ_7745c5c3_Buffer)
templ_7745c5c3_Err = templ.Raw(data.Trends.Chunks).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+20 -19
View File
@@ -87,15 +87,15 @@ templ ClusterCollections(data dash.ClusterCollectionsData) {
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
Total Files
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1" title="Chunks stored in volumes. A file is split into one or more chunks, so this is not the number of files.">
Total Chunks
</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">
{fmt.Sprintf("%d", data.TotalFiles)}
{fmt.Sprintf("%d", data.TotalChunks)}
</div>
</div>
<div class="col-auto">
<i class="fas fa-file fa-2x text-gray-300"></i>
<i class="fas fa-cubes fa-2x text-gray-300"></i>
</div>
</div>
</div>
@@ -139,7 +139,7 @@ templ ClusterCollections(data dash.ClusterCollectionsData) {
<th>Collection Name</th>
<th>Regular Volumes</th>
<th>EC Volumes</th>
<th>Files</th>
<th>Chunks</th>
<th>Size (Logical)</th>
<th>Disk Types</th>
<th>Actions</th>
@@ -179,8 +179,8 @@ templ ClusterCollections(data dash.ClusterCollectionsData) {
</td>
<td>
<div class="d-flex align-items-center">
<i class="fas fa-file me-2 text-muted"></i>
{fmt.Sprintf("%d", collection.FileCount)}
<i class="fas fa-cubes me-2 text-muted"></i>
{fmt.Sprintf("%d", collection.ChunkCount)}
</div>
</td>
<td>
@@ -209,7 +209,7 @@ templ ClusterCollections(data dash.ClusterCollectionsData) {
data-datacenter={collection.DataCenter}
data-volume-count={fmt.Sprintf("%d", collection.VolumeCount)}
data-ec-volume-count={fmt.Sprintf("%d", collection.EcVolumeCount)}
data-file-count={fmt.Sprintf("%d", collection.FileCount)}
data-chunk-count={fmt.Sprintf("%d", collection.ChunkCount)}
data-total-size={fmt.Sprintf("%d", collection.TotalSize)}
data-disk-types={formatDiskTypes(collection.DiskTypes)}>
<i class="fas fa-eye"></i>
@@ -262,7 +262,7 @@ templ ClusterCollections(data dash.ClusterCollectionsData) {
datacenter: button.getAttribute('data-datacenter'),
volumeCount: parseInt(button.getAttribute('data-volume-count')),
ecVolumeCount: parseInt(button.getAttribute('data-ec-volume-count')),
fileCount: parseInt(button.getAttribute('data-file-count')),
chunkCount: parseInt(button.getAttribute('data-chunk-count')),
totalSize: parseInt(button.getAttribute('data-total-size')),
diskTypes: button.getAttribute('data-disk-types')
};
@@ -311,10 +311,10 @@ templ ClusterCollections(data dash.ClusterCollectionsData) {
'<span>' + collection.ecVolumeCount.toLocaleString() + '</span>' +
'</div>' +
'</td></tr>' +
'<tr><td><strong>Total Files:</strong></td><td>' +
'<tr><td><strong>Total Chunks:</strong></td><td>' +
'<div class="d-flex align-items-center">' +
'<i class="fas fa-file me-2 text-muted"></i>' +
'<span>' + collection.fileCount.toLocaleString() + '</span>' +
'<i class="fas fa-cubes me-2 text-muted"></i>' +
'<span>' + collection.chunkCount.toLocaleString() + '</span>' +
'</div>' +
'</td></tr>' +
'<tr><td><strong>Total Size (Logical):</strong></td><td>' +
@@ -396,17 +396,18 @@ templ ClusterCollections(data dash.ClusterCollectionsData) {
return {
name: cells[0].textContent.trim(),
volumes: cells[1].textContent.trim(),
files: cells[2].textContent.trim(),
size: cells[3].textContent.trim(),
diskTypes: cells[4].textContent.trim()
ecVolumes: cells[2].textContent.trim(),
chunks: cells[3].textContent.trim(),
size: cells[4].textContent.trim(),
diskTypes: cells[5].textContent.trim()
};
}
return null;
}).filter(row => row !== null);
const csvContent = "data:text/csv;charset=utf-8," +
"Collection Name,Volumes,Files,Size,Disk Types\n" +
rows.map(r => '"' + r.name + '","' + r.volumes + '","' + r.files + '","' + r.size + '","' + r.diskTypes + '"').join("\n");
const csvContent = "data:text/csv;charset=utf-8," +
"Collection Name,Volumes,EC Volumes,Chunks,Size,Disk Types\n" +
rows.map(r => '"' + r.name + '","' + r.volumes + '","' + r.ecVolumes + '","' + r.chunks + '","' + r.size + '","' + r.diskTypes + '"').join("\n");
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1001
// templ: version: v0.3.1020
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -73,20 +73,20 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div><div class=\"col-auto\"><i class=\"fas fa-th-large fa-2x text-gray-300\"></i></div></div></div></div></div><div class=\"col-xl-2 col-lg-3 col-md-4 col-sm-6 mb-4\"><div class=\"card border-left-warning shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-warning text-uppercase mb-1\">Total Files</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div><div class=\"col-auto\"><i class=\"fas fa-th-large fa-2x text-gray-300\"></i></div></div></div></div></div><div class=\"col-xl-2 col-lg-3 col-md-4 col-sm-6 mb-4\"><div class=\"card border-left-warning shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-warning text-uppercase mb-1\" title=\"Chunks stored in volumes. A file is split into one or more chunks, so this is not the number of files.\">Total Chunks</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalFiles))
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalChunks))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 94, Col: 71}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 94, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div></div><div class=\"col-auto\"><i class=\"fas fa-file fa-2x text-gray-300\"></i></div></div></div></div></div><div class=\"col-xl-2 col-lg-3 col-md-4 col-sm-6 mb-4\"><div class=\"card border-left-secondary shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-secondary text-uppercase mb-1\">Total Storage Size (Logical)</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div></div><div class=\"col-auto\"><i class=\"fas fa-cubes fa-2x text-gray-300\"></i></div></div></div></div></div><div class=\"col-xl-2 col-lg-3 col-md-4 col-sm-6 mb-4\"><div class=\"card border-left-secondary shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-secondary text-uppercase mb-1\">Total Storage Size (Logical)</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -104,7 +104,7 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
if len(data.Collections) > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div class=\"table-responsive\"><table class=\"table table-hover\" id=\"collectionsTable\"><thead><tr><th>Collection Name</th><th>Regular Volumes</th><th>EC Volumes</th><th>Files</th><th>Size (Logical)</th><th>Disk Types</th><th>Actions</th></tr></thead> <tbody>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div class=\"table-responsive\"><table class=\"table table-hover\" id=\"collectionsTable\"><thead><tr><th>Collection Name</th><th>Regular Volumes</th><th>EC Volumes</th><th>Chunks</th><th>Size (Logical)</th><th>Disk Types</th><th>Actions</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -201,14 +201,14 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</div></a></td><td><div class=\"d-flex align-items-center\"><i class=\"fas fa-file me-2 text-muted\"></i> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</div></a></td><td><div class=\"d-flex align-items-center\"><i class=\"fas fa-cubes me-2 text-muted\"></i> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", collection.FileCount))
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", collection.ChunkCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 183, Col: 88}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 183, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
@@ -252,11 +252,11 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var15).String())
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var15).String())
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -289,11 +289,11 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(collection.Name)
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.ResolveAttributeValue(collection.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 208, Col: 78}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -302,11 +302,11 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(collection.DataCenter)
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.ResolveAttributeValue(collection.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 209, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var19)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -315,11 +315,11 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", collection.VolumeCount))
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", collection.VolumeCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 210, Col: 112}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var20)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -328,24 +328,24 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", collection.EcVolumeCount))
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", collection.EcVolumeCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 211, Col: 117}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\" data-file-count=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\" data-chunk-count=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", collection.FileCount))
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", collection.ChunkCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 212, Col: 108}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 212, Col: 110}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var22)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -354,11 +354,11 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", collection.TotalSize))
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", collection.TotalSize))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 213, Col: 108}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -367,11 +367,11 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(formatDiskTypes(collection.DiskTypes))
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.ResolveAttributeValue(formatDiskTypes(collection.DiskTypes))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_collections.templ`, Line: 214, Col: 106}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -403,7 +403,7 @@ func ClusterCollections(data dash.ClusterCollectionsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</small></div></div></div><!-- JavaScript for cluster collections functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle collection action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const collectionData = {\n name: button.getAttribute('data-name'),\n datacenter: button.getAttribute('data-datacenter'),\n volumeCount: parseInt(button.getAttribute('data-volume-count')),\n ecVolumeCount: parseInt(button.getAttribute('data-ec-volume-count')),\n fileCount: parseInt(button.getAttribute('data-file-count')),\n totalSize: parseInt(button.getAttribute('data-total-size')),\n diskTypes: button.getAttribute('data-disk-types')\n };\n showCollectionDetails(collectionData);\n break;\n }\n });\n });\n \n function showCollectionDetails(collection) {\n const modalHtml = '<div class=\"modal fade\" id=\"collectionDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-layer-group me-2\"></i>Collection Details: ' + collection.name + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Collection Name:</strong></td><td><code>' + collection.name + '</code></td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td>' +\n (collection.datacenter ? '<span class=\"badge bg-light text-dark\">' + collection.datacenter + '</span>' : '<span class=\"text-muted\">N/A</span>') +\n '</td></tr>' +\n '<tr><td><strong>Disk Types:</strong></td><td>' +\n (collection.diskTypes ? collection.diskTypes.split(', ').map(type => \n '<span class=\"badge bg-' + getDiskTypeBadgeColor(type) + ' me-1\">' + type + '</span>'\n ).join('') : '<span class=\"text-muted\">Unknown</span>') +\n '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Storage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Regular Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-database me-2 text-muted\"></i>' +\n '<span>' + collection.volumeCount.toLocaleString() + '</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>EC Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-th-large me-2 text-muted\"></i>' +\n '<span>' + collection.ecVolumeCount.toLocaleString() + '</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Total Files:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-file me-2 text-muted\"></i>' +\n '<span>' + collection.fileCount.toLocaleString() + '</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Total Size (Logical):</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-hdd me-2 text-muted\"></i>' +\n '<span>' + formatBytes(collection.totalSize) + '</span>' +\n '</div>' +\n '</td></tr>' +\n '</table>' +\n '</div>' +\n '</div>' +\n '<div class=\"row mt-3\">' +\n '<div class=\"col-12\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-link me-1\"></i>Quick Actions</h6>' +\n '<div class=\"d-grid gap-2 d-md-flex\">' +\n '<a href=\"' + (window.__BASE_PATH__ || '') + '/storage/volumes?collection=' + encodeURIComponent(collection.name) + '\" class=\"btn btn-outline-primary\">' +\n '<i class=\"fas fa-database me-1\"></i>View Volumes' +Line truncated
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</small></div></div></div><!-- JavaScript for cluster collections functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle collection action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const collectionData = {\n name: button.getAttribute('data-name'),\n datacenter: button.getAttribute('data-datacenter'),\n volumeCount: parseInt(button.getAttribute('data-volume-count')),\n ecVolumeCount: parseInt(button.getAttribute('data-ec-volume-count')),\n chunkCount: parseInt(button.getAttribute('data-chunk-count')),\n totalSize: parseInt(button.getAttribute('data-total-size')),\n diskTypes: button.getAttribute('data-disk-types')\n };\n showCollectionDetails(collectionData);\n break;\n }\n });\n });\n \n function showCollectionDetails(collection) {\n const modalHtml = '<div class=\"modal fade\" id=\"collectionDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-layer-group me-2\"></i>Collection Details: ' + collection.name + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Collection Name:</strong></td><td><code>' + collection.name + '</code></td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td>' +\n (collection.datacenter ? '<span class=\"badge bg-light text-dark\">' + collection.datacenter + '</span>' : '<span class=\"text-muted\">N/A</span>') +\n '</td></tr>' +\n '<tr><td><strong>Disk Types:</strong></td><td>' +\n (collection.diskTypes ? collection.diskTypes.split(', ').map(type => \n '<span class=\"badge bg-' + getDiskTypeBadgeColor(type) + ' me-1\">' + type + '</span>'\n ).join('') : '<span class=\"text-muted\">Unknown</span>') +\n '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Storage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Regular Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-database me-2 text-muted\"></i>' +\n '<span>' + collection.volumeCount.toLocaleString() + '</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>EC Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-th-large me-2 text-muted\"></i>' +\n '<span>' + collection.ecVolumeCount.toLocaleString() + '</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Total Chunks:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-cubes me-2 text-muted\"></i>' +\n '<span>' + collection.chunkCount.toLocaleString() + '</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Total Size (Logical):</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<i class=\"fas fa-hdd me-2 text-muted\"></i>' +\n '<span>' + formatBytes(collection.totalSize) + '</span>' +\n '</div>' +\n '</td></tr>' +\n '</table>' +\n '</div>' +\n '</div>' +\n '<div class=\"row mt-3\">' +\n '<div class=\"col-12\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-link me-1\"></i>Quick Actions</h6>' +\n '<div class=\"d-grid gap-2 d-md-flex\">' +\n '<a href=\"' + (window.__BASE_PATH__ || '') + '/storage/volumes?collection=' + encodeURIComponent(collection.name) + '\" class=\"btn btn-outline-primary\">' +\n '<i class=\"fas fa-database me-1\"></i>View VolumLine truncated
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+5 -5
View File
@@ -71,12 +71,12 @@ templ CollectionDetails(data dash.CollectionDetailsData) {
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h6 class="card-title">Total Files</h6>
<h4 class="mb-0">{fmt.Sprintf("%d", data.TotalFiles)}</h4>
<small>Files stored</small>
<h6 class="card-title">Total Chunks</h6>
<h4 class="mb-0">{fmt.Sprintf("%d", data.TotalChunks)}</h4>
<small>A file is split into one or more chunks</small>
</div>
<div class="align-self-center">
<i class="fas fa-file fa-2x"></i>
<i class="fas fa-cubes fa-2x"></i>
</div>
</div>
</div>
@@ -169,7 +169,7 @@ templ CollectionDetails(data dash.CollectionDetailsData) {
</a>
</th>
<th class="text-dark">Logical Size / Shard Count</th>
<th class="text-dark">Files</th>
<th class="text-dark">Chunks</th>
<th class="text-dark">Status</th>
<th class="text-dark">Actions</th>
</tr>
+20 -20
View File
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1001
// templ: version: v0.3.1020
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -113,20 +113,20 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</h4><small>Erasure coded volumes</small></div><div class=\"align-self-center\"><i class=\"fas fa-th-large fa-2x\"></i></div></div></div></div></div><div class=\"col-md-3\"><div class=\"card text-bg-success\"><div class=\"card-body\"><div class=\"d-flex justify-content-between\"><div><h6 class=\"card-title\">Total Files</h6><h4 class=\"mb-0\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</h4><small>Erasure coded volumes</small></div><div class=\"align-self-center\"><i class=\"fas fa-th-large fa-2x\"></i></div></div></div></div></div><div class=\"col-md-3\"><div class=\"card text-bg-success\"><div class=\"card-body\"><div class=\"d-flex justify-content-between\"><div><h6 class=\"card-title\">Total Chunks</h6><h4 class=\"mb-0\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalFiles))
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalChunks))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 75, Col: 59}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 75, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</h4><small>Files stored</small></div><div class=\"align-self-center\"><i class=\"fas fa-file fa-2x\"></i></div></div></div></div></div><div class=\"col-md-3\"><div class=\"card text-bg-warning\"><div class=\"card-body\"><div class=\"d-flex justify-content-between\"><div><h6 class=\"card-title\">Total Size (Logical)</h6><h4 class=\"mb-0\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</h4><small>A file is split into one or more chunks</small></div><div class=\"align-self-center\"><i class=\"fas fa-cubes fa-2x\"></i></div></div></div></div></div><div class=\"col-md-3\"><div class=\"card text-bg-warning\"><div class=\"card-body\"><div class=\"d-flex justify-content-between\"><div><h6 class=\"card-title\">Total Size (Logical)</h6><h4 class=\"mb-0\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -269,7 +269,7 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</a></th><th class=\"text-dark\">Logical Size / Shard Count</th><th class=\"text-dark\">Files</th><th class=\"text-dark\">Status</th><th class=\"text-dark\">Actions</th></tr></thead> <tbody>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</a></th><th class=\"text-dark\">Logical Size / Shard Count</th><th class=\"text-dark\">Chunks</th><th class=\"text-dark\">Status</th><th class=\"text-dark\">Actions</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -333,11 +333,11 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.Id))
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", volume.Id))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 206, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -346,11 +346,11 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(volume.Server)
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.ResolveAttributeValue(volume.Server)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 207, Col: 37}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var17)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -419,11 +419,11 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", ecVolume.VolumeID))
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", ecVolume.VolumeID))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 249, Col: 63}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -466,11 +466,11 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page-1))
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.Page-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 280, Col: 104}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -504,11 +504,11 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 291, Col: 95}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var25)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -547,11 +547,11 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page+1))
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.Page+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 306, Col: 104}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -560,11 +560,11 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 309, Col: 108}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+4
View File
@@ -3,6 +3,8 @@ package command
import (
"os"
"time"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
)
type MountOptions struct {
@@ -20,6 +22,7 @@ type MountOptions struct {
concurrentWriters *int
concurrentReaders *int
cacheMetaTtlSec *int
dirListCacheEntries *int
cacheDirForRead *string
cacheDirForWrite *string
cacheSizeMBForRead *int64
@@ -114,6 +117,7 @@ func init() {
mountOptions.cacheDirForWrite = cmdMount.Flag.String("cacheDirWrite", "", "buffer writes mostly for large files")
mountOptions.writeBufferSizeMB = cmdMount.Flag.Int64("writeBufferSizeMB", 0, "global cap on the per-mount write buffer (memory + swap) in MB, 0 means unlimited. Bounds /tmp growth when volume uploads stall")
mountOptions.cacheMetaTtlSec = cmdMount.Flag.Int("cacheMetaTtlSec", 60, "metadata cache validity seconds")
mountOptions.dirListCacheEntries = cmdMount.Flag.Int("dirListCacheEntries", meta_cache.DefaultListingCacheEntries, "directory children kept decoded in memory, so reopening a folder rereads nothing. A ceiling, not a reservation: only walked directories are held, at roughly half a kilobyte per child. 0 disables")
mountOptions.dataCenter = cmdMount.Flag.String("dataCenter", "", "prefer to write to the data center")
mountOptions.allowOthers = cmdMount.Flag.Bool("allowOthers", true, "allows other users to access the file system")
mountOptions.defaultPermissions = cmdMount.Flag.Bool("defaultPermissions", true, "enforce permissions by the operating system")
+1
View File
@@ -197,6 +197,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
CacheDirForWrite: p.cacheDirForWrite,
WriteBufferSizeMB: *option.writeBufferSizeMB,
CacheMetaTTlSec: *option.cacheMetaTtlSec,
DirListCacheEntries: *option.dirListCacheEntries,
DataCenter: *option.dataCenter,
Quota: int64(*option.collectionQuota) * 1024 * 1024,
LogicalDiskUsage: *option.logicalDiskUsage,
+213
View File
@@ -0,0 +1,213 @@
package filer
import (
"context"
"errors"
"fmt"
"sync"
"unicode/utf8"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// Field numbers from filer.proto. Only the ones this decoder has to recognise
// are named; every other Entry field is handed to the generated unmarshaller
// as-is.
const (
entryChunksField = 3 // Entry.chunks
fileChunkOffsetField = 2 // FileChunk.offset
fileChunkSizeField = 3 // FileChunk.size
)
// The chunk bytes are the one part of the blob the generated unmarshaller never
// sees, so the checks it would have made are made here instead: a submessage
// has to parse, and a proto3 string has to be valid UTF-8. Anything else in a
// FileChunk is a scalar, which walking it already validates.
// TestChunkValidationCoversEveryField fails if FileChunk gains a field of
// either kind that is missing from these.
var (
fileChunkMessageFields = map[protowire.Number]bool{
7: true, // fid, a FileId of scalars only, so walking it is a full check
8: true, // source_fid
}
fileChunkStringFields = map[protowire.Number]bool{
1: true, // file_id
5: true, // e_tag
6: true, // source_file_id
}
)
// attributesScratchPool holds the re-encoded entry, which is the blob minus its
// chunks and so much smaller than what came in.
var attributesScratchPool = sync.Pool{
New: func() any {
b := make([]byte, 0, 256)
return &b
},
}
// DecodeListedEntry decodes one listed entry, dropping the chunk list when the
// listing asked for attributes only.
func DecodeListedEntry(ctx context.Context, entry *Entry, blob []byte) error {
if filer_pb.ChunksOmitted(ctx) {
return entry.DecodeAttributesOnly(blob)
}
return entry.DecodeAttributesAndChunks(blob)
}
// DecodeAttributesOnly fills entry from blob without building its chunk list,
// which is the bulk of the work for anything but a tiny file. Chunks are still
// measured, because an entry whose stored FileSize is zero takes its size from
// them, but no FileChunk is allocated.
//
// entry.Chunks is left nil. The one exception is a hard link, whose attributes
// and chunks are replaced wholesale by a full decode of its own record in
// FilerStoreWrapper.maybeReadHardLink straight after the store listing. Only a
// caller that reads attributes and nothing else may use this.
func (entry *Entry) DecodeAttributesOnly(blob []byte) error {
// The scratch buffer is only taken once a chunk is actually found, so an
// entry with none — every directory, for one — neither re-encodes nor
// touches the pool, and is unmarshalled where it lies.
var scratchPtr *[]byte
var scratch []byte
defer func() {
if scratchPtr != nil {
*scratchPtr = scratch
attributesScratchPool.Put(scratchPtr)
}
}()
var chunkExtent uint64
attributes := blob
for pos := 0; pos < len(blob); {
rest := blob[pos:]
num, typ, tagLen := protowire.ConsumeTag(rest)
if tagLen < 0 {
return fmt.Errorf("decoding value blob for %s: %w", entry.FullPath, protowire.ParseError(tagLen))
}
var valLen int
if num == entryChunksField && typ == protowire.BytesType {
chunk, n := protowire.ConsumeBytes(rest[tagLen:])
if n < 0 {
return fmt.Errorf("decoding value blob for %s: %w", entry.FullPath, protowire.ParseError(n))
}
valLen = n
end, err := chunkExtentEnd(chunk)
if err != nil {
return fmt.Errorf("decoding value blob for %s: %w", entry.FullPath, err)
}
if end > chunkExtent {
chunkExtent = end
}
if scratchPtr == nil {
scratchPtr = attributesScratchPool.Get().(*[]byte)
scratch = append((*scratchPtr)[:0], blob[:pos]...)
}
} else {
valLen = protowire.ConsumeFieldValue(num, typ, rest[tagLen:])
if valLen < 0 {
return fmt.Errorf("decoding value blob for %s: %w", entry.FullPath, protowire.ParseError(valLen))
}
if scratchPtr != nil {
scratch = append(scratch, rest[:tagLen+valLen]...)
}
}
pos += tagLen + valLen
}
if scratchPtr != nil {
attributes = scratch
}
message := pbEntryPool.Get().(*filer_pb.Entry)
defer func() {
resetPbEntry(message)
pbEntryPool.Put(message)
}()
if err := proto.Unmarshal(attributes, message); err != nil {
return fmt.Errorf("decoding value blob for %s: %v", entry.FullPath, err)
}
FromPbEntryToExistingEntry(message, entry)
// FromPbEntryToExistingEntry took the size over a chunk list that is not
// there, so fold in what the chunks actually reached. This is TotalSize.
if chunkExtent > entry.FileSize {
entry.FileSize = chunkExtent
}
return nil
}
// chunkExtentEnd reports where one encoded FileChunk ends, the offset plus size
// that TotalSize maximises over, without building the chunk. A chunk this
// rejects is one the full decoder rejects too, so a listing never reports a
// size for an entry that cannot be opened.
//
// A manifest chunk needs no special handling: it carries the offset and size of
// the whole range it stands for, and TotalSize does not resolve it either.
func chunkExtentEnd(chunk []byte) (uint64, error) {
var offset int64
var size uint64
for len(chunk) > 0 {
num, typ, tagLen := protowire.ConsumeTag(chunk)
if tagLen < 0 {
return 0, protowire.ParseError(tagLen)
}
chunk = chunk[tagLen:]
if typ == protowire.VarintType && (num == fileChunkOffsetField || num == fileChunkSizeField) {
v, n := protowire.ConsumeVarint(chunk)
if n < 0 {
return 0, protowire.ParseError(n)
}
if num == fileChunkOffsetField {
offset = int64(v)
} else {
size = v
}
chunk = chunk[n:]
continue
}
if typ == protowire.BytesType {
v, n := protowire.ConsumeBytes(chunk)
if n < 0 {
return 0, protowire.ParseError(n)
}
if fileChunkMessageFields[num] {
if err := validateMessage(v); err != nil {
return 0, err
}
} else if fileChunkStringFields[num] && !utf8.Valid(v) {
return 0, errors.New("invalid UTF-8 in string field")
}
chunk = chunk[n:]
continue
}
n := protowire.ConsumeFieldValue(num, typ, chunk)
if n < 0 {
return 0, protowire.ParseError(n)
}
chunk = chunk[n:]
}
return uint64(offset + int64(size)), nil
}
// validateMessage walks an encoded message to check it parses, which is all the
// generated unmarshaller would do for one whose fields are scalars.
func validateMessage(b []byte) error {
for len(b) > 0 {
num, typ, tagLen := protowire.ConsumeTag(b)
if tagLen < 0 {
return protowire.ParseError(tagLen)
}
valLen := protowire.ConsumeFieldValue(num, typ, b[tagLen:])
if valLen < 0 {
return protowire.ParseError(valLen)
}
b = b[tagLen+valLen:]
}
return nil
}
+444
View File
@@ -0,0 +1,444 @@
package filer
import (
"fmt"
"math/rand"
"os"
"reflect"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
// decodeBothWays round-trips entry and returns what each decoder made of it.
func decodeBothWays(t *testing.T, entry *Entry) (full, attrsOnly Entry) {
t.Helper()
blob, err := entry.EncodeAttributesAndChunks()
if err != nil {
t.Fatalf("encode: %v", err)
}
full.FullPath = entry.FullPath
if err := full.DecodeAttributesAndChunks(blob); err != nil {
t.Fatalf("full decode: %v", err)
}
attrsOnly.FullPath = entry.FullPath
if err := attrsOnly.DecodeAttributesOnly(blob); err != nil {
t.Fatalf("attributes-only decode: %v", err)
}
return full, attrsOnly
}
// assertSameButChunks checks the two decoders agree on everything a listing
// reads. Chunks are the deliberate exception; size is not, because an entry can
// carry a zero FileSize and take its size from the chunks.
func assertSameButChunks(t *testing.T, full, attrsOnly Entry) {
t.Helper()
if attrsOnly.Chunks != nil {
t.Errorf("attributes-only decode built %d chunks, want none", len(attrsOnly.Chunks))
}
if full.FileSize != attrsOnly.FileSize {
t.Errorf("FileSize = %d, want %d", attrsOnly.FileSize, full.FileSize)
}
if full.Size() != attrsOnly.Size() {
t.Errorf("Size() = %d, want %d", attrsOnly.Size(), full.Size())
}
if !reflect.DeepEqual(full.Attr, attrsOnly.Attr) {
t.Errorf("Attr = %+v, want %+v", attrsOnly.Attr, full.Attr)
}
if string(full.HardLinkId) != string(attrsOnly.HardLinkId) {
t.Errorf("HardLinkId = %x, want %x", attrsOnly.HardLinkId, full.HardLinkId)
}
if full.HardLinkCounter != attrsOnly.HardLinkCounter {
t.Errorf("HardLinkCounter = %d, want %d", attrsOnly.HardLinkCounter, full.HardLinkCounter)
}
if string(full.Content) != string(attrsOnly.Content) {
t.Errorf("Content = %q, want %q", attrsOnly.Content, full.Content)
}
if full.Quota != attrsOnly.Quota {
t.Errorf("Quota = %d, want %d", attrsOnly.Quota, full.Quota)
}
if full.WORMEnforcedAtTsNs != attrsOnly.WORMEnforcedAtTsNs {
t.Errorf("WORMEnforcedAtTsNs = %d, want %d", attrsOnly.WORMEnforcedAtTsNs, full.WORMEnforcedAtTsNs)
}
if len(full.Extended) != len(attrsOnly.Extended) {
t.Errorf("Extended has %d keys, want %d", len(attrsOnly.Extended), len(full.Extended))
}
for k, v := range full.Extended {
if string(attrsOnly.Extended[k]) != string(v) {
t.Errorf("Extended[%q] = %q, want %q", k, attrsOnly.Extended[k], v)
}
}
if (full.Remote == nil) != (attrsOnly.Remote == nil) {
t.Errorf("Remote presence differs: %v vs %v", attrsOnly.Remote != nil, full.Remote != nil)
} else if full.Remote != nil && full.Remote.RemoteSize != attrsOnly.Remote.RemoteSize {
t.Errorf("Remote.RemoteSize = %d, want %d", attrsOnly.Remote.RemoteSize, full.Remote.RemoteSize)
}
}
func chunkAt(offset int64, size uint64, i int) *filer_pb.FileChunk {
return &filer_pb.FileChunk{
FileId: fmt.Sprintf("3,01637037d6%04d", i),
Offset: offset,
Size: size,
ModifiedTsNs: int64(1700000000+i) * 1e9,
ETag: "1a2b3c4d5e6f7890",
Fid: &filer_pb.FileId{VolumeId: uint32(3 + i), FileKey: uint64(i), Cookie: 0x1637037d},
CipherKey: []byte{1, 2, 3, 4},
}
}
func TestDecodeAttributesOnlyMatchesFullDecode(t *testing.T) {
now := time.Unix(1700000000, 123456789)
cases := []struct {
name string
entry *Entry
}{
{"no chunks", &Entry{
FullPath: util.FullPath("/d/plain"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, Ctime: now, Uid: 99, Gid: 100, FileSize: 12},
}},
{"directory", &Entry{
FullPath: util.FullPath("/d/sub"),
Attr: Attr{Mode: os.ModeDir | 0o755, Mtime: now, Crtime: now, Uid: 99, Gid: 100},
}},
{"one chunk", &Entry{
FullPath: util.FullPath("/d/one"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, Uid: 99, Gid: 100, FileSize: 4 << 20},
Chunks: []*filer_pb.FileChunk{chunkAt(0, 4<<20, 0)},
}},
// The S3 copy and multipart paths deliberately store a zero FileSize and
// let the chunks define it, so this is the case that forces the extent
// walk rather than just skipping the field.
{"zero FileSize, size comes from chunks", &Entry{
FullPath: util.FullPath("/d/zerosize"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, Uid: 99, Gid: 100, FileSize: 0},
Chunks: []*filer_pb.FileChunk{
chunkAt(0, 4<<20, 0), chunkAt(4<<20, 4<<20, 1), chunkAt(8<<20, 1234, 2),
},
}},
{"chunks out of order", &Entry{
FullPath: util.FullPath("/d/unordered"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, Uid: 99, Gid: 100},
Chunks: []*filer_pb.FileChunk{
chunkAt(8<<20, 99, 0), chunkAt(0, 4<<20, 1), chunkAt(4<<20, 4<<20, 2),
},
}},
{"stored FileSize larger than chunks", &Entry{
FullPath: util.FullPath("/d/sparse"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, Uid: 99, Gid: 100, FileSize: 1 << 30},
Chunks: []*filer_pb.FileChunk{chunkAt(0, 16, 0)},
}},
{"symlink", &Entry{
FullPath: util.FullPath("/d/link"),
Attr: Attr{Mode: os.ModeSymlink | 0o777, Mtime: now, Crtime: now, SymlinkTarget: "../target"},
}},
{"hard link", &Entry{
FullPath: util.FullPath("/d/hard"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now},
HardLinkId: HardLinkId([]byte{9, 8, 7, 6}),
HardLinkCounter: 3,
}},
{"inline content", &Entry{
FullPath: util.FullPath("/d/inline"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now},
Content: []byte("hello world"),
}},
{"extended attributes", &Entry{
FullPath: util.FullPath("/d/xattr"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now},
Extended: map[string][]byte{"a": []byte("1"), "b": []byte("2"), "Seaweed-X": []byte("y")},
}},
{"remote entry", &Entry{
FullPath: util.FullPath("/d/remote"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 5},
Remote: &filer_pb.RemoteEntry{RemoteSize: 4096, RemoteMtime: now.Unix() + 60, StorageName: "s3"},
}},
{"quota and worm", &Entry{
FullPath: util.FullPath("/d/bucket"),
Attr: Attr{Mode: os.ModeDir | 0o755, Mtime: now, Crtime: now},
Quota: 1 << 40,
WORMEnforcedAtTsNs: now.UnixNano(),
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
full, attrsOnly := decodeBothWays(t, tc.entry)
assertSameButChunks(t, full, attrsOnly)
})
}
}
// TestDecodeAttributesOnlyRandomEntries fuzzes the field combinations, since the
// decoder walks the wire format by hand and has to stay in step with the
// generated one as filer.proto grows.
func TestDecodeAttributesOnlyRandomEntries(t *testing.T) {
rnd := rand.New(rand.NewSource(1))
for i := 0; i < 2000; i++ {
now := time.Unix(1600000000+rnd.Int63n(1e8), rnd.Int63n(1e9))
entry := &Entry{
FullPath: util.FullPath(fmt.Sprintf("/d/f%d", i)),
Attr: Attr{
Mode: os.FileMode(rnd.Intn(0o777)),
Mtime: now, Crtime: now, Ctime: now,
Uid: uint32(rnd.Intn(70000)), Gid: uint32(rnd.Intn(70000)),
FileSize: uint64(rnd.Int63n(1 << 34)),
Inode: rnd.Uint64(),
Rdev: uint32(rnd.Intn(1 << 20)),
TtlSec: int32(rnd.Intn(1000)),
},
}
if rnd.Intn(2) == 0 {
entry.Attr.FileSize = 0
}
if rnd.Intn(4) == 0 {
entry.Content = make([]byte, rnd.Intn(64))
rnd.Read(entry.Content)
}
if rnd.Intn(4) == 0 {
entry.Extended = map[string][]byte{}
for k := 0; k < rnd.Intn(4); k++ {
entry.Extended[fmt.Sprintf("k%d", k)] = []byte(fmt.Sprintf("v%d", rnd.Intn(1000)))
}
}
if rnd.Intn(8) == 0 {
entry.Remote = &filer_pb.RemoteEntry{RemoteSize: rnd.Int63n(1 << 30), RemoteMtime: now.Unix() + int64(rnd.Intn(120)) - 60}
}
for c := 0; c < rnd.Intn(20); c++ {
entry.Chunks = append(entry.Chunks, chunkAt(rnd.Int63n(1<<30), uint64(rnd.Int63n(1<<22)), c))
}
full, attrsOnly := decodeBothWays(t, entry)
assertSameButChunks(t, full, attrsOnly)
}
}
func TestDecodeAttributesOnlyRejectsGarbage(t *testing.T) {
var entry Entry
entry.FullPath = util.FullPath("/d/bad")
if err := entry.DecodeAttributesOnly([]byte{0xff, 0xff, 0xff, 0xff}); err == nil {
t.Fatal("expected an error for a malformed blob")
}
}
func BenchmarkDecode(b *testing.B) {
now := time.Unix(1700000000, 0)
for _, n := range []int{0, 1, 4, 16, 64} {
entry := &Entry{
FullPath: util.FullPath("/images/image-00000001.jpg"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, Ctime: now, Uid: 99, Gid: 100, FileSize: uint64(n) * 4 << 20},
}
for i := 0; i < n; i++ {
entry.Chunks = append(entry.Chunks, chunkAt(int64(i)*4<<20, 4<<20, i))
}
blob, err := entry.EncodeAttributesAndChunks()
if err != nil {
b.Fatal(err)
}
b.Run(fmt.Sprintf("chunks=%d/decoder=full", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var out Entry
if err := out.DecodeAttributesAndChunks(blob); err != nil {
b.Fatal(err)
}
}
})
b.Run(fmt.Sprintf("chunks=%d/decoder=attrsonly", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var out Entry
if err := out.DecodeAttributesOnly(blob); err != nil {
b.Fatal(err)
}
}
})
}
}
// TestProtoEntryWithoutChunksKeepsSize covers the wire contract the filer's
// omit_chunks listing relies on: the size a client needs survives in the
// attributes once the chunk list is dropped, including for the entries that
// store a zero FileSize and take their size from the chunks.
func TestProtoEntryWithoutChunksKeepsSize(t *testing.T) {
now := time.Unix(1700000000, 0)
for _, storedSize := range []uint64{0, 7, 1 << 30} {
stored := &Entry{
FullPath: util.FullPath("/d/obj"),
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: storedSize},
Chunks: []*filer_pb.FileChunk{chunkAt(0, 4<<20, 0), chunkAt(4<<20, 1234, 1)},
}
blob, err := stored.EncodeAttributesAndChunks()
if err != nil {
t.Fatalf("encode: %v", err)
}
// What the filer holds after reading the entry out of its store.
var loaded Entry
loaded.FullPath = stored.FullPath
if err := loaded.DecodeAttributesAndChunks(blob); err != nil {
t.Fatalf("decode: %v", err)
}
want := FileSize(loaded.ToProtoEntry())
pbEntry := loaded.ToProtoEntry()
pbEntry.Chunks = nil
if got := FileSize(pbEntry); got != want {
t.Errorf("stored FileSize %d: size over the wire = %d, want %d", storedSize, got, want)
}
if got := FromPbEntry("/d", pbEntry).Size(); got != want {
t.Errorf("stored FileSize %d: size at the client = %d, want %d", storedSize, got, want)
}
}
}
// TestChunkValidationCoversEveryField keeps the hand-rolled chunk walk honest as
// filer.proto grows. The generated unmarshaller never sees the chunk bytes, so
// every FileChunk field whose contents it would have checked -- a submessage, or
// a proto3 string's UTF-8 -- has to be listed for the walk to check instead.
func TestChunkValidationCoversEveryField(t *testing.T) {
fields := (&filer_pb.FileChunk{}).ProtoReflect().Descriptor().Fields()
for i := 0; i < fields.Len(); i++ {
f := fields.Get(i)
switch f.Kind() {
case protoreflect.MessageKind, protoreflect.GroupKind:
if !fileChunkMessageFields[protowire.Number(f.Number())] {
t.Errorf("FileChunk.%s (field %d) is a message but is not in fileChunkMessageFields, so a corrupt one would pass the listing decoder and fail the full one", f.Name(), f.Number())
}
case protoreflect.StringKind:
if !fileChunkStringFields[protowire.Number(f.Number())] {
t.Errorf("FileChunk.%s (field %d) is a string but is not in fileChunkStringFields, so invalid UTF-8 would pass the listing decoder and fail the full one", f.Name(), f.Number())
}
}
}
}
// corruptChunkBlobs builds entry blobs whose chunk bytes are damaged in ways the
// generated unmarshaller rejects.
func corruptChunkBlobs(t *testing.T) map[string][]byte {
t.Helper()
now := time.Unix(1700000000, 0)
base := func() *filer_pb.FileChunk {
return &filer_pb.FileChunk{Offset: 0, Size: 1024, Fid: &filer_pb.FileId{VolumeId: 3, FileKey: 7, Cookie: 9}}
}
blobFor := func(mangle func(raw []byte) []byte) []byte {
chunk := base()
chunkBytes, err := proto.Marshal(chunk)
if err != nil {
t.Fatalf("marshal chunk: %v", err)
}
chunkBytes = mangle(chunkBytes)
var blob []byte
blob = protowire.AppendTag(blob, entryChunksField, protowire.BytesType)
blob = protowire.AppendBytes(blob, chunkBytes)
attrs, err := proto.Marshal(&filer_pb.FuseAttributes{FileSize: 0, Mtime: now.Unix(), FileMode: 0o644})
if err != nil {
t.Fatalf("marshal attrs: %v", err)
}
blob = protowire.AppendTag(blob, 4, protowire.BytesType)
return protowire.AppendBytes(blob, attrs)
}
out := map[string][]byte{}
// The exact probe from review: a nested fid whose payload is not a message.
out["corrupt nested fid"] = blobFor(func(raw []byte) []byte {
var b []byte
b = protowire.AppendTag(b, 2, protowire.VarintType)
b = protowire.AppendVarint(b, 0)
b = protowire.AppendTag(b, 3, protowire.VarintType)
b = protowire.AppendVarint(b, 1024)
b = protowire.AppendTag(b, 7, protowire.BytesType)
return protowire.AppendBytes(b, []byte{0xff, 0xff, 0xff, 0xff})
})
out["invalid utf8 in file_id"] = blobFor(func(raw []byte) []byte {
var b []byte
b = protowire.AppendTag(b, 1, protowire.BytesType)
b = protowire.AppendBytes(b, []byte{0xff, 0xfe, 0xfd})
b = protowire.AppendTag(b, 3, protowire.VarintType)
return protowire.AppendVarint(b, 1024)
})
out["truncated chunk"] = blobFor(func(raw []byte) []byte { return raw[:len(raw)-1] })
return out
}
// TestDecodeAttributesOnlyRejectsWhatFullDecodeRejects is the invariant that
// keeps a listing from showing a file that cannot then be opened: the fast path
// must never accept a blob the full decoder turns away.
func TestDecodeAttributesOnlyRejectsWhatFullDecodeRejects(t *testing.T) {
for name, blob := range corruptChunkBlobs(t) {
t.Run(name, func(t *testing.T) {
var full, attrsOnly Entry
full.FullPath = util.FullPath("/d/corrupt")
attrsOnly.FullPath = full.FullPath
fullErr := full.DecodeAttributesAndChunks(blob)
attrsErr := attrsOnly.DecodeAttributesOnly(blob)
if fullErr == nil {
t.Skip("full decoder accepts this blob, nothing to match")
}
if attrsErr == nil {
t.Errorf("full decode rejected the blob (%v) but attributes-only accepted it with FileSize=%d", fullErr, attrsOnly.FileSize)
}
})
}
}
// TestDecodeAttributesOnlyManifestChunk pins that a manifest chunk needs no
// resolving: it carries the offset and size of the range it stands for, and
// TotalSize does not resolve it either, so both decoders see one number.
func TestDecodeAttributesOnlyManifestChunk(t *testing.T) {
now := time.Unix(1700000000, 0)
manifest := chunkAt(0, 64<<20, 0)
manifest.IsChunkManifest = true
entry := &Entry{
FullPath: util.FullPath("/d/big"),
// Zero stored size, so the manifest's extent is the only source.
Attr: Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 0},
Chunks: []*filer_pb.FileChunk{manifest},
}
full, attrsOnly := decodeBothWays(t, entry)
assertSameButChunks(t, full, attrsOnly)
if attrsOnly.FileSize != 64<<20 {
t.Errorf("FileSize = %d, want %d from the manifest extent", attrsOnly.FileSize, 64<<20)
}
}
// TestDecodeAttributesOnlyFieldBeforeChunks exercises the prefix copy, which no
// other case reaches: EncodeAttributesAndChunks emits chunks before every field
// the other tests set, so `dropping` always turns on at pos 0 there.
func TestDecodeAttributesOnlyFieldBeforeChunks(t *testing.T) {
now := time.Unix(1700000000, 0)
attrs, err := proto.Marshal(&filer_pb.FuseAttributes{FileSize: 0, Mtime: now.Unix(), FileMode: 0o755})
if err != nil {
t.Fatalf("marshal attrs: %v", err)
}
chunkBytes, err := proto.Marshal(chunkAt(0, 4<<20, 0))
if err != nil {
t.Fatalf("marshal chunk: %v", err)
}
// is_directory (2) ahead of chunks (3), so the walk has a prefix to copy.
var blob []byte
blob = protowire.AppendTag(blob, 2, protowire.VarintType)
blob = protowire.AppendVarint(blob, 1)
blob = protowire.AppendTag(blob, entryChunksField, protowire.BytesType)
blob = protowire.AppendBytes(blob, chunkBytes)
blob = protowire.AppendTag(blob, 4, protowire.BytesType)
blob = protowire.AppendBytes(blob, attrs)
var full, attrsOnly Entry
full.FullPath = util.FullPath("/d/dirwithchunks")
attrsOnly.FullPath = full.FullPath
if err := full.DecodeAttributesAndChunks(blob); err != nil {
t.Fatalf("full decode: %v", err)
}
if err := attrsOnly.DecodeAttributesOnly(blob); err != nil {
t.Fatalf("attributes-only decode: %v", err)
}
assertSameButChunks(t, full, attrsOnly)
if attrsOnly.FileSize != 4<<20 {
t.Errorf("FileSize = %d, want %d", attrsOnly.FileSize, 4<<20)
}
}
+1 -1
View File
@@ -237,7 +237,7 @@ func (store *LevelDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dir
entry := &filer.Entry{
FullPath: weed_util.NewFullPath(string(dirPath), fileName),
}
if decodeErr := entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(iter.Value())); decodeErr != nil {
if decodeErr := filer.DecodeListedEntry(ctx, entry, weed_util.MaybeDecompressData(iter.Value())); decodeErr != nil {
err = decodeErr
glog.V(0).InfofCtx(ctx, "list %s : %v", entry.FullPath, err)
break
+6
View File
@@ -15,6 +15,10 @@ type DirEntrySink interface {
// AddEntryPlus is AddEntry for readdirplus, returning the attribute block
// to fill in, or nil once the sink is full.
AddEntryPlus(entry fuse.DirEntry) *fuse.EntryOut
// TakesLookupRef reports whether AddEntryPlus hands the sink a reference the
// mount must hold until a FORGET returns it.
TakesLookupRef() bool
}
// fuseDirEntryList adapts the kernel reply buffer to DirEntrySink.
@@ -30,6 +34,8 @@ func (l fuseDirEntryList) AddEntryPlus(entry fuse.DirEntry) *fuse.EntryOut {
return l.AddDirLookupEntry(entry)
}
func (l fuseDirEntryList) TakesLookupRef() bool { return true }
// ReadDirectoryInto runs a readdir against sink. ReadDir and ReadDirPlus are
// this with the kernel reply buffer as the sink.
func (wfs *WFS) ReadDirectoryInto(input *fuse.ReadIn, sink DirEntrySink, isPlusMode bool) fuse.Status {
@@ -111,6 +111,7 @@ func TestReadUncachedRemoteEntryDoesNotDeadlock(t *testing.T) {
wfs.fhLockTable.ReleaseLock(fh.fh, lock)
},
nil,
meta_cache.DefaultListingCacheEntries,
)
wfs.inodeToPath.MarkChildrenCached(root)
wfs.inodeToPath.Lookup(util.FullPath("/dir"), time.Now().Unix(), true, false, 0, false)
+29
View File
@@ -137,6 +137,35 @@ func (i *InodeToPath) Lookup(path util.FullPath, unixTime int64, isDirectory boo
return inode
}
// IncrementNlookup takes one more reference on an inode already in the table,
// reporting false if it is not there.
func (i *InodeToPath) IncrementNlookup(inode uint64) bool {
i.Lock()
defer i.Unlock()
entry, found := i.inode2path[inode]
if !found {
return false
}
entry.nlookup++
return true
}
// InodeForListing returns the inode number a readdir should report for path
// without entering it in the table. Nothing is reserved, so the collision probe
// Lookup does is skipped: the worst case is a repeated st_ino in one listing.
func (i *InodeToPath) InodeForListing(path util.FullPath, unixTime int64, possibleInode uint64) uint64 {
i.RLock()
inode, found := i.path2inode[path]
i.RUnlock()
if found {
return inode
}
if possibleInode != 0 {
return possibleInode
}
return path.AsInode(unixTime)
}
func (i *InodeToPath) AllocateInode(path util.FullPath, unixTime int64) uint64 {
if path == "/" {
return 1
+195
View File
@@ -0,0 +1,195 @@
package meta_cache
import (
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// DefaultListingCacheEntries is how many directory children the mount will hold
// decoded in memory across every cached listing.
//
// This is a ceiling, not a reservation: nothing is held for a directory that was
// never walked, so a mount over ordinary directories never approaches it. A
// chunkless child measured about 480 bytes, so reaching the default means
// holding something near 450MB, and a mount that wants a tighter bound should
// lower it rather than rely on never walking that far.
const DefaultListingCacheEntries = 1000000
// listingCache keeps directories that have been walked all the way through, so
// walking one again costs no store reads and no decoding. It holds only what the
// meta cache already holds, and is void the moment that is: every store write
// goes through one of a handful of methods, and each drops the directory it
// touched.
//
// The entries are shared with whoever listed them, and are never written to
// after publication.
type listingCache struct {
mu sync.Mutex
maxTotal int
total int
listings map[util.FullPath]*cachedListing
// builds are the walks in progress. A walk publishes only if its build is
// still the live one for that directory when it finishes, so a write landing
// halfway through cannot leave a stale listing behind.
builds map[util.FullPath]*listingBuild
}
type cachedListing struct {
entries []*filer.Entry
lastAccess time.Time
}
type listingBuild struct {
entries []*filer.Entry
// nextStart is the name the next page has to begin at for this build to be
// a continuation rather than a different walk.
nextStart string
}
func newListingCache(maxTotal int) *listingCache {
return &listingCache{
maxTotal: maxTotal,
listings: make(map[util.FullPath]*cachedListing),
builds: make(map[util.FullPath]*listingBuild),
}
}
func (lc *listingCache) enabled() bool { return lc != nil && lc.maxTotal > 0 }
// lookup returns a directory's complete listing.
func (lc *listingCache) lookup(dirPath util.FullPath) ([]*filer.Entry, bool) {
if !lc.enabled() {
return nil, false
}
lc.mu.Lock()
defer lc.mu.Unlock()
cached, found := lc.listings[dirPath]
if !found {
return nil, false
}
cached.lastAccess = time.Now()
return cached.entries, true
}
// invalidate drops a directory's listing and kills any walk building one. Called
// for every write the meta cache makes, so it has to stay cheap on a miss.
func (lc *listingCache) invalidate(dirPath util.FullPath) {
if !lc.enabled() {
return
}
lc.mu.Lock()
defer lc.mu.Unlock()
lc.dropLocked(dirPath)
delete(lc.builds, dirPath)
}
// invalidateChild drops the listing of the directory holding path.
func (lc *listingCache) invalidateChild(path util.FullPath) {
if !lc.enabled() {
return
}
dir, _ := path.DirAndName()
lc.invalidate(util.FullPath(dir))
}
func (lc *listingCache) invalidateAll() {
if !lc.enabled() {
return
}
lc.mu.Lock()
defer lc.mu.Unlock()
lc.listings = make(map[util.FullPath]*cachedListing)
lc.builds = make(map[util.FullPath]*listingBuild)
lc.total = 0
}
func (lc *listingCache) dropLocked(dirPath util.FullPath) {
if cached, found := lc.listings[dirPath]; found {
lc.total -= len(cached.entries)
delete(lc.listings, dirPath)
}
}
// beginOrContinue reports the build a page belongs to, or nil when this page is
// not the next step of a walk from the directory's first child. Only a walk that
// covers every child in order can be published.
func (lc *listingCache) beginOrContinue(dirPath util.FullPath, startFileName string, includeStartFile bool) *listingBuild {
if !lc.enabled() || includeStartFile {
return nil
}
lc.mu.Lock()
defer lc.mu.Unlock()
if startFileName == "" {
build := &listingBuild{}
lc.builds[dirPath] = build
return build
}
build, found := lc.builds[dirPath]
if !found || build.nextStart != startFileName {
// A seek, a second walk at a different position, or a page that follows
// one this build never saw. Neither walk can be trusted to be complete.
delete(lc.builds, dirPath)
return nil
}
return build
}
// carry keeps a build alive for the next page.
func (lc *listingCache) carry(dirPath util.FullPath, build *listingBuild, nextStart string) {
if build == nil {
return
}
lc.mu.Lock()
defer lc.mu.Unlock()
if lc.builds[dirPath] != build {
return // invalidated mid-walk
}
build.nextStart = nextStart
}
// publish installs a completed walk, unless a write invalidated it on the way or
// it does not fit. Dropping is always safe: the next walk reads the store.
func (lc *listingCache) publish(dirPath util.FullPath, build *listingBuild) {
if build == nil {
return
}
lc.mu.Lock()
defer lc.mu.Unlock()
if lc.builds[dirPath] != build {
return
}
delete(lc.builds, dirPath)
if len(build.entries) > lc.maxTotal {
return
}
lc.dropLocked(dirPath)
lc.evictLocked(len(build.entries))
lc.listings[dirPath] = &cachedListing{entries: build.entries, lastAccess: time.Now()}
lc.total += len(build.entries)
}
// evictLocked makes room for want entries, oldest use first.
func (lc *listingCache) evictLocked(want int) {
for lc.total+want > lc.maxTotal && len(lc.listings) > 0 {
var oldestPath util.FullPath
var oldest time.Time
for path, cached := range lc.listings {
if oldest.IsZero() || cached.lastAccess.Before(oldest) {
oldestPath, oldest = path, cached.lastAccess
}
}
lc.dropLocked(oldestPath)
}
}
func (lc *listingCache) size() (dirs, entries int) {
if !lc.enabled() {
return 0, 0
}
lc.mu.Lock()
defer lc.mu.Unlock()
return len(lc.listings), lc.total
}
+330
View File
@@ -0,0 +1,330 @@
package meta_cache
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func newListingTestCache(t *testing.T, maxEntries int) *MetaCache {
t.Helper()
uidGidMapper, err := NewUidGidMapper("", "")
if err != nil {
t.Fatalf("uid/gid mapper: %v", err)
}
cached := map[util.FullPath]bool{}
mc := NewMetaCache(t.TempDir(), uidGidMapper, util.FullPath("/"), false,
func(p util.FullPath) { cached[p] = true },
func(p util.FullPath) bool { return cached[p] },
func(EntryInvalidation) {}, nil, maxEntries)
t.Cleanup(mc.Shutdown)
return mc
}
func seedDir(t *testing.T, mc *MetaCache, dir util.FullPath, names ...string) {
t.Helper()
now := time.Now()
ctx := context.Background()
if err := mc.InsertEntry(ctx, &filer.Entry{
FullPath: dir, Attr: filer.Attr{Mode: os.ModeDir | 0o755, Mtime: now, Crtime: now},
}, 0); err != nil {
t.Fatalf("insert dir: %v", err)
}
for _, name := range names {
if err := mc.InsertEntry(ctx, &filer.Entry{
FullPath: dir.Child(name), Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 1},
}, 0); err != nil {
t.Fatalf("insert %s: %v", name, err)
}
}
mc.markCachedFn(util.FullPath("/"))
mc.markCachedFn(dir)
}
// walk lists a directory to exhaustion in pages, returning the names seen.
func walk(t *testing.T, mc *MetaCache, ctx context.Context, dir util.FullPath, pageSize int64) []string {
t.Helper()
var seen []string
start := ""
for round := 0; round < 100; round++ {
count := 0
last, err := mc.ListDirectoryEntries(ctx, dir, start, false, pageSize, func(entry *filer.Entry) (bool, error) {
seen = append(seen, entry.Name())
count++
return true, nil
})
if err != nil {
t.Fatalf("list: %v", err)
}
if last == "" || last == start {
break
}
start = last
if int64(count) < pageSize && count == 0 {
break
}
}
return seen
}
func listingCtx() context.Context { return filer_pb.WithChunksOmitted(context.Background()) }
func TestListingCacheServesAfterFullWalk(t *testing.T) {
mc := newListingTestCache(t, DefaultListingCacheEntries)
dir := util.FullPath("/d")
seedDir(t, mc, dir, "a", "b", "c")
if got := walk(t, mc, listingCtx(), dir, 100); len(got) != 3 {
t.Fatalf("first walk listed %v, want 3 entries", got)
}
dirs, entries := mc.ListingCacheSize()
if dirs != 1 || entries != 3 {
t.Fatalf("cache holds %d dirs / %d entries, want 1/3", dirs, entries)
}
if got := walk(t, mc, listingCtx(), dir, 100); len(got) != 3 {
t.Fatalf("second walk listed %v, want the same 3", got)
}
}
func TestListingCacheNotUsedWithoutChunksOmitted(t *testing.T) {
mc := newListingTestCache(t, DefaultListingCacheEntries)
dir := util.FullPath("/d")
seedDir(t, mc, dir, "a", "b")
// A listing that wants chunks must neither fill nor read the cache, since
// the cached entries were decoded without them.
if got := walk(t, mc, context.Background(), dir, 100); len(got) != 2 {
t.Fatalf("listed %v, want 2", got)
}
if dirs, _ := mc.ListingCacheSize(); dirs != 0 {
t.Fatalf("cache holds %d dirs, want none", dirs)
}
}
func TestListingCachePartialWalkIsNotCached(t *testing.T) {
mc := newListingTestCache(t, DefaultListingCacheEntries)
dir := util.FullPath("/d")
seedDir(t, mc, dir, "a", "b", "c", "d")
// Caller stops after the first entry: the rest of the directory was never
// seen, so nothing may be published.
if _, err := mc.ListDirectoryEntries(listingCtx(), dir, "", false, 100, func(entry *filer.Entry) (bool, error) {
return false, nil
}); err != nil {
t.Fatalf("list: %v", err)
}
if dirs, entries := mc.ListingCacheSize(); dirs != 0 {
t.Fatalf("cache holds %d dirs / %d entries after a stopped walk, want none", dirs, entries)
}
}
func TestListingCacheSeekDoesNotBuild(t *testing.T) {
mc := newListingTestCache(t, DefaultListingCacheEntries)
dir := util.FullPath("/d")
seedDir(t, mc, dir, "a", "b", "c")
// Starting partway through is not a walk of the whole directory.
if _, err := mc.ListDirectoryEntries(listingCtx(), dir, "a", false, 100, func(entry *filer.Entry) (bool, error) {
return true, nil
}); err != nil {
t.Fatalf("list: %v", err)
}
if dirs, _ := mc.ListingCacheSize(); dirs != 0 {
t.Fatalf("cache holds %d dirs after a mid-directory listing, want none", dirs)
}
}
func TestListingCacheInvalidation(t *testing.T) {
dir := util.FullPath("/d")
now := time.Now()
cases := []struct {
name string
mutate func(t *testing.T, mc *MetaCache)
}{
{"insert a child", func(t *testing.T, mc *MetaCache) {
if err := mc.InsertEntry(context.Background(), &filer.Entry{
FullPath: dir.Child("new"), Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: now},
}, 0); err != nil {
t.Fatal(err)
}
}},
{"update a child", func(t *testing.T, mc *MetaCache) {
if err := mc.UpdateEntry(context.Background(), &filer.Entry{
FullPath: dir.Child("a"), Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 99},
}); err != nil {
t.Fatal(err)
}
}},
{"delete a child", func(t *testing.T, mc *MetaCache) {
if err := mc.DeleteEntry(context.Background(), dir.Child("a")); err != nil {
t.Fatal(err)
}
}},
{"delete the children", func(t *testing.T, mc *MetaCache) {
if err := mc.DeleteFolderChildren(context.Background(), dir); err != nil {
t.Fatal(err)
}
}},
{"rename into the directory", func(t *testing.T, mc *MetaCache) {
if err := mc.AtomicUpdateEntryFromFiler(context.Background(), "", &filer.Entry{
FullPath: dir.Child("moved"), Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: now},
}); err != nil {
t.Fatal(err)
}
}},
{"purge the children", func(t *testing.T, mc *MetaCache) {
mc.PurgeDirectoryChildren(dir, func() {})
}},
{"distrust everything", func(t *testing.T, mc *MetaCache) {
mc.InvalidateAllListings()
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mc := newListingTestCache(t, DefaultListingCacheEntries)
seedDir(t, mc, dir, "a", "b", "c")
walk(t, mc, listingCtx(), dir, 100)
if dirs, _ := mc.ListingCacheSize(); dirs != 1 {
t.Fatalf("expected the walk to cache the directory, got %d dirs", dirs)
}
tc.mutate(t, mc)
if dirs, entries := mc.ListingCacheSize(); dirs != 0 {
t.Errorf("cache still holds %d dirs / %d entries after %s", dirs, entries, tc.name)
}
})
}
}
func TestListingCacheSeesAWriteThatLandsMidWalk(t *testing.T) {
mc := newListingTestCache(t, DefaultListingCacheEntries)
dir := util.FullPath("/d")
seedDir(t, mc, dir, "a", "b", "c", "d")
ctx := listingCtx()
// First page of a two-page walk.
last, err := mc.ListDirectoryEntries(ctx, dir, "", false, 2, func(entry *filer.Entry) (bool, error) {
return true, nil
})
if err != nil {
t.Fatalf("list: %v", err)
}
// A write lands before the walk finishes.
if err := mc.InsertEntry(context.Background(), &filer.Entry{
FullPath: dir.Child("e"), Attr: filer.Attr{Mode: 0o644, Mtime: time.Now(), Crtime: time.Now()},
}, 0); err != nil {
t.Fatal(err)
}
// Finishing the walk must not publish what it started collecting.
if _, err := mc.ListDirectoryEntries(ctx, dir, last, false, 100, func(entry *filer.Entry) (bool, error) {
return true, nil
}); err != nil {
t.Fatalf("list: %v", err)
}
if dirs, entries := mc.ListingCacheSize(); dirs != 0 {
t.Fatalf("published %d dirs / %d entries from a walk a write interrupted", dirs, entries)
}
// A fresh walk sees all five.
if got := walk(t, mc, ctx, dir, 100); len(got) != 5 {
t.Fatalf("walk listed %v, want 5 entries", got)
}
}
func TestListingCacheAppliesExpiryOnServe(t *testing.T) {
mc := newListingTestCache(t, DefaultListingCacheEntries)
dir := util.FullPath("/d")
now := time.Now()
ctx := context.Background()
if err := mc.InsertEntry(ctx, &filer.Entry{
FullPath: dir, Attr: filer.Attr{Mode: os.ModeDir | 0o755, Mtime: now, Crtime: now},
}, 0); err != nil {
t.Fatal(err)
}
// "b" expires two seconds from now; nothing will write when it does.
for _, e := range []struct {
name string
ttlSec int32
crtime time.Time
}{{"a", 0, now}, {"b", 2, now}, {"c", 0, now}} {
if err := mc.InsertEntry(ctx, &filer.Entry{
FullPath: dir.Child(e.name),
Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: e.crtime, TtlSec: e.ttlSec},
}, 0); err != nil {
t.Fatal(err)
}
}
mc.markCachedFn(util.FullPath("/"))
mc.markCachedFn(dir)
if got := walk(t, mc, listingCtx(), dir, 100); len(got) != 3 {
t.Fatalf("first walk listed %v, want 3", got)
}
// Age "b" past its TTL in place, the way the clock would, and confirm the
// cached listing stops reporting it without anything invalidating.
entry, _, err := mc.FindEntry(ctx, dir.Child("b"))
if err != nil {
t.Fatalf("find: %v", err)
}
entry.Crtime = now.Add(-time.Hour)
cachedEntries, found := mc.listings.lookup(dir)
if !found {
t.Fatal("expected the directory to be cached")
}
for _, e := range cachedEntries {
if e.Name() == "b" {
e.Crtime = now.Add(-time.Hour)
}
}
got := walk(t, mc, listingCtx(), dir, 100)
for _, name := range got {
if name == "b" {
t.Fatalf("expired entry still listed: %v", got)
}
}
if len(got) != 2 {
t.Fatalf("listed %v, want a and c", got)
}
}
func TestListingCacheEvictsToStayWithinBudget(t *testing.T) {
mc := newListingTestCache(t, 6)
ctx := listingCtx()
for d := 0; d < 4; d++ {
dir := util.FullPath(fmt.Sprintf("/d%d", d))
seedDir(t, mc, dir, "a", "b", "c")
if got := walk(t, mc, ctx, dir, 100); len(got) != 3 {
t.Fatalf("%s listed %v, want 3", dir, got)
}
_, entries := mc.ListingCacheSize()
if entries > 6 {
t.Fatalf("cache holds %d entries, over the 6 budget", entries)
}
}
dirs, entries := mc.ListingCacheSize()
if dirs != 2 || entries != 6 {
t.Fatalf("cache holds %d dirs / %d entries, want 2/6 after eviction", dirs, entries)
}
}
func TestListingCacheDisabled(t *testing.T) {
mc := newListingTestCache(t, 0)
dir := util.FullPath("/d")
seedDir(t, mc, dir, "a", "b")
if got := walk(t, mc, listingCtx(), dir, 100); len(got) != 2 {
t.Fatalf("listed %v, want 2", got)
}
if dirs, entries := mc.ListingCacheSize(); dirs != 0 || entries != 0 {
t.Fatalf("disabled cache holds %d dirs / %d entries", dirs, entries)
}
}
+153 -22
View File
@@ -5,6 +5,7 @@ import (
"errors"
"math"
"os"
"sort"
"sync"
"time"
@@ -43,6 +44,11 @@ type MetaCache struct {
dedupRing dedupRingBuffer
includeSystemEntries bool
// listings holds directories walked all the way through, so walking one
// again reads and decodes nothing. Every store write drops the directory it
// touched; see the storeX wrappers.
listings *listingCache
// dirVersionFloors is each cached directory's listing snapshot: the
// version of every child the listing covered, present or absent, unless
// a later event gave that child its own record. One map write per build
@@ -101,8 +107,10 @@ type metadataApplyRequest struct {
done chan error
}
// listingCacheEntries sizes the directory listing cache; zero disables it.
func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPath, includeSystemEntries bool,
markCachedFn func(path util.FullPath), isCachedFn func(path util.FullPath) bool, invalidateFunc func(EntryInvalidation), onDirectoryUpdate func(dir util.FullPath)) *MetaCache {
markCachedFn func(path util.FullPath), isCachedFn func(path util.FullPath) bool, invalidateFunc func(EntryInvalidation), onDirectoryUpdate func(dir util.FullPath),
listingCacheEntries int) *MetaCache {
leveldbStore, virtualStore := openMetaStore(dbFolder)
mc := &MetaCache{
root: root,
@@ -119,6 +127,7 @@ func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPat
buildingDirs: make(map[util.FullPath]*directoryBuildState),
dedupRing: newDedupRingBuffer(),
dirVersionFloors: make(map[util.FullPath]int64),
listings: newListingCache(listingCacheEntries),
}
mc.invalidateWorker = util.NewAsyncBatchWorker(func(batch []EntryInvalidation) {
for _, invalidation := range batch {
@@ -157,7 +166,7 @@ func (mc *MetaCache) InsertEntry(ctx context.Context, entry *filer.Entry, versio
}
func (mc *MetaCache) doInsertEntry(ctx context.Context, entry *filer.Entry, versionTsNs int64) error {
if err := mc.localStore.InsertEntry(ctx, entry); err != nil {
if err := mc.storeInsertEntry(ctx, entry); err != nil {
return err
}
mc.setEntryVersionLocked(ctx, entry.FullPath, versionTsNs)
@@ -187,7 +196,7 @@ func (mc *MetaCache) atomicUpdateEntryFromFilerLocked(ctx context.Context, oldPa
if entry != nil && vacatingOldPath {
ctx = context.WithValue(ctx, "OP", "MV")
glog.V(3).Infof("DeleteEntry %s", oldPath)
if err := mc.localStore.DeleteEntry(ctx, oldPath); err != nil {
if err := mc.storeDeleteEntry(ctx, oldPath); err != nil {
return err
}
}
@@ -209,7 +218,7 @@ func (mc *MetaCache) atomicUpdateEntryFromFilerLocked(ctx context.Context, oldPa
newDir, _ := newEntry.DirAndName()
if allowUncachedInsert || mc.isCachedFn(util.FullPath(newDir)) {
glog.V(3).Infof("InsertEntry %s/%s", newDir, newEntry.Name())
if err := mc.localStore.InsertEntry(ctx, newEntry); err != nil {
if err := mc.storeInsertEntry(ctx, newEntry); err != nil {
return err
}
mc.setEntryVersionLocked(ctx, newEntry.FullPath, versionTsNs)
@@ -230,11 +239,11 @@ func (mc *MetaCache) purgeEntryLocked(ctx context.Context, fullpath util.FullPat
if fullpath == "" {
return nil
}
if err := mc.localStore.DeleteEntry(ctx, fullpath); err != nil {
if err := mc.storeDeleteEntry(ctx, fullpath); err != nil {
return err
}
if isDirectory {
if err := mc.localStore.DeleteFolderChildren(ctx, fullpath); err != nil {
if err := mc.storeDeleteFolderChildren(ctx, fullpath); err != nil {
return err
}
}
@@ -303,7 +312,10 @@ func (mc *MetaCache) applyMetadataResponseEnqueue(ctx context.Context, resp *fil
}
}
// BeginDirectoryBuild drops the cached listing: a rebuild replaces the whole
// child set, and nothing may be served from the old one meanwhile.
func (mc *MetaCache) BeginDirectoryBuild(ctx context.Context, dirPath util.FullPath) error {
mc.listings.invalidate(dirPath)
return mc.enqueueAndWait(ctx, metadataApplyRequest{
kind: metadataBeginBuild,
buildPath: dirPath,
@@ -311,6 +323,7 @@ func (mc *MetaCache) BeginDirectoryBuild(ctx context.Context, dirPath util.FullP
}
func (mc *MetaCache) CompleteDirectoryBuild(ctx context.Context, dirPath util.FullPath, snapshotTsNs int64) error {
mc.listings.invalidate(dirPath)
return mc.enqueueAndWait(ctx, metadataApplyRequest{
kind: metadataCompleteBuild,
buildPath: dirPath,
@@ -319,6 +332,7 @@ func (mc *MetaCache) CompleteDirectoryBuild(ctx context.Context, dirPath util.Fu
}
func (mc *MetaCache) AbortDirectoryBuild(ctx context.Context, dirPath util.FullPath) error {
mc.listings.invalidate(dirPath)
return mc.enqueueAndWait(ctx, metadataApplyRequest{
kind: metadataAbortBuild,
buildPath: dirPath,
@@ -330,6 +344,7 @@ func (mc *MetaCache) AbortDirectoryBuild(ctx context.Context, dirPath util.FullP
// like kernel Forget don't block; see purgeDirectoryChildrenNow for why off-loop
// callers must route through here rather than wiping the store directly.
func (mc *MetaCache) PurgeDirectoryChildren(dirPath util.FullPath, resetFn func()) {
mc.listings.invalidate(dirPath)
_ = mc.enqueueApplyRequest(metadataApplyRequest{
ctx: context.Background(),
kind: metadataPurgeDir,
@@ -342,7 +357,7 @@ func (mc *MetaCache) PurgeDirectoryChildren(dirPath util.FullPath, resetFn func(
func (mc *MetaCache) UpdateEntry(ctx context.Context, entry *filer.Entry) error {
mc.Lock()
defer mc.Unlock()
if err := mc.localStore.UpdateEntry(ctx, entry); err != nil {
if err := mc.storeUpdateEntry(ctx, entry); err != nil {
return err
}
mc.markEntryUnversionedLocked(ctx, entry.FullPath)
@@ -365,7 +380,7 @@ func (mc *MetaCache) TouchDirMtimeCtime(ctx context.Context, dirPath util.FullPa
}
entry.Attr.Mtime = now
entry.Attr.Ctime = now
if err := mc.localStore.UpdateEntry(ctx, entry); err != nil {
if err := mc.storeUpdateEntry(ctx, entry); err != nil {
return err
}
mc.markEntryUnversionedLocked(ctx, dirPath)
@@ -576,7 +591,7 @@ func (mc *MetaCache) deleteChildVersionRecordsLocked(ctx context.Context, dirPat
func (mc *MetaCache) DeleteEntry(ctx context.Context, fp util.FullPath) (err error) {
mc.Lock()
defer mc.Unlock()
if err = mc.localStore.DeleteEntry(ctx, fp); err != nil {
if err = mc.storeDeleteEntry(ctx, fp); err != nil {
return err
}
mc.clearEntryVersionLocked(ctx, fp)
@@ -587,7 +602,7 @@ func (mc *MetaCache) DeleteFolderChildren(ctx context.Context, fp util.FullPath)
defer mc.Unlock()
delete(mc.dirVersionFloors, fp)
mc.deleteChildVersionRecordsLocked(ctx, fp)
return mc.localStore.DeleteFolderChildren(ctx, fp)
return mc.storeDeleteFolderChildren(ctx, fp)
}
// SetPinnedChildFn installs a predicate reporting whether a child holds
@@ -606,7 +621,7 @@ func (mc *MetaCache) deleteFolderChildrenForRebuild(ctx context.Context, dirPath
mc.Lock()
defer mc.Unlock()
if mc.pinnedChildFn == nil {
return mc.localStore.DeleteFolderChildren(ctx, dirPath)
return mc.storeDeleteFolderChildren(ctx, dirPath)
}
var pinned []*filer.Entry
if _, err := mc.localStore.ListDirectoryEntries(ctx, dirPath, "", true, math.MaxInt64, func(entry *filer.Entry) (bool, error) {
@@ -617,7 +632,7 @@ func (mc *MetaCache) deleteFolderChildrenForRebuild(ctx context.Context, dirPath
}); err != nil {
return err
}
if err := mc.localStore.DeleteFolderChildren(ctx, dirPath); err != nil {
if err := mc.storeDeleteFolderChildren(ctx, dirPath); err != nil {
return err
}
if len(pinned) > 0 {
@@ -626,26 +641,142 @@ func (mc *MetaCache) deleteFolderChildrenForRebuild(ctx context.Context, dirPath
return nil
}
func (mc *MetaCache) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) error {
// ListDirectoryEntries reports the last name the store reached, which is not
// the last name handed to eachEntryFunc: an expired child is dropped here after
// the store has already spent it against limit. A caller paginating by count
// would read a short batch as the end of the directory, and one resuming from
// the last name it saw would re-read the dropped ones forever.
//
// A directory already walked all the way through is served from memory. Only a
// listing that leaves out chunk lists is cached or served, so an entry from the
// cache can never be handed to a caller that wanted chunks.
func (mc *MetaCache) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
mc.RLock()
defer mc.RUnlock()
if !mc.isCachedFn(dirPath) {
// if this request comes after renaming, it should be fine
glog.Warningf("unsynchronized dir: %v", dirPath)
mc.listings.invalidate(dirPath)
return mc.listFromStore(ctx, dirPath, startFileName, includeStartFile, limit, eachEntryFunc, nil)
}
_, err := mc.localStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, func(entry *filer.Entry) (bool, error) {
if entry.TtlSec > 0 && entry.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now()) {
return true, nil
cacheable := filer_pb.ChunksOmitted(ctx)
if cacheable {
if entries, found := mc.listings.lookup(dirPath); found {
return serveCachedListing(entries, startFileName, includeStartFile, limit, eachEntryFunc)
}
}
var build *listingBuild
if cacheable {
build = mc.listings.beginOrContinue(dirPath, startFileName, includeStartFile)
}
storeCount := int64(0)
stoppedEarly := false
wrapped := func(entry *filer.Entry) (bool, error) {
ok, err := eachEntryFunc(entry)
if err != nil || !ok {
stoppedEarly = true
}
return ok, err
}
lastFileName, err = mc.listFromStore(ctx, dirPath, startFileName, includeStartFile, limit, wrapped, func(entry *filer.Entry) {
storeCount++
if build != nil {
build.entries = append(build.entries, entry)
}
mc.mapIdFromFilerToLocal(entry)
return eachEntryFunc(entry)
})
if err != nil {
return err
mc.listings.invalidate(dirPath)
return lastFileName, err
}
return err
if build != nil {
// A short page means the store ran out only if the caller did not stop
// it first. A caller whose buffer filled has seen part of a page, and
// the rest of the directory is still out there.
if storeCount < limit && !stoppedEarly {
mc.listings.publish(dirPath, build)
} else {
mc.listings.carry(dirPath, build, lastFileName)
}
}
return lastFileName, nil
}
// listFromStore reads a page, dropping expired children and mapping ids. observe,
// when set, sees every entry the store produced, expired ones included, since
// those are what limit was spent on.
func (mc *MetaCache) listFromStore(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc, observe func(*filer.Entry)) (string, error) {
return mc.localStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, func(entry *filer.Entry) (bool, error) {
mc.mapIdFromFilerToLocal(entry)
if observe != nil {
observe(entry)
}
if isTtlExpired(entry) {
return true, nil
}
return eachEntryFunc(entry)
})
}
// serveCachedListing walks an in-memory listing the way the store would: limit
// counts every child it steps over, expired or not, and lastFileName is the last
// one stepped over rather than the last one reported. Expiry is applied here
// rather than at cache time, so a listing does not go stale as children age out.
func serveCachedListing(entries []*filer.Entry, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
start := sort.Search(len(entries), func(i int) bool {
if includeStartFile {
return entries[i].Name() >= startFileName
}
return entries[i].Name() > startFileName
})
for i := start; i < len(entries) && int64(i-start) < limit; i++ {
entry := entries[i]
lastFileName = entry.Name()
if isTtlExpired(entry) {
continue
}
if ok, err := eachEntryFunc(entry); err != nil || !ok {
return lastFileName, err
}
}
return lastFileName, nil
}
// Every write to the local store goes through these, so a directory's cached
// listing cannot outlive a change to it. Reaching past them to mc.localStore
// for a write would leave the listing stale.
func (mc *MetaCache) storeInsertEntry(ctx context.Context, entry *filer.Entry) error {
mc.listings.invalidateChild(entry.FullPath)
return mc.localStore.InsertEntry(ctx, entry)
}
func (mc *MetaCache) storeUpdateEntry(ctx context.Context, entry *filer.Entry) error {
mc.listings.invalidateChild(entry.FullPath)
return mc.localStore.UpdateEntry(ctx, entry)
}
func (mc *MetaCache) storeDeleteEntry(ctx context.Context, fp util.FullPath) error {
mc.listings.invalidateChild(fp)
return mc.localStore.DeleteEntry(ctx, fp)
}
func (mc *MetaCache) storeDeleteFolderChildren(ctx context.Context, fp util.FullPath) error {
mc.listings.invalidate(fp)
return mc.localStore.DeleteFolderChildren(ctx, fp)
}
// InvalidateAllListings distrusts every cached listing, for when a subscription
// gap means the mount cannot know what it missed.
func (mc *MetaCache) InvalidateAllListings() {
mc.listings.invalidateAll()
}
// ListingCacheSize reports the cached directories and the children they hold.
func (mc *MetaCache) ListingCacheSize() (dirs, entries int) {
return mc.listings.size()
}
func (mc *MetaCache) Shutdown() {
@@ -934,7 +1065,7 @@ func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *file
isDelete := message.NewEntry == nil
isMove := message.NewEntry != nil && (message.NewParentPath != resp.Directory || message.NewEntry.Name != message.OldEntry.Name)
if isDelete || isMove {
if deleteErr := mc.localStore.DeleteFolderChildren(ctx, oldPath); deleteErr != nil {
if deleteErr := mc.storeDeleteFolderChildren(ctx, oldPath); deleteErr != nil {
glog.V(2).Infof("delete descendants of %s: %v", oldPath, deleteErr)
}
}
@@ -976,7 +1107,7 @@ func (mc *MetaCache) purgeDirectoryChildrenNow(ctx context.Context, dirPath util
defer mc.Unlock()
delete(mc.dirVersionFloors, dirPath)
mc.deleteChildVersionRecordsLocked(ctx, dirPath)
return mc.localStore.DeleteFolderChildren(ctx, dirPath)
return mc.storeDeleteFolderChildren(ctx, dirPath)
}
func (mc *MetaCache) completeDirectoryBuildNow(ctx context.Context, dirPath util.FullPath, snapshotTsNs int64) error {
@@ -506,6 +506,7 @@ func newTestMetaCache(t *testing.T, cached map[util.FullPath]bool) (*MetaCache,
func(dir util.FullPath) {
notifications.record(dir)
},
DefaultListingCacheEntries,
)
return mc, cached, notifications, invalidations
@@ -66,6 +66,7 @@ func TestApplyLoopInvalidateDoesNotDeadlockWithLockHoldingEnqueuer(t *testing.T)
fhLockTable.ReleaseLock(fhKey, lock)
},
func(dir util.FullPath) {},
DefaultListingCacheEntries,
)
defer func() {
// Only safe to shut down once the apply loop is unwedged.
+3 -1
View File
@@ -53,6 +53,7 @@ type Option struct {
CacheDirForWrite string
WriteBufferSizeMB int64
CacheMetaTTlSec int
DirListCacheEntries int
DataCenter string
Umask os.FileMode
Quota int64
@@ -314,7 +315,7 @@ func NewSeaweedFileSystem(option *Option) *WFS {
if wfs.inodeToPath.RecordDirectoryUpdate(dirPath, time.Now(), wfs.dirHotWindow, wfs.dirHotThreshold) {
wfs.markDirectoryReadThrough(dirPath)
}
})
}, option.DirListCacheEntries)
wfs.metaCache.SetPinnedChildFn(wfs.isLocalOnlyEntry)
grace.OnInterrupt(func() {
// grace calls os.Exit(0) after all hooks, so WaitForAsyncFlush
@@ -506,6 +507,7 @@ func (wfs *WFS) StartBackgroundTasks() error {
// wipe the root's stale children through the apply loop so the delete
// cannot strand a concurrent rebuild cached-but-empty.
wfs.inodeToPath.InvalidateAllChildrenCache()
wfs.metaCache.InvalidateAllListings()
wfs.purgeDirectoryCache(util.FullPath(wfs.option.FilerMountRootPath))
}, follower)
go wfs.loopCheckQuota()
+82 -15
View File
@@ -20,6 +20,11 @@ const (
batchSize = 1000
)
// readdirContext marks the meta cache listing as reading attributes only. A
// readdir never looks at a chunk list, and building one per child is most of
// the cost of decoding a wide directory.
var readdirContext = filer_pb.WithChunksOmitted(context.Background())
// DirectoryHandle represents an open directory handle.
// It maintains state for directory listing pagination and is protected by a mutex
// to handle concurrent readdir operations from NFS-Ganesha and other multi-threaded clients.
@@ -28,11 +33,15 @@ type DirectoryHandle struct {
isFinished bool
entryStream []*filer.Entry
entryStreamOffset uint64
snapshotTsNs int64 // snapshot timestamp for consistent readdir in direct mode
// lastListedName is how far the store itself reached, which runs ahead of
// the last visible entry whenever children are dropped as expired.
lastListedName string
snapshotTsNs int64 // snapshot timestamp for consistent readdir in direct mode
}
func (dh *DirectoryHandle) reset() {
dh.isFinished = false
dh.lastListedName = ""
dh.snapshotTsNs = 0
// Nil out pointers to allow garbage collection of old entries,
// then reuse the slice's capacity to avoid re-allocations.
@@ -156,6 +165,11 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
if input.Offset == 0 {
dh.reset()
} else if input.Offset < dh.entryStreamOffset {
// Seeking back before what the handle still holds. Start the directory
// again rather than reporting nothing; the preload below refills up to
// the requested offset.
dh.reset()
} else if dh.isFinished && input.Offset >= dh.entryStreamOffset {
entryCurrentIndex := input.Offset - dh.entryStreamOffset
if uint64(len(dh.entryStream)) <= entryCurrentIndex {
@@ -170,12 +184,21 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
wfs.inodeToPath.TouchDirectory(dirPath)
var dirEntry fuse.DirEntry
// Only a reference makes a child worth entering in the inode table: without
// one nothing ever arrives to take the entry back out again.
takesLookupRef := isPlusMode && out.TakesLookupRef()
// index is the position in entryStream, used to calculate the offset for next readdir
processEachEntryFn := func(entry *filer.Entry, index int64) bool {
dirEntry.Name = entry.Name()
dirEntry.Mode = toSyscallMode(entry.Mode)
inode := wfs.inodeToPath.Lookup(dirPath.Child(dirEntry.Name), entry.Crtime.Unix(), entry.IsDirectory(), len(entry.HardLinkId) > 0, entry.Inode, false)
childPath := dirPath.Child(dirEntry.Name)
var inode uint64
if takesLookupRef {
inode = wfs.inodeToPath.Lookup(childPath, entry.Crtime.Unix(), entry.IsDirectory(), len(entry.HardLinkId) > 0, entry.Inode, false)
} else {
inode = wfs.inodeToPath.InodeForListing(childPath, entry.Crtime.Unix(), entry.Inode)
}
dirEntry.Ino = inode
// Set Off to the next offset so client can resume from correct position
@@ -191,11 +214,15 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
return false
}
if fh, found := wfs.fhMap.FindFileHandle(inode); found {
glog.V(4).Infof("readdir opened file %s", dirPath.Child(dirEntry.Name))
glog.V(4).Infof("readdir opened file %s", childPath)
entry = filer.FromPbEntry(string(dirPath), fh.GetEntry().GetEntry())
}
wfs.outputFilerEntry(entryOut, inode, entry)
wfs.inodeToPath.Lookup(dirPath.Child(dirEntry.Name), entry.Crtime.Unix(), entry.IsDirectory(), len(entry.HardLinkId) > 0, entry.Inode, true)
// Taken only once the entry is really in the sink, so one that did not
// fit leaves no reference behind. The fallback covers a racing Forget.
if takesLookupRef && !wfs.inodeToPath.IncrementNlookup(inode) {
wfs.inodeToPath.Lookup(childPath, entry.Crtime.Unix(), entry.IsDirectory(), len(entry.HardLinkId) > 0, entry.Inode, true)
}
}
return true
}
@@ -223,6 +250,19 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
// Read from cache first, then load next batch if needed
if input.Offset >= dh.entryStreamOffset {
// Drop what the client has walked past. Offsets are indexes into the
// stream from entryStreamOffset, so advancing the two together keeps
// them lined up; one entry is kept back because the next batch resumes
// from the name immediately before the offset.
if trim := int(input.Offset-dh.entryStreamOffset) - 1; trim > 0 && trim <= len(dh.entryStream) {
copy(dh.entryStream, dh.entryStream[trim:])
for i := len(dh.entryStream) - trim; i < len(dh.entryStream); i++ {
dh.entryStream[i] = nil
}
dh.entryStream = dh.entryStream[:len(dh.entryStream)-trim]
dh.entryStreamOffset += uint64(trim)
}
// Handle case: new handle with non-zero offset but empty cache
// This happens when NFS-Ganesha opens multiple directory handles
if len(dh.entryStream) == 0 && input.Offset > dh.entryStreamOffset {
@@ -234,10 +274,11 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
}
// Load entries from beginning to fill cache up to the requested offset
loadErr := wfs.metaCache.ListDirectoryEntries(context.Background(), dirPath, "", false, skipCount+int64(batchSize), func(entry *filer.Entry) (bool, error) {
storeLastName, loadErr := wfs.metaCache.ListDirectoryEntries(readdirContext, dirPath, "", false, skipCount+int64(batchSize), func(entry *filer.Entry) (bool, error) {
dh.entryStream = append(dh.entryStream, entry)
return true, nil
})
dh.lastListedName = storeLastName
if loadErr != nil {
glog.Errorf("list meta cache: %v", loadErr)
return fuse.EIO
@@ -248,6 +289,13 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
entryPreviousIndex := (input.Offset - dh.entryStreamOffset) - 1
if uint64(len(dh.entryStream)) > entryPreviousIndex {
lastEntryName = dh.entryStream[entryPreviousIndex].Name()
} else {
// The stream runs from the directory's first child, so failing to
// reach the entry before this offset means the directory has since
// shrunk past it. Listing on from an empty name would replay the
// directory from the start and hand the client every name twice.
dh.isFinished = true
return fuse.OK
}
}
@@ -268,13 +316,18 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
return fuse.EIO
}
// Batch loading: fetch batchSize entries starting from lastEntryName
loadedCount := 0
// Page from where the store itself reached, not from the last entry the
// sink saw. An expired child is counted against the batch and then
// dropped, so resuming from the last visible name would re-read it every
// round and never get past a batch that was entirely expired.
if dh.lastListedName > lastEntryName {
lastEntryName = dh.lastListedName
}
bufferFull := false
loadErr := wfs.metaCache.ListDirectoryEntries(context.Background(), dirPath, lastEntryName, false, int64(batchSize), func(entry *filer.Entry) (bool, error) {
storeLastName, loadErr := wfs.metaCache.ListDirectoryEntries(readdirContext, dirPath, lastEntryName, false, int64(batchSize), func(entry *filer.Entry) (bool, error) {
currentIndex := int64(len(dh.entryStream))
dh.entryStream = append(dh.entryStream, entry)
loadedCount++
if !processEachEntryFn(entry, currentIndex) {
bufferFull = true
return false, nil
@@ -285,10 +338,12 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
glog.Errorf("list meta cache: %v", loadErr)
return fuse.EIO
}
dh.lastListedName = storeLastName
// Mark finished only when loading completed normally (not buffer full)
// and we got fewer entries than requested
if !bufferFull && loadedCount < batchSize {
// The store reaching nothing is the only sound end-of-directory signal:
// a batch can come back short because entries expired, not because the
// directory ran out.
if !bufferFull && storeLastName == "" {
dh.isFinished = true
}
}
@@ -302,7 +357,7 @@ func (wfs *WFS) readDirectoryDirect(input *fuse.ReadIn, out DirEntrySink, dh *Di
if input.Offset >= dh.entryStreamOffset {
if len(dh.entryStream) == 0 && input.Offset > dh.entryStreamOffset {
skipCount := uint32(input.Offset-dh.entryStreamOffset) + batchSize
entries, snapshotTs, err := loadDirectoryEntriesDirect(context.Background(), wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
entries, snapshotTs, err := loadDirectoryEntriesDirect(readdirContext, wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
if err != nil {
glog.Errorf("list filer directory: %v", err)
return fuse.EIO
@@ -317,6 +372,11 @@ func (wfs *WFS) readDirectoryDirect(input *fuse.ReadIn, out DirEntrySink, dh *Di
entryPreviousIndex := (input.Offset - dh.entryStreamOffset) - 1
if uint64(len(dh.entryStream)) > entryPreviousIndex {
lastEntryName = dh.entryStream[entryPreviousIndex].Name()
} else {
// See the cached path: the directory shrank past this offset, and
// resuming from an empty name would replay it from the start.
dh.isFinished = true
return fuse.OK
}
}
@@ -331,7 +391,7 @@ func (wfs *WFS) readDirectoryDirect(input *fuse.ReadIn, out DirEntrySink, dh *Di
}
}
entries, snapshotTs, err := loadDirectoryEntriesDirect(context.Background(), wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
entries, snapshotTs, err := loadDirectoryEntriesDirect(readdirContext, wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
if err != nil {
glog.Errorf("list filer directory: %v", err)
return fuse.EIO
@@ -361,7 +421,14 @@ func (wfs *WFS) readDirectoryDirect(input *fuse.ReadIn, out DirEntrySink, dh *Di
}
func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient, uidGidMapper *meta_cache.UidGidMapper, dirPath util.FullPath, startFileName string, includeStart bool, limit uint32, snapshotTsNs int64, includeSystemEntries bool) ([]*filer.Entry, int64, error) {
entries := make([]*filer.Entry, 0, limit)
// limit can be a client-supplied resume offset rather than a batch size, so
// preallocating for it would size the slice from where the caller happened to
// seek. Reserve a batch and let append find the rest.
prealloc := limit
if prealloc > batchSize {
prealloc = batchSize
}
entries := make([]*filer.Entry, 0, prealloc)
var actualSnapshotTsNs int64
err := client.WithFilerClient(false, func(sc filer_pb.SeaweedFilerClient) error {
var innerErr error
+234
View File
@@ -0,0 +1,234 @@
package mount
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
const benchDirEntryCount = 200000
// benchSink drains a readdir the way a front end does. sinkLimit is how many
// entries one round accepts, standing in for the kernel reply buffer or the
// WinFsp adapter's batch.
type benchSink struct {
plus bool
takesRef bool
sinkLimit int
count int
inodes []uint64
lastOff uint64
attrs []fuse.EntryOut
}
func (s *benchSink) reset() {
s.count = 0
s.inodes = s.inodes[:0]
s.attrs = s.attrs[:0]
}
func (s *benchSink) AddEntry(entry fuse.DirEntry) bool {
if s.count >= s.sinkLimit {
return false
}
s.count++
s.lastOff = entry.Off
s.inodes = append(s.inodes, entry.Ino)
return true
}
func (s *benchSink) AddEntryPlus(entry fuse.DirEntry) *fuse.EntryOut {
if s.count >= s.sinkLimit {
return nil
}
s.count++
s.lastOff = entry.Off
s.inodes = append(s.inodes, entry.Ino)
s.attrs = append(s.attrs, fuse.EntryOut{})
return &s.attrs[len(s.attrs)-1]
}
func (s *benchSink) TakesLookupRef() bool { return s.takesRef }
func inodeTableSize(i *InodeToPath) int {
i.RLock()
defer i.RUnlock()
return len(i.inode2path)
}
func newBenchWFS(tb testing.TB, dir util.FullPath, n int) *WFS {
tb.Helper()
uidGidMapper, err := meta_cache.NewUidGidMapper("", "")
if err != nil {
tb.Fatalf("uid/gid mapper: %v", err)
}
root := util.FullPath("/")
option := &Option{
ChunkSizeLimit: 1024,
ConcurrentReaders: 1,
VolumeServerAccess: "filerProxy",
FilerAddresses: []pb.ServerAddress{pb.NewServerAddressWithGrpcPort("127.0.0.1:1", 1)},
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
FilerMountRootPath: "/",
MountUid: 99,
MountGid: 100,
MountMode: 0o777,
MountMtime: time.Now(),
MountCtime: time.Now(),
UidGidMapper: uidGidMapper,
}
wfs := &WFS{
option: option,
signature: 1,
inodeToPath: NewInodeToPath(root, 0),
fhMap: NewFileHandleToInode(),
dhMap: NewDirectoryHandleToInode(),
fhLockTable: util.NewLockTable[FileHandleId](),
hardLinkLockTable: util.NewLockTable[string](),
}
wfs.metaCache = meta_cache.NewMetaCache(
filepath.Join(tb.TempDir(), "meta"),
uidGidMapper,
root,
false,
func(path util.FullPath) { wfs.inodeToPath.MarkChildrenCached(path) },
func(path util.FullPath) bool { return wfs.inodeToPath.IsChildrenCached(path) },
func(meta_cache.EntryInvalidation) {},
nil,
meta_cache.DefaultListingCacheEntries,
)
tb.Cleanup(wfs.metaCache.Shutdown)
now := time.Now()
ctx := context.Background()
if err := wfs.metaCache.InsertEntry(ctx, &filer.Entry{
FullPath: dir,
Attr: filer.Attr{Mode: os.ModeDir | 0o755, Mtime: now, Crtime: now, Uid: 99, Gid: 100},
}, 0); err != nil {
tb.Fatalf("insert dir: %v", err)
}
for i := 0; i < n; i++ {
child := dir.Child(fmt.Sprintf("image-%08d.jpg", i))
if err := wfs.metaCache.InsertEntry(ctx, &filer.Entry{
FullPath: child,
// The filer stamps an inode on every entry it stores, so a listing
// arrives with one and never has to derive its own.
Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: now, Uid: 99, Gid: 100, FileSize: 4 << 20, Inode: child.AsInode(now.Unix())},
// A real file has chunks, and building them is most of what decoding
// an entry costs.
// No FileId: BeforeEntrySerialization reparses that legacy string
// over Fid on the way in, which would make every entry's chunk
// byte-identical instead of varying per file.
Chunks: []*filer_pb.FileChunk{{
Size: 4 << 20, ModifiedTsNs: now.UnixNano(),
ETag: "1a2b3c4d5e6f7890",
Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i), Cookie: 0x1637037d},
}},
}, 0); err != nil {
tb.Fatalf("insert entry %d: %v", i, err)
}
}
// Mark the tree cached so the listing is served from the meta cache and no
// filer client is dialled.
wfs.inodeToPath.MarkChildrenCached(root)
wfs.inodeToPath.Lookup(dir, now.Unix(), true, false, 0, true)
wfs.inodeToPath.MarkChildrenCached(dir)
return wfs
}
// walkOnce enumerates the whole directory the way a front end does: repeated
// rounds against one handle until the listing runs dry, returning whatever
// references the round took.
func walkOnce(tb testing.TB, wfs *WFS, dirInode uint64, sink *benchSink, forgets bool) int {
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
total := 0
offset := uint64(0)
for {
sink.reset()
status := wfs.doReadDirectory(&fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, sink.plus)
if status != fuse.OK {
tb.Fatalf("readdir: %v", status)
}
if sink.count == 0 {
return total
}
total += sink.count
if forgets {
// HasInode keeps this to the entries that really hold a reference,
// so a listing that took none is not charged for a bogus Forget.
for _, ino := range sink.inodes {
if wfs.inodeToPath.HasInode(ino) {
wfs.Forget(ino, 1)
}
}
}
if sink.lastOff <= offset {
return total
}
offset = sink.lastOff
}
}
var benchCases = []struct {
name string
plus bool
// ref mirrors the sink's TakesLookupRef. The kernel's reports true whatever
// the mode, exactly as fuseDirEntryList does; it is the mode that decides
// whether a reference is actually granted.
ref bool
// forgets is what the front end does after a round: the kernel returns one
// FORGET per readdirplus entry and none for a plain readdir, and the WinFsp
// adapter hands back everything a round gave it.
forgets bool
}{
{"kernel_readdir", false, true, false},
{"kernel_readdirplus", true, true, true},
{"winfsp_readdirplus", true, false, true},
}
func BenchmarkReadDirectory(b *testing.B) {
dir := util.FullPath("/images")
for _, tc := range benchCases {
b.Run(tc.name, func(b *testing.B) {
wfs := newBenchWFS(b, dir, benchDirEntryCount)
dirInode, _ := wfs.inodeToPath.GetInode(dir)
sink := &benchSink{plus: tc.plus, takesRef: tc.ref, sinkLimit: 4096}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if got := walkOnce(b, wfs, dirInode, sink, tc.forgets); got != benchDirEntryCount+2 {
b.Fatalf("listed %d entries, want %d", got, benchDirEntryCount+2)
}
}
b.StopTimer()
// What the listing left in the inode table, over the root and the
// directory itself.
b.ReportMetric(float64(inodeTableSize(wfs.inodeToPath)), "inodes_left")
})
}
}
+55
View File
@@ -0,0 +1,55 @@
package mount
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// TestListDirectoryEntriesOmitsChunks covers the wiring the readdir speedup
// rests on: that the context marker actually reaches the store's decode. Every
// other test exercises the decoder directly, so a refactor that stopped
// threading the context would revert the optimisation silently.
func TestListDirectoryEntriesOmitsChunks(t *testing.T) {
dir := util.FullPath("/images")
wfs := newBenchWFS(t, dir, 4)
for _, tc := range []struct {
name string
ctx context.Context
wantChunks bool
}{
{"plain listing keeps chunks", context.Background(), true},
{"marked listing drops chunks", filer_pb.WithChunksOmitted(context.Background()), false},
} {
t.Run(tc.name, func(t *testing.T) {
var seen int
_, err := wfs.metaCache.ListDirectoryEntries(tc.ctx, dir, "", false, 100, func(entry *filer.Entry) (bool, error) {
seen++
if got := len(entry.Chunks) > 0; got != tc.wantChunks {
t.Errorf("%s: has chunks = %v, want %v", entry.Name(), got, tc.wantChunks)
}
// The size has to survive either way, since that is what the
// readdir reports.
if entry.FileSize != 4<<20 {
t.Errorf("%s: FileSize = %d, want %d", entry.Name(), entry.FileSize, 4<<20)
}
return true, nil
})
if err != nil {
t.Fatalf("list: %v", err)
}
if seen != 4 {
t.Fatalf("listed %d entries, want 4", seen)
}
})
}
// readdirContext is what weedfs_dir_read.go actually passes.
if !filer_pb.ChunksOmitted(readdirContext) {
t.Error("readdirContext does not carry the chunks-omitted marker")
}
}
@@ -0,0 +1,247 @@
package mount
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// pagingSink collects names, accepting at most limit per round the way a kernel
// reply buffer does.
type pagingSink struct {
limit int
names []string
lastOff uint64
round int
}
func (s *pagingSink) AddEntry(entry fuse.DirEntry) bool {
if s.round >= s.limit {
return false
}
s.round++
s.names = append(s.names, entry.Name)
s.lastOff = entry.Off
return true
}
func (s *pagingSink) AddEntryPlus(entry fuse.DirEntry) *fuse.EntryOut { return nil }
func (s *pagingSink) TakesLookupRef() bool { return true }
func newPagingWFS(tb testing.TB, dir util.FullPath, names []string, ttlSec int32) *WFS {
tb.Helper()
uidGidMapper, err := meta_cache.NewUidGidMapper("", "")
if err != nil {
tb.Fatalf("uid/gid mapper: %v", err)
}
root := util.FullPath("/")
wfs := &WFS{
option: &Option{
ChunkSizeLimit: 1024, ConcurrentReaders: 1, VolumeServerAccess: "filerProxy",
FilerAddresses: []pb.ServerAddress{pb.NewServerAddressWithGrpcPort("127.0.0.1:1", 1)},
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
FilerMountRootPath: "/", MountUid: 99, MountGid: 100, MountMode: 0o777,
MountMtime: time.Now(), MountCtime: time.Now(), UidGidMapper: uidGidMapper,
},
signature: 1, inodeToPath: NewInodeToPath(root, 0),
fhMap: NewFileHandleToInode(), dhMap: NewDirectoryHandleToInode(),
fhLockTable: util.NewLockTable[FileHandleId](), hardLinkLockTable: util.NewLockTable[string](),
}
wfs.metaCache = meta_cache.NewMetaCache(
filepath.Join(tb.TempDir(), "meta"), uidGidMapper, root, false,
func(p util.FullPath) { wfs.inodeToPath.MarkChildrenCached(p) },
func(p util.FullPath) bool { return wfs.inodeToPath.IsChildrenCached(p) },
func(meta_cache.EntryInvalidation) {}, nil,
meta_cache.DefaultListingCacheEntries,
)
tb.Cleanup(wfs.metaCache.Shutdown)
now := time.Now()
ctx := context.Background()
if err := wfs.metaCache.InsertEntry(ctx, &filer.Entry{
FullPath: dir,
Attr: filer.Attr{Mode: os.ModeDir | 0o755, Mtime: now, Crtime: now},
}, 0); err != nil {
tb.Fatalf("insert dir: %v", err)
}
for _, name := range names {
child := dir.Child(name)
attr := filer.Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 1, Inode: child.AsInode(now.Unix())}
if ttlSec > 0 {
// Expired well in the past, so the meta cache drops it after the
// store has already counted it against the limit.
attr.TtlSec = ttlSec
attr.Crtime = now.Add(-time.Duration(ttlSec+60) * time.Second)
}
if err := wfs.metaCache.InsertEntry(ctx, &filer.Entry{FullPath: child, Attr: attr}, 0); err != nil {
tb.Fatalf("insert %s: %v", name, err)
}
}
wfs.inodeToPath.MarkChildrenCached(root)
wfs.inodeToPath.Lookup(dir, now.Unix(), true, false, 0, true)
wfs.inodeToPath.MarkChildrenCached(dir)
return wfs
}
// TestReadDirResumePastShrunkDirectory covers a client resuming a fresh handle
// at a cookie from an earlier, larger listing. The directory has since shrunk
// past that offset, and the readdir used to fall back to listing from the first
// child again, handing back names the client had already consumed.
func TestReadDirResumePastShrunkDirectory(t *testing.T) {
dir := util.FullPath("/d")
var names []string
for i := 0; i < 100; i++ {
names = append(names, fmt.Sprintf("f%03d", i))
}
wfs := newPagingWFS(t, dir, names, 0)
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: 4096}
status := wfs.doReadDirectory(&fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: 152, // past the end of a directory that now holds 100
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if len(sink.names) != 0 {
t.Errorf("resuming past the end returned %d entries (first %q), want none", len(sink.names), sink.names[0])
}
}
// TestReadDirWithExpiredEntries covers a batch the store fills to the limit but
// whose entries the meta cache then drops as expired. The post-filter count used
// to be read as end-of-directory, silently hiding every later child.
func TestReadDirWithExpiredEntries(t *testing.T) {
dir := util.FullPath("/d")
// One full store batch of entries that all expire, then live ones behind
// them. Nothing survives the first batch, which is the case that latched.
var names []string
for i := 0; i < batchSize; i++ {
names = append(names, fmt.Sprintf("a%05d", i))
}
wfs := newPagingWFS(t, dir, names, 30)
live := []string{"z001", "z002", "z003"}
now := time.Now()
for _, name := range live {
child := dir.Child(name)
if err := wfs.metaCache.InsertEntry(context.Background(), &filer.Entry{
FullPath: child,
Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 1, Inode: child.AsInode(now.Unix())},
}, 0); err != nil {
t.Fatalf("insert %s: %v", name, err)
}
}
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: 4096}
var offset uint64
for round := 0; round < 20; round++ {
sink.round = 0
status := wfs.doReadDirectory(&fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
var seen []string
for _, n := range sink.names {
if n != "." && n != ".." {
seen = append(seen, n)
}
}
if len(seen) != len(live) {
t.Fatalf("listed %d entries %v, want the %d live ones %v", len(seen), seen, len(live), live)
}
}
// TestReadDirTrimsConsumedEntries checks that a walk does not accumulate the
// whole directory in the handle. Offsets index into the stream from
// entryStreamOffset, so the two have to advance together or the listing
// silently misaligns.
func TestReadDirTrimsConsumedEntries(t *testing.T) {
dir := util.FullPath("/d")
const total = 5000
var names []string
for i := 0; i < total; i++ {
names = append(names, fmt.Sprintf("f%05d", i))
}
wfs := newPagingWFS(t, dir, names, 0)
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, dh := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
// A small sink forces many rounds, which is when the stream would grow.
sink := &pagingSink{limit: 64}
var offset uint64
var seen []string
peak := 0
for round := 0; round < 500; round++ {
sink.round = 0
before := len(sink.names)
status := wfs.doReadDirectory(&fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if n := len(dh.entryStream); n > peak {
peak = n
}
if len(sink.names) == before || sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
for _, n := range sink.names {
if n != "." && n != ".." {
seen = append(seen, n)
}
}
if len(seen) != total {
t.Fatalf("listed %d entries, want %d", len(seen), total)
}
for i, name := range seen {
if want := fmt.Sprintf("f%05d", i); name != want {
t.Fatalf("entry %d is %q, want %q -- trimming misaligned the offsets", i, name, want)
}
}
// Without trimming the handle ends up holding every entry.
if peak >= total {
t.Errorf("handle held %d entries at peak, want well under the %d in the directory", peak, total)
}
}
@@ -348,6 +348,7 @@ func newCopyRangeTestWFSWithMetaCache(t *testing.T) *WFS {
},
func(meta_cache.EntryInvalidation) {},
nil,
meta_cache.DefaultListingCacheEntries,
)
t.Cleanup(func() {
wfs.metaCache.Shutdown()
+1
View File
@@ -130,6 +130,7 @@ func newCreateTestWFS(t *testing.T) (*WFS, *createEntryTestServer) {
},
func(meta_cache.EntryInvalidation) {},
nil,
meta_cache.DefaultListingCacheEntries,
)
wfs.inodeToPath.MarkChildrenCached(root)
t.Cleanup(func() {
@@ -62,6 +62,7 @@ func newInvalidateTestWFS(t *testing.T) *WFS {
func(path util.FullPath) bool { return wfs.inodeToPath.IsChildrenCached(path) },
wfs.invalidateOpenFileHandle,
nil,
meta_cache.DefaultListingCacheEntries,
)
t.Cleanup(wfs.metaCache.Shutdown)
+1
View File
@@ -32,6 +32,7 @@ func TestHandleRenameResponseLeavesUncachedTargetOutOfCache(t *testing.T) {
},
func(meta_cache.EntryInvalidation) {},
nil,
meta_cache.DefaultListingCacheEntries,
)
defer mc.Shutdown()
+3 -6
View File
@@ -651,6 +651,9 @@ func (s *readdirSink) AddEntryPlus(entry fuse.DirEntry) *fuse.EntryOut {
return out
}
// WinFsp has no FORGET, and every EntryOut is converted before the round ends.
func (s *readdirSink) TakesLookupRef() bool { return false }
func (w *WinFS) Readdir(path string, fill func(name string, stat *cgofuse.Stat_t, ofst int64) bool, ofst int64, fh uint64) int {
inode := w.inodeForHandle(w.dirInodes, fh)
if inode == 0 {
@@ -699,12 +702,6 @@ func (w *WinFS) Readdir(path string, fill func(name string, stat *cgofuse.Stat_t
filled = false
}
}
// A readdirplus entry carries a reference of its own. Give every one
// of them back, including any the fill above stopped short of, or a
// single walk of a wide directory strands one reference per child.
for _, child := range sink.inodes {
w.forget(child)
}
if !filled {
return 0
}
+4
View File
@@ -136,6 +136,10 @@ message ListEntriesRequest {
bool inclusiveStartFrom = 4;
uint32 limit = 5;
int64 snapshot_ts_ns = 6;
// Leave the chunk list out of every entry in the response. The attributes
// still carry the file size, so a listing that only reads attributes can
// ask for this and skip the largest part of the payload.
bool omit_chunks = 7;
}
message ListEntriesResponse {
+17 -4
View File
@@ -440,8 +440,12 @@ type ListEntriesRequest struct {
InclusiveStartFrom bool `protobuf:"varint,4,opt,name=inclusiveStartFrom,proto3" json:"inclusiveStartFrom,omitempty"`
Limit uint32 `protobuf:"varint,5,opt,name=limit,proto3" json:"limit,omitempty"`
SnapshotTsNs int64 `protobuf:"varint,6,opt,name=snapshot_ts_ns,json=snapshotTsNs,proto3" json:"snapshot_ts_ns,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// Leave the chunk list out of every entry in the response. The attributes
// still carry the file size, so a listing that only reads attributes can
// ask for this and skip the largest part of the payload.
OmitChunks bool `protobuf:"varint,7,opt,name=omit_chunks,json=omitChunks,proto3" json:"omit_chunks,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListEntriesRequest) Reset() {
@@ -516,6 +520,13 @@ func (x *ListEntriesRequest) GetSnapshotTsNs() int64 {
return 0
}
func (x *ListEntriesRequest) GetOmitChunks() bool {
if x != nil {
return x.OmitChunks
}
return false
}
type ListEntriesResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Entry *Entry `protobuf:"bytes,1,opt,name=entry,proto3" json:"entry,omitempty"`
@@ -6939,14 +6950,16 @@ const file_filer_proto_rawDesc = "" +
"\x1cLookupDirectoryEntryResponse\x12%\n" +
"\x05entry\x18\x01 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x12\x1a\n" +
"\tlog_ts_ns\x18\x02 \x01(\x03R\alogTsNs\x12#\n" +
"\rlog_signature\x18\x03 \x01(\x05R\flogSignature\"\xe4\x01\n" +
"\rlog_signature\x18\x03 \x01(\x05R\flogSignature\"\x85\x02\n" +
"\x12ListEntriesRequest\x12\x1c\n" +
"\tdirectory\x18\x01 \x01(\tR\tdirectory\x12\x16\n" +
"\x06prefix\x18\x02 \x01(\tR\x06prefix\x12,\n" +
"\x11startFromFileName\x18\x03 \x01(\tR\x11startFromFileName\x12.\n" +
"\x12inclusiveStartFrom\x18\x04 \x01(\bR\x12inclusiveStartFrom\x12\x14\n" +
"\x05limit\x18\x05 \x01(\rR\x05limit\x12$\n" +
"\x0esnapshot_ts_ns\x18\x06 \x01(\x03R\fsnapshotTsNs\"b\n" +
"\x0esnapshot_ts_ns\x18\x06 \x01(\x03R\fsnapshotTsNs\x12\x1f\n" +
"\vomit_chunks\x18\a \x01(\bR\n" +
"omitChunks\"b\n" +
"\x13ListEntriesResponse\x12%\n" +
"\x05entry\x18\x01 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x12$\n" +
"\x0esnapshot_ts_ns\x18\x02 \x01(\x03R\fsnapshotTsNs\"\xa1\x02\n" +
+1
View File
@@ -139,6 +139,7 @@ func DoSeaweedListWithSnapshot(ctx context.Context, client SeaweedFilerClient, f
Limit: redLimit,
InclusiveStartFrom: inclusive,
SnapshotTsNs: snapshotTsNs,
OmitChunks: ChunksOmitted(ctx),
}
// Preserve the caller-requested snapshot so pagination uses the same
+33
View File
@@ -149,6 +149,16 @@ func (m *ListEntriesRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
i -= len(m.unknownFields)
copy(dAtA[i:], m.unknownFields)
}
if m.OmitChunks {
i--
if m.OmitChunks {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x38
}
if m.SnapshotTsNs != 0 {
i = protohelpers.EncodeVarint(dAtA, i, uint64(m.SnapshotTsNs))
i--
@@ -6285,6 +6295,9 @@ func (m *ListEntriesRequest) SizeVT() (n int) {
if m.SnapshotTsNs != 0 {
n += 1 + protohelpers.SizeOfVarint(uint64(m.SnapshotTsNs))
}
if m.OmitChunks {
n += 2
}
n += len(m.unknownFields)
return n
}
@@ -9140,6 +9153,26 @@ func (m *ListEntriesRequest) UnmarshalVT(dAtA []byte) error {
break
}
}
case 7:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field OmitChunks", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return protohelpers.ErrIntOverflow
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.OmitChunks = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
+22
View File
@@ -0,0 +1,22 @@
package filer_pb
import "context"
type omitChunksKey struct{}
// WithChunksOmitted marks a listing as wanting attributes only. A listing over
// gRPC then asks the filer to leave the chunk lists out, and a listing served
// from a local store skips building them. The file size is carried in the
// attributes either way.
//
// Only a caller that reads attributes and nothing else may use this. In
// particular a listing that populates a cache, or one whose entries can be
// written back or deleted, needs the chunks.
func WithChunksOmitted(ctx context.Context) context.Context {
return context.WithValue(ctx, omitChunksKey{}, true)
}
// ChunksOmitted reports whether the listing wants attributes only.
func ChunksOmitted(ctx context.Context) bool {
return ctx.Value(omitChunksKey{}) != nil
}
-1
View File
@@ -26,7 +26,6 @@ type PolicyEvaluationContext struct {
bucketName string
policy *CompiledPolicy
cache *PolicyCache
mutex sync.RWMutex
}
// PolicyEngine is the main policy evaluation engine
+1 -3
View File
@@ -7,7 +7,6 @@ import (
"slices"
"sort"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
s3const "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
@@ -320,8 +319,7 @@ type PolicyEvaluationArgs struct {
// PolicyCache for caching compiled policies
type PolicyCache struct {
policies map[string]*CompiledPolicy
lastUpdate time.Time
policies map[string]*CompiledPolicy
}
// CompiledPolicy represents a policy that has been compiled for efficient evaluation
+14 -1
View File
@@ -86,8 +86,21 @@ func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream file
var hasEntries bool
lastFileName, listErr = fs.filer.StreamListDirectoryEntries(stream.Context(), util.FullPath(req.Directory), lastFileName, includeLastFile, int64(paginationLimit), req.Prefix, "", "", func(entry *filer.Entry) (bool, error) {
hasEntries = true
pbEntry := entry.ToProtoEntry()
if req.OmitChunks {
// Stamp the size before dropping the only other thing carrying
// it. Most stores fold the chunk extents into FileSize when they
// decode, but one that keeps entries as JSON rather than as an
// encoded Entry never re-derives it, and the caller would be
// left with a zero. The entries are still read whole, because
// expiring one here deletes its data and that needs the chunks.
if pbEntry.Attributes != nil {
pbEntry.Attributes.FileSize = filer.FileSize(pbEntry)
}
pbEntry.Chunks = nil
}
resp := &filer_pb.ListEntriesResponse{
Entry: entry.ToProtoEntry(),
Entry: pbEntry,
}
if !sentSnapshot {
resp.SnapshotTsNs = snapshotTsNs
+27 -8
View File
@@ -88,20 +88,39 @@ func fitTtlCount(count int, unit byte) *TTL {
return EMPTY_TTL
}
// read stored bytes to a ttl
func LoadTTLFromBytes(input []byte) (t *TTL) {
if input[0] == 0 && input[1] == 0 {
// storedTTLs interns every count paired with a defined unit. The master decodes
// one per volume in every heartbeat and keeps it for the volume's lifetime, so
// sharing spares a cluster with millions of volume replicas a distinct two-byte
// object for each.
//
// Entries are immutable. Callers must not write through the returned pointer.
var storedTTLs = func() (table [256][Year + 1]TTL) {
for count := range table {
for unit := range table[count] {
table[count][unit] = TTL{Count: byte(count), Unit: byte(unit)}
}
}
return table
}()
func loadTTL(count, unit byte) *TTL {
if count == 0 && unit == 0 {
return EMPTY_TTL
}
return &TTL{Count: input[0], Unit: input[1]}
if unit <= Year {
return &storedTTLs[count][unit]
}
return &TTL{Count: count, Unit: unit}
}
// read stored bytes to a ttl
func LoadTTLFromBytes(input []byte) (t *TTL) {
return loadTTL(input[0], input[1])
}
// read stored bytes to a ttl
func LoadTTLFromUint32(ttl uint32) (t *TTL) {
input := make([]byte, 2)
input[1] = byte(ttl)
input[0] = byte(ttl >> 8)
return LoadTTLFromBytes(input)
return loadTTL(byte(ttl>>8), byte(ttl))
}
// save stored bytes to an output with 2 bytes
+23
View File
@@ -73,3 +73,26 @@ func TestTTLReadWrite(t *testing.T) {
}
}
func TestLoadTTLIsInterned(t *testing.T) {
for count := 0; count < 256; count++ {
for unit := 0; unit < 256; unit++ {
got := LoadTTLFromBytes([]byte{byte(count), byte(unit)})
if got.Count != byte(count) || got.Unit != byte(unit) {
if count == 0 && unit == 0 {
continue
}
t.Fatalf("count %d unit %d: got %+v", count, unit, got)
}
if fromUint32 := LoadTTLFromUint32(got.ToUint32()); count != 0 && *fromUint32 != *got {
t.Fatalf("count %d unit %d: uint32 round trip gave %+v", count, unit, fromUint32)
}
}
}
if LoadTTLFromBytes([]byte{3, Day}) != LoadTTLFromBytes([]byte{3, Day}) {
t.Error("expected repeated loads of the same stored ttl to share one value")
}
if LoadTTLFromBytes([]byte{0, 0}) != EMPTY_TTL {
t.Error("expected a zero ttl to stay EMPTY_TTL")
}
}
+19 -1
View File
@@ -43,8 +43,26 @@ func NewReplicaPlacementFromString(t string) (*ReplicaPlacement, error) {
return rp, nil
}
// replicaPlacementsByByte is one 6KB pointer-free array covering every encoding
// a byte can hold. The master decodes one per volume in every volume server
// heartbeat and keeps it for the volume's lifetime, so handing out a shared
// element keeps that path off fmt and off the heap entirely.
//
// Elements are immutable. Callers must not write through the returned pointer.
var replicaPlacementsByByte [256]ReplicaPlacement
func init() {
for b := range replicaPlacementsByByte {
replicaPlacementsByByte[b] = ReplicaPlacement{
DiffDataCenterCount: b / 100,
DiffRackCount: b / 10 % 10,
SameRackCount: b % 10,
}
}
}
func NewReplicaPlacementFromByte(b byte) (*ReplicaPlacement, error) {
return NewReplicaPlacementFromString(fmt.Sprintf("%03d", b))
return &replicaPlacementsByByte[b], nil
}
func (rp *ReplicaPlacement) HasReplication() bool {
@@ -1,9 +1,29 @@
package super_block
import (
"fmt"
"testing"
)
func TestReplicaPlacementFromByteMatchesString(t *testing.T) {
for b := 0; b < 256; b++ {
want, err := NewReplicaPlacementFromString(fmt.Sprintf("%03d", b))
if err != nil {
t.Fatalf("byte %d: %v", b, err)
}
got, err := NewReplicaPlacementFromByte(byte(b))
if err != nil {
t.Fatalf("byte %d: %v", b, err)
}
if !got.Equals(want) {
t.Errorf("byte %d: got %+v, want %+v", b, got, want)
}
if got.Byte() != byte(b) {
t.Errorf("byte %d: round trip gave %d", b, got.Byte())
}
}
}
func TestReplicaPlacementSerialDeserial(t *testing.T) {
rp, _ := NewReplicaPlacementFromString("001")
newRp, _ := NewReplicaPlacementFromByte(rp.Byte())
+50
View File
@@ -0,0 +1,50 @@
package storage
import (
"encoding/binary"
"github.com/cespare/xxhash/v2"
)
// ReportHash digests everything a volume server reports about a volume, so the
// two ends of a heartbeat can agree on whether the master's copy is current
// without shipping the volume list.
//
// It must cover every field of VolumeInformationMessage: a change the hash
// misses is a change the master would never be told about. Volume servers hash
// the message they are about to send, masters hash what they already hold, and
// the two match only when the master is up to date.
func (vi VolumeInfo) ReportHash() uint64 {
var buf [57]byte
binary.LittleEndian.PutUint32(buf[0:], uint32(vi.Id))
binary.LittleEndian.PutUint64(buf[4:], vi.Size)
binary.LittleEndian.PutUint64(buf[12:], uint64(vi.FileCount))
binary.LittleEndian.PutUint64(buf[20:], uint64(vi.DeleteCount))
binary.LittleEndian.PutUint64(buf[28:], vi.DeletedByteCount)
binary.LittleEndian.PutUint32(buf[36:], uint32(vi.ReplicaPlacement.Byte()))
binary.LittleEndian.PutUint32(buf[40:], uint32(vi.Version))
binary.LittleEndian.PutUint32(buf[44:], vi.Ttl.ToUint32())
binary.LittleEndian.PutUint32(buf[48:], vi.CompactRevision)
binary.LittleEndian.PutUint32(buf[52:], vi.DiskId)
if vi.ReadOnly {
buf[56] = 1
}
h := xxhash.Sum64(buf[:])
var modified [8]byte
binary.LittleEndian.PutUint64(modified[:], uint64(vi.ModifiedAtSecond))
h = foldReportHash(h, xxhash.Sum64(modified[:]))
h = foldReportHash(h, xxhash.Sum64String(vi.Collection))
h = foldReportHash(h, xxhash.Sum64String(vi.DiskType))
h = foldReportHash(h, xxhash.Sum64String(vi.RemoteStorageName))
h = foldReportHash(h, xxhash.Sum64String(vi.RemoteStorageKey))
return h
}
// foldReportHash combines two hashes order-dependently, so swapping two string
// fields is not invisible.
func foldReportHash(h, x uint64) uint64 {
h ^= x
h *= 0x9E3779B97F4A7C15
return h ^ (h >> 29)
}
+53 -39
View File
@@ -2,7 +2,6 @@ package topology
import (
"fmt"
"slices"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/glog"
@@ -25,6 +24,12 @@ type DataNode struct {
IsTerminating bool
MaintenanceMode bool
// lookupDigest covers the volumes reachable through this node in the volume
// layouts, for comparison against what its disks actually hold.
lookupDigest atomic.Uint64
// duplicateVolumeIds records that the node last reported one volume id more
// than once, which the master cannot represent.
duplicateVolumeIds atomic.Bool
// diskMetas holds each physical disk's tags, type, and capacity from the
// heartbeat DiskTags, including disks with no volumes or EC shards.
diskMetas map[uint32]diskMeta
@@ -78,22 +83,26 @@ func (dn *DataNode) doAddOrUpdateVolume(v storage.VolumeInfo) (isNew, isChanged
// used in master to notify master clients of these changes.
func (dn *DataNode) UpdateVolumes(actualVolumes []storage.VolumeInfo) (newVolumes, deletedVolumes, changedVolumes []storage.VolumeInfo) {
actualVolumeMap := make(map[needle.VolumeId]storage.VolumeInfo)
actualVolumeIds := make(map[needle.VolumeId]struct{}, len(actualVolumes))
for _, v := range actualVolumes {
actualVolumeMap[v.Id] = v
actualVolumeIds[v.Id] = struct{}{}
}
// A volume id mounted on two disks of one server -- a stale twin re-attached
// after a disk repair -- is reported twice, but the master keys volumes by
// id alone and keeps only the last copy. Its digest can then never equal the
// server's however often the list is resent, so record it and let the
// heartbeat fall back to the full list for this node.
dn.duplicateVolumeIds.Store(len(actualVolumeIds) < len(actualVolumes))
dn.Lock()
defer dn.Unlock()
existingVolumes := dn.getVolumes()
for _, v := range existingVolumes {
vid := v.Id
if _, ok := actualVolumeMap[vid]; !ok {
glog.V(0).Infoln("Deleting volume id:", vid)
disk := dn.getOrCreateDisk(v.DiskType)
disk.DeleteVolumeById(vid)
keptCount := 0
for _, c := range dn.children {
disk := c.(*Disk)
for _, v := range disk.RemoveVolumesNotIn(actualVolumeIds) {
glog.V(0).Infoln("Deleting volume id:", v.Id)
deletedVolumes = append(deletedVolumes, v)
deltaDiskUsage := &DiskUsageCounts{}
@@ -106,6 +115,13 @@ func (dn *DataNode) UpdateVolumes(actualVolumes []storage.VolumeInfo) (newVolume
}
disk.UpAdjustDiskUsageDelta(types.ToDiskType(v.DiskType), deltaDiskUsage)
}
keptCount += disk.VolumeCount()
}
// Everything still on the node is also in this heartbeat, so the remainder
// is what the node is about to gain. A steady-state heartbeat gains nothing
// and must not allocate here; a reconnecting server gains all of them.
if addedCount := len(actualVolumes) - keptCount; addedCount > 0 {
newVolumes = make([]storage.VolumeInfo, 0, addedCount)
}
for _, v := range actualVolumes {
isNew, isChanged := dn.doAddOrUpdateVolume(v)
@@ -196,14 +212,37 @@ func (dn *DataNode) AdjustDiskUsageBytes(diskTotalBytes, diskFreeBytes map[strin
func (dn *DataNode) GetVolumes() (ret []storage.VolumeInfo) {
dn.RLock()
defer dn.RUnlock()
total := 0
for _, c := range dn.children {
disk := c.(*Disk)
ret = append(ret, disk.GetVolumes()...)
total += c.(*Disk).VolumeCount()
}
ret = make([]storage.VolumeInfo, 0, total)
for _, c := range dn.children {
ret = c.(*Disk).AppendVolumes(ret)
}
dn.RUnlock()
return ret
}
// HasDuplicateVolumeIds reports whether the node's last full report named one
// volume id more than once. While it does, the node's digest is not meaningful.
func (dn *DataNode) HasDuplicateVolumeIds() bool {
return dn.duplicateVolumeIds.Load()
}
// VolumeDigest summarises every volume the master believes this node holds. A
// volume server that reports a different digest has drifted from the master and
// needs to resend its volume list.
func (dn *DataNode) VolumeDigest() uint64 {
dn.RLock()
defer dn.RUnlock()
var digest uint64
for _, c := range dn.children {
digest ^= c.(*Disk).VolumeDigest()
}
return digest
}
func (dn *DataNode) GetVolumesById(id needle.VolumeId) (vInfo storage.VolumeInfo, err error) {
dn.RLock()
defer dn.RUnlock()
@@ -384,28 +423,3 @@ func (dn *DataNode) UpdateDiskTags(tags []*master_pb.DiskTag) {
dn.diskMetas = metas
dn.Unlock()
}
// GetVolumeIds returns the human readable volume ids limited to count of max 100.
func (dn *DataNode) GetVolumeIds() string {
dn.RLock()
defer dn.RUnlock()
existingVolumes := dn.getVolumes()
ids := make([]int, 0, len(existingVolumes))
for k := range existingVolumes {
ids = append(ids, int(k))
}
slices.Sort(ids)
return util.HumanReadableIntsMax(100, ids...)
}
func (dn *DataNode) getVolumes() []storage.VolumeInfo {
var existingVolumes []storage.VolumeInfo
for _, c := range dn.children {
disk := c.(*Disk)
existingVolumes = append(existingVolumes, disk.GetVolumes()...)
}
return existingVolumes
}
+66 -5
View File
@@ -26,6 +26,15 @@ type Disk struct {
// outer key is the volume id; the inner key is the physical disk id.
ecShards map[needle.VolumeId]map[types.DiskId]*erasure_coding.EcVolumeInfo
ecShardsLock sync.RWMutex
// volumeDigest is the xor of every volume's ReportHash. Order-independent
// and its own inverse, so it stays current by xoring a volume out before
// its old state is dropped and back in after the new one lands.
volumeDigest uint64
// volumeIdDigest covers which volumes are on the disk, ignoring their
// state, so it can be compared against the lookup index the master serves
// reads from. The two indexes are maintained separately and have been seen
// to drift.
volumeIdDigest uint64
}
// ecShardSlots returns the number of volume slots consumed by the given
@@ -163,6 +172,8 @@ func (d *Disk) doAddOrUpdateVolume(v storage.VolumeInfo) (isNew, isChanged bool)
deltaDiskUsage := &DiskUsageCounts{}
if oldV, ok := d.volumes[v.Id]; !ok {
d.volumes[v.Id] = v
d.volumeDigest ^= v.ReportHash()
d.volumeIdDigest ^= VolumeIdDigestHash(v.Id)
deltaDiskUsage.volumeCount = 1
if v.IsRemote() {
deltaDiskUsage.remoteVolumeCount = 1
@@ -183,6 +194,7 @@ func (d *Disk) doAddOrUpdateVolume(v storage.VolumeInfo) (isNew, isChanged bool)
}
d.UpAdjustDiskUsageDelta(types.ToDiskType(v.DiskType), deltaDiskUsage)
}
d.volumeDigest ^= oldV.ReportHash() ^ v.ReportHash()
isChanged = d.volumes[v.Id].ReadOnly != v.ReadOnly
if isChanged {
// Adjust active volume count when ReadOnly status changes
@@ -202,13 +214,42 @@ func (d *Disk) doAddOrUpdateVolume(v storage.VolumeInfo) (isNew, isChanged bool)
return
}
func (d *Disk) GetVolumes() (ret []storage.VolumeInfo) {
func (d *Disk) GetVolumes() []storage.VolumeInfo {
return d.AppendVolumes(make([]storage.VolumeInfo, 0, d.VolumeCount()))
}
// AppendVolumes appends the disk's volumes to dst, so a caller gathering
// several disks fills one slice instead of concatenating a copy per disk.
func (d *Disk) AppendVolumes(dst []storage.VolumeInfo) []storage.VolumeInfo {
d.RLock()
defer d.RUnlock()
for _, v := range d.volumes {
ret = append(ret, v)
dst = append(dst, v)
}
d.RUnlock()
return ret
return dst
}
func (d *Disk) VolumeCount() int {
d.RLock()
defer d.RUnlock()
return len(d.volumes)
}
// RemoveVolumesNotIn drops the volumes whose ids are absent from keep and
// returns them, so a heartbeat can be diffed without first copying the whole
// volume map out.
func (d *Disk) RemoveVolumesNotIn(keep map[needle.VolumeId]struct{}) (removed []storage.VolumeInfo) {
d.Lock()
defer d.Unlock()
for vid, v := range d.volumes {
if _, ok := keep[vid]; !ok {
removed = append(removed, v)
delete(d.volumes, vid)
d.volumeDigest ^= v.ReportHash()
d.volumeIdDigest ^= VolumeIdDigestHash(vid)
}
}
return removed
}
func (d *Disk) GetVolumesById(id needle.VolumeId) (storage.VolumeInfo, error) {
@@ -225,7 +266,25 @@ func (d *Disk) GetVolumesById(id needle.VolumeId) (storage.VolumeInfo, error) {
func (d *Disk) DeleteVolumeById(id needle.VolumeId) {
d.Lock()
defer d.Unlock()
delete(d.volumes, id)
if v, ok := d.volumes[id]; ok {
d.volumeDigest ^= v.ReportHash()
d.volumeIdDigest ^= VolumeIdDigestHash(id)
delete(d.volumes, id)
}
}
// VolumeDigest returns the disk's running volume digest.
func (d *Disk) VolumeDigest() uint64 {
d.RLock()
defer d.RUnlock()
return d.volumeDigest
}
// VolumeIdDigest returns the digest of which volumes the disk holds.
func (d *Disk) VolumeIdDigest() uint64 {
d.RLock()
defer d.RUnlock()
return d.volumeIdDigest
}
func (d *Disk) GetDataCenter() *DataCenter {
@@ -289,9 +348,11 @@ func (d *Disk) ToDiskInfo() *master_pb.DiskInfo {
DiskTotalBytes: uint64(max(0, diskUsage.diskTotalBytes)),
DiskFreeBytes: uint64(max(0, diskUsage.diskFreeBytes)),
}
m.VolumeInfos = make([]*master_pb.VolumeInformationMessage, 0, len(volumes))
for _, v := range volumes {
m.VolumeInfos = append(m.VolumeInfos, v.ToVolumeInformationMessage())
}
m.EcShardInfos = make([]*master_pb.VolumeEcShardInformationMessage, 0, len(ecShards))
for _, ecv := range ecShards {
m.EcShardInfos = append(m.EcShardInfos, ecv.ToVolumeEcShardInformationMessage())
}
+1 -1
View File
@@ -587,7 +587,7 @@ func (t *Topology) ListDCAndRacks() (dcs map[NodeId][]NodeId) {
func (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformationMessage, dn *DataNode) (newVolumes, deletedVolumes []storage.VolumeInfo) {
// convert into in memory struct storage.VolumeInfo
var volumeInfos []storage.VolumeInfo
volumeInfos := make([]storage.VolumeInfo, 0, len(volumes))
for _, v := range volumes {
if vi, err := storage.NewVolumeInfo(v); err == nil {
volumeInfos = append(volumeInfos, vi)
@@ -0,0 +1,52 @@
package topology
import (
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
func benchHeartbeatMessages(count int) []*master_pb.VolumeInformationMessage {
messages := make([]*master_pb.VolumeInformationMessage, 0, count)
for i := 0; i < count; i++ {
messages = append(messages, &master_pb.VolumeInformationMessage{
Id: uint32(i),
Size: 1024 * 1024,
Collection: "benchcollection",
FileCount: 100,
DeleteCount: 1,
DeletedByteCount: 1024,
ReplicaPlacement: 0,
Version: 3,
CompactRevision: 1,
ModifiedAtSecond: 1700000000,
})
}
return messages
}
// A volume server re-sends its whole volume list on every heartbeat, so this is
// the master's steady-state cost per volume server every VolumePulsePeriod.
func benchSyncDataNodeRegistration(b *testing.B, count int) {
topo := NewTopology("bench", nil, 32*1024*1024*1024, 5, false)
dn := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
GetOrCreateDataNode("127.0.0.1", 8080, 18080, "", "", map[string]uint32{"": uint32(count) * 2})
topo.SyncDataNodeRegistration(benchHeartbeatMessages(count), dn)
messages := benchHeartbeatMessages(count)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
topo.SyncDataNodeRegistration(messages, dn)
}
}
func BenchmarkSyncDataNodeRegistration(b *testing.B) {
for _, count := range []int{1000, 100000} {
b.Run(fmt.Sprintf("%dVolumes", count), func(b *testing.B) {
benchSyncDataNodeRegistration(b, count)
})
}
}
+6 -3
View File
@@ -72,8 +72,9 @@ func (t *Topology) ToVolumeMap() interface{} {
dataNodes := make(map[NodeId]interface{})
for _, d := range rack.Children() {
dn := d.(*DataNode)
var volumes []interface{}
for _, v := range dn.GetVolumes() {
dnVolumes := dn.GetVolumes()
volumes := make([]interface{}, 0, len(dnVolumes))
for _, v := range dnVolumes {
volumes = append(volumes, v)
}
dataNodes[d.Id()] = volumes
@@ -99,7 +100,9 @@ func (t *Topology) ToVolumeLocations() (volumeLocations []*master_pb.VolumeLocat
DataCenter: dn.GetDataCenterId(),
GrpcPort: uint32(dn.GrpcPort),
}
for _, v := range dn.GetVolumes() {
dnVolumes := dn.GetVolumes()
volumeLocation.NewVids = make([]uint32, 0, len(dnVolumes))
for _, v := range dnVolumes {
volumeLocation.NewVids = append(volumeLocation.NewVids, uint32(v.Id))
}
// A single EC volume's shards can live on multiple disks of
+410
View File
@@ -0,0 +1,410 @@
package topology
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
func digestTestNode(t *testing.T) (*Topology, *DataNode) {
t.Helper()
topo := NewTopology("digest", nil, 32*1024*1024*1024, 5, false)
dn := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
GetOrCreateDataNode("127.0.0.1", 8080, 18080, "", "", map[string]uint32{"": 1000})
return topo, dn
}
func digestTestVolume(id uint32) *master_pb.VolumeInformationMessage {
return &master_pb.VolumeInformationMessage{
Id: id,
Size: 1024 * 1024,
Collection: "c",
FileCount: 10,
DeleteCount: 1,
DeletedByteCount: 128,
ReplicaPlacement: 0,
Version: 3,
CompactRevision: 1,
ModifiedAtSecond: 1700000000,
}
}
func TestVolumeDigestIsStableAcrossRepeatedHeartbeats(t *testing.T) {
topo, dn := digestTestNode(t)
volumes := []*master_pb.VolumeInformationMessage{digestTestVolume(1), digestTestVolume(2), digestTestVolume(3)}
topo.SyncDataNodeRegistration(volumes, dn)
first := dn.VolumeDigest()
if first == 0 {
t.Fatal("expected a non-zero digest for a node holding volumes")
}
for i := 0; i < 3; i++ {
topo.SyncDataNodeRegistration(volumes, dn)
if got := dn.VolumeDigest(); got != first {
t.Fatalf("heartbeat %d changed the digest with no change to report: %d != %d", i, got, first)
}
}
}
func TestVolumeDigestIsIndependentOfReportOrder(t *testing.T) {
topoA, dnA := digestTestNode(t)
topoA.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
digestTestVolume(1), digestTestVolume(2), digestTestVolume(3),
}, dnA)
topoB, dnB := digestTestNode(t)
topoB.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
digestTestVolume(3), digestTestVolume(1), digestTestVolume(2),
}, dnB)
if dnA.VolumeDigest() != dnB.VolumeDigest() {
t.Errorf("digest depends on report order: %d != %d", dnA.VolumeDigest(), dnB.VolumeDigest())
}
}
func TestVolumeDigestTracksEveryReportedField(t *testing.T) {
base := digestTestVolume(1)
mutations := map[string]func(*master_pb.VolumeInformationMessage){
"Id": func(m *master_pb.VolumeInformationMessage) { m.Id = 2 },
"Size": func(m *master_pb.VolumeInformationMessage) { m.Size++ },
"Collection": func(m *master_pb.VolumeInformationMessage) { m.Collection = "other" },
"FileCount": func(m *master_pb.VolumeInformationMessage) { m.FileCount++ },
"DeleteCount": func(m *master_pb.VolumeInformationMessage) { m.DeleteCount++ },
"DeletedByteCount": func(m *master_pb.VolumeInformationMessage) { m.DeletedByteCount++ },
"ReadOnly": func(m *master_pb.VolumeInformationMessage) { m.ReadOnly = true },
"ReplicaPlacement": func(m *master_pb.VolumeInformationMessage) { m.ReplicaPlacement = 10 },
"Version": func(m *master_pb.VolumeInformationMessage) { m.Version = 2 },
"Ttl": func(m *master_pb.VolumeInformationMessage) { m.Ttl = 3 << 8 },
"CompactRevision": func(m *master_pb.VolumeInformationMessage) { m.CompactRevision++ },
"ModifiedAtSecond": func(m *master_pb.VolumeInformationMessage) { m.ModifiedAtSecond++ },
"RemoteStorageName": func(m *master_pb.VolumeInformationMessage) { m.RemoteStorageName = "s3" },
"RemoteStorageKey": func(m *master_pb.VolumeInformationMessage) { m.RemoteStorageKey = "k" },
"DiskType": func(m *master_pb.VolumeInformationMessage) { m.DiskType = "ssd" },
"DiskId": func(m *master_pb.VolumeInformationMessage) { m.DiskId = 1 },
}
baseInfo, err := storage.NewVolumeInfo(base)
if err != nil {
t.Fatal(err)
}
for name, mutate := range mutations {
t.Run(name, func(t *testing.T) {
changed := digestTestVolume(1)
mutate(changed)
changedInfo, err := storage.NewVolumeInfo(changed)
if err != nil {
t.Fatal(err)
}
if baseInfo.ReportHash() == changedInfo.ReportHash() {
t.Errorf("a change to %s is invisible to the digest, so the master would never be told about it", name)
}
})
}
}
func TestVolumeDigestFollowsVolumeChanges(t *testing.T) {
topo, dn := digestTestNode(t)
volumes := []*master_pb.VolumeInformationMessage{digestTestVolume(1), digestTestVolume(2)}
topo.SyncDataNodeRegistration(volumes, dn)
original := dn.VolumeDigest()
grown := []*master_pb.VolumeInformationMessage{digestTestVolume(1), digestTestVolume(2)}
grown[1].Size += 4096
topo.SyncDataNodeRegistration(grown, dn)
if dn.VolumeDigest() == original {
t.Error("a volume that grew left the digest unchanged")
}
topo.SyncDataNodeRegistration(volumes, dn)
if dn.VolumeDigest() != original {
t.Error("reverting a volume did not restore the digest")
}
topo.SyncDataNodeRegistration(volumes[:1], dn)
if dn.VolumeDigest() == original {
t.Error("dropping a volume left the digest unchanged")
}
topo.SyncDataNodeRegistration(volumes, dn)
if dn.VolumeDigest() != original {
t.Error("restoring a dropped volume did not restore the digest")
}
}
func TestVolumeDigestEmptiesWithTheNode(t *testing.T) {
topo, dn := digestTestNode(t)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
digestTestVolume(1), digestTestVolume(2),
}, dn)
topo.SyncDataNodeRegistration(nil, dn)
if got := dn.VolumeDigest(); got != 0 {
t.Errorf("expected an empty node to digest to 0, got %d", got)
}
}
func TestVolumeDigestFollowsDeltaRegistration(t *testing.T) {
topo, dn := digestTestNode(t)
full := []*master_pb.VolumeInformationMessage{digestTestVolume(1), digestTestVolume(2)}
topo.SyncDataNodeRegistration(full, dn)
both := dn.VolumeDigest()
topo.IncrementalSyncDataNodeRegistration(nil, []*master_pb.VolumeShortInformationMessage{{Id: 2}}, dn)
if dn.VolumeDigest() == both {
t.Error("unmounting a volume left the digest unchanged")
}
topo.SyncDataNodeRegistration(full, dn)
if dn.VolumeDigest() != both {
t.Error("a full heartbeat did not restore the digest after an unmount")
}
}
// The point of the digest is not to detect that volumes changed -- in any live
// cluster some always have. It is to confirm that after applying the changes a
// heartbeat did carry, the master holds what the volume server holds. So a
// heartbeat reporting only the volumes that moved must still reconcile.
func TestVolumeDigestMatchesAfterApplyingOnlyChangedVolumes(t *testing.T) {
const total = 50
full := make([]*master_pb.VolumeInformationMessage, 0, total)
for i := 1; i <= total; i++ {
v := digestTestVolume(uint32(i))
v.ReadOnly = i > 5 // only the first few are writable, as in a tiered cluster
full = append(full, v)
}
topo, dn := digestTestNode(t)
topo.SyncDataNodeRegistration(full, dn)
// Three writable volumes take writes between two heartbeats.
changed := make([]storage.VolumeInfo, 0, 3)
for _, v := range full[:3] {
v.Size += 4096
v.FileCount++
v.ModifiedAtSecond += 5
vi, err := storage.NewVolumeInfo(v)
if err != nil {
t.Fatal(err)
}
changed = append(changed, vi)
}
// What the volume server would now report for its whole set.
reference, referenceNode := digestTestNode(t)
reference.SyncDataNodeRegistration(full, referenceNode)
want := referenceNode.VolumeDigest()
if dn.VolumeDigest() == want {
t.Fatal("expected the master to be behind before the changes are applied")
}
// The heartbeat carries three volumes, not fifty.
dn.DeltaUpdateVolumes(changed, nil)
if got := dn.VolumeDigest(); got != want {
t.Errorf("digest still disagrees after applying the reported changes: %d != %d", got, want)
}
}
// A volume that disappears without a delta is exactly what the full list exists
// to catch, and is the case the digest has to keep catching.
func TestVolumeDigestCatchesASilentlyLostVolume(t *testing.T) {
full := []*master_pb.VolumeInformationMessage{
digestTestVolume(1), digestTestVolume(2), digestTestVolume(3),
}
topo, dn := digestTestNode(t)
topo.SyncDataNodeRegistration(full, dn)
// The volume server no longer has volume 2 and never got to say so.
reference, referenceNode := digestTestNode(t)
reference.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{full[0], full[2]}, referenceNode)
if dn.VolumeDigest() == referenceNode.VolumeDigest() {
t.Error("a volume lost without a delta went undetected, which is what the full list is for")
}
}
// The disk map and the lookup index are maintained separately, and a disconnect
// racing a reconnect has been seen to drop a volume from the lookup index while
// leaving it on the node. The volume server's report is identical either way, so
// the heartbeat digest cannot see it and the master has to notice on its own.
func TestVolumeIndexDigestSeesLookupDivergence(t *testing.T) {
topo, dn := digestTestNode(t)
v := digestTestVolume(1)
v.Collection = "drr"
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{v}, dn)
if !dn.HasConsistentVolumeIndex() {
t.Fatal("a freshly registered node should have a consistent index")
}
reported := dn.VolumeDigest()
rp, _ := super_block.NewReplicaPlacementFromString("000")
vl := topo.GetVolumeLayout("drr", rp, needle.EMPTY_TTL, types.HardDriveType)
vl.SetVolumeUnavailable(dn, needle.VolumeId(1))
if got := topo.Lookup("drr", needle.VolumeId(1)); got != nil {
t.Fatalf("expected the volume to have become unservable, got %v", got)
}
if _, err := dn.GetVolumesById(needle.VolumeId(1)); err != nil {
t.Fatalf("the volume should still be on the node: %v", err)
}
if dn.VolumeDigest() != reported {
t.Error("the reported digest should not move: the volume server sees no change")
}
if dn.HasConsistentVolumeIndex() {
t.Error("a volume held but not servable left the index digests agreeing, so nothing would repair it")
}
// The full heartbeat self-heal puts it back.
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{v}, dn)
if !dn.HasConsistentVolumeIndex() {
t.Error("the self-heal did not restore index consistency")
}
}
func TestVolumeIndexDigestFollowsNodeLifecycle(t *testing.T) {
topo, dn := digestTestNode(t)
full := []*master_pb.VolumeInformationMessage{digestTestVolume(1), digestTestVolume(2), digestTestVolume(3)}
topo.SyncDataNodeRegistration(full, dn)
if !dn.HasConsistentVolumeIndex() {
t.Fatal("registration left the indexes disagreeing")
}
topo.SyncDataNodeRegistration(full[:2], dn)
if !dn.HasConsistentVolumeIndex() {
t.Error("dropping a volume left the indexes disagreeing")
}
topo.IncrementalSyncDataNodeRegistration(
[]*master_pb.VolumeShortInformationMessage{{Id: 9}}, nil, dn)
if !dn.HasConsistentVolumeIndex() {
t.Error("a mount delta left the indexes disagreeing")
}
topo.IncrementalSyncDataNodeRegistration(
nil, []*master_pb.VolumeShortInformationMessage{{Id: 9}}, dn)
if !dn.HasConsistentVolumeIndex() {
t.Error("an unmount delta left the indexes disagreeing")
}
topo.UnRegisterDataNode(dn)
held, servable := dn.VolumeIndexDigests()
if held != 0 || servable != 0 {
t.Errorf("an unregistered node should hold nothing: held=%d servable=%d", held, servable)
}
}
// A volume id mounted on two disks of one server is reported twice with
// different disk ids, but the master keys volumes by id alone, so it keeps only
// one copy and its digest can never equal the server's. Resending the full list
// cannot fix that, so the node has to be excluded from digest comparison
// entirely rather than resend forever.
func TestVolumeDigestRefusesDuplicateVolumeIds(t *testing.T) {
topo, dn := digestTestNode(t)
first := digestTestVolume(1)
second := digestTestVolume(1)
second.DiskId = 1
second.Size = first.Size * 2
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{first, second}, dn)
if !dn.HasDuplicateVolumeIds() {
t.Fatal("a volume id reported twice went unnoticed, so the digest would be trusted and never reconcile")
}
firstInfo, err := storage.NewVolumeInfo(first)
if err != nil {
t.Fatal(err)
}
secondInfo, err := storage.NewVolumeInfo(second)
if err != nil {
t.Fatal(err)
}
if dn.VolumeDigest() == firstInfo.ReportHash()^secondInfo.ReportHash() {
t.Error("expected the master to be unable to represent both copies; if it now can, the guard is no longer needed")
}
// Once the stale twin is gone the node is comparable again.
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{first}, dn)
if dn.HasDuplicateVolumeIds() {
t.Error("the node stayed marked as duplicated after reporting a clean list")
}
if dn.VolumeDigest() != firstInfo.ReportHash() {
t.Error("digest did not settle on the surviving copy")
}
}
// Two volume servers can hold one address. GetOrCreateDataNode keys on the id a
// server reports and deliberately refuses to merge a new id onto an address an
// older node still claims, while the lookup list keys on address alone -- so
// registering the second server displaces the first from the lookup entry
// without either node being told. The digest has to follow the entry, not the
// node that was passed in.
func addressSharingNodes(t *testing.T) (*Topology, *DataNode, *DataNode) {
t.Helper()
topo := NewTopology("digest", nil, 32*1024*1024*1024, 5, false)
rack := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1")
counts := map[string]uint32{"": 1000}
old := rack.GetOrCreateDataNode("10.1.2.3", 8080, 18080, "", "n1", counts)
fresh := rack.GetOrCreateDataNode("10.1.2.3", 8080, 18080, "", "n2", counts)
if old == fresh {
t.Skip("address reuse no longer produces two nodes")
}
return topo, old, fresh
}
func TestVolumeIndexDigestFollowsDisplacedLookupEntry(t *testing.T) {
topo, old, fresh := addressSharingNodes(t)
v := digestTestVolume(1)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{v}, old)
if !old.HasConsistentVolumeIndex() {
t.Fatal("the first node should be consistent before it is displaced")
}
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{v}, fresh)
servable := map[*DataNode]bool{}
for _, dn := range topo.Lookup("", needle.VolumeId(1)) {
servable[dn] = true
}
if servable[old] || !servable[fresh] {
t.Fatalf("expected the lookup entry to move to the new node, got old=%v fresh=%v",
servable[old], servable[fresh])
}
if old.HasConsistentVolumeIndex() {
t.Error("the displaced node still holds the volume and can no longer serve it, so its index must read as inconsistent")
}
if !fresh.HasConsistentVolumeIndex() {
t.Error("the node the lookup entry now names reads as inconsistent")
}
}
func TestVolumeIndexDigestFollowsRemovedLookupEntry(t *testing.T) {
topo, old, fresh := addressSharingNodes(t)
v := digestTestVolume(1)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{v}, old)
// fresh shares old's address, so unregistering through it removes old's
// lookup entry. The digest must come off the node that was actually removed.
rp, _ := super_block.NewReplicaPlacementFromString("000")
vl := topo.GetVolumeLayout("c", rp, needle.EMPTY_TTL, types.HardDriveType)
vl.SetVolumeUnavailable(fresh, needle.VolumeId(1))
if got := topo.Lookup("c", needle.VolumeId(1)); got != nil {
t.Fatalf("expected the lookup entry to be gone, got %v", got)
}
if old.HasConsistentVolumeIndex() {
t.Error("the removed node still holds the volume and cannot serve it, so its index must read as inconsistent")
}
if _, servable := fresh.VolumeIndexDigests(); servable != 0 {
t.Error("the node that was merely passed in should never have gained the entry")
}
}
+69
View File
@@ -0,0 +1,69 @@
package topology
import (
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
// VolumeIdDigestHash spreads a volume id across the whole 64-bit range so that
// xoring a set of them together does not collide for the near-consecutive ids a
// cluster actually allocates.
func VolumeIdDigestHash(vid needle.VolumeId) uint64 {
h := uint64(vid) + 0x9E3779B97F4A7C15
h = (h ^ (h >> 30)) * 0xBF58476D1CE4E5B9
h = (h ^ (h >> 27)) * 0x94D049BB133111EB
return h ^ (h >> 31)
}
// VolumeIndexDigests returns the digest of the volumes the node's disks hold and
// the digest of the volumes the lookup index will serve from that node.
//
// The master keeps those two indexes separately, and a disconnect racing a
// reconnect has been seen to drop a volume from the lookup index while leaving
// it on the node: the volume stays visible in volume.list and the admin UI while
// LookupVolume answers "volume id not found". A volume server cannot detect that
// -- its own report is identical either way -- so the master has to notice it
// on its own rather than rely on the heartbeat digest.
func (dn *DataNode) VolumeIndexDigests() (held, servable uint64) {
dn.RLock()
for _, c := range dn.children {
held ^= c.(*Disk).VolumeIdDigest()
}
dn.RUnlock()
return held, dn.lookupDigest.Load()
}
// HasConsistentVolumeIndex reports whether every volume on the node is reachable
// through the lookup index, and nothing else is.
func (dn *DataNode) HasConsistentVolumeIndex() bool {
held, servable := dn.VolumeIndexDigests()
return held == servable
}
// moveLookupOwnership transfers the digest bit for vid from the node a lookup
// entry used to name to the node it now names. Either may be nil, for an entry
// being created or dropped.
func moveLookupOwnership(vid needle.VolumeId, from, to *DataNode) {
if from == to {
return
}
if from != nil {
from.trackLookupChange(vid)
}
if to != nil {
to.trackLookupChange(vid)
}
}
// trackLookupChange records that vid became reachable through this node, or
// stopped being: xor is its own inverse, so both are the same update. Volume
// layouts for different collections share the node, so it cannot assume the
// caller's lock.
func (dn *DataNode) trackLookupChange(vid needle.VolumeId) {
delta := VolumeIdDigestHash(vid)
for {
old := dn.lookupDigest.Load()
if dn.lookupDigest.CompareAndSwap(old, old^delta) {
return
}
}
}
+22 -16
View File
@@ -196,7 +196,7 @@ func (vl *VolumeLayout) RegisterVolume(v *storage.VolumeInfo, dn *DataNode) {
defer vl.rememberOversizedVolume(v, dn)
vl.getOrCreateLocationList(v.Id).Set(dn)
moveLookupOwnership(v.Id, vl.getOrCreateLocationList(v.Id).Set(dn), dn)
vl.initSizeTracking(v.Id, v.Size, v.CompactRevision)
// glog.V(4).Infof("volume %d added to %s len %d copy %d", v.Id, dn.Id(), vl.vid2location[v.Id].Length(), v.ReplicaPlacement.GetCopyCount())
for _, dn := range vl.vid2location[v.Id].list {
@@ -315,7 +315,8 @@ func (vl *VolumeLayout) UnRegisterVolume(v *storage.VolumeInfo, dn *DataNode) {
return
}
if location.Remove(dn) {
if removed := location.Remove(dn); removed != nil {
moveLookupOwnership(v.Id, removed, nil)
vl.readonlyVolumes.Remove(v.Id, dn)
vl.oversizedVolumes.Remove(v.Id, dn)
@@ -343,18 +344,22 @@ func (vl *VolumeLayout) ensureCorrectWritables(vid needle.VolumeId) {
isOversizedVolume := vl.oversizedVolumes.IsTrue(vid)
if isEnoughCopies && isAllWritable && !isOversizedVolume {
vl.setVolumeWritable(vid)
} else {
if !isEnoughCopies {
glog.V(0).Infof("volume %d does not have enough copies", vid)
}
if !isAllWritable {
glog.V(0).Infof("volume %d are not all writable", vid)
}
if isOversizedVolume {
glog.V(1).Infof("volume %d are oversized", vid)
}
glog.V(0).Infof("volume %d remove from writable", vid)
vl.removeFromWritable(vid)
return
}
// removeFromWritable reports the transition itself, and only when there is
// one. Explain it only then: every heartbeat re-runs this for every volume,
// so a volume that is simply staying read-only must not log.
if !vl.removeFromWritable(vid) {
return
}
if !isEnoughCopies {
glog.V(0).Infof("volume %d does not have enough copies", vid)
}
if !isAllWritable {
glog.V(0).Infof("volume %d is not fully writable", vid)
}
if isOversizedVolume {
glog.V(0).Infof("volume %d is oversized", vid)
}
}
@@ -875,7 +880,8 @@ func (vl *VolumeLayout) SetVolumeUnavailable(dn *DataNode, vid needle.VolumeId)
defer vl.accessLock.Unlock()
if location, ok := vl.vid2location[vid]; ok {
if location.Remove(dn) {
if removed := location.Remove(dn); removed != nil {
moveLookupOwnership(vid, removed, nil)
vl.readonlyVolumes.Remove(vid, dn)
vl.oversizedVolumes.Remove(vid, dn)
wasWritable := false
@@ -915,7 +921,7 @@ func (vl *VolumeLayout) SetVolumeAvailable(dn *DataNode, vid needle.VolumeId, is
// A disconnect during a long vacuum can drop the entry while the volume is
// still on the node; re-create it (and seed size tracking) instead of
// dereferencing a nil location, so the commit also repairs the split.
vl.getOrCreateLocationList(vid).Set(dn)
moveLookupOwnership(vid, vl.getOrCreateLocationList(vid).Set(dn), dn)
vl.initSizeTracking(vid, vInfo.Size, vInfo.CompactRevision)
if vInfo.ReadOnly || isReadOnly || isFullCapacity {
+16 -5
View File
@@ -46,24 +46,35 @@ func (dnll *VolumeLocationList) Length() int {
return len(dnll.list)
}
func (dnll *VolumeLocationList) Set(loc *DataNode) {
// Set adds loc, or replaces the entry at the same address, returning the node it
// displaced. Two volume servers can share an address -- GetOrCreateDataNode keys
// on the reported id and refuses to merge a new id onto an address an older node
// still claims -- so the displaced node is not necessarily loc, and callers
// tracking which node a volume is reachable through must move their bookkeeping
// off it rather than assume loc already owned the entry.
func (dnll *VolumeLocationList) Set(loc *DataNode) (displaced *DataNode) {
for i := 0; i < len(dnll.list); i++ {
if loc.Ip == dnll.list[i].Ip && loc.Port == dnll.list[i].Port {
displaced = dnll.list[i]
dnll.list[i] = loc
return
return displaced
}
}
dnll.list = append(dnll.list, loc)
return nil
}
func (dnll *VolumeLocationList) Remove(loc *DataNode) bool {
// Remove drops the entry at loc's address and returns the node removed, or nil
// if the volume was not reachable there. As with Set, the removed node is
// matched by address and need not be loc.
func (dnll *VolumeLocationList) Remove(loc *DataNode) (removed *DataNode) {
for i, dnl := range dnll.list {
if loc.Ip == dnl.Ip && loc.Port == dnl.Port {
dnll.list = append(dnll.list[:i], dnll.list[i+1:]...)
return true
return dnl
}
}
return false
return nil
}
func (dnll *VolumeLocationList) Refresh(freshThreshHold int64) {