Compare commits

..
Author SHA1 Message Date
Chris LuandDevin 0f342e8abe ci: extract the tar in the rust-volume-go-tests shards too
The shard restore step only chmodded paths that were never unpacked —
the tar extract was added to rust-integration-tests but missed here.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 06:02:51 -07:00
Chris LuandDevin f6d019eb3c ci: preserve binary paths through the artifact round-trip
upload-artifact stores single files flat, so weed/weed would come back
at the workspace root and the consumers' expected paths break. Pack the
binaries in a tar before upload and extract on download.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 03:44:18 -07:00
Chris LuandDevin ff2fbfc6be ci: build test binaries once, share them across shard jobs
Each of the 6 rust-volume-go-tests shards, the rust-integration-tests
job, and the 6 volume-server-integration-tests shards rebuilt the same
weed and weed-volume binaries — 13 duplicate builds per run. A
build-test-binaries / build-weed job now compiles them once under the
existing cargo cache and publishes them as artifacts; the consumers
download and chmod them instead of building.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 03:41:32 -07:00
Chris LuandDevin ab738bfd33 rust volume: repair an unindexed .dat tail at load (#11878)
* rust volume: repair an unindexed .dat tail at load

Mirror Go's repairUnindexedDatTail (#11870): a crash between the .dat\nappend and the .idx append leaves a .dat tail no index entry covers,\nwhich sent the volume read-only on the next load and left acknowledged\nneedles unreadable. Before the index loads, re-index the complete\nneedles in the tail (a size 0 record as the tombstone or empty write\nresolveEmptyTailRecords reads it as) and cut only an incomplete last\nrecord. A tail an interrupted append does not explain is left as it is\nand the integrity check quarantines the volume read-only as before.

Generated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: tests for the unindexed .dat tail repair

Reload volumes through the real load path after dropping .idx entries\nand cutting or damaging the .dat, mirroring Go's\nvolume_checking_tail_repair_test.go: complete unindexed needles are\nre-indexed (deletes as tombstones, empty writes as empty needles), an\nincomplete last record is cut, and a tail an interrupted append does\nnot explain is left untouched with the volume read-only.

Generated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: re-index a torn size 0 record as a live empty needle

A delete and a write with no data append the identical size 0 record, so a
recovered one cannot be told apart from the prior index state alone: the
write path accepts an empty overwrite of a live key and indexes it with
size 0, while a delete of the same key publishes a tombstone. Inferring a
tombstone from prior live state turned a lost index row after an empty
overwrite into a deletion -- the object read back not-found although the
write was answered.

Every re-indexed record is now indexed at its on-disk size, the entry
publishWriteRequest writes for an empty write. The other misread is
bounded: a recovered delete reads its key back as an empty object rather
than not-found, and the size 0 record carries no data to resurrect.

Review feedback on the Rust mirror (#11878): the same bug exists here;
fixing both sides identically.

Generated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: re-index a torn size 0 record as a live empty needle

Mirrors the Go fix in this pull request. A delete and a write with no data
append the identical size 0 record, so resolve_empty_tail_records could
not tell them apart from the prior index state: it treated a zero-size
record of a live id as a tombstone, although the write path indexes the
same bytes as a live size 0 entry. A crash after an empty overwrite of a
live key therefore recovered the object as deleted.

Every re-indexed record is now indexed at its on-disk size, the entry
publish_write writes for an empty write. A recovered delete reads its key
back as an empty object rather than not-found; the size 0 record carries
no data to resurrect.

Review: greptile-apps[bot] and devin-ai-integration[bot] on #11878.

Generated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: repair a .dat tail left past an empty .idx

The writable index loader creates the .idx before the first needle append,
so a crash after that append leaves a volume whose data nothing indexes.
CheckVolumeDataIntegrity skipped an empty index outright, so the volume
loaded writable and the surviving first needle stayed invisible while
later writes appended past it.

A zero-size index now runs the same repair with tailEntryPos -1: the walk
starts at the first record past the superblock with no anchor needle and
no append timestamp to compare against, gets the same complete-record
validation and incomplete-tail policy, and re-verifies through the normal
tail check once it wrote entries. A tail the repair cannot explain fails
the check, so the volume loads read-only instead of writable on an
unaccounted-for .dat.

Review feedback on the Rust mirror (#11878): the same bug exists here;
fixing both sides identically.

Generated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: repair a .dat tail left past an empty .idx

Mirrors the Go fix in this pull request. The writable index loader creates
the .idx before the first needle append, so a crash after that append
leaves a volume whose data nothing indexes. Both the repair and the
integrity check skipped an empty index, so the volume loaded writable and
the surviving first needle stayed invisible while later writes appended
past it.

An empty .idx now runs the same repair with no anchor: the walk starts at
the first record past the superblock, and a tail it cannot explain fails
the load like any other repair failure, since every later check skips an
empty index.

Review: devin-ai-integration[bot] on #11878.

Generated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: sync the .dat before publishing re-indexed .idx rows

A power loss after the repaired .idx rows become durable but before the
.dat tail records they name are flushed leaves the index pointing past
the end of the data file; the next load then keeps the volume read-only
until an operator steps in. Sync the .dat first so the rows never
outlive the records they reference.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: sync the .dat before publishing re-indexed .idx rows

Mirrors the Go fix: a power loss after the repaired .idx rows become
durable but before the .dat tail records they name are flushed leaves
the index pointing past the end of the data file. Sync the .dat first.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-20 23:13:51 -07:00
Chris LuandDevin 222e96d6ab iceberg maintenance: merge bin files across parquet schema spellings (#11875)
* iceberg maintenance: compare parquet schemas by field id in bin-pack merge

parquet.EqualNodes ignores Iceberg field ids, so a column dropped and\nre-added under the same name and type compared equal and was merged,\nfiling the new column's values under the dropped field id. Require the\nfield ids to agree wherever both sides carry one; the v3 layout's\nper-field check uses the same test.\n\nGenerated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iceberg maintenance: merge bin files whose schemas differ by field id

A bin used to take the first file's Parquet schema as the writer's and\nrefuse every file that was not structurally identical, so a table never\ncompacted once files had a different column set or REQUIRED-vs-OPTIONAL\nrepetition. A file whose flat columns the writer's schema covers by\nfield id is converted into it (a column the file lacks reads as null);\na file that covers the writer's schema restarts the bin with it, so no\ncolumn is dropped. Equality-delete columns resolve on each file's own\nschema. Renames, type changes, nested columns and files without field\nids stay refused. The sorted and spatial merges are unchanged.\n\nGenerated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iceberg maintenance: test bin-pack merge across parquet schema spellings

Regression coverage for the field-id merge: an added column in either\norder, REQUIRED vs OPTIONAL, equality deletes resolved per file, the\nre-added column refused on v1/v2 and v3, and the refusals that stay\n(rename, type change, one-sided columns, an added required column, no\nfield ids).\n\nGenerated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iceberg maintenance: resolve missing delete columns as null in bin-pack merge

An equality delete on an optional column added after a data file was\nwritten no longer refuses the bin: the file reads the column as null,\nso a real delete key cannot match its rows and a null key deletes them.\n\nGenerated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iceberg maintenance: write bin-pack merges under the files' union schema

The writer schema is now the union of the bin's file schemas by field\nid, computed in a schema-only pass before any row is written: a column\nstays REQUIRED only where every file has it and spells it so, and the\nmerge refuses only true name/type/id conflicts. Files that need a union\nneither side covers (an added column plus a REQUIRED/OPTIONAL\ndifference, disjoint added columns) now merge in a single pass instead\nof refusing, and progressively wider bins no longer reread and rewrite\nevery earlier file per restart.\n\nGenerated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iceberg maintenance: spell the re-added column's test file for codespell

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iceberg maintenance: resolve equality-delete columns by field id

A column renamed after its data and delete files were written still carries
its field id there; resolving it by id instead of the current name keeps a
rename from turning every equality key null. The missing-column null-key
fallback is now for data files only: an equality-delete file that lacks its
equality column is refused, as the spec requires it to carry them.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iceberg maintenance: read only the parquet footer choosing a bin's writer schema

The union-schema pass downloaded every input in full, then the merge
downloaded each again. The footer suffices for the schema, and a chunked
file's ReadAt pulls only the chunks the footer spans.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-20 23:13:43 -07:00
Chris Lu a724f4296c s3, s3tables: create buckets and namespaces exclusively (#11872)
* filer_pb: add MkdirExclusive

A taken name leaves the callback as a result, not an error, so filer
failover does not count a lost race as a filer failure.

* s3tables: create the entry with its attributes in one exclusive create

CreateTableBucket and CreateNamespace checked that the name was free and
then wrote the entry in several calls, so a second create in the window
replaced the first caller's entry including its owner. The create now
carries the marker, metadata and tags in one O_EXCL CreateEntry that
answers ErrEntryAlreadyExists with the same 409.

* s3: PutBucket uses an exclusive mkdir

The same window let a plain PutBucket replace a table bucket created
concurrently. The already-exists branch now answers from the entry itself,
since the registry just cached the name as absent, and the admin
auto-create path is exclusive too.

* s3: read the winning entry when a create loses the race

The concurrent-create branch called existingBucketError on a name the
registry had just cached as absent, answering NoSuchBucket, and the
auto-create fallback could assign an S3 owner to a table bucket it met
there. The negative cache is cleared before the existing-bucket error is
built, and a table bucket keeps its owner-less shape.

* s3: fail an auto-create that met a table bucket

A table bucket carries no S3 owner and must not gain one, and the upload
that auto-create ran for must not continue into it either.

* s3: fail an auto-create when the winning entry cannot be read

An unreadable existing entry fell through to success, so the write
continued into an unvalidated entry, possibly a table bucket.
2026-10-20 19:01:08 -07:00
Chris Lu f05d743459 s3: resolve versionId tagging requests to the version-tagging actions (#11874)
* s3: resolve versionId tagging requests to the version-tagging actions

A request for an object's tags with versionId acted on a historical
version but authorized against the current-object tagging action, so an
explicit Deny on s3:*ObjectVersionTagging never applied.

* iam: map PutObjectVersionTagging and DeleteObjectVersionTagging to the tagging action

* s3: only resolve tagging when the query value is empty

The tagging routes match ?tagging with an empty value, so a non-empty one
is not a tagging request and would resolve a tagging grant onto the plain
read or version read that actually serves it.

* s3: keep resolving tagging for any query value

The routes match ?tagging whenever the key is present, so tagging=x is a
tagging request served by the tagging handlers and must resolve to the
tagging actions.
2026-10-20 18:59:19 -07:00
Chris Lu 03a75cbc52 s3tables: only the admin repairs a table bucket that has no owner metadata (#11873)
* s3tables: only the admin repairs a table bucket that has no owner metadata

CreateNamespace wrote bucket metadata naming the caller as owner before any
permission check ran, so an ordinary caller that found the marker without
metadata was written in as the bucket's owner and passed every check after.
A bucket in that state is answered with the operation's own denial; the
admin or a trusted internal handler may still repair it.

* s3tables: repair the marker-only bucket under the entry lock

A creator finishing its own create between the missing-metadata check and
the repair write would have its owner overwritten. The mutation now adopts
whatever metadata is there and writes only while it is still absent.

* s3tables: gate the repair on the Admin action, not an operation grant

hasAdminAction also answers s3tables:*, so a non-admin identity holding
the wildcard operation grant could pass the repair check and write itself
in as the bucket's owner.
2026-10-20 18:58:54 -07:00
dependabot[bot] efa9d304d2 build(deps): bump github.com/klauspost/compress from 1.18.0 to 1.18.7 in /test/kafka/kafka-client-loadtest (#11879)
build(deps): bump github.com/klauspost/compress

Bumps [github.com/klauspost/compress](https://github.com/klauspost/compress) from 1.18.0 to 1.18.7.
- [Release notes](https://github.com/klauspost/compress/releases)
- [Commits](https://github.com/klauspost/compress/compare/v1.18.0...v1.18.7)

---
updated-dependencies:
- dependency-name: github.com/klauspost/compress
  dependency-version: 1.18.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-20 17:49:47 -07:00
github-actions[bot] b7f5d04428 docs: regenerate star history chart 2026-10-21 00:43:44 +00:00
Chris LuandDevin ece2f7a7c2 iam: targeted writes for single-user IAM actions (#11877)
* s3api: persist single-identity IAM changes through the credential manager

CreateAccessKey, DeleteAccessKey, UpdateAccessKey, PutUserPolicy, DeleteUserPolicy, SetUserStatus, UpdateUser and DeleteUser used to load the whole configuration, change one identity and then SaveConfiguration, rewriting and re-propagating every identity. They now write only the identity (and, for rename/delete, the groups and service accounts that referenced it) through the credential manager, which propagates that identity alone. Static identities and skipPersist keep the previous full-save/no-write contract.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iamapi: persist single-identity IAM changes through the credential manager

Same targeted-write change as the embedded IAM API for the standalone weed iam dispatcher: UpdateUser, DeleteUser, CreateAccessKey, DeleteAccessKey, UpdateAccessKey, PutUserPolicy and DeleteUserPolicy write one identity through the credential manager instead of saving the whole configuration. CreateAccessKey keeps the full save when the handler created a user the store does not know.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* credential/memory: re-key identity on UpdateUser rename

UpdateUser stored the identity under the old username key even when identity.Name changed. Re-key it the way filer_etc does (delete old, save new) so the targeted rename path sees the moved record.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: cover targeted single-identity IAM writes

Recording-store tests assert each rerouted action uses the single-identity credential store methods and never SaveConfiguration, in both the embedded S3 IAM dispatcher and the standalone iamapi dispatcher, plus the skipPersist and static-identity contracts and a memory-store rename case.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* credential: keep not-found and rename-collision semantics in stores

IamGrpcStore.DeleteAccessKey translates gRPC NotFound to ErrAccessKeyNotFound so a repeat delete stays the no-op the IAM handlers advertise. MemoryStore.UpdateUser rejects a rename onto an existing user instead of overwriting it, matching RenameUser.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-20 17:41:37 -07:00
Chris LuandDevin 610346ae8c iceberg: keep version-hint.text out of remove_orphans (#11867) (#11871)
Generated with [Devin](https://devin.ai)

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-20 13:05:38 -07:00
Javier de la TorreandJavier de la Torre df89afbef4 volume: repair an unindexed .dat tail at load instead of loading read-only (#11870)
* volume: repair an unindexed .dat tail at load instead of loading read-only

A needle write appends the needle to the .dat, then its entry to the .idx,
then answers the client. A crash between the two appends leaves a .dat that
ends past the last indexed needle; on the next start CheckVolumeDataIntegrity
reports "actual N bytes expected M bytes" and the volume loads read-only, and
a complete needle in that tail cannot be read because nothing indexes it.
After a process crash those bytes belong to a write that was never answered;
after a power loss a complete needle can survive in the .dat while its .idx
entry did not, although the client was answered. So complete needles are
re-indexed rather than cut.

CheckVolumeDataIntegrity now repairs the tail before the existing check,
which then runs on the repaired files as before. The repair:

- acts only on a local, version 3 volume within MaxPossibleVolumeSize, with a
  whole number of .idx entries, that is about to load writable (neither
  noWriteOrDelete nor noWriteCanDelete is set);
- requires the needle at the highest indexed offset to match its entry (id,
  size, whole record, CRC);
- walks from the end of that needle to the real end of the file and gives
  every complete needle (header, body, checksum, timestamp and padding inside
  the file, CRC valid, append timestamp later than the needle before it) the
  .idx entry the volume server would have written, in .dat order; a size 0
  record, which is how a delete is appended, is indexed as a tombstone;
- cuts only an incomplete last record: fewer bytes than a header, a record
  running past the end of the file, or a last record whose CRC fails;
- changes nothing otherwise (a damaged record with more data after it, a
  header with id 0 or a negative size, append timestamps going backwards), so
  the volume loads read-only exactly as before.

The .idx entries are written and synced before the .dat is truncated and
synced, so a crash during the repair leaves the needles indexed and the
remainder still past them; the next load cuts it. One warning per repaired
volume names the needles re-indexed and the bytes cut.

Tests: volume_checking_tail_repair_test.go reloads volumes through the normal
load path. Repaired: one and two complete unindexed needles, an unindexed
delete, a partial header, a partial body, a complete needle followed by a
partial one, a last needle with a bad CRC, a partial needle after an indexed
tombstone; each reloads clean afterwards. Left read-only and unchanged: the
last indexed needle with a wrong id or a bad CRC, a bad CRC followed by more
data, zero bytes past the last needle, an index past the data, a volume
persisted read-only, a partial .idx entry, and a clean volume.
TestCheckVolumeDataIntegrityVerifiesDeletionTail now also checks that on a
writable volume its 64 zero bytes are reported and kept.

Fixes #11864

* volume: fail the integrity check when a tail repair cannot complete

A repair that wrote the .idx or cut the .dat and then failed to sync only
logged the error; the check that followed saw the repaired files and the
volume loaded writable on a repair that may not be on disk. Any repair
error other than an unexplained tail now fails the check, so the volume
loads read-only, and the next load repairs again.

A failed .idx append could leave part of an entry behind, which made every
later load reject the .idx as a partial entry. The appended bytes are
truncated away again before the error is returned.

* volume: do not cut a tail record that could not be read

The walk cut a last record whose read failed for any reason, so an I/O
error (EIO) on a complete record erased it. Only a record whose bytes are
damaged (needle.ErrorCorrupted: a CRC mismatch or a body that does not
parse) is cut now; any other read error is returned with both files left
as they are, and the volume loads read-only.

* volume: treat a sized tail record with no data as damaged

A needle with no data is written with size 0. A tail record whose header
gives a body but whose data size field reads 0 parsed as an empty needle,
and ReadBytes checks the CRC only when there is data, so the repair indexed
it with its positive size and reads returned an empty body. Such a record
is now damaged like one with a bad CRC: cut when it is the last record,
otherwise the tail is left alone and the volume loads read-only.

* volume: keep an unindexed empty write as an empty needle

A delete and a write with no data both append a size 0 record, and the
repair indexed every size 0 record in the tail as a tombstone, so an
acknowledged empty write whose .idx entry was lost read back as deleted.
A delete is only appended for a needle that is live, so a size 0 record
of a needle that is absent or deleted (in the .idx and in the tail before
it) is an empty write and is re-indexed with size 0. One of a live needle
stays a tombstone, the reading weed fix and the backup's index
regeneration already give it. The .idx is scanned only when the tail holds
a size 0 record.

* volume: cut torn-tail test records inside their body, not at +40

The partial-record cases cut the .dat 40 bytes into a record. A needle
with up to 7 bytes of data is a 40-byte record, so newRandomNeedle's
random length (1..1023) left it whole about once in 150 runs per case:
the repair then correctly re-indexed it and cut nothing, and the test
failed on the .dat size. The cut now lands halfway through the record's
body, which is always past its header and short of its end.

---------

Co-authored-by: Javier de la Torre <jatorre@lakehousebox.com>
2026-10-20 13:03:00 -07:00
dependabot[bot] 1253b97303 build(deps): bump github.com/klauspost/compress from 1.15.9 to 1.18.7 in /test/kafka/kafka-client-loadtest/tools (#11866)
build(deps): bump github.com/klauspost/compress

Bumps [github.com/klauspost/compress](https://github.com/klauspost/compress) from 1.15.9 to 1.18.7.
- [Release notes](https://github.com/klauspost/compress/releases)
- [Commits](https://github.com/klauspost/compress/compare/v1.15.9...v1.18.7)

---
updated-dependencies:
- dependency-name: github.com/klauspost/compress
  dependency-version: 1.18.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-20 13:02:26 -07:00
dependabot[bot] a1d8739464 build(deps): bump github.com/klauspost/compress from 1.17.0 to 1.18.7 in /test/kafka/simple-consumer (#11869)
build(deps): bump github.com/klauspost/compress

Bumps [github.com/klauspost/compress](https://github.com/klauspost/compress) from 1.17.0 to 1.18.7.
- [Release notes](https://github.com/klauspost/compress/releases)
- [Commits](https://github.com/klauspost/compress/compare/v1.17.0...v1.18.7)

---
updated-dependencies:
- dependency-name: github.com/klauspost/compress
  dependency-version: 1.18.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-20 13:01:44 -07:00
Chris LuandDevin 1cfd9bbb4c volume: run the durable sync outside the reader-visible lock (#11863)
* volume: run the durable sync outside the reader-visible lock

Reads of a volume waited on that volume's fsync because the write lock
was held across Sync()/sync_all. A new per-volume lock (Go
dataFileSyncLock, Rust data_file_sync_lock) now serializes every .dat
mutation and lifecycle op across append+publish+sync+rollback, while the
fsync itself runs with dataFileAccessLock/the io write guard dropped —
so readers proceed during a sync, and a failed sync's rollback still
cannot clobber another write or a compaction swap.

Same change in Go (volume_write.go syncWrite/processBatch, SyncToDisk)
and Rust (write_needles_grouped/write_synced_run).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: publish after sync; fix Close/CommitCompact lock order

Address review on #11863:

- Close took dataFileSyncLock before waiting on isCompactionInProgress
  while CommitCompact claims the flag then takes the lock — a deadlock.
  Close now claims the flag before taking the locks (flag -> sync -> access).

- Go now publishes needle-map entries only after the .dat sync, matching
  Rust's ordering: appendWriteRequest/appendDeleteRequest stage the bytes,
  publishWriteRequest/publishDeleteRequest index them after Sync. A failed
  sync rolls back bytes no reader ever resolved — the streamed-read
  offset-invalidation window is gone. processBatch splits runs at repeated
  needle ids (Rust parity) so dedup/cookie checks stay sequential; the old
  snapshot/restore rollback machinery is removed.

- Rust commit_compact (store-lock caller) takes data_file_sync_lock via
  try_lock -> WouldBlock before the write lease; commit_compact_held and
  the tier-down _held paths document/require the caller-held sync lock,
  and the two vol.instance().write_lock() grpc sites take it first. The
  swap can no longer land between a durable write's append and publish.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: restore write watermarks when an inline fsync fails

The syncWrite rollback truncated the .dat but left lastAppendAtNs,
lastWriteAppendAtNs, lastWriteNeedleKey, lastWriteDeleted and
lastModifiedTsSeconds describing the rejected write; recovery and
compaction could read a watermark for a record that no longer exists.
Snapshot and restore them on failure, as processBatchRun already does.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-20 12:58:02 -07:00
Chris LuandDevin 0de6347b11 s3: mask anonymous misses behind AccessDenied unless the bucket is listable (#11857)
* s3: mask anonymous misses behind AccessDenied unless the bucket is listable

Deferred anonymous GET/HEAD authorization only runs once an entry is
selected, so misses returned 404 while existing keys returned 403 — an
unauthenticated existence oracle for bucket names and object keys.

Route not-found responses in Get/HeadObjectHandler through a check that
only discloses 404 when anonymous listing is allowed (policy, identity or
a public-read bucket); otherwise the miss is indistinguishable from a
denied read, matching AWS and 4.48 behavior.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: mask missing-directory misses for anonymous reads too

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: check a fixed request shape when masking anonymous misses

The miss check passed the caller's request through, so query parameters
could retarget the resolved action (?policy) or satisfy an s3:prefix
condition on an unrelated subtree. Each check now runs on a request with a
fixed shape: a ListBucket scoped to the probed key and a plain read of the
key, so the miss only shows when the caller could learn the same fact
directly.

* s3: mask conditional-header misses for anonymous reads

An If-Match conditional on a missing key wrote NoSuchKey directly from
processConditionalHeaders, before the handlers reached the masked miss
path, so anonymous callers could still distinguish a missing key from a
denied read.

* s3: keep the versionId when masking anonymous misses

The read leg must evaluate the action the caller's request resolves to:
a versioned miss is s3:GetObjectVersion, and dropping versionId would let a
plain GetObject grant disclose versions the caller may not read.

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-20 12:52:58 -07:00
Chris Lu 6936bbdc3e rust volume: score EC shard placement with the volume's own ratio (#11862)
The auto-select branches of ReceiveFile (is_ec_volume) and
VolumeEcShardsCopy passed the build-default DATA_SHARDS_COUNT into
find_ec_shard_target_location, so its free-slot maths scored every
volume as 10+4 even when the volume's .vif declares a custom ratio
(e.g. 6+2). A wider-ratio volume's shards could be steered onto a disk
too full to hold them all, and a narrower one would be refused slots
it actually has.

Add Store::lookup_ec_data_shards(collection, vid), which answers from
the mounted EC volume first and then from the .vif on whichever disk
holds it (via read_ec_shard_config_across_dirs, so split -dir/-dir.idx
and rebuild-staging layouts are covered), falling back to the default
when no metadata exists yet.

Mirrors the enterprise fix (seaweed-mono c22fa8a15).
2026-10-20 07:40:43 -07:00
Chris Lu 4d06742664 Detect and quarantine duplicate volume ids (#11763) (#11828)
* master: detect and quarantine duplicate volume ids across layouts (#11763)

* shell: volume.check.duplicate_ids audit command (#11763)

* master: persist duplicate-vid quarantine across heartbeats (#11763)

* master: quarantine all copies of a duplicated volume id

Near-simultaneous registrations let each side quarantine only the other,
so arrival order decided which copy stayed writable. A confirmed
cross-layout collision means either copy could be the impostor, so flag
every colliding copy read-only regardless of registration order.

* topology: return a copy from VolumeLayout.Lookup

Callers iterating the returned slice raced with registrations and
removals replacing the location list in place.

* master: release duplicate-vid quarantine when the conflict resolves

A cross-node volume.move briefly shows the same id on two nodes under
different disk layouts; permanent quarantine would pin a valid target
read-only. Keep the first-reported state per quarantined copy and lift
the marks once the conflicting copy unregisters, so only a persistent
collision stays read-only.

* shell: include ec shards in volume.check.duplicate_ids

Ec-only volumes share the global id space. Compare shard collections
against regular ones while allowing shards and regular copies of the
same encoded volume.

* master: keep quarantine release current and cover all removal paths

Track the latest server-reported read-only flag while quarantined so a
release restores the server s true state, and run the release check on
collection deletion and data-node removal too, not only explicit volume
unregistration.

* shell: do not flag ec-only volumes as duplicates

An ec-only volume has no regular copy, so its shard collections had
nothing to compare against and always read as foreign.

* master: quarantine every conflicting layout at the layout level (#11763)

- collect all conflicting layouts, not just the first, so a vid spanning
  three layouts does not leave one writable
- mark quarantine on the location list only: folding it into the stored
  report made the volume digest permanently disagree with the server and
  forced a full volume list every heartbeat
- isAllWritable now honors the location read-only mark so a quarantined
  copy stays out of writables through resyncs and re-registration
- re-check the conflict before keeping marks, and do not clear a node's
  quarantine while it still holds the vid in another layout
- log the full layout keys on both sides of the conflict

* master: push duplicate-vid quarantine to the volume server (#11763)

A quarantined copy stayed writable on the volume server itself for a
client holding an existing file id, since the master-only mark never
reached the server's local write path. Quarantine now also calls
VolumeMarkReadonly (can_delete so expiry still drains), is re-pushed if
the server comes back reporting it writable, and VolumeMarkWritable
runs when the conflict resolves and the server had reported writable.

* master: retry unenforced quarantine marks and restore server writability on release (#11763)

Dial the advertised grpc port, return mark errors, and keep a
quarantine entry until the writable push succeeds so a released
copy does not stay read-only on the server.

* master: treat rp-only layout differences as an in-flight replication change (#11763)

volume.configure.replication rolls through nodes one at a time, so a
volume legitimately reports the old and new replica placement while it
settles. Layouts differing only in rp within the same collection are a
supported transition, not a reused id.

* shell: group ec shards by collection in the duplicate id audit (#11763)

EC shards of one volume legitimately span disk types when
DiskTypePrefer spills, so grouping by disk type reports healthy
volumes as duplicates.
2026-10-20 07:37:33 -07:00
61 changed files with 6718 additions and 2036 deletions

No files matched your search

+73 -52
View File
@@ -52,6 +52,63 @@ jobs:
- 'seaweed-volume/**'
- '.github/workflows/rust-volume-server-tests.yml'
build-test-binaries:
name: Build Test Binaries
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
# cargo tracks its own inputs but not the runner's C toolchain, so a cached
# target/ can carry C objects built against a different glibc than we link against.
- name: Fingerprint build toolchain
id: toolchain
run: echo "fingerprint=$(getconf GNU_LIBC_VERSION | tr ' ' '-')-rustc-$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- name: Cache cargo registry and target
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
key: rust-${{ steps.toolchain.outputs.fingerprint }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-common/Cargo.lock') }}
restore-keys: |
rust-${{ steps.toolchain.outputs.fingerprint }}-
- name: Build Go weed binary
run: |
cd weed
go build -tags 5BytesOffset -o weed .
chmod +x weed
./weed version
- name: Build Rust volume binary
run: cd seaweed-volume && cargo build --release
- name: Package binaries
run: tar cf rust-test-binaries.tar weed/weed seaweed-volume/target/release/weed-volume
- name: Upload test binaries
uses: actions/upload-artifact@v7
with:
# archive layout mirrors the workspace: weed/weed and
# seaweed-volume/target/release/weed-volume
name: rust-test-binaries
if-no-files-found: error
retention-days: 1
path: rust-test-binaries.tar
rust-unit-tests:
name: Rust Unit Tests
runs-on: ubuntu-22.04
@@ -154,6 +211,7 @@ jobs:
name: Rust Integration Tests
runs-on: ubuntu-22.04
timeout-minutes: 30
needs: [build-test-binaries]
steps:
- name: Checkout code
@@ -164,35 +222,16 @@ jobs:
with:
go-version-file: 'go.mod'
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
# cargo tracks its own inputs but not the runner's C toolchain, so a cached
# target/ can carry C objects built against a different glibc than we link against.
- name: Fingerprint build toolchain
id: toolchain
run: echo "fingerprint=$(getconf GNU_LIBC_VERSION | tr ' ' '-')-rustc-$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- name: Cache cargo registry and target
uses: actions/cache@v6
- name: Download test binaries
uses: actions/download-artifact@v7
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
key: rust-${{ steps.toolchain.outputs.fingerprint }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-common/Cargo.lock') }}
restore-keys: |
rust-${{ steps.toolchain.outputs.fingerprint }}-
name: rust-test-binaries
- name: Build Go weed binary
- name: Restore binaries
run: |
cd weed
go build -tags 5BytesOffset -o weed .
chmod +x weed
./weed version
- name: Build Rust volume binary
run: cd seaweed-volume && cargo build --release
tar xf rust-test-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
./weed/weed version
- name: Run integration tests
env:
@@ -228,6 +267,7 @@ jobs:
name: Go Tests with Rust Volume (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
runs-on: ubuntu-22.04
timeout-minutes: 45
needs: [build-test-binaries]
env:
# Keep in step with the length of matrix.shard below.
SHARD_COUNT: 3
@@ -246,35 +286,16 @@ jobs:
with:
go-version-file: 'go.mod'
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
# cargo tracks its own inputs but not the runner's C toolchain, so a cached
# target/ can carry C objects built against a different glibc than we link against.
- name: Fingerprint build toolchain
id: toolchain
run: echo "fingerprint=$(getconf GNU_LIBC_VERSION | tr ' ' '-')-rustc-$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- name: Cache cargo registry and target
uses: actions/cache@v6
- name: Download test binaries
uses: actions/download-artifact@v7
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
key: rust-${{ steps.toolchain.outputs.fingerprint }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-common/Cargo.lock') }}
restore-keys: |
rust-${{ steps.toolchain.outputs.fingerprint }}-
name: rust-test-binaries
- name: Build Go weed binary
- name: Restore binaries
run: |
cd weed
go build -tags 5BytesOffset -o weed .
chmod +x weed
./weed version
- name: Build Rust volume binary
run: cd seaweed-volume && cargo build --release
tar xf rust-test-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
./weed/weed version
# Dealing the listed tests out one by one keeps the shards even. Bucketing
# them by first letter did not: names cluster, so ^Test[I-S] drew 50 of
@@ -33,15 +33,10 @@ env:
SHARD_COUNT: 3
jobs:
volume-server-integration-tests:
name: Volume Server Integration Tests (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
build-weed:
name: Build SeaweedFS Binary
runs-on: ubuntu-22.04
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
test-type: [grpc, http]
shard: [1, 2, 3]
timeout-minutes: 15
steps:
- name: Checkout code
@@ -59,6 +54,48 @@ jobs:
chmod +x weed
./weed version
- name: Package binary
run: tar cf weed-binary.tar weed/weed
- name: Upload binary
uses: actions/upload-artifact@v7
with:
name: weed-binary
if-no-files-found: error
retention-days: 1
path: weed-binary.tar
volume-server-integration-tests:
name: Volume Server Integration Tests (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
runs-on: ubuntu-22.04
timeout-minutes: 45
needs: [build-weed]
strategy:
fail-fast: false
matrix:
test-type: [grpc, http]
shard: [1, 2, 3]
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
- name: Download binary
uses: actions/download-artifact@v7
with:
name: weed-binary
- name: Restore binary
run: |
tar xf weed-binary.tar
chmod +x weed/weed
./weed/weed version
# Dealing the listed tests out one by one keeps the shards even. Bucketing
# them by first letter did not: names cluster, so ^Test[I-S] drew 50 of
# the 114 grpc tests and ran nearly twice as long as the other two shards.
+1099 -1050
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 55 KiB

+14 -9
View File
@@ -16,7 +16,7 @@ use crate::pb::filer_pb;
use crate::pb::master_pb;
use crate::pb::volume_server_pb;
use crate::pb::volume_server_pb::volume_server_server::VolumeServer;
use crate::storage::erasure_coding::ec_shard::{DATA_SHARDS_COUNT, ShardId, shard_id_try_from};
use crate::storage::erasure_coding::ec_shard::{ShardId, shard_id_try_from};
use crate::storage::erasure_coding::ecj_merge::EcjIdDecoder;
use crate::storage::needle::needle::{self, Needle};
use crate::storage::types::*;
@@ -1353,6 +1353,7 @@ impl VolumeServer for VolumeGrpcService {
// Go's CommitCompact waits out leased readers under
// dataFileAccessLock — do it without holding the store
// guard, so a slow download stalls only this vacuum.
let _sync_guard = vol.data_file_sync_lock().lock().unwrap();
let _lease = vol.instance().write_lock();
let is_read_only = vol.is_read_only();
vol.commit_compact_held()
@@ -2317,9 +2318,9 @@ impl VolumeServer for VolumeGrpcService {
// owns the .ecx on disk (volume not yet mounted — relevant
// when shards stream in mid-rebuild before any
// VolumeEcShardsMount has happened; see #9212), then any
// HDD, then any disk. Pass the build's default data-shard
// count for free-slot maths; the helper takes it as a
// parameter so custom-ratio builds can swap it.
// HDD, then any disk. The free-slot maths uses the
// volume's own data-shard count from its .vif so a
// custom-ratio volume is not scored as 10+4.
let vid = VolumeId(info.volume_id);
let dir = if info.disk_id > 0 {
let count = store.locations.len();
@@ -2334,11 +2335,13 @@ impl VolumeServer for VolumeGrpcService {
} else {
// The mounted-volume refusal above means no disk
// holds an in-memory claim here.
let data_shards =
store.lookup_ec_data_shards(&info.collection, vid);
store
.find_ec_shard_target_location(
&info.collection,
vid,
DATA_SHARDS_COUNT as u32,
data_shards,
&[],
)
.map(|i| store.locations[i].directory.clone())
@@ -3288,9 +3291,9 @@ impl VolumeServer for VolumeGrpcService {
// volume mounted, then a disk that owns the .ecx on disk (volume
// not yet mounted — relevant for ec.rebuild, where only the
// first shard carries .ecx and subsequent shards must land on
// the same disk; see #9212), then any HDD, then any disk. Pass
// the build's default data-shard count; the helper takes it as a
// parameter so custom-ratio builds can swap it.
// the same disk; see #9212), then any HDD, then any disk. The
// free-slot maths uses the volume's own data-shard count from its
// .vif so a custom-ratio volume is not scored as 10+4.
let (dest_dir, dest_idx_dir) = {
let store = self.state.store.read().unwrap();
let count = store.locations.len();
@@ -3322,10 +3325,11 @@ impl VolumeServer for VolumeGrpcService {
req.volume_id, shard_ids, dirs
)));
}
let data_shards = store.lookup_ec_data_shards(&req.collection, vid);
match store.find_ec_shard_target_location(
&req.collection,
vid,
DATA_SHARDS_COUNT as u32,
data_shards,
&shard_ids,
) {
Some(i) => {
@@ -4723,6 +4727,7 @@ impl VolumeServer for VolumeGrpcService {
// backend swap: between clearing the remote-only write
// restriction and attaching the local .dat a write would
// pass check_writable and then fail on a missing dat_file.
let _sync_guard = vol.data_file_sync_lock().lock().unwrap();
let _lease = vol.instance().write_lock();
// The store guard dropped before the lease was taken, so an
+1
View File
@@ -18,3 +18,4 @@ pub mod volume_idx_repair;
pub mod volume_open;
pub mod volume_report;
pub mod volume_report_hash;
pub mod volume_tail_repair;
+63 -1
View File
@@ -14,7 +14,7 @@ use crate::pb::master_pb;
use crate::storage::disk_location::DiskLocation;
use crate::storage::erasure_coding::ec_shard::{EcVolumeShard, MAX_SHARD_COUNT, ShardId};
use crate::storage::erasure_coding::ec_volume::{
ECJ_COMPACT_TMP_EXT, EcVolume, is_usable_ecx_file,
ECJ_COMPACT_TMP_EXT, EcVolume, is_usable_ecx_file, read_ec_shard_config_across_dirs,
};
use crate::storage::needle::needle::{Needle, get_actual_size};
use crate::storage::needle_map::NeedleMapKind;
@@ -416,6 +416,39 @@ impl Store {
.collect()
}
/// Look up the per-volume EC data-shard count, preferring a mounted EC
/// volume's own config and then the `.vif` on whichever disk holds it.
/// Falls back to the default when neither exists yet (e.g. before the
/// first shard streams in during ec.rebuild), so
/// `find_ec_shard_target_location`'s free-slot maths scores custom-ratio
/// volumes against their real width instead of the build default.
pub fn lookup_ec_data_shards(&self, collection: &str, vid: VolumeId) -> u32 {
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
for loc in &self.locations {
if let Some(ec_vol) = loc.find_ec_volume(vid) {
return ec_vol.data_shards;
}
}
let Some(first) = self.locations.first() else {
return DATA_SHARDS_COUNT as u32;
};
let other_dirs: Vec<String> = self.locations[1..]
.iter()
.flat_map(|loc| [loc.directory.clone(), loc.idx_directory.clone()])
.filter(|d| !d.is_empty())
.collect();
read_ec_shard_config_across_dirs(
&first.directory,
&first.idx_directory,
&other_dirs,
collection,
vid,
)
.map(|(data_shards, _, _)| data_shards)
.unwrap_or(DATA_SHARDS_COUNT as u32)
}
/// Create a new volume, placing it on the location with the most free space.
pub fn add_volume(
&mut self,
@@ -2980,6 +3013,35 @@ mod tests {
);
}
/// A volume whose `.vif` declares a custom EC ratio must feed its own
/// data-shard count into the free-slot maths — not the build default —
/// wherever the `.vif` happens to sit. With no `.vif` anywhere (a
/// brand-new volume mid-ec.rebuild) the answer is the default.
#[test]
fn test_lookup_ec_data_shards_reads_vif_on_any_disk() {
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let (store, _tmp) = make_ec_target_test_store(3);
let collection = "custom-ratio";
let vid = VolumeId(4242);
assert_eq!(
store.lookup_ec_data_shards(collection, vid),
DATA_SHARDS_COUNT as u32,
"no .vif anywhere must answer the default"
);
// A 6+2 .vif lands on disk 2 only — the rebuild staging disk.
let base = volume_file_name(&store.locations[2].directory, collection, vid);
std::fs::write(
format!("{}.vif", base),
br#"{"ecShardConfig":{"dataShards":6,"parityShards":2}}"#,
)
.unwrap();
assert_eq!(store.lookup_ec_data_shards(collection, vid), 6);
}
/// Deleting a disk's last shard removes that disk's now-orphaned `.ecsum`;
/// a disk this delete never changed keeps its sidecar. Disk 0 models
/// ec.rebuild's index-prep state (`.ecsum` landed, no shards yet) — an
+175 -64
View File
@@ -29,6 +29,7 @@ use crate::storage::needle_map::{CompactNeedleMap, NeedleMap, NeedleMapKind, Red
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE, SuperBlock};
use crate::storage::types::*;
use crate::storage::volume_open::open_volume_file;
use crate::storage::volume_tail_repair::TailRepairError;
// ============================================================================
// Errors
@@ -1247,6 +1248,12 @@ pub struct Volume {
idx_syncs_for_test: std::sync::atomic::AtomicUsize,
needle_map_kind: NeedleMapKind,
data_file_access_control: Arc<DataFileAccessControl>,
/// Serializes a data-file mutation with the sync that makes it durable:
/// write, delete and lifecycle paths hold it for their whole critical
/// section, while the fsync itself runs with only the `io` read guard so
/// readers of this volume do not wait on it. Lock order is
/// `data_file_sync_lock` -> `data_file_access_control` -> `io`.
data_file_sync_lock: std::sync::Mutex<()>,
/// Go's superBlockAccessLock.
super_block: RwLock<SuperBlock>,
@@ -1370,6 +1377,7 @@ impl Volume {
idx_syncs_for_test: Default::default(),
needle_map_kind,
data_file_access_control: Arc::new(DataFileAccessControl::default()),
data_file_sync_lock: std::sync::Mutex::new(()),
super_block: RwLock::new(SuperBlock {
replica_placement: replica_placement.unwrap_or_default(),
ttl: ttl.unwrap_or(crate::storage::needle::ttl::TTL::EMPTY),
@@ -1426,6 +1434,7 @@ impl Volume {
idx_syncs_for_test: Default::default(),
needle_map_kind: NeedleMapKind::InMemory,
data_file_access_control: Arc::new(DataFileAccessControl::default()),
data_file_sync_lock: std::sync::Mutex::new(()),
super_block: RwLock::new(SuperBlock::default()),
no_write: AtomicU8::new(0),
io_unavailable: Arc::default(),
@@ -1446,6 +1455,13 @@ impl Volume {
self.data_file_access_control.clone()
}
/// The mutation/sync serializer, for callers that manage the access
/// lease themselves (the `_held` lifecycle paths). Same lock order as
/// everywhere else: sync lock first, then the write lease, then `io`.
pub(crate) fn data_file_sync_lock(&self) -> &std::sync::Mutex<()> {
&self.data_file_sync_lock
}
pub(crate) fn is_instance(&self, instance: &Arc<DataFileAccessControl>) -> bool {
Arc::ptr_eq(instance, &self.data_file_access_control)
}
@@ -1709,6 +1725,46 @@ impl Volume {
),
}
// A crash between the .dat append and the .idx append leaves a
// .dat tail no index entry covers. Re-index complete needles and
// cut an incomplete remainder before the index loads, so the
// recovered rows land in the needle map and inside its append
// offset. Mirrors Go running repairUnindexedDatTail inside
// CheckVolumeDataIntegrity ahead of the needle map load. Only a
// volume about to load writable is repaired.
if !self.has_remote_file() && self.no_write_flags() == (false, false) {
// An empty .idx gets the same repair: every check below
// skips an empty index on its own, so a tail the repair
// cannot explain there fails the load like in Go rather
// than warn and load writable.
let idx_empty = fs::metadata(self.file_name(".idx"))
.map(|m| m.len() == 0)
.unwrap_or(false);
match self.repair_unindexed_dat_tail(io) {
Ok(()) => {}
Err(e) if e.is_not_torn() && !idx_empty => warn!(
volume_id = self.id.0,
error = %e,
"unindexed .dat tail not repaired"
),
// The index refusing a read-write open is the same failure
// Go reports opening it ahead of the check: it fails the
// load rather than only the repair.
Err(TailRepairError::OpenIndex(e)) => return Err(e),
Err(e) => {
// A repair that could not complete must not load the
// volume writable on files it half-fixed: the check
// fails as in Go, so the volume loads read-only.
self.set_no_write_flag(NO_WRITE_OR_DELETE, true);
warn!(
volume_id = self.id.0,
error = %e,
"repair unindexed .dat tail"
);
}
}
}
self.load_index(io)?;
// Match Go: CheckVolumeDataIntegrity after loading index (volume_loading.go L154-159)
@@ -1980,6 +2036,7 @@ impl Volume {
}
pub(crate) fn load_remote_dat_file(&self) -> Result<(), VolumeError> {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
self.load_remote_dat_file_io(&mut io)
@@ -2066,7 +2123,7 @@ impl Volume {
self.current_dat_file_size_io(&io)
}
fn current_dat_file_size_io(&self, io: &VolumeIo) -> io::Result<u64> {
pub(crate) fn current_dat_file_size_io(&self, io: &VolumeIo) -> io::Result<u64> {
if let Some(ref f) = io.dat_file {
Ok(f.metadata()?.len())
} else if let Some(ref remote_dat_file) = io.remote_dat_file {
@@ -2290,7 +2347,7 @@ impl Volume {
self.read_needle_blob_unlocked(&io, offset, size)
}
fn read_needle_blob_unlocked(
pub(crate) fn read_needle_blob_unlocked(
&self,
io: &VolumeIo,
offset: i64,
@@ -2509,10 +2566,14 @@ impl Volume {
check_cookie: bool,
fsync: bool,
) -> Result<(u64, Size, bool), VolumeError> {
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
self.check_writable()?;
self.do_write_request(&mut io, n, check_cookie, fsync)
// A single write is a one-entry run of the grouped path: identical
// outcome, and the fsync handling lives in one place.
debug_assert!(check_cookie, "every write_needle caller checks the cookie");
let _ = check_cookie;
let mut writes = [(std::mem::take(n), fsync)];
let mut results = self.write_needles_grouped(&mut writes);
*n = std::mem::replace(&mut writes[0].0, Needle::default());
results.pop().unwrap_or(Err(VolumeError::NotFound))
}
/// Write a batch of needles the way Go's processBatch does: one .dat
@@ -2527,8 +2588,13 @@ impl Volume {
&self,
writes: &mut [(Needle, bool)],
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
// The sync lock serializes a .dat mutation with the flush that makes
// it durable: a failed sync's rollback can never clobber an append
// that slipped in behind it, and a compaction swap or unlink cannot
// land between the append and its sync. Readers never take it, and
// the write-side guards are dropped for the sync itself, so reads of
// this volume do not wait on fsync.
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let mut results = Vec::with_capacity(writes.len());
let mut rest = writes;
while !rest.is_empty() {
@@ -2536,8 +2602,10 @@ impl Volume {
let len = rest.iter().take_while(|(n, _)| ids.insert(n.id)).count();
let (run, tail) = std::mem::take(&mut rest).split_at_mut(len);
if run.iter().any(|(_, fsync)| *fsync) {
results.extend(self.write_synced_run(&mut io, run));
results.extend(self.write_synced_run(run));
} else {
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
for (n, _) in run.iter_mut() {
results.push(
self.check_writable()
@@ -2552,7 +2620,6 @@ impl Volume {
fn write_synced_run(
&self,
io: &mut VolumeIo,
run: &mut [(Needle, bool)],
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
// Per entry: Some(offset) once appended, None when it dedups.
@@ -2560,63 +2627,82 @@ impl Volume {
// Per entry: the I/O error streak once it is staged, where a write
// sent on its own would have recorded its success.
let mut marks = Vec::with_capacity(run.len());
let mut last_append_at_ns = io.last_append_at_ns;
let mut last_append_at_ns;
let mut run_start = None;
let mut sync = false;
for (n, fsync) in run.iter_mut() {
let r = self.append_unpublished(io, n, &mut last_append_at_ns);
marks.push(self.io_errors.mark());
if let Ok(Some(offset)) = r {
run_start.get_or_insert(offset);
}
// Only a durable entry that got this far needs the sync.
sync |= *fsync && r.is_ok();
staged.push(r);
}
if sync && let Err(e) = self.flush_dat(io) {
self.check_read_write_error(Some(&e));
if let Some(start) = run_start {
self.undo_unsynced_append(io, start);
}
let e = VolumeError::Io(e);
return staged
.into_iter()
.map(|r| r.and_then(|_| Err(run_error(&e))))
.collect();
}
io.last_append_at_ns = last_append_at_ns;
for ((n, _), r) in run.iter().zip(&staged) {
if matches!(r, Ok(Some(_))) && n.append_at_ns > io.last_write_append_at_ns {
io.last_write_append_at_ns = n.append_at_ns;
io.last_write_needle_key = n.id;
io.last_write_deleted = false;
{
// Append under the write guards, then drop them for the flush:
// readers need only `io`'s read side, while mutators and a
// compaction swap stay excluded by the caller's sync lock.
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
last_append_at_ns = io.last_append_at_ns;
for (n, fsync) in run.iter_mut() {
let r = self.append_unpublished(&mut io, n, &mut last_append_at_ns);
marks.push(self.io_errors.mark());
if let Ok(Some(offset)) = r {
run_start.get_or_insert(offset);
}
// Only a durable entry that got this far needs the sync.
sync |= *fsync && r.is_ok();
staged.push(r);
}
}
// A durable entry that fails to publish stops the volume taking
// writes, so the entries after it are refused the way a lone
// write would be.
let mut refused = false;
for ((n, fsync), r) in run.iter().zip(staged.iter_mut()) {
if refused {
*r = Err(self
.check_writable()
.err()
.unwrap_or(VolumeError::ReadOnly(self.id)));
} else if let Ok(Some(offset)) = *r
&& let Err(e) = self.publish_write(io, n, offset, *fsync)
{
*r = Err(e);
refused = *fsync;
if sync {
let io = self.io.read().unwrap();
if let Err(e) = self.flush_dat(&io) {
self.check_read_write_error(Some(&e));
if let Some(start) = run_start {
self.undo_unsynced_append(&io, start);
}
let e = VolumeError::Io(e);
return staged
.into_iter()
.map(|r| r.and_then(|_| Err(run_error(&e))))
.collect();
}
}
if sync && let Err(e) = self.flush_idx(io) {
return staged
.into_iter()
.map(|r| r.and_then(|_| Err(run_error(&e))))
.collect();
{
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
io.last_append_at_ns = last_append_at_ns;
for ((n, _), r) in run.iter().zip(&staged) {
if matches!(r, Ok(Some(_))) && n.append_at_ns > io.last_write_append_at_ns {
io.last_write_append_at_ns = n.append_at_ns;
io.last_write_needle_key = n.id;
io.last_write_deleted = false;
}
}
// A durable entry that fails to publish stops the volume taking
// writes, so the entries after it are refused the way a lone
// write would be.
let mut refused = false;
for ((n, fsync), r) in run.iter().zip(staged.iter_mut()) {
if refused {
*r = Err(self
.check_writable()
.err()
.unwrap_or(VolumeError::ReadOnly(self.id)));
} else if let Ok(Some(offset)) = *r
&& let Err(e) = self.publish_write(&mut io, n, offset, *fsync)
{
*r = Err(e);
refused = *fsync;
}
}
}
if sync {
let io = self.io.read().unwrap();
if let Err(e) = self.flush_idx(&io) {
return staged
.into_iter()
.map(|r| r.and_then(|_| Err(run_error(&e))))
.collect();
}
}
let written = run
@@ -2630,7 +2716,9 @@ impl Volume {
// Sent one at a time, the last write to land would have cleared
// the streak of the appends before it, and the ones after it
// would have failed on top of that.
self.finish_write(io, last_modified, sync, marks[last]);
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
self.finish_write(&mut io, last_modified, sync, marks[last]);
}
run.iter()
@@ -2679,7 +2767,7 @@ impl Volume {
/// Flush the .dat, the first half of a durable write. The .idx is flushed
/// separately by flush_idx once the row is published; the two are split so
/// nothing is indexed before the bytes it points at are down.
fn flush_dat(&self, io: &VolumeIo) -> io::Result<()> {
pub(crate) fn flush_dat(&self, io: &VolumeIo) -> io::Result<()> {
#[cfg(test)]
self.dat_syncs_for_test.fetch_add(1, Ordering::Relaxed);
#[cfg(test)]
@@ -2731,7 +2819,7 @@ impl Volume {
}
/// Take an unflushed append back off the .dat after its sync failed.
fn truncate_dat(&self, io: &VolumeIo, len: u64) -> io::Result<()> {
pub(crate) fn truncate_dat(&self, io: &VolumeIo, len: u64) -> io::Result<()> {
#[cfg(test)]
if io.fail_truncate_for_test {
return Err(io::Error::other("injected truncate failure"));
@@ -3082,6 +3170,7 @@ impl Volume {
/// Delete a needle from the volume.
pub fn delete_needle(&self, n: &mut Needle) -> Result<Size, VolumeError> {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
if self.is_closed() {
@@ -3464,7 +3553,7 @@ impl Volume {
/// key-sorted .idx (e.g. legacy weed fix output) falls back to a single
/// linear scan for the maximum offset. Returns -1 when no entry has a
/// non-zero offset (a pre-allocated / all-zero index).
fn find_dat_tail_entry_offset(
pub(crate) fn find_dat_tail_entry_offset(
&self,
io: &VolumeIo,
idx_file: &mut File,
@@ -3981,6 +4070,7 @@ impl Volume {
offset: Offset,
size: Size,
) -> Result<(), VolumeError> {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
let mut io = self.io.write().unwrap();
if let Some(ref mut nm) = io.nm {
@@ -4005,6 +4095,7 @@ impl Volume {
// The flag flip and the .vif save are one critical section with the idx
// attach: Go's markVolumeReadonly runs under dataFileAccessLock, so a
// racing mark-writable cannot interleave a save of half-applied state.
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
self.set_read_only_persist_held(can_delete, persist)
}
@@ -4089,6 +4180,7 @@ impl Volume {
if let Some(e) = self.unavailable_error() {
return Err(e);
}
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
let (was_no_write_or_delete, was_no_write_can_delete) = self.no_write_flags();
// Remote-tiered volumes must stay no_write_can_delete regardless of marks.
@@ -4187,6 +4279,7 @@ impl Volume {
&self,
f: impl FnOnce(&mut Vec<PbRemoteFile>),
) -> Result<(), VolumeError> {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
self.update_remote_files_held(f)
}
@@ -4451,6 +4544,7 @@ impl Volume {
/// Change the replication placement and rewrite the super block.
pub fn set_replica_placement(&self, rp: ReplicaPlacement) -> Result<(), VolumeError> {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
let bytes = {
let mut sb = self.super_block.write().unwrap();
@@ -4621,6 +4715,7 @@ impl Volume {
/// Write a raw needle blob at a specific offset in the .dat file.
pub fn write_needle_blob(&self, offset: i64, needle_blob: &[u8]) -> Result<(), VolumeError> {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
if self.is_read_only() {
return Err(VolumeError::ReadOnly(self.id));
@@ -4652,6 +4747,7 @@ impl Volume {
needle_blob: &[u8],
size: Size,
) -> Result<(), VolumeError> {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
// nm.put on a read-only volume fails only after the blob is appended to .dat.
if self.is_read_only() {
@@ -4956,6 +5052,16 @@ impl Volume {
// would stall every volume behind one slow client. The vacuum-commit
// RPC uses the lease-holding path instead — it waits with no store
// guard held, matching Go's blocking commit.
// The sync lock must come before the lease and be non-blocking like
// it: a durable write holds it across its fsync, and the commit must
// not swap files over an unpublished write — nor stall the store
// behind one.
let Ok(_sync_guard) = self.data_file_sync_lock.try_lock() else {
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::WouldBlock,
COMMIT_WAITS_FOR_READS,
)));
};
let Some(_lease) = self.data_file_access_control.try_write_lock() else {
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::WouldBlock,
@@ -4965,7 +5071,9 @@ impl Volume {
self.commit_compact_held()
}
/// `commit_compact` for callers already holding the write lease.
/// `commit_compact` for callers already holding `data_file_sync_lock`
/// and the write lease — the swap must not land between a durable
/// write's append and its publish.
pub(crate) fn commit_compact_held(&self) -> Result<(), VolumeError> {
// A handle detached between lookup and lease must not swap compacted
// files over the ones its remounted replacement now owns.
@@ -5356,6 +5464,7 @@ impl Volume {
/// Go's `Volume.Close`: the write lease excludes in-flight I/O — with a
/// shared handle, `&mut self` no longer provides that exclusion.
pub fn close(&self) {
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
self.closed.store(true, Ordering::Release);
self.close_locked();
@@ -5401,6 +5510,7 @@ impl Volume {
if self.is_compacting() {
return Err(self.compacting_error());
}
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
if self.dir_idx() == new_idx_dir {
@@ -5463,6 +5573,7 @@ impl Volume {
) -> Result<(), VolumeError> {
// Go's Destroy holds dataFileAccessLock: file unlinking must exclude
// in-flight I/O from a shared handle, not just borrow exclusivity.
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
let _guard = self.data_file_access_control.write_lock();
// Either enabled check may pass: a volume with no live data qualifies
// whether it reads empty or as all garbage. Byte counters, not counts:
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -24,7 +24,7 @@ require (
github.com/jcmturner/gofork v1.7.6 // indirect
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/compress v1.18.7 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pierrec/lz4/v4 v4.1.22 // indirect
+2 -2
View File
@@ -38,8 +38,8 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -5,6 +5,6 @@ go 1.24.7
require github.com/segmentio/kafka-go v0.4.49
require (
github.com/klauspost/compress v1.15.9 // indirect
github.com/klauspost/compress v1.18.7 // indirect
github.com/pierrec/lz4/v4 v4.1.15 // indirect
)
@@ -1,7 +1,7 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0=
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+2 -2
View File
@@ -1,10 +1,10 @@
module simple-consumer
go 1.21
go 1.24
require github.com/segmentio/kafka-go v0.4.47
require (
github.com/klauspost/compress v1.17.0 // indirect
github.com/klauspost/compress v1.18.7 // indirect
github.com/pierrec/lz4/v4 v4.1.15 // indirect
)
+2 -2
View File
@@ -2,8 +2,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0=
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+8 -1
View File
@@ -120,13 +120,20 @@ func (store *IamGrpcStore) CreateAccessKey(ctx context.Context, username string,
}
func (store *IamGrpcStore) DeleteAccessKey(ctx context.Context, username string, accessKey string) error {
return store.withIamClient(ctx, func(ctx context.Context, client iam_pb.SeaweedIdentityAccessManagementClient) error {
err := store.withIamClient(ctx, func(ctx context.Context, client iam_pb.SeaweedIdentityAccessManagementClient) error {
_, err := client.DeleteAccessKey(ctx, &iam_pb.DeleteAccessKeyRequest{
Username: username,
AccessKey: accessKey,
})
return err
})
// The filer-side handler returns gRPC NotFound when the user or the key is
// absent; translate back to the sentinel so callers can use
// errors.Is(err, credential.ErrAccessKeyNotFound) uniformly across stores.
if err != nil && status.Code(err) == codes.NotFound {
return credential.ErrAccessKeyNotFound
}
return err
}
// AttachUserPolicy attaches a managed policy to a user by policy name
+48
View File
@@ -2,6 +2,7 @@ package grpc
import (
"context"
"errors"
"fmt"
"net"
"strings"
@@ -106,3 +107,50 @@ func TestIamGrpcStore_AdminBearerToken(t *testing.T) {
}
})
}
// TestIamGrpcStore_DeleteAccessKeyNotFound pins the not-found translation:
// the filer reports a missing user or key as gRPC NotFound, and the store must
// surface it as credential.ErrAccessKeyNotFound so repeat deletes stay a no-op
// for IAM dispatchers that tolerate the sentinel.
func TestIamGrpcStore_DeleteAccessKeyNotFound(t *testing.T) {
const goodKey = "iam-admin-itest-key"
cm, err := credential.NewCredentialManager(credential.StoreTypeMemory, nil, "")
if err != nil {
t.Fatalf("NewCredentialManager: %v", err)
}
defer cm.Shutdown()
iamSrv := weed_server.NewIamGrpcServer(cm, security.SigningKey(goodKey))
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
grpcSrv := grpc.NewServer()
iam_pb.RegisterSeaweedIdentityAccessManagementServer(grpcSrv, iamSrv)
go func() { _ = grpcSrv.Serve(lis) }()
t.Cleanup(grpcSrv.Stop)
_, portStr, err := net.SplitHostPort(lis.Addr().String())
if err != nil {
t.Fatalf("split listener addr: %v", err)
}
serverAddr := pb.ServerAddress(fmt.Sprintf("127.0.0.1:0.%s", portStr))
store := &IamGrpcStore{}
store.SetFilerAddressFunc(func() pb.ServerAddress { return serverAddr }, grpc.WithTransportCredentials(insecure.NewCredentials()))
store.SetAdminSigning(security.SigningKey(goodKey), 0)
ctx := context.Background()
if err := store.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := store.DeleteAccessKey(ctx, "alice", "AKIAMISSING0000000001"); !errors.Is(err, credential.ErrAccessKeyNotFound) {
t.Fatalf("DeleteAccessKey with missing key: got %v, want ErrAccessKeyNotFound", err)
}
if err := store.DeleteAccessKey(ctx, "ghost", "AKIAMISSING0000000001"); !errors.Is(err, credential.ErrAccessKeyNotFound) {
t.Fatalf("DeleteAccessKey with missing user: got %v, want ErrAccessKeyNotFound", err)
}
}
+14 -2
View File
@@ -142,6 +142,14 @@ func (store *MemoryStore) UpdateUser(ctx context.Context, username string, ident
return credential.ErrUserNotFound
}
if identity.Name != username {
// Rename: the destination name must not already be taken, matching
// RenameUser's collision check.
if _, clash := store.users[identity.Name]; clash {
return credential.ErrUserAlreadyExists
}
}
// Remove old access keys from index
for _, cred := range existingUser.Credentials {
delete(store.accessKeys, cred.AccessKey)
@@ -156,11 +164,15 @@ func (store *MemoryStore) UpdateUser(ctx context.Context, username string, ident
// Deep copy to avoid mutation issues
identityCopy := store.deepCopyIdentity(identity)
store.users[username] = identityCopy
if identityCopy.Name != username {
// Rename: re-key the record, the way filer_etc does (delete old, save new).
delete(store.users, username)
}
store.users[identityCopy.Name] = identityCopy
// Re-index access keys
for _, cred := range identity.Credentials {
store.accessKeys[cred.AccessKey] = username
store.accessKeys[cred.AccessKey] = identityCopy.Name
}
return nil
@@ -378,3 +378,82 @@ func TestMemoryStoreServiceAccountByAccessKey(t *testing.T) {
t.Errorf("Expected ErrAccessKeyNotFound after delete, got %v", err)
}
}
// TestMemoryStoreUpdateUserRename: UpdateUser with an identity whose Name
// differs from the key must re-key the record, the way filer_etc does
// (delete old, save new). The IAM rename path relies on this.
func TestMemoryStoreUpdateUserRename(t *testing.T) {
store := &MemoryStore{}
if err := store.Initialize(util.GetViper(), "credential."); err != nil {
t.Fatalf("Failed to initialize store: %v", err)
}
ctx := context.Background()
err := store.CreateUser(ctx, &iam_pb.Identity{
Name: "oldname",
Credentials: []*iam_pb.Credential{{AccessKey: "access123", SecretKey: "secret123"}},
})
if err != nil {
t.Fatalf("Failed to create user: %v", err)
}
err = store.UpdateUser(ctx, "oldname", &iam_pb.Identity{
Name: "newname",
Credentials: []*iam_pb.Credential{{AccessKey: "access123", SecretKey: "secret123"}},
})
if err != nil {
t.Fatalf("Failed to rename user via UpdateUser: %v", err)
}
if _, err := store.GetUser(ctx, "oldname"); err != credential.ErrUserNotFound {
t.Fatalf("Expected ErrUserNotFound for old name, got %v", err)
}
renamed, err := store.GetUser(ctx, "newname")
if err != nil {
t.Fatalf("Failed to get renamed user: %v", err)
}
if renamed.Name != "newname" {
t.Errorf("Expected 'newname', got '%s'", renamed.Name)
}
byKey, err := store.GetUserByAccessKey(ctx, "access123")
if err != nil {
t.Fatalf("Access key must resolve to the renamed user: %v", err)
}
if byKey.Name != "newname" {
t.Errorf("Expected access key owner 'newname', got '%s'", byKey.Name)
}
}
// TestMemoryStoreUpdateUserRenameCollision: a rename whose destination name is
// taken must fail rather than overwrite the existing user.
func TestMemoryStoreUpdateUserRenameCollision(t *testing.T) {
store := &MemoryStore{}
if err := store.Initialize(util.GetViper(), "credential."); err != nil {
t.Fatalf("Failed to initialize store: %v", err)
}
ctx := context.Background()
if err := store.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}); err != nil {
t.Fatalf("Failed to create alice: %v", err)
}
if err := store.CreateUser(ctx, &iam_pb.Identity{
Name: "bob",
Credentials: []*iam_pb.Credential{{AccessKey: "bobkey123", SecretKey: "secret123"}},
}); err != nil {
t.Fatalf("Failed to create bob: %v", err)
}
err := store.UpdateUser(ctx, "alice", &iam_pb.Identity{Name: "bob"})
if err != credential.ErrUserAlreadyExists {
t.Fatalf("Expected ErrUserAlreadyExists, got %v", err)
}
// Both users must be intact.
if _, err := store.GetUser(ctx, "alice"); err != nil {
t.Fatalf("alice must still exist: %v", err)
}
bob, err := store.GetUserByAccessKey(ctx, "bobkey123")
if err != nil || bob.Name != "bob" {
t.Fatalf("bob's access key must still resolve to bob: %v", err)
}
}
+9 -7
View File
@@ -104,13 +104,15 @@ var baseS3ActionMap = map[string]string{
"DeleteObjectVersion": s3_constants.ACTION_WRITE,
"GetObjectVersion": s3_constants.ACTION_READ,
// Tagging operations
"GetObjectTagging": s3_constants.ACTION_TAGGING,
"GetObjectVersionTagging": s3_constants.ACTION_TAGGING,
"PutObjectTagging": s3_constants.ACTION_TAGGING,
"DeleteObjectTagging": s3_constants.ACTION_TAGGING,
"GetBucketTagging": s3_constants.ACTION_TAGGING,
"PutBucketTagging": s3_constants.ACTION_TAGGING,
"DeleteBucketTagging": s3_constants.ACTION_TAGGING,
"GetObjectTagging": s3_constants.ACTION_TAGGING,
"GetObjectVersionTagging": s3_constants.ACTION_TAGGING,
"PutObjectTagging": s3_constants.ACTION_TAGGING,
"PutObjectVersionTagging": s3_constants.ACTION_TAGGING,
"DeleteObjectTagging": s3_constants.ACTION_TAGGING,
"DeleteObjectVersionTagging": s3_constants.ACTION_TAGGING,
"GetBucketTagging": s3_constants.ACTION_TAGGING,
"PutBucketTagging": s3_constants.ACTION_TAGGING,
"DeleteBucketTagging": s3_constants.ACTION_TAGGING,
// ACL operations
"PutObjectAcl": s3_constants.ACTION_WRITE_ACP,
"GetObjectAcl": s3_constants.ACTION_READ_ACP,
+203 -2
View File
@@ -4,6 +4,7 @@ package iamapi
// Common IAM types and helpers are imported from the shared weed/iam package.
import (
"context"
"encoding/json"
"errors"
"fmt"
@@ -14,6 +15,7 @@ import (
"sync"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/glog"
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -1312,6 +1314,115 @@ func (iama *IamApiServer) handleImplicitUsername(r *http.Request, values url.Val
values.Set("UserName", identity.Name)
}
// targetedCredentialManager returns the credential manager through which a change to the named
// identity is written on its own instead of via SaveConfiguration, or nil when this server has
// none, or the identity is static: static identities live outside the store and keep the
// full-save path.
func (iama *IamApiServer) targetedCredentialManager(userName string) *credential.CredentialManager {
if iama.iam == nil {
return nil
}
cm := iama.iam.GetCredentialManager()
if cm == nil || cm.IsStaticIdentity(userName) {
return nil
}
return cm
}
// findIdentityByName returns the identity named userName in s3cfg, or nil.
func findIdentityByName(s3cfg *iam_pb.S3ApiConfiguration, userName string) *iam_pb.Identity {
for _, ident := range s3cfg.Identities {
if ident.Name == userName {
return ident
}
}
return nil
}
// groupsWithMember returns the groups in s3cfg that list userName as a member. Taken before a
// handler renames or removes the user, it names the group records that handler will change.
func groupsWithMember(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.Group {
var groups []*iam_pb.Group
for _, g := range s3cfg.Groups {
for _, m := range g.Members {
if m == userName {
groups = append(groups, g)
break
}
}
}
return groups
}
// serviceAccountsOf returns the service accounts in s3cfg whose parent is userName.
func serviceAccountsOf(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.ServiceAccount {
var accounts []*iam_pb.ServiceAccount
for _, sa := range s3cfg.ServiceAccounts {
if sa.ParentUser == userName {
accounts = append(accounts, sa)
}
}
return accounts
}
// persistIdentity writes the one identity a handler changed in s3cfg through the credential
// manager. The store writes that identity's record and propagates it alone; the other
// identities are not rewritten.
func persistIdentity(ctx context.Context, cm *credential.CredentialManager, s3cfg *iam_pb.S3ApiConfiguration, userName string) error {
ident := findIdentityByName(s3cfg, userName)
if ident == nil {
return credential.ErrUserNotFound
}
return cm.UpdateUser(ctx, userName, ident)
}
// persistRenamedIdentity writes a user renamed from oldName to newName by UpdateUser through the
// credential manager: the identity, the groups that listed the old name and the service accounts
// it parented. UpdateUser under the old name moves the record in stores that treat a changed Name
// as a rename (filer_etc, memory), and the propagating store propagates the new identity and the
// old name's removal; UpdateUser already moved the inline policies through PutPolicies. A store
// that did not move the record still holds the user under the old name; the caller is told so
// (false) and keeps the full save, which is what renames such a store today.
func persistRenamedIdentity(ctx context.Context, cm *credential.CredentialManager, s3cfg *iam_pb.S3ApiConfiguration, oldName, newName string, groups []*iam_pb.Group, accounts []*iam_pb.ServiceAccount) (bool, error) {
ident := findIdentityByName(s3cfg, newName)
if ident == nil {
return false, credential.ErrUserNotFound
}
if err := cm.UpdateUser(ctx, oldName, ident); err != nil {
return false, err
}
if _, err := cm.GetUser(ctx, newName); err != nil {
return false, nil
}
for _, g := range groups {
if err := cm.UpdateGroup(ctx, g); err != nil {
return false, fmt.Errorf("update group %s: %w", g.Name, err)
}
}
for _, sa := range accounts {
if err := cm.UpdateServiceAccount(ctx, sa.Id, sa); err != nil {
return false, fmt.Errorf("update service account %s: %w", sa.Id, err)
}
}
return true, nil
}
// deleteIdentity removes a user deleted by DeleteUser through the credential manager: its record
// (the store propagates the one removal) and the groups that listed it, whose membership
// DeleteUser already changed in s3cfg. DeleteUser already removed the inline policies through
// PutPolicies.
func deleteIdentity(ctx context.Context, cm *credential.CredentialManager, userName string, groups []*iam_pb.Group) error {
if err := cm.DeleteUser(ctx, userName); err != nil {
return err
}
for _, g := range groups {
if err := cm.UpdateGroup(ctx, g); err != nil {
return fmt.Errorf("update group %s: %w", g.Name, err)
}
}
return nil
}
func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
// Lock to prevent concurrent read-modify-write race conditions
policyLock.Lock()
@@ -1333,6 +1444,9 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
glog.V(4).Infof("DoActions: %+v", iamlib.RedactSensitiveFormValues(values))
var response iamlib.RequestIDSetter
changed := true
// persisted is set by the actions that wrote one identity through the credential manager
// instead of SaveConfiguration; the in-memory identity maps are reloaded after them too.
persisted := false
switch r.Form.Get("Action") {
case "ListUsers":
response = iama.ListUsers(s3cfg, values)
@@ -1365,40 +1479,107 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
}
changed = false
case "UpdateUser":
userName, newUserName := values.Get("UserName"), values.Get("NewUserName")
// Taken before the rename: the records the handler changes besides the identity.
groups := groupsWithMember(s3cfg, userName)
accounts := serviceAccountsOf(s3cfg, userName)
var err *IamError
response, err = iama.UpdateUser(s3cfg, values)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
// Write the renamed identity, its groups and service accounts through the credential
// manager instead of rewriting every identity via SaveConfiguration. A request that
// renames nothing changed nothing, so there is nothing to write either way.
if cm := iama.targetedCredentialManager(userName); cm != nil {
renamed := true
if newUserName != "" && newUserName != userName {
var err error
renamed, err = persistRenamedIdentity(r.Context(), cm, s3cfg, userName, newUserName, groups, accounts)
if err != nil {
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
return
}
}
changed, persisted = !renamed, renamed
}
case "DeleteUser":
userName := values.Get("UserName")
groups := groupsWithMember(s3cfg, userName)
var err *IamError
response, err = iama.DeleteUser(s3cfg, userName)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
// Targeted delete: one record removed and one removal propagated, plus the groups whose
// membership changed, instead of rewriting every remaining identity.
if cm := iama.targetedCredentialManager(userName); cm != nil {
if err := deleteIdentity(r.Context(), cm, userName, groups); err != nil {
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
return
}
changed, persisted = false, true
}
case "CreateAccessKey":
iama.handleImplicitUsername(r, values)
var err *IamError
response, err = iama.CreateAccessKey(s3cfg, values)
userName := values.Get("UserName")
resp, err := iama.CreateAccessKey(s3cfg, values)
if err != nil {
glog.Errorf("CreateAccessKey: %+v", err.Error)
writeIamErrorResponse(w, r, reqID, err)
return
}
response = resp
// Targeted write: credentialManager.CreateAccessKey adds the key to the one identity and
// propagates that identity alone. The handler creates the identity for a user it does
// not know; that case still needs the full save.
if cm := iama.targetedCredentialManager(userName); cm != nil {
if _, known := cm.GetUser(r.Context(), userName); known == nil {
cred := &iam_pb.Credential{
AccessKey: *resp.CreateAccessKeyResult.AccessKey.AccessKeyId,
SecretKey: *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey,
Status: accessKeyStatusActive,
}
if err := cm.CreateAccessKey(r.Context(), userName, cred); err != nil {
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
return
}
changed, persisted = false, true
}
}
case "DeleteAccessKey":
iama.handleImplicitUsername(r, values)
userName, accessKeyId := values.Get("UserName"), values.Get("AccessKeyId")
response = iama.DeleteAccessKey(s3cfg, values)
// Targeted write: credentialManager.DeleteAccessKey removes the key from the one identity
// and propagates that identity alone. The handler answers 200 for a key or user it does
// not know, so a not-found from the store is the same no-op it always was.
if cm := iama.targetedCredentialManager(userName); cm != nil {
err := cm.DeleteAccessKey(r.Context(), userName, accessKeyId)
if err != nil && !errors.Is(err, credential.ErrAccessKeyNotFound) && !errors.Is(err, credential.ErrUserNotFound) {
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
return
}
changed, persisted = false, true
}
case "UpdateAccessKey":
iama.handleImplicitUsername(r, values)
userName := values.Get("UserName")
var err *IamError
response, err = iama.UpdateAccessKey(s3cfg, values)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
if cm := iama.targetedCredentialManager(userName); cm != nil {
if err := persistIdentity(r.Context(), cm, s3cfg, userName); err != nil {
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
return
}
changed, persisted = false, true
}
case "CreatePolicy":
var err *IamError
response, err = iama.CreatePolicy(s3cfg, values)
@@ -1410,6 +1591,7 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
// The `changed` flag is false because this does not modify the main s3cfg.Identities configuration.
changed = false
case "PutUserPolicy":
userName := values.Get("UserName")
var err *IamError
response, err = iama.PutUserPolicy(s3cfg, values)
if err != nil {
@@ -1417,6 +1599,15 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
writeIamErrorResponse(w, r, reqID, err)
return
}
// The policy document is already stored through PutPolicies; what remains is the
// identity's recomputed Actions, written and propagated for that identity alone.
if cm := iama.targetedCredentialManager(userName); cm != nil {
if err := persistIdentity(r.Context(), cm, s3cfg, userName); err != nil {
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
return
}
changed, persisted = false, true
}
case "GetUserPolicy":
var err *IamError
response, err = iama.GetUserPolicy(s3cfg, values)
@@ -1426,12 +1617,20 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
}
changed = false
case "DeleteUserPolicy":
userName := values.Get("UserName")
var err *IamError
response, err = iama.DeleteUserPolicy(s3cfg, values)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
if cm := iama.targetedCredentialManager(userName); cm != nil {
if err := persistIdentity(r.Context(), cm, s3cfg, userName); err != nil {
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
return
}
changed, persisted = false, true
}
case "ListUserPolicies":
iama.handleImplicitUsername(r, values)
var err *IamError
@@ -1642,6 +1841,8 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
writeIamErrorResponse(w, r, reqID, &iamError)
return
}
}
if changed || persisted {
// Reload in-memory identity maps so subsequent LookupByAccessKey calls
// can see newly created or deleted keys immediately
if iama.iam != nil {
+302
View File
@@ -0,0 +1,302 @@
package iamapi
// Targeted-write regression tests: single-identity IAM actions must write only
// the identity they changed through the credential manager, not every identity
// via PutS3ApiConfiguration/SaveConfiguration.
// See https://github.com/seaweedfs/seaweedfs/issues/11865.
import (
"context"
"net/http"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/credential/memory"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// targetedRecordingStore wraps a memory store and counts the write methods
// the dispatcher used, so a test can assert the single-identity path was
// taken. It embeds the concrete store (rather than the CredentialStore
// interface) so optional interfaces like InlinePolicyStore stay visible
// through the wrapper.
type targetedRecordingStore struct {
*memory.MemoryStore
saves int
createAccessKeys int
deleteAccessKeys int
updateUsers int
deleteUsers int
updateGroups int
}
func (r *targetedRecordingStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
r.saves++
return r.MemoryStore.SaveConfiguration(ctx, config)
}
func (r *targetedRecordingStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
r.createAccessKeys++
return r.MemoryStore.CreateAccessKey(ctx, username, cred)
}
func (r *targetedRecordingStore) DeleteAccessKey(ctx context.Context, username string, accessKey string) error {
r.deleteAccessKeys++
return r.MemoryStore.DeleteAccessKey(ctx, username, accessKey)
}
func (r *targetedRecordingStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
r.updateUsers++
return r.MemoryStore.UpdateUser(ctx, username, identity)
}
func (r *targetedRecordingStore) DeleteUser(ctx context.Context, username string) error {
r.deleteUsers++
return r.MemoryStore.DeleteUser(ctx, username)
}
func (r *targetedRecordingStore) UpdateGroup(ctx context.Context, group *iam_pb.Group) error {
r.updateGroups++
return r.MemoryStore.UpdateGroup(ctx, group)
}
func targetedIamApiServer() (*IamApiServer, *credential.CredentialManager, *countingConfigSaver, *targetedRecordingStore) {
srv, cm, counter := iamApiServerWithCredentialManager()
rec := &targetedRecordingStore{MemoryStore: cm.Store.(*memory.MemoryStore)}
cm.Store = rec
return srv, cm, counter, rec
}
const targetedTestPolicy = `{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::bench/*"]}]
}`
func TestIamApiCreateAccessKeyTargeted(t *testing.T) {
srv, cm, counter, rec := targetedIamApiServer()
ctx := context.Background()
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
req, _ := iam.New(session.New()).CreateAccessKeyRequest(&iam.CreateAccessKeyInput{UserName: aws.String("alice")})
_ = req.Build()
out := CreateAccessKeyResponse{}
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled, "CreateAccessKey must not PutS3ApiConfiguration")
assert.Equal(t, 0, rec.saves)
assert.Equal(t, 1, rec.createAccessKeys)
ident, err := cm.GetUser(ctx, "alice")
require.NoError(t, err)
require.Len(t, ident.Credentials, 1)
assert.Equal(t, *out.CreateAccessKeyResult.AccessKey.AccessKeyId, ident.Credentials[0].AccessKey)
}
// CreateAccessKey for a user the store does not know still needs the full save:
// the handler creates the identity in the config, so there is no existing
// record to write a key into.
func TestIamApiCreateAccessKeyUnknownUserFallsBack(t *testing.T) {
srv, cm, counter, _ := targetedIamApiServer()
ctx := context.Background()
req, _ := iam.New(session.New()).CreateAccessKeyRequest(&iam.CreateAccessKeyInput{UserName: aws.String("ghost")})
_ = req.Build()
out := CreateAccessKeyResponse{}
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 1, counter.putCalled)
ident, err := cm.GetUser(ctx, "ghost")
require.NoError(t, err)
assert.Len(t, ident.Credentials, 1)
}
func TestIamApiDeleteAccessKeyTargeted(t *testing.T) {
srv, cm, counter, rec := targetedIamApiServer()
ctx := context.Background()
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{
Name: "alice",
Credentials: []*iam_pb.Credential{{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake"}},
}))
req, _ := iam.New(session.New()).DeleteAccessKeyRequest(&iam.DeleteAccessKeyInput{
UserName: aws.String("alice"),
AccessKeyId: aws.String("AKIATESTFAKEKEY00001"),
})
_ = req.Build()
out := DeleteAccessKeyResponse{}
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled, "DeleteAccessKey must not PutS3ApiConfiguration")
assert.Equal(t, 1, rec.deleteAccessKeys)
ident, err := cm.GetUser(ctx, "alice")
require.NoError(t, err)
assert.Empty(t, ident.Credentials)
// Deleting a key that does not exist still answers 200 and stays targeted.
req, _ = iam.New(session.New()).DeleteAccessKeyRequest(&iam.DeleteAccessKeyInput{
UserName: aws.String("alice"),
AccessKeyId: aws.String("AKIATESTFAKEKEY99999"),
})
_ = req.Build()
resp, err = executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled)
}
func TestIamApiUpdateAccessKeyTargeted(t *testing.T) {
srv, cm, counter, rec := targetedIamApiServer()
ctx := context.Background()
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{
Name: "alice",
Credentials: []*iam_pb.Credential{{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake", Status: "Active"}},
}))
req, _ := iam.New(session.New()).UpdateAccessKeyRequest(&iam.UpdateAccessKeyInput{
UserName: aws.String("alice"),
AccessKeyId: aws.String("AKIATESTFAKEKEY00001"),
Status: aws.String(iam.StatusTypeInactive),
})
_ = req.Build()
out := UpdateAccessKeyResponse{}
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled, "UpdateAccessKey must not PutS3ApiConfiguration")
assert.Equal(t, 1, rec.updateUsers)
ident, err := cm.GetUser(ctx, "alice")
require.NoError(t, err)
require.Len(t, ident.Credentials, 1)
assert.Equal(t, iam.StatusTypeInactive, ident.Credentials[0].Status)
}
func TestIamApiPutUserPolicyTargeted(t *testing.T) {
srv, cm, counter, rec := targetedIamApiServer()
ctx := context.Background()
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
req, _ := iam.New(session.New()).PutUserPolicyRequest(&iam.PutUserPolicyInput{
UserName: aws.String("alice"),
PolicyName: aws.String("read-bench"),
PolicyDocument: aws.String(targetedTestPolicy),
})
_ = req.Build()
out := PutUserPolicyResponse{}
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled, "PutUserPolicy must not PutS3ApiConfiguration")
assert.Equal(t, 0, rec.saves)
assert.Equal(t, 1, rec.updateUsers)
ident, err := cm.GetUser(ctx, "alice")
require.NoError(t, err)
assert.NotEmpty(t, ident.Actions, "recomputed Actions must be persisted for the one identity")
}
func TestIamApiDeleteUserPolicyTargeted(t *testing.T) {
srv, cm, counter, rec := targetedIamApiServer()
ctx := context.Background()
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
putReq, _ := iam.New(session.New()).PutUserPolicyRequest(&iam.PutUserPolicyInput{
UserName: aws.String("alice"),
PolicyName: aws.String("read-bench"),
PolicyDocument: aws.String(targetedTestPolicy),
})
_ = putReq.Build()
putOut := PutUserPolicyResponse{}
resp, err := executeRequestWith(srv, putReq.HTTPRequest, &putOut)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
delReq, _ := iam.New(session.New()).DeleteUserPolicyRequest(&iam.DeleteUserPolicyInput{
UserName: aws.String("alice"),
PolicyName: aws.String("read-bench"),
})
_ = delReq.Build()
delOut := DeleteUserPolicyResponse{}
resp, err = executeRequestWith(srv, delReq.HTTPRequest, &delOut)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled, "DeleteUserPolicy must not PutS3ApiConfiguration")
assert.Equal(t, 2, rec.updateUsers)
policies := Policies{}
require.NoError(t, srv.s3ApiConfig.GetPolicies(&policies))
assert.Empty(t, policies.InlinePolicies["alice"])
}
func TestIamApiUpdateUserRenameTargeted(t *testing.T) {
srv, cm, counter, _ := targetedIamApiServer()
ctx := context.Background()
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
require.NoError(t, cm.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
req, _ := iam.New(session.New()).UpdateUserRequest(&iam.UpdateUserInput{
UserName: aws.String("alice"),
NewUserName: aws.String("alice-renamed"),
})
_ = req.Build()
out := UpdateUserResponse{}
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled, "UpdateUser rename must not PutS3ApiConfiguration")
_, err = cm.GetUser(ctx, "alice")
require.ErrorIs(t, err, credential.ErrUserNotFound)
_, err = cm.GetUser(ctx, "alice-renamed")
require.NoError(t, err)
g, err := cm.GetGroup(ctx, "devs")
require.NoError(t, err)
assert.ElementsMatch(t, []string{"alice-renamed", "bob"}, g.Members)
}
func TestIamApiDeleteUserTargeted(t *testing.T) {
srv, cm, counter, rec := targetedIamApiServer()
ctx := context.Background()
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
require.NoError(t, cm.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
req, _ := iam.New(session.New()).DeleteUserRequest(&iam.DeleteUserInput{UserName: aws.String("alice")})
_ = req.Build()
out := DeleteUserResponse{}
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, 0, counter.putCalled, "DeleteUser must not PutS3ApiConfiguration")
assert.Equal(t, 1, rec.deleteUsers)
assert.Equal(t, 1, rec.updateGroups)
_, err = cm.GetUser(ctx, "alice")
require.ErrorIs(t, err, credential.ErrUserNotFound)
g, err := cm.GetGroup(ctx, "devs")
require.NoError(t, err)
assert.ElementsMatch(t, []string{"bob"}, g.Members)
_, err = cm.GetUser(ctx, "bob")
require.NoError(t, err, "other identities must be untouched")
}
+9
View File
@@ -17,6 +17,7 @@ import (
"github.com/jinzhu/copier"
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/credential/memory"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
@@ -607,6 +608,7 @@ func iamApiServerWithCredentialManager() (*IamApiServer, *credential.CredentialM
type countingConfigSaver struct {
cm *credential.CredentialManager
putCalled int
policies Policies
}
func (c *countingConfigSaver) GetS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfiguration) error {
@@ -616,6 +618,8 @@ func (c *countingConfigSaver) GetS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfigura
}
s3cfg.Identities = config.Identities
s3cfg.Policies = config.Policies
s3cfg.Groups = config.Groups
s3cfg.ServiceAccounts = config.ServiceAccounts
return nil
}
@@ -625,10 +629,15 @@ func (c *countingConfigSaver) PutS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfigura
}
func (c *countingConfigSaver) GetPolicies(policies *Policies) error {
*policies = c.policies
if c.policies.Policies == nil && c.policies.InlinePolicies == nil {
return filer_pb.ErrNotFound
}
return nil
}
func (c *countingConfigSaver) PutPolicies(policies *Policies) error {
c.policies = *policies
return nil
}
+25
View File
@@ -244,7 +244,31 @@ func Mkdir(ctx context.Context, filerClient FilerClient, parentDirectoryPath str
})
}
// MkdirExclusive is Mkdir that never replaces an entry already at the path:
// the create is O_EXCL and a taken name answers ErrEntryAlreadyExists. The
// taken name leaves the callback as a result, not an error: failover counts a
// callback error against the filer and retries on the next one.
func MkdirExclusive(ctx context.Context, filerClient FilerClient, parentDirectoryPath string, dirName string, fn func(entry *Entry)) error {
var taken error
err := filerClient.WithFilerClient(false, func(client SeaweedFilerClient) error {
err := doMkdir(ctx, client, parentDirectoryPath, dirName, true, fn)
if errors.Is(err, ErrEntryAlreadyExists) {
taken = err
return nil
}
return err
})
if err == nil {
err = taken
}
return err
}
func DoMkdir(ctx context.Context, client SeaweedFilerClient, parentDirectoryPath string, dirName string, fn func(entry *Entry)) error {
return doMkdir(ctx, client, parentDirectoryPath, dirName, false, fn)
}
func doMkdir(ctx context.Context, client SeaweedFilerClient, parentDirectoryPath string, dirName string, exclusive bool, fn func(entry *Entry)) error {
entry := &Entry{
Name: dirName,
IsDirectory: true,
@@ -264,6 +288,7 @@ func DoMkdir(ctx context.Context, client SeaweedFilerClient, parentDirectoryPath
request := &CreateEntryRequest{
Directory: parentDirectoryPath,
Entry: entry,
OExcl: exclusive,
}
glog.V(1).InfofCtx(ctx, "mkdir: %v", request)
+18
View File
@@ -11,6 +11,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -22,6 +23,23 @@ func (s3a *S3ApiServer) mkdir(parentDirectoryPath string, dirName string, fn fun
}
// mkdirExclusive never replaces an entry already at the path: PutBucket uses
// it so a plain bucket cannot replace a table bucket created in its
// check-to-create window.
func (s3a *S3ApiServer) mkdirExclusive(parentDirectoryPath string, dirName string, fn func(entry *filer_pb.Entry)) error {
return filer_pb.MkdirExclusive(context.Background(), s3a, parentDirectoryPath, dirName, fn)
}
// concurrentEntryIsForeign: after PutBucket's exclusive mkdir met an entry,
// whether that entry must be answered BucketAlreadyExists without looking at
// its owner: a table bucket (it carries no S3 owner and must never read as
// "owned by you"), or an entry that could not be read.
func concurrentEntryIsForeign(entry *filer_pb.Entry, err error) bool {
return err != nil || entry == nil || s3tables.IsTableBucketEntry(entry)
}
func (s3a *S3ApiServer) mkFile(parentDirectoryPath string, fileName string, chunks []*filer_pb.FileChunk, fn func(entry *filer_pb.Entry)) error {
err := filer_pb.MkFile(context.Background(), s3a, parentDirectoryPath, fileName, chunks, fn)
+14 -1
View File
@@ -182,20 +182,33 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool)
}
}
// Tagging operations
// Tagging operations. The routes match ?tagging whenever the key is
// present (gorilla/mux does not compare the value), so any value counts.
// A versionId retargets the request at a specific version, so the
// version-tagging action applies, not the current-object one.
if query.Has("tagging") {
versioned := hasObject && query.Get("versionId") != ""
switch method {
case http.MethodGet:
if versioned {
return s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING
}
if hasObject {
return s3_constants.S3_ACTION_GET_OBJECT_TAGGING
}
return s3_constants.S3_ACTION_GET_BUCKET_TAGGING
case http.MethodPut:
if versioned {
return s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING
}
if hasObject {
return s3_constants.S3_ACTION_PUT_OBJECT_TAGGING
}
return s3_constants.S3_ACTION_PUT_BUCKET_TAGGING
case http.MethodDelete:
if versioned {
return s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING
}
if hasObject {
return s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING
}
+32
View File
@@ -114,6 +114,38 @@ func TestResolveS3Action_AttributesBeforeVersionId(t *testing.T) {
}
}
// A tagging request carrying versionId targets a specific version and must
// resolve to the version-tagging action so a grant limited to current-object
// tagging cannot reach historical versions.
func TestResolveS3Action_VersionTagging(t *testing.T) {
tests := []struct {
name string
method string
object string
query string
want string
}{
{"get current tags", http.MethodGet, "key", "tagging", s3_constants.S3_ACTION_GET_OBJECT_TAGGING},
{"put current tags", http.MethodPut, "key", "tagging", s3_constants.S3_ACTION_PUT_OBJECT_TAGGING},
{"delete current tags", http.MethodDelete, "key", "tagging", s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING},
{"get version tags", http.MethodGet, "key", "tagging&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING},
{"put version tags", http.MethodPut, "key", "tagging&versionId=v1", s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING},
{"delete version tags", http.MethodDelete, "key", "tagging&versionId=v1", s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING},
{"empty versionId stays current", http.MethodGet, "key", "tagging&versionId=", s3_constants.S3_ACTION_GET_OBJECT_TAGGING},
{"bucket tagging ignores versionId", http.MethodGet, "", "tagging&versionId=v1", s3_constants.S3_ACTION_GET_BUCKET_TAGGING},
{"non-empty tagging is still tagging", http.MethodGet, "key", "tagging=x&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING},
{"non-empty tagging plain", http.MethodGet, "key", "tagging=x", s3_constants.S3_ACTION_GET_OBJECT_TAGGING},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
if got := ResolveS3Action(r, s3_constants.ACTION_READ, "bucket", tt.object); got != tt.want {
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
}
})
}
}
// Bucket subresources registered with ACTION_ADMIN must resolve to their own
// S3 actions so a policy granting one of them does not need s3:*, and so no
// broader grant sweeps them in.
@@ -20,6 +20,11 @@ const (
S3_ACTION_PUT_OBJECT_TAGGING = "s3:PutObjectTagging"
S3_ACTION_DELETE_OBJECT_TAGGING = "s3:DeleteObjectTagging"
// Version-specific tagging operations (?tagging&versionId)
S3_ACTION_GET_OBJECT_VERSION_TAGGING = "s3:GetObjectVersionTagging"
S3_ACTION_PUT_OBJECT_VERSION_TAGGING = "s3:PutObjectVersionTagging"
S3_ACTION_DELETE_OBJECT_VERSION_TAGGING = "s3:DeleteObjectVersionTagging"
// Object retention and legal hold
S3_ACTION_GET_OBJECT_RETENTION = "s3:GetObjectRetention"
S3_ACTION_PUT_OBJECT_RETENTION = "s3:PutObjectRetention"
+35 -16
View File
@@ -330,7 +330,7 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
// This ensures Object Lock configuration is set in the same CreateEntry call,
// preventing race conditions where the bucket exists without Object Lock enabled
var bucketCrtime int64
if err := s3a.mkdir(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
if err := s3a.mkdirExclusive(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
bucketCrtime = entry.Attributes.Crtime
// Set bucket owner
@@ -373,6 +373,16 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
// return the appropriate already-exists error instead of InternalError.
if exist, checkErr := s3a.exists(s3a.option.BucketsPath, bucket, true); checkErr == nil && exist {
glog.V(3).Infof("PutBucketHandler: bucket %s was created concurrently", bucket)
// From the entry itself, not the bucket registry: the pre-check
// above has just cached this name as not found, so in the race this
// branch exists for the registry would still say "no table bucket".
if concurrentEntryIsForeign(s3a.getEntry(s3a.option.BucketsPath, bucket)) {
s3err.WriteErrorResponse(w, r, s3err.ErrBucketAlreadyExists)
return
}
if s3a.bucketConfigCache != nil {
s3a.bucketConfigCache.RemoveNegativeCache(bucket)
}
errCode := s3a.existingBucketError(r, bucket, currentIdentityId, requestHasACL)
if errCode == s3err.ErrBucketAlreadyOwnedByYou {
s3a.healBucketOwnerIndex(bucket, currentIdentityId)
@@ -744,7 +754,7 @@ func (s3a *S3ApiServer) autoCreateBucket(r *http.Request, bucket string) error {
identityId := s3_constants.GetIdentityNameFromContext(r)
var bucketCrtime int64
if err := s3a.mkdir(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
if err := s3a.mkdirExclusive(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
bucketCrtime = entry.Attributes.Crtime
setBucketOwner(r)(entry)
}); err != nil {
@@ -754,26 +764,35 @@ func (s3a *S3ApiServer) autoCreateBucket(r *http.Request, bucket string) error {
glog.Warningf("autoCreateBucket: failed to check existence for bucket %s: %v", bucket, err2)
return fmt.Errorf("failed to auto-create bucket %s: %w", bucket, errors.Join(err, err2))
} else if exist {
entry, getErr := s3a.getEntry(s3a.option.BucketsPath, bucket)
if getErr != nil {
glog.Warningf("autoCreateBucket: failed to get entry for existing bucket %s: %v", bucket, getErr)
return fmt.Errorf("failed to auto-create bucket %s: %w", bucket, errors.Join(err, getErr))
}
if concurrentEntryIsForeign(entry, nil) {
// A table bucket carries no S3 owner and must not gain one —
// or a write intended for a missing plain bucket.
if s3a.bucketConfigCache != nil {
s3a.bucketConfigCache.RemoveNegativeCache(bucket)
}
return fmt.Errorf("auto-create bucket %s: name taken by a table bucket: %w", bucket, err)
}
// The bucket exists, which is fine. However, we should ensure it has an owner.
// If it was created by a concurrent request that didn't set an owner,
// we'll set it here to ensure consistency.
if entry, getErr := s3a.getEntry(s3a.option.BucketsPath, bucket); getErr == nil {
if entry.Extended == nil || len(entry.Extended[s3_constants.AmzIdentityId]) == 0 {
// No owner set, assign current admin as owner
setBucketOwner(r)(entry)
if updateErr := s3a.updateEntry(s3a.option.BucketsPath, entry); updateErr != nil {
glog.Warningf("autoCreateBucket: failed to set owner for existing bucket %s: %v", bucket, updateErr)
} else {
glog.V(1).Infof("Set owner for existing bucket %s (created by concurrent request)", bucket)
if owner := bucketEntryOwner(entry); owner != "" {
if indexErr := s3a.addBucketToOwnerIndex(owner, bucket, entry.Attributes.Crtime); indexErr != nil {
glog.Warningf("autoCreateBucket: owner index add %s/%s: %v", owner, bucket, indexErr)
}
if entry.Extended == nil || len(entry.Extended[s3_constants.AmzIdentityId]) == 0 {
// No owner set, assign current admin as owner
setBucketOwner(r)(entry)
if updateErr := s3a.updateEntry(s3a.option.BucketsPath, entry); updateErr != nil {
glog.Warningf("autoCreateBucket: failed to set owner for existing bucket %s: %v", bucket, updateErr)
} else {
glog.V(1).Infof("Set owner for existing bucket %s (created by concurrent request)", bucket)
if owner := bucketEntryOwner(entry); owner != "" {
if indexErr := s3a.addBucketToOwnerIndex(owner, bucket, entry.Attributes.Crtime); indexErr != nil {
glog.Warningf("autoCreateBucket: owner index add %s/%s: %v", owner, bucket, indexErr)
}
}
}
} else {
glog.Warningf("autoCreateBucket: failed to get entry for existing bucket %s: %v", bucket, getErr)
}
// Remove bucket from negative cache — it exists now
if s3a.bucketConfigCache != nil {
+215 -3
View File
@@ -67,6 +67,136 @@ func (e *EmbeddedIamApi) refreshIAMConfiguration() error {
return nil
}
// canPersistIdentity reports whether a change to the named identity can be written through the
// credential manager's single-identity methods instead of SaveConfiguration. It is false when
// there is no credential manager, when the caller asked for no persistent write (skipPersist),
// and for static identities, which live outside the store: those keep the full-save path.
func (e *EmbeddedIamApi) canPersistIdentity(skipPersist bool, userName string) bool {
return e.credentialManager != nil && !skipPersist && !e.credentialManager.IsStaticIdentity(userName)
}
// groupsWithMember returns the groups in s3cfg that list userName as a member. Taken before a
// handler renames or removes the user, it names the group records that handler will change.
func groupsWithMember(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.Group {
var groups []*iam_pb.Group
for _, g := range s3cfg.Groups {
for _, m := range g.Members {
if m == userName {
groups = append(groups, g)
break
}
}
}
return groups
}
// serviceAccountsOf returns the service accounts in s3cfg whose parent is userName.
func serviceAccountsOf(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.ServiceAccount {
var accounts []*iam_pb.ServiceAccount
for _, sa := range s3cfg.ServiceAccounts {
if sa.ParentUser == userName {
accounts = append(accounts, sa)
}
}
return accounts
}
// persistIdentity writes the one identity a handler changed in s3cfg through the credential
// manager. The store writes that identity's record and propagates it alone; the other
// identities are not rewritten.
func (e *EmbeddedIamApi) persistIdentity(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration, userName string) error {
ident := findIdentityByName(s3cfg, userName)
if ident == nil {
return credential.ErrUserNotFound
}
return e.credentialManager.UpdateUser(ctx, userName, ident)
}
// persistRenamedIdentity writes a user renamed from oldName to newName by UpdateUser through the
// credential manager: the identity, the groups that listed the old name and the service accounts
// it parented. Where the store has RenameUser the handler already moved the record and its inline
// policies, and the identity is written under the new name. Otherwise UpdateUser under the old
// name moves the record in stores that treat a changed Name as a rename (filer_etc, memory), the
// propagating store propagates the new identity and the old name's removal, and the inline policy
// copies the handler left under the old name are removed. A store that did neither still holds
// the user under the old name; the caller is told so (false) and keeps the full save, which is
// what renames such a store today.
func (e *EmbeddedIamApi) persistRenamedIdentity(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration, oldName, newName string, groups []*iam_pb.Group, accounts []*iam_pb.ServiceAccount) (bool, error) {
ident := findIdentityByName(s3cfg, newName)
if ident == nil {
return false, credential.ErrUserNotFound
}
storedAs := oldName
if _, err := e.credentialManager.GetUser(ctx, newName); err == nil {
storedAs = newName
}
if err := e.credentialManager.UpdateUser(ctx, storedAs, ident); err != nil {
return false, err
}
if storedAs == oldName {
if _, err := e.credentialManager.GetUser(ctx, newName); err != nil {
return false, nil
}
policyNames, err := e.credentialManager.ListUserInlinePolicies(ctx, oldName)
if err != nil {
return false, fmt.Errorf("list inline policies for %s: %w", oldName, err)
}
for _, policyName := range policyNames {
if err := e.credentialManager.DeleteUserInlinePolicy(ctx, oldName, policyName); err != nil {
return false, fmt.Errorf("remove inline policy %s from %s: %w", policyName, oldName, err)
}
}
}
for _, g := range groups {
if err := e.credentialManager.UpdateGroup(ctx, g); err != nil {
return false, fmt.Errorf("update group %s: %w", g.Name, err)
}
}
for _, sa := range accounts {
if err := e.credentialManager.UpdateServiceAccount(ctx, sa.Id, sa); err != nil {
return false, fmt.Errorf("update service account %s: %w", sa.Id, err)
}
}
return true, nil
}
// deleteIdentity removes a user deleted by DeleteUser through the credential manager: its inline
// policies, its record (the store propagates the one removal) and the groups that listed it,
// whose membership DeleteUser already changed in s3cfg.
func (e *EmbeddedIamApi) deleteIdentity(ctx context.Context, userName string, groups []*iam_pb.Group) error {
policyNames, err := e.credentialManager.ListUserInlinePolicies(ctx, userName)
if err != nil {
return fmt.Errorf("list inline policies for %s: %w", userName, err)
}
for _, policyName := range policyNames {
if err := e.credentialManager.DeleteUserInlinePolicy(ctx, userName, policyName); err != nil {
return fmt.Errorf("remove inline policy %s from %s: %w", policyName, userName, err)
}
}
if err := e.credentialManager.DeleteUser(ctx, userName); err != nil {
return err
}
for _, g := range groups {
if err := e.credentialManager.UpdateGroup(ctx, g); err != nil {
return fmt.Errorf("update group %s: %w", g.Name, err)
}
}
return nil
}
// reloadsAfterTargetedWrite names the actions that persist through the credential manager
// rather than SaveConfiguration; the in-memory identity maps are refreshed after them the way
// they are after a full save.
func reloadsAfterTargetedWrite(action string) bool {
switch action {
case "AttachUserPolicy", "DetachUserPolicy", "CreatePolicy", "CreatePolicyVersion", "DeletePolicy",
"CreateUser", "UpdateUser", "DeleteUser", "CreateAccessKey", "DeleteAccessKey", "UpdateAccessKey",
"SetUserStatus", "PutUserPolicy", "DeleteUserPolicy", "PutGroupPolicy", "DeleteGroupPolicy":
return true
}
return false
}
// Constants for service account identifiers
const (
ServiceAccountIDLength = 12 // Length of the service account ID
@@ -2735,27 +2865,79 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
}
changed = false
case "UpdateUser":
userName, newUserName := values.Get("UserName"), values.Get("NewUserName")
// Taken before the rename: the records the handler changes besides the identity.
groups := groupsWithMember(s3cfg, userName)
accounts := serviceAccountsOf(s3cfg, userName)
var iamErr *iamError
response, iamErr = e.UpdateUser(ctx, s3cfg, values)
if iamErr != nil {
return nil, iamErr
}
// Write the renamed identity, its groups and service accounts through the credential
// manager instead of rewriting every identity via SaveConfiguration. A request that
// renames nothing changed nothing, so there is nothing to write either way.
if e.canPersistIdentity(skipPersist, userName) {
renamed := true
if newUserName != "" && newUserName != userName {
var err error
renamed, err = e.persistRenamedIdentity(ctx, s3cfg, userName, newUserName, groups, accounts)
if err != nil {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
}
changed = !renamed
}
case "DeleteUser":
userName := values.Get("UserName")
groups := groupsWithMember(s3cfg, userName)
var iamErr *iamError
response, iamErr = e.DeleteUser(s3cfg, userName)
if iamErr != nil {
return nil, iamErr
}
// Targeted delete: one record removed and one removal propagated, plus the groups whose
// membership changed, instead of rewriting every remaining identity.
if e.canPersistIdentity(skipPersist, userName) {
if err := e.deleteIdentity(ctx, userName, groups); err != nil {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
changed = false
}
case "CreateAccessKey":
var iamErr *iamError
response, iamErr = e.CreateAccessKey(s3cfg, values)
userName := values.Get("UserName")
resp, iamErr := e.CreateAccessKey(s3cfg, values)
if iamErr != nil {
glog.Errorf("CreateAccessKey: %+v", iamErr.Error)
return nil, iamErr
}
response = resp
// Targeted write: credentialManager.CreateAccessKey adds the key to the one identity
// and propagates that identity alone.
if e.canPersistIdentity(skipPersist, userName) {
cred := &iam_pb.Credential{
AccessKey: *resp.CreateAccessKeyResult.AccessKey.AccessKeyId,
SecretKey: *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey,
Status: iamAccessKeyStatusActive,
}
if err := e.credentialManager.CreateAccessKey(ctx, userName, cred); err != nil {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
changed = false
}
case "DeleteAccessKey":
userName, accessKeyId := values.Get("UserName"), values.Get("AccessKeyId")
response = e.DeleteAccessKey(s3cfg, values)
// Targeted write: credentialManager.DeleteAccessKey removes the key from the one identity
// and propagates that identity alone. The handler answers 200 for a key or user it does
// not know, so a not-found from the store is the same no-op it always was.
if e.canPersistIdentity(skipPersist, userName) {
err := e.credentialManager.DeleteAccessKey(ctx, userName, accessKeyId)
if err != nil && !errors.Is(err, credential.ErrAccessKeyNotFound) && !errors.Is(err, credential.ErrUserNotFound) {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
changed = false
}
case "CreatePolicy":
var iamErr *iamError
response, iamErr = e.CreatePolicy(ctx, values)
@@ -2773,12 +2955,21 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
}
changed = false
case "PutUserPolicy":
userName := values.Get("UserName")
var iamErr *iamError
response, iamErr = e.PutUserPolicy(s3cfg, values)
if iamErr != nil {
glog.Errorf("PutUserPolicy: %+v", iamErr.Error)
return nil, iamErr
}
// The policy document is already stored; what remains is the identity's recomputed
// Actions, written and propagated for that identity alone.
if e.canPersistIdentity(skipPersist, userName) {
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
changed = false
}
case "GetUserPolicy":
var iamErr *iamError
response, iamErr = e.GetUserPolicy(s3cfg, values)
@@ -2787,11 +2978,18 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
}
changed = false
case "DeleteUserPolicy":
userName := values.Get("UserName")
var iamErr *iamError
response, iamErr = e.DeleteUserPolicy(s3cfg, values)
if iamErr != nil {
return nil, iamErr
}
if e.canPersistIdentity(skipPersist, userName) {
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
changed = false
}
case "ListUserPolicies":
var iamErr *iamError
response, iamErr = e.ListUserPolicies(s3cfg, values)
@@ -2883,17 +3081,31 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
}
changed = false
case "SetUserStatus":
userName := values.Get("UserName")
var iamErr *iamError
response, iamErr = e.SetUserStatus(s3cfg, values)
if iamErr != nil {
return nil, iamErr
}
if e.canPersistIdentity(skipPersist, userName) {
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
changed = false
}
case "UpdateAccessKey":
userName := values.Get("UserName")
var iamErr *iamError
response, iamErr = e.UpdateAccessKey(s3cfg, values)
if iamErr != nil {
return nil, iamErr
}
if e.canPersistIdentity(skipPersist, userName) {
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
}
changed = false
}
// Service Account actions
case "CreateServiceAccount":
createdBy := values.Get("CreatedBy")
@@ -3034,7 +3246,7 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
glog.Errorf("Failed to reload IAM configuration after mutation: %v", err)
// Don't fail the request since the persistent save succeeded
}
} else if action == "AttachUserPolicy" || action == "DetachUserPolicy" || action == "CreatePolicy" || action == "CreatePolicyVersion" || action == "DeletePolicy" || action == "CreateUser" || action == "PutGroupPolicy" || action == "DeleteGroupPolicy" {
} else if reloadsAfterTargetedWrite(action) {
// Even if changed=false (persisted via credentialManager), we should still reload
// if we are utilizing the local in-memory cache for speed
if err := e.ReloadConfiguration(); err != nil {
@@ -0,0 +1,362 @@
package s3api
// Targeted-write regression tests: single-identity IAM actions must write and
// propagate only the identity they changed, not every identity via
// SaveConfiguration. See https://github.com/seaweedfs/seaweedfs/issues/11865.
import (
"context"
"encoding/json"
"net/url"
"testing"
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/credential/memory"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// recordingStore wraps a memory store and counts the write methods the
// dispatcher used, so a test can assert the single-identity path was taken and
// SaveConfiguration was not. It embeds the concrete store (rather than the
// CredentialStore interface) so optional interfaces like InlinePolicyStore and
// UserRenamer stay visible through the wrapper.
type recordingStore struct {
*memory.MemoryStore
saves int
createAccessKeys int
deleteAccessKeys int
updateUsers int
deleteUsers int
updateGroups int
}
func (r *recordingStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
r.saves++
return r.MemoryStore.SaveConfiguration(ctx, config)
}
func (r *recordingStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
r.createAccessKeys++
return r.MemoryStore.CreateAccessKey(ctx, username, cred)
}
func (r *recordingStore) DeleteAccessKey(ctx context.Context, username string, accessKey string) error {
r.deleteAccessKeys++
return r.MemoryStore.DeleteAccessKey(ctx, username, accessKey)
}
func (r *recordingStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
r.updateUsers++
return r.MemoryStore.UpdateUser(ctx, username, identity)
}
func (r *recordingStore) DeleteUser(ctx context.Context, username string) error {
r.deleteUsers++
return r.MemoryStore.DeleteUser(ctx, username)
}
func (r *recordingStore) UpdateGroup(ctx context.Context, group *iam_pb.Group) error {
r.updateGroups++
return r.MemoryStore.UpdateGroup(ctx, group)
}
// newTargetedWriteTestApi seeds cfg into the store and wraps the store in a
// recordingStore. The initial sync save happens before the recorder is
// installed so it does not count.
func newTargetedWriteTestApi(t *testing.T, cfg *iam_pb.S3ApiConfiguration) (*EmbeddedIamApiForTest, *recordingStore) {
t.Helper()
api := NewEmbeddedIamApiForTest()
api.mockConfig = cfg
// Trigger the one-time mockConfig -> store seed through a read action.
_, iamErr := api.ExecuteAction(context.Background(), url.Values{"Action": {"ListUsers"}}, false, "")
require.Nil(t, iamErr)
rec := &recordingStore{MemoryStore: api.credentialManager.Store.(*memory.MemoryStore)}
api.credentialManager.Store = rec
return api, rec
}
func executeAction(t *testing.T, api *EmbeddedIamApiForTest, vals url.Values) {
t.Helper()
_, iamErr := api.ExecuteAction(context.Background(), vals, false, "")
require.Nil(t, iamErr)
}
func TestEmbeddedIamCreateAccessKeyTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
})
ctx := context.Background()
resp, iamErr := api.ExecuteAction(ctx, url.Values{
"Action": {"CreateAccessKey"},
"UserName": {"alice"},
}, false, "")
require.Nil(t, iamErr)
require.Equal(t, 0, rec.saves, "CreateAccessKey must not SaveConfiguration")
require.Equal(t, 1, rec.createAccessKeys)
out := resp.(*iamCreateAccessKeyResponse)
ident, err := api.credentialManager.GetUser(ctx, "alice")
require.NoError(t, err)
require.Len(t, ident.Credentials, 1)
assert.Equal(t, *out.CreateAccessKeyResult.AccessKey.AccessKeyId, ident.Credentials[0].AccessKey)
// The new key resolves in the store.
byKey, err := api.credentialManager.GetUserByAccessKey(ctx, *out.CreateAccessKeyResult.AccessKey.AccessKeyId)
require.NoError(t, err)
assert.Equal(t, "alice", byKey.Name)
}
func TestEmbeddedIamDeleteAccessKeyTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{
Name: "alice",
Credentials: []*iam_pb.Credential{{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake"}},
}},
})
ctx := context.Background()
executeAction(t, api, url.Values{
"Action": {"DeleteAccessKey"},
"UserName": {"alice"},
"AccessKeyId": {"AKIATESTFAKEKEY00001"},
})
require.Equal(t, 0, rec.saves, "DeleteAccessKey must not SaveConfiguration")
require.Equal(t, 1, rec.deleteAccessKeys)
ident, err := api.credentialManager.GetUser(ctx, "alice")
require.NoError(t, err)
assert.Empty(t, ident.Credentials)
_, err = api.credentialManager.GetUserByAccessKey(ctx, "AKIATESTFAKEKEY00001")
require.ErrorIs(t, err, credential.ErrAccessKeyNotFound)
}
func TestEmbeddedIamUpdateAccessKeyTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{
Name: "alice",
Credentials: []*iam_pb.Credential{
{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake", Status: iamAccessKeyStatusActive},
},
}},
})
ctx := context.Background()
executeAction(t, api, url.Values{
"Action": {"UpdateAccessKey"},
"UserName": {"alice"},
"AccessKeyId": {"AKIATESTFAKEKEY00001"},
"Status": {iamAccessKeyStatusInactive},
})
require.Equal(t, 0, rec.saves, "UpdateAccessKey must not SaveConfiguration")
require.Equal(t, 1, rec.updateUsers)
ident, err := api.credentialManager.GetUser(ctx, "alice")
require.NoError(t, err)
require.Len(t, ident.Credentials, 1)
assert.Equal(t, iamAccessKeyStatusInactive, ident.Credentials[0].Status)
}
const iamTargetedTestPolicy = `{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::bench/*"]}]
}`
func TestEmbeddedIamPutUserPolicyTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
})
ctx := context.Background()
executeAction(t, api, url.Values{
"Action": {"PutUserPolicy"},
"UserName": {"alice"},
"PolicyName": {"read-bench"},
"PolicyDocument": {iamTargetedTestPolicy},
})
require.Equal(t, 0, rec.saves, "PutUserPolicy must not SaveConfiguration")
require.Equal(t, 1, rec.updateUsers)
ident, err := api.credentialManager.GetUser(ctx, "alice")
require.NoError(t, err)
assert.NotEmpty(t, ident.Actions, "identity Actions must be recomputed and persisted")
doc, err := api.credentialManager.GetUserInlinePolicy(ctx, "alice", "read-bench")
require.NoError(t, err)
require.NotNil(t, doc)
}
func TestEmbeddedIamDeleteUserPolicyTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{Name: "alice"}},
})
ctx := context.Background()
executeAction(t, api, url.Values{
"Action": {"PutUserPolicy"},
"UserName": {"alice"},
"PolicyName": {"read-bench"},
"PolicyDocument": {iamTargetedTestPolicy},
})
require.Equal(t, 1, rec.updateUsers)
executeAction(t, api, url.Values{
"Action": {"DeleteUserPolicy"},
"UserName": {"alice"},
"PolicyName": {"read-bench"},
})
require.Equal(t, 0, rec.saves, "DeleteUserPolicy must not SaveConfiguration")
require.Equal(t, 2, rec.updateUsers)
policies, err := api.credentialManager.ListUserInlinePolicies(ctx, "alice")
require.NoError(t, err)
assert.Empty(t, policies)
ident, err := api.credentialManager.GetUser(ctx, "alice")
require.NoError(t, err)
assert.Empty(t, ident.Actions)
}
func TestEmbeddedIamSetUserStatusTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{Name: "alice"}},
})
ctx := context.Background()
executeAction(t, api, url.Values{
"Action": {"SetUserStatus"},
"UserName": {"alice"},
"Status": {iamAccessKeyStatusInactive},
})
require.Equal(t, 0, rec.saves, "SetUserStatus must not SaveConfiguration")
require.Equal(t, 1, rec.updateUsers)
ident, err := api.credentialManager.GetUser(ctx, "alice")
require.NoError(t, err)
assert.True(t, ident.Disabled)
}
func TestEmbeddedIamUpdateUserRenameTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
Groups: []*iam_pb.Group{
{Name: "devs", Members: []string{"alice", "bob"}},
{Name: "ops", Members: []string{"bob"}},
},
})
ctx := context.Background()
// Groups in the seed config must also be created in the store directly:
// the memory store only surfaces groups written via CreateGroup.
require.NoError(t, api.credentialManager.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
require.NoError(t, api.credentialManager.CreateGroup(ctx, &iam_pb.Group{Name: "ops", Members: []string{"bob"}}))
require.NoError(t, api.credentialManager.PutUserInlinePolicy(ctx, "alice", "p1", mustParseIamTargetedTestPolicy(t)))
executeAction(t, api, url.Values{
"Action": {"UpdateUser"},
"UserName": {"alice"},
"NewUserName": {"alice-renamed"},
})
require.Equal(t, 0, rec.saves, "UpdateUser rename must not SaveConfiguration")
_, err := api.credentialManager.GetUser(ctx, "alice")
require.ErrorIs(t, err, credential.ErrUserNotFound)
_, err = api.credentialManager.GetUser(ctx, "alice-renamed")
require.NoError(t, err)
// Group membership and inline policies follow the rename.
g, err := api.credentialManager.GetGroup(ctx, "devs")
require.NoError(t, err)
assert.ElementsMatch(t, []string{"alice-renamed", "bob"}, g.Members)
g, err = api.credentialManager.GetGroup(ctx, "ops")
require.NoError(t, err)
assert.ElementsMatch(t, []string{"bob"}, g.Members)
policies, err := api.credentialManager.ListUserInlinePolicies(ctx, "alice-renamed")
require.NoError(t, err)
assert.Equal(t, []string{"p1"}, policies)
policies, err = api.credentialManager.ListUserInlinePolicies(ctx, "alice")
require.NoError(t, err)
assert.Empty(t, policies)
}
func TestEmbeddedIamDeleteUserTargeted(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
Groups: []*iam_pb.Group{{Name: "devs", Members: []string{"alice", "bob"}}},
})
ctx := context.Background()
require.NoError(t, api.credentialManager.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
executeAction(t, api, url.Values{
"Action": {"DeleteUser"},
"UserName": {"alice"},
})
require.Equal(t, 0, rec.saves, "DeleteUser must not SaveConfiguration")
require.Equal(t, 1, rec.deleteUsers)
require.Equal(t, 1, rec.updateGroups)
_, err := api.credentialManager.GetUser(ctx, "alice")
require.ErrorIs(t, err, credential.ErrUserNotFound)
g, err := api.credentialManager.GetGroup(ctx, "devs")
require.NoError(t, err)
assert.ElementsMatch(t, []string{"bob"}, g.Members)
_, err = api.credentialManager.GetUser(ctx, "bob")
require.NoError(t, err, "other identities must be untouched")
}
// TestEmbeddedIamTargetedSkipPersist: skipPersist must suppress the targeted
// write exactly like it suppresses the full save.
func TestEmbeddedIamTargetedSkipPersist(t *testing.T) {
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{Name: "alice"}},
})
ctx := context.Background()
for _, vals := range []url.Values{
{"Action": {"CreateAccessKey"}, "UserName": {"alice"}},
{"Action": {"SetUserStatus"}, "UserName": {"alice"}, "Status": {iamAccessKeyStatusInactive}},
{"Action": {"PutUserPolicy"}, "UserName": {"alice"}, "PolicyName": {"p"}, "PolicyDocument": {iamTargetedTestPolicy}},
} {
_, iamErr := api.ExecuteAction(ctx, vals, true /*skipPersist*/, "")
require.Nil(t, iamErr, "action %v", vals.Get("Action"))
}
assert.Equal(t, 0, rec.saves)
assert.Equal(t, 0, rec.createAccessKeys)
assert.Equal(t, 0, rec.updateUsers)
ident, err := api.credentialManager.GetUser(ctx, "alice")
require.NoError(t, err)
assert.Empty(t, ident.Credentials)
assert.False(t, ident.Disabled)
}
// TestEmbeddedIamStaticIdentityKeepsFullSave: static identities live outside
// the store, so a change to one still takes the full-save path.
func TestEmbeddedIamStaticIdentityKeepsFullSave(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
api.credentialManager.SetStaticIdentities([]*iam_pb.Identity{{Name: "static-admin"}})
rec := &recordingStore{MemoryStore: api.credentialManager.Store.(*memory.MemoryStore)}
api.credentialManager.Store = rec
// Seed via a read action; static identities are merged into the loaded config.
_, iamErr := api.ExecuteAction(context.Background(), url.Values{"Action": {"ListUsers"}}, false, "")
require.Nil(t, iamErr)
rec.saves = 0
executeAction(t, api, url.Values{
"Action": {"SetUserStatus"},
"UserName": {"static-admin"},
"Status": {iamAccessKeyStatusInactive},
})
assert.Equal(t, 1, rec.saves, "static identity changes keep the full-save path")
assert.Equal(t, 0, rec.updateUsers)
}
func mustParseIamTargetedTestPolicy(t *testing.T) (doc policy_engine.PolicyDocument) {
t.Helper()
require.NoError(t, json.Unmarshal([]byte(iamTargetedTestPolicy), &doc))
return doc
}
@@ -174,7 +174,7 @@ func TestAnonymousObjectACLVersionedEmptyDirectoryMarker(t *testing.T) {
require.Equal(t, "null", rr.Header().Get("x-amz-version-id"))
}
rr := serveAnonymousRead(s3a, method, "folder", "", nil)
require.Equal(t, 404, rr.Code, "the bare prefix is still not an object")
require.Equal(t, 403, rr.Code, "the bare prefix is not an object, and the miss stays masked for a non-listable bucket")
marker.Extended[s3_constants.ExtAmzAclKey] = []byte(`[]`)
rr = serveAnonymousRead(s3a, method, "folder/", "", nil)
require.Equal(t, 403, rr.Code, rr.Body.String())
@@ -238,8 +238,12 @@ func TestAnonymousObjectACLVersionedDirectoryIdentity(t *testing.T) {
f.entries["/buckets/b/folder/.versions"] = &filer_pb.Entry{IsDirectory: true, Extended: map[string][]byte{s3_constants.ExtLatestVersionIdKey: []byte("")}}
}
// Equivalent filer-path spellings must not recover a different object's data.
for _, object := range []string{"folder/", "folder//", "folder\\"} {
assertMissing(serveAnonymousRead(s3a, method, object, route.query, headers))
assertMissing(serveAnonymousRead(s3a, method, "folder/", route.query, headers))
// Spellings the policy's folder/ grant does not cover are
// masked: a miss must be indistinguishable from a denied read.
for _, object := range []string{"folder//", "folder\\"} {
rr := serveAnonymousRead(s3a, method, object, route.query, headers)
require.Equal(t, http.StatusForbidden, rr.Code, rr.Body.String())
}
if kind == "regular file" || kind == "prefix object" || kind == "empty prefix object" {
// A slash-only policy must not authorize data belonging to the bare key.
+69
View File
@@ -4,10 +4,12 @@ import (
"context"
"encoding/json"
"net/http"
"net/url"
"path"
"strings"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
@@ -110,3 +112,70 @@ func (s3a *S3ApiServer) authorizeAnonymousObjectRead(r *http.Request, bucket, ob
}
return s3err.ErrAccessDenied
}
// authorizeAnonymousBucketList reports whether an anonymous caller may learn
// which keys exist in the bucket: bucket listing via policy or identity, or a
// public-read bucket. Anything else masks the miss as AccessDenied.
func (s3a *S3ApiServer) authorizeAnonymousBucketList(r *http.Request, bucket string) s3err.ErrorCode {
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
object := mux.Vars(r)["object"]
// The caller's query parameters would otherwise retarget these checks
// (?policy resolves to GetBucketPolicy) or satisfy a prefix condition on an
// unrelated subtree, so each runs on a request with a fixed shape: a
// ListBucket scoped to the probed key, and a plain read of the key itself.
// A caller that could learn the key's existence either way — by listing or
// by getting it — gets the real miss.
listReq := r.Clone(r.Context())
listReq.URL = &url.URL{Path: "/" + bucket, RawQuery: url.Values{"prefix": {object}}.Encode()}
// versionId must survive: a read of a specific version resolves to
// s3:GetObjectVersion, and dropping it would let a GetObject grant answer
// for versions the caller may not read.
readQuery := url.Values{}
if v := r.URL.Query().Get("versionId"); v != "" {
readQuery.Set("versionId", v)
}
readReq := r.Clone(r.Context())
readReq.URL = &url.URL{Path: "/" + bucket + "/" + object, RawQuery: readQuery.Encode()}
principal := buildPrincipalARN(identity, r)
policyAllowed := false
code, allowed := s3a.checkPolicyWithEntry(listReq, bucket, "", string(s3_constants.ACTION_LIST), principal, nil)
if code != s3err.ErrNone {
return code
}
policyAllowed = allowed
if !policyAllowed {
code, allowed = s3a.checkPolicyWithEntry(readReq, bucket, object, string(s3_constants.ACTION_READ), principal, nil)
if code != s3err.ErrNone {
return code
}
policyAllowed = allowed
}
if s3a.iam.isActionExplicitlyDeniedByApplicablePolicies(listReq, identity, s3_constants.ACTION_LIST, bucket, "") ||
s3a.iam.isActionExplicitlyDeniedByApplicablePolicies(readReq, identity, s3_constants.ACTION_READ, bucket, object) {
return s3err.ErrAccessDenied
}
if policyAllowed {
return s3err.ErrNone
}
if identity != nil &&
(s3a.iam.VerifyActionPermission(listReq, identity, s3_constants.ACTION_LIST, bucket, "") == s3err.ErrNone ||
s3a.iam.VerifyActionPermission(readReq, identity, s3_constants.ACTION_READ, bucket, object) == s3err.ErrNone) {
return s3err.ErrNone
}
if config, code := s3a.getBucketConfig(bucket); code == s3err.ErrNone && config.IsPublicRead {
return s3err.ErrNone
}
return s3err.ErrAccessDenied
}
// writeAnonymousAwareNotFound keeps missing-bucket and missing-key misses
// indistinguishable from denied reads for anonymous callers: a 404 only
// reaches the wire when the bucket is anonymously listable.
func (s3a *S3ApiServer) writeAnonymousAwareNotFound(w http.ResponseWriter, r *http.Request, bucket string, code s3err.ErrorCode) {
if isAnonymousObjectRead(r) && s3a.authorizeAnonymousBucketList(r, bucket) != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
return
}
s3err.WriteErrorResponse(w, r, code)
}
+23 -19
View File
@@ -663,7 +663,7 @@ func (s3a *S3ApiServer) handleDirectoryObjectRequest(w http.ResponseWriter, r *h
} else if isDirectoryObject {
// Directory object but doesn't exist
glog.V(2).Infof("%s: directory object %s/%s not found", handlerName, bucket, object)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return true // Request was handled (with not found)
}
@@ -770,7 +770,11 @@ func (s3a *S3ApiServer) processConditionalHeaders(w http.ResponseWriter, r *http
w.Header().Set("ETag", result.ETag)
}
s3err.WriteErrorResponse(w, r, result.ErrorCode)
if result.ErrorCode == s3err.ErrNoSuchKey || result.ErrorCode == s3err.ErrNoSuchBucket {
s3a.writeAnonymousAwareNotFound(w, r, bucket, result.ErrorCode)
} else {
s3err.WriteErrorResponse(w, r, result.ErrorCode)
}
return result, true // request handled
}
return result, false // request not handled
@@ -841,7 +845,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
versioningConfigured, err = s3a.isVersioningConfigured(bucket)
if err != nil {
if err == filer_pb.ErrNotFound {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchBucket)
return
}
glog.Errorf("Error checking versioning status for bucket %s: %v", bucket, err)
@@ -860,7 +864,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
if err != nil {
glog.Errorf("Failed to get specific version %s: %v", versionId, err)
if errors.Is(err, filer_pb.ErrNotFound) {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchVersion)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchVersion)
} else {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
}
@@ -886,7 +890,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
entry, err = s3a.getLatestObjectVersion(bucket, object)
if err != nil {
glog.Errorf("GetObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
} else if errors.Is(versionsErr, filer_pb.ErrNotFound) {
@@ -900,7 +904,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
} else {
// No object at regular path either - object doesn't exist
glog.V(3).Infof("GetObject: object not found at regular path or .versions for %s/%s", bucket, object)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
} else {
@@ -909,7 +913,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
entry, err = s3a.getLatestObjectVersion(bucket, object)
if err != nil {
glog.Errorf("GetObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
}
@@ -930,7 +934,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
// Check if this is a delete marker
if entry.Extended != nil {
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
}
@@ -975,7 +979,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
return
}
if objectEntryForSSE == nil {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
}
@@ -992,7 +996,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
// A bare directory path is not an object: 404 like AWS instead of an empty 200,
// so Hadoop-style clients fall back to LIST discovery. HEAD and ranged GET already 404.
if !strings.HasSuffix(object, "/") && isBareDirectory(objectEntryForSSE) {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
@@ -2518,7 +2522,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
versioningConfigured, err = s3a.isVersioningConfigured(bucket)
if err != nil {
if err == filer_pb.ErrNotFound {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchBucket)
return
}
glog.Errorf("Error checking versioning status for bucket %s: %v", bucket, err)
@@ -2536,7 +2540,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
if err != nil {
glog.Errorf("Failed to get specific version %s for %s/%s: %v", versionId, bucket, object, err)
if errors.Is(err, filer_pb.ErrNotFound) {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchVersion)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchVersion)
} else {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
}
@@ -2562,7 +2566,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
entry, err = s3a.getLatestObjectVersion(bucket, object)
if err != nil {
glog.Errorf("HeadObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
} else if errors.Is(versionsErr, filer_pb.ErrNotFound) {
@@ -2576,7 +2580,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
} else {
// No object at regular path either - object doesn't exist
glog.V(3).Infof("HeadObject: object not found at regular path or .versions for %s/%s", bucket, object)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
} else {
@@ -2585,7 +2589,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
entry, err = s3a.getLatestObjectVersion(bucket, object)
if err != nil {
glog.Errorf("HeadObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
}
@@ -2606,7 +2610,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
// Check if this is a delete marker
if entry.Extended != nil {
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
}
@@ -2644,7 +2648,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
return
}
if objectEntryForSSE == nil {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
}
@@ -2710,7 +2714,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
isZeroByteFile := objectEntryForSSE.Attributes.FileSize == 0 && !objectEntryForSSE.IsDirectory
// A directory with data (a promoted file) is retrievable; empty directories 404 for LIST fallback.
if isBareDirectory(objectEntryForSSE) {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
if isZeroByteFile {
@@ -2718,7 +2722,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
if s3a.hasChildren(r.Context(), bucket, object) {
// This is an implicit directory with children
// Return 404 to force clients (like s3fs) to use LIST-based discovery
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
return
}
}
@@ -11,6 +11,7 @@ import (
"github.com/gorilla/mux"
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/require"
)
@@ -228,6 +229,22 @@ func TestObjectLockActionsRoundTrip(t *testing.T) {
}
}
// Anonymous misses must not disclose bucket or key existence: 404 is only
// served when anonymous listing is allowed.
func TestAnonymousBucketListAuthorization(t *testing.T) {
s3a := &S3ApiServer{iam: &IdentityAccessManagement{}, bucketConfigCache: NewBucketConfigCache(time.Minute)}
s3a.bucketConfigCache.Set("open", &BucketConfig{Name: "open", IsPublicRead: true})
s3a.bucketConfigCache.Set("private", &BucketConfig{Name: "private"})
req := httptest.NewRequest(http.MethodGet, "http://localhost:8333/open/key", nil)
if got := s3a.authorizeAnonymousBucketList(req, "open"); got != s3err.ErrNone {
t.Errorf("listable bucket: %v, want ErrNone", got)
}
if got := s3a.authorizeAnonymousBucketList(req, "private"); got != s3err.ErrAccessDenied {
t.Errorf("private bucket: %v, want AccessDenied", got)
}
}
// Internal Seaweed-X-Amz-* headers carry server-validated object lock values
// into entry metadata; client-supplied ones must be dropped on entry or the
// dedicated-permission check on x-amz-object-lock-* is bypassed.
+14
View File
@@ -27,10 +27,23 @@ const extendedAttributeUpdateAttempts = 5
// createDirectory creates a new directory at the specified path
func (h *S3TablesHandler) createDirectory(ctx context.Context, client filer_pb.SeaweedFilerClient, path string) error {
return h.createDirectoryEntry(ctx, client, path, false, nil)
}
// createDirectoryExclusive creates a directory entry together with its
// extended attributes in one CreateEntry that fails with
// filer_pb.ErrEntryAlreadyExists when an entry is already there: nothing is
// replaced and no reader sees the directory without its attributes.
func (h *S3TablesHandler) createDirectoryExclusive(ctx context.Context, client filer_pb.SeaweedFilerClient, path string, extended map[string][]byte) error {
return h.createDirectoryEntry(ctx, client, path, true, extended)
}
func (h *S3TablesHandler) createDirectoryEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, path string, exclusive bool, extended map[string][]byte) error {
dir, name := splitPath(path)
now := time.Now().Unix()
return filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
Directory: dir,
OExcl: exclusive,
Entry: &filer_pb.Entry{
Name: name,
IsDirectory: true,
@@ -39,6 +52,7 @@ func (h *S3TablesHandler) createDirectory(ctx context.Context, client filer_pb.S
Crtime: now,
FileMode: uint32(0755 | os.ModeDir),
},
Extended: extended,
},
})
}
@@ -0,0 +1,89 @@
package s3tables
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
// competingCreateClient lands a foreign entry where the handler's existence
// check just answered "not there": the create that follows must lose to it
// rather than replace it, the way a second caller's create wins the window in
// a check-then-create race.
type competingCreateClient struct {
filer_pb.SeaweedFilerClient
f *s3tablestest.MemFiler
dir string
name string
plant bool
}
func (c *competingCreateClient) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
resp, err := c.SeaweedFilerClient.LookupDirectoryEntry(ctx, req, opts...)
if c.plant && err != nil && req.Directory == c.dir && req.Name == c.name {
c.plant = false
c.f.Put(c.dir, c.name, map[string][]byte{
ExtendedKeyTableBucket: []byte("true"),
ExtendedKeyMetadata: []byte(`{"OwnerAccountID":"competitor"}`),
})
}
return resp, err
}
func runHandler(t *testing.T, m *Manager, client filer_pb.SeaweedFilerClient, operation string, input interface{}) (int, S3TablesError) {
t.Helper()
body, err := json.Marshal(input)
require.NoError(t, err)
req, err := newManagerRequest(context.Background(), operation, body, "admin")
require.NoError(t, err)
recorder := httptest.NewRecorder()
m.handler.HandleRequest(recorder, req, NewManagerClient(client))
result := recorder.Result()
defer result.Body.Close()
var response S3TablesError
json.NewDecoder(result.Body).Decode(&response)
return result.StatusCode, response
}
func TestCreateTableBucketLostRaceKeepsTheFirstCreate(t *testing.T) {
fs := s3tablestest.Start(t)
m := NewManager()
client := &competingCreateClient{SeaweedFilerClient: fs.Client, f: fs, dir: TablesPath, name: "bucket", plant: true}
status, resp := runHandler(t, m, client, "CreateTableBucket", &CreateTableBucketRequest{Name: "bucket"})
assert.Equal(t, http.StatusConflict, status)
assert.Equal(t, ErrCodeBucketAlreadyExists, resp.Type)
survivor := fs.Get(TablesPath, "bucket")
require.NotNil(t, survivor)
assert.Equal(t, `{"OwnerAccountID":"competitor"}`, string(survivor.Extended[ExtendedKeyMetadata]))
}
func TestCreateNamespaceLostRaceKeepsTheFirstCreate(t *testing.T) {
fs := s3tablestest.Start(t)
m := NewManager()
bucketMetadata, _ := json.Marshal(&tableBucketMetadata{Name: "bucket", OwnerAccountID: DefaultAccountID})
fs.Put(TablesPath, "bucket", map[string][]byte{ExtendedKeyTableBucket: []byte("true"), ExtendedKeyMetadata: bucketMetadata})
arn, err := BuildBucketARN(DefaultRegion, DefaultAccountID, "bucket")
require.NoError(t, err)
client := &competingCreateClient{SeaweedFilerClient: fs.Client, f: fs, dir: GetTableBucketPath("bucket"), name: "ns", plant: true}
status, resp := runHandler(t, m, client, "CreateNamespace", &CreateNamespaceRequest{
TableBucketARN: arn,
Namespace: []string{"ns"},
})
assert.Equal(t, http.StatusConflict, status)
assert.Equal(t, ErrCodeNamespaceAlreadyExists, resp.Type)
survivor := fs.Get(GetTableBucketPath("bucket"), "ns")
require.NotNil(t, survivor)
assert.Equal(t, `{"OwnerAccountID":"competitor"}`, string(survivor.Extended[ExtendedKeyMetadata]))
}
+18 -17
View File
@@ -140,6 +140,7 @@ func (h *S3TablesHandler) handleCreateTableBucket(w http.ResponseWriter, r *http
return err
}
var taken error
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
// Ensure root tables directory exists
if !h.entryExists(r.Context(), client, TablesPath) {
@@ -148,35 +149,35 @@ func (h *S3TablesHandler) handleCreateTableBucket(w http.ResponseWriter, r *http
}
}
// Create bucket directory
if err := h.createDirectory(r.Context(), client, bucketPath); err != nil {
return err
extended := map[string][]byte{
ExtendedKeyTableBucket: []byte("true"),
ExtendedKeyMetadata: metadataBytes,
}
// Mark as a table bucket
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyTableBucket, []byte("true")); err != nil {
return err
}
// Set metadata as extended attribute
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata, metadataBytes); err != nil {
return err
}
// Set tags if provided
if len(req.Tags) > 0 {
tagsBytes, err := json.Marshal(req.Tags)
if err != nil {
return fmt.Errorf("failed to marshal tags: %w", err)
}
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyTags, tagsBytes); err != nil {
return err
extended[ExtendedKeyTags] = tagsBytes
}
if err := h.createDirectoryExclusive(r.Context(), client, bucketPath, extended); err != nil {
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
taken = err // an answer, not a filer failure
return nil
}
return err
}
return nil
})
if err == nil && taken != nil {
err = taken
}
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
h.writeError(w, http.StatusConflict, ErrCodeBucketAlreadyExists, fmt.Sprintf("table bucket %s already exists", req.Name))
return err
}
if err != nil {
glog.Errorf("S3Tables: failed to create table bucket %s: %v", req.Name, err)
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, "failed to create table bucket")
+60 -20
View File
@@ -11,8 +11,29 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
// errOwnerlessBucket marks a table bucket that has the marker but no
// metadata: damaged, and answered with the operation's own denial rather than
// letting the caller name itself the bucket's owner before any check runs.
var errOwnerlessBucket = fmt.Errorf("table bucket has no owner metadata")
// mayRepairOwnerlessBucket reports whether the caller may repair a bucket in
// that state: the admin or a trusted internal handler. hasAdminAction also
// answers s3tables:*, an operation grant, not administrator status.
func (h *S3TablesHandler) mayRepairOwnerlessBucket(r *http.Request) bool {
if h.trusted || h.getAccountID(r) == s3_constants.AccountAdminId {
return true
}
for _, action := range getIdentityActions(r) {
if action == s3_constants.ACTION_ADMIN {
return true
}
}
return false
}
// handleCreateNamespace creates a new namespace in a table bucket
func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.Request, filerClient FilerClient) error {
glog.Errorf("S3Tables: handleCreateNamespace called")
@@ -66,16 +87,29 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
if entryResp.Entry == nil || !IsTableBucketEntry(entryResp.Entry) {
return filer_pb.ErrNotFound
}
bucketMetadata = tableBucketMetadata{
Name: bucketName,
CreatedAt: time.Now(),
OwnerAccountID: ownerAccountID,
if !h.mayRepairOwnerlessBucket(r) {
return errOwnerlessBucket
}
metadataBytes, err := json.Marshal(&bucketMetadata)
if err != nil {
return fmt.Errorf("failed to marshal bucket metadata: %w", err)
}
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata, metadataBytes); err != nil {
// Repair the marker-only entry under the entry lock so a
// creator finishing its own create in the meantime keeps its
// owner: adopt whatever metadata is there, write only when it
// is still absent.
if err := h.mutateEntryExtended(r.Context(), client, bucketPath, func(extended map[string][]byte) error {
if data, ok := extended[ExtendedKeyMetadata]; ok {
return json.Unmarshal(data, &bucketMetadata)
}
bucketMetadata = tableBucketMetadata{
Name: bucketName,
CreatedAt: time.Now(),
OwnerAccountID: ownerAccountID,
}
metadataBytes, err := json.Marshal(&bucketMetadata)
if err != nil {
return fmt.Errorf("failed to marshal bucket metadata: %w", err)
}
extended[ExtendedKeyMetadata] = metadataBytes
return nil
}); err != nil {
return err
}
} else {
@@ -101,6 +135,10 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
})
if err != nil {
if errors.Is(err, errOwnerlessBucket) {
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to create namespace in this bucket")
return ErrAccessDenied
}
if errors.Is(err, filer_pb.ErrNotFound) {
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
} else {
@@ -159,20 +197,22 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
return fmt.Errorf("failed to marshal metadata: %w", err)
}
var taken error
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
// Create namespace directory
if err := h.createDirectory(r.Context(), client, namespacePath); err != nil {
return err
err := h.createDirectoryExclusive(r.Context(), client, namespacePath, map[string][]byte{ExtendedKeyMetadata: metadataBytes})
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
taken = err // an answer, not a filer failure
return nil
}
// Set metadata as extended attribute
if err := h.setExtendedAttribute(r.Context(), client, namespacePath, ExtendedKeyMetadata, metadataBytes); err != nil {
return err
}
return nil
return err
})
if err == nil && taken != nil {
err = taken
}
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
h.writeError(w, http.StatusConflict, ErrCodeNamespaceAlreadyExists, fmt.Sprintf("namespace %s already exists", namespaceName))
return err
}
if err != nil {
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, "failed to create namespace")
return err
@@ -0,0 +1,88 @@
package s3tables
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A table bucket with the marker but no metadata is damaged, not ownerless for
// the taking: an ordinary caller is answered with the operation's own denial,
// and the admin or a trusted handler may repair it.
func TestCreateNamespaceOnAnOwnerlessBucket(t *testing.T) {
const bucket = "broken"
plant := func(fs *s3tablestest.MemFiler) {
fs.Put(TablesPath, bucket, map[string][]byte{ExtendedKeyTableBucket: []byte("true")})
}
arn, err := BuildBucketARN(DefaultRegion, DefaultAccountID, bucket)
require.NoError(t, err)
request := &CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{"ns"}}
t.Run("an outsider gets the denial and writes nothing", func(t *testing.T) {
fs := s3tablestest.Start(t)
plant(fs)
m := NewManager()
body, err := json.Marshal(request)
require.NoError(t, err)
identity := &testIdentity{Name: "outsider", Account: &testIdentityAccount{Id: "outsider"}, Actions: []string{"Read"}}
req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "outsider")
require.NoError(t, err)
recorder := httptest.NewRecorder()
m.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client))
assert.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String())
entry := fs.Get(TablesPath, bucket)
require.NotNil(t, entry)
assert.Empty(t, entry.Extended[ExtendedKeyMetadata], "the denied caller wrote itself in as the bucket owner")
assert.Nil(t, fs.Get(GetTableBucketPath(bucket), "ns"))
})
t.Run("a trusted handler repairs it and owns it", func(t *testing.T) {
fs := s3tablestest.Start(t)
plant(fs)
m := NewManager()
m.SetTrusted(true)
body, err := json.Marshal(request)
require.NoError(t, err)
identity := &testIdentity{Name: "svc", Account: &testIdentityAccount{Id: "svc"}, Actions: []string{"Read"}}
req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "svc")
require.NoError(t, err)
recorder := httptest.NewRecorder()
m.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client))
assert.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
entry := fs.Get(TablesPath, bucket)
require.NotNil(t, entry)
var metadata tableBucketMetadata
require.NoError(t, json.Unmarshal(entry.Extended[ExtendedKeyMetadata], &metadata))
assert.Equal(t, "svc", metadata.OwnerAccountID)
require.NotNil(t, fs.Get(GetTableBucketPath(bucket), "ns"))
})
t.Run("an untrusted admin repairs it too", func(t *testing.T) {
fs := s3tablestest.Start(t)
plant(fs)
m := NewManager()
body, err := json.Marshal(request)
require.NoError(t, err)
identity := &testIdentity{Name: "admin", Account: &testIdentityAccount{Id: s3_constants.AccountAdminId}, Actions: []string{"Admin"}}
req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "admin")
require.NoError(t, err)
recorder := httptest.NewRecorder()
m.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client))
assert.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
entry := fs.Get(TablesPath, bucket)
require.NotNil(t, entry)
var metadata tableBucketMetadata
require.NoError(t, json.Unmarshal(entry.Extended[ExtendedKeyMetadata], &metadata))
assert.Equal(t, s3_constants.AccountAdminId, metadata.OwnerAccountID)
})
}
+1 -22
View File
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
@@ -75,8 +74,7 @@ type MasterServer struct {
option *MasterOption
guard *security.Guard
preallocateSize int64
volumeIdAllocatorCloser io.Closer
preallocateSize int64
Topo *topology.Topology
vg *topology.VolumeGrowth
@@ -129,10 +127,6 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
option.VolumeGrowthDisabled = v.GetBool("master.volume_growth.disable")
v.SetDefault("master.volume_growth.freeze_on_topology_mismatch", true)
v.SetDefault("master.volume_growth.state_loss_recovery_wait", "0s")
v.SetDefault("master.volume_id_allocator", "")
v.SetDefault("master.volume_id_etcd.servers", "localhost:2379")
v.SetDefault("master.volume_id_etcd.key_prefix", "/seaweedfs")
v.SetDefault("master.volume_id_etcd.timeout", "3s")
topology.VolumeGrowStrategy.Copy1Count = v.GetUint32("master.volume_growth.copy_1")
topology.VolumeGrowStrategy.Copy2Count = v.GetUint32("master.volume_growth.copy_2")
@@ -187,18 +181,6 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
}
return err
}
switch v.GetString("master.volume_id_allocator") {
case "":
case "etcd":
allocator, closer, err := newVolumeIdAllocator(v, ms.Topo)
if err != nil {
glog.Fatalf("volume id allocator: %v", err)
}
ms.volumeIdAllocatorCloser = closer
ms.Topo.SetVolumeIdAllocator(allocator)
default:
glog.Fatalf("unknown master.volume_id_allocator %q", v.GetString("master.volume_id_allocator"))
}
ms.vg = topology.NewDefaultVolumeGrowth()
glog.V(0).Infoln("Volume Size Limit is", ms.option.VolumeSizeLimitMB, "MB")
@@ -690,9 +672,6 @@ func (ms *MasterServer) Shutdown() {
if raftServer != nil {
raftServer.Stop()
}
if ms.volumeIdAllocatorCloser != nil {
ms.volumeIdAllocatorCloser.Close()
}
}
func (ms *MasterServer) Reload() {
-60
View File
@@ -1,60 +0,0 @@
package weed_server
import (
"crypto/tls"
"fmt"
"io"
"strings"
"time"
"go.etcd.io/etcd/client/pkg/v3/transport"
clientv3 "go.etcd.io/etcd/client/v3"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/topology"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// newVolumeIdAllocator returns the allocator and an io.Closer to release the
// etcd client on shutdown; the closer is nil for built-in allocation.
func newVolumeIdAllocator(v *util.ViperProxy, topo *topology.Topology) (topology.VolumeIdAllocator, io.Closer, error) {
servers := v.GetString("master.volume_id_etcd.servers")
timeout, err := time.ParseDuration(v.GetString("master.volume_id_etcd.timeout"))
if err != nil {
return nil, nil, fmt.Errorf("parse master.volume_id_etcd.timeout: %w", err)
}
var tlsConfig *tls.Config
caFile := v.GetString("master.volume_id_etcd.tls_ca_file")
certFile := v.GetString("master.volume_id_etcd.tls_client_crt_file")
keyFile := v.GetString("master.volume_id_etcd.tls_client_key_file")
if caFile != "" || certFile != "" || keyFile != "" {
tlsInfo := transport.TLSInfo{
CertFile: certFile,
KeyFile: keyFile,
TrustedCAFile: caFile,
}
if tlsConfig, err = tlsInfo.ClientConfig(); err != nil {
return nil, nil, fmt.Errorf("etcd TLS client configuration error: %w", err)
}
}
client, err := clientv3.New(clientv3.Config{
Endpoints: strings.Split(servers, ","),
Username: v.GetString("master.volume_id_etcd.username"),
Password: v.GetString("master.volume_id_etcd.password"),
DialTimeout: timeout,
TLS: tlsConfig,
})
if err != nil {
return nil, nil, fmt.Errorf("connect volume id etcd: %w", err)
}
glog.Infof("volume id allocator: etcd %s", servers)
allocator := topology.NewEtcdVolumeIdAllocator(
client,
v.GetString("master.volume_id_etcd.key_prefix"),
timeout,
topo.GetMaxVolumeId)
return allocator, allocator, nil
}
+4
View File
@@ -913,6 +913,8 @@ func (s *Store) MarkVolumeReadonly(i needle.VolumeId, canDelete bool, persist bo
}
// Wait for in-flight appends so a mark acked mid-write cannot race an
// encode that reads the index and deletes the replica the write lands on.
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
if canDelete && !v.HasRemoteFile() {
@@ -1207,6 +1209,7 @@ func (s *Store) deleteVolumeGuarded(i needle.VolumeId, onlyEmpty bool, onlyGarba
unlockAll := func() {
for _, v := range lockedVolumes {
v.dataFileAccessLock.Unlock()
v.dataFileSyncLock.Unlock()
}
for _, location := range lockedLocations {
location.volumesLock.Unlock()
@@ -1217,6 +1220,7 @@ func (s *Store) deleteVolumeGuarded(i needle.VolumeId, onlyEmpty bool, onlyGarba
for _, location := range s.Locations {
location.volumesLock.Lock()
if v, ok := location.volumes[i]; ok {
v.dataFileSyncLock.Lock()
v.dataFileAccessLock.Lock()
lockedLocations = append(lockedLocations, location)
lockedVolumes = append(lockedVolumes, v)
+25 -7
View File
@@ -43,7 +43,12 @@ type Volume struct {
super_block.SuperBlock
dataFileAccessLock sync.RWMutex
dataFileAccessLock sync.RWMutex
// Serializes a data-file mutation with the sync that makes it durable:
// write, delete, lifecycle and compaction paths hold it for their whole
// critical section, while the fsync itself runs with dataFileAccessLock
// released so readers of this volume do not wait on it.
dataFileSyncLock sync.Mutex
superBlockAccessLock sync.Mutex
// The batch worker exists only once the volume takes a durable write. Most
@@ -129,6 +134,8 @@ func (v *Volume) FileName(ext string) (fileName string) {
// gone. A no-op when the index already lives in newIdxDir. A derived .ldb is
// not moved: the reload rebuilds it in newIdxDir from the .idx.
func (v *Volume) RelocateIndexTo(newIdxDir string) error {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
@@ -290,32 +297,41 @@ func (v *Volume) DiskType() types.DiskType {
}
func (v *Volume) SyncToDisk() {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
if v.nm != nil {
if err := v.nm.Sync(); err != nil {
// Flush with the access lock dropped so readers are not stalled by the
// fsync; writers and file swaps stay excluded by dataFileSyncLock.
nm, backend := v.nm, v.DataBackend
v.dataFileAccessLock.Unlock()
if nm != nil {
if err := nm.Sync(); err != nil {
glog.Warningf("Volume Close fail to sync volume idx %d", v.Id)
}
}
if v.DataBackend != nil {
if err := v.DataBackend.Sync(); err != nil {
if backend != nil {
if err := backend.Sync(); err != nil {
glog.Warningf("Volume Close fail to sync volume %d", v.Id)
}
}
v.dataFileAccessLock.Lock()
}
// Close cleanly shuts down this volume
func (v *Volume) Close() {
// Wait for any in-progress compaction to finish and claim the flag so no
// new compaction can start. This must happen BEFORE acquiring
// dataFileAccessLock to avoid deadlocking with CommitCompact which holds
// the flag while waiting for the lock.
// dataFileSyncLock and dataFileAccessLock to avoid deadlocking with
// CommitCompact which holds the flag while waiting for the locks.
for !v.isCompactionInProgress.CompareAndSwap(false, true) {
time.Sleep(521 * time.Millisecond)
glog.Warningf("Volume Close wait for compaction %d", v.Id)
}
defer v.isCompactionInProgress.Store(false)
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
@@ -331,6 +347,8 @@ func (v *Volume) Close() {
// stale-false flag would make doDeleteRequest skip the new .dat's tombstones and
// disable the phantom-.dat guard.
func (v *Volume) SwapDataBackend(newBackend backend.BackendStorageFile, hasRemoteFile bool) {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
v.swapDataBackendLocked(newBackend, hasRemoteFile)
+274 -1
View File
@@ -1,6 +1,7 @@
package storage
import (
"errors"
"fmt"
"io"
"os"
@@ -10,6 +11,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -143,7 +145,25 @@ func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) (lastAppendAtNs uin
return 0, fmt.Errorf("verifyIndexFileIntegrity %s failed: %v", indexFile.Name(), err)
}
if indexSize == 0 {
return 0, nil
if v.noWriteOrDelete || v.noWriteCanDelete {
return 0, nil
}
// An empty index can hide writes a crash stranded in the .dat: the
// writable index loader creates the .idx before the first needle
// append, so a crash after that append leaves a volume whose data
// nothing indexes — and every check below skips an empty index. The
// same repair runs from the first record past the superblock; a tail
// it cannot explain fails the check, since an unaccounted-for .dat
// must not load writable either.
if _, _, err = repairUnindexedDatTail(v, indexFile, 0, -1); err != nil {
return 0, fmt.Errorf("CheckVolumeDataIntegrity %s: repair unindexed .dat tail: %v", indexFile.Name(), err)
}
if indexSize, err = verifyIndexFileIntegrity(indexFile); err != nil {
return 0, fmt.Errorf("verifyIndexFileIntegrity %s after re-indexing failed: %v", indexFile.Name(), err)
}
if indexSize == 0 {
return 0, nil
}
}
// The deeper-than-tail structural check (every (offset + actual size)
// fits inside .dat) lives in volume.load(): it reads
@@ -166,6 +186,32 @@ func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) (lastAppendAtNs uin
return 0, nil
}
// A crash between appending a needle to the .dat and appending its entry to
// the .idx leaves a .dat tail no index entry covers. Re-index the complete
// needles in it and cut an incomplete remainder before the check below,
// which would otherwise load the volume read-only. Only a volume that is
// about to load writable is repaired; a read-only one is left as it is.
// A repair that fails for any other reason than an unexplained tail (a
// read, write, truncate or sync error) fails the check, so the volume
// loads read-only instead of writable on a repair that may not be on disk.
if !v.noWriteOrDelete && !v.noWriteCanDelete {
reindexed, _, err := repairUnindexedDatTail(v, indexFile, indexSize, tailEntryPos)
if err != nil {
if !errors.Is(err, errTailNotTorn) {
return 0, fmt.Errorf("CheckVolumeDataIntegrity %s: repair unindexed .dat tail: %v", indexFile.Name(), err)
}
glog.Warningf("volume %d: unindexed .dat tail not repaired: %v", v.Id, err)
}
if reindexed > 0 {
if indexSize, err = verifyIndexFileIntegrity(indexFile); err != nil {
return 0, fmt.Errorf("verifyIndexFileIntegrity %s after re-indexing failed: %v", indexFile.Name(), err)
}
if tailEntryPos, err = findDatTailEntryOffset(v, indexFile, indexSize); err != nil {
return 0, fmt.Errorf("CheckVolumeDataIntegrity %s: %v", indexFile.Name(), err)
}
}
}
if lastAppendAtNs, err = doCheckAndFixVolumeData(v, indexFile, tailEntryPos); err != nil {
return lastAppendAtNs, fmt.Errorf("CheckVolumeDataIntegrity %s failed: %v", indexFile.Name(), err)
}
@@ -219,6 +265,233 @@ func needleDiskEnd(offset types.Offset, size types.Size, version needle.Version)
return offset.ToActualOffset() + needle.GetActualSize(types.Size(size.Raw()), version)
}
// errTailNotTorn marks a .dat tail that is not the result of an interrupted
// append; the volume keeps loading read-only.
var errTailNotTorn = errors.New("not a torn tail")
// repairUnindexedDatTail re-indexes the complete needles a crash left past the
// last indexed needle of a local version 3 volume, cuts an incomplete
// remainder, and returns how many needles it indexed and how many bytes it cut.
//
// A write appends the needle to the .dat, then its entry to the .idx, then
// answers the client. A process killed between the first two steps leaves a
// needle, or part of one, past the end of the needle at the highest indexed
// offset; a crash after the very first append leaves it past an index with
// no entry at all, which tailEntryPos < 0 marks: the walk then starts at the
// first record past the superblock with no anchor needle and no append
// timestamp to compare against. After a power loss the order on disk is
// whatever the page cache
// flushed: a complete needle can survive whose .idx entry did not, although
// the client was answered. So a complete needle is never dropped: every
// complete needle in the tail (its header, body, checksum, timestamp and
// padding inside the file, its CRC valid, its append timestamp later than the
// needle before it) gets the .idx entry the volume server would have written,
// in .dat order; the .dat is synced first so the rows never become durable
// ahead of the records they name, and the .idx is synced after. A size 0
// record is indexed at size 0,
// the same live entry the write path publishes for a write with no data. A
// delete appends the identical record, so a recovered size 0 record can also
// be a delete whose key then reads back as an empty object rather than
// not-found -- the two cannot be told apart, and resurrecting an empty
// placeholder beats a wrong tombstone, which drops an acknowledged write's
// object entirely. Only what follows the last complete
// needle and is itself incomplete is cut: fewer bytes than a header, a record
// running past the end of the file, or a last record whose bytes are damaged
// (its CRC fails or its body does not parse); the .dat is synced after the
// cut. A record that cannot be read is not cut: a read error is returned and
// nothing is changed.
//
// Nothing is changed when the tail is anything else: the .idx entry at the
// highest offset does not describe the needle there (id, size, CRC), a record
// inside the tail is damaged while more data follows it, a header carries id 0
// or a negative size, append timestamps go backwards, the .dat is beyond what
// 4-byte offsets can address, the needle version is not 3, or the .idx size is
// not a whole number of entries. The integrity check that follows then marks
// the volume read-only exactly as before.
func repairUnindexedDatTail(v *Volume, indexFile *os.File, indexSize int64, tailEntryPos int64) (int, int64, error) {
version := v.Version()
if version != needle.Version3 || v.DataBackend == nil {
return 0, 0, nil
}
datSize, _, err := v.DataBackend.GetStat()
if err != nil {
return 0, 0, fmt.Errorf("stat %s: %v", v.FileName(".dat"), err)
}
if datSize <= int64(super_block.SuperBlockSize) || datSize > int64(types.MaxPossibleVolumeSize) {
// past MaxPossibleVolumeSize the .idx offsets wrap: an entry's offset
// does not name its needle's position on its own
return 0, 0, nil
}
var start int64
var lastAppendAtNs uint64
if tailEntryPos < 0 {
// The index holds no row at all, so no entry can anchor the walk:
// it starts at the first record past the superblock.
start = int64(v.SuperBlock.BlockSize())
} else {
entry, err := readIndexEntryAtOffset(indexFile, tailEntryPos)
if err != nil {
return 0, 0, fmt.Errorf("read index entry at %d: %v", tailEntryPos, err)
}
key, offset, size := idx.IdxFileEntry(entry)
if offset.IsZero() {
return 0, 0, nil
}
start = needleDiskEnd(offset, size, version)
if start >= datSize {
// the .dat ends at the last needle (clean), or the index references
// bytes the .dat does not have: not a torn tail, not ours to fix
return 0, 0, nil
}
// Anchor: the needle at the highest indexed offset must be the one its
// entry describes, whole and with a valid CRC.
onDiskSize := size
if size.IsDeleted() {
onDiskSize = 0
}
anchor, err := readTailNeedle(v.DataBackend, version, offset.ToActualOffset(), onDiskSize)
if err != nil {
return 0, 0, fmt.Errorf("last indexed needle %v at %d: %v: %w", key, offset.ToActualOffset(), err, errTailNotTorn)
}
if anchor.Id != key {
return 0, 0, fmt.Errorf("needle at %d is id %v, its index entry says id %v: %w", offset.ToActualOffset(), anchor.Id, key, errTailNotTorn)
}
lastAppendAtNs = anchor.AppendAtNs
}
if start >= datSize {
// no record past the superblock: nothing to index
return 0, 0, nil
}
// The backend rounds its size up to the needle alignment; the walk needs
// the bytes that are really there.
fileSize := datSize
if st, statErr := os.Stat(v.DataBackend.Name()); statErr == nil {
fileSize = st.Size()
}
entries, cutAt, err := walkUnindexedDatTail(v.DataBackend, version, start, fileSize, lastAppendAtNs)
if err != nil {
return 0, 0, err
}
reindexed := len(entries) / types.NeedleMapEntrySize
if reindexed > 0 {
// The new .idx rows must not become durable before the .dat records
// they name: a power loss between the two would leave the .idx
// pointing past the end of the .dat.
if err := v.DataBackend.Sync(); err != nil {
return 0, 0, fmt.Errorf("sync %s before re-indexing: %v", v.FileName(".dat"), err)
}
if err := appendIndexEntries(indexFile, entries, indexSize); err != nil {
return 0, 0, err
}
}
var cut int64
if cutAt < fileSize {
if err := v.DataBackend.Truncate(cutAt); err != nil {
return reindexed, 0, fmt.Errorf("truncate %s to %d: %v", v.FileName(".dat"), cutAt, err)
}
if err := v.DataBackend.Sync(); err != nil {
return reindexed, fileSize - cutAt, fmt.Errorf("sync %s after truncating to %d: %v", v.FileName(".dat"), cutAt, err)
}
cut = fileSize - cutAt
}
glog.Warningf("volume %d: repaired the unindexed tail of %s: re-indexed %d needle(s), cut %d bytes (%d -> %d bytes)",
v.Id, v.FileName(".dat"), reindexed, cut, fileSize, fileSize-cut)
return reindexed, cut, nil
}
// indexAppender is the part of the .idx file the repair writes through.
type indexAppender interface {
io.WriterAt
Truncate(size int64) error
Sync() error
Name() string
}
// appendIndexEntries writes entries at the end (at) of the .idx and syncs it.
// A failed write can leave part of the entries behind, which would make the
// next load reject the .idx as a partial entry; they are removed again.
func appendIndexEntries(indexFile indexAppender, entries []byte, at int64) error {
if _, err := indexFile.WriteAt(entries, at); err != nil {
if truncErr := indexFile.Truncate(at); truncErr != nil {
return fmt.Errorf("append %d bytes to %s: %v; truncate back to %d: %v", len(entries), indexFile.Name(), err, at, truncErr)
}
return fmt.Errorf("append %d bytes to %s: %v", len(entries), indexFile.Name(), err)
}
if err := indexFile.Sync(); err != nil {
return fmt.Errorf("sync %s: %v", indexFile.Name(), err)
}
return nil
}
// readTailNeedle reads and verifies the whole record of a needle of the given
// on-disk size at offset: header, body, CRC and timestamp.
func readTailNeedle(datFile backend.BackendStorageFile, version needle.Version, at int64, size types.Size) (*needle.Needle, error) {
blob, err := needle.ReadNeedleBlob(datFile, at, size, version)
if err != nil {
return nil, err
}
n := new(needle.Needle)
if err := n.ReadBytes(blob, at, size, version); err != nil {
return nil, err
}
if size > 0 && len(n.Data) == 0 {
// A needle with no data is written with size 0, so a record with a
// body whose data size reads 0 is damaged. The CRC covers only the
// data, and ReadBytes does not check it for empty data.
return nil, fmt.Errorf("needle %v at %d has size %d but no data: %w", n.Id, at, size, needle.ErrorCorrupted)
}
return n, nil
}
// walkUnindexedDatTail walks the needles from start to fileSize and returns
// the .idx entries of the complete ones, and the offset from which the rest is
// an incomplete last record (fileSize when there is none). It fails with
// errTailNotTorn when the tail is damaged in a way an interrupted append does
// not explain.
func walkUnindexedDatTail(datFile backend.BackendStorageFile, version needle.Version, start, fileSize int64, lastAppendAtNs uint64) ([]byte, int64, error) {
var entries []byte
at := start
for at < fileSize {
if fileSize-at < types.NeedleHeaderSize {
return entries, at, nil // a partial header
}
header, _, _, err := needle.ReadNeedleHeader(datFile, version, at)
if err != nil || header == nil {
return nil, 0, fmt.Errorf("read needle header at %d: %v", at, err)
}
if header.Id == 0 || header.Size < 0 {
return nil, 0, fmt.Errorf("record at %d has id %v size %d: %w", at, header.Id, header.Size, errTailNotTorn)
}
end := at + needle.GetActualSize(header.Size, version)
if end > fileSize {
return entries, at, nil // the last record runs past the end of the file
}
n, err := readTailNeedle(datFile, version, at, header.Size)
if err != nil {
if !errors.Is(err, needle.ErrorCorrupted) {
// a read error says nothing about the bytes: leave them
return nil, 0, fmt.Errorf("read record %v at %d: %w", header.Id, at, err)
}
if end == fileSize {
return entries, at, nil // the last record is damaged: it never completed
}
return nil, 0, fmt.Errorf("record %v at %d is damaged and %d bytes follow it: %v: %w", header.Id, at, fileSize-end, err, errTailNotTorn)
}
if n.AppendAtNs <= lastAppendAtNs {
return nil, 0, fmt.Errorf("record %v at %d was appended at %d, not after %d: %w", n.Id, at, n.AppendAtNs, lastAppendAtNs, errTailNotTorn)
}
lastAppendAtNs = n.AppendAtNs
// A size 0 record is a delete or an empty write; the two append the
// identical record, so it is indexed at size 0 the way the write path
// indexes an empty write.
entries = append(entries, needle_map.ToBytes(n.Id, types.ToOffset(at), header.Size)...)
at = end
}
return entries, fileSize, nil
}
func doCheckAndFixVolumeData(v *Volume, indexFile *os.File, indexOffset int64) (lastAppendAtNs uint64, err error) {
var lastIdxEntry []byte
if lastIdxEntry, err = readIndexEntryAtOffset(indexFile, indexOffset); err != nil {
@@ -0,0 +1,709 @@
package storage
import (
"bytes"
"errors"
"os"
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
// A torn tail is what a crash between the two appends of a write leaves: the
// needle is in the .dat, its entry never reached the .idx. After a process
// crash the client was never answered; after a power loss it may have been.
// These tests write needles (and deletes) normally, drop the last .idx
// entries, cut or damage the .dat as a crash would, and reload the volume
// through the real load path.
type tornOp struct {
id uint64
del bool
empty bool // a write with no data, which appends a size 0 record like a delete
}
type tornFixture struct {
dir string
datName string
idxName string
starts []int64 // .dat offset of each op's record
end int64 // .dat size after every op
written map[uint64]*needle.Needle
}
func newTornTailTestVolume(t *testing.T, dir string) *Volume {
t.Helper()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("load volume: %v", err)
}
return v
}
// buildTornFixture runs ops against a fresh volume (each op appends one .dat
// record and one .idx entry), closes it and drops the last unindexed entries.
func buildTornFixture(t *testing.T, ops []tornOp, unindexed int) *tornFixture {
t.Helper()
f := &tornFixture{dir: t.TempDir(), written: map[uint64]*needle.Needle{}}
v := newTornTailTestVolume(t, f.dir)
for _, op := range ops {
at, _, err := v.DataBackend.GetStat()
if err != nil {
t.Fatal(err)
}
f.starts = append(f.starts, at)
if op.del {
if _, err := v.doDeleteRequest(newEmptyNeedle(op.id)); err != nil {
t.Fatalf("delete needle %d: %v", op.id, err)
}
continue
}
n := newRandomNeedle(op.id)
if op.empty {
n = newEmptyNeedle(op.id)
}
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
t.Fatalf("write needle %d: %v", op.id, err)
}
f.written[op.id] = n
}
f.end, _, _ = v.DataBackend.GetStat()
f.datName, f.idxName = v.FileName(".dat"), v.FileName(".idx")
v.Close()
if unindexed > 0 {
if err := os.Truncate(f.idxName, fileSize(t, f.idxName)-int64(unindexed)*types.NeedleMapEntrySize); err != nil {
t.Fatalf("drop %d .idx entries: %v", unindexed, err)
}
}
return f
}
// midRecord is an offset inside the body of op i's record: past its header,
// short of its end. A fixed offset is not: a needle with a few bytes of data
// is a 40-byte record, which a cut at +40 leaves whole.
func (f *tornFixture) midRecord(i int) int64 {
end := f.end
if i+1 < len(f.starts) {
end = f.starts[i+1]
}
return midRecordBody(f.starts[i], end)
}
func midRecordBody(start, end int64) int64 {
return start + types.NeedleHeaderSize + (end-start-types.NeedleHeaderSize)/2
}
func (f *tornFixture) truncateDat(t *testing.T, size int64) {
t.Helper()
if err := os.Truncate(f.datName, size); err != nil {
t.Fatal(err)
}
}
// flipDataByte damages the data of the record at the given offset, so its
// CRC no longer matches.
func (f *tornFixture) flipDataByte(t *testing.T, at int64) {
t.Helper()
file, err := os.OpenFile(f.datName, os.O_RDWR, 0644)
if err != nil {
t.Fatal(err)
}
defer file.Close()
b := make([]byte, 1)
pos := at + types.NeedleHeaderSize + 4 // past the 4-byte DataSize field
if _, err := file.ReadAt(b, pos); err != nil {
t.Fatal(err)
}
b[0] ^= 0xff
if _, err := file.WriteAt(b, pos); err != nil {
t.Fatal(err)
}
}
// zeroDataSize zeroes the DataSize field and the first data byte (read as
// the flags once DataSize is 0) of the record at the given offset: the header
// still claims a body, the body parses as an empty needle.
func (f *tornFixture) zeroDataSize(t *testing.T, at int64) {
t.Helper()
file, err := os.OpenFile(f.datName, os.O_RDWR, 0644)
if err != nil {
t.Fatal(err)
}
defer file.Close()
if _, err := file.WriteAt(make([]byte, 5), at+types.NeedleHeaderSize); err != nil {
t.Fatal(err)
}
}
func assertReadable(t *testing.T, v *Volume, want *needle.Needle) {
t.Helper()
got := &needle.Needle{Id: want.Id}
if _, err := v.readNeedle(got, nil, nil); err != nil {
t.Fatalf("read needle %d: %v", want.Id, err)
}
if !bytes.Equal(got.Data, want.Data) {
t.Fatalf("needle %d reads back different data", want.Id)
}
}
func assertNotReadable(t *testing.T, v *Volume, id uint64) {
t.Helper()
if _, err := v.readNeedle(&needle.Needle{Id: types.Uint64ToNeedleId(id)}, nil, nil); err == nil {
t.Fatalf("needle %d reads back; it should be deleted or absent", id)
}
}
// A recovered size 0 record indexes as a live empty needle: a delete and a
// write with no data append the identical record, so the repair cannot tell
// them apart and indexes the entry the write path would have written.
func assertEmpty(t *testing.T, v *Volume, id uint64) {
t.Helper()
n := &needle.Needle{Id: types.Uint64ToNeedleId(id)}
if _, err := v.readNeedle(n, nil, nil); err != nil {
t.Fatalf("read needle %d: %v", id, err)
}
if len(n.Data) != 0 {
t.Fatalf("needle %d reads back %d bytes, want an empty needle", id, len(n.Data))
}
}
func writes(ids ...uint64) []tornOp {
ops := make([]tornOp, len(ids))
for i, id := range ids {
ops[i] = tornOp{id: id}
}
return ops
}
func TestVolumeLoadRepairsUnindexedDatTail(t *testing.T) {
cases := []struct {
name string
ops []tornOp
unindexed int
damage func(t *testing.T, f *tornFixture)
wantSize func(f *tornFixture) int64 // .dat size after the repair
reindexed int
readable []uint64
empty []uint64 // readable as an empty live needle
absent []uint64
}{
{name: "one complete unindexed needle is re-indexed",
ops: writes(1, 2, 3, 4), unindexed: 1,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
readable: []uint64{1, 2, 3, 4}},
{name: "two complete unindexed needles are re-indexed",
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 2,
readable: []uint64{1, 2, 3, 4, 5}},
{name: "an unindexed delete is re-indexed as an empty live needle",
ops: append(writes(1, 2, 3), tornOp{id: 2, del: true}), unindexed: 1,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
readable: []uint64{1, 3}, empty: []uint64{2}},
{name: "an unindexed empty write of a live id stays an empty needle",
ops: append(writes(1, 2, 3), tornOp{id: 2, empty: true}), unindexed: 1,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
readable: []uint64{1, 3}, empty: []uint64{2}},
{name: "a partial header is cut",
ops: writes(1, 2, 3, 4), unindexed: 1,
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.starts[3]+7) },
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
{name: "a partial body is cut",
ops: writes(1, 2, 3, 4), unindexed: 1,
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(3)) },
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
{name: "a complete needle is re-indexed and the partial one after it cut",
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(4)) },
wantSize: func(f *tornFixture) int64 { return f.starts[4] }, reindexed: 1,
readable: []uint64{1, 2, 3, 4}, absent: []uint64{5}},
{name: "a last needle with a bad CRC is cut",
ops: writes(1, 2, 3, 4), unindexed: 1,
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[3]) },
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
{name: "a last needle whose data size field reads 0 is cut",
ops: writes(1, 2, 3, 4), unindexed: 1,
damage: func(t *testing.T, f *tornFixture) { f.zeroDataSize(t, f.starts[3]) },
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
{name: "an unindexed empty write of a new id stays an empty needle",
ops: append(writes(1, 2), tornOp{id: 3, empty: true}), unindexed: 1,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
readable: []uint64{1, 2, 3}},
{name: "an unindexed empty write after a delete of the same id stays an empty needle",
ops: append(append(writes(1, 2), tornOp{id: 2, del: true}), tornOp{id: 2, empty: true}), unindexed: 1,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
readable: []uint64{1, 2}},
{name: "an unindexed write and delete of the same id are re-indexed in order",
ops: append(writes(1, 2, 3), tornOp{id: 3, del: true}), unindexed: 2,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 2,
readable: []uint64{1, 2}, empty: []uint64{3}},
{name: "an unindexed empty write and its delete are re-indexed in order",
ops: append(writes(1, 2), tornOp{id: 3, empty: true}, tornOp{id: 3, del: true}), unindexed: 2,
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 2,
readable: []uint64{1, 2}, empty: []uint64{3}},
{name: "a partial needle after an indexed tombstone is cut",
ops: append(append(writes(1, 2, 3), tornOp{id: 2, del: true}), tornOp{id: 4}), unindexed: 1,
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(4)) },
wantSize: func(f *tornFixture) int64 { return f.starts[4] },
readable: []uint64{1, 3}, absent: []uint64{2, 4}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := buildTornFixture(t, tc.ops, tc.unindexed)
if tc.damage != nil {
tc.damage(t, f)
}
idxBefore := fileSize(t, f.idxName)
v := newTornTailTestVolume(t, f.dir)
defer v.Close()
if v.noWriteOrDelete || v.noWriteCanDelete {
t.Fatal("volume with an unindexed .dat tail loaded read-only")
}
if got, want := fileSize(t, f.datName), tc.wantSize(f); got != want {
t.Fatalf(".dat is %d bytes after load, want %d", got, want)
}
if got, want := fileSize(t, f.idxName), idxBefore+int64(tc.reindexed)*types.NeedleMapEntrySize; got != want {
t.Fatalf(".idx is %d bytes after load, want %d (%d entries re-indexed)", got, want, tc.reindexed)
}
for _, id := range tc.readable {
assertReadable(t, v, f.written[id])
}
for _, id := range tc.empty {
assertEmpty(t, v, id)
}
for _, id := range tc.absent {
assertNotReadable(t, v, id)
}
extra := newRandomNeedle(100)
if _, _, _, err := v.writeNeedle2(extra, true, false, false); err != nil {
t.Fatalf("write after repair: %v", err)
}
assertReadable(t, v, extra)
v.Close()
// the repaired volume reloads clean, and keeps what it indexed
v2 := newTornTailTestVolume(t, f.dir)
defer v2.Close()
if v2.noWriteOrDelete {
t.Fatal("repaired volume loaded read-only on the next load")
}
for _, id := range tc.readable {
assertReadable(t, v2, f.written[id])
}
assertReadable(t, v2, extra)
})
}
}
// An empty index can hide writes a crash stranded in the .dat: the writable
// index loader creates the .idx before the first needle append, so a crash
// after that append leaves a volume whose data nothing indexes. The same
// repair runs from the first record past the superblock.
func TestVolumeLoadRepairsTailPastEmptyIndex(t *testing.T) {
cases := []struct {
name string
ops []tornOp
damage func(t *testing.T, f *tornFixture)
wantSize func(f *tornFixture) int64 // .dat size after the repair
reindexed int
readable []uint64
empty []uint64
absent []uint64
}{
{name: "the only write is re-indexed",
ops: writes(7),
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
readable: []uint64{7}},
{name: "every write is re-indexed",
ops: writes(1, 2, 3),
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 3,
readable: []uint64{1, 2, 3}},
{name: "an unindexed delete is re-indexed as an empty live needle",
ops: append(writes(1, 2, 3), tornOp{id: 2, del: true}),
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 4,
readable: []uint64{1, 3}, empty: []uint64{2}},
{name: "a complete needle is re-indexed and the partial one after it cut",
ops: writes(1, 2),
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(1)) },
wantSize: func(f *tornFixture) int64 { return f.starts[1] }, reindexed: 1,
readable: []uint64{1}, absent: []uint64{2}},
{name: "a last needle with a bad CRC is cut",
ops: writes(1, 2),
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[1]) },
wantSize: func(f *tornFixture) int64 { return f.starts[1] }, reindexed: 1,
readable: []uint64{1}, absent: []uint64{2}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := buildTornFixture(t, tc.ops, len(tc.ops))
if tc.damage != nil {
tc.damage(t, f)
}
v := newTornTailTestVolume(t, f.dir)
defer v.Close()
if v.noWriteOrDelete || v.noWriteCanDelete {
t.Fatal("volume with an unindexed .dat tail loaded read-only")
}
if got, want := fileSize(t, f.datName), tc.wantSize(f); got != want {
t.Fatalf(".dat is %d bytes after load, want %d", got, want)
}
if got, want := fileSize(t, f.idxName), int64(tc.reindexed)*types.NeedleMapEntrySize; got != want {
t.Fatalf(".idx is %d bytes after load, want %d (%d entries re-indexed)", got, want, tc.reindexed)
}
for _, id := range tc.readable {
assertReadable(t, v, f.written[id])
}
for _, id := range tc.empty {
assertEmpty(t, v, id)
}
for _, id := range tc.absent {
assertNotReadable(t, v, id)
}
v.Close()
// the repaired volume reloads clean, and keeps what it indexed
v2 := newTornTailTestVolume(t, f.dir)
defer v2.Close()
if v2.noWriteOrDelete {
t.Fatal("repaired volume loaded read-only on the next load")
}
for _, id := range tc.readable {
assertReadable(t, v2, f.written[id])
}
for _, id := range tc.empty {
assertEmpty(t, v2, id)
}
})
}
}
// An .dat an interrupted append does not explain, over an index with no rows
// at all, loads the volume read-only: the checks that would quarantine it
// otherwise all skip an empty index.
func TestVolumeLoadKeepsUnexplainedTailPastEmptyIndexReadOnly(t *testing.T) {
cases := []struct {
name string
damage func(t *testing.T, f *tornFixture)
}{
{name: "zero bytes where the first record would be (id 0)",
damage: func(t *testing.T, f *tornFixture) {
file, err := os.OpenFile(f.datName, os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
t.Fatal(err)
}
defer file.Close()
if _, err := file.Write(make([]byte, 64)); err != nil {
t.Fatal(err)
}
}},
{name: "a damaged record more data follows",
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[0]) }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := buildTornFixture(t, writes(1, 2), 2)
tc.damage(t, f)
datBefore, idxBefore := fileSize(t, f.datName), fileSize(t, f.idxName)
v := newTornTailTestVolume(t, f.dir)
defer v.Close()
if !v.noWriteOrDelete {
t.Fatal("volume with an unexplained tail past an empty index loaded writable")
}
if got := fileSize(t, f.datName); got != datBefore {
t.Fatalf(".dat changed from %d to %d bytes", datBefore, got)
}
if got := fileSize(t, f.idxName); got != idxBefore {
t.Fatalf(".idx changed from %d to %d bytes", idxBefore, got)
}
})
}
}
// Every tail an interrupted append does not explain is left exactly as it is,
// and the volume loads read-only as before.
func TestVolumeLoadKeepsUnexplainedTailReadOnly(t *testing.T) {
cases := []struct {
name string
ops []tornOp
unindexed int
damage func(t *testing.T, f *tornFixture)
}{
{name: "the last indexed needle's id differs from its entry",
ops: writes(1, 2, 3, 4), unindexed: 1,
damage: func(t *testing.T, f *tornFixture) {
file, err := os.OpenFile(f.datName, os.O_RDWR, 0644)
if err != nil {
t.Fatal(err)
}
defer file.Close()
if _, err := file.WriteAt([]byte{0xff}, f.starts[2]+types.CookieSize+types.NeedleIdSize-1); err != nil {
t.Fatal(err)
}
}},
{name: "the last indexed needle fails its CRC",
ops: writes(1, 2, 3, 4), unindexed: 1,
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[2]) }},
{name: "a zeroed data size field followed by more data",
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
damage: func(t *testing.T, f *tornFixture) { f.zeroDataSize(t, f.starts[3]) }},
{name: "a bad CRC followed by more data",
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[3]) }},
{name: "zero bytes past the last needle (id 0)",
ops: writes(1, 2, 3),
damage: func(t *testing.T, f *tornFixture) {
file, err := os.OpenFile(f.datName, os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
t.Fatal(err)
}
defer file.Close()
if _, err := file.Write(make([]byte, 64)); err != nil {
t.Fatal(err)
}
}},
{name: "the index ends past the data",
ops: writes(1, 2, 3),
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.end-10) }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := buildTornFixture(t, tc.ops, tc.unindexed)
tc.damage(t, f)
datBefore, idxBefore := fileSize(t, f.datName), fileSize(t, f.idxName)
v := newTornTailTestVolume(t, f.dir)
defer v.Close()
if !v.noWriteOrDelete {
t.Fatal("volume with an unexplained tail loaded writable")
}
if got := fileSize(t, f.datName); got != datBefore {
t.Fatalf(".dat changed from %d to %d bytes", datBefore, got)
}
if got := fileSize(t, f.idxName); got != idxBefore {
t.Fatalf(".idx changed from %d to %d bytes", idxBefore, got)
}
})
}
}
func TestVolumeLoadLeavesCleanVolumeUntouched(t *testing.T) {
f := buildTornFixture(t, append(writes(1, 2, 3), tornOp{id: 2, del: true}), 0)
datBefore, idxBefore := fileSize(t, f.datName), fileSize(t, f.idxName)
v := newTornTailTestVolume(t, f.dir)
defer v.Close()
if v.noWriteOrDelete || v.noWriteCanDelete {
t.Fatal("clean volume loaded read-only")
}
if got := fileSize(t, f.datName); got != datBefore {
t.Fatalf("clean .dat changed from %d to %d bytes", datBefore, got)
}
if got := fileSize(t, f.idxName); got != idxBefore {
t.Fatalf("clean .idx changed from %d to %d bytes", idxBefore, got)
}
assertReadable(t, v, f.written[1])
assertReadable(t, v, f.written[3])
assertNotReadable(t, v, 2)
}
// A volume persisted read-only is not repaired: the tail stays for whoever
// marked it.
func TestVolumeLoadLeavesReadOnlyVolumeTailAlone(t *testing.T) {
dir := t.TempDir()
v := newTornTailTestVolume(t, dir)
for _, id := range []uint64{1, 2, 99} {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
t.Fatal(err)
}
}
if err := v.PersistReadOnly(true, false); err != nil {
t.Fatal(err)
}
datName, idxName := v.FileName(".dat"), v.FileName(".idx")
v.Close()
if err := os.Truncate(idxName, fileSize(t, idxName)-types.NeedleMapEntrySize); err != nil {
t.Fatal(err)
}
datBefore, idxBefore := fileSize(t, datName), fileSize(t, idxName)
v = newTornTailTestVolume(t, dir)
defer v.Close()
if !v.noWriteOrDelete {
t.Fatal("volume persisted read-only loaded writable")
}
if got := fileSize(t, datName); got != datBefore {
t.Fatalf(".dat of a read-only volume changed from %d to %d bytes", datBefore, got)
}
if got := fileSize(t, idxName); got != idxBefore {
t.Fatalf(".idx of a read-only volume changed from %d to %d bytes", idxBefore, got)
}
}
// An .idx that ends in a partial entry keeps the existing behaviour:
// the volume does not load writable and neither file is changed.
func TestVolumeLoadLeavesPartialIdxEntryAlone(t *testing.T) {
f := buildTornFixture(t, writes(1, 2, 3), 0)
idxPartial := fileSize(t, f.idxName) - types.NeedleMapEntrySize/2
if err := os.Truncate(f.idxName, idxPartial); err != nil {
t.Fatal(err)
}
datBefore := fileSize(t, f.datName)
v2, err := NewVolume(f.dir, f.dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err == nil {
t.Logf("partial .idx: volume loaded, noWriteOrDelete=%v", v2.noWriteOrDelete)
if !v2.noWriteOrDelete {
v2.Close()
t.Fatal("volume with a partial .idx entry loaded writable")
}
v2.Close()
} else {
t.Logf("partial .idx: volume not loaded: %v", err)
}
if got := fileSize(t, f.datName); got != datBefore {
t.Fatalf(".dat changed from %d to %d bytes", datBefore, got)
}
if got := fileSize(t, f.idxName); got != idxPartial {
t.Fatalf(".idx changed from %d to %d bytes", idxPartial, got)
}
}
// faultyDatFile fails Sync, or the read of a whole record at one offset, the
// way a failing disk does.
type faultyDatFile struct {
backend.BackendStorageFile
failSync bool
failRecordAt int64
failRecordSet bool
}
var errFaultyDisk = errors.New("input/output error")
func (f *faultyDatFile) Sync() error {
if f.failSync {
return errFaultyDisk
}
return f.BackendStorageFile.Sync()
}
func (f *faultyDatFile) ReadAt(p []byte, off int64) (int, error) {
if f.failRecordSet && off == f.failRecordAt && len(p) > types.NeedleHeaderSize {
return 0, errFaultyDisk
}
return f.BackendStorageFile.ReadAt(p, off)
}
// A read error is not evidence of a torn write: the last record is kept.
func TestWalkUnindexedDatTailKeepsRecordOnReadError(t *testing.T) {
f := buildTornFixture(t, writes(1, 2, 3, 4), 1)
file, err := os.Open(f.datName)
if err != nil {
t.Fatal(err)
}
dat := &faultyDatFile{BackendStorageFile: backend.NewDiskFile(file), failRecordAt: f.starts[3], failRecordSet: true}
defer dat.Close()
records, cutAt, err := walkUnindexedDatTail(dat, needle.Version3, f.starts[3], f.end, 0)
if err == nil {
t.Fatalf("read error on the last record: walk returned %d record(s) and a cut at %d, want an error", len(records), cutAt)
}
if errors.Is(err, errTailNotTorn) {
t.Fatalf("read error reported as an unexplained tail: %v", err)
}
if !errors.Is(err, errFaultyDisk) {
t.Fatalf("walk error %v does not carry the read error", err)
}
}
// A repair that changed a file but could not sync it fails the integrity
// check, so the volume loads read-only rather than writable on an unsynced
// repair.
func TestCheckVolumeDataIntegrityFailsOnUnsyncedRepair(t *testing.T) {
dir := t.TempDir()
v := newTornTailTestVolume(t, dir)
var starts []int64
for _, id := range []uint64{1, 2, 3, 4} {
at, _, _ := v.DataBackend.GetStat()
starts = append(starts, at)
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
t.Fatal(err)
}
}
end, _, _ := v.DataBackend.GetStat()
// persisted read-only so the load below does not repair the tail itself
if err := v.PersistReadOnly(true, false); err != nil {
t.Fatal(err)
}
datName, idxName := v.FileName(".dat"), v.FileName(".idx")
v.Close()
if err := os.Truncate(idxName, fileSize(t, idxName)-types.NeedleMapEntrySize); err != nil {
t.Fatal(err)
}
if err := os.Truncate(datName, midRecordBody(starts[3], end)); err != nil {
t.Fatal(err)
}
v = newTornTailTestVolume(t, dir)
defer v.Close()
v.noWriteOrDelete = false
v.DataBackend = &faultyDatFile{BackendStorageFile: v.DataBackend, failSync: true}
indexFile, err := os.OpenFile(idxName, os.O_RDWR, 0644)
if err != nil {
t.Fatal(err)
}
defer indexFile.Close()
if _, err := CheckVolumeDataIntegrity(v, indexFile); err == nil {
t.Fatal("integrity check passed although the repaired .dat was not synced")
}
}
// partialWriteIndex accepts only the first n bytes of a write, as a full disk
// does.
type partialWriteIndex struct {
data []byte
accept int
truncated bool
}
func (p *partialWriteIndex) WriteAt(b []byte, off int64) (int, error) {
n := min(len(b), p.accept)
if end := int(off) + n; end > len(p.data) {
p.data = append(p.data, make([]byte, end-len(p.data))...)
}
copy(p.data[off:], b[:n])
if n < len(b) {
return n, errors.New("no space left on device")
}
return n, nil
}
func (p *partialWriteIndex) Truncate(size int64) error {
p.data = p.data[:size]
p.truncated = true
return nil
}
func (p *partialWriteIndex) Sync() error { return nil }
func (p *partialWriteIndex) Name() string { return "test.idx" }
// A failed append leaves no partial entry behind.
func TestAppendIndexEntriesRemovesPartialWrite(t *testing.T) {
idxFile := &partialWriteIndex{data: make([]byte, 2*types.NeedleMapEntrySize), accept: types.NeedleMapEntrySize + 5}
entries := make([]byte, 2*types.NeedleMapEntrySize)
if err := appendIndexEntries(idxFile, entries, 2*types.NeedleMapEntrySize); err == nil {
t.Fatal("a partial append reported success")
}
if got, want := len(idxFile.data), 2*types.NeedleMapEntrySize; got != want {
t.Fatalf(".idx is %d bytes after a failed append, want %d", got, want)
}
}
+12
View File
@@ -427,9 +427,21 @@ func TestCheckVolumeDataIntegrityVerifiesDeletionTail(t *testing.T) {
}
defer idxFile.Close()
// A read-only volume keeps its tail: the check must report it.
v.noWriteOrDelete = true
if _, err := CheckVolumeDataIntegrity(v, idxFile); err == nil {
t.Fatal("CheckVolumeDataIntegrity should detect bytes past a deletion-tombstone tail")
}
// A writable volume would have a torn needle re-indexed or cut, but 64 zero
// bytes are no needle (id 0): they are reported and left in place.
v.noWriteOrDelete = false
if _, err := CheckVolumeDataIntegrity(v, idxFile); err == nil {
t.Fatal("CheckVolumeDataIntegrity should detect zero bytes past a deletion-tombstone tail on a writable volume")
}
if got, _, _ := v.DataBackend.GetStat(); got != datSize+64 {
t.Fatalf(".dat is %d bytes after the check, want %d (nothing cut)", got, datSize+64)
}
}
// TestVolumeLoadStaysWritableWithKeySortedIndex exercises end to
+2
View File
@@ -63,6 +63,8 @@ func loadVolumeWithoutWorker(dirname string, dirIdx string, collection string, i
//
// No-op when v.nm is already a writable form.
func (v *Volume) reopenIdxForWrite() error {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
return v.reopenIdxForWriteLocked()
+2
View File
@@ -80,6 +80,8 @@ func (v *Volume) HasRemoteFile() bool {
// backend concurrently. load() must instead use loadRemoteFileLocked, since it
// can be reached with the lock already held (CommitCompact).
func (v *Volume) LoadRemoteFile() error {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
return v.loadRemoteFileLocked()
+4
View File
@@ -177,6 +177,8 @@ func (v *Volume) CommitCompact() error {
}
defer v.isCompactionInProgress.Store(false)
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
@@ -367,6 +369,8 @@ func (v *Volume) cleanupCompact() error {
// Serialize with CommitCompact's swap and refuse to unlink .cpd/.cpx while a
// .cpc marker exists: those temp files are the only inputs reconcile can roll
// forward to, so removing them mid-commit would strand a decided swap.
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
if util.FileExists(v.FileName(".cpc")) {
+195 -205
View File
@@ -16,101 +16,6 @@ var ErrorNotFound = errors.New("not found")
var ErrorDeleted = errors.New("already deleted")
var ErrorSizeMismatch = errors.New("size mismatch")
type batchNeedleSnapshot struct {
id NeedleId
found bool
offset Offset
size Size
changed bool
}
func newBatchNeedleSnapshot(v *Volume, id NeedleId) *batchNeedleSnapshot {
snapshot := &batchNeedleSnapshot{id: id}
if element, found := v.nm.Get(id); found && element != nil {
snapshot.found = true
snapshot.offset = element.Offset
snapshot.size = element.Size
}
return snapshot
}
func (s *batchNeedleSnapshot) observeCurrent(v *Volume) {
element, found := v.nm.Get(s.id)
if found != s.found {
s.changed = true
return
}
if found && (element == nil || element.Offset != s.offset || element.Size != s.size) {
s.changed = true
}
}
func (v *Volume) restoreBatchNeedle(snapshot *batchNeedleSnapshot) error {
mapRollbacker, ok := v.nm.(batchMapRollbacker)
if !ok {
return fmt.Errorf("mapper %T cannot restore its mappings", v.nm)
}
if snapshot.found {
return mapRollbacker.restoreMapping(snapshot.id, snapshot.offset, snapshot.size)
}
// A plain Delete would leave a tombstoned entry whose stale offset makes
// the next write to this needle fail reading a header that no longer exists.
return mapRollbacker.removeMapping(snapshot.id)
}
func (v *Volume) rollbackBatch(end int64, indexEnd int64, snapshots []*batchNeedleSnapshot,
metricRollbacker batchMetricRollbacker, metrics batchMapMetricSnapshot) error {
var recoveryErrors []error
for _, snapshot := range snapshots {
if !snapshot.changed {
continue
}
if err := v.restoreBatchNeedle(snapshot); err != nil {
recoveryErrors = append(recoveryErrors,
fmt.Errorf("restore needle %d: %w", snapshot.id, err))
}
}
if len(recoveryErrors) == 0 {
rollbacker, ok := v.nm.(batchIndexRollbacker)
if !ok {
recoveryErrors = append(recoveryErrors,
fmt.Errorf("mapper %T cannot truncate its index", v.nm))
} else if err := rollbacker.truncateIndex(indexEnd); err != nil {
recoveryErrors = append(recoveryErrors,
fmt.Errorf("truncate index to %d: %w", indexEnd, err))
}
}
if len(recoveryErrors) == 0 {
if err := v.nm.Sync(); err != nil {
recoveryErrors = append(recoveryErrors,
fmt.Errorf("sync recovered index: %w", err))
}
}
if len(recoveryErrors) == 0 {
if err := v.DataBackend.Truncate(end); err != nil {
recoveryErrors = append(recoveryErrors,
fmt.Errorf("truncate %s to %d: %w", v.DataBackend.Name(), end, err))
} else if err := v.DataBackend.Sync(); err != nil {
recoveryErrors = append(recoveryErrors,
fmt.Errorf("sync truncated %s: %w", v.DataBackend.Name(), err))
}
}
if len(recoveryErrors) == 0 {
if metricRollbacker == nil {
recoveryErrors = append(recoveryErrors,
fmt.Errorf("mapper %T cannot restore its metrics", v.nm))
} else {
metricRollbacker.restoreBatchMetrics(metrics)
}
}
return errors.Join(recoveryErrors...)
}
// isFileUnchanged checks whether this needle to write is same as last one.
// It requires serialized access in the same volume.
func (v *Volume) isFileUnchanged(n *needle.Needle) bool {
@@ -140,6 +45,8 @@ var ErrVolumeNotEmpty = fmt.Errorf("volume not empty")
// true the cloud-tier object backing the volume is left intact — used by
// moves where another server is taking over the same .vif.
func (v *Volume) Destroy(onlyEmpty bool, onlyGarbage bool, keepRemoteData bool) (err error) {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
return v.destroyLocked(onlyEmpty, onlyGarbage, keepRemoteData)
@@ -264,6 +171,8 @@ func (v *Volume) asyncRequestAppend(request *needle.AsyncRequest) bool {
func (v *Volume) syncWrite(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
// glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
@@ -288,65 +197,47 @@ func (v *Volume) syncWrite(n *needle.Needle, checkCookie bool, fsync bool) (offs
if statErr != nil {
return 0, 0, false, fmt.Errorf("cannot read current volume position: %v", statErr)
}
priorOffset, priorSize, hasPrior := Offset{}, Size(0), false
if nv, found := v.nm.Get(n.Id); found {
priorOffset, priorSize, hasPrior = nv.Offset, nv.Size, true
}
offset, size, isUnchanged, err = v.doWriteRequest(n, checkCookie, fsync)
lastAppendAtNs := v.lastAppendAtNs
lastWriteAppendAtNs := v.lastWriteAppendAtNs
lastWriteNeedleKey := v.lastWriteNeedleKey
lastWriteDeleted := v.lastWriteDeleted
lastModifiedTsSeconds := v.lastModifiedTsSeconds
offset, size, isUnchanged, err = v.appendWriteRequest(n, checkCookie, fsync)
if err != nil {
return
}
if syncErr := v.DataBackend.Sync(); syncErr != nil {
// fsync with the access lock dropped so same-volume reads do not wait on
// it; writers and compaction stay excluded by dataFileSyncLock. Nothing
// has been published yet, so no reader can capture the appended offset.
backend := v.DataBackend
v.dataFileAccessLock.Unlock()
syncErr := backend.Sync()
v.dataFileAccessLock.Lock()
if syncErr != nil {
v.checkReadWriteError(syncErr)
v.lastAppendAtNs = lastAppendAtNs
v.lastWriteAppendAtNs = lastWriteAppendAtNs
v.lastWriteNeedleKey = lastWriteNeedleKey
v.lastWriteDeleted = lastWriteDeleted
v.lastModifiedTsSeconds = lastModifiedTsSeconds
if !isUnchanged {
v.rollbackUnflushedWrite(n, offset, end, priorOffset, priorSize, hasPrior)
// Nothing was published, so the whole rollback is taking the
// unflushed append back off the .dat.
if te := v.DataBackend.Truncate(end); te != nil {
v.markIoUnavailable(fmt.Errorf("truncate %s back to %d after a failed fsync: %w",
v.DataBackend.Name(), end, te))
}
}
return 0, 0, false, syncErr
}
if !isUnchanged {
err = v.publishWriteRequest(n, offset, fsync)
}
return
}
// rollbackUnflushedWrite undoes an append whose fsync failed: the bytes are not
// data we can vouch for, so they come back off the .dat and the needle map goes
// back to what it pointed at before, rather than at an offset past the new end.
func (v *Volume) rollbackUnflushedWrite(n *needle.Needle, offset uint64, end int64, priorOffset Offset, priorSize Size, hasPrior bool) {
var recoveryErr error
if te := v.DataBackend.Truncate(end); te != nil {
recoveryErr = fmt.Errorf("truncate %s back to %d: %w", v.DataBackend.Name(), end, te)
}
current, found := v.nm.Get(n.Id)
if found && current.Offset.ToActualOffset() == int64(offset) {
var err error
if hasPrior {
err = v.nm.Put(n.Id, priorOffset, priorSize)
} else {
// The tombstone must reach .idx so a replay forgets the needle, but
// the negated entry it leaves in memory points at truncated bytes
// and would fail the next write, so erase the mapping as well.
err = v.nm.Delete(n.Id, ToOffset(int64(offset)))
if err == nil {
if rb, ok := v.nm.(batchMapRollbacker); ok {
err = rb.removeMapping(n.Id)
} else {
err = fmt.Errorf("mapper %T cannot remove mapping", v.nm)
}
}
}
if err == nil && n.Id == v.lastWriteNeedleKey {
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
v.lastWriteDeleted = true
}
if err != nil {
recoveryErr = errors.Join(recoveryErr,
fmt.Errorf("roll back the index of needle %d in volume %d: %w", n.Id, v.Id, err))
}
}
if recoveryErr != nil {
v.markIoUnavailable(recoveryErr)
}
}
// writeNeedle2 appends a needle. A durable write normally goes through the
// async batch worker, which fsyncs once for the whole batch; while the server
// is stopping the worker is winding down, so it is flushed inline instead. Both
@@ -379,6 +270,17 @@ func (v *Volume) writeNeedle2(n *needle.Needle, checkCookie bool, fsync bool, is
}
func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
offset, size, isUnchanged, err = v.appendWriteRequest(n, checkCookie, fsync)
if err != nil || isUnchanged {
return
}
err = v.publishWriteRequest(n, offset, fsync)
return
}
// appendWriteRequest is doWriteRequest through the .dat append, leaving the
// needle-map update to publishWriteRequest.
func (v *Volume) appendWriteRequest(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
// glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
// Re-check under the write lock: the outer checks run before the needle
// is assembled, and VolumeMarkReadonly can land in between.
@@ -426,7 +328,16 @@ func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool, fsync bool)
v.lastWriteNeedleKey = n.Id
v.lastWriteDeleted = false
// add to needle map
return
}
// publishWriteRequest indexes an already-appended needle. It is split from
// appendWriteRequest so a durable write can fsync before the mapping exists:
// an index entry that outlives the bytes it points at loads read-only, and
// an unpublished offset can never be captured by an in-flight read before a
// failed sync truncates it.
func (v *Volume) publishWriteRequest(n *needle.Needle, offset uint64, fsync bool) (err error) {
nv, ok := v.nm.Get(n.Id)
if !ok || uint64(nv.Offset.ToActualOffset()) < offset {
if err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {
err = fmt.Errorf("index needle %d of volume %d at offset %d: %w", n.Id, v.Id, offset, err)
@@ -449,6 +360,8 @@ func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool, fsync bool)
func (v *Volume) syncDelete(n *needle.Needle) (Size, error) {
// glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
@@ -487,37 +400,81 @@ func (v *Volume) deleteNeedle2(n *needle.Needle) (Size, error) {
func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
nv, ok := v.nm.Get(n.Id)
// fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
if ok && !nv.Size.IsDeleted() {
var offset uint64
var err error
size := nv.Size
if !v.HasRemoteFile() {
n.Data = nil
n.UpdateAppendAtNs(v.lastAppendAtNs)
offset, _, _, err = n.Append(v.DataBackend, v.Version())
v.checkReadWriteError(err)
if err != nil {
return size, err
}
}
v.lastAppendAtNs = n.AppendAtNs
if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
return size, err
}
if n.Id == v.lastWriteNeedleKey {
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
v.lastWriteDeleted = true
}
size, offset, tombstoned, err := v.appendDeleteRequest(n)
if err != nil || !tombstoned {
return size, err
}
return 0, nil
if err = v.publishDeleteRequest(n, offset); err != nil {
return size, err
}
return size, nil
}
// appendDeleteRequest writes the tombstone record but leaves the map update
// to publishDeleteRequest, so a batch can fsync before any deletion is
// visible — same publication-after-sync ordering as writes.
func (v *Volume) appendDeleteRequest(n *needle.Needle) (size Size, offset uint64, tombstoned bool, err error) {
nv, ok := v.nm.Get(n.Id)
// fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
if !ok || nv.Size.IsDeleted() {
return 0, 0, false, nil
}
size = nv.Size
if !v.HasRemoteFile() {
n.Data = nil
n.UpdateAppendAtNs(v.lastAppendAtNs)
offset, _, _, err = n.Append(v.DataBackend, v.Version())
v.checkReadWriteError(err)
if err != nil {
return size, 0, false, err
}
}
v.lastAppendAtNs = n.AppendAtNs
return size, offset, true, nil
}
func (v *Volume) publishDeleteRequest(n *needle.Needle, offset uint64) error {
if err := v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
return err
}
if n.Id == v.lastWriteNeedleKey {
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
v.lastWriteDeleted = true
}
return nil
}
func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
// The batch is applied in runs of distinct needle ids: a repeated id
// starts a new run so its dedup, cookie and delete checks see the earlier
// operation's published result — the same rule as Rust's
// write_needles_grouped.
seen := make(map[NeedleId]bool, len(currentRequests))
start := 0
for i := 0; i < len(currentRequests); i++ {
if seen[currentRequests[i].N.Id] {
v.processBatchRun(currentRequests[start:i])
seen = make(map[NeedleId]bool, len(currentRequests)-i)
start = i
}
seen[currentRequests[i].N.Id] = true
}
if start < len(currentRequests) {
v.processBatchRun(currentRequests[start:])
}
}
// processBatchRun applies one run of distinct-id requests: every .dat
// mutation is staged, the run is synced once with the access lock dropped,
// and only then are the map changes published — in request order, and only
// over an older offset — so a failed sync rolls back bytes no reader ever
// resolved. A durable entry that fails to index stops the volume taking
// writes, and the entries after it in the run are refused read only.
func (v *Volume) processBatchRun(run []*needle.AsyncRequest) {
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
end, e := int64(0), error(nil)
if unavailableErr := v.UnavailableError(); unavailableErr != nil {
@@ -528,62 +485,65 @@ func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
end, _, e = v.DataBackend.GetStat()
}
if e != nil {
for i := 0; i < len(currentRequests); i++ {
currentRequests[i].Complete(0, 0, false,
v.dataFileAccessLock.Unlock()
for i := 0; i < len(run); i++ {
run[i].Complete(0, 0, false,
fmt.Errorf("cannot read current volume position: %v", e))
}
return
}
batchSnapshots := make(map[NeedleId]*batchNeedleSnapshot, len(currentRequests))
orderedSnapshots := make([]*batchNeedleSnapshot, 0, len(currentRequests))
metricRollbacker, _ := v.nm.(batchMetricRollbacker)
var batchMetrics batchMapMetricSnapshot
if metricRollbacker != nil {
batchMetrics = metricRollbacker.snapshotBatchMetrics()
}
indexEnd := int64(v.nm.IndexFileSize())
batchLastAppendAtNs := v.lastAppendAtNs
batchLastWriteAppendAtNs := v.lastWriteAppendAtNs
batchLastWriteNeedleKey := v.lastWriteNeedleKey
batchLastWriteDeleted := v.lastWriteDeleted
batchLastModifiedTsSeconds := v.lastModifiedTsSeconds
for i := 0; i < len(currentRequests); i++ {
needleID := currentRequests[i].N.Id
snapshot, found := batchSnapshots[needleID]
if !found {
snapshot = newBatchNeedleSnapshot(v, needleID)
batchSnapshots[needleID] = snapshot
orderedSnapshots = append(orderedSnapshots, snapshot)
}
stagedWriteOffsets := make([]uint64, len(run))
stagedWriteOk := make([]bool, len(run))
stagedDeleteOffsets := make([]uint64, len(run))
stagedDeleteOk := make([]bool, len(run))
for i := 0; i < len(run); i++ {
// Every queued request meets the same refusal it would get sent on
// its own: once a durable index update fails the volume stops taking
// writes, and a lone write is turned away before it appends.
if currentRequests[i].IsWriteRequest {
if run[i].IsWriteRequest {
if unavailableErr := v.UnavailableError(); unavailableErr != nil {
currentRequests[i].UpdateResult(0, 0, false, unavailableErr)
run[i].UpdateResult(0, 0, false, unavailableErr)
} else if v.IsReadOnly() {
currentRequests[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
run[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
} else {
offset, size, isUnchanged, err := v.doWriteRequest(currentRequests[i].N, true, true)
currentRequests[i].UpdateResult(offset, uint64(size), isUnchanged, err)
offset, size, isUnchanged, err := v.appendWriteRequest(run[i].N, true, true)
if err == nil && !isUnchanged {
stagedWriteOffsets[i] = offset
stagedWriteOk[i] = true
}
run[i].UpdateResult(offset, uint64(size), isUnchanged, err)
}
} else {
if unavailableErr := v.UnavailableError(); unavailableErr != nil {
currentRequests[i].UpdateResult(0, 0, false, unavailableErr)
run[i].UpdateResult(0, 0, false, unavailableErr)
} else if _, noWriteOrDelete, _, _ := v.ReadOnlyReasons(); noWriteOrDelete {
currentRequests[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
run[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
} else {
size, err := v.doDeleteRequest(currentRequests[i].N)
currentRequests[i].UpdateResult(0, uint64(size), false, err)
size, offset, tombstoned, err := v.appendDeleteRequest(run[i].N)
if err == nil && tombstoned {
stagedDeleteOffsets[i] = offset
stagedDeleteOk[i] = true
}
run[i].UpdateResult(0, uint64(size), false, err)
}
}
snapshot.observeCurrent(v)
}
// if sync error the batch is not durable; restore it before another
// operation observes the volume
if syncErr := v.DataBackend.Sync(); syncErr != nil {
// The sync excludes writers and compaction via dataFileSyncLock but not
// readers: nothing is published yet, so dropping the access lock here
// lets same-volume reads proceed during the fsync.
backend := v.DataBackend
v.dataFileAccessLock.Unlock()
syncErr := backend.Sync()
v.dataFileAccessLock.Lock()
if syncErr != nil {
v.checkReadWriteError(syncErr)
v.lastAppendAtNs = batchLastAppendAtNs
v.lastWriteAppendAtNs = batchLastWriteAppendAtNs
@@ -591,17 +551,45 @@ func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
v.lastWriteDeleted = batchLastWriteDeleted
v.lastModifiedTsSeconds = batchLastModifiedTsSeconds
batchErr := syncErr
if recoveryErr := v.rollbackBatch(end, indexEnd, orderedSnapshots, metricRollbacker, batchMetrics); recoveryErr != nil {
batchErr = errors.Join(syncErr, recoveryErr)
// Nothing was published: truncating the run's bytes is the whole
// rollback, and no reader ever resolved them.
if te := v.DataBackend.Truncate(end); te != nil {
batchErr = errors.Join(syncErr,
fmt.Errorf("truncate %s to %d: %w", v.DataBackend.Name(), end, te))
v.markIoUnavailable(batchErr)
}
for i := 0; i < len(currentRequests); i++ {
currentRequests[i].UpdateResult(0, 0, false, batchErr)
for i := 0; i < len(run); i++ {
run[i].UpdateResult(0, 0, false, batchErr)
}
v.dataFileAccessLock.Unlock()
for i := 0; i < len(run); i++ {
run[i].Submit()
}
return
}
for i := 0; i < len(currentRequests); i++ {
currentRequests[i].Submit()
refused := false
for i := 0; i < len(run); i++ {
if refused {
run[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
continue
}
if run[i].IsWriteRequest {
if stagedWriteOk[i] {
if perr := v.publishWriteRequest(run[i].N, stagedWriteOffsets[i], true); perr != nil {
run[i].UpdateResult(0, 0, false, perr)
refused = true
}
}
} else if stagedDeleteOk[i] {
if perr := v.publishDeleteRequest(run[i].N, stagedDeleteOffsets[i]); perr != nil {
run[i].UpdateResult(0, 0, false, perr)
}
}
}
v.dataFileAccessLock.Unlock()
for i := 0; i < len(run); i++ {
run[i].Submit()
}
}
@@ -673,6 +661,8 @@ func (v *Volume) stopWorker() {
func (v *Volume) WriteNeedleBlob(needleId NeedleId, needleBlob []byte, size Size) error {
v.dataFileSyncLock.Lock()
defer v.dataFileSyncLock.Unlock()
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
+9 -6
View File
@@ -446,23 +446,26 @@ func TestBatchFsyncRollbackRestoresOriginalValueAfterRepeatedNeedleId(t *testing
}
v.processBatch(requests)
for _, request := range requests {
_, _, _, err = request.WaitComplete()
require.Error(t, err)
}
// A repeated needle id starts a new batch run, so the second write syncs
// on its own: the first run rolls back to "original-value" and the second
// write lands as a normal sequential overwrite.
_, _, _, err = requests[0].WaitComplete()
require.Error(t, err)
_, _, _, err = requests[1].WaitComplete()
require.NoError(t, err)
readBack := new(needle.Needle)
readBack.Id = kept.Id
_, err = v.readNeedle(readBack, nil, nil)
require.NoError(t, err)
require.Equal(t, []byte("original-value"), readBack.Data)
require.Equal(t, []byte("second-failed-value"), readBack.Data)
reloaded := reopenCountingVolume(t, v)
readBack = new(needle.Needle)
readBack.Id = kept.Id
_, err = reloaded.readNeedle(readBack, nil, nil)
require.NoError(t, err)
require.Equal(t, []byte("original-value"), readBack.Data)
require.Equal(t, []byte("second-failed-value"), readBack.Data)
}
// Rolling back a first-time write must not leave a tombstoned map entry: the
+24 -40
View File
@@ -90,7 +90,6 @@ type Topology struct {
lastPersistedMaxVolumeId atomic.Uint32
lastPersistedTopologyId atomic.Value
lastPersistedGrowthFrozen atomic.Bool
volumeIdAllocator VolumeIdAllocator
growthFrozen atomic.Bool
growthFrozenAt atomic.Int64
@@ -472,22 +471,6 @@ func (t *Topology) NextVolumeId() (needle.VolumeId, error) {
return 0, fmt.Errorf("volume growth is frozen after master state loss; verify the cluster inventory, then run: volume.growth.resume")
}
}
if a := t.volumeIdAllocator; a != nil {
vid, err := a.NextVolumeId()
if err != nil {
return 0, err
}
if err := t.PersistMaxVolumeId(vid); err != nil {
return 0, fmt.Errorf("can not assign next volume id %d: %w", vid, err)
}
// Still record through raft so followers' boundaries and mirrors track
// allocations made against the external allocator.
if err := t.raftApply(NewMaxVolumeIdCommand(vid, t.GetTopologyId())); err != nil {
return 0, err
}
t.UpAdjustMaxVolumeId(vid)
return vid, nil
}
vid := t.GetMaxVolumeId()
next := vid.Next()
@@ -495,27 +478,23 @@ func (t *Topology) NextVolumeId() (needle.VolumeId, error) {
return 0, fmt.Errorf("persist max volume id %d: %w", next, err)
}
if err := t.raftApply(NewMaxVolumeIdCommand(next, t.GetTopologyId())); err != nil {
return 0, err
}
return next, nil
}
func (t *Topology) raftApply(cmd *MaxVolumeIdCommand) error {
t.RaftServerAccessLock.RLock()
defer t.RaftServerAccessLock.RUnlock()
if t.RaftServer != nil {
_, err := t.RaftServer.Do(cmd)
return err
}
if t.HashicorpRaft != nil {
b, err := json.Marshal(cmd)
if _, err := t.RaftServer.Do(NewMaxVolumeIdCommand(next, t.GetTopologyId())); err != nil {
return 0, err
}
} else if t.HashicorpRaft != nil {
b, err := json.Marshal(NewMaxVolumeIdCommand(next, t.GetTopologyId()))
if err != nil {
return fmt.Errorf("failed marshal %s: %+v", cmd.CommandName(), err)
return 0, fmt.Errorf("failed marshal NewMaxVolumeIdCommand: %+v", err)
}
if future := t.HashicorpRaft.Apply(b, time.Second); future.Error() != nil {
return 0, future.Error()
}
return t.HashicorpRaft.Apply(b, time.Second).Error()
}
return nil
return next, nil
}
// DefaultNeedleSizeEstimate is the fallback per-file-ID size estimate when
@@ -818,6 +797,7 @@ func ttlEqual(a, b *needle.TTL) bool {
return a.ToUint32() == b.ToUint32()
}
// findDuplicateVolumeLayouts reports every layout that already holds v.Id on
// data nodes other than dn. Volume ids are global, so the same id held by two
// nodes under two layouts means the allocator reused an id.
@@ -1222,10 +1202,6 @@ func (t *Topology) SetGrowthFreezeConfig(freezeOnMismatch bool, recoveryWait tim
t.stateLossRecoveryWait.Store(int64(recoveryWait))
}
func (t *Topology) SetVolumeIdAllocator(a VolumeIdAllocator) {
t.volumeIdAllocator = a
}
// CheckReportedTopologyId freezes growth when a volume server reports a
// topology id different from this cluster's: the topology id survives raft
// state cleanup, so a mismatch means the master's state was rebuilt (or a
@@ -1306,13 +1282,21 @@ func (t *Topology) SetGrowthFrozen(frozen bool) {
func (t *Topology) applyGrowthFreeze(frozen bool) {
cmd := NewMaxVolumeIdCommand(t.GetMaxVolumeId(), t.GetTopologyId())
cmd.GrowthFrozen = &frozen
if t.RaftServer != nil || t.HashicorpRaft != nil {
if err := t.raftApply(cmd); err != nil {
t.RaftServerAccessLock.RLock()
defer t.RaftServerAccessLock.RUnlock()
if t.RaftServer != nil {
if _, err := t.RaftServer.Do(cmd); err != nil {
glog.Warningf("apply growth freeze %v: %v", frozen, err)
}
return
} else if t.HashicorpRaft != nil {
if b, err := json.Marshal(cmd); err != nil {
glog.Warningf("marshal growth freeze %v: %v", frozen, err)
} else if future := t.HashicorpRaft.Apply(b, time.Second); future.Error() != nil {
glog.Warningf("apply growth freeze %v: %v", frozen, future.Error())
}
} else {
t.SetGrowthFrozen(frozen)
}
t.SetGrowthFrozen(frozen)
}
// SetTopologyInitPending gates allocation while a topology id is being
-96
View File
@@ -1,96 +0,0 @@
package topology
import (
"context"
"fmt"
"math"
"strconv"
"strings"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
// VolumeIdAllocator hands out the next volume id. The builtin path advances
// the raft-applied high-water mark; an external implementation makes the
// boundary survive total master state loss.
type VolumeIdAllocator interface {
NextVolumeId() (needle.VolumeId, error)
}
// EtcdVolumeIdAllocator keeps the volume id counter in a single etcd key,
// advanced by compare-and-swap. Unlike the raft/mirror/echo layers it has no
// residual window: an id cannot be issued without the etcd write committing.
type EtcdVolumeIdAllocator struct {
kv clientv3.KV
client *clientv3.Client
key string
timeout time.Duration
seed func() needle.VolumeId
}
func NewEtcdVolumeIdAllocator(client *clientv3.Client, keyPrefix string, timeout time.Duration, seed func() needle.VolumeId) *EtcdVolumeIdAllocator {
a := newEtcdVolumeIdAllocator(client.KV, keyPrefix, timeout, seed)
a.client = client
return a
}
func newEtcdVolumeIdAllocator(kv clientv3.KV, keyPrefix string, timeout time.Duration, seed func() needle.VolumeId) *EtcdVolumeIdAllocator {
return &EtcdVolumeIdAllocator{
kv: kv,
key: strings.TrimRight(keyPrefix, "/") + "/max_volume_id",
timeout: timeout,
seed: seed,
}
}
func (a *EtcdVolumeIdAllocator) Close() error {
if a.client == nil {
return nil
}
return a.client.Close()
}
func (a *EtcdVolumeIdAllocator) NextVolumeId() (needle.VolumeId, error) {
ctx, cancel := context.WithTimeout(context.Background(), a.timeout)
defer cancel()
for {
resp, err := a.kv.Get(ctx, a.key)
if err != nil {
return 0, fmt.Errorf("volume id allocator read: %w", err)
}
var cur uint64
cmp := clientv3.Compare(clientv3.CreateRevision(a.key), "=", 0)
if len(resp.Kvs) > 0 {
if cur, err = strconv.ParseUint(string(resp.Kvs[0].Value), 10, 32); err != nil {
return 0, fmt.Errorf("volume id counter %q: %w", resp.Kvs[0].Value, err)
}
cmp = clientv3.Compare(clientv3.ModRevision(a.key), "=", resp.Kvs[0].ModRevision)
}
// A stale etcd counter (restored backup, re-enabled allocator) must
// never go below the bound this master already knows. Resampled per
// attempt because a heartbeat can raise it while the CAS retries.
if seedBound := uint64(a.seed()); seedBound > cur {
cur = seedBound
}
if cur >= math.MaxUint32 {
return 0, fmt.Errorf("volume id counter exhausted at %d", cur)
}
committed, err := a.kv.Txn(ctx).If(cmp).Then(clientv3.OpPut(a.key, strconv.FormatUint(cur+1, 10))).Commit()
if err != nil {
return 0, fmt.Errorf("volume id allocator commit: %w", err)
}
if !committed.Succeeded {
continue
}
// The bound may have moved past the committed id while the CAS was in
// flight. That id could name an existing volume, so skip it; wasting a
// number is safe, reusing one is not.
if latest := uint64(a.seed()); latest > cur {
continue
}
return needle.VolumeId(cur + 1), nil
}
}
-288
View File
@@ -1,288 +0,0 @@
package topology
import (
"context"
"errors"
"math"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"go.etcd.io/etcd/api/v3/etcdserverpb"
mvccpb "go.etcd.io/etcd/api/v3/mvccpb"
clientv3 "go.etcd.io/etcd/client/v3"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
// fakeEtcdKV is an in-memory clientv3.KV honoring CreateRevision/ModRevision
// compare-and-swap, enough to exercise the allocator's CAS loop.
type fakeEtcdKV struct {
mu sync.Mutex
rev int64
data map[string]*mvccpb.KeyValue
// beforeCmp runs inside Commit before the compares are evaluated, to
// model a competing writer landing between the read and the CAS.
beforeCmp func()
getErr error
commitErr error
}
func newFakeEtcdKV() *fakeEtcdKV {
return &fakeEtcdKV{data: make(map[string]*mvccpb.KeyValue)}
}
func (kv *fakeEtcdKV) Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) {
kv.mu.Lock()
defer kv.mu.Unlock()
if kv.getErr != nil {
return nil, kv.getErr
}
if v, ok := kv.data[key]; ok {
cp := *v
return &clientv3.GetResponse{Kvs: []*mvccpb.KeyValue{&cp}}, nil
}
return &clientv3.GetResponse{}, nil
}
func (kv *fakeEtcdKV) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) {
kv.mu.Lock()
defer kv.mu.Unlock()
kv.applyPut(key, val)
return &clientv3.PutResponse{}, nil
}
func (kv *fakeEtcdKV) applyPut(key, val string) {
kv.rev++
if v, ok := kv.data[key]; ok {
v.Value = []byte(val)
v.ModRevision = kv.rev
} else {
kv.data[key] = &mvccpb.KeyValue{Key: []byte(key), Value: []byte(val), CreateRevision: kv.rev, ModRevision: kv.rev}
}
}
func (kv *fakeEtcdKV) GetStream(ctx context.Context, key string, opts ...clientv3.OpOption) (clientv3.GetStreamChan, error) {
return nil, nil
}
func (kv *fakeEtcdKV) Delete(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.DeleteResponse, error) {
kv.mu.Lock()
defer kv.mu.Unlock()
delete(kv.data, key)
return &clientv3.DeleteResponse{}, nil
}
func (kv *fakeEtcdKV) Compact(ctx context.Context, rev int64, opts ...clientv3.CompactOption) (*clientv3.CompactResponse, error) {
return &clientv3.CompactResponse{}, nil
}
func (kv *fakeEtcdKV) Do(ctx context.Context, op clientv3.Op) (clientv3.OpResponse, error) {
return clientv3.OpResponse{}, nil
}
func (kv *fakeEtcdKV) Txn(ctx context.Context) clientv3.Txn {
return &fakeEtcdTxn{kv: kv}
}
type fakeEtcdTxn struct {
kv *fakeEtcdKV
cmps []clientv3.Cmp
ops []clientv3.Op
}
func (t *fakeEtcdTxn) If(cs ...clientv3.Cmp) clientv3.Txn {
t.cmps = append(t.cmps, cs...)
return t
}
func (t *fakeEtcdTxn) Then(ops ...clientv3.Op) clientv3.Txn {
t.ops = append(t.ops, ops...)
return t
}
func (t *fakeEtcdTxn) Else(ops ...clientv3.Op) clientv3.Txn {
return t
}
func (t *fakeEtcdTxn) Commit() (*clientv3.TxnResponse, error) {
t.kv.mu.Lock()
defer t.kv.mu.Unlock()
if t.kv.beforeCmp != nil {
t.kv.beforeCmp()
}
for _, cmp := range t.cmps {
if !t.kv.evalCmp(cmp) {
return &clientv3.TxnResponse{Succeeded: false}, nil
}
}
for _, op := range t.ops {
if op.IsPut() {
t.kv.applyPut(string(op.KeyBytes()), string(op.ValueBytes()))
}
}
if t.kv.commitErr != nil {
return nil, t.kv.commitErr
}
return &clientv3.TxnResponse{Succeeded: true}, nil
}
func (kv *fakeEtcdKV) evalCmp(cmp clientv3.Cmp) bool {
c := cmp.GetCompare()
if c.Result != etcdserverpb.Compare_EQUAL {
return false
}
existing := kv.data[string(c.Key)]
switch u := c.TargetUnion.(type) {
case *etcdserverpb.Compare_CreateRevision:
var rev int64
if existing != nil {
rev = existing.CreateRevision
}
return rev == u.CreateRevision
case *etcdserverpb.Compare_ModRevision:
var rev int64
if existing != nil {
rev = existing.ModRevision
}
return rev == u.ModRevision
}
return false
}
func TestEtcdAllocatorSeedsFromLocalBound(t *testing.T) {
alloc := newEtcdVolumeIdAllocator(newFakeEtcdKV(), "/sw/", time.Second, func() needle.VolumeId {
return 41
})
for i, want := range []needle.VolumeId{42, 43, 44} {
got, err := alloc.NextVolumeId()
if err != nil {
t.Fatalf("alloc %d: %v", i, err)
}
if got != want {
t.Fatalf("alloc %d = %d, want %d", i, got, want)
}
}
}
func TestEtcdAllocatorNeverBelowLocalBound(t *testing.T) {
kv := newFakeEtcdKV()
kv.Put(context.Background(), "seaweedfs/max_volume_id", "10")
alloc := newEtcdVolumeIdAllocator(kv, "seaweedfs", time.Second, func() needle.VolumeId {
return 41
})
got, err := alloc.NextVolumeId()
if err != nil {
t.Fatalf("alloc: %v", err)
}
if got != 42 {
t.Fatalf("a stale stored counter must not reissue ids: got %d", got)
}
}
func TestEtcdAllocatorResumesFromStoredKey(t *testing.T) {
kv := newFakeEtcdKV()
kv.Put(context.Background(), "seaweedfs/max_volume_id", "100")
alloc := newEtcdVolumeIdAllocator(kv, "seaweedfs", time.Second, func() needle.VolumeId {
return 41
})
got, err := alloc.NextVolumeId()
if err != nil {
t.Fatalf("alloc: %v", err)
}
if got != 101 {
t.Fatalf("stored counter wins over the seed: got %d", got)
}
}
func TestEtcdAllocatorRetriesOnCasConflict(t *testing.T) {
kv := newFakeEtcdKV()
// a competing writer lands the key once, between the read and the CAS
kv.beforeCmp = func() {
kv.applyPut("seaweedfs/max_volume_id", "55")
kv.beforeCmp = nil
}
alloc := newEtcdVolumeIdAllocator(kv, "seaweedfs", time.Second, func() needle.VolumeId {
return 5
})
got, err := alloc.NextVolumeId()
if err != nil {
t.Fatalf("alloc: %v", err)
}
if got != 56 {
t.Fatalf("CAS retry should allocate 56, got %d", got)
}
}
func TestEtcdAllocatorSkipsIdBelowFreshBound(t *testing.T) {
kv := newFakeEtcdKV()
var bound atomic.Uint32
bound.Store(5)
// a heartbeat raises the local bound while the CAS is in flight; the
// committed 6 must not be handed out
kv.beforeCmp = func() {
bound.Store(43)
kv.beforeCmp = nil
}
alloc := newEtcdVolumeIdAllocator(kv, "seaweedfs", time.Second, func() needle.VolumeId {
return needle.VolumeId(bound.Load())
})
got, err := alloc.NextVolumeId()
if err != nil {
t.Fatalf("alloc: %v", err)
}
if got != 44 {
t.Fatalf("an id at or below the fresher bound must be skipped, got %d", got)
}
}
func TestEtcdAllocatorReadError(t *testing.T) {
kv := newFakeEtcdKV()
kv.getErr = errors.New("etcd read failed")
alloc := newEtcdVolumeIdAllocator(kv, "seaweedfs", time.Second, func() needle.VolumeId {
return 41
})
if _, err := alloc.NextVolumeId(); err == nil {
t.Fatal("a failed read must return an error, not an id")
}
kv.getErr = nil
got, err := alloc.NextVolumeId()
if err != nil {
t.Fatalf("alloc: %v", err)
}
if got != 42 {
t.Fatalf("got %d, want 42", got)
}
}
func TestEtcdAllocatorCommitError(t *testing.T) {
kv := newFakeEtcdKV()
kv.commitErr = errors.New("etcd commit failed")
alloc := newEtcdVolumeIdAllocator(kv, "seaweedfs", time.Second, func() needle.VolumeId {
return 41
})
if _, err := alloc.NextVolumeId(); err == nil {
t.Fatal("a failed commit must return an error, not an id")
}
kv.commitErr = nil
got, err := alloc.NextVolumeId()
if err != nil {
t.Fatalf("alloc: %v", err)
}
if got != 43 {
t.Fatalf("the id written by the failed commit must be skipped, got %d", got)
}
}
func TestEtcdAllocatorExhaustion(t *testing.T) {
kv := newFakeEtcdKV()
kv.Put(context.Background(), "seaweedfs/max_volume_id", strconv.FormatUint(math.MaxUint32, 10))
alloc := newEtcdVolumeIdAllocator(kv, "seaweedfs", time.Second, func() needle.VolumeId {
return 5
})
if _, err := alloc.NextVolumeId(); err == nil {
t.Fatal("expected exhaustion error at MaxUint32")
}
}
+180 -17
View File
@@ -962,7 +962,7 @@ func readEqualityDeleteFile(
reader := parquet.NewReader(bytes.NewReader(data))
defer reader.Close()
colIndices, err := resolveEqualityColIndices(reader.Schema(), fieldIDs, icebergSchema)
colIndices, err := resolveEqualityColIndices(reader.Schema(), fieldIDs, icebergSchema, false)
if err != nil {
return nil, fmt.Errorf("resolve columns in %s: %w", filePath, err)
}
@@ -993,24 +993,37 @@ func readEqualityDeleteFile(
// buildEqualityKey builds a composite string key from specific column values
// in a row. Each value is serialized as "kind:length:value" to avoid ambiguity
// between types (e.g., int 123 vs string "123") and to prevent collisions from
// values containing separator characters.
// values containing separator characters. A negative column index is a field
// the file lacks: the value there is null.
func buildEqualityKey(row parquet.Row, colIndices []int) string {
if len(colIndices) == 1 {
v := row[colIndices[0]]
v := equalityKeyValue(row, colIndices[0])
s := v.String()
return fmt.Sprintf("%d:%d:%s", v.Kind(), len(s), s)
}
var b strings.Builder
for _, idx := range colIndices {
v := row[idx]
v := equalityKeyValue(row, idx)
s := v.String()
fmt.Fprintf(&b, "%d:%d:%s", v.Kind(), len(s), s)
}
return b.String()
}
func equalityKeyValue(row parquet.Row, idx int) parquet.Value {
if idx < 0 {
return parquet.NullValue()
}
return row[idx]
}
// resolveEqualityColIndices maps Iceberg field IDs to Parquet column indices.
func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, icebergSchema *iceberg.Schema) ([]int, error) {
// A file carrying field ids resolves by id, so a column renamed since the
// file was written still matches; one without ids falls back to the Iceberg
// name. allowMissing reads a column the file lacks as null (-1 marks it in
// the key): for data files only — an equality-delete file always carries
// its equality columns, so a missing one stays an error there.
func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, icebergSchema *iceberg.Schema, allowMissing bool) ([]int, error) {
if len(fieldIDs) == 0 {
return nil, nil
}
@@ -1019,6 +1032,14 @@ func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, iceberg
for i, col := range pqSchema.Columns() {
colNameToIdx[strings.Join(col, ".")] = i
}
idToIdx := make(map[int]int)
for _, f := range pqSchema.Fields() {
if f.Leaf() && f.ID() > 0 {
if idx, ok := colNameToIdx[f.Name()]; ok {
idToIdx[f.ID()] = idx
}
}
}
indices := make([]int, len(fieldIDs))
for i, fid := range fieldIDs {
@@ -1026,8 +1047,17 @@ func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, iceberg
if !ok {
return nil, fmt.Errorf("field ID %d not found in iceberg schema", fid)
}
idx, ok := colNameToIdx[field.Name]
idx, ok := idToIdx[fid]
if !ok && len(idToIdx) == 0 {
idx, ok = colNameToIdx[field.Name]
}
if !ok {
// An optional column added to the table after this file was
// written reads as null there (-1 marks it in the key).
if allowMissing && !field.Required {
indices[i] = -1
continue
}
return nil, fmt.Errorf("column %q (field ID %d) not found in parquet schema", field.Name, fid)
}
indices[i] = idx
@@ -1089,6 +1119,86 @@ func mergeParquetFiles(
icebergSchema *iceberg.Schema,
rowGroupRows int64,
lineage bool,
) ([]byte, int64, error) {
// On a v1/v2 table the writer's schema is chosen before any row is
// written: the union of the bin's file schemas by field id, so a bin of
// progressively wider files merges in one pass instead of restarting
// (and rewriting every earlier file) on each wider one. The v3 merge
// keeps the first file's columns plus the lineage columns.
var target *parquet.Schema
if !lineage {
var err error
if target, err = binWriterSchema(ctx, filerClient, bucketName, dataPath, entries); err != nil {
return nil, 0, err
}
}
for attempt := 0; ; attempt++ {
out, rows, err := mergeParquetFilesInto(ctx, filerClient, bucketName, dataPath, entries, positionDeletes,
eqDeleteGroups, icebergSchema, rowGroupRows, lineage, target)
var wider *widerSchemaError
if errors.As(err, &wider) && attempt < len(entries) {
target = wider.schema
continue
}
return out, rows, err
}
}
// binWriterSchema is the writer schema for a v1/v2 bin-pack merge: the union
// of the files' schemas by field id. Only each file's footer is read to learn
// its schema; the merge then downloads each file once. Files whose schemas
// cannot union (no field ids, nested or repeated columns, a field id or name
// carrying different types) merge only under the old rule — every file's
// schema equal to the first — and the bin is refused as before otherwise.
func binWriterSchema(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath string,
entries []iceberg.ManifestEntry,
) (*parquet.Schema, error) {
var union schemaUnion
var first *parquet.Schema
unionable, allEqual := true, true
for _, entry := range entries {
source := entry.DataFile().FilePath()
schema, err := parquetSchemaByIcebergPath(ctx, filerClient, bucketName, dataPath, source)
if err != nil {
return nil, fmt.Errorf("schema of %s: %w", source, err)
}
if schema == nil {
return nil, fmt.Errorf("no parquet schema found in %s", source)
}
if first == nil {
first = schema
} else if !schemasEqual(first, schema) {
allEqual = false
}
if unionable {
unionable = union.fold(schema, source) == nil
}
if !unionable && !allEqual {
return nil, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", source)
}
}
if !unionable || first == nil {
return nil, nil // every file spells the first file's schema
}
return union.schema(first.Name(), first), nil
}
// mergeParquetFilesInto merges with target as the writer's schema on a v1/v2
// table (nil: the first file's).
func mergeParquetFilesInto(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath string,
entries []iceberg.ManifestEntry,
positionDeletes map[string][]int64,
eqDeleteGroups []equalityDeleteGroup,
icebergSchema *iceberg.Schema,
rowGroupRows int64,
lineage bool,
target *parquet.Schema,
) ([]byte, int64, error) {
if len(entries) == 0 {
return nil, 0, fmt.Errorf("no entries to merge")
@@ -1122,6 +1232,30 @@ func mergeParquetFiles(
return nil, 0, fmt.Errorf("schema of %s: %w", entries[0].DataFile().FilePath(), err)
}
outputSchema = layout.schema
} else if target != nil {
outputSchema = target
}
// joins is how one file enters the merge on a v1/v2 table: converted into
// the writer's schema when that covers it, with its equality-delete
// columns resolved on its own schema.
joins := func(reader *parquet.Reader, entry iceberg.ManifestEntry) (parquet.Conversion, []resolvedEqDeleteGroup, error) {
if layout != nil {
return nil, resolvedEqGroups, nil // a v3 merge matches files with their lineage columns set aside
}
source := entry.DataFile().FilePath()
conv, err := evolvedFileConversion(outputSchema, reader.Schema(), source)
if err != nil {
return nil, nil, err
}
if schemasEqual(parquetSchema, reader.Schema()) {
return conv, resolvedEqGroups, nil
}
groups, err := resolveEqualityDeleteGroupsForSchema(reader.Schema(), eqDeleteGroups, icebergSchema)
if err != nil {
return nil, nil, fmt.Errorf("resolve equality columns in %s: %w", source, err)
}
return conv, groups, nil
}
var outputBuf bytes.Buffer
@@ -1129,7 +1263,17 @@ func mergeParquetFiles(
drainReader := func(reader *parquet.Reader, entry iceberg.ManifestEntry) (int64, error) {
source := entry.DataFile().FilePath()
return copyFileRows(ctx, reader, entry, layout, bucketName, dataPath, positionDeletes, resolvedEqGroups, eqDeleteGroups, icebergSchema, func(filtered []parquet.Row) error {
conv, groups, err := joins(reader, entry)
if err != nil {
reader.Close()
return 0, err
}
return copyFileRows(ctx, reader, entry, layout, bucketName, dataPath, positionDeletes, groups, eqDeleteGroups, icebergSchema, func(filtered []parquet.Row) error {
if conv != nil {
if _, err := conv.Convert(filtered); err != nil {
return fmt.Errorf("convert rows from %s: %w", source, err)
}
}
if _, err := writer.WriteRows(filtered); err != nil {
return fmt.Errorf("write rows from %s: %w", source, err)
}
@@ -1161,13 +1305,6 @@ func mergeParquetFiles(
}
reader := parquet.NewReader(bytes.NewReader(data))
// A v3 merge matches files with their lineage columns set aside.
if layout == nil && !schemasEqual(parquetSchema, reader.Schema()) {
reader.Close()
writer.Close()
return nil, 0, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", entry.DataFile().FilePath())
}
rowsWritten, err := drainReader(reader, entry)
if err != nil {
writer.Close()
@@ -1200,7 +1337,7 @@ func resolveEqualityDeleteGroupsForSchema(
resolved := make([]resolvedEqDeleteGroup, 0, len(eqDeleteGroups))
for _, g := range eqDeleteGroups {
indices, err := resolveEqualityColIndices(parquetSchema, g.FieldIDs, icebergSchema)
indices, err := resolveEqualityColIndices(parquetSchema, g.FieldIDs, icebergSchema, true)
if err != nil {
return nil, err
}
@@ -1429,7 +1566,8 @@ func compactRandomSuffix() string {
return hex.EncodeToString(b)
}
// schemasEqual compares two parquet schemas structurally.
// schemasEqual compares two parquet schemas structurally, and their Iceberg
// field ids wherever both carry them.
func schemasEqual(a, b *parquet.Schema) bool {
if a == b {
return true
@@ -1437,7 +1575,32 @@ func schemasEqual(a, b *parquet.Schema) bool {
if a == nil || b == nil {
return false
}
return parquet.EqualNodes(a, b)
return parquet.EqualNodes(a, b) && fieldIDsAgree(a, b)
}
// fieldIDsAgree reports whether two structurally equal nodes carry the same
// Iceberg field id at every position where both carry one. parquet-go's
// EqualNodes ignores field ids, so a column dropped and re-added under the
// same name and type (a new field id) looked like the old one, and a merge
// filed the old values under the new field, or the live values under the
// dropped one.
func fieldIDsAgree(a, b parquet.Node) bool {
if a.ID() > 0 && b.ID() > 0 && a.ID() != b.ID() {
return false
}
if a.Leaf() || b.Leaf() {
return a.Leaf() == b.Leaf()
}
fa, fb := a.Fields(), b.Fields()
if len(fa) != len(fb) {
return false
}
for i := range fa {
if fa[i].Name() != fb[i].Name() || !fieldIDsAgree(fa[i], fb[i]) {
return false
}
}
return true
}
// ensureFilerDir ensures a directory exists in the filer.
@@ -0,0 +1,644 @@
package iceberg
import (
"bytes"
"context"
"io"
"strings"
"testing"
"github.com/apache/iceberg-go"
"github.com/parquet-go/parquet-go"
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// Files of one Iceberg table may spell its schema differently in Parquet:
// a column added by schema evolution, or the same schema written REQUIRED
// by one engine and OPTIONAL by another (PyIceberg writes REQUIRED, DuckDB
// OPTIONAL). The bin-pack merge joins such files by Iceberg field id,
// reading a column a file lacks as null, and refuses files whose same-name
// columns carry different field ids (a column dropped and re-added).
type narrowSchemaRow struct { // id REQUIRED id=1, name OPTIONAL id=2
ID int64 `parquet:"id,id(1)"`
Name string `parquet:"name,id(2),optional"`
}
type wideSchemaRow struct { // plus extra OPTIONAL id=3
ID int64 `parquet:"id,id(1)"`
Name string `parquet:"name,id(2),optional"`
Extra string `parquet:"extra,id(3),optional"`
}
type reorderedSchemaRow struct { // the wide schema's columns in another order
Extra string `parquet:"extra,id(3),optional"`
ID int64 `parquet:"id,id(1)"`
Name string `parquet:"name,id(2),optional"`
}
type optionalIDSchemaRow struct { // id OPTIONAL id=1
ID int64 `parquet:"id,id(1),optional"`
Name string `parquet:"name,id(2),optional"`
}
type readdedNameSchemaRow struct { // name re-added under field id 3
ID int64 `parquet:"id,id(1)"`
Name string `parquet:"name,id(3),optional"`
}
type nullableExtraSchemaRow struct { // the wide schema, extra writable as null
ID int64 `parquet:"id,id(1)"`
Name string `parquet:"name,id(2),optional"`
Extra *string `parquet:"extra,id(3),optional"`
}
func newAddedColumnSchema() *iceberg.Schema { // newTestSchema plus extra id=3
return iceberg.NewSchema(0,
iceberg.NestedField{ID: 1, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true},
iceberg.NestedField{ID: 2, Type: iceberg.PrimitiveTypes.String, Name: "name", Required: false},
iceberg.NestedField{ID: 3, Type: iceberg.PrimitiveTypes.String, Name: "extra", Required: false},
)
}
func schemaFileEntry(t *testing.T, path string, recordCount int64) iceberg.ManifestEntry {
t.Helper()
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData,
path, iceberg.ParquetFile, map[int]any{}, nil, nil, recordCount, 1024)
if err != nil {
t.Fatalf("build data file: %v", err)
}
snapID := int64(1)
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())
}
func mergeNamedFiles(t *testing.T, client filer_pb.SeaweedFilerClient, names []string, counts map[string]int64,
eqGroups []equalityDeleteGroup, schema *iceberg.Schema, lineage bool) ([]byte, int64, error) {
t.Helper()
var entries []iceberg.ManifestEntry
for _, name := range names {
entries = append(entries, schemaFileEntry(t, "data/"+name, counts[name]))
}
return mergeParquetFiles(context.Background(), client, "test-bucket", "ns/tbl",
entries, nil, eqGroups, schema, 0, lineage)
}
// mergedValues returns the merged file's schema and each row's leaf values
// in column order (nil for nulls).
func mergedValues(t *testing.T, data []byte) (*parquet.Schema, [][]any) {
t.Helper()
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("open merged: %v", err)
}
var out [][]any
for _, rg := range f.RowGroups() {
rows := rg.Rows()
buf := make([]parquet.Row, 16)
for {
n, err := rows.ReadRows(buf)
for _, r := range buf[:n] {
vals := make([]any, len(r))
for i, v := range r {
if v.IsNull() {
continue
}
if v.Kind() == parquet.Int64 {
vals[i] = v.Int64()
} else {
vals[i] = v.String()
}
}
out = append(out, vals)
}
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("read merged rows: %v", err)
}
}
rows.Close()
}
return f.Schema(), out
}
func checkMergedRows(t *testing.T, data []byte, want [][]any) *parquet.Schema {
t.Helper()
schema, got := mergedValues(t, data)
if len(got) != len(want) {
t.Fatalf("merged rows = %v, want %v", got, want)
}
for i := range want {
if len(got[i]) != len(want[i]) {
t.Fatalf("row %d = %v, want %v", i, got[i], want[i])
}
for j := range want[i] {
if got[i][j] != want[i][j] {
t.Fatalf("row %d column %d = %v, want %v (row %v)", i, j, got[i][j], want[i][j], got[i])
}
}
}
return schema
}
// A column added to the table after some files were written: the merge
// joins the files by field id and reads the new column as null for the
// old file's rows, whichever file leads the bin.
func TestMergeParquetFilesAddedColumn(t *testing.T) {
put := func(fs *fakeFilerServer) map[string]int64 {
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
putDataFileRows(t, fs, "wide.parquet", []wideSchemaRow{{4, "d", "e4"}, {5, "e", "e5"}})
return map[string]int64{"narrow.parquet": 3, "wide.parquet": 2}
}
checkFields := func(t *testing.T, schema *parquet.Schema) {
fields := schema.Fields()
if len(fields) != 3 {
t.Fatalf("merged fields = %d, want 3", len(fields))
}
names := []string{fields[0].Name(), fields[1].Name(), fields[2].Name()}
if names[0] != "id" || names[1] != "name" || names[2] != "extra" {
t.Fatalf("merged fields = %v, want [id name extra]", names)
}
if fields[2].ID() != 3 {
t.Fatalf("extra field id = %d, want 3", fields[2].ID())
}
}
t.Run("narrow first", func(t *testing.T) {
fs, client := startFakeFiler(t)
counts := put(fs)
merged, count, err := mergeNamedFiles(t, client,
[]string{"narrow.parquet", "wide.parquet"}, counts, nil, nil, false)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
}
if count != 5 {
t.Fatalf("merged %d rows, want 5", count)
}
checkFields(t, checkMergedRows(t, merged, [][]any{
{int64(1), "a", nil},
{int64(2), "b", nil},
{int64(3), "c", nil},
{int64(4), "d", "e4"},
{int64(5), "e", "e5"},
}))
})
t.Run("wide first", func(t *testing.T) {
fs, client := startFakeFiler(t)
counts := put(fs)
merged, count, err := mergeNamedFiles(t, client,
[]string{"wide.parquet", "narrow.parquet"}, counts, nil, nil, false)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
}
if count != 5 {
t.Fatalf("merged %d rows, want 5", count)
}
checkFields(t, checkMergedRows(t, merged, [][]any{
{int64(4), "d", "e4"},
{int64(5), "e", "e5"},
{int64(1), "a", nil},
{int64(2), "b", nil},
{int64(3), "c", nil},
}))
})
}
// The same Iceberg schema written REQUIRED by one engine and OPTIONAL by
// another merges; the writer keeps the wider, optional, repetition.
func TestMergeParquetFilesRequiredVsOptional(t *testing.T) {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "required.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}})
putDataFileRows(t, fs, "optional.parquet", []optionalIDSchemaRow{{3, "c"}, {4, "d"}})
merged, count, err := mergeNamedFiles(t, client,
[]string{"required.parquet", "optional.parquet"},
map[string]int64{"required.parquet": 2, "optional.parquet": 2}, nil, nil, false)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
}
if count != 4 {
t.Fatalf("merged %d rows, want 4", count)
}
schema := checkMergedRows(t, merged, [][]any{
{int64(1), "a"},
{int64(2), "b"},
{int64(3), "c"},
{int64(4), "d"},
})
if !schema.Fields()[0].Optional() {
t.Error("merged id column is REQUIRED, want OPTIONAL")
}
}
// A column dropped and re-added under the same name and type has a new
// field id; merging its file with an old one would file the new column's
// values under the dropped field id, so the bin is refused.
func TestMergeParquetFilesReaddedColumn(t *testing.T) {
for _, names := range [][]string{
{"narrow.parquet", "re-added.parquet"},
{"re-added.parquet", "narrow.parquet"},
} {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
putDataFileRows(t, fs, "re-added.parquet", []readdedNameSchemaRow{{2, "new-2"}})
_, _, err := mergeNamedFiles(t, client, names,
map[string]int64{"narrow.parquet": 1, "re-added.parquet": 1}, nil, nil, false)
if err == nil || !strings.Contains(err.Error(), "cannot merge files with different schemas") {
t.Errorf("merge of %v: %v, want schema mismatch", names, err)
}
}
}
type disjointColumnsRow struct { // id id=1, extra id=3: no name
ID int64 `parquet:"id,id(1)"`
Extra string `parquet:"extra,id(3),optional"`
}
type requiredExtraSchemaRow struct { // extra REQUIRED id=3
ID int64 `parquet:"id,id(1)"`
Name string `parquet:"name,id(2),optional"`
Extra string `parquet:"extra,id(3)"`
}
// Differences field-id matching does not cover stay refused: a rename, a
// type change, files without field ids; and a control pair still compacts.
func TestMergeParquetFilesSchemaRefusals(t *testing.T) {
type renamedSchemaRow struct {
ID int64 `parquet:"id,id(1)"`
Other string `parquet:"other,id(2),optional"`
}
type widenedSchemaRow struct {
ID int32 `parquet:"id,id(1)"`
Name string `parquet:"name,id(2),optional"`
}
type noIDExtraRow struct {
ID int64 `parquet:"id"`
Name string `parquet:"name,optional"`
Extra string `parquet:"extra,optional"`
}
cases := []struct {
name string
writeFile func(fs *fakeFilerServer, name string)
}{
{"rename", func(fs *fakeFilerServer, name string) {
putDataFileRows(t, fs, name, []renamedSchemaRow{{5, "e"}})
}},
{"type change", func(fs *fakeFilerServer, name string) {
putDataFileRows(t, fs, name, []widenedSchemaRow{{5, "e"}})
}},
{"no field ids", func(fs *fakeFilerServer, name string) {
putDataFileRows(t, fs, name, []noIDExtraRow{{5, "e", "x"}})
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
tc.writeFile(fs, "other.parquet")
_, _, err := mergeNamedFiles(t, client,
[]string{"narrow.parquet", "other.parquet"},
map[string]int64{"narrow.parquet": 1, "other.parquet": 1}, nil, nil, false)
if err == nil || !strings.Contains(err.Error(), "cannot merge files with different schemas") {
t.Errorf("merge: %v, want schema mismatch", err)
}
})
}
t.Run("control", func(t *testing.T) {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "a.parquet", []narrowSchemaRow{{1, "a"}})
putDataFileRows(t, fs, "b.parquet", []narrowSchemaRow{{2, "b"}})
if _, _, err := mergeNamedFiles(t, client, []string{"a.parquet", "b.parquet"},
map[string]int64{"a.parquet": 1, "b.parquet": 1}, nil, nil, false); err != nil {
t.Errorf("control merge: %v", err)
}
})
}
// An equality-delete column can sit at a different position in an older
// file: it is resolved on each file's own schema.
func TestMergeParquetFilesEvolvedSchemaEqualityDelete(t *testing.T) {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
putDataFileRows(t, fs, "reordered.parquet", []reorderedSchemaRow{
{"e4", 4, "d"}, {"e5", 5, "e"},
})
// An equality delete on name (field id 2) for "b" (index 1 in the
// narrow file) and "e" (index 2 in the reordered file).
type eqDeleteRow struct {
Name string `parquet:"name"`
}
var eqBuf bytes.Buffer
eqWriter := parquet.NewWriter(&eqBuf, parquet.SchemaOf(new(eqDeleteRow)))
for _, r := range []eqDeleteRow{{"b"}, {"e"}} {
if err := eqWriter.Write(&r); err != nil {
t.Fatalf("write eq delete: %v", err)
}
}
if err := eqWriter.Close(); err != nil {
t.Fatalf("close eq writer: %v", err)
}
fs.putEntry("/buckets/test-bucket/ns/tbl/data", "eq-del.parquet", &filer_pb.Entry{
Name: "eq-del.parquet", Content: eqBuf.Bytes(),
})
eqDfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentEqDeletes,
"data/eq-del.parquet", iceberg.ParquetFile, map[int]any{}, nil, nil, 2, int64(eqBuf.Len()))
if err != nil {
t.Fatalf("build eq delete: %v", err)
}
eqDfb.EqualityFieldIDs([]int{2})
snapID := int64(1)
eqEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, eqDfb.Build())
eqGroups, err := collectEqualityDeletes(context.Background(), client, "test-bucket", "ns/tbl",
[]iceberg.ManifestEntry{eqEntry}, newTestSchema())
if err != nil {
t.Fatalf("collectEqualityDeletes: %v", err)
}
merged, count, err := mergeNamedFiles(t, client,
[]string{"narrow.parquet", "reordered.parquet"},
map[string]int64{"narrow.parquet": 3, "reordered.parquet": 2}, eqGroups, newTestSchema(), false)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
}
if count != 3 {
t.Fatalf("merged %d rows, want 3", count)
}
// The union schema (id, name, extra) is the writer's.
checkMergedRows(t, merged, [][]any{
{int64(1), "a", nil},
{int64(3), "c", nil},
{int64(4), "d", "e4"},
})
}
// File pairs where neither schema covers the other merge under the union
// writer schema: a REQUIRED/OPTIONAL difference plus an added column, a
// column each side lacks the other's of, and an added REQUIRED column
// (demoted to OPTIONAL: the files without it read null).
func TestMergeParquetFilesUnionWriterSchema(t *testing.T) {
t.Run("added column and repetition differ", func(t *testing.T) {
for _, names := range [][]string{
{"wide.parquet", "optional.parquet"},
{"optional.parquet", "wide.parquet"},
} {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "wide.parquet", []wideSchemaRow{{4, "d", "e4"}, {5, "e", "e5"}})
putDataFileRows(t, fs, "optional.parquet", []optionalIDSchemaRow{{1, "a"}, {2, "b"}})
merged, count, err := mergeNamedFiles(t, client, names,
map[string]int64{"wide.parquet": 2, "optional.parquet": 2}, nil, nil, false)
if err != nil {
t.Fatalf("merge of %v: %v", names, err)
}
if count != 4 {
t.Fatalf("merged %d rows, want 4", count)
}
var want [][]any
if names[0] == "wide.parquet" {
want = [][]any{{int64(4), "d", "e4"}, {int64(5), "e", "e5"}, {int64(1), "a", nil}, {int64(2), "b", nil}}
} else {
want = [][]any{{int64(1), "a", nil}, {int64(2), "b", nil}, {int64(4), "d", "e4"}, {int64(5), "e", "e5"}}
}
schema := checkMergedRows(t, merged, want)
if !schema.Fields()[0].Optional() {
t.Errorf("merged id column is REQUIRED, want OPTIONAL")
}
}
})
t.Run("disjoint columns", func(t *testing.T) {
for _, names := range [][]string{
{"narrow.parquet", "disjoint.parquet"},
{"disjoint.parquet", "narrow.parquet"},
} {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
putDataFileRows(t, fs, "disjoint.parquet", []disjointColumnsRow{{5, "e"}})
merged, count, err := mergeNamedFiles(t, client, names,
map[string]int64{"narrow.parquet": 1, "disjoint.parquet": 1}, nil, nil, false)
if err != nil {
t.Fatalf("merge of %v: %v", names, err)
}
if count != 2 {
t.Fatalf("merged %d rows, want 2", count)
}
var want [][]any
if names[0] == "narrow.parquet" { // union (id, name, extra)
want = [][]any{{int64(1), "a", nil}, {int64(5), nil, "e"}}
} else { // union (id, extra, name)
want = [][]any{{int64(5), "e", nil}, {int64(1), nil, "a"}}
}
checkMergedRows(t, merged, want)
}
})
t.Run("added required column", func(t *testing.T) {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
putDataFileRows(t, fs, "required-extra.parquet", []requiredExtraSchemaRow{{5, "e", "x"}})
merged, count, err := mergeNamedFiles(t, client,
[]string{"narrow.parquet", "required-extra.parquet"},
map[string]int64{"narrow.parquet": 1, "required-extra.parquet": 1}, nil, nil, false)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
}
if count != 2 {
t.Fatalf("merged %d rows, want 2", count)
}
schema := checkMergedRows(t, merged, [][]any{
{int64(1), "a", nil},
{int64(5), "e", "x"},
})
if !schema.Fields()[2].Optional() {
t.Error("merged extra column is REQUIRED, want OPTIONAL")
}
})
}
// An equality delete naming a column added after some files were written:
// the files that lack it read the delete key's column as null, so a real
// key does not match their rows and a null key deletes them all.
func TestMergeParquetFilesEqualityDeleteAddedColumn(t *testing.T) {
strPtr := func(s string) *string { return &s }
put := func(fs *fakeFilerServer) map[string]int64 {
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
putDataFileRows(t, fs, "wide.parquet", []nullableExtraSchemaRow{{4, "d", strPtr("e4")}, {5, "e", nil}})
return map[string]int64{"narrow.parquet": 3, "wide.parquet": 2}
}
eqGroups := func(keys ...parquet.Value) []equalityDeleteGroup {
set := make(map[string]struct{}, len(keys))
for _, k := range keys {
set[buildEqualityKey(parquet.Row{k}, []int{0})] = struct{}{}
}
return []equalityDeleteGroup{{FieldIDs: []int{3}, Keys: set}}
}
schema := newAddedColumnSchema()
t.Run("key matches no null", func(t *testing.T) {
for _, names := range [][]string{
{"narrow.parquet", "wide.parquet"},
{"wide.parquet", "narrow.parquet"},
} {
fs, client := startFakeFiler(t)
counts := put(fs)
merged, count, err := mergeNamedFiles(t, client, names, counts,
eqGroups(parquet.ValueOf("e4")), schema, false)
if err != nil {
t.Fatalf("merge of %v: %v", names, err)
}
if count != 4 {
t.Fatalf("merged %d rows, want 4", count)
}
var want [][]any
if names[0] == "narrow.parquet" {
want = [][]any{{int64(1), "a", nil}, {int64(2), "b", nil}, {int64(3), "c", nil}, {int64(5), "e", nil}}
} else {
want = [][]any{{int64(5), "e", nil}, {int64(1), "a", nil}, {int64(2), "b", nil}, {int64(3), "c", nil}}
}
checkMergedRows(t, merged, want)
}
})
t.Run("null key deletes nulls", func(t *testing.T) {
for _, names := range [][]string{
{"narrow.parquet", "wide.parquet"},
{"wide.parquet", "narrow.parquet"},
} {
fs, client := startFakeFiler(t)
counts := put(fs)
merged, count, err := mergeNamedFiles(t, client, names, counts,
eqGroups(parquet.NullValue()), schema, false)
if err != nil {
t.Fatalf("merge of %v: %v", names, err)
}
if count != 1 {
t.Fatalf("merged %d rows, want 1", count)
}
checkMergedRows(t, merged, [][]any{{int64(4), "d", "e4"}})
}
})
}
// A column renamed after its files were written still carries its field id,
// so an equality delete on it resolves the column by id and removes only the
// rows it names — the old name looking absent must not turn every key null.
func TestMergeParquetFilesEqualityDeleteRenamedColumn(t *testing.T) {
// The table renamed name (field id 2) to label; every file still spells
// the old name.
schema := iceberg.NewSchema(0,
iceberg.NestedField{ID: 1, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true},
iceberg.NestedField{ID: 2, Type: iceberg.PrimitiveTypes.String, Name: "label", Required: false},
)
type eqDeleteRow struct {
Name string `parquet:"name,id(2)"`
}
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "a.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
putDataFileRows(t, fs, "b.parquet", []narrowSchemaRow{{4, "d"}})
var eqBuf bytes.Buffer
eqWriter := parquet.NewWriter(&eqBuf, parquet.SchemaOf(new(eqDeleteRow)))
if err := eqWriter.Write(&eqDeleteRow{"b"}); err != nil {
t.Fatalf("write eq delete: %v", err)
}
if err := eqWriter.Close(); err != nil {
t.Fatalf("close eq writer: %v", err)
}
fs.putEntry("/buckets/test-bucket/ns/tbl/data", "eq-del.parquet", &filer_pb.Entry{
Name: "eq-del.parquet", Content: eqBuf.Bytes(),
})
eqDfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentEqDeletes,
"data/eq-del.parquet", iceberg.ParquetFile, map[int]any{}, nil, nil, 1, int64(eqBuf.Len()))
if err != nil {
t.Fatalf("build eq delete: %v", err)
}
eqDfb.EqualityFieldIDs([]int{2})
snapID := int64(1)
eqEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, eqDfb.Build())
eqGroups, err := collectEqualityDeletes(context.Background(), client, "test-bucket", "ns/tbl",
[]iceberg.ManifestEntry{eqEntry}, schema)
if err != nil {
t.Fatalf("collectEqualityDeletes: %v", err)
}
merged, count, err := mergeNamedFiles(t, client,
[]string{"a.parquet", "b.parquet"},
map[string]int64{"a.parquet": 3, "b.parquet": 1}, eqGroups, schema, false)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
}
if count != 3 {
t.Fatalf("merged %d rows, want 3", count)
}
checkMergedRows(t, merged, [][]any{
{int64(1), "a"},
{int64(3), "c"},
{int64(4), "d"},
})
}
// An equality-delete file that lacks its equality column is refused rather
// than read as null keys: the spec requires equality deletes to carry the
// columns they name, so the missing-column fallback is for data files only.
func TestEqualityDeleteFileMissingColumn(t *testing.T) {
fs, client := startFakeFiler(t)
type otherRow struct {
Other string `parquet:"other,id(9)"`
}
var eqBuf bytes.Buffer
eqWriter := parquet.NewWriter(&eqBuf, parquet.SchemaOf(new(otherRow)))
if err := eqWriter.Write(&otherRow{"x"}); err != nil {
t.Fatalf("write eq delete: %v", err)
}
if err := eqWriter.Close(); err != nil {
t.Fatalf("close eq writer: %v", err)
}
fs.putEntry("/buckets/test-bucket/ns/tbl/data", "eq-del.parquet", &filer_pb.Entry{
Name: "eq-del.parquet", Content: eqBuf.Bytes(),
})
eqDfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentEqDeletes,
"data/eq-del.parquet", iceberg.ParquetFile, map[int]any{}, nil, nil, 1, int64(eqBuf.Len()))
if err != nil {
t.Fatalf("build eq delete: %v", err)
}
eqDfb.EqualityFieldIDs([]int{2})
snapID := int64(1)
eqEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, eqDfb.Build())
_, err = collectEqualityDeletes(context.Background(), client, "test-bucket", "ns/tbl",
[]iceberg.ManifestEntry{eqEntry}, newAddedColumnSchema())
if err == nil {
t.Fatal("collectEqualityDeletes: want an error for a missing equality column")
}
}
// The v3 merge matches files on the first file's columns; the re-added
// column is refused there too.
func TestMergeParquetFilesV3ReaddedColumn(t *testing.T) {
fs, client := startFakeFiler(t)
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
putDataFileRows(t, fs, "re-added.parquet", []readdedNameSchemaRow{{2, "new-2"}})
_, _, err := mergeNamedFiles(t, client,
[]string{"narrow.parquet", "re-added.parquet"},
map[string]int64{"narrow.parquet": 1, "re-added.parquet": 1}, nil, nil, true)
if err == nil || !strings.Contains(err.Error(), "cannot merge files with different schemas") {
t.Fatalf("merge: %v, want schema mismatch", err)
}
}
+51 -7
View File
@@ -1,6 +1,7 @@
package iceberg
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
@@ -14,6 +15,7 @@ import (
"sync"
"time"
"github.com/parquet-go/parquet-go"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/operation"
@@ -160,9 +162,9 @@ func loadCurrentMetadata(ctx context.Context, client filer_pb.SeaweedFilerClient
return state, nil
}
// loadFileByIcebergPath loads a file from the filer given an Iceberg-style path.
// dataPath is the bucket-relative directory the table's files live in.
func loadFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) ([]byte, error) {
// lookupFileByIcebergPath returns the filer entry holding an Iceberg-style
// path. dataPath is the bucket-relative directory the table's files live in.
func lookupFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) (*filer_pb.Entry, error) {
fullPath, err := icebergFilerPath(bucketName, dataPath, icebergPath)
if err != nil {
return nil, err
@@ -179,23 +181,65 @@ func loadFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClie
if resp == nil || resp.Entry == nil {
return nil, fmt.Errorf("file not found: %s/%s", dir, fileName)
}
return resp.Entry, nil
}
if len(resp.Entry.Content) > 0 || len(resp.Entry.Chunks) == 0 {
return resp.Entry.Content, nil
// loadFileByIcebergPath loads a file from the filer given an Iceberg-style path.
func loadFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) ([]byte, error) {
entry, err := lookupFileByIcebergPath(ctx, client, bucketName, dataPath, icebergPath)
if err != nil {
return nil, err
}
if len(entry.Content) > 0 || len(entry.Chunks) == 0 {
return entry.Content, nil
}
initGlobalHTTPClientOnce.Do(util_http.InitGlobalHttpClient)
reader := filer.NewFileReader(singleFilerClient{client: client}, resp.Entry)
reader := filer.NewFileReader(singleFilerClient{client: client}, entry)
if closer, ok := reader.(io.Closer); ok {
defer closer.Close()
}
data, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("read chunked file %s/%s: %w", dir, fileName, err)
return nil, fmt.Errorf("read chunked file %s: %w", icebergPath, err)
}
return data, nil
}
// parquetSchemaByIcebergPath reads a file's parquet schema from its footer,
// so the file's body is never fetched: a chunked file's ReadAt pulls only the
// chunks the footer spans.
func parquetSchemaByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) (*parquet.Schema, error) {
entry, err := lookupFileByIcebergPath(ctx, client, bucketName, dataPath, icebergPath)
if err != nil {
return nil, err
}
var readerAt io.ReaderAt
size := int64(entry.GetAttributes().GetFileSize())
if len(entry.Content) > 0 || len(entry.Chunks) == 0 {
readerAt = bytes.NewReader(entry.Content)
size = int64(len(entry.Content))
} else {
initGlobalHTTPClientOnce.Do(util_http.InitGlobalHttpClient)
reader := filer.NewChunkStreamReader(singleFilerClient{client: client}, entry.Chunks)
defer reader.Close()
readerAt = reader
if size <= 0 {
if size, err = reader.Seek(0, io.SeekEnd); err != nil {
return nil, fmt.Errorf("size of %s: %w", icebergPath, err)
}
}
}
f, err := parquet.OpenFile(readerAt, size)
if err != nil {
return nil, fmt.Errorf("open parquet file %s: %w", icebergPath, err)
}
return f.Schema(), nil
}
// normalizeIcebergPath converts an Iceberg path (an S3 URL, an absolute filer
// path, or a path relative to the table root) into a path relative to the
// bucket root, e.g. "ns/table/metadata/snap-1.avro". Absolute references are
+3
View File
@@ -342,6 +342,9 @@ func collectOrphanCandidates(
}
referencedFiles[path.Join("metadata", metadataFileName)] = struct{}{}
// Table-root readers (DuckDB iceberg_scan, Hadoop tables) open this to find
// the current metadata; nothing in the metadata references it.
referencedFiles[path.Join("metadata", "version-hint.text")] = struct{}{}
for mle := range meta.PreviousFiles() {
referencedFiles[mle.MetadataFile] = struct{}{}
}
+2 -1
View File
@@ -210,7 +210,8 @@ func (l *lineageLayout) mapperFor(input *parquet.Schema, src lineageSource) (*li
next++
continue
}
if base >= len(l.baseFields) || f.Name() != l.baseFields[base].Name() || !parquet.EqualNodes(f, l.baseFields[base]) {
if base >= len(l.baseFields) || f.Name() != l.baseFields[base].Name() || !parquet.EqualNodes(f, l.baseFields[base]) ||
!fieldIDsAgree(f, l.baseFields[base]) {
return nil, fmt.Errorf("cannot merge files with different schemas")
}
for i := 0; i < n; i++ {
@@ -0,0 +1,184 @@
package iceberg
import (
"fmt"
"reflect"
"github.com/parquet-go/parquet-go"
)
// The bin-pack merge of a v1/v2 table whose data files spell its schema
// differently. A bin used to take the first file's Parquet schema as the
// writer's and refuse every file whose schema was not structurally identical
// ("cannot merge files with different schemas"). That refused:
// - schema evolution: a column added to the table after some files were
// written;
// - one Iceberg schema written REQUIRED by one engine and OPTIONAL by another.
//
// The writer's schema is now the union of the bin's files' schemas, matched
// by Iceberg field id and computed before any row is written (schemaUnion),
// so every file converts into it in a single pass:
// - the same field id carries the same name and type;
// - the writer's column may be optional where the file's is required, never
// the reverse;
// - a writer column the file lacks must be optional, and reads as null.
//
// Anything else (a rename, a type change, the same name under different field
// ids, nested columns, no field ids) is refused as before.
// flatColumnsByFieldID is the schema's columns by Iceberg field id when every
// column is a top-level, non-repeated leaf with a field id of its own; ok is
// false otherwise.
func flatColumnsByFieldID(s *parquet.Schema) (map[int]parquet.Field, bool) {
if s == nil {
return nil, false
}
out := make(map[int]parquet.Field)
for _, f := range s.Fields() {
if !f.Leaf() || f.Repeated() || f.ID() <= 0 {
return nil, false
}
if _, dup := out[f.ID()]; dup {
return nil, false
}
out[f.ID()] = f
}
return out, true
}
// schemaCovers reports whether every row of a file written in source converts
// to target without losing or inventing a value (the rules above).
func schemaCovers(target, source *parquet.Schema) bool {
targetCols, ok := flatColumnsByFieldID(target)
if !ok {
return false
}
sourceCols, ok := flatColumnsByFieldID(source)
if !ok {
return false
}
for id, s := range sourceCols {
t, ok := targetCols[id]
if !ok || t.Name() != s.Name() || !parquet.EqualTypes(t.Type(), s.Type()) {
return false
}
if t.Required() && !s.Required() {
return false
}
}
for id, t := range targetCols {
if _, ok := sourceCols[id]; !ok && !t.Optional() {
return false
}
}
return true
}
// schemaUnion folds a bin's file schemas into the writer schema the merge
// needs: every field id any file carries, in the order first seen, under the
// name and type all of its files agree on. A column is REQUIRED only when
// every file has it and spells it so; a file that lacks it or spells it
// optional reads and writes nulls there. A shared field id with a different
// name or type, or the same name under different field ids (a column dropped
// and re-added), is a conflict the merge refuses.
type schemaUnion struct {
fields []unionField
byID map[int]int
byName map[string]int
folds int
}
type unionField struct {
field parquet.Field // the field as first seen
required bool // required in every file that carries it
presentInAll bool // present in every file folded so far
}
func (u *schemaUnion) fold(s *parquet.Schema, path string) error {
cols, ok := flatColumnsByFieldID(s)
if !ok {
return fmt.Errorf("schema of %s does not key flat columns by field id", path)
}
if u.byID == nil {
u.byID, u.byName = make(map[int]int), make(map[string]int)
}
for _, f := range s.Fields() {
id, name := f.ID(), f.Name()
if j, ok := u.byID[id]; ok {
e := &u.fields[j]
if e.field.Name() != name || !parquet.EqualTypes(e.field.Type(), f.Type()) {
return fmt.Errorf("field id %d is %q in one file but %q in %s", id, e.field.Name(), name, path)
}
e.required = e.required && f.Required()
continue
}
if _, ok := u.byName[name]; ok {
return fmt.Errorf("column %q carries different field ids in %s", name, path)
}
u.byID[id], u.byName[name] = len(u.fields), id
// A field folded in after the first schema is absent from every
// file seen before it.
u.fields = append(u.fields, unionField{field: f, required: f.Required(), presentInAll: u.folds == 0})
}
for i := range u.fields {
if _, ok := cols[u.fields[i].field.ID()]; !ok {
u.fields[i].presentInAll = false
}
}
u.folds++
return nil
}
// schema is the union as a writer schema; name and group give the root node
// (their Go type is never read: the merge writes parquet.Row values).
func (u *schemaUnion) schema(name string, group parquet.Node) *parquet.Schema {
fields := make([]parquet.Field, len(u.fields))
for i, e := range u.fields {
fields[i] = e.field
if !e.field.Optional() && !(e.required && e.presentInAll) {
fields[i] = unionOptionalField{Node: parquet.Optional(e.field), name: e.field.Name()}
}
}
return parquet.NewSchema(name, &orderedGroup{Node: group, fields: fields})
}
// unionOptionalField spells a field optional in the union schema when the
// file it came from wrote it required.
type unionOptionalField struct {
parquet.Node
name string
}
func (f unionOptionalField) Name() string { return f.name }
func (f unionOptionalField) Value(base reflect.Value) reflect.Value { return reflect.Value{} }
// widerSchemaError stops a merge that met a file whose schema covers the
// writer's: the bin is merged again with it.
type widerSchemaError struct {
schema *parquet.Schema
path string
}
func (e *widerSchemaError) Error() string {
return fmt.Sprintf("schema of %s is wider than the bin's writer schema", e.path)
}
// evolvedFileConversion is how a file of schema source joins a merge written
// in target: nil when they are equal, a conversion when target covers it, a
// *widerSchemaError when it covers target, else the merge's mismatch error.
func evolvedFileConversion(target, source *parquet.Schema, path string) (parquet.Conversion, error) {
if schemasEqual(target, source) {
return nil, nil
}
if schemaCovers(target, source) {
conv, err := parquet.Convert(target, source)
if err != nil {
return nil, fmt.Errorf("schema of %s: %w", path, err)
}
return conv, nil
}
if schemaCovers(source, target) {
return nil, &widerSchemaError{schema: source, path: path}
}
return nil, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", path)
}
@@ -57,6 +57,7 @@ func TestOrphanCleanupKeepsStatisticsFiles(t *testing.T) {
filer.PutFile(metaDir, "stats-1.puffin", old)
filer.PutFile(metaDir, "partition-stats-1.parquet", old)
filer.PutFile(metaDir, "stats-0.puffin", old) // superseded: a real orphan
filer.PutFile(metaDir, "version-hint.text", old)
candidates, err := collectOrphanCandidates(context.Background(), filer.Client, bucket, path.Join(namespace, tbl),
meta, "v1.metadata.json", 1)
@@ -70,7 +71,7 @@ func TestOrphanCleanupKeepsStatisticsFiles(t *testing.T) {
if !doomed["stats-0.puffin"] {
t.Fatalf("expected the unreferenced stats-0.puffin to be an orphan, got %v", doomed)
}
for _, name := range []string{"stats-1.puffin", "partition-stats-1.parquet", "v1.metadata.json"} {
for _, name := range []string{"stats-1.puffin", "partition-stats-1.parquet", "v1.metadata.json", "version-hint.text"} {
if doomed[name] {
t.Errorf("%s is referenced by the table metadata and must not be an orphan", name)
}