mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b3cc8d121 | ||
|
|
6cbcdf488c | ||
|
|
c934b5dab6 | ||
|
|
4f628ff4e5 | ||
|
|
dc462a80d7 | ||
|
|
f407bdaa36 | ||
|
|
0716577ec8 | ||
|
|
654292b57d | ||
|
|
525900dfe4 |
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -1,237 +0,0 @@
|
||||
# Parquet Pushdown Dev Plan
|
||||
|
||||
Companion to [PARQUET_PUSHDOWN_DESIGN.md](./PARQUET_PUSHDOWN_DESIGN.md). The design defines *what* the system does; this doc defines *how it lands in this codebase, in what order, with what milestones*.
|
||||
|
||||
## Status
|
||||
|
||||
Open questions resolved (see [Decisions Recorded](#decisions-recorded)). M0 is unblocked.
|
||||
|
||||
## Goals for the implementation
|
||||
|
||||
1. Ship the design's Phase 1 in production-quality form: a pushdown service that, given an Iceberg snapshot resolution, returns column-chunk byte ranges and prunes row groups using parsed-footer statistics.
|
||||
2. Establish the package layout, wire protocol, and trust-mode plumbing so later phases (scalar indexes, page-level pruning, deletes, vector search) attach without reshaping the surface.
|
||||
3. Avoid breaking any existing read path — pushdown is additive; standard S3 reads keep working.
|
||||
|
||||
## What already exists in the codebase
|
||||
|
||||
| Component | Path | Reuse |
|
||||
|---|---|---|
|
||||
| Iceberg-Go client and table/manifest types | `weed/s3api/iceberg/`, `weed/plugin/worker/iceberg/` | Catalog reads, manifest parsing, planning |
|
||||
| Parquet reader (`parquet-go/parquet-go v0.28.0`) | `weed/mq/logstore/`, `weed/query/engine/parquet_scanner.go` | Footer parse, ColumnIndex/OffsetIndex |
|
||||
| SQL/value type conversion | `weed/query/engine/parquet_scanner.go`, `weed/query/sqltypes/` | Predicate constant typing |
|
||||
| Iceberg compaction worker (uses iceberg-go for planning) | `weed/plugin/worker/iceberg/planning_index.go` | Reference for snapshot → file-list resolution |
|
||||
| Filer gRPC + protobuf scaffolding | `weed/pb/filer_pb/`, `weed/server/filer_grpc_server.go` | Wire-protocol pattern, auth |
|
||||
| S3 IAM / bucket ACL | `weed/s3api/`, `weed/iam/` | Trust enforcement on data files |
|
||||
| Substrait Go SDK (already a transitive dep) | `github.com/substrait-io/substrait-go/v7` | Predicate decode in v2 |
|
||||
|
||||
The dependencies needed for v1 (`parquet-go`, `iceberg-go`, `RoaringBitmap/roaring`, `substrait-go/v7`) are already in `go.mod` (some as indirect; will become direct).
|
||||
|
||||
## Architectural decisions for v1
|
||||
|
||||
These are commitments unless an open question below changes them.
|
||||
|
||||
- **Residency: catalog server (planning) + volume servers (heavy execution).** Pushdown is *not* a separate daemon. Planning (snapshot resolution, file-level pruning, side-index registry, footer cache, request validation) runs inside the existing catalog-server role — today colocated with the S3 gateway's Iceberg REST handlers in `weed/s3api/iceberg/`. Heavy execution (local index lookup, scalar predicate evaluation against indexes, vector distance + local top-K) runs on the volume server next to the data. The S3 gateway remains the compatibility path for unmodified readers. Rationale: the catalog already knows tables, snapshots, and table-to-files mapping, which is exactly what the planner needs — adding a separate daemon would duplicate that state. Heavy work goes to the volume servers so a single hot table cannot bottleneck cluster-wide planning. A standalone query-worker tier remains an option (design's Phase 4) only if measurements demand it.
|
||||
- **Wire protocol: gRPC.** New service definition `parquet_pushdown_pb.ParquetPushdown` in `weed/pb/parquet_pushdown_pb/`. REST/HTTP shim only if a connector requires it. JSON variant deferred.
|
||||
- **Trust mode for v1: catalog-validated, with connector-trusted as a developer-only flag.** The default deployment validates every request's `DataFiles` and `Deletes` against the Iceberg catalog at the requested snapshot before serving (full rules in [Trust Model](./PARQUET_PUSHDOWN_DESIGN.md#trust-model-and-catalog-validation)). Connector-trusted is supported but only enabled by an explicit flag for local development and benchmarks; it is not the default and is rejected in production builds. Manifest-signed is not on the roadmap.
|
||||
- **Predicate engine for v1: built-in subset evaluator.** The wire format accepts Substrait `ExtendedExpression`, but v1 implements only: comparisons (`=, !=, <, <=, >, >=`), `IN`, `BETWEEN`, `IS NULL`, and boolean `AND/OR/NOT` over them. Anything outside this subset returns `unsupported predicate`, and the connector falls back to a standard scan. Full Substrait evaluation lands in Phase 2.
|
||||
- **Side-index physical location:** co-located with the data in a hidden `.index/` directory next to each Parquet file or its parent folder, governed by the same filer ACLs as the data. Path layout matches the design's `<parquet_parent>/.index/<file_name>/<identity>/...` (file-scoped) and `<parquet_parent>/.index/<identity>/...` (folder-scoped) shapes — see [Physical Layout](./PARQUET_PUSHDOWN_DESIGN.md#physical-layout). The hidden-prefix name is configurable for deployments whose readers do not respect dot-prefix conventions.
|
||||
- **Parquet library: `parquet-go/parquet-go`** (already in use elsewhere in the repo). Apache `arrow-go/v18/parquet` is *not* introduced.
|
||||
- **Bitmap library: `RoaringBitmap/roaring`.** Used for position-delete bitmaps and DV decoding.
|
||||
|
||||
## Code layout
|
||||
|
||||
Code lives in two trees that match the architecture's two tiers. The proto stays shared.
|
||||
|
||||
**Catalog-server side** — registered on the gRPC server hosted by the catalog (today colocated with the S3 gateway's Iceberg REST handlers in `weed/s3api/iceberg/`):
|
||||
|
||||
```text
|
||||
weed/s3api/iceberg/pushdown/
|
||||
service.go # SeaweedParquetPushdown service entry
|
||||
request_validation.go # request-shape limits, trust-mode enforcement
|
||||
catalog/ # Phase 1: catalog-validated mode
|
||||
validator.go # cross-checks request DataFiles against manifest
|
||||
footer/
|
||||
cache.go # parsed-footer LRU, keyed by file identity
|
||||
parser.go # footer + ColumnIndex/OffsetIndex extraction
|
||||
predicate/
|
||||
substrait_decode.go # decode Substrait ExtendedExpression
|
||||
iceberg_decode.go # decode Iceberg Expression JSON
|
||||
eval_subset.go # v1 built-in evaluator (comparisons + boolean)
|
||||
rowgroup_prune.go # zone-map pruning for v1
|
||||
registry/ # Phase 2: side-index registry
|
||||
schema.go # registry rows + filer-backed CRUD
|
||||
reconciler.go # background freshness checker
|
||||
delete/ # Phase 2: Iceberg delete metadata
|
||||
position.go # tracks v2 position-delete files + DVs
|
||||
equality.go # tracks v2 equality-delete files
|
||||
loader.go # FileHandle + Loader (filer-backed for production)
|
||||
stats.go # PushdownStats accumulation
|
||||
```
|
||||
|
||||
**Volume-server side** (lands in Phase 3) — registered on the volume server's gRPC surface so index lookup, predicate evaluation, and vector compute run colocated with data:
|
||||
|
||||
```text
|
||||
weed/server/volume_grpc_pushdown.go # entry point on the volume server
|
||||
weed/storage/pushdown/
|
||||
index/
|
||||
bloom/ # Phase 3
|
||||
bitmap/ # Phase 3
|
||||
btree/ # Phase 3
|
||||
page/ # Phase 3
|
||||
vector/ivf/ # Phase 3
|
||||
exec/
|
||||
predicate.go # evaluate v1 predicate subset against indexes
|
||||
vector.go # local distance + top-K
|
||||
bitmap_merge.go # delete-bitmap union / subtraction
|
||||
```
|
||||
|
||||
**Shared proto** stays as today:
|
||||
|
||||
```text
|
||||
weed/pb/parquet_pushdown.proto # request/response messages
|
||||
weed/pb/parquet_pushdown_pb/ # generated
|
||||
```
|
||||
|
||||
Tests live alongside the code. Cross-tier integration tests live in `test/parquet_pushdown/`.
|
||||
|
||||
> **Existing code at `weed/parquet_pushdown/`** (M0 + M1) was scaffolded under the prior standalone-daemon decision. A code-move commit relocates the package to `weed/s3api/iceberg/pushdown/`, drops the `weed pushdown` subcommand and the standalone-daemon bootstrap, and rewires the service into the existing s3api gRPC server. That move is sequenced as the first task of M2 work in the revised milestones below.
|
||||
|
||||
## Milestones
|
||||
|
||||
Milestones are organized by the design's four-phase rollout: catalog candidates, catalog index registry, volume execution, optional workers. M0 and M1 already shipped under the previous standalone-daemon decision; **M2-rebase** is the first task of the revised plan and unblocks everything that follows.
|
||||
|
||||
### Already shipped under the prior architecture
|
||||
|
||||
Two milestones live at `weed/parquet_pushdown/` and need the rebase below before further work:
|
||||
|
||||
- **M0 (shipped):** proto + service skeleton + bufconn integration test.
|
||||
- **M1 (shipped):** parsed-footer cache + file/range-level pushdown for predicate-less requests.
|
||||
|
||||
### M2-rebase — Move pushdown into the catalog server (1 PR)
|
||||
|
||||
- Move `weed/parquet_pushdown/` to `weed/s3api/iceberg/pushdown/`. Update import paths.
|
||||
- Drop `weed pushdown` and `weed pushdown.ping`; remove `weed/parquet_pushdown/daemon/`. The standalone-daemon path is retired.
|
||||
- Register `SeaweedParquetPushdown` on the s3api gRPC server alongside the existing Iceberg REST handlers, gated by a `-pushdown.enabled` flag (default off until Phase 1 ships).
|
||||
- Update the existing M0/M1 tests to exercise the service via the s3api gRPC registration rather than a bufconn-only listener.
|
||||
- Acceptance: existing M0/M1 tests pass against the relocated package; `weed s3 -pushdown.enabled` exposes the service.
|
||||
|
||||
### Phase 1: Catalog returns candidate files / row groups / ranges
|
||||
|
||||
#### M3 — Row-group zone-map pruning (1 PR)
|
||||
|
||||
- `predicate/eval_subset.go`: evaluator for the v1 predicate subset.
|
||||
- `predicate/rowgroup_prune.go`: read row-group statistics from the parsed footer, drop row groups where the predicate cannot be true, return per-data-file `RowGroupRef` list.
|
||||
- `predicate/substrait_decode.go`: decode just enough Substrait to feed the subset evaluator; everything else returns `unsupported`.
|
||||
- Acceptance:
|
||||
- Predicate `WHERE timestamp BETWEEN t1 AND t2` against a 5M-row partitioned Iceberg table prunes to the expected row groups.
|
||||
- `unsupported predicate` returns a status the connector can recognize and fall back from.
|
||||
|
||||
#### M4 — Catalog-validated trust mode (1 PR; required for Phase 1)
|
||||
|
||||
- `catalog/validator.go`: read the Iceberg snapshot via the existing internal Iceberg package (decision 6 below), verify `(Path, SizeBytes, RecordCount, DataSequenceNumber, PartitionSpecId, PartitionValues)` for each `DataFile` and that the `Deletes` list matches the manifest's attached delete files.
|
||||
- Configurable per-endpoint: `pushdown.trust=catalog-validated|connector-trusted` (default `catalog-validated`; `connector-trusted` requires an explicit dev-mode flag).
|
||||
- Cache validated planning result keyed by `(table, SnapshotId)` to amortize manifest reads across requests in the same snapshot.
|
||||
- Acceptance: a tampered request (omitted delete file, wrong sequence number, file not in manifest, wrong partition values) is rejected with `permission_denied`. Cache hit/miss visible in `PushdownStats`.
|
||||
|
||||
**End of design Phase 1.** Phase 1 does not ship without M2-rebase + M3 + M4.
|
||||
|
||||
### Phase 2: Catalog tracks side-index registry
|
||||
|
||||
#### M5 — Index registry schema and CRUD (1 PR)
|
||||
|
||||
- `registry/schema.go`: registry rows of shape `(table, file_identity, kind, field_id) -> (.index path, build identity, build_time, healthy)`. Stored in the filer under a system path, separate from the table's bucket prefix.
|
||||
- CRUD APIs (gRPC + internal Go) for register, lookup, mark-stale, delete.
|
||||
- Planner consults the registry to know which indexes exist; missing entries fall through gracefully and are reported in stats.
|
||||
- Acceptance: register, lookup, list, and delete round-trips pass; planner stats show `indexes_used` / `indexes_missing` correctly populated.
|
||||
|
||||
#### M6 — Iceberg delete metadata in the registry (1 PR)
|
||||
|
||||
- Register position-delete files, equality-delete files, and v3 deletion vectors as registry entries attached to the data file they target.
|
||||
- Planner resolves applicable deletes per the design's applicability rules (sequence + partition + file scope, with per-row `file_path` filter for multi-target position-delete files).
|
||||
- Acceptance: planner returns the same data-file → delete-files mapping as a brute-force Iceberg manifest scan.
|
||||
|
||||
#### M7 — Background reconciler (1 PR)
|
||||
|
||||
- Worker that iterates the registry, verifies each `.index/` payload exists at the recorded path with the recorded identity, marks stale rows, and rebuilds when possible.
|
||||
- Compaction / snapshot expiration eviction: registry rows whose `file_identity` is no longer referenced by any active snapshot are reclaimable.
|
||||
- Acceptance: tampering with an index payload causes the next request to report it missing; reconciler restores the registry on the next pass.
|
||||
|
||||
### Phase 3: Volume servers execute local index/vector pushdown
|
||||
|
||||
#### M8 — Volume-server bloom-filter index (1–2 PRs)
|
||||
|
||||
- Build path: a worker reads Parquet column chunks and writes SplitBlock Bloom Filters to `.index/<file_name>/<identity>/bloom.fid_<id>` next to the data needles. Registry entry written on completion.
|
||||
- Read path: volume server gains a `PushdownExec` gRPC service that, given a (path, identity, kind, field_id, predicate), returns a per-row-group bitmap of surviving rows. Catalog plans for predicates touching bloom-able columns include the volume-server endpoint.
|
||||
- Acceptance: equality predicate `WHERE user_id = 'x'` against a 10M-row column with no matches reads zero column-chunk bytes after planning.
|
||||
|
||||
#### M9 — Volume-server bitmap and B-tree (1 PR each)
|
||||
|
||||
- `index/bitmap/` for low/medium-cardinality columns; integrates with `RoaringBitmap`.
|
||||
- `index/btree/` for sortable columns; range and point-lookup predicates.
|
||||
- Acceptance: ≥10× row-group reduction vs M3's footer-only pruning on the standard test workload.
|
||||
|
||||
#### M10 — Volume-server page-level pruning (1 PR)
|
||||
|
||||
- `index/page/`: wraps Parquet's `ColumnIndex` + `OffsetIndex` per [Page-Level Index](./PARQUET_PUSHDOWN_DESIGN.md#3-page-level-index); row-range translation across columns; dictionary-page byte-range inclusion.
|
||||
- Volume server returns `PageRef` entries with byte ranges for each projected column.
|
||||
- Acceptance: predicate selectivity ≥0.99 returns ≤1 page per surviving row group across all projected columns.
|
||||
|
||||
#### M11 — Volume-server delete bitmap evaluation (1 PR)
|
||||
|
||||
- v2 position-delete bitmap merge per the design's filter-by-`file_path` rule; cached with the registry's identity key.
|
||||
- v3 deletion-vector (Puffin `deletion-vector-v1`) reader + cache.
|
||||
- v2 equality-delete per-pair bitmap evaluation, accelerated by the volume server's scalar indexes.
|
||||
- Acceptance: a reference table with both delete forms returns identical row sets to a Spark scan of the same snapshot.
|
||||
|
||||
#### M12 — Volume-server vector index (1 PR)
|
||||
|
||||
- Partitioned IVF index per [Filtered-ANN strategy](./PARQUET_PUSHDOWN_DESIGN.md#filtered-ann-strategy); per-partition top-K runs entirely on the volume server. Catalog merges per-partition top-Ks across volume servers.
|
||||
- Acceptance: recall ≥0.95 vs brute force at top-20, 10× end-to-end speedup on the standard test set.
|
||||
|
||||
#### M13 — Hybrid scalar+vector pushdown (1 PR)
|
||||
|
||||
- Planner selects partitioned-IVF, post-filter+overscan, or filtered-HNSW per the design's strategy section based on selectivity estimate.
|
||||
- Acceptance: hybrid query that combines `tenant_id = 'x' AND timestamp >= t` with `ORDER BY embedding <-> q LIMIT 20` returns recall-correct results in <2× the cost of the lighter clause alone.
|
||||
|
||||
**End of design Phase 3.**
|
||||
|
||||
### Phase 4: Optional standalone query workers
|
||||
|
||||
Built only if profiling shows planning, hot-path coordination, or cross-volume merges become a bottleneck. Out of scope until measurements demand it.
|
||||
|
||||
### Connector integrations (parallel with Phases 1–3)
|
||||
|
||||
These run in parallel with Phases 1–3 once the catalog API stabilizes (post-M4). Each consumer reads byte ranges directly via S3 (compatibility path) or dispatches to volume-server endpoints (hot path) per request.
|
||||
|
||||
- DuckDB extension as PoC; consumes the gRPC API directly.
|
||||
- Trino connector pushdown.
|
||||
- Spark DataSource / Iceberg integration.
|
||||
|
||||
## Test strategy
|
||||
|
||||
- **Unit tests:** every package, with parquet-go in-memory fixtures.
|
||||
- **Integration tests:** `test/parquet_pushdown/` — spins up filer + a small Iceberg catalog (reuse `weed/s3api/iceberg/` infrastructure), generates Parquet data with `parquet-go` writers, compares pushdown results to a brute-force scan.
|
||||
- **Correctness oracle:** every milestone validates that pushdown output is a *strict subset* of a brute-force Iceberg+Parquet scan with the same predicate, and that the projected-column byte ranges decode to the same rows. The oracle is the safety net that lets us refactor index internals freely.
|
||||
- **Performance suite:** runs in CI weekly, not on every PR. Tracks footer-cache hit rate, row-group reduction, page reduction, end-to-end query latency vs a baseline standard scan.
|
||||
|
||||
## Decisions Recorded
|
||||
|
||||
These were the open questions before M0. All have been resolved; recording for traceability and to anchor future amendments.
|
||||
|
||||
1. **Residency:** catalog server (planning, registry, footer cache) + volume servers (local index lookup, predicate eval, vector compute). Standalone daemons are *not* introduced; query workers as an extra tier remain a future option contingent on measurements. (See [Architectural decisions](#architectural-decisions-for-v1).)
|
||||
2. **Service surface:** new `weed/pb/parquet_pushdown_pb/` package; not extending `filer_pb`.
|
||||
3. **Trust mode:** catalog-validated is the default and required for Phase 1 shipping; connector-trusted is a dev-only flag rejected in production builds.
|
||||
4. **Side-index path:** co-located in a hidden `.index/` directory next to the Parquet data, under the same parent folder. File-scoped: `<parquet_parent>/.index/<file_name>/<identity>/...`. Folder-scoped: `<parquet_parent>/.index/<identity>/...`. Hidden-prefix name configurable for non-dot-aware readers.
|
||||
5. **Predicate subset for v1:** `=`, `!=`, `<`, `<=`, `>`, `>=`, `IN`, `BETWEEN`, `IS NULL`, boolean `AND/OR/NOT`. `LIKE` deferred to the inverted-index milestone. Wire format is Substrait `ExtendedExpression` from M0.
|
||||
6. **Iceberg snapshot integration:** route through the existing internal Iceberg packages (`weed/s3api/iceberg/`, `weed/plugin/worker/iceberg/`); do not add a parallel `iceberg-go` integration in `weed/parquet_pushdown/`.
|
||||
7. **Auth:** reuse the filer's existing auth. The request principal must have read access to every `DataFile` listed; the daemon enforces this by re-using the filer's authorization on every blob fetch.
|
||||
8. **Test corpus:** generated from scratch in `test/parquet_pushdown/fixtures/`, parameterized over (with-position-deletes, with-equality-deletes, with-DVs, partitioned/unpartitioned).
|
||||
9. **Phase 1 done bar:** passing CI tests + an I/O-reduction benchmark on a reference query. Connector PoC slips to M12.
|
||||
10. **Performance regression budget for v1:** ≤10% added latency vs a direct ranged GET on a 10 MiB single-file scan in the worst case (predicate prunes nothing). The threshold is exposed as a configuration knob (`pushdown.max_overhead_pct`, default `10`) so deployments can tighten or loosen it without code changes.
|
||||
|
||||
## Risk register
|
||||
|
||||
- **Iceberg-Go maturity for v3 deletion vectors / Puffin.** If `iceberg-go v0.5.0` does not expose Puffin DV blobs, M8 needs a vendored Puffin parser. Spike during M0 to verify.
|
||||
- **parquet-go ColumnIndex/OffsetIndex completeness.** M6 depends on full ColumnIndex/OffsetIndex support. If the library returns nil for some files, fall back to row-group-only pruning per the design.
|
||||
- **Catalog read latency.** M3's per-request manifest read must be cacheable per snapshot, otherwise the catalog-validated mode adds >100ms per request. Cache eviction strategy is part of M3's spec.
|
||||
- **Trust boundary leakage.** A pushdown response must not return data references that a direct read would deny. The auth check (open question 7) is load-bearing; integration tests in M0 must include negative cases.
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.21"
|
||||
appVersion: "4.22"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.21.0
|
||||
version: 4.22.0
|
||||
@@ -370,11 +370,77 @@ func findWeedBinary() string {
|
||||
|
||||
// Helper functions for test assertions
|
||||
|
||||
// AssertFileExists checks if a file exists in the mount point
|
||||
// AssertFileExists checks if a file exists in the mount point. On failure,
|
||||
// it gathers diagnostic state (retry stat, parent listing, direct open) so
|
||||
// transient FUSE flakes leave enough information to identify the layer that
|
||||
// dropped the entry. The diagnostic block runs only on the failure path.
|
||||
func (f *FuseTestFramework) AssertFileExists(relativePath string) {
|
||||
fullPath := filepath.Join(f.mountPoint, relativePath)
|
||||
_, err := os.Stat(fullPath)
|
||||
require.NoError(f.t, err, "file should exist: %s", relativePath)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
f.dumpExistenceDiagnostics(relativePath, fullPath, err)
|
||||
require.NoError(f.t, err, "file should exist: %s (see diagnostic logs above)", relativePath)
|
||||
}
|
||||
|
||||
// dumpExistenceDiagnostics is invoked when AssertFileExists fails. It probes
|
||||
// whether the missing entry is transient (retries appear), missing from the
|
||||
// parent directory listing, or missing via a direct open syscall — three
|
||||
// signals that triangulate where the entry was lost (kernel dentry cache vs
|
||||
// mount lookup vs filer).
|
||||
func (f *FuseTestFramework) dumpExistenceDiagnostics(relativePath, fullPath string, initialErr error) {
|
||||
f.t.Logf("AssertFileExists diagnostic dump for %s", relativePath)
|
||||
f.t.Logf(" initial stat: err=%v isNotExist=%v", initialErr, os.IsNotExist(initialErr))
|
||||
|
||||
// Retry stat to detect transient invisibility — if it becomes visible
|
||||
// the issue is a short-lived dentry/cache window; if it stays missing
|
||||
// the entry is genuinely gone from the filer or the local cache.
|
||||
for attempt := 1; attempt <= 5; attempt++ {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_, err := os.Stat(fullPath)
|
||||
f.t.Logf(" retry #%d after %dms: err=%v", attempt, attempt*100, err)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// List the parent directory: if the file appears here but stat fails,
|
||||
// the failure is in the kernel's per-name dentry cache; if not, the
|
||||
// mount-side LOOKUP itself is dropping the entry.
|
||||
parentDir := filepath.Dir(fullPath)
|
||||
target := filepath.Base(fullPath)
|
||||
if entries, listErr := os.ReadDir(parentDir); listErr != nil {
|
||||
f.t.Logf(" ReadDir(%s) failed: %v", parentDir, listErr)
|
||||
} else {
|
||||
found := false
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
if e.Name() == target {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
f.t.Logf(" ReadDir(%s): %d entries, target %q present=%v", parentDir, len(entries), target, found)
|
||||
if len(names) <= 32 {
|
||||
f.t.Logf(" ReadDir entries: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// Direct O_RDONLY open — exercises the same FUSE Lookup+Open path
|
||||
// userspace would, but separately from stat, in case stat-only caching
|
||||
// is interfering.
|
||||
if fd, openErr := os.OpenFile(fullPath, os.O_RDONLY, 0); openErr != nil {
|
||||
f.t.Logf(" Open(%s, O_RDONLY): %v", fullPath, openErr)
|
||||
} else {
|
||||
st, statErr := fd.Stat()
|
||||
fd.Close()
|
||||
size := int64(-1)
|
||||
if statErr == nil && st != nil {
|
||||
size = st.Size()
|
||||
}
|
||||
f.t.Logf(" Open(%s, O_RDONLY): success size=%d statErr=%v", fullPath, size, statErr)
|
||||
}
|
||||
}
|
||||
|
||||
// AssertFileNotExists checks if a file does not exist in the mount point
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -773,6 +774,281 @@ func TestSSEMultipartUploadIntegration(t *testing.T) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAwsKms, resp.ServerSideEncryption)
|
||||
assert.Equal(t, kmsKeyID, aws.ToString(resp.SSEKMSKeyId))
|
||||
})
|
||||
|
||||
t.Run("Multipart Parts Larger Than Internal Chunks Across SSE Types", func(t *testing.T) {
|
||||
largeParts := [][]byte{
|
||||
generateTestData(9*1024*1024 + 123), // crosses SeaweedFS 8MB internal chunk boundary
|
||||
generateTestData(5*1024*1024 + 321),
|
||||
}
|
||||
|
||||
t.Run("SSE-C", func(t *testing.T) {
|
||||
sseKey := generateSSECKey()
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-ssec", largeParts, multipartSSEOptions{
|
||||
configureCreate: func(input *s3.CreateMultipartUploadInput) {
|
||||
input.SSECustomerAlgorithm = aws.String("AES256")
|
||||
input.SSECustomerKey = aws.String(sseKey.KeyB64)
|
||||
input.SSECustomerKeyMD5 = aws.String(sseKey.KeyMD5)
|
||||
},
|
||||
configureUploadPart: func(input *s3.UploadPartInput) {
|
||||
input.SSECustomerAlgorithm = aws.String("AES256")
|
||||
input.SSECustomerKey = aws.String(sseKey.KeyB64)
|
||||
input.SSECustomerKeyMD5 = aws.String(sseKey.KeyMD5)
|
||||
},
|
||||
configureGet: func(input *s3.GetObjectInput) {
|
||||
input.SSECustomerAlgorithm = aws.String("AES256")
|
||||
input.SSECustomerKey = aws.String(sseKey.KeyB64)
|
||||
input.SSECustomerKeyMD5 = aws.String(sseKey.KeyMD5)
|
||||
},
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, "AES256", aws.ToString(resp.SSECustomerAlgorithm))
|
||||
assert.Equal(t, sseKey.KeyMD5, aws.ToString(resp.SSECustomerKeyMD5))
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("SSE-KMS", func(t *testing.T) {
|
||||
kmsKeyID := "test-large-internal-chunks-key"
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-ssekms", largeParts, multipartSSEOptions{
|
||||
configureCreate: func(input *s3.CreateMultipartUploadInput) {
|
||||
input.ServerSideEncryption = types.ServerSideEncryptionAwsKms
|
||||
input.SSEKMSKeyId = aws.String(kmsKeyID)
|
||||
},
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAwsKms, resp.ServerSideEncryption)
|
||||
assert.Equal(t, kmsKeyID, aws.ToString(resp.SSEKMSKeyId))
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("SSE-S3 Explicit", func(t *testing.T) {
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-sses3-explicit", largeParts, multipartSSEOptions{
|
||||
configureCreate: func(input *s3.CreateMultipartUploadInput) {
|
||||
input.ServerSideEncryption = types.ServerSideEncryptionAes256
|
||||
},
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("SSE-S3 Bucket Default", func(t *testing.T) {
|
||||
_, err := client.PutBucketEncryption(ctx, &s3.PutBucketEncryptionInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
ServerSideEncryptionConfiguration: &types.ServerSideEncryptionConfiguration{
|
||||
Rules: []types.ServerSideEncryptionRule{
|
||||
{
|
||||
ApplyServerSideEncryptionByDefault: &types.ServerSideEncryptionByDefault{
|
||||
SSEAlgorithm: types.ServerSideEncryptionAes256,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "Failed to set bucket default SSE-S3 encryption")
|
||||
defer client.DeleteBucketEncryption(ctx, &s3.DeleteBucketEncryptionInput{Bucket: aws.String(bucketName)})
|
||||
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-sses3-default", largeParts, multipartSSEOptions{
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
type multipartSSEOptions struct {
|
||||
configureCreate func(*s3.CreateMultipartUploadInput)
|
||||
configureUploadPart func(*s3.UploadPartInput)
|
||||
configureGet func(*s3.GetObjectInput)
|
||||
verifyGet func(*s3.GetObjectOutput)
|
||||
}
|
||||
|
||||
func uploadAndVerifyMultipartSSEObject(t *testing.T, ctx context.Context, client *s3.Client, bucketName, objectKey string, partsData [][]byte, opts multipartSSEOptions) {
|
||||
t.Helper()
|
||||
|
||||
createInput := &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
}
|
||||
if opts.configureCreate != nil {
|
||||
opts.configureCreate(createInput)
|
||||
}
|
||||
createResp, err := client.CreateMultipartUpload(ctx, createInput)
|
||||
require.NoError(t, err, "Failed to create multipart upload")
|
||||
|
||||
uploadID := aws.ToString(createResp.UploadId)
|
||||
completedParts := make([]types.CompletedPart, 0, len(partsData))
|
||||
|
||||
// Abort the multipart upload if anything between here and a successful
|
||||
// CompleteMultipartUpload fails (require.NoError calls t.Fatal, which
|
||||
// triggers t.Cleanup but skips inline defers). We use context.Background
|
||||
// because the parent ctx may have been cancelled by the time cleanup runs,
|
||||
// and we only Logf the abort error so it does not mask the real failure.
|
||||
completed := false
|
||||
t.Cleanup(func() {
|
||||
if completed {
|
||||
return
|
||||
}
|
||||
if _, abortErr := client.AbortMultipartUpload(context.Background(), &s3.AbortMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
UploadId: aws.String(uploadID),
|
||||
}); abortErr != nil {
|
||||
t.Logf("AbortMultipartUpload(%s/%s, uploadID=%s) cleanup failed: %v", bucketName, objectKey, uploadID, abortErr)
|
||||
}
|
||||
})
|
||||
|
||||
for i, partData := range partsData {
|
||||
partNumber := int32(i + 1)
|
||||
uploadInput := &s3.UploadPartInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
UploadId: aws.String(uploadID),
|
||||
Body: bytes.NewReader(partData),
|
||||
}
|
||||
if opts.configureUploadPart != nil {
|
||||
opts.configureUploadPart(uploadInput)
|
||||
}
|
||||
partResp, err := client.UploadPart(ctx, uploadInput)
|
||||
require.NoError(t, err, "Failed to upload part %d", partNumber)
|
||||
|
||||
completedParts = append(completedParts, types.CompletedPart{
|
||||
ETag: partResp.ETag,
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
})
|
||||
}
|
||||
|
||||
_, err = client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
UploadId: aws.String(uploadID),
|
||||
MultipartUpload: &types.CompletedMultipartUpload{
|
||||
Parts: completedParts,
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "Failed to complete multipart upload")
|
||||
completed = true
|
||||
|
||||
expectedData := bytes.Join(partsData, nil)
|
||||
getInput := &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
}
|
||||
if opts.configureGet != nil {
|
||||
opts.configureGet(getInput)
|
||||
}
|
||||
resp, err := client.GetObject(ctx, getInput)
|
||||
require.NoError(t, err, "Failed to retrieve completed multipart object")
|
||||
downloadedData, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
require.NoError(t, err, "Failed to read completed multipart object")
|
||||
assertDataEqual(t, expectedData, downloadedData, "Multipart object data does not match original")
|
||||
assert.Equal(t, int64(len(expectedData)), aws.ToInt64(resp.ContentLength), "Multipart content length mismatch")
|
||||
if opts.verifyGet != nil {
|
||||
opts.verifyGet(resp)
|
||||
}
|
||||
|
||||
rangeStart := int64(8*1024*1024 - 64)
|
||||
rangeEnd := int64(8*1024*1024 + 64)
|
||||
rangeInput := &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
Range: aws.String(fmt.Sprintf("bytes=%d-%d", rangeStart, rangeEnd)),
|
||||
}
|
||||
if opts.configureGet != nil {
|
||||
opts.configureGet(rangeInput)
|
||||
}
|
||||
rangeResp, err := client.GetObject(ctx, rangeInput)
|
||||
require.NoError(t, err, "Failed to retrieve range crossing internal chunk boundary")
|
||||
rangeData, err := io.ReadAll(rangeResp.Body)
|
||||
rangeResp.Body.Close()
|
||||
require.NoError(t, err, "Failed to read range crossing internal chunk boundary")
|
||||
assertDataEqual(t, expectedData[rangeStart:rangeEnd+1], rangeData, "Range crossing internal chunk boundary does not match")
|
||||
if opts.verifyGet != nil {
|
||||
opts.verifyGet(rangeResp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEMultipartManyChunksIntegration pins the end-to-end fix for issue
|
||||
// #8908. A Docker Registry blob upload typically produces a multipart upload
|
||||
// with many small parts (5MB each) that totals 100MB+. After the per-chunk
|
||||
// metadata fix in #9211 and the completion backfill in #9224, the remaining
|
||||
// failure mode reported in #8908 was that GET would return truncated bytes —
|
||||
// Docker registry then computed a SHA over the truncated bytes and reported
|
||||
// "Digest did not match." The root cause was that buildMultipartSSES3Reader
|
||||
// (and its SSE-KMS / SSE-C peers) opened a volume-server HTTP connection for
|
||||
// EVERY chunk upfront, then walked them with io.MultiReader; later chunks'
|
||||
// connections sat idle while earlier chunks were being consumed and could be
|
||||
// closed by the volume server's keep-alive logic under load, producing
|
||||
// unexpected EOFs at the S3 client.
|
||||
//
|
||||
// This test mirrors that shape: 25 parts of 5MB each (125MB total, 25
|
||||
// internal chunks since each part is below the 8MB internal chunk size) with
|
||||
// bucket-default SSE-S3. The full GET must return exactly the bytes we
|
||||
// uploaded, with the SHA-256 matching. The lazy chunk reader keeps at most
|
||||
// one volume-server HTTP connection open at a time, which both eliminates the
|
||||
// idle-connection failure mode and makes resource usage proportional to one
|
||||
// chunk regardless of object size.
|
||||
//
|
||||
// The function name ends in "Integration" so it is matched by the existing
|
||||
// `.*Multipart.*Integration` pattern in .github/workflows/s3-sse-tests.yml
|
||||
// (and the `TestSSE.*Integration` pattern in test/s3/sse/Makefile's `test`
|
||||
// target), so this regression coverage is run automatically in CI.
|
||||
func TestSSEMultipartManyChunksIntegration(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client, err := createS3Client(ctx, defaultConfig)
|
||||
require.NoError(t, err, "Failed to create S3 client")
|
||||
|
||||
bucketName, err := createTestBucket(ctx, client, defaultConfig.BucketPrefix+"sse-s3-many-chunks-")
|
||||
require.NoError(t, err, "Failed to create test bucket")
|
||||
defer cleanupTestBucket(ctx, client, bucketName)
|
||||
|
||||
_, err = client.PutBucketEncryption(ctx, &s3.PutBucketEncryptionInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
ServerSideEncryptionConfiguration: &types.ServerSideEncryptionConfiguration{
|
||||
Rules: []types.ServerSideEncryptionRule{
|
||||
{
|
||||
ApplyServerSideEncryptionByDefault: &types.ServerSideEncryptionByDefault{
|
||||
SSEAlgorithm: types.ServerSideEncryptionAes256,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "Failed to set bucket default SSE-S3 encryption")
|
||||
|
||||
const numParts = 25
|
||||
const partSize = 5 * 1024 * 1024 // S3 minimum part size
|
||||
parts := make([][]byte, numParts)
|
||||
for i := range parts {
|
||||
parts[i] = generateTestData(partSize)
|
||||
}
|
||||
expected := bytes.Join(parts, nil)
|
||||
expectedHash := sha256.Sum256(expected)
|
||||
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "many-chunks-blob", parts, multipartSSEOptions{
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
},
|
||||
})
|
||||
|
||||
// Re-fetch and verify SHA-256 of the entire stream matches what we uploaded.
|
||||
// uploadAndVerifyMultipartSSEObject already does a byte-equal check, but
|
||||
// hashing is what Docker Registry actually does on pull, so pinning that
|
||||
// path here is the most faithful reproduction of #8908's symptom.
|
||||
getResp, err := client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("many-chunks-blob"),
|
||||
})
|
||||
require.NoError(t, err, "Failed to GET many-chunks-blob for SHA verification")
|
||||
defer getResp.Body.Close()
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(h, getResp.Body)
|
||||
require.NoError(t, err, "Streaming GET body to SHA hasher must not error (this is the #8908 truncation symptom)")
|
||||
assert.Equal(t, int64(len(expected)), n, "GET stream returned %d bytes, expected %d (truncation reproduces #8908)", n, len(expected))
|
||||
assert.Equal(t, expectedHash, sha256.Sum256(expected), "sanity") // tautology for clarity
|
||||
assert.Equal(t, expectedHash, [32]byte(h.Sum(nil)), "SHA-256 of GET stream must match SHA-256 of uploaded bytes (this is exactly the digest check Docker Registry does)")
|
||||
}
|
||||
|
||||
// TestDebugSSEMultipart helps debug the multipart SSE-KMS data mismatch
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
package sse_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// internalChunkSize mirrors the constant in weed/s3api/s3api_object_handlers_put.go
|
||||
// (the size at which auto-chunking splits a single PUT or part body inside the
|
||||
// volume-server layer). Range-read coverage that's interesting for SSE has to
|
||||
// straddle this boundary, since each internal chunk is encrypted with its own
|
||||
// adjusted IV (SSE-S3 / SSE-KMS) or its own random IV + PartOffset (SSE-C),
|
||||
// and the read path has to stitch keystreams across chunks correctly.
|
||||
const internalChunkSize = 8 * 1024 * 1024
|
||||
|
||||
// TestSSERangeReadIntegration is the canonical end-to-end coverage matrix
|
||||
// for HTTP range GETs across SSE modes, object size classes, and range
|
||||
// patterns. It supplements the per-SSE-mode TestSSExxxRangeRequests tests
|
||||
// (which are scoped to small single-chunk objects, ≤1MB) by also exercising
|
||||
// MEDIUM single-PUT objects that cross one internal 8MB chunk boundary AND
|
||||
// LARGE multipart objects whose content spans many internal chunks. The
|
||||
// many-chunk case is the path that broke in #8908 for full-object GETs;
|
||||
// pinning range correctness here protects against any future regression in
|
||||
// per-chunk IV / PartOffset plumbing for partial reads.
|
||||
//
|
||||
// The function name ends in "Integration" so it is matched by the existing
|
||||
// `TestSSE.*Integration` pattern that the test/s3/sse Makefile and the
|
||||
// .github/workflows/s3-sse-tests.yml CI flow use to discover SSE integration
|
||||
// tests; both flows already start the server using s3-config-template.json,
|
||||
// which configures the embedded `local` KMS provider with on-demand DEK
|
||||
// creation, so the sse_kms subtests run end-to-end in CI.
|
||||
//
|
||||
// For ad-hoc local runs against a server without any KMS provider, the test
|
||||
// probes once with a 1-byte SSE-KMS PUT and t.Skip's the sse_kms subtree
|
||||
// with a clear message rather than producing a 5xx-storm in the logs.
|
||||
func TestSSERangeReadIntegration(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client, err := createS3Client(ctx, defaultConfig)
|
||||
require.NoError(t, err, "create S3 client")
|
||||
|
||||
bucketName, err := createTestBucket(ctx, client, defaultConfig.BucketPrefix+"range-matrix-")
|
||||
require.NoError(t, err, "create test bucket")
|
||||
// MUST be t.Cleanup, not defer: the mode/size subtests below call
|
||||
// t.Parallel(), which pauses them and yields back to this function. If
|
||||
// we used defer, the for loop would finish scheduling, the function
|
||||
// would return, and defer would fire BEFORE any parallel subtest body
|
||||
// has run -- deleting the bucket out from under them. t.Cleanup waits
|
||||
// until the test AND all its subtests complete.
|
||||
t.Cleanup(func() { cleanupTestBucket(ctx, client, bucketName) })
|
||||
|
||||
modes := []sseRangeMode{
|
||||
newRangeModeNone(),
|
||||
newRangeModeSSEC(),
|
||||
newRangeModeSSEKMS("test-range-coverage-key"),
|
||||
newRangeModeSSES3(),
|
||||
}
|
||||
|
||||
// Size classes. Sizes are chosen to stress specific boundaries:
|
||||
// small : single internal chunk, no boundary
|
||||
// medium : one internal chunk boundary (8MB+arbitrary tail)
|
||||
// large : multipart with parts > 8MB, so each part itself spans
|
||||
// multiple internal chunks AND the object spans multiple
|
||||
// parts -- this is the shape the #8908 fix targets.
|
||||
sizes := []sseRangeSize{
|
||||
{
|
||||
name: "small_256KB_single_chunk",
|
||||
singlePutBytes: 256 * 1024,
|
||||
},
|
||||
{
|
||||
name: "medium_12MB_one_internal_boundary",
|
||||
singlePutBytes: internalChunkSize + 4*1024*1024,
|
||||
},
|
||||
{
|
||||
name: "large_multipart_5x9MB_many_internal_boundaries",
|
||||
// 5 parts of 9MB each: 45MB total. Every part exceeds the 8MB
|
||||
// internal chunk size, so every part is split into 2 internal
|
||||
// chunks (8MB + 1MB), giving ~10 internal chunks across the
|
||||
// object. With AWS's 5MB minimum part size, this is the
|
||||
// smallest realistic shape that exercises both inter-part
|
||||
// stitching and intra-part chunk-boundary crossing.
|
||||
multipartParts: []int{
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Each (mode, size) pair uploads an independent object key under the
|
||||
// shared bucket and exercises range reads against it. The four modes
|
||||
// have no shared state (each one carries its own SSE-C key, KMS keyID,
|
||||
// or none); within a mode each size class also writes a unique key.
|
||||
// That makes both levels safe to t.Parallel(), which substantially cuts
|
||||
// CI wall time on the matrix (~45MB of data per mode).
|
||||
for _, mode := range modes {
|
||||
mode := mode
|
||||
t.Run(mode.name(), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if reason := mode.probe(t, ctx, client, bucketName); reason != "" {
|
||||
t.Skipf("%s unsupported in this test environment: %s", mode.name(), reason)
|
||||
}
|
||||
|
||||
for _, sz := range sizes {
|
||||
sz := sz
|
||||
t.Run(sz.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
objectKey := fmt.Sprintf("%s/%s", mode.name(), sz.name)
|
||||
var data []byte
|
||||
if len(sz.multipartParts) > 0 {
|
||||
parts := make([][]byte, len(sz.multipartParts))
|
||||
for i, n := range sz.multipartParts {
|
||||
parts[i] = generateTestData(n)
|
||||
}
|
||||
mode.uploadMultipart(t, ctx, client, bucketName, objectKey, parts)
|
||||
data = bytes.Join(parts, nil)
|
||||
} else {
|
||||
data = generateTestData(sz.singlePutBytes)
|
||||
mode.uploadSingle(t, ctx, client, bucketName, objectKey, data)
|
||||
}
|
||||
|
||||
for _, rc := range rangeCasesFor(int64(len(data))) {
|
||||
rc := rc
|
||||
t.Run(rc.name, func(t *testing.T) {
|
||||
verifyRangeRead(t, ctx, client, mode, bucketName, objectKey, data, rc)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// rangeCasesFor returns the set of range patterns to exercise on an object of
|
||||
// the given total length. Some patterns are skipped automatically when the
|
||||
// object is too small for them to be meaningful (e.g. the many-chunk-spanning
|
||||
// case requires the object to actually span many internal chunks).
|
||||
func rangeCasesFor(totalLen int64) []sseRangeCase {
|
||||
cases := []sseRangeCase{
|
||||
{
|
||||
name: "single_byte_at_zero",
|
||||
rangeHeader: "bytes=0-0",
|
||||
start: 0,
|
||||
end: 0,
|
||||
},
|
||||
{
|
||||
name: "prefix_512_bytes",
|
||||
rangeHeader: "bytes=0-511",
|
||||
start: 0,
|
||||
end: 511,
|
||||
},
|
||||
{
|
||||
name: "single_byte_at_last",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-%d", totalLen-1, totalLen-1),
|
||||
start: totalLen - 1,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
{
|
||||
name: "suffix_last_100_bytes",
|
||||
rangeHeader: "bytes=-100",
|
||||
start: totalLen - 100,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
{
|
||||
name: "open_ended_from_middle",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-", totalLen/2),
|
||||
start: totalLen / 2,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
{
|
||||
name: "whole_object_as_range",
|
||||
rangeHeader: fmt.Sprintf("bytes=0-%d", totalLen-1),
|
||||
start: 0,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
}
|
||||
|
||||
if totalLen >= 64 {
|
||||
cases = append(cases, sseRangeCase{
|
||||
// AES block-boundary stress: a 17-byte range starting at byte 15
|
||||
// crosses the AES block boundary at byte 16. SSE-C historically
|
||||
// has the most fragile offset arithmetic here, so this is worth
|
||||
// pinning across all modes.
|
||||
name: "mid_chunk_crosses_aes_block_boundary",
|
||||
rangeHeader: "bytes=15-31",
|
||||
start: 15,
|
||||
end: 31,
|
||||
})
|
||||
}
|
||||
|
||||
if totalLen > internalChunkSize+128 {
|
||||
// Range straddles one internal 8MB chunk boundary by 64 bytes on
|
||||
// each side. Decryption has to fetch two distinct chunks and stitch
|
||||
// the keystreams together correctly -- the path that exposed #8908's
|
||||
// SSE-KMS double-IV bug (fixed in #9224 commit 4) and is the most
|
||||
// sensitive single test for chunk-boundary stitching.
|
||||
cases = append(cases, sseRangeCase{
|
||||
name: "mid_straddles_one_internal_boundary",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-%d", internalChunkSize-64, internalChunkSize+63),
|
||||
start: internalChunkSize - 64,
|
||||
end: internalChunkSize + 63,
|
||||
})
|
||||
}
|
||||
|
||||
if totalLen > 3*internalChunkSize+128 {
|
||||
// Range that spans more than three internal 8MB chunks. This is
|
||||
// the regression path for #8908's read-side issue: the eager
|
||||
// multipart reader opened all chunks at once and could close
|
||||
// later ones via keepalive while earlier ones were still being
|
||||
// drained; range path uses the per-chunk view helpers (always
|
||||
// lazy) but a generous-size cross-many-chunks range is still the
|
||||
// best end-to-end pin that the per-chunk IV plumbing is correct
|
||||
// across part and chunk boundaries.
|
||||
start := int64(internalChunkSize/2) + 5
|
||||
end := start + 3*internalChunkSize + 17
|
||||
if end >= totalLen {
|
||||
end = totalLen - 1
|
||||
}
|
||||
cases = append(cases, sseRangeCase{
|
||||
name: "mid_spans_many_internal_boundaries",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-%d", start, end),
|
||||
start: start,
|
||||
end: end,
|
||||
})
|
||||
}
|
||||
|
||||
return cases
|
||||
}
|
||||
|
||||
// sseRangeCase is one (start,end) range to GET, with the literal Range header
|
||||
// to send so we cover both `bytes=N-M`, `bytes=N-`, and `bytes=-N` forms.
|
||||
type sseRangeCase struct {
|
||||
name string
|
||||
rangeHeader string
|
||||
start, end int64 // inclusive byte offsets in the source data
|
||||
}
|
||||
|
||||
type sseRangeSize struct {
|
||||
name string
|
||||
singlePutBytes int // if >0, upload via PutObject of this many random bytes
|
||||
multipartParts []int // if non-empty, multipart upload with these part sizes (in bytes)
|
||||
}
|
||||
|
||||
// sseRangeMode is the per-SSE-type behavior plug for the matrix: how to
|
||||
// configure CreateBucket / PutObject / CreateMultipartUpload / UploadPart /
|
||||
// GetObject, and what to assert on GET responses.
|
||||
type sseRangeMode interface {
|
||||
name() string
|
||||
// probe attempts a 1-byte upload and returns "" on success or a short
|
||||
// reason string if the test environment doesn't support this mode (used
|
||||
// to t.Skip the SSE-KMS subtests when no KMS provider is configured).
|
||||
probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string
|
||||
uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte)
|
||||
uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte)
|
||||
configureGet(in *s3.GetObjectInput)
|
||||
verifyGet(t *testing.T, resp *s3.GetObjectOutput)
|
||||
}
|
||||
|
||||
func newRangeModeNone() sseRangeMode { return &rangeModeNone{} }
|
||||
|
||||
type rangeModeNone struct{}
|
||||
|
||||
func (m *rangeModeNone) name() string { return "no_sse" }
|
||||
func (m *rangeModeNone) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeNone) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err, "PutObject")
|
||||
}
|
||||
func (m *rangeModeNone) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts, nil, nil)
|
||||
}
|
||||
func (m *rangeModeNone) configureGet(in *s3.GetObjectInput) {}
|
||||
func (m *rangeModeNone) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Empty(t, string(resp.ServerSideEncryption), "no SSE response header expected for plaintext object")
|
||||
}
|
||||
|
||||
func newRangeModeSSEC() sseRangeMode {
|
||||
return &rangeModeSSEC{key: generateSSECKey()}
|
||||
}
|
||||
|
||||
type rangeModeSSEC struct {
|
||||
key *SSECKey
|
||||
}
|
||||
|
||||
func (m *rangeModeSSEC) name() string { return "sse_c" }
|
||||
func (m *rangeModeSSEC) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeSSEC) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
SSECustomerAlgorithm: aws.String("AES256"),
|
||||
SSECustomerKey: aws.String(m.key.KeyB64),
|
||||
SSECustomerKeyMD5: aws.String(m.key.KeyMD5),
|
||||
})
|
||||
require.NoError(t, err, "PutObject SSE-C")
|
||||
}
|
||||
func (m *rangeModeSSEC) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts,
|
||||
func(in *s3.CreateMultipartUploadInput) {
|
||||
in.SSECustomerAlgorithm = aws.String("AES256")
|
||||
in.SSECustomerKey = aws.String(m.key.KeyB64)
|
||||
in.SSECustomerKeyMD5 = aws.String(m.key.KeyMD5)
|
||||
},
|
||||
func(in *s3.UploadPartInput) {
|
||||
in.SSECustomerAlgorithm = aws.String("AES256")
|
||||
in.SSECustomerKey = aws.String(m.key.KeyB64)
|
||||
in.SSECustomerKeyMD5 = aws.String(m.key.KeyMD5)
|
||||
},
|
||||
)
|
||||
}
|
||||
func (m *rangeModeSSEC) configureGet(in *s3.GetObjectInput) {
|
||||
in.SSECustomerAlgorithm = aws.String("AES256")
|
||||
in.SSECustomerKey = aws.String(m.key.KeyB64)
|
||||
in.SSECustomerKeyMD5 = aws.String(m.key.KeyMD5)
|
||||
}
|
||||
func (m *rangeModeSSEC) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "AES256", aws.ToString(resp.SSECustomerAlgorithm))
|
||||
assert.Equal(t, m.key.KeyMD5, aws.ToString(resp.SSECustomerKeyMD5))
|
||||
}
|
||||
|
||||
func newRangeModeSSEKMS(keyID string) sseRangeMode {
|
||||
return &rangeModeSSEKMS{keyID: keyID}
|
||||
}
|
||||
|
||||
type rangeModeSSEKMS struct {
|
||||
keyID string
|
||||
}
|
||||
|
||||
func (m *rangeModeSSEKMS) name() string { return "sse_kms" }
|
||||
func (m *rangeModeSSEKMS) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
t.Helper()
|
||||
probeKey := "__probe__" + m.name()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(probeKey),
|
||||
Body: bytes.NewReader([]byte{0}),
|
||||
ServerSideEncryption: types.ServerSideEncryptionAwsKms,
|
||||
SSEKMSKeyId: aws.String(m.keyID),
|
||||
})
|
||||
if err != nil {
|
||||
// "KMS provider not configured" is the friendly diagnostic that
|
||||
// causes the caller to t.Skip the SSE-KMS subtree. We use it for
|
||||
// two narrow categories:
|
||||
// 1. 5xx responses -- the s3api InternalError surface when no KMS
|
||||
// provider is wired up at server start.
|
||||
// 2. Specific error strings ("KMS.NotConfigured" /
|
||||
// "NotImplemented" / "not configured") regardless of status,
|
||||
// to catch other servers that may use a 4xx/501 to signal the
|
||||
// same condition.
|
||||
// We deliberately do NOT auto-skip on a generic 4xx: a real
|
||||
// SSE-KMS misconfiguration in the test request itself (bad keyID
|
||||
// format, missing header, etc.) also surfaces as a 400, and the
|
||||
// CI-meaningful path -- where the server IS configured for KMS --
|
||||
// must fail loudly in that case rather than silently skip the
|
||||
// integration coverage.
|
||||
var apiErr *smithyhttp.ResponseError
|
||||
if errors.As(err, &apiErr) {
|
||||
if code := apiErr.HTTPStatusCode(); code >= 500 {
|
||||
return fmt.Sprintf("KMS provider not configured (PutObject returned %d)", code)
|
||||
}
|
||||
}
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "KMS.NotConfigured") ||
|
||||
strings.Contains(errMsg, "NotImplemented") ||
|
||||
strings.Contains(errMsg, "not configured") {
|
||||
return fmt.Sprintf("KMS provider not configured: %v", err)
|
||||
}
|
||||
return fmt.Sprintf("KMS PutObject probe failed: %v", err)
|
||||
}
|
||||
// Best-effort cleanup of the probe object.
|
||||
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(probeKey),
|
||||
})
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeSSEKMS) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
ServerSideEncryption: types.ServerSideEncryptionAwsKms,
|
||||
SSEKMSKeyId: aws.String(m.keyID),
|
||||
})
|
||||
require.NoError(t, err, "PutObject SSE-KMS")
|
||||
}
|
||||
func (m *rangeModeSSEKMS) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts,
|
||||
func(in *s3.CreateMultipartUploadInput) {
|
||||
in.ServerSideEncryption = types.ServerSideEncryptionAwsKms
|
||||
in.SSEKMSKeyId = aws.String(m.keyID)
|
||||
},
|
||||
// SSE-KMS does not require per-part headers (server reuses upload-init key).
|
||||
nil,
|
||||
)
|
||||
}
|
||||
func (m *rangeModeSSEKMS) configureGet(in *s3.GetObjectInput) {}
|
||||
func (m *rangeModeSSEKMS) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Equal(t, types.ServerSideEncryptionAwsKms, resp.ServerSideEncryption)
|
||||
assert.Equal(t, m.keyID, aws.ToString(resp.SSEKMSKeyId))
|
||||
}
|
||||
|
||||
func newRangeModeSSES3() sseRangeMode { return &rangeModeSSES3{} }
|
||||
|
||||
type rangeModeSSES3 struct{}
|
||||
|
||||
func (m *rangeModeSSES3) name() string { return "sse_s3" }
|
||||
func (m *rangeModeSSES3) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeSSES3) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
ServerSideEncryption: types.ServerSideEncryptionAes256,
|
||||
})
|
||||
require.NoError(t, err, "PutObject SSE-S3")
|
||||
}
|
||||
func (m *rangeModeSSES3) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts,
|
||||
func(in *s3.CreateMultipartUploadInput) {
|
||||
in.ServerSideEncryption = types.ServerSideEncryptionAes256
|
||||
},
|
||||
// SSE-S3 multipart parts inherit encryption from the upload init.
|
||||
nil,
|
||||
)
|
||||
}
|
||||
func (m *rangeModeSSES3) configureGet(in *s3.GetObjectInput) {}
|
||||
func (m *rangeModeSSES3) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
}
|
||||
|
||||
// multipartUpload is a small helper shared across SSE modes that need to
|
||||
// assemble the test object via Create / UploadPart / Complete with optional
|
||||
// per-mode header injection. It registers a t.Cleanup that aborts the upload
|
||||
// if Complete didn't run successfully, so a test failure mid-way doesn't
|
||||
// leave an orphan upload behind.
|
||||
func multipartUpload(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte,
|
||||
configCreate func(*s3.CreateMultipartUploadInput),
|
||||
configPart func(*s3.UploadPartInput)) {
|
||||
t.Helper()
|
||||
createIn := &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
}
|
||||
if configCreate != nil {
|
||||
configCreate(createIn)
|
||||
}
|
||||
createResp, err := client.CreateMultipartUpload(ctx, createIn)
|
||||
require.NoError(t, err, "CreateMultipartUpload")
|
||||
uploadID := aws.ToString(createResp.UploadId)
|
||||
|
||||
completed := false
|
||||
t.Cleanup(func() {
|
||||
if completed {
|
||||
return
|
||||
}
|
||||
_, _ = client.AbortMultipartUpload(context.Background(), &s3.AbortMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
UploadId: aws.String(uploadID),
|
||||
})
|
||||
})
|
||||
|
||||
completedParts := make([]types.CompletedPart, 0, len(parts))
|
||||
for i, part := range parts {
|
||||
partNumber := int32(i + 1)
|
||||
in := &s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
UploadId: aws.String(uploadID),
|
||||
Body: bytes.NewReader(part),
|
||||
}
|
||||
if configPart != nil {
|
||||
configPart(in)
|
||||
}
|
||||
resp, err := client.UploadPart(ctx, in)
|
||||
require.NoError(t, err, "UploadPart %d", partNumber)
|
||||
completedParts = append(completedParts, types.CompletedPart{
|
||||
ETag: resp.ETag,
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
})
|
||||
}
|
||||
|
||||
_, err = client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
UploadId: aws.String(uploadID),
|
||||
MultipartUpload: &types.CompletedMultipartUpload{Parts: completedParts},
|
||||
})
|
||||
require.NoError(t, err, "CompleteMultipartUpload")
|
||||
completed = true
|
||||
}
|
||||
|
||||
// verifyRangeRead does the actual GET + assertions for one (mode, object,
|
||||
// range case). It checks: the body bytes match the source slice; the
|
||||
// Content-Length header matches the range length; the Content-Range header
|
||||
// matches the resolved byte range; the SSE response headers match the mode.
|
||||
func verifyRangeRead(t *testing.T, ctx context.Context, client *s3.Client, mode sseRangeMode,
|
||||
bucket, key string, source []byte, rc sseRangeCase) {
|
||||
t.Helper()
|
||||
|
||||
totalLen := int64(len(source))
|
||||
in := &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Range: aws.String(rc.rangeHeader),
|
||||
}
|
||||
mode.configureGet(in)
|
||||
|
||||
resp, err := client.GetObject(ctx, in)
|
||||
require.NoError(t, err, "GetObject %s range=%s", key, rc.rangeHeader)
|
||||
defer resp.Body.Close()
|
||||
|
||||
got, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err, "read range body")
|
||||
|
||||
expected := source[rc.start : rc.end+1]
|
||||
expectedLen := rc.end - rc.start + 1
|
||||
// Body-length check is `require` rather than `assert` because the bug
|
||||
// fixed in #8908 surfaces as a fully-readable body that is shorter than
|
||||
// requested -- a "truncation regression". Comparing different-length
|
||||
// slices with assertDataEqual below would just produce a noisy byte-diff
|
||||
// on top of the underlying truncation; bailing here keeps the failure
|
||||
// log focused on the symptom that actually matters.
|
||||
require.Equal(t, len(expected), len(got),
|
||||
"body length mismatch for %s range=%s (source size=%d) — likely truncation regression", key, rc.rangeHeader, totalLen)
|
||||
assert.Equal(t, expectedLen, aws.ToInt64(resp.ContentLength),
|
||||
"Content-Length header mismatch for %s range=%s", key, rc.rangeHeader)
|
||||
|
||||
// Content-Range: bytes start-end/total
|
||||
wantContentRange := fmt.Sprintf("bytes %d-%d/%d", rc.start, rc.end, totalLen)
|
||||
assert.Equal(t, wantContentRange, aws.ToString(resp.ContentRange),
|
||||
"Content-Range header mismatch for %s range=%s", key, rc.rangeHeader)
|
||||
|
||||
// Compare bytes with a hash-only assertion to keep failure output small
|
||||
// (the actual byte content is random and unhelpful printed verbatim).
|
||||
assertDataEqual(t, expected, got, "Range body mismatch for %s range=%s", key, rc.rangeHeader)
|
||||
|
||||
mode.verifyGet(t, resp)
|
||||
}
|
||||
@@ -10,11 +10,10 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
var dirStatusClient = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
const dirStatusTimeout = 5 * time.Second
|
||||
|
||||
// GetClusterTopology returns the current cluster topology with caching
|
||||
func (s *AdminServer) GetClusterTopology() (*ClusterTopology, error) {
|
||||
@@ -50,8 +49,16 @@ func (s *AdminServer) fetchPublicUrlMap() map[string]string {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), dirStatusTimeout)
|
||||
defer cancel()
|
||||
|
||||
url := fmt.Sprintf("http://%s/dir/status", currentMaster.ToHttpAddress())
|
||||
resp, err := dirStatusClient.Get(url)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("Failed to build /dir/status request for %s: %v", currentMaster, err)
|
||||
return nil
|
||||
}
|
||||
resp, err := util_http.GetGlobalHttpClient().Do(req)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("Failed to fetch /dir/status from %s: %v", currentMaster, err)
|
||||
return nil
|
||||
|
||||
@@ -37,8 +37,6 @@ var Commands = []*Command{
|
||||
cmdMqAgent,
|
||||
cmdMqBroker,
|
||||
cmdMqKafkaGateway,
|
||||
cmdPushdown,
|
||||
cmdPushdownPing,
|
||||
cmdS3,
|
||||
cmdScaffold,
|
||||
cmdServer,
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown"
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown/daemon"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
)
|
||||
|
||||
var (
|
||||
pushdownOptions PushdownOptions
|
||||
)
|
||||
|
||||
type PushdownOptions struct {
|
||||
filer *string
|
||||
ip *string
|
||||
port *int
|
||||
trustMode *string
|
||||
connectorTrustedAck *bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdPushdown.Run = runPushdown // break init cycle
|
||||
pushdownOptions.filer = cmdPushdown.Flag.String("filer", "localhost:8888", "comma-separated filer server addresses for high availability")
|
||||
pushdownOptions.ip = cmdPushdown.Flag.String("ip", util.DetectedHostAddress(), "pushdown daemon gRPC listen ip address")
|
||||
pushdownOptions.port = cmdPushdown.Flag.Int("port", 18888, "pushdown daemon gRPC listen port")
|
||||
pushdownOptions.trustMode = cmdPushdown.Flag.String("trust", string(parquet_pushdown.TrustModeCatalogValidated), "trust mode: catalog-validated (default) or connector-trusted (dev only)")
|
||||
pushdownOptions.connectorTrustedAck = cmdPushdown.Flag.Bool("dev.connector_trusted_ack", false, "explicitly acknowledge running with -trust=connector-trusted; required for that mode")
|
||||
}
|
||||
|
||||
var cmdPushdown = &Command{
|
||||
UsageLine: "pushdown [-port=18888] [-filer=<ip:port>[,<ip:port>]...] [-trust=catalog-validated]",
|
||||
Short: "<WIP> start the SeaweedFS Parquet pushdown daemon (M0 skeleton)",
|
||||
Long: `start the SeaweedFS Parquet pushdown daemon.
|
||||
|
||||
The pushdown daemon is a standalone gRPC service that accelerates Parquet/
|
||||
Iceberg scans by pruning files, row groups, and pages before the engine
|
||||
reads data. See PARQUET_PUSHDOWN_DESIGN.md and PARQUET_PUSHDOWN_DEV_PLAN.md
|
||||
at the repo root for the full design and milestone plan.
|
||||
|
||||
M0 ships request validation and the gRPC surface only; pruning logic
|
||||
lands in M1+.
|
||||
|
||||
Trust modes:
|
||||
catalog-validated (default)
|
||||
Server validates each request's DataFiles and Deletes against the
|
||||
Iceberg catalog at the requested snapshot before serving.
|
||||
connector-trusted
|
||||
Skip catalog validation. Developer-only; production builds must
|
||||
not enable. Requires the explicit -dev.connector_trusted_ack flag.
|
||||
|
||||
Multiple filer addresses can be specified for high availability,
|
||||
separated by commas.`,
|
||||
}
|
||||
|
||||
func runPushdown(cmd *Command, args []string) bool {
|
||||
cfg := daemon.Config{
|
||||
IP: *pushdownOptions.ip,
|
||||
Port: *pushdownOptions.port,
|
||||
FilerAddresses: pb.ServerAddresses(*pushdownOptions.filer).ToAddresses(),
|
||||
TrustMode: parquet_pushdown.TrustMode(*pushdownOptions.trustMode),
|
||||
ConnectorTrustedAck: *pushdownOptions.connectorTrustedAck,
|
||||
Version: version.Version(),
|
||||
}
|
||||
if err := daemon.Run(cfg); err != nil {
|
||||
glog.Fatalf("pushdown daemon: %v", err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
var (
|
||||
pushdownPingOptions PushdownPingOptions
|
||||
)
|
||||
|
||||
type PushdownPingOptions struct {
|
||||
target *string
|
||||
timeout *time.Duration
|
||||
useTLS *bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdPushdownPing.Run = runPushdownPing
|
||||
pushdownPingOptions.target = cmdPushdownPing.Flag.String("server", "localhost:18888", "pushdown daemon gRPC address")
|
||||
pushdownPingOptions.timeout = cmdPushdownPing.Flag.Duration("timeout", 5*time.Second, "RPC deadline")
|
||||
pushdownPingOptions.useTLS = cmdPushdownPing.Flag.Bool("tls", false, "dial with TLS using grpc.client config")
|
||||
}
|
||||
|
||||
var cmdPushdownPing = &Command{
|
||||
UsageLine: "pushdown.ping [-server=<ip:port>]",
|
||||
Short: "<WIP> ping a running pushdown daemon (M0 smoke test)",
|
||||
Long: `ping a running pushdown daemon.
|
||||
|
||||
Calls the SeaweedParquetPushdown.Ping RPC and prints the daemon's
|
||||
reported version and trust mode. Used as a deployment smoke test
|
||||
and by the M0 integration test.`,
|
||||
}
|
||||
|
||||
func runPushdownPing(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
|
||||
dialOpt := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
if *pushdownPingOptions.useTLS {
|
||||
dialOpt = security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *pushdownPingOptions.timeout)
|
||||
defer cancel()
|
||||
|
||||
conn, err := grpc.NewClient(*pushdownPingOptions.target, dialOpt)
|
||||
if err != nil {
|
||||
glog.Errorf("dial %s: %v", *pushdownPingOptions.target, err)
|
||||
return false
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
resp, err := pb.NewSeaweedParquetPushdownClient(conn).Ping(ctx, &pb.PingRequest{})
|
||||
if err != nil {
|
||||
glog.Errorf("ping %s: %v", *pushdownPingOptions.target, err)
|
||||
return false
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stdout, "ok: server=%s version=%q trust=%q\n", *pushdownPingOptions.target, resp.Version, resp.TrustMode)
|
||||
return true
|
||||
}
|
||||
@@ -305,6 +305,20 @@ func (cm *CredentialManager) ListUserInlinePolicies(ctx context.Context, userNam
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// RenameUser atomically renames a user along with all FK-backed
|
||||
// dependents (credentials, inline policies, ...) when the underlying
|
||||
// store implements UserRenamer. Returns false if the store does not
|
||||
// support an atomic rename, in which case the caller is expected to
|
||||
// fall back to its own best-effort path. A returned non-nil error
|
||||
// always means the rename was attempted and failed.
|
||||
func (cm *CredentialManager) RenameUser(ctx context.Context, oldName, newName string) (bool, error) {
|
||||
store, ok := cm.Store.(UserRenamer)
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
return true, store.RenameUser(ctx, oldName, newName)
|
||||
}
|
||||
|
||||
// LoadS3ConfigFile reads a static S3 identity config file and registers
|
||||
// the identities so they appear in LoadConfiguration and listing results.
|
||||
func (cm *CredentialManager) LoadS3ConfigFile(path string) error {
|
||||
|
||||
@@ -148,5 +148,17 @@ type InlinePolicyStore interface {
|
||||
ListUserInlinePolicies(ctx context.Context, userName string) ([]string, error)
|
||||
}
|
||||
|
||||
// UserRenamer is an optional interface for credential stores that can
|
||||
// atomically rename a user along with all rows that reference the old
|
||||
// username (credentials, inline policies, etc). Backends with referential
|
||||
// integrity (e.g. PostgreSQL with ON DELETE CASCADE foreign keys on
|
||||
// user_inline_policies) MUST implement this so the IAM rename path can
|
||||
// move the dependents within a single transaction; copying them via
|
||||
// per-row Put / Get / Delete calls would violate the FK at statement
|
||||
// time because the new user row does not yet exist.
|
||||
type UserRenamer interface {
|
||||
RenameUser(ctx context.Context, oldName, newName string) error
|
||||
}
|
||||
|
||||
// Stores holds all available credential store implementations
|
||||
var Stores []CredentialStore
|
||||
@@ -176,6 +176,46 @@ func (store *MemoryStore) DeleteUser(ctx context.Context, username string) error
|
||||
|
||||
// Remove user
|
||||
delete(store.users, username)
|
||||
delete(store.inlinePolicies, username)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RenameUser implements credential.UserRenamer for the memory store.
|
||||
// Renames the user and re-points access-key and inline-policy indexes
|
||||
// to the new name. The whole operation is performed under the store
|
||||
// lock so it is atomic with respect to concurrent reads.
|
||||
func (store *MemoryStore) RenameUser(ctx context.Context, oldName, newName string) error {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
|
||||
if !store.initialized {
|
||||
return fmt.Errorf("store not initialized")
|
||||
}
|
||||
if oldName == newName {
|
||||
return nil
|
||||
}
|
||||
|
||||
user, exists := store.users[oldName]
|
||||
if !exists {
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
if _, clash := store.users[newName]; clash {
|
||||
return credential.ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
user.Name = newName
|
||||
store.users[newName] = user
|
||||
delete(store.users, oldName)
|
||||
|
||||
for _, cred := range user.Credentials {
|
||||
store.accessKeys[cred.AccessKey] = newName
|
||||
}
|
||||
|
||||
if policies, ok := store.inlinePolicies[oldName]; ok {
|
||||
store.inlinePolicies[newName] = policies
|
||||
delete(store.inlinePolicies, oldName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -173,3 +173,23 @@ func (store *MemoryStore) ListUserInlinePolicies(ctx context.Context, userName s
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// LoadInlinePolicies returns all inline policies keyed by username then policy name.
|
||||
func (store *MemoryStore) LoadInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
store.mu.RLock()
|
||||
defer store.mu.RUnlock()
|
||||
|
||||
if !store.initialized {
|
||||
return nil, fmt.Errorf("store not initialized")
|
||||
}
|
||||
|
||||
result := make(map[string]map[string]policy_engine.PolicyDocument, len(store.inlinePolicies))
|
||||
for userName, userPolicies := range store.inlinePolicies {
|
||||
copied := make(map[string]policy_engine.PolicyDocument, len(userPolicies))
|
||||
for policyName, doc := range userPolicies {
|
||||
copied[policyName] = doc
|
||||
}
|
||||
result[userName] = copied
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func (store *PostgresStore) CreateGroup(ctx context.Context, group *iam_pb.Group
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
`INSERT INTO groups (name, members, policy_names, disabled) VALUES ($1, $2, $3, $4)`,
|
||||
group.Name, membersJSON, policyNamesJSON, group.Disabled)
|
||||
group.Name, jsonbParam(membersJSON), jsonbParam(policyNamesJSON), group.Disabled)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
@@ -112,7 +112,7 @@ func (store *PostgresStore) UpdateGroup(ctx context.Context, group *iam_pb.Group
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
`UPDATE groups SET members = $1, policy_names = $2, disabled = $3, updated_at = CURRENT_TIMESTAMP WHERE name = $4`,
|
||||
membersJSON, policyNamesJSON, group.Disabled, group.Name)
|
||||
jsonbParam(membersJSON), jsonbParam(policyNamesJSON), group.Disabled, group.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update group: %w", err)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
|
||||
@@ -17,9 +18,9 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
|
||||
config := &iam_pb.S3ApiConfiguration{}
|
||||
|
||||
// Query all users
|
||||
rows, err := store.db.QueryContext(ctx, "SELECT username, email, account_data, actions, policy_names FROM users")
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: LoadConfiguration query failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to query users: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
@@ -29,6 +30,7 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
var accountDataJSON, actionsJSON, policyNamesJSON []byte
|
||||
|
||||
if err := rows.Scan(&username, &email, &accountDataJSON, &actionsJSON, &policyNamesJSON); err != nil {
|
||||
glog.Errorf("credential postgres: LoadConfiguration scan failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to scan user row: %w", err)
|
||||
}
|
||||
|
||||
@@ -36,28 +38,24 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
Name: username,
|
||||
}
|
||||
|
||||
// Parse account data
|
||||
if len(accountDataJSON) > 0 {
|
||||
if err := json.Unmarshal(accountDataJSON, &identity.Account); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal account data for user %s: %v", username, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse actions
|
||||
if len(actionsJSON) > 0 {
|
||||
if err := json.Unmarshal(actionsJSON, &identity.Actions); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal actions for user %s: %v", username, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse policy names
|
||||
if len(policyNamesJSON) > 0 {
|
||||
if err := json.Unmarshal(policyNamesJSON, &identity.PolicyNames); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal policy names for user %s: %v", username, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Query credentials for this user
|
||||
credRows, err := store.db.QueryContext(ctx, "SELECT access_key, secret_key FROM credentials WHERE username = $1", username)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query credentials for user %s: %v", username, err)
|
||||
@@ -75,11 +73,18 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
SecretKey: secretKey,
|
||||
})
|
||||
}
|
||||
credErr := credRows.Err()
|
||||
credRows.Close()
|
||||
|
||||
if credErr != nil {
|
||||
return nil, fmt.Errorf("failed iterating credential rows for user %s: %w", username, credErr)
|
||||
}
|
||||
config.Identities = append(config.Identities, identity)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating user rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: LoadConfiguration loaded %d identities", len(config.Identities))
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -88,24 +93,20 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Start transaction
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Clear existing data
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM credentials"); err != nil {
|
||||
return fmt.Errorf("failed to clear credentials: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM users"); err != nil {
|
||||
return fmt.Errorf("failed to clear users: %w", err)
|
||||
// Track which usernames are in the incoming config for pruning
|
||||
configUsernames := make(map[string]bool, len(config.Identities))
|
||||
for _, identity := range config.Identities {
|
||||
configUsernames[identity.Name] = true
|
||||
}
|
||||
|
||||
// Insert all identities
|
||||
// Upsert each user's row.
|
||||
for _, identity := range config.Identities {
|
||||
// Marshal account data
|
||||
var accountDataJSON []byte
|
||||
if identity.Account != nil {
|
||||
accountDataJSON, err = json.Marshal(identity.Account)
|
||||
@@ -114,7 +115,6 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal actions
|
||||
var actionsJSON []byte
|
||||
if identity.Actions != nil {
|
||||
actionsJSON, err = json.Marshal(identity.Actions)
|
||||
@@ -123,7 +123,6 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal policy names
|
||||
var policyNamesJSON []byte
|
||||
if identity.PolicyNames != nil {
|
||||
policyNamesJSON, err = json.Marshal(identity.PolicyNames)
|
||||
@@ -132,26 +131,98 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
}
|
||||
}
|
||||
|
||||
// Insert user
|
||||
_, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO users (username, email, account_data, actions, policy_names) VALUES ($1, $2, $3, $4, $5)",
|
||||
identity.Name, "", accountDataJSON, actionsJSON, policyNamesJSON)
|
||||
// Upsert user — preserves the row (and its CASCADE dependents) if it already exists
|
||||
_, err = tx.ExecContext(ctx,
|
||||
`INSERT INTO users (username, email, account_data, actions, policy_names)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (username) DO UPDATE SET
|
||||
email = EXCLUDED.email,
|
||||
account_data = EXCLUDED.account_data,
|
||||
actions = EXCLUDED.actions,
|
||||
policy_names = EXCLUDED.policy_names,
|
||||
updated_at = CURRENT_TIMESTAMP`,
|
||||
identity.Name, "", jsonbParam(accountDataJSON), jsonbParam(actionsJSON), jsonbParam(policyNamesJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert user %s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to upsert user %s: %v", identity.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Insert credentials
|
||||
// Prune users no longer in config BEFORE replacing credentials. The
|
||||
// IAM rename path (s3api UpdateUser) renames an identity in place and
|
||||
// keeps its access keys: the renamed user shows up in the incoming
|
||||
// config, the old name shows up in the pruned set. If we inserted the
|
||||
// new credentials first, the renamed user's access keys would still be
|
||||
// owned by the old row in this transaction and the INSERT would
|
||||
// violate the global UNIQUE constraint on credentials.access_key.
|
||||
// CASCADE on the old row releases those keys before the insert.
|
||||
rows, err := tx.QueryContext(ctx, "SELECT username FROM users")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list existing users for pruning: %w", err)
|
||||
}
|
||||
var toDelete []string
|
||||
for rows.Next() {
|
||||
var username string
|
||||
if err := rows.Scan(&username); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("failed to scan username for pruning: %w", err)
|
||||
}
|
||||
if !configUsernames[username] {
|
||||
toDelete = append(toDelete, username)
|
||||
}
|
||||
}
|
||||
scanErr := rows.Err()
|
||||
rows.Close()
|
||||
if scanErr != nil {
|
||||
return fmt.Errorf("failed iterating user rows for pruning: %w", scanErr)
|
||||
}
|
||||
|
||||
if len(toDelete) > 0 {
|
||||
var inlineCount int
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM user_inline_policies WHERE username = ANY($1)",
|
||||
toDelete).Scan(&inlineCount); err != nil {
|
||||
glog.Warningf("credential postgres: SaveConfiguration failed to count inline policies for prune candidates: %v", err)
|
||||
} else if inlineCount > 0 {
|
||||
glog.Warningf("credential postgres: SaveConfiguration pruning %d users will CASCADE-remove %d inline policies; if this was a rename, re-create them under the new name", len(toDelete), inlineCount)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM users WHERE username = ANY($1)", toDelete); err != nil {
|
||||
return fmt.Errorf("failed to prune users: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Two-pass credential replace: first clear every user we are about to
|
||||
// rewrite in a single round-trip, then insert. Doing the per-user delete
|
||||
// + insert in a single pass would violate the global UNIQUE constraint
|
||||
// on credentials.access_key when an access key gets reassigned from one
|
||||
// user to another within the same SaveConfiguration call.
|
||||
usernames := make([]string, 0, len(configUsernames))
|
||||
for name := range configUsernames {
|
||||
usernames = append(usernames, name)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM credentials WHERE username = ANY($1)", usernames); err != nil {
|
||||
return fmt.Errorf("failed to clear credentials for incoming users: %w", err)
|
||||
}
|
||||
for _, identity := range config.Identities {
|
||||
for _, cred := range identity.Credentials {
|
||||
_, err := tx.ExecContext(ctx,
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
identity.Name, cred.AccessKey, cred.SecretKey)
|
||||
if err != nil {
|
||||
identity.Name, cred.AccessKey, cred.SecretKey); err != nil {
|
||||
return fmt.Errorf("failed to insert credential for user %s: %v", identity.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: SaveConfiguration commit failed: %v", err)
|
||||
return fmt.Errorf("failed to commit SaveConfiguration: %w", err)
|
||||
}
|
||||
|
||||
if len(toDelete) > 0 {
|
||||
glog.Warningf("credential postgres: SaveConfiguration saved %d identities, pruned %d", len(config.Identities), len(toDelete))
|
||||
} else {
|
||||
glog.V(0).Infof("credential postgres: SaveConfiguration saved %d identities", len(config.Identities))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Identity) error {
|
||||
@@ -159,24 +230,23 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
var count int
|
||||
err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", identity.Name).Scan(&count)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser check failed user=%s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to check user existence: %w", err)
|
||||
}
|
||||
if count > 0 {
|
||||
glog.V(1).Infof("credential postgres: CreateUser user=%s already exists", identity.Name)
|
||||
return credential.ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
// Start transaction
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Marshal account data
|
||||
var accountDataJSON []byte
|
||||
if identity.Account != nil {
|
||||
accountDataJSON, err = json.Marshal(identity.Account)
|
||||
@@ -185,7 +255,6 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal actions
|
||||
var actionsJSON []byte
|
||||
if identity.Actions != nil {
|
||||
actionsJSON, err = json.Marshal(identity.Actions)
|
||||
@@ -194,7 +263,6 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal policy names
|
||||
var policyNamesJSON []byte
|
||||
if identity.PolicyNames != nil {
|
||||
policyNamesJSON, err = json.Marshal(identity.PolicyNames)
|
||||
@@ -203,25 +271,31 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
}
|
||||
}
|
||||
|
||||
// Insert user
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"INSERT INTO users (username, email, account_data, actions, policy_names) VALUES ($1, $2, $3, $4, $5)",
|
||||
identity.Name, "", accountDataJSON, actionsJSON, policyNamesJSON)
|
||||
identity.Name, "", jsonbParam(accountDataJSON), jsonbParam(actionsJSON), jsonbParam(policyNamesJSON))
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser insert failed user=%s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to insert user: %w", err)
|
||||
}
|
||||
|
||||
// Insert credentials
|
||||
for _, cred := range identity.Credentials {
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
identity.Name, cred.AccessKey, cred.SecretKey)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser insert credential failed user=%s accessKey=%s: %v", identity.Name, cred.AccessKey, err)
|
||||
return fmt.Errorf("failed to insert credential: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser commit failed user=%s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to commit create user %s: %w", identity.Name, err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: CreateUser user=%s credentials=%d actions=%d", identity.Name, len(identity.Credentials), len(identity.Actions))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_pb.Identity, error) {
|
||||
@@ -237,8 +311,10 @@ func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_
|
||||
username).Scan(&email, &accountDataJSON, &actionsJSON, &policyNamesJSON)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
glog.V(2).Infof("credential postgres: GetUser user=%s not found", username)
|
||||
return nil, credential.ErrUserNotFound
|
||||
}
|
||||
glog.Errorf("credential postgres: GetUser query failed user=%s: %v", username, err)
|
||||
return nil, fmt.Errorf("failed to query user: %w", err)
|
||||
}
|
||||
|
||||
@@ -246,28 +322,24 @@ func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_
|
||||
Name: username,
|
||||
}
|
||||
|
||||
// Parse account data
|
||||
if len(accountDataJSON) > 0 {
|
||||
if err := json.Unmarshal(accountDataJSON, &identity.Account); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal account data: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse actions
|
||||
if len(actionsJSON) > 0 {
|
||||
if err := json.Unmarshal(actionsJSON, &identity.Actions); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal actions: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse policy names
|
||||
if len(policyNamesJSON) > 0 {
|
||||
if err := json.Unmarshal(policyNamesJSON, &identity.PolicyNames); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal policy names: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Query credentials
|
||||
rows, err := store.db.QueryContext(ctx, "SELECT access_key, secret_key FROM credentials WHERE username = $1", username)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query credentials: %w", err)
|
||||
@@ -279,13 +351,16 @@ func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_
|
||||
if err := rows.Scan(&accessKey, &secretKey); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan credential: %w", err)
|
||||
}
|
||||
|
||||
identity.Credentials = append(identity.Credentials, &iam_pb.Credential{
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating credential rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("credential postgres: GetUser user=%s credentials=%d actions=%d", username, len(identity.Credentials), len(identity.Actions))
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
@@ -294,14 +369,12 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Start transaction
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Check if user exists
|
||||
var count int
|
||||
err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", username).Scan(&count)
|
||||
if err != nil {
|
||||
@@ -311,7 +384,6 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
|
||||
// Marshal account data
|
||||
var accountDataJSON []byte
|
||||
if identity.Account != nil {
|
||||
accountDataJSON, err = json.Marshal(identity.Account)
|
||||
@@ -320,7 +392,6 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal actions
|
||||
var actionsJSON []byte
|
||||
if identity.Actions != nil {
|
||||
actionsJSON, err = json.Marshal(identity.Actions)
|
||||
@@ -329,7 +400,6 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal policy names
|
||||
var policyNamesJSON []byte
|
||||
if identity.PolicyNames != nil {
|
||||
policyNamesJSON, err = json.Marshal(identity.PolicyNames)
|
||||
@@ -338,21 +408,19 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
// Update user
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"UPDATE users SET email = $2, account_data = $3, actions = $4, policy_names = $5, updated_at = CURRENT_TIMESTAMP WHERE username = $1",
|
||||
username, "", accountDataJSON, actionsJSON, policyNamesJSON)
|
||||
username, "", jsonbParam(accountDataJSON), jsonbParam(actionsJSON), jsonbParam(policyNamesJSON))
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: UpdateUser failed user=%s: %v", username, err)
|
||||
return fmt.Errorf("failed to update user: %w", err)
|
||||
}
|
||||
|
||||
// Delete existing credentials
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM credentials WHERE username = $1", username)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete existing credentials: %w", err)
|
||||
}
|
||||
|
||||
// Insert new credentials
|
||||
for _, cred := range identity.Credentials {
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
@@ -362,7 +430,13 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: UpdateUser commit failed user=%s: %v", username, err)
|
||||
return fmt.Errorf("failed to commit update user %s: %w", username, err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: UpdateUser user=%s credentials=%d", username, len(identity.Credentials))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) DeleteUser(ctx context.Context, username string) error {
|
||||
@@ -372,6 +446,7 @@ func (store *PostgresStore) DeleteUser(ctx context.Context, username string) err
|
||||
|
||||
result, err := store.db.ExecContext(ctx, "DELETE FROM users WHERE username = $1", username)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: DeleteUser failed user=%s: %v", username, err)
|
||||
return fmt.Errorf("failed to delete user: %w", err)
|
||||
}
|
||||
|
||||
@@ -381,9 +456,86 @@ func (store *PostgresStore) DeleteUser(ctx context.Context, username string) err
|
||||
}
|
||||
|
||||
if rowsAffected == 0 {
|
||||
glog.V(1).Infof("credential postgres: DeleteUser user=%s not found", username)
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: DeleteUser user=%s", username)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RenameUser atomically renames oldName to newName, re-pointing every
|
||||
// FK-backed dependent row in a single transaction. The schema's foreign
|
||||
// keys (credentials.username, user_inline_policies.username) reference
|
||||
// users.username with ON DELETE CASCADE and the default ON UPDATE
|
||||
// NO ACTION, which means a plain UPDATE users SET username = newName
|
||||
// would fail because the children still reference the old name. Instead:
|
||||
// 1. Insert the new users row by copying every non-key column from old.
|
||||
// 2. Re-point the dependent tables (credentials, user_inline_policies)
|
||||
// to the new username — both rows now exist so the FK is satisfied.
|
||||
// 3. Delete the old users row, which has no remaining dependents.
|
||||
//
|
||||
// Implements credential.UserRenamer.
|
||||
func (store *PostgresStore) RenameUser(ctx context.Context, oldName, newName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
if oldName == newName {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Refuse if oldName is missing or newName already exists, so the
|
||||
// caller surfaces a recognisable error instead of a constraint
|
||||
// violation midway through.
|
||||
var oldExists, newExists bool
|
||||
if err := tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)", oldName).Scan(&oldExists); err != nil {
|
||||
return fmt.Errorf("failed to check old user %s: %w", oldName, err)
|
||||
}
|
||||
if !oldExists {
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
if err := tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)", newName).Scan(&newExists); err != nil {
|
||||
return fmt.Errorf("failed to check new user %s: %w", newName, err)
|
||||
}
|
||||
if newExists {
|
||||
return credential.ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO users (username, email, account_data, actions, policy_names, created_at, updated_at)
|
||||
SELECT $1, email, account_data, actions, policy_names, created_at, CURRENT_TIMESTAMP
|
||||
FROM users WHERE username = $2`,
|
||||
newName, oldName); err != nil {
|
||||
return fmt.Errorf("failed to insert renamed user %s: %w", newName, err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE credentials SET username = $1 WHERE username = $2", newName, oldName); err != nil {
|
||||
return fmt.Errorf("failed to re-point credentials to %s: %w", newName, err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE user_inline_policies SET username = $1 WHERE username = $2", newName, oldName); err != nil {
|
||||
return fmt.Errorf("failed to re-point inline policies to %s: %w", newName, err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM users WHERE username = $1", oldName); err != nil {
|
||||
return fmt.Errorf("failed to drop old user %s: %w", oldName, err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: RenameUser commit failed %s -> %s: %v", oldName, newName, err)
|
||||
return fmt.Errorf("failed to commit rename %s -> %s: %w", oldName, newName, err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: RenameUser %s -> %s", oldName, newName)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -394,6 +546,7 @@ func (store *PostgresStore) ListUsers(ctx context.Context) ([]string, error) {
|
||||
|
||||
rows, err := store.db.QueryContext(ctx, "SELECT username FROM users ORDER BY username")
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: ListUsers query failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to query users: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
@@ -406,7 +559,11 @@ func (store *PostgresStore) ListUsers(ctx context.Context) ([]string, error) {
|
||||
}
|
||||
usernames = append(usernames, username)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating user rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: ListUsers count=%d", len(usernames))
|
||||
return usernames, nil
|
||||
}
|
||||
|
||||
@@ -419,11 +576,14 @@ func (store *PostgresStore) GetUserByAccessKey(ctx context.Context, accessKey st
|
||||
err := store.db.QueryRowContext(ctx, "SELECT username FROM credentials WHERE access_key = $1", accessKey).Scan(&username)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
glog.V(2).Infof("credential postgres: GetUserByAccessKey accessKey=%s not found", accessKey)
|
||||
return nil, credential.ErrAccessKeyNotFound
|
||||
}
|
||||
glog.Errorf("credential postgres: GetUserByAccessKey query failed accessKey=%s: %v", accessKey, err)
|
||||
return nil, fmt.Errorf("failed to query access key: %w", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("credential postgres: GetUserByAccessKey accessKey=%s resolved to user=%s", accessKey, username)
|
||||
return store.GetUser(ctx, username)
|
||||
}
|
||||
|
||||
@@ -432,7 +592,6 @@ func (store *PostgresStore) CreateAccessKey(ctx context.Context, username string
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Check if user exists
|
||||
var count int
|
||||
err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", username).Scan(&count)
|
||||
if err != nil {
|
||||
@@ -442,14 +601,15 @@ func (store *PostgresStore) CreateAccessKey(ctx context.Context, username string
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
|
||||
// Insert credential
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
username, cred.AccessKey, cred.SecretKey)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateAccessKey failed user=%s accessKey=%s: %v", username, cred.AccessKey, err)
|
||||
return fmt.Errorf("failed to insert credential: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: CreateAccessKey user=%s accessKey=%s", username, cred.AccessKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -462,6 +622,7 @@ func (store *PostgresStore) DeleteAccessKey(ctx context.Context, username string
|
||||
"DELETE FROM credentials WHERE username = $1 AND access_key = $2",
|
||||
username, accessKey)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: DeleteAccessKey failed user=%s accessKey=%s: %v", username, accessKey, err)
|
||||
return fmt.Errorf("failed to delete access key: %w", err)
|
||||
}
|
||||
|
||||
@@ -471,7 +632,6 @@ func (store *PostgresStore) DeleteAccessKey(ctx context.Context, username string
|
||||
}
|
||||
|
||||
if rowsAffected == 0 {
|
||||
// Check if user exists
|
||||
var count int
|
||||
err = store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", username).Scan(&count)
|
||||
if err != nil {
|
||||
@@ -483,22 +643,20 @@ func (store *PostgresStore) DeleteAccessKey(ctx context.Context, username string
|
||||
return credential.ErrAccessKeyNotFound
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: DeleteAccessKey user=%s accessKey=%s", username, accessKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// AttachUserPolicy attaches a managed policy to a user by policy name
|
||||
func (store *PostgresStore) AttachUserPolicy(ctx context.Context, username string, policyName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Get user
|
||||
identity, err := store.GetUser(ctx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify policy exists
|
||||
policy, err := store.GetPolicy(ctx, policyName)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -507,31 +665,31 @@ func (store *PostgresStore) AttachUserPolicy(ctx context.Context, username strin
|
||||
return credential.ErrPolicyNotFound
|
||||
}
|
||||
|
||||
// Check if already attached
|
||||
for _, p := range identity.PolicyNames {
|
||||
if p == policyName {
|
||||
return credential.ErrPolicyAlreadyAttached
|
||||
}
|
||||
}
|
||||
|
||||
// Append policy name and update
|
||||
identity.PolicyNames = append(identity.PolicyNames, policyName)
|
||||
return store.UpdateUser(ctx, username, identity)
|
||||
if err := store.UpdateUser(ctx, username, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: AttachUserPolicy user=%s policy=%s", username, policyName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DetachUserPolicy detaches a managed policy from a user
|
||||
func (store *PostgresStore) DetachUserPolicy(ctx context.Context, username string, policyName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Get user
|
||||
identity, err := store.GetUser(ctx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Find and remove policy
|
||||
found := false
|
||||
var newPolicyNames []string
|
||||
for _, p := range identity.PolicyNames {
|
||||
@@ -547,10 +705,14 @@ func (store *PostgresStore) DetachUserPolicy(ctx context.Context, username strin
|
||||
}
|
||||
|
||||
identity.PolicyNames = newPolicyNames
|
||||
return store.UpdateUser(ctx, username, identity)
|
||||
if err := store.UpdateUser(ctx, username, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: DetachUserPolicy user=%s policy=%s", username, policyName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAttachedUserPolicies returns the list of policy names attached to a user
|
||||
func (store *PostgresStore) ListAttachedUserPolicies(ctx context.Context, username string) ([]string, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
)
|
||||
|
||||
func (store *PostgresStore) PutUserInlinePolicy(ctx context.Context, userName, policyName string, document policy_engine.PolicyDocument) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
docJSON, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: PutUserInlinePolicy marshal failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return fmt.Errorf("failed to marshal policy document: %w", err)
|
||||
}
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
`INSERT INTO user_inline_policies (username, policy_name, document)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (username, policy_name)
|
||||
DO UPDATE SET document = $3, updated_at = CURRENT_TIMESTAMP`,
|
||||
userName, policyName, jsonbParam(docJSON))
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: PutUserInlinePolicy failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return fmt.Errorf("failed to upsert inline policy: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: PutUserInlinePolicy user=%s policy=%s", userName, policyName)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) GetUserInlinePolicy(ctx context.Context, userName, policyName string) (*policy_engine.PolicyDocument, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
var docJSON []byte
|
||||
err := store.db.QueryRowContext(ctx,
|
||||
"SELECT document FROM user_inline_policies WHERE username = $1 AND policy_name = $2",
|
||||
userName, policyName).Scan(&docJSON)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
glog.V(2).Infof("credential postgres: GetUserInlinePolicy user=%s policy=%s not found", userName, policyName)
|
||||
return nil, nil
|
||||
}
|
||||
glog.Errorf("credential postgres: GetUserInlinePolicy query failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return nil, fmt.Errorf("failed to query inline policy: %w", err)
|
||||
}
|
||||
|
||||
var doc policy_engine.PolicyDocument
|
||||
if err := json.Unmarshal(docJSON, &doc); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal inline policy: %w", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("credential postgres: GetUserInlinePolicy user=%s policy=%s found", userName, policyName)
|
||||
return &doc, nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) DeleteUserInlinePolicy(ctx context.Context, userName, policyName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
"DELETE FROM user_inline_policies WHERE username = $1 AND policy_name = $2",
|
||||
userName, policyName)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: DeleteUserInlinePolicy failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return fmt.Errorf("failed to delete inline policy: %w", err)
|
||||
}
|
||||
|
||||
rowsAffected, _ := result.RowsAffected()
|
||||
glog.V(0).Infof("credential postgres: DeleteUserInlinePolicy user=%s policy=%s deleted=%d", userName, policyName, rowsAffected)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) ListUserInlinePolicies(ctx context.Context, userName string) ([]string, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
rows, err := store.db.QueryContext(ctx,
|
||||
"SELECT policy_name FROM user_inline_policies WHERE username = $1 ORDER BY policy_name",
|
||||
userName)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: ListUserInlinePolicies query failed user=%s: %v", userName, err)
|
||||
return nil, fmt.Errorf("failed to query inline policies: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var names []string
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan policy name: %w", err)
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating inline policy rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: ListUserInlinePolicies user=%s count=%d", userName, len(names))
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) LoadInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
rows, err := store.db.QueryContext(ctx,
|
||||
"SELECT username, policy_name, document FROM user_inline_policies ORDER BY username, policy_name")
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: LoadInlinePolicies query failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to query inline policies: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string]map[string]policy_engine.PolicyDocument)
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
var username, policyName string
|
||||
var docJSON []byte
|
||||
if err := rows.Scan(&username, &policyName, &docJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan inline policy row: %w", err)
|
||||
}
|
||||
|
||||
var doc policy_engine.PolicyDocument
|
||||
if err := json.Unmarshal(docJSON, &doc); err != nil {
|
||||
glog.Warningf("credential postgres: LoadInlinePolicies unmarshal failed user=%s policy=%s: %v", username, policyName, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if result[username] == nil {
|
||||
result[username] = make(map[string]policy_engine.PolicyDocument)
|
||||
}
|
||||
result[username][policyName] = doc
|
||||
count++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating inline policy rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: LoadInlinePolicies loaded %d policies for %d users", count, len(result))
|
||||
return result, nil
|
||||
}
|
||||
@@ -78,7 +78,7 @@ func (store *PostgresStore) CreatePolicy(ctx context.Context, name string, docum
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
"INSERT INTO policies (name, document) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET document = $2, updated_at = CURRENT_TIMESTAMP",
|
||||
name, documentJSON)
|
||||
name, jsonbParam(documentJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert policy: %w", err)
|
||||
}
|
||||
@@ -104,7 +104,7 @@ func (store *PostgresStore) UpdatePolicy(ctx context.Context, name string, docum
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
"UPDATE policies SET document = $2, updated_at = CURRENT_TIMESTAMP WHERE name = $1",
|
||||
name, documentJSON)
|
||||
name, jsonbParam(documentJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update policy: %w", err)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func (store *PostgresStore) CreateServiceAccount(ctx context.Context, sa *iam_pb
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
"INSERT INTO service_accounts (id, access_key, content) VALUES ($1, $2, $3)",
|
||||
sa.Id, accessKey, data)
|
||||
sa.Id, accessKey, jsonbParam(data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert service account: %w", err)
|
||||
}
|
||||
@@ -63,7 +63,7 @@ func (store *PostgresStore) UpdateServiceAccount(ctx context.Context, id string,
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
"UPDATE service_accounts SET access_key = $2, content = $3, updated_at = CURRENT_TIMESTAMP WHERE id = $1",
|
||||
id, accessKey, data)
|
||||
id, accessKey, jsonbParam(data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update service account: %w", err)
|
||||
}
|
||||
|
||||
@@ -3,14 +3,31 @@ package postgres
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/pgxutil"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultMaxOpenConns = 25
|
||||
defaultMaxIdleConns = 5
|
||||
defaultConnMaxLifetimeSecs = 300
|
||||
)
|
||||
|
||||
// jsonbParam adapts JSON bytes for an ExecContext call against a JSONB
|
||||
// column. Returns nil (so the driver writes SQL NULL) when b is nil or
|
||||
// empty; otherwise returns string(b) so pgx drives it as JSONB text — []byte
|
||||
// would be encoded as bytea under simple_protocol (pgbouncer mode) and
|
||||
// rejected by Postgres with "invalid input syntax for type json".
|
||||
func jsonbParam(b []byte) interface{} {
|
||||
if len(b) == 0 {
|
||||
return nil
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func init() {
|
||||
credential.Stores = append(credential.Stores, &PostgresStore{})
|
||||
}
|
||||
@@ -37,56 +54,76 @@ func (store *PostgresStore) Initialize(configuration util.Configuration, prefix
|
||||
database := configuration.GetString(prefix + "database")
|
||||
schema := configuration.GetString(prefix + "schema")
|
||||
sslmode := configuration.GetString(prefix + "sslmode")
|
||||
sslcert := configuration.GetString(prefix + "sslcert")
|
||||
sslkey := configuration.GetString(prefix + "sslkey")
|
||||
sslrootcert := configuration.GetString(prefix + "sslrootcert")
|
||||
sslcrl := configuration.GetString(prefix + "sslcrl")
|
||||
pgbouncerCompatible := configuration.GetBool(prefix + "pgbouncer_compatible")
|
||||
maxIdle := configuration.GetInt(prefix + "connection_max_idle")
|
||||
maxOpen := configuration.GetInt(prefix + "connection_max_open")
|
||||
maxLifetimeSeconds := configuration.GetInt(prefix + "connection_max_lifetime_seconds")
|
||||
|
||||
// Set defaults
|
||||
if hostname == "" {
|
||||
hostname = "localhost"
|
||||
}
|
||||
if port == 0 {
|
||||
port = 5432
|
||||
}
|
||||
if schema == "" {
|
||||
schema = "public"
|
||||
}
|
||||
if sslmode == "" {
|
||||
sslmode = "disable"
|
||||
}
|
||||
if maxOpen == 0 {
|
||||
maxOpen = defaultMaxOpenConns
|
||||
}
|
||||
if maxIdle == 0 {
|
||||
maxIdle = defaultMaxIdleConns
|
||||
}
|
||||
if maxLifetimeSeconds == 0 {
|
||||
maxLifetimeSeconds = defaultConnMaxLifetimeSecs
|
||||
}
|
||||
|
||||
// Build pgx-optimized connection string
|
||||
// Note: prefer_simple_protocol=true is only needed for PgBouncer, not direct PostgreSQL connections
|
||||
connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s search_path=%s",
|
||||
hostname, port, username, password, database, sslmode, schema)
|
||||
glog.V(0).Infof("credential postgres: initializing store host=%s port=%d user=%s db=%s sslmode=%s pgbouncer=%v",
|
||||
hostname, port, username, database, sslmode, pgbouncerCompatible)
|
||||
|
||||
db, err := sql.Open("pgx", connStr)
|
||||
dsn, adaptedDSN := pgxutil.BuildDSN(pgxutil.DSNOptions{
|
||||
Hostname: hostname,
|
||||
Port: port,
|
||||
User: username,
|
||||
Password: password,
|
||||
Database: database,
|
||||
Schema: schema,
|
||||
SSLMode: sslmode,
|
||||
SSLCert: sslcert,
|
||||
SSLKey: sslkey,
|
||||
SSLRootCert: sslrootcert,
|
||||
SSLCRL: sslcrl,
|
||||
PgBouncerCompatible: pgbouncerCompatible,
|
||||
})
|
||||
|
||||
db, err := pgxutil.OpenDB(dsn, adaptedDSN, pgbouncerCompatible, maxIdle, maxOpen, maxLifetimeSeconds)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: failed to open database: %v", err)
|
||||
return fmt.Errorf("failed to open database: %w", err)
|
||||
}
|
||||
|
||||
// Test connection
|
||||
if err := db.Ping(); err != nil {
|
||||
db.Close()
|
||||
return fmt.Errorf("failed to ping database: %w", err)
|
||||
}
|
||||
|
||||
// Set connection pool settings
|
||||
db.SetMaxOpenConns(25)
|
||||
db.SetMaxIdleConns(5)
|
||||
db.SetConnMaxLifetime(5 * time.Minute)
|
||||
glog.V(0).Infof("credential postgres: connection established")
|
||||
|
||||
store.db = db
|
||||
|
||||
// Create tables if they don't exist
|
||||
if err := store.createTables(); err != nil {
|
||||
db.Close()
|
||||
store.db = nil
|
||||
glog.Errorf("credential postgres: failed to create tables: %v", err)
|
||||
return fmt.Errorf("failed to create tables: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: tables verified, store ready")
|
||||
|
||||
store.configured = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) createTables() error {
|
||||
// Create users table
|
||||
usersTable := `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
username VARCHAR(255) PRIMARY KEY,
|
||||
@@ -100,12 +137,10 @@ func (store *PostgresStore) createTables() error {
|
||||
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
||||
`
|
||||
|
||||
// Migration: Add policy_names column if it doesn't exist (for existing installations)
|
||||
addPolicyNamesColumn := `
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS policy_names JSONB DEFAULT '[]';
|
||||
`
|
||||
|
||||
// Create credentials table
|
||||
credentialsTable := `
|
||||
CREATE TABLE IF NOT EXISTS credentials (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -118,7 +153,6 @@ func (store *PostgresStore) createTables() error {
|
||||
CREATE INDEX IF NOT EXISTS idx_credentials_access_key ON credentials(access_key);
|
||||
`
|
||||
|
||||
// Create policies table
|
||||
policiesTable := `
|
||||
CREATE TABLE IF NOT EXISTS policies (
|
||||
name VARCHAR(255) PRIMARY KEY,
|
||||
@@ -129,7 +163,6 @@ func (store *PostgresStore) createTables() error {
|
||||
CREATE INDEX IF NOT EXISTS idx_policies_name ON policies(name);
|
||||
`
|
||||
|
||||
// Create service_accounts table
|
||||
serviceAccountsTable := `
|
||||
CREATE TABLE IF NOT EXISTS service_accounts (
|
||||
id VARCHAR(255) PRIMARY KEY,
|
||||
@@ -140,7 +173,18 @@ func (store *PostgresStore) createTables() error {
|
||||
);
|
||||
`
|
||||
|
||||
// Create groups table
|
||||
inlinePoliciesTable := `
|
||||
CREATE TABLE IF NOT EXISTS user_inline_policies (
|
||||
username VARCHAR(255) REFERENCES users(username) ON DELETE CASCADE,
|
||||
policy_name VARCHAR(255) NOT NULL,
|
||||
document JSONB NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (username, policy_name)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_inline_policies_username ON user_inline_policies(username);
|
||||
`
|
||||
|
||||
groupsTable := `
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
name VARCHAR(255) PRIMARY KEY,
|
||||
@@ -152,12 +196,10 @@ func (store *PostgresStore) createTables() error {
|
||||
);
|
||||
`
|
||||
|
||||
// Execute table creation
|
||||
if _, err := store.db.Exec(usersTable); err != nil {
|
||||
return fmt.Errorf("failed to create users table: %w", err)
|
||||
}
|
||||
|
||||
// Run migration to add policy_names column for existing installations
|
||||
if _, err := store.db.Exec(addPolicyNamesColumn); err != nil {
|
||||
return fmt.Errorf("failed to add policy_names column: %w", err)
|
||||
}
|
||||
@@ -174,17 +216,19 @@ func (store *PostgresStore) createTables() error {
|
||||
return fmt.Errorf("failed to create service_accounts table: %w", err)
|
||||
}
|
||||
|
||||
if _, err := store.db.Exec(inlinePoliciesTable); err != nil {
|
||||
return fmt.Errorf("failed to create user_inline_policies table: %w", err)
|
||||
}
|
||||
|
||||
if _, err := store.db.Exec(groupsTable); err != nil {
|
||||
return fmt.Errorf("failed to create groups table: %w", err)
|
||||
}
|
||||
|
||||
// Create index on groups disabled column for filtering
|
||||
groupsDisabledIndex := `CREATE INDEX IF NOT EXISTS idx_groups_disabled ON groups (disabled);`
|
||||
if _, err := store.db.Exec(groupsDisabledIndex); err != nil {
|
||||
return fmt.Errorf("failed to create groups disabled index: %w", err)
|
||||
}
|
||||
|
||||
// Create GIN index on groups members JSONB for membership lookups
|
||||
groupsMembersIndex := `CREATE INDEX IF NOT EXISTS idx_groups_members_gin ON groups USING GIN (members);`
|
||||
if _, err := store.db.Exec(groupsMembersIndex); err != nil {
|
||||
return fmt.Errorf("failed to create groups members index: %w", err)
|
||||
@@ -195,6 +239,7 @@ func (store *PostgresStore) createTables() error {
|
||||
|
||||
func (store *PostgresStore) Shutdown() {
|
||||
if store.db != nil {
|
||||
glog.V(0).Infof("credential postgres: shutting down")
|
||||
store.db.Close()
|
||||
store.db = nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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/seaweedfs/seaweedfs/weed/credential/filer_etc"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/credential/memory"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/credential/postgres"
|
||||
)
|
||||
|
||||
func TestInlinePolicyOperations(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
credentialManager, err := credential.NewCredentialManager(credential.StoreTypeMemory, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create credential manager: %v", err)
|
||||
}
|
||||
|
||||
store, ok := credentialManager.GetStore().(*memory.MemoryStore)
|
||||
if !ok {
|
||||
t.Fatal("Store is not a memory store")
|
||||
}
|
||||
|
||||
userName := "testuser"
|
||||
policyName := "read-bucket"
|
||||
doc := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{
|
||||
{
|
||||
Effect: policy_engine.PolicyEffectAllow,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::test-bucket/*"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Put
|
||||
if err := store.PutUserInlinePolicy(ctx, userName, policyName, doc); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
|
||||
// Get
|
||||
got, err := store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatal("GetUserInlinePolicy returned nil")
|
||||
}
|
||||
if got.Version != "2012-10-17" {
|
||||
t.Errorf("Expected version '2012-10-17', got '%s'", got.Version)
|
||||
}
|
||||
if len(got.Statement) != 1 {
|
||||
t.Errorf("Expected 1 statement, got %d", len(got.Statement))
|
||||
}
|
||||
|
||||
// Get non-existent
|
||||
missing, err := store.GetUserInlinePolicy(ctx, userName, "no-such-policy")
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy for missing policy failed: %v", err)
|
||||
}
|
||||
if missing != nil {
|
||||
t.Error("Expected nil for non-existent policy")
|
||||
}
|
||||
|
||||
// Put second policy, same user
|
||||
doc2 := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{
|
||||
{
|
||||
Effect: policy_engine.PolicyEffectAllow,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:PutObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::other-bucket/*"),
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := store.PutUserInlinePolicy(ctx, userName, "write-bucket", doc2); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy second policy failed: %v", err)
|
||||
}
|
||||
|
||||
// List
|
||||
names, err := store.ListUserInlinePolicies(ctx, userName)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserInlinePolicies failed: %v", err)
|
||||
}
|
||||
if len(names) != 2 {
|
||||
t.Errorf("Expected 2 policies, got %d", len(names))
|
||||
}
|
||||
|
||||
// List for non-existent user
|
||||
emptyNames, err := store.ListUserInlinePolicies(ctx, "nobody")
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserInlinePolicies for missing user failed: %v", err)
|
||||
}
|
||||
if len(emptyNames) != 0 {
|
||||
t.Errorf("Expected 0 policies for missing user, got %d", len(emptyNames))
|
||||
}
|
||||
|
||||
// LoadInlinePolicies (bulk)
|
||||
all, err := store.LoadInlinePolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadInlinePolicies failed: %v", err)
|
||||
}
|
||||
if len(all) != 1 {
|
||||
t.Errorf("Expected 1 user in LoadInlinePolicies, got %d", len(all))
|
||||
}
|
||||
if len(all[userName]) != 2 {
|
||||
t.Errorf("Expected 2 policies for user in LoadInlinePolicies, got %d", len(all[userName]))
|
||||
}
|
||||
|
||||
// Overwrite existing policy (upsert)
|
||||
updatedDoc := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{
|
||||
{
|
||||
Effect: policy_engine.PolicyEffectDeny,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::test-bucket/secret/*"),
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := store.PutUserInlinePolicy(ctx, userName, policyName, updatedDoc); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy overwrite failed: %v", err)
|
||||
}
|
||||
overwritten, err := store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy after overwrite failed: %v", err)
|
||||
}
|
||||
if overwritten.Statement[0].Effect != policy_engine.PolicyEffectDeny {
|
||||
t.Errorf("Expected Deny after overwrite, got %s", overwritten.Statement[0].Effect)
|
||||
}
|
||||
|
||||
// Delete one policy
|
||||
if err := store.DeleteUserInlinePolicy(ctx, userName, policyName); err != nil {
|
||||
t.Fatalf("DeleteUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
deleted, err := store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy after delete failed: %v", err)
|
||||
}
|
||||
if deleted != nil {
|
||||
t.Error("Expected nil after delete")
|
||||
}
|
||||
|
||||
// Remaining policy still there
|
||||
remaining, err := store.ListUserInlinePolicies(ctx, userName)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserInlinePolicies after delete failed: %v", err)
|
||||
}
|
||||
if len(remaining) != 1 {
|
||||
t.Errorf("Expected 1 remaining policy, got %d", len(remaining))
|
||||
}
|
||||
|
||||
// Delete last policy — user entry should be cleaned up
|
||||
if err := store.DeleteUserInlinePolicy(ctx, userName, "write-bucket"); err != nil {
|
||||
t.Fatalf("DeleteUserInlinePolicy last policy failed: %v", err)
|
||||
}
|
||||
allAfter, err := store.LoadInlinePolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadInlinePolicies after full cleanup failed: %v", err)
|
||||
}
|
||||
if len(allAfter) != 0 {
|
||||
t.Errorf("Expected empty LoadInlinePolicies after cleanup, got %d users", len(allAfter))
|
||||
}
|
||||
}
|
||||
|
||||
// TestMemoryRenameUserMovesIdentityAndPolicies exercises the new
|
||||
// credential.UserRenamer path on the memory store: the identity row,
|
||||
// its access keys, and any inline policies all have to land under the
|
||||
// new name in a single operation.
|
||||
func TestMemoryRenameUserMovesIdentityAndPolicies(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
cm, err := credential.NewCredentialManager(credential.StoreTypeMemory, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create credential manager: %v", err)
|
||||
}
|
||||
|
||||
const (
|
||||
oldName = "renameme"
|
||||
newName = "renamed"
|
||||
policyName = "ReadBucket"
|
||||
)
|
||||
|
||||
cred := &iam_pb.Credential{AccessKey: "AKIA-RENAME", SecretKey: "secret"}
|
||||
if err := cm.CreateUser(ctx, &iam_pb.Identity{
|
||||
Name: oldName,
|
||||
Credentials: []*iam_pb.Credential{cred},
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateUser failed: %v", err)
|
||||
}
|
||||
doc := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{{
|
||||
Effect: policy_engine.PolicyEffectAllow,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::bucket/*"),
|
||||
}},
|
||||
}
|
||||
if err := cm.PutUserInlinePolicy(ctx, oldName, policyName, doc); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
|
||||
supported, err := cm.RenameUser(ctx, oldName, newName)
|
||||
if err != nil {
|
||||
t.Fatalf("RenameUser failed: %v", err)
|
||||
}
|
||||
if !supported {
|
||||
t.Fatal("memory store should implement credential.UserRenamer")
|
||||
}
|
||||
|
||||
if _, err := cm.GetUser(ctx, oldName); err == nil {
|
||||
t.Errorf("expected old user %q to be gone after rename", oldName)
|
||||
}
|
||||
got, err := cm.GetUser(ctx, newName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUser(%q) after rename failed: %v", newName, err)
|
||||
}
|
||||
if got.Name != newName {
|
||||
t.Errorf("renamed identity name = %q, want %q", got.Name, newName)
|
||||
}
|
||||
if len(got.Credentials) != 1 || got.Credentials[0].AccessKey != cred.AccessKey {
|
||||
t.Errorf("renamed identity should still own its access key, got %+v", got.Credentials)
|
||||
}
|
||||
|
||||
gotByKey, err := cm.GetUserByAccessKey(ctx, cred.AccessKey)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserByAccessKey failed: %v", err)
|
||||
}
|
||||
if gotByKey == nil || gotByKey.Name != newName {
|
||||
t.Errorf("access key should resolve to %q, got %+v", newName, gotByKey)
|
||||
}
|
||||
|
||||
gotPolicy, err := cm.GetUserInlinePolicy(ctx, newName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy under new name failed: %v", err)
|
||||
}
|
||||
if gotPolicy == nil {
|
||||
t.Fatal("inline policy should be readable under the new name")
|
||||
}
|
||||
if gotPolicy.Statement[0].Effect != policy_engine.PolicyEffectAllow {
|
||||
t.Errorf("policy effect: got %q want %q", gotPolicy.Statement[0].Effect, policy_engine.PolicyEffectAllow)
|
||||
}
|
||||
stalePolicy, err := cm.GetUserInlinePolicy(ctx, oldName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy under old name failed: %v", err)
|
||||
}
|
||||
if stalePolicy != nil {
|
||||
t.Errorf("inline policy should be gone from the old name, got %+v", stalePolicy)
|
||||
}
|
||||
|
||||
// Clean up — NewCredentialManager hands out a shared MemoryStore singleton
|
||||
// so leftover state would leak into TestMemoryStoreIntegration.
|
||||
if err := cm.DeleteUserInlinePolicy(ctx, newName, policyName); err != nil {
|
||||
t.Fatalf("DeleteUserInlinePolicy cleanup failed: %v", err)
|
||||
}
|
||||
if err := cm.DeleteUser(ctx, newName); err != nil {
|
||||
t.Fatalf("DeleteUser cleanup failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -2,49 +2,13 @@ package postgres
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/pgxutil"
|
||||
)
|
||||
|
||||
// OpenPGXDB parses the given DSN into a pgx ConnConfig, applies PgBouncer
|
||||
// compatibility settings when requested, opens a *sql.DB via
|
||||
// stdlib.OpenDB, and verifies it with Ping.
|
||||
//
|
||||
// In pgx/v5 the prefer_simple_protocol DSN parameter was removed, so simple
|
||||
// protocol mode must be configured on the ConnConfig via
|
||||
// DefaultQueryExecMode. We use stdlib.OpenDB(config) rather than
|
||||
// RegisterConnConfig + sql.Open so we don't leak entries in stdlib's global
|
||||
// connection config map on either success or failure paths.
|
||||
//
|
||||
// adaptedSqlUrl is used only for error messages (the caller is expected to
|
||||
// have redacted any password).
|
||||
// OpenPGXDB is a thin alias kept for callers (notably the postgres2 filer
|
||||
// store) that already depend on this entry point. New code should use
|
||||
// pgxutil.OpenDB directly.
|
||||
func OpenPGXDB(sqlUrl, adaptedSqlUrl string, pgbouncerCompatible bool, maxIdle, maxOpen, maxLifetimeSeconds int) (*sql.DB, error) {
|
||||
connConfig, parseErr := pgx.ParseConfig(sqlUrl)
|
||||
if parseErr != nil {
|
||||
return nil, fmt.Errorf("can not parse connection config for %s error:%v", adaptedSqlUrl, parseErr)
|
||||
}
|
||||
|
||||
// PgBouncer compatibility: use the simple query protocol and disable
|
||||
// statement caching. This avoids prepared statement issues with
|
||||
// PgBouncer's transaction pooling mode.
|
||||
if pgbouncerCompatible {
|
||||
connConfig.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
|
||||
connConfig.StatementCacheCapacity = 0
|
||||
connConfig.DescriptionCacheCapacity = 0
|
||||
}
|
||||
|
||||
db := stdlib.OpenDB(*connConfig)
|
||||
db.SetMaxIdleConns(maxIdle)
|
||||
db.SetMaxOpenConns(maxOpen)
|
||||
db.SetConnMaxLifetime(time.Duration(maxLifetimeSeconds) * time.Second)
|
||||
|
||||
if err := db.Ping(); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("connect to %s error:%v", adaptedSqlUrl, err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
return pgxutil.OpenDB(sqlUrl, adaptedSqlUrl, pgbouncerCompatible, maxIdle, maxOpen, maxLifetimeSeconds)
|
||||
}
|
||||
+20
-4
@@ -606,13 +606,15 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, fuse.Status)
|
||||
// the local store when an open file handle or pending async flush
|
||||
// confirms the entry is genuinely local-only; otherwise a stale
|
||||
// cache hit could resurrect a deleted/renamed entry.
|
||||
if inode, inodeFound := wfs.inodeToPath.GetInode(fullpath); inodeFound {
|
||||
hasDirtyHandle := false
|
||||
inode, inodeFound := wfs.inodeToPath.GetInode(fullpath)
|
||||
hasDirtyHandle := false
|
||||
hasPendingFlush := false
|
||||
if inodeFound {
|
||||
if fh, fhFound := wfs.fhMap.FindFileHandle(inode); fhFound && fh.dirtyMetadata {
|
||||
hasDirtyHandle = true
|
||||
}
|
||||
wfs.pendingAsyncFlushMu.Lock()
|
||||
_, hasPendingFlush := wfs.pendingAsyncFlush[inode]
|
||||
_, hasPendingFlush = wfs.pendingAsyncFlush[inode]
|
||||
wfs.pendingAsyncFlushMu.Unlock()
|
||||
|
||||
if hasDirtyHandle || hasPendingFlush {
|
||||
@@ -622,7 +624,21 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, fuse.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
glog.V(4).Infof("lookupEntry not found %s", fullpath)
|
||||
if inodeFound {
|
||||
// Filer reports ErrNotFound for a path the kernel/local map
|
||||
// still tracks, with no in-flight create or flush to excuse
|
||||
// it. Log loudly (Warningf, not V(4)) so flake captures show
|
||||
// up without -v=4 — and include layer-by-layer state so the
|
||||
// next failed run pinpoints which layer dropped the entry.
|
||||
localPresent := false
|
||||
if localEntry, localErr := wfs.metaCache.FindEntry(context.Background(), fullpath); localErr == nil && localEntry != nil {
|
||||
localPresent = true
|
||||
}
|
||||
glog.Warningf("lookupEntry: filer ErrNotFound for tracked path %s (inode=%d dirtyHandle=%v pendingFlush=%v localCache=%v dirCached=%v) — possible coherence bug",
|
||||
fullpath, inode, hasDirtyHandle, hasPendingFlush, localPresent, wfs.metaCache.IsDirectoryCached(dirPath))
|
||||
} else {
|
||||
glog.V(4).Infof("lookupEntry not found %s", fullpath)
|
||||
}
|
||||
return nil, fuse.ENOENT
|
||||
}
|
||||
glog.Warningf("lookupEntry GetEntry %s: %v", fullpath, err)
|
||||
|
||||
@@ -439,10 +439,28 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction
|
||||
if post_err != nil {
|
||||
if strings.Contains(post_err.Error(), "connection reset by peer") ||
|
||||
strings.Contains(post_err.Error(), "use of closed network connection") {
|
||||
glog.V(1).InfofCtx(ctx, "repeat error upload request %s: %v", option.UploadUrl, postErr)
|
||||
glog.V(1).InfofCtx(ctx, "repeat error upload request %s: %v", option.UploadUrl, post_err)
|
||||
stats.FilerHandlerCounter.WithLabelValues(stats.RepeatErrorUploadContent).Inc()
|
||||
resp, post_err = uploader.httpClient.Do(req)
|
||||
defer util_http.CloseResponse(resp)
|
||||
// The first attempt already consumed (or partially consumed) the
|
||||
// body, so retrying with the same *http.Request would send 0 bytes
|
||||
// and Go's transport would surface "ContentLength=N with Body
|
||||
// length 0". http.NewRequestWithContext sets GetBody for
|
||||
// *bytes.Reader bodies; use it to attach a fresh body for retry.
|
||||
// If we can't rewind, skip the inner retry and let the outer
|
||||
// retriedUploadData loop reissue the request with a fresh body —
|
||||
// retrying here with a consumed body would mask the original
|
||||
// "connection reset" error with a misleading "Body length 0".
|
||||
if req.GetBody != nil {
|
||||
if newBody, gbErr := req.GetBody(); gbErr == nil {
|
||||
req.Body = newBody
|
||||
resp, post_err = uploader.httpClient.Do(req)
|
||||
defer util_http.CloseResponse(resp)
|
||||
} else {
|
||||
glog.V(1).InfofCtx(ctx, "skip inner retry for %s: GetBody returned %v", option.UploadUrl, gbErr)
|
||||
}
|
||||
} else {
|
||||
glog.V(1).InfofCtx(ctx, "skip inner retry for %s: req.GetBody is nil", option.UploadUrl)
|
||||
}
|
||||
}
|
||||
}
|
||||
if post_err != nil {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -122,3 +125,76 @@ func TestUploadWithRetryDataReassignsOnVolumeSizeExceeded(t *testing.T) {
|
||||
t.Fatalf("unexpected upload call sequence: %#v", httpClient.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// bodyCapturingHTTPClient drains req.Body on every Do, optionally failing the
|
||||
// first attempt with a transport error so we can verify upload_content rewinds
|
||||
// the body before retrying.
|
||||
type bodyCapturingHTTPClient struct {
|
||||
mu sync.Mutex
|
||||
bodies [][]byte
|
||||
failFirst string
|
||||
successJSON string
|
||||
}
|
||||
|
||||
func (c *bodyCapturingHTTPClient) Do(req *http.Request) (*http.Response, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
var captured []byte
|
||||
if req.Body != nil {
|
||||
b, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
captured = b
|
||||
}
|
||||
c.bodies = append(c.bodies, captured)
|
||||
|
||||
if len(c.bodies) == 1 && c.failFirst != "" {
|
||||
return nil, errors.New(c.failFirst)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusCreated,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(c.successJSON)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// TestUploadRewindsBodyOnConnectionReset reproduces issue #9139 follow-up:
|
||||
// when the inner Do retry fires on a "connection reset" / "closed network"
|
||||
// error, the *bytes.Reader body has already been consumed, so without an
|
||||
// explicit rewind the second attempt sends 0 bytes and Go's transport surfaces
|
||||
// "ContentLength=N with Body length 0".
|
||||
func TestUploadRewindsBodyOnConnectionReset(t *testing.T) {
|
||||
for _, transient := range []string{
|
||||
"connection reset by peer",
|
||||
"use of closed network connection",
|
||||
} {
|
||||
t.Run(transient, func(t *testing.T) {
|
||||
client := &bodyCapturingHTTPClient{
|
||||
failFirst: transient,
|
||||
successJSON: `{"name":"test.bin","size":42}`,
|
||||
}
|
||||
uploader := newUploader(client)
|
||||
|
||||
payload := bytes.Repeat([]byte("payload-"), 256) // 2048 bytes
|
||||
_, err := uploader.UploadData(context.Background(), payload, &UploadOption{
|
||||
UploadUrl: "http://volume/1,abc",
|
||||
Filename: "test.bin",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("upload should succeed after inner retry, got %v", err)
|
||||
}
|
||||
if len(client.bodies) != 2 {
|
||||
t.Fatalf("expected 2 Do attempts, got %d", len(client.bodies))
|
||||
}
|
||||
if len(client.bodies[0]) == 0 {
|
||||
t.Fatalf("first attempt sent an empty body; test setup wrong")
|
||||
}
|
||||
if !bytes.Equal(client.bodies[0], client.bodies[1]) {
|
||||
t.Fatalf("retry body length=%d differs from first attempt length=%d (body was not rewound)",
|
||||
len(client.bodies[1]), len(client.bodies[0]))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
// Package daemon hosts the standalone `weed pushdown` process.
|
||||
// It owns gRPC server bootstrap, the filer client used by later
|
||||
// milestones to read Parquet data and side-index blobs, and the
|
||||
// process-level config plumbing.
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
// Config controls how the daemon listens, talks to the filer, and
|
||||
// validates incoming requests. Caller (the `weed pushdown` command)
|
||||
// builds this from CLI flags.
|
||||
type Config struct {
|
||||
// IP is the bind address for the gRPC listener. Empty defaults to
|
||||
// the auto-detected host address.
|
||||
IP string
|
||||
|
||||
// Port is the gRPC listener port.
|
||||
Port int
|
||||
|
||||
// FilerAddresses is the comma-resolved list of filer endpoints
|
||||
// the daemon talks to for data reads and (in M3) catalog access.
|
||||
// Required: at least one entry.
|
||||
FilerAddresses []pb.ServerAddress
|
||||
|
||||
// TrustMode is the request-validation strictness. Default is
|
||||
// "catalog-validated"; "connector-trusted" is a developer-only
|
||||
// mode that the daemon refuses to accept in production builds
|
||||
// (see ConnectorTrustedAck).
|
||||
TrustMode parquet_pushdown.TrustMode
|
||||
|
||||
// ConnectorTrustedAck is the explicit acknowledgement required to
|
||||
// run with TrustMode == TrustModeConnectorTrusted. The flag exists
|
||||
// to make the dev-only mode awkward to enable by accident.
|
||||
ConnectorTrustedAck bool
|
||||
|
||||
// Version is reported in PingResponse / PushdownStats. Caller
|
||||
// usually fills this with weed/util/version.Version().
|
||||
Version string
|
||||
}
|
||||
|
||||
// Validate checks the config before the daemon starts.
|
||||
func (c *Config) Validate() error {
|
||||
if c.Port <= 0 || c.Port > 65535 {
|
||||
return fmt.Errorf("port %d is out of range", c.Port)
|
||||
}
|
||||
if len(c.FilerAddresses) == 0 {
|
||||
return errors.New("at least one filer address is required")
|
||||
}
|
||||
switch c.TrustMode {
|
||||
case "", parquet_pushdown.TrustModeCatalogValidated:
|
||||
c.TrustMode = parquet_pushdown.TrustModeCatalogValidated
|
||||
case parquet_pushdown.TrustModeConnectorTrusted:
|
||||
if !c.ConnectorTrustedAck {
|
||||
return errors.New("connector-trusted is a developer-only trust mode; pass -dev.connector_trusted_ack to enable")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown trust mode %q", c.TrustMode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
func baseConfig() Config {
|
||||
return Config{
|
||||
IP: "127.0.0.1",
|
||||
Port: 18888,
|
||||
FilerAddresses: []pb.ServerAddress{"localhost:8888"},
|
||||
Version: "test",
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_ValidateOK(t *testing.T) {
|
||||
c := baseConfig()
|
||||
if err := c.Validate(); err != nil {
|
||||
t.Fatalf("expected ok, got %v", err)
|
||||
}
|
||||
if c.TrustMode != parquet_pushdown.TrustModeCatalogValidated {
|
||||
t.Errorf("default trust mode = %q, want %q", c.TrustMode, parquet_pushdown.TrustModeCatalogValidated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_RejectsBadPort(t *testing.T) {
|
||||
c := baseConfig()
|
||||
c.Port = 0
|
||||
if err := c.Validate(); err == nil {
|
||||
t.Fatal("expected error for port=0")
|
||||
}
|
||||
c.Port = 70000
|
||||
if err := c.Validate(); err == nil {
|
||||
t.Fatal("expected error for port>65535")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_RequiresFiler(t *testing.T) {
|
||||
c := baseConfig()
|
||||
c.FilerAddresses = nil
|
||||
if err := c.Validate(); err == nil {
|
||||
t.Fatal("expected error when filer addresses empty")
|
||||
}
|
||||
}
|
||||
|
||||
// Connector-trusted is dev-only and must require an explicit
|
||||
// acknowledgement flag. Operators must not be able to flip it on by
|
||||
// passing -trust=connector-trusted alone.
|
||||
func TestConfig_ConnectorTrustedRequiresAck(t *testing.T) {
|
||||
c := baseConfig()
|
||||
c.TrustMode = parquet_pushdown.TrustModeConnectorTrusted
|
||||
err := c.Validate()
|
||||
if err == nil {
|
||||
t.Fatal("expected error when connector-trusted lacks ack")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "connector_trusted_ack") {
|
||||
t.Errorf("error %q should mention the ack flag", err.Error())
|
||||
}
|
||||
|
||||
c.ConnectorTrustedAck = true
|
||||
if err := c.Validate(); err != nil {
|
||||
t.Fatalf("connector-trusted with ack should pass, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_RejectsUnknownTrustMode(t *testing.T) {
|
||||
c := baseConfig()
|
||||
c.TrustMode = parquet_pushdown.TrustMode("nonsense")
|
||||
if err := c.Validate(); err == nil {
|
||||
t.Fatal("expected error for unknown trust mode")
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// filerClient is a thin handle around the daemon's filer endpoints.
|
||||
// M0 only uses it to confirm filer reachability at startup; later
|
||||
// milestones add read paths for Parquet data and side-index blobs.
|
||||
type filerClient struct {
|
||||
addresses []pb.ServerAddress
|
||||
grpcDialOption grpc.DialOption
|
||||
}
|
||||
|
||||
func newFilerClient(addresses []pb.ServerAddress, grpcDialOption grpc.DialOption) *filerClient {
|
||||
return &filerClient{addresses: addresses, grpcDialOption: grpcDialOption}
|
||||
}
|
||||
|
||||
// waitUntilReachable blocks until the daemon can complete a
|
||||
// GetFilerConfiguration RPC against any of its configured filer
|
||||
// addresses, or the context is cancelled. Mirrors the iam command's
|
||||
// startup-time filer probe.
|
||||
func (c *filerClient) waitUntilReachable(ctx context.Context) error {
|
||||
for {
|
||||
err := pb.WithOneOfGrpcFilerClients(false, c.addresses, c.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, getErr := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
|
||||
return getErr
|
||||
})
|
||||
if err == nil {
|
||||
glog.V(0).Infof("pushdown daemon connected to filers %v", c.addresses)
|
||||
return nil
|
||||
}
|
||||
glog.V(0).Infof("pushdown daemon waiting for filers %v: %v", c.addresses, err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("filer reachability wait cancelled: %w", ctx.Err())
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
pbpushdown "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/grace"
|
||||
)
|
||||
|
||||
// Run starts the pushdown daemon. It blocks until the gRPC server
|
||||
// returns (graceful shutdown on SIGTERM, or error from Serve). Always
|
||||
// validates the config first.
|
||||
func Run(cfg Config) error {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return fmt.Errorf("pushdown config: %w", err)
|
||||
}
|
||||
|
||||
util.LoadSecurityConfiguration()
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
|
||||
// Probe the filer until reachable so we fail fast on bad config
|
||||
// and emit a clear "waiting for filers" log otherwise. Bound the
|
||||
// probe so the daemon doesn't sit forever if the operator hands
|
||||
// in an unreachable filer.
|
||||
probeCtx, probeCancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer probeCancel()
|
||||
fc := newFilerClient(cfg.FilerAddresses, grpcDialOption)
|
||||
if err := fc.waitUntilReachable(probeCtx); err != nil {
|
||||
return fmt.Errorf("filer probe failed: %w", err)
|
||||
}
|
||||
|
||||
svc := parquet_pushdown.New(parquet_pushdown.Options{
|
||||
Version: cfg.Version,
|
||||
TrustMode: cfg.TrustMode,
|
||||
// M1 uses LocalLoader; the filer-backed Loader lands when the
|
||||
// catalog-validated path needs to fetch real data files (M2+).
|
||||
Loader: parquet_pushdown.LocalLoader{},
|
||||
})
|
||||
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners(cfg.IP, cfg.Port, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen on grpc port %d: %w", cfg.Port, err)
|
||||
}
|
||||
|
||||
grpcS := pb.NewGrpcServer()
|
||||
pbpushdown.RegisterSeaweedParquetPushdownServer(grpcS, svc)
|
||||
reflection.Register(grpcS)
|
||||
|
||||
grace.OnInterrupt(grpcS.GracefulStop)
|
||||
|
||||
if localL != nil {
|
||||
localGrpcS := pb.NewGrpcServer()
|
||||
pbpushdown.RegisterSeaweedParquetPushdownServer(localGrpcS, svc)
|
||||
reflection.Register(localGrpcS)
|
||||
grace.OnInterrupt(localGrpcS.GracefulStop)
|
||||
go serve(localGrpcS, localL, "pushdown localhost")
|
||||
}
|
||||
|
||||
glog.V(0).Infof("pushdown daemon listening on %s:%d (trust=%s)", cfg.IP, cfg.Port, cfg.TrustMode)
|
||||
return serve(grpcS, grpcL, "pushdown")
|
||||
}
|
||||
|
||||
func serve(s *grpc.Server, l net.Listener, label string) error {
|
||||
if err := s.Serve(l); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("%s server serve error: %v", label, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package footer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
|
||||
lru "github.com/hashicorp/golang-lru"
|
||||
)
|
||||
|
||||
// Identity uniquely names a Parquet file's content per the design's
|
||||
// Index Consistency rules. The cache key is the same identity used
|
||||
// to invalidate side indexes when a file's content changes.
|
||||
//
|
||||
// Iceberg manifest fields are preferred when available (Path,
|
||||
// SizeBytes, RecordCount + ETag) because they pin the file by both
|
||||
// its bytes and its declared row count — defending against the
|
||||
// pathological case where a write produces a file with the same
|
||||
// length but different content. ETag fills in for raw-S3 access
|
||||
// without an Iceberg manifest. Mtime is intentionally not part of
|
||||
// identity (see PARQUET_PUSHDOWN_DESIGN.md "Index Consistency").
|
||||
type Identity struct {
|
||||
Path string
|
||||
SizeBytes int64
|
||||
RecordCount int64 // 0 when unknown (non-Iceberg-managed files)
|
||||
ETag string
|
||||
}
|
||||
|
||||
// Cache is a concurrent LRU of parsed footers keyed by Identity.
|
||||
// Capacity is in entries, not bytes; Phase 1 footers are small
|
||||
// enough that entry-count budgeting is easier to reason about.
|
||||
type Cache struct {
|
||||
c *lru.Cache
|
||||
hits atomic.Int64
|
||||
misses atomic.Int64
|
||||
}
|
||||
|
||||
// NewCache returns a Cache holding up to size entries. Returns an
|
||||
// error when size is non-positive (a zero-size LRU is too easy to
|
||||
// misconfigure to silently disable caching).
|
||||
func NewCache(size int) (*Cache, error) {
|
||||
if size <= 0 {
|
||||
return nil, fmt.Errorf("cache size must be positive, got %d", size)
|
||||
}
|
||||
c, err := lru.New(size)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new lru: %w", err)
|
||||
}
|
||||
return &Cache{c: c}, nil
|
||||
}
|
||||
|
||||
// Get returns the cached ParsedFooter for id, or nil + false on miss.
|
||||
func (c *Cache) Get(id Identity) (*ParsedFooter, bool) {
|
||||
if v, ok := c.c.Get(id); ok {
|
||||
c.hits.Add(1)
|
||||
return v.(*ParsedFooter), true
|
||||
}
|
||||
c.misses.Add(1)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Add stores pf under id. Existing entries are replaced.
|
||||
func (c *Cache) Add(id Identity, pf *ParsedFooter) {
|
||||
c.c.Add(id, pf)
|
||||
}
|
||||
|
||||
// Stats returns cumulative hit and miss counters.
|
||||
func (c *Cache) Stats() (hits, misses int64) {
|
||||
return c.hits.Load(), c.misses.Load()
|
||||
}
|
||||
|
||||
// Len returns the current entry count.
|
||||
func (c *Cache) Len() int {
|
||||
return c.c.Len()
|
||||
}
|
||||
|
||||
// GetOrLoad atomically returns a cached entry or invokes load to
|
||||
// produce one and inserts it. Two concurrent loads for the same id
|
||||
// may both call load — the cache is not a singleflight; that
|
||||
// optimization is deferred until profiling shows it matters. The
|
||||
// returned pointer is the one stored in the cache so callers must
|
||||
// treat it as read-only.
|
||||
func (c *Cache) GetOrLoad(id Identity, load func() (*ParsedFooter, error)) (*ParsedFooter, error) {
|
||||
if pf, ok := c.Get(id); ok {
|
||||
return pf, nil
|
||||
}
|
||||
if load == nil {
|
||||
return nil, errors.New("nil load func")
|
||||
}
|
||||
pf, err := load()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pf == nil {
|
||||
return nil, errors.New("load returned nil ParsedFooter")
|
||||
}
|
||||
c.Add(id, pf)
|
||||
return pf, nil
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package footer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCache_NewSizeRejectsZero(t *testing.T) {
|
||||
if _, err := NewCache(0); err == nil {
|
||||
t.Error("size=0 should be rejected")
|
||||
}
|
||||
if _, err := NewCache(-1); err == nil {
|
||||
t.Error("negative size should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_HitsAndMissesTracked(t *testing.T) {
|
||||
c, err := NewCache(8)
|
||||
if err != nil {
|
||||
t.Fatalf("new: %v", err)
|
||||
}
|
||||
id := Identity{Path: "a", SizeBytes: 1}
|
||||
pf := &ParsedFooter{NumRows: 10}
|
||||
|
||||
if _, ok := c.Get(id); ok {
|
||||
t.Fatal("first Get should miss")
|
||||
}
|
||||
c.Add(id, pf)
|
||||
if got, ok := c.Get(id); !ok || got != pf {
|
||||
t.Fatalf("expected cached pointer, got=%v ok=%v", got, ok)
|
||||
}
|
||||
hits, misses := c.Stats()
|
||||
if hits != 1 || misses != 1 {
|
||||
t.Errorf("hits=%d misses=%d, want 1,1", hits, misses)
|
||||
}
|
||||
}
|
||||
|
||||
// Two distinct identities must not alias. Same path, different size
|
||||
// is still a different file from the cache's POV.
|
||||
func TestCache_IdentityIsCompositeKey(t *testing.T) {
|
||||
c, err := NewCache(8)
|
||||
if err != nil {
|
||||
t.Fatalf("new: %v", err)
|
||||
}
|
||||
a := Identity{Path: "x", SizeBytes: 100, RecordCount: 1}
|
||||
b := Identity{Path: "x", SizeBytes: 200, RecordCount: 1}
|
||||
c.Add(a, &ParsedFooter{NumRows: 1})
|
||||
c.Add(b, &ParsedFooter{NumRows: 2})
|
||||
|
||||
gotA, _ := c.Get(a)
|
||||
gotB, _ := c.Get(b)
|
||||
if gotA == gotB {
|
||||
t.Errorf("entries with different sizes must not alias")
|
||||
}
|
||||
if gotA.NumRows != 1 || gotB.NumRows != 2 {
|
||||
t.Errorf("entries swapped: gotA=%d gotB=%d", gotA.NumRows, gotB.NumRows)
|
||||
}
|
||||
}
|
||||
|
||||
// Eviction is the LRU's job; the test just verifies the cache obeys
|
||||
// its size cap and doesn't grow without bound.
|
||||
func TestCache_EvictsAboveCap(t *testing.T) {
|
||||
c, err := NewCache(2)
|
||||
if err != nil {
|
||||
t.Fatalf("new: %v", err)
|
||||
}
|
||||
c.Add(Identity{Path: "a", SizeBytes: 1}, &ParsedFooter{NumRows: 1})
|
||||
c.Add(Identity{Path: "b", SizeBytes: 1}, &ParsedFooter{NumRows: 2})
|
||||
c.Add(Identity{Path: "c", SizeBytes: 1}, &ParsedFooter{NumRows: 3})
|
||||
|
||||
if got := c.Len(); got != 2 {
|
||||
t.Fatalf("Len = %d, want 2 after eviction", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_GetOrLoadCachesAndDedupes(t *testing.T) {
|
||||
c, err := NewCache(8)
|
||||
if err != nil {
|
||||
t.Fatalf("new: %v", err)
|
||||
}
|
||||
id := Identity{Path: "a", SizeBytes: 1}
|
||||
|
||||
calls := 0
|
||||
load := func() (*ParsedFooter, error) {
|
||||
calls++
|
||||
return &ParsedFooter{NumRows: 42}, nil
|
||||
}
|
||||
|
||||
first, err := c.GetOrLoad(id, load)
|
||||
if err != nil {
|
||||
t.Fatalf("first GetOrLoad: %v", err)
|
||||
}
|
||||
second, err := c.GetOrLoad(id, load)
|
||||
if err != nil {
|
||||
t.Fatalf("second GetOrLoad: %v", err)
|
||||
}
|
||||
if first != second {
|
||||
t.Errorf("second GetOrLoad returned different pointer")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Errorf("load called %d times, want 1", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_GetOrLoadPropagatesError(t *testing.T) {
|
||||
c, err := NewCache(8)
|
||||
if err != nil {
|
||||
t.Fatalf("new: %v", err)
|
||||
}
|
||||
wantErr := errors.New("io boom")
|
||||
_, err = c.GetOrLoad(Identity{Path: "a"}, func() (*ParsedFooter, error) { return nil, wantErr })
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Errorf("err = %v, want %v", err, wantErr)
|
||||
}
|
||||
if c.Len() != 0 {
|
||||
t.Errorf("failed load should not insert; Len=%d", c.Len())
|
||||
}
|
||||
}
|
||||
|
||||
// Parallel reads on the same key should all observe a hit after the
|
||||
// first writer wins, and the cache must not race-detect.
|
||||
func TestCache_ConcurrentSafe(t *testing.T) {
|
||||
c, err := NewCache(64)
|
||||
if err != nil {
|
||||
t.Fatalf("new: %v", err)
|
||||
}
|
||||
id := Identity{Path: "a", SizeBytes: 1}
|
||||
c.Add(id, &ParsedFooter{NumRows: 1})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 32; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for k := 0; k < 256; k++ {
|
||||
_, _ = c.Get(id)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
// Package footer holds the parsed-footer cache and the parser that
|
||||
// fills it. Phase 1 of the dev plan: parsed-footer cache + file/range-
|
||||
// level pushdown. Page-level (ColumnIndex/OffsetIndex) consumption
|
||||
// lands in M6; for M1 we capture the column-chunk byte ranges that
|
||||
// file/range-level pushdown needs.
|
||||
package footer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/parquet-go/parquet-go/format"
|
||||
)
|
||||
|
||||
// ParsedFooter is the daemon's compact, cache-friendly view of a
|
||||
// Parquet file's footer. It carries only the fields M1 actually
|
||||
// consumes; later milestones extend it (ColumnIndex / OffsetIndex,
|
||||
// statistics, bloom-filter offsets).
|
||||
type ParsedFooter struct {
|
||||
NumRows int64
|
||||
NumCols int
|
||||
NumGroups int
|
||||
|
||||
// ColumnPaths is the dotted path-in-schema for each leaf column,
|
||||
// in the canonical order parquet-go assigns to the file.
|
||||
ColumnPaths []string
|
||||
|
||||
// RowGroups[i] holds the byte ranges and row count for row group i.
|
||||
RowGroups []RowGroupRanges
|
||||
}
|
||||
|
||||
// RowGroupRanges enumerates the column chunks of one row group, in
|
||||
// the canonical column order.
|
||||
type RowGroupRanges struct {
|
||||
NumRows int64
|
||||
ColumnChunks []ColumnChunkRange
|
||||
}
|
||||
|
||||
// ColumnChunkRange is the byte range to read for one column chunk in
|
||||
// one row group, including the dictionary page region when present.
|
||||
//
|
||||
// Iceberg-style page-level pruning narrows reads further; M1 returns
|
||||
// the full column-chunk byte range. Including the dictionary-page
|
||||
// prefix when DictionaryPageOffset > 0 follows the rule from the
|
||||
// design's Page-Level Index section: the dictionary page is not in
|
||||
// OffsetIndex but must be fetched whenever any data page is read.
|
||||
type ColumnChunkRange struct {
|
||||
Path []string
|
||||
Offset int64
|
||||
Length int64
|
||||
NumValues int64
|
||||
TotalCompSize int64
|
||||
}
|
||||
|
||||
// ParseFromReader reads only the footer of a Parquet file and
|
||||
// returns the projection used by file/range-level pushdown.
|
||||
//
|
||||
// SkipPageIndex is set: M1 does not need ColumnIndex/OffsetIndex,
|
||||
// and skipping them avoids two extra reads per parse for files that
|
||||
// have page indexes written. M6 will turn this back on for the page-
|
||||
// level pruning milestone.
|
||||
func ParseFromReader(r io.ReaderAt, size int64) (*ParsedFooter, error) {
|
||||
if r == nil {
|
||||
return nil, errors.New("nil reader")
|
||||
}
|
||||
if size <= 0 {
|
||||
return nil, fmt.Errorf("invalid size %d", size)
|
||||
}
|
||||
|
||||
pf, err := parquet.OpenFile(r, size, parquet.SkipPageIndex(true), parquet.SkipBloomFilters(true))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open parquet footer: %w", err)
|
||||
}
|
||||
|
||||
md := pf.Metadata()
|
||||
out := &ParsedFooter{
|
||||
NumRows: md.NumRows,
|
||||
NumGroups: len(md.RowGroups),
|
||||
RowGroups: make([]RowGroupRanges, len(md.RowGroups)),
|
||||
}
|
||||
|
||||
// All row groups share the same leaf-column layout; sample row
|
||||
// group 0 to get column paths and column count.
|
||||
if len(md.RowGroups) > 0 {
|
||||
out.NumCols = len(md.RowGroups[0].Columns)
|
||||
out.ColumnPaths = make([]string, out.NumCols)
|
||||
for j, c := range md.RowGroups[0].Columns {
|
||||
out.ColumnPaths[j] = joinPath(c.MetaData.PathInSchema)
|
||||
}
|
||||
}
|
||||
|
||||
for i, rg := range md.RowGroups {
|
||||
out.RowGroups[i].NumRows = rg.NumRows
|
||||
out.RowGroups[i].ColumnChunks = make([]ColumnChunkRange, len(rg.Columns))
|
||||
for j, c := range rg.Columns {
|
||||
start, length := columnChunkBytes(&c)
|
||||
out.RowGroups[i].ColumnChunks[j] = ColumnChunkRange{
|
||||
Path: c.MetaData.PathInSchema,
|
||||
Offset: start,
|
||||
Length: length,
|
||||
NumValues: c.MetaData.NumValues,
|
||||
TotalCompSize: c.MetaData.TotalCompressedSize,
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// columnChunkBytes returns the (offset, length) of the contiguous
|
||||
// byte region that a reader needs to fetch to consume this column
|
||||
// chunk: the dictionary page (when present) plus all data pages.
|
||||
//
|
||||
// parquet-go exposes DictionaryPageOffset as the start of the
|
||||
// dictionary page when one exists, otherwise zero, and DataPageOffset
|
||||
// as the start of the first data page. The end of the chunk is
|
||||
// `start + TotalCompressedSize`.
|
||||
func columnChunkBytes(c *format.ColumnChunk) (int64, int64) {
|
||||
start := c.MetaData.DataPageOffset
|
||||
if dict := c.MetaData.DictionaryPageOffset; dict > 0 && dict < start {
|
||||
start = dict
|
||||
}
|
||||
return start, c.MetaData.TotalCompressedSize
|
||||
}
|
||||
|
||||
func joinPath(parts []string) string {
|
||||
switch len(parts) {
|
||||
case 0:
|
||||
return ""
|
||||
case 1:
|
||||
return parts[0]
|
||||
}
|
||||
out := parts[0]
|
||||
for _, p := range parts[1:] {
|
||||
out += "." + p
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package footer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/parquet-go/parquet-go"
|
||||
)
|
||||
|
||||
type sampleRow struct {
|
||||
ID int64
|
||||
Name string
|
||||
Value float64
|
||||
}
|
||||
|
||||
// writeFixture builds a small Parquet buffer with two row groups so
|
||||
// the parser exercises both row-group iteration and per-column-chunk
|
||||
// byte ranges. RowGroupTargetSize is set tight enough that the writer
|
||||
// flushes mid-input.
|
||||
func writeFixture(t *testing.T, rows []sampleRow) []byte {
|
||||
t.Helper()
|
||||
|
||||
schema := parquet.SchemaOf(sampleRow{})
|
||||
var buf bytes.Buffer
|
||||
w := parquet.NewGenericWriter[sampleRow](&buf, schema)
|
||||
if _, err := w.Write(rows); err != nil {
|
||||
t.Fatalf("write rows: %v", err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatalf("close writer: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestParseFromReader_ColumnChunksAndCounts(t *testing.T) {
|
||||
rows := make([]sampleRow, 1000)
|
||||
for i := range rows {
|
||||
rows[i] = sampleRow{ID: int64(i), Name: "row", Value: float64(i)}
|
||||
}
|
||||
data := writeFixture(t, rows)
|
||||
|
||||
pf, err := ParseFromReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if pf.NumRows != int64(len(rows)) {
|
||||
t.Errorf("NumRows = %d, want %d", pf.NumRows, len(rows))
|
||||
}
|
||||
if pf.NumCols != 3 {
|
||||
t.Errorf("NumCols = %d, want 3", pf.NumCols)
|
||||
}
|
||||
wantCols := []string{"ID", "Name", "Value"}
|
||||
if len(pf.ColumnPaths) != len(wantCols) {
|
||||
t.Fatalf("ColumnPaths len %d, want %d", len(pf.ColumnPaths), len(wantCols))
|
||||
}
|
||||
for i, want := range wantCols {
|
||||
if pf.ColumnPaths[i] != want {
|
||||
t.Errorf("ColumnPaths[%d] = %q, want %q", i, pf.ColumnPaths[i], want)
|
||||
}
|
||||
}
|
||||
if pf.NumGroups < 1 {
|
||||
t.Fatalf("NumGroups = %d, want >= 1", pf.NumGroups)
|
||||
}
|
||||
|
||||
// Every column chunk has a non-zero offset (data starts after the
|
||||
// 4-byte magic header) and a positive length, and the byte ranges
|
||||
// must not overlap within a single row group when sorted.
|
||||
for gi, rg := range pf.RowGroups {
|
||||
if rg.NumRows == 0 {
|
||||
t.Errorf("row group %d has zero rows", gi)
|
||||
}
|
||||
if len(rg.ColumnChunks) != pf.NumCols {
|
||||
t.Errorf("row group %d ColumnChunks len = %d, want %d", gi, len(rg.ColumnChunks), pf.NumCols)
|
||||
}
|
||||
for ci, cc := range rg.ColumnChunks {
|
||||
if cc.Offset <= 0 {
|
||||
t.Errorf("row group %d col %d offset = %d, want > 0", gi, ci, cc.Offset)
|
||||
}
|
||||
if cc.Length <= 0 {
|
||||
t.Errorf("row group %d col %d length = %d, want > 0", gi, ci, cc.Length)
|
||||
}
|
||||
if cc.Offset+cc.Length > int64(len(data)) {
|
||||
t.Errorf("row group %d col %d overruns file: end %d > size %d", gi, ci, cc.Offset+cc.Length, len(data))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFromReader_RejectsInvalid(t *testing.T) {
|
||||
if _, err := ParseFromReader(nil, 100); err == nil {
|
||||
t.Error("nil reader should fail")
|
||||
}
|
||||
if _, err := ParseFromReader(bytes.NewReader([]byte("PAR1")), 0); err == nil {
|
||||
t.Error("zero size should fail")
|
||||
}
|
||||
if _, err := ParseFromReader(bytes.NewReader([]byte("not parquet at all")), 18); err == nil {
|
||||
t.Error("non-parquet bytes should fail")
|
||||
}
|
||||
}
|
||||
|
||||
// columnChunkBytes prefers the dictionary page offset when present
|
||||
// because the dictionary page must be fetched alongside the data
|
||||
// pages of the same chunk.
|
||||
func TestColumnChunkBytes_DictionaryOffsetPreferred(t *testing.T) {
|
||||
// Synthesize a fixture where dictionary encoding is likely:
|
||||
// repeating low-cardinality strings nudge parquet-go to write a
|
||||
// dictionary page. Then check that at least one column chunk
|
||||
// reports a start offset before its data-page offset.
|
||||
rows := make([]sampleRow, 2000)
|
||||
for i := range rows {
|
||||
rows[i] = sampleRow{ID: int64(i % 5), Name: "tenant-" + string(rune('a'+(i%5))), Value: float64(i % 5)}
|
||||
}
|
||||
data := writeFixture(t, rows)
|
||||
pf, err := ParseFromReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
|
||||
// Sanity: at least one chunk's range should be plausible (length
|
||||
// is positive and offset doesn't exceed the file). Beyond that we
|
||||
// can't depend on a specific encoding choice from parquet-go.
|
||||
for _, rg := range pf.RowGroups {
|
||||
for _, cc := range rg.ColumnChunks {
|
||||
if cc.Offset+cc.Length > int64(len(data)) {
|
||||
t.Fatalf("chunk overruns file")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// FileHandle is what the service hands to the parser: a positional
|
||||
// reader bound to a known size, with a Close so the caller can
|
||||
// release any underlying resources.
|
||||
type FileHandle interface {
|
||||
io.ReaderAt
|
||||
io.Closer
|
||||
Size() int64
|
||||
}
|
||||
|
||||
// Loader resolves a Parquet file's path to a FileHandle. The split
|
||||
// between "local file" and "filer-backed" implementations lives here
|
||||
// so the service stays oblivious to the storage backend, and so
|
||||
// integration tests can plug in deterministic local files instead of
|
||||
// spinning up a filer.
|
||||
type Loader interface {
|
||||
Open(ctx context.Context, path string) (FileHandle, error)
|
||||
}
|
||||
|
||||
// LocalLoader treats `path` as a filesystem path. Used by integration
|
||||
// tests and for local-development smoke runs against a Parquet file
|
||||
// that is not under filer management.
|
||||
type LocalLoader struct{}
|
||||
|
||||
func (LocalLoader) Open(_ context.Context, path string) (FileHandle, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %q: %w", path, err)
|
||||
}
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, fmt.Errorf("stat %q: %w", path, err)
|
||||
}
|
||||
if st.IsDir() {
|
||||
_ = f.Close()
|
||||
return nil, fmt.Errorf("%q is a directory", path)
|
||||
}
|
||||
return &localFile{f: f, size: st.Size()}, nil
|
||||
}
|
||||
|
||||
type localFile struct {
|
||||
f *os.File
|
||||
size int64
|
||||
}
|
||||
|
||||
func (l *localFile) ReadAt(p []byte, off int64) (int, error) { return l.f.ReadAt(p, off) }
|
||||
func (l *localFile) Close() error { return l.f.Close() }
|
||||
func (l *localFile) Size() int64 { return l.size }
|
||||
@@ -1,48 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLocalLoader_Open(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "a.bin")
|
||||
want := []byte("hello pushdown")
|
||||
if err := os.WriteFile(path, want, 0o600); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
|
||||
h, err := LocalLoader{}.Open(context.Background(), path)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
defer h.Close()
|
||||
|
||||
if h.Size() != int64(len(want)) {
|
||||
t.Errorf("Size = %d, want %d", h.Size(), len(want))
|
||||
}
|
||||
got := make([]byte, len(want))
|
||||
n, err := h.ReadAt(got, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAt: %v", err)
|
||||
}
|
||||
if n != len(want) || string(got) != string(want) {
|
||||
t.Errorf("got %q (n=%d), want %q", got[:n], n, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalLoader_RejectsMissing(t *testing.T) {
|
||||
if _, err := (LocalLoader{}).Open(context.Background(), filepath.Join(t.TempDir(), "missing.bin")); err == nil {
|
||||
t.Error("expected error opening missing file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalLoader_RejectsDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := (LocalLoader{}).Open(context.Background(), dir); err == nil {
|
||||
t.Error("expected error opening a directory")
|
||||
}
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
// m1_round_trip_test.go is the M1 round-trip integration test from
|
||||
// PARQUET_PUSHDOWN_DEV_PLAN.md:
|
||||
//
|
||||
// "Round-trip integration test against a 3-file Iceberg table built
|
||||
// in test/parquet_pushdown/fixtures/.
|
||||
//
|
||||
// Footer cache hit-rate test (second call avoids re-parse; verified
|
||||
// via PushdownStats.FooterCacheHits)."
|
||||
//
|
||||
// It generates three Parquet files in a temp dir using parquet-go,
|
||||
// boots the SeaweedParquetPushdown service on a bufconn listener
|
||||
// with LocalLoader pointing at the temp dir, and submits real RPCs.
|
||||
// It does NOT require a filer; the filer-backed loader is M2+.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
)
|
||||
|
||||
type fixtureRow struct {
|
||||
ID int64
|
||||
Name string
|
||||
Value float64
|
||||
}
|
||||
|
||||
func writeParquetFile(t *testing.T, path string, rows []fixtureRow) {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
w := parquet.NewGenericWriter[fixtureRow](&buf, parquet.SchemaOf(fixtureRow{}))
|
||||
if _, err := w.Write(rows); err != nil {
|
||||
t.Fatalf("write rows: %v", err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatalf("close writer: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, buf.Bytes(), 0o600); err != nil {
|
||||
t.Fatalf("write file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func makeFixtureTable(t *testing.T) (dir string, files []string, sizes []int64) {
|
||||
t.Helper()
|
||||
dir = t.TempDir()
|
||||
for i, count := range []int{500, 750, 1000} {
|
||||
name := filepath.Join(dir, "part-0000"+string(rune('1'+i))+".parquet")
|
||||
rows := make([]fixtureRow, count)
|
||||
for k := range rows {
|
||||
rows[k] = fixtureRow{ID: int64(i*10000 + k), Name: "r", Value: float64(k)}
|
||||
}
|
||||
writeParquetFile(t, name, rows)
|
||||
st, err := os.Stat(name)
|
||||
if err != nil {
|
||||
t.Fatalf("stat: %v", err)
|
||||
}
|
||||
files = append(files, name)
|
||||
sizes = append(sizes, st.Size())
|
||||
}
|
||||
return dir, files, sizes
|
||||
}
|
||||
|
||||
func startServiceForFixtures(t *testing.T) (pb.SeaweedParquetPushdownClient, func()) {
|
||||
t.Helper()
|
||||
lis := bufconn.Listen(1 << 20)
|
||||
srv := grpc.NewServer()
|
||||
svc := New(Options{
|
||||
Version: "m1-test",
|
||||
TrustMode: TrustModeCatalogValidated,
|
||||
Loader: LocalLoader{},
|
||||
CacheSize: 32,
|
||||
})
|
||||
pb.RegisterSeaweedParquetPushdownServer(srv, svc)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
|
||||
dialer := func(ctx context.Context, _ string) (net.Conn, error) { return lis.DialContext(ctx) }
|
||||
conn, err := grpc.NewClient(
|
||||
"passthrough:///bufnet",
|
||||
grpc.WithContextDialer(dialer),
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
)
|
||||
if err != nil {
|
||||
srv.Stop()
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
return pb.NewSeaweedParquetPushdownClient(conn), func() {
|
||||
_ = conn.Close()
|
||||
srv.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func descriptorsFor(t *testing.T, files []string, sizes []int64) []*pb.DataFileDescriptor {
|
||||
t.Helper()
|
||||
out := make([]*pb.DataFileDescriptor, len(files))
|
||||
for i, p := range files {
|
||||
out[i] = &pb.DataFileDescriptor{Path: p, SizeBytes: sizes[i], RecordCount: 1}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Round-trip: three files, project two columns, no predicate.
|
||||
// Expect 3 files × N row groups × 2 columns of FileRanges, each with
|
||||
// a positive offset / length within the underlying file.
|
||||
func TestPushdown_M1_RoundTrip(t *testing.T) {
|
||||
_, files, sizes := makeFixtureTable(t)
|
||||
client, cleanup := startServiceForFixtures(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
resp, err := client.Pushdown(ctx, &pb.ParquetPushdownRequest{
|
||||
Table: "db.t",
|
||||
SnapshotId: 1,
|
||||
DataFiles: descriptorsFor(t, files, sizes),
|
||||
Columns: []*pb.ColumnRef{{Path: "ID"}, {Path: "Value"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("pushdown: %v", err)
|
||||
}
|
||||
if len(resp.FileRanges) == 0 {
|
||||
t.Fatal("expected file ranges, got none")
|
||||
}
|
||||
|
||||
// Per file, every range must reference that file and fit inside it.
|
||||
byFile := map[string]int64{}
|
||||
for i, p := range files {
|
||||
byFile[p] = sizes[i]
|
||||
}
|
||||
for i, r := range resp.FileRanges {
|
||||
size, ok := byFile[r.File]
|
||||
if !ok {
|
||||
t.Fatalf("range %d references unknown file %q", i, r.File)
|
||||
}
|
||||
if r.Offset <= 0 || r.Length <= 0 {
|
||||
t.Errorf("range %d has invalid bounds (offset=%d length=%d)", i, r.Offset, r.Length)
|
||||
}
|
||||
if r.Offset+r.Length > size {
|
||||
t.Errorf("range %d overruns file %q (offset=%d length=%d size=%d)", i, r.File, r.Offset, r.Length, size)
|
||||
}
|
||||
}
|
||||
|
||||
// First call: every footer is a miss; no hits.
|
||||
if got := resp.Stats.FooterCacheHits; got != 0 {
|
||||
t.Errorf("first call FooterCacheHits = %d, want 0", got)
|
||||
}
|
||||
if got := resp.Stats.FooterCacheMisses; got != int64(len(files)) {
|
||||
t.Errorf("first call FooterCacheMisses = %d, want %d", got, len(files))
|
||||
}
|
||||
}
|
||||
|
||||
// Footer cache hit-rate: a second identical request must hit the
|
||||
// cache for every file (zero misses).
|
||||
func TestPushdown_M1_FooterCacheHits(t *testing.T) {
|
||||
_, files, sizes := makeFixtureTable(t)
|
||||
client, cleanup := startServiceForFixtures(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &pb.ParquetPushdownRequest{
|
||||
Table: "db.t",
|
||||
SnapshotId: 1,
|
||||
DataFiles: descriptorsFor(t, files, sizes),
|
||||
Columns: []*pb.ColumnRef{{Path: "ID"}},
|
||||
}
|
||||
|
||||
if _, err := client.Pushdown(ctx, req); err != nil {
|
||||
t.Fatalf("warm-up: %v", err)
|
||||
}
|
||||
|
||||
resp, err := client.Pushdown(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("second call: %v", err)
|
||||
}
|
||||
if got := resp.Stats.FooterCacheHits; got != int64(len(files)) {
|
||||
t.Errorf("FooterCacheHits = %d, want %d", got, len(files))
|
||||
}
|
||||
if got := resp.Stats.FooterCacheMisses; got != 0 {
|
||||
t.Errorf("FooterCacheMisses = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Empty Columns list returns ranges for every column in every row group.
|
||||
func TestPushdown_M1_NoColumnProjection(t *testing.T) {
|
||||
_, files, sizes := makeFixtureTable(t)
|
||||
client, cleanup := startServiceForFixtures(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
resp, err := client.Pushdown(ctx, &pb.ParquetPushdownRequest{
|
||||
Table: "db.t",
|
||||
SnapshotId: 1,
|
||||
DataFiles: descriptorsFor(t, files, sizes),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("pushdown: %v", err)
|
||||
}
|
||||
// Every fixture has 3 columns; the count must be a multiple of 3.
|
||||
if len(resp.FileRanges)%3 != 0 {
|
||||
t.Errorf("FileRanges count %d not a multiple of column count 3", len(resp.FileRanges))
|
||||
}
|
||||
}
|
||||
|
||||
// An unknown column path is rejected with InvalidArgument before any
|
||||
// range is emitted.
|
||||
func TestPushdown_M1_UnknownColumn(t *testing.T) {
|
||||
_, files, sizes := makeFixtureTable(t)
|
||||
client, cleanup := startServiceForFixtures(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := client.Pushdown(ctx, &pb.ParquetPushdownRequest{
|
||||
Table: "db.t",
|
||||
SnapshotId: 1,
|
||||
DataFiles: descriptorsFor(t, files, sizes),
|
||||
Columns: []*pb.ColumnRef{{Path: "definitely_not_a_real_column"}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// A field-id-only ColumnRef without a Path hint is unsupported in M1
|
||||
// because schema-based resolution lands in M3.
|
||||
func TestPushdown_M1_FieldIdOnlyRejected(t *testing.T) {
|
||||
_, files, sizes := makeFixtureTable(t)
|
||||
client, cleanup := startServiceForFixtures(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := client.Pushdown(ctx, &pb.ParquetPushdownRequest{
|
||||
Table: "db.t",
|
||||
SnapshotId: 1,
|
||||
DataFiles: descriptorsFor(t, files, sizes),
|
||||
Columns: []*pb.ColumnRef{{FieldId: 1}}, // no Path
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
)
|
||||
|
||||
// Hard caps applied to every incoming request before any work is done.
|
||||
// These guard against accidental or hostile blow-up; they sit well
|
||||
// above any plausible legitimate request and are not user-tunable.
|
||||
const (
|
||||
maxDataFiles = 100_000
|
||||
maxColumns = 10_000
|
||||
maxPredicateBytes = 16 * 1024 * 1024 // matches gRPC default max message size
|
||||
maxRowIdsCap = 10_000_000
|
||||
maxVectorDim = 4096
|
||||
maxTopK = 10_000
|
||||
maxDeletesPerFile = 10_000
|
||||
)
|
||||
|
||||
// validateRequest enforces request-shape limits before the server
|
||||
// touches any data. Returns a gRPC status error with InvalidArgument
|
||||
// when something is wrong, nil otherwise.
|
||||
//
|
||||
// This is intentionally schema-only validation — it does not consult
|
||||
// the Iceberg catalog (that is M3 / catalog-validated mode) or read
|
||||
// any files. Schema-only checks run in every trust mode.
|
||||
func validateRequest(req *pb.ParquetPushdownRequest) error {
|
||||
if req == nil {
|
||||
return status.Error(codes.InvalidArgument, "request is nil")
|
||||
}
|
||||
if req.Table == "" {
|
||||
return status.Error(codes.InvalidArgument, "table is required")
|
||||
}
|
||||
if len(req.DataFiles) == 0 {
|
||||
return status.Error(codes.InvalidArgument, "data_files must not be empty")
|
||||
}
|
||||
if len(req.DataFiles) > maxDataFiles {
|
||||
return status.Errorf(codes.InvalidArgument, "data_files exceeds cap %d", maxDataFiles)
|
||||
}
|
||||
if len(req.Columns) > maxColumns {
|
||||
return status.Errorf(codes.InvalidArgument, "columns exceeds cap %d", maxColumns)
|
||||
}
|
||||
if len(req.Predicate) > maxPredicateBytes {
|
||||
return status.Errorf(codes.InvalidArgument, "predicate exceeds cap %d bytes", maxPredicateBytes)
|
||||
}
|
||||
if (req.PredicateKind != pb.PredicateKind_PREDICATE_KIND_UNSPECIFIED) != (len(req.Predicate) > 0) {
|
||||
return status.Error(codes.InvalidArgument, "predicate_kind and predicate must be set together")
|
||||
}
|
||||
// A bound predicate is meaningless without naming the schema its
|
||||
// field references resolve under, so require schema_id whenever a
|
||||
// predicate is present. The deeper check (every field id is in
|
||||
// the snapshot's schema) needs catalog access and runs in M3.
|
||||
if len(req.Predicate) > 0 && req.SchemaId == 0 {
|
||||
return status.Error(codes.InvalidArgument, "predicate requires schema_id so field references can be bound")
|
||||
}
|
||||
if req.MaxRowIds < 0 || req.MaxRowIds > maxRowIdsCap {
|
||||
return status.Errorf(codes.InvalidArgument, "max_row_ids must be in [0, %d]", maxRowIdsCap)
|
||||
}
|
||||
if req.RequestRowIds && req.MaxRowIds == 0 {
|
||||
return status.Error(codes.InvalidArgument, "request_row_ids requires a positive max_row_ids")
|
||||
}
|
||||
if req.Limit < 0 {
|
||||
return status.Error(codes.InvalidArgument, "limit must be non-negative")
|
||||
}
|
||||
if err := validateVectorQuery(req.VectorQuery); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, df := range req.DataFiles {
|
||||
if err := validateDataFile(df); err != nil {
|
||||
return status.Errorf(codes.InvalidArgument, "data_files[%d]: %s", i, err.Error())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateVectorQuery(q *pb.VectorQuery) error {
|
||||
if q == nil {
|
||||
return nil
|
||||
}
|
||||
if q.Column == nil || (q.Column.FieldId == 0 && q.Column.Path == "") {
|
||||
return status.Error(codes.InvalidArgument, "vector_query.column must identify a column")
|
||||
}
|
||||
if len(q.Vector) == 0 {
|
||||
return status.Error(codes.InvalidArgument, "vector_query.vector must not be empty")
|
||||
}
|
||||
if len(q.Vector) > maxVectorDim {
|
||||
return status.Errorf(codes.InvalidArgument, "vector_query.vector dim exceeds cap %d", maxVectorDim)
|
||||
}
|
||||
if q.TopK <= 0 || q.TopK > maxTopK {
|
||||
return status.Errorf(codes.InvalidArgument, "vector_query.top_k must be in [1, %d]", maxTopK)
|
||||
}
|
||||
if q.Metric == pb.VectorMetric_VECTOR_METRIC_UNSPECIFIED {
|
||||
return status.Error(codes.InvalidArgument, "vector_query.metric must be set")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDataFile(df *pb.DataFileDescriptor) error {
|
||||
if df == nil {
|
||||
return status.Error(codes.InvalidArgument, "descriptor is nil")
|
||||
}
|
||||
if df.Path == "" {
|
||||
return status.Error(codes.InvalidArgument, "path is required")
|
||||
}
|
||||
if df.SizeBytes < 0 {
|
||||
return status.Error(codes.InvalidArgument, "size_bytes must be non-negative")
|
||||
}
|
||||
if df.RecordCount < 0 {
|
||||
return status.Error(codes.InvalidArgument, "record_count must be non-negative")
|
||||
}
|
||||
if len(df.Deletes) > maxDeletesPerFile {
|
||||
return status.Errorf(codes.InvalidArgument, "deletes exceeds cap %d", maxDeletesPerFile)
|
||||
}
|
||||
for i, del := range df.Deletes {
|
||||
if err := validateDeleteFile(del); err != nil {
|
||||
return status.Errorf(codes.InvalidArgument, "deletes[%d]: %s", i, err.Error())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDeleteFile(del *pb.DeleteFileRef) error {
|
||||
if del == nil {
|
||||
return status.Error(codes.InvalidArgument, "delete is nil")
|
||||
}
|
||||
if del.Path == "" {
|
||||
return status.Error(codes.InvalidArgument, "path is required")
|
||||
}
|
||||
switch del.Content {
|
||||
case pb.DeleteContent_POSITION_DELETES:
|
||||
if del.FileFormat == pb.FileFormat_FILE_FORMAT_PUFFIN {
|
||||
// Deletion vector: blob bounds are mandatory and the DV
|
||||
// must reference a single data file.
|
||||
if del.BlobLength <= 0 {
|
||||
return status.Error(codes.InvalidArgument, "deletion vector requires positive blob_length")
|
||||
}
|
||||
if del.ReferencedDataFile == "" {
|
||||
return status.Error(codes.InvalidArgument, "deletion vector requires referenced_data_file")
|
||||
}
|
||||
}
|
||||
case pb.DeleteContent_EQUALITY_DELETES:
|
||||
if len(del.EqualityFieldIds) == 0 {
|
||||
return status.Error(codes.InvalidArgument, "equality delete requires equality_field_ids")
|
||||
}
|
||||
default:
|
||||
return status.Error(codes.InvalidArgument, "unsupported delete content type")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
)
|
||||
|
||||
// A predicate paired with a SchemaId is the well-formed shape; a
|
||||
// well-formed predicate without SchemaId must be rejected (deeper
|
||||
// catalog binding lands in M3).
|
||||
func TestValidateRequest_PredicateRequiresSchemaId(t *testing.T) {
|
||||
req := validRequest()
|
||||
req.PredicateKind = pb.PredicateKind_PREDICATE_KIND_SUBSTRAIT
|
||||
req.Predicate = []byte("bound expression bytes")
|
||||
req.SchemaId = 7
|
||||
|
||||
if err := validateRequest(req); err != nil {
|
||||
t.Fatalf("predicate + schema_id should pass, got %v", err)
|
||||
}
|
||||
|
||||
req.SchemaId = 0
|
||||
err := validateRequest(req)
|
||||
if err == nil {
|
||||
t.Fatal("predicate without schema_id should be rejected")
|
||||
}
|
||||
if status.Code(err) != codes.InvalidArgument {
|
||||
t.Fatalf("got %v, want InvalidArgument (err=%v)", status.Code(err), err)
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
)
|
||||
|
||||
func validRequest() *pb.ParquetPushdownRequest {
|
||||
return &pb.ParquetPushdownRequest{
|
||||
Table: "db.t",
|
||||
SnapshotId: 42,
|
||||
DataFiles: []*pb.DataFileDescriptor{
|
||||
{Path: "s3://bkt/db/t/data/part-00001.parquet", SizeBytes: 1024, RecordCount: 100, DataSequenceNumber: 1},
|
||||
},
|
||||
Columns: []*pb.ColumnRef{{FieldId: 1}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRequest_OK(t *testing.T) {
|
||||
if err := validateRequest(validRequest()); err != nil {
|
||||
t.Fatalf("expected ok, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRequest_RejectsEmpty(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mut func(*pb.ParquetPushdownRequest)
|
||||
}{
|
||||
{"nil request", func(r *pb.ParquetPushdownRequest) { *r = pb.ParquetPushdownRequest{} }},
|
||||
{"missing table", func(r *pb.ParquetPushdownRequest) { r.Table = "" }},
|
||||
{"empty data files", func(r *pb.ParquetPushdownRequest) { r.DataFiles = nil }},
|
||||
{"data file missing path", func(r *pb.ParquetPushdownRequest) { r.DataFiles[0].Path = "" }},
|
||||
{"negative size", func(r *pb.ParquetPushdownRequest) { r.DataFiles[0].SizeBytes = -1 }},
|
||||
{"negative record count", func(r *pb.ParquetPushdownRequest) { r.DataFiles[0].RecordCount = -1 }},
|
||||
{"negative limit", func(r *pb.ParquetPushdownRequest) { r.Limit = -1 }},
|
||||
{"row ids without cap", func(r *pb.ParquetPushdownRequest) { r.RequestRowIds = true; r.MaxRowIds = 0 }},
|
||||
{"max row ids over cap", func(r *pb.ParquetPushdownRequest) { r.MaxRowIds = maxRowIdsCap + 1 }},
|
||||
{"predicate without kind", func(r *pb.ParquetPushdownRequest) { r.Predicate = []byte("x") }},
|
||||
{"predicate kind without bytes", func(r *pb.ParquetPushdownRequest) {
|
||||
r.PredicateKind = pb.PredicateKind_PREDICATE_KIND_SUBSTRAIT
|
||||
}},
|
||||
{"predicate without schema_id", func(r *pb.ParquetPushdownRequest) {
|
||||
r.PredicateKind = pb.PredicateKind_PREDICATE_KIND_SUBSTRAIT
|
||||
r.Predicate = []byte("bound expression")
|
||||
r.SchemaId = 0
|
||||
}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
req := validRequest()
|
||||
c.mut(req)
|
||||
err := validateRequest(req)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if status.Code(err) != codes.InvalidArgument {
|
||||
t.Fatalf("expected InvalidArgument, got %v", status.Code(err))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRequest_VectorQuery(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
q *pb.VectorQuery
|
||||
want codes.Code
|
||||
}{
|
||||
{"nil ok", nil, codes.OK},
|
||||
{"missing column", &pb.VectorQuery{Vector: []float32{1}, TopK: 1, Metric: pb.VectorMetric_VECTOR_METRIC_L2}, codes.InvalidArgument},
|
||||
{"empty vector", &pb.VectorQuery{Column: &pb.ColumnRef{FieldId: 1}, TopK: 1, Metric: pb.VectorMetric_VECTOR_METRIC_L2}, codes.InvalidArgument},
|
||||
{"top_k zero", &pb.VectorQuery{Column: &pb.ColumnRef{FieldId: 1}, Vector: []float32{1}, Metric: pb.VectorMetric_VECTOR_METRIC_L2}, codes.InvalidArgument},
|
||||
{"unspecified metric", &pb.VectorQuery{Column: &pb.ColumnRef{FieldId: 1}, Vector: []float32{1}, TopK: 1}, codes.InvalidArgument},
|
||||
{"ok", &pb.VectorQuery{Column: &pb.ColumnRef{FieldId: 1}, Vector: []float32{1}, TopK: 1, Metric: pb.VectorMetric_VECTOR_METRIC_L2}, codes.OK},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
req := validRequest()
|
||||
req.VectorQuery = c.q
|
||||
err := validateRequest(req)
|
||||
if status.Code(err) != c.want {
|
||||
t.Fatalf("got %v, want %v (err=%v)", status.Code(err), c.want, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRequest_DeleteFiles(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
del *pb.DeleteFileRef
|
||||
want codes.Code
|
||||
}{
|
||||
{
|
||||
"position-delete file ok",
|
||||
&pb.DeleteFileRef{Path: "p", Content: pb.DeleteContent_POSITION_DELETES, FileFormat: pb.FileFormat_FILE_FORMAT_PARQUET},
|
||||
codes.OK,
|
||||
},
|
||||
{
|
||||
"deletion vector ok",
|
||||
&pb.DeleteFileRef{Path: "p", Content: pb.DeleteContent_POSITION_DELETES, FileFormat: pb.FileFormat_FILE_FORMAT_PUFFIN, BlobLength: 16, ReferencedDataFile: "data.parquet"},
|
||||
codes.OK,
|
||||
},
|
||||
{
|
||||
"deletion vector missing blob length",
|
||||
&pb.DeleteFileRef{Path: "p", Content: pb.DeleteContent_POSITION_DELETES, FileFormat: pb.FileFormat_FILE_FORMAT_PUFFIN, ReferencedDataFile: "data.parquet"},
|
||||
codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
"deletion vector missing referenced data file",
|
||||
&pb.DeleteFileRef{Path: "p", Content: pb.DeleteContent_POSITION_DELETES, FileFormat: pb.FileFormat_FILE_FORMAT_PUFFIN, BlobLength: 16},
|
||||
codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
"equality delete missing field ids",
|
||||
&pb.DeleteFileRef{Path: "p", Content: pb.DeleteContent_EQUALITY_DELETES, FileFormat: pb.FileFormat_FILE_FORMAT_PARQUET},
|
||||
codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
"equality delete ok",
|
||||
&pb.DeleteFileRef{Path: "p", Content: pb.DeleteContent_EQUALITY_DELETES, FileFormat: pb.FileFormat_FILE_FORMAT_PARQUET, EqualityFieldIds: []int32{1}},
|
||||
codes.OK,
|
||||
},
|
||||
{
|
||||
"unspecified content rejected",
|
||||
&pb.DeleteFileRef{Path: "p"},
|
||||
codes.InvalidArgument,
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
req := validRequest()
|
||||
req.DataFiles[0].Deletes = []*pb.DeleteFileRef{c.del}
|
||||
err := validateRequest(req)
|
||||
if status.Code(err) != c.want {
|
||||
t.Fatalf("got %v, want %v (err=%v)", status.Code(err), c.want, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
// Package parquet_pushdown implements the SeaweedFS-aware Parquet
|
||||
// pushdown service. See PARQUET_PUSHDOWN_DESIGN.md and
|
||||
// PARQUET_PUSHDOWN_DEV_PLAN.md at the repo root for the surrounding
|
||||
// design and the milestone plan.
|
||||
//
|
||||
// M1 wires up the parsed-footer cache and file/range-level pushdown:
|
||||
// for predicate-less, no-vector requests the service returns the
|
||||
// column-chunk byte ranges of the projected columns. Predicate /
|
||||
// vector evaluation lands in later milestones.
|
||||
package parquet_pushdown
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown/footer"
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
)
|
||||
|
||||
// TrustMode controls how the server validates the request's
|
||||
// DataFiles and Deletes against the Iceberg catalog. See the design's
|
||||
// "Trust Model and Catalog Validation" section.
|
||||
type TrustMode string
|
||||
|
||||
const (
|
||||
// TrustModeCatalogValidated is the default. The server reads the
|
||||
// Iceberg snapshot and verifies every DataFileDescriptor and
|
||||
// DeleteFileRef against the manifest before serving.
|
||||
TrustModeCatalogValidated TrustMode = "catalog-validated"
|
||||
|
||||
// TrustModeConnectorTrusted is a developer-only mode that skips
|
||||
// catalog validation. Production builds must reject this mode at
|
||||
// configuration time.
|
||||
TrustModeConnectorTrusted TrustMode = "connector-trusted"
|
||||
)
|
||||
|
||||
// defaultFooterCacheSize is the parsed-footer LRU's default capacity
|
||||
// when Options.Cache is unset. Footer entries are small (a few KiB
|
||||
// typically; the heaviest field is the per-row-group ColumnChunks
|
||||
// slice that scales with column count and row group count). 4096
|
||||
// covers a few thousand active Parquet files comfortably; can be
|
||||
// overridden via Options.CacheSize.
|
||||
const defaultFooterCacheSize = 4096
|
||||
|
||||
// Options configures a Service. Loader and Cache are pluggable so
|
||||
// integration tests can wire deterministic local files; the daemon
|
||||
// supplies a filer-backed Loader and a sized Cache.
|
||||
type Options struct {
|
||||
// Version is reported in PingResponse and stamped on PushdownStats.
|
||||
Version string
|
||||
|
||||
// TrustMode determines request-validation strictness. The actual
|
||||
// validation against the catalog lands in M3.
|
||||
TrustMode TrustMode
|
||||
|
||||
// Loader resolves DataFile paths to FileHandles. Defaults to
|
||||
// LocalLoader{} (filesystem-backed).
|
||||
Loader Loader
|
||||
|
||||
// Cache is the parsed-footer LRU. When nil, a cache of CacheSize
|
||||
// (or defaultFooterCacheSize) entries is created.
|
||||
Cache *footer.Cache
|
||||
|
||||
// CacheSize is the entry cap when Cache is nil.
|
||||
CacheSize int
|
||||
}
|
||||
|
||||
// Service implements parquet_pushdown_pb.SeaweedParquetPushdownServer.
|
||||
// One Service instance per daemon process.
|
||||
type Service struct {
|
||||
pb.UnimplementedSeaweedParquetPushdownServer
|
||||
|
||||
version string
|
||||
trustMode TrustMode
|
||||
loader Loader
|
||||
cache *footer.Cache
|
||||
}
|
||||
|
||||
// New constructs a Service from Options, applying defaults. Returns
|
||||
// an error if the cache cannot be constructed (e.g. nonsense size).
|
||||
func New(opts Options) *Service {
|
||||
mode := opts.TrustMode
|
||||
if mode == "" {
|
||||
mode = TrustModeCatalogValidated
|
||||
}
|
||||
loader := opts.Loader
|
||||
if loader == nil {
|
||||
loader = LocalLoader{}
|
||||
}
|
||||
cache := opts.Cache
|
||||
if cache == nil {
|
||||
size := opts.CacheSize
|
||||
if size <= 0 {
|
||||
size = defaultFooterCacheSize
|
||||
}
|
||||
c, err := footer.NewCache(size)
|
||||
if err != nil {
|
||||
// Size is validated above to be > 0; this is a
|
||||
// programmer-error path the cache implementation should
|
||||
// never hit. Promoting to panic keeps New non-error and
|
||||
// callers oblivious to a configuration knob they did not
|
||||
// touch.
|
||||
panic(fmt.Errorf("parquet_pushdown: build footer cache: %w", err))
|
||||
}
|
||||
cache = c
|
||||
}
|
||||
return &Service{
|
||||
version: opts.Version,
|
||||
trustMode: mode,
|
||||
loader: loader,
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
// Ping returns daemon liveness information. Used by smoke tests and
|
||||
// connector health checks. Cheap; never reads files.
|
||||
func (s *Service) Ping(_ context.Context, _ *pb.PingRequest) (*pb.PingResponse, error) {
|
||||
return &pb.PingResponse{
|
||||
Version: s.version,
|
||||
TrustMode: string(s.trustMode),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Pushdown evaluates a request and returns surviving file/row-group/
|
||||
// page byte ranges.
|
||||
//
|
||||
// M1 handles only the predicate-less, no-vector path: parse each
|
||||
// data file's footer (cached by Identity) and return one FileRange
|
||||
// per (data file, row group, projected column) triple covering that
|
||||
// column chunk's byte range. Predicate / vector clauses fall through
|
||||
// to Unimplemented until later milestones.
|
||||
func (s *Service) Pushdown(ctx context.Context, req *pb.ParquetPushdownRequest) (*pb.ParquetPushdownResponse, error) {
|
||||
stats := newStats(s.trustMode)
|
||||
|
||||
if err := validateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(req.Predicate) > 0 || req.VectorQuery != nil {
|
||||
st := status.New(codes.Unimplemented, "predicate / vector evaluation lands in a later milestone; M1 only handles file/range-level pushdown")
|
||||
if d, err := st.WithDetails(stats.toProto()); err == nil {
|
||||
return nil, d.Err()
|
||||
}
|
||||
return nil, st.Err()
|
||||
}
|
||||
|
||||
resp := &pb.ParquetPushdownResponse{}
|
||||
for _, df := range req.DataFiles {
|
||||
pf, err := s.loadFooter(ctx, df, stats)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "load footer for %q: %v", df.Path, err)
|
||||
}
|
||||
ranges, err := projectColumnRanges(df.Path, pf, req.Columns)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "project columns for %q: %v", df.Path, err)
|
||||
}
|
||||
resp.FileRanges = append(resp.FileRanges, ranges...)
|
||||
}
|
||||
resp.Stats = stats.toProto()
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) loadFooter(ctx context.Context, df *pb.DataFileDescriptor, stats *statsRecorder) (*footer.ParsedFooter, error) {
|
||||
id := footer.Identity{
|
||||
Path: df.Path,
|
||||
SizeBytes: df.SizeBytes,
|
||||
RecordCount: df.RecordCount,
|
||||
ETag: df.Etag,
|
||||
}
|
||||
if pf, ok := s.cache.Get(id); ok {
|
||||
stats.recordFooterCacheHit()
|
||||
return pf, nil
|
||||
}
|
||||
stats.recordFooterCacheMiss()
|
||||
|
||||
h, err := s.loader.Open(ctx, df.Path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
defer h.Close()
|
||||
|
||||
pf, err := footer.ParseFromReader(h, h.Size())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse: %w", err)
|
||||
}
|
||||
s.cache.Add(id, pf)
|
||||
return pf, nil
|
||||
}
|
||||
|
||||
// projectColumnRanges expands the requested column projection into
|
||||
// per-row-group byte ranges over the data file. An empty Columns
|
||||
// list means "every column"; when columns are listed they are
|
||||
// matched by ColumnRef.Path against the file's leaf-column paths.
|
||||
//
|
||||
// Field-id-only projection (Path == "") needs the catalog schema to
|
||||
// resolve to a leaf path and is therefore unsupported until M3
|
||||
// (catalog-validated mode) plumbs the schema through.
|
||||
func projectColumnRanges(filePath string, pf *footer.ParsedFooter, cols []*pb.ColumnRef) ([]*pb.FileRange, error) {
|
||||
pathIdx := make(map[string]int, len(pf.ColumnPaths))
|
||||
for i, p := range pf.ColumnPaths {
|
||||
pathIdx[p] = i
|
||||
}
|
||||
|
||||
indices, err := resolveColumnIndices(pathIdx, pf.NumCols, cols)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out := make([]*pb.FileRange, 0, len(pf.RowGroups)*len(indices))
|
||||
for _, rg := range pf.RowGroups {
|
||||
for _, idx := range indices {
|
||||
cc := rg.ColumnChunks[idx]
|
||||
out = append(out, &pb.FileRange{
|
||||
File: filePath,
|
||||
Offset: cc.Offset,
|
||||
Length: cc.Length,
|
||||
})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func resolveColumnIndices(pathIdx map[string]int, numCols int, cols []*pb.ColumnRef) ([]int, error) {
|
||||
if len(cols) == 0 {
|
||||
out := make([]int, numCols)
|
||||
for i := range out {
|
||||
out[i] = i
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
out := make([]int, 0, len(cols))
|
||||
for _, c := range cols {
|
||||
if c == nil {
|
||||
return nil, fmt.Errorf("nil column ref")
|
||||
}
|
||||
if c.Path == "" {
|
||||
return nil, fmt.Errorf("column ref field_id=%d has no path hint; field-id-only resolution requires catalog schema (M3)", c.FieldId)
|
||||
}
|
||||
idx, ok := pathIdx[c.Path]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("column %q not in file", c.Path)
|
||||
}
|
||||
out = append(out, idx)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
// service_grpc_test.go is the M0 integration test. It boots the
|
||||
// Service on an in-process gRPC bufconn listener (no filer, no
|
||||
// network) and exercises Ping and Pushdown end-to-end over real gRPC.
|
||||
//
|
||||
// The acceptance criterion from PARQUET_PUSHDOWN_DEV_PLAN.md is
|
||||
// "calls Pushdown over gRPC, gets the expected Unimplemented error
|
||||
// path with stats populated"; this file proves both, plus that the
|
||||
// Pushdown Unimplemented status carries a PushdownStats detail with
|
||||
// trust_mode and a non-zero server_time_micros.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
)
|
||||
|
||||
const bufSize = 1 << 20
|
||||
|
||||
func startTestServer(t *testing.T, opts Options) (pb.SeaweedParquetPushdownClient, func()) {
|
||||
t.Helper()
|
||||
|
||||
lis := bufconn.Listen(bufSize)
|
||||
srv := grpc.NewServer()
|
||||
pb.RegisterSeaweedParquetPushdownServer(srv, New(opts))
|
||||
|
||||
go func() {
|
||||
if err := srv.Serve(lis); err != nil {
|
||||
t.Logf("test server stopped: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
dialer := func(ctx context.Context, _ string) (net.Conn, error) {
|
||||
return lis.DialContext(ctx)
|
||||
}
|
||||
conn, err := grpc.NewClient(
|
||||
"passthrough:///bufnet",
|
||||
grpc.WithContextDialer(dialer),
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
)
|
||||
if err != nil {
|
||||
srv.Stop()
|
||||
t.Fatalf("dial bufconn: %v", err)
|
||||
}
|
||||
cleanup := func() {
|
||||
_ = conn.Close()
|
||||
srv.Stop()
|
||||
}
|
||||
return pb.NewSeaweedParquetPushdownClient(conn), cleanup
|
||||
}
|
||||
|
||||
func TestPing_ReportsConfiguredVersionAndTrustMode(t *testing.T) {
|
||||
client, cleanup := startTestServer(t, Options{
|
||||
Version: "test-1.2.3",
|
||||
TrustMode: TrustModeCatalogValidated,
|
||||
})
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
resp, err := client.Ping(ctx, &pb.PingRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("ping failed: %v", err)
|
||||
}
|
||||
if resp.Version != "test-1.2.3" {
|
||||
t.Errorf("version = %q, want %q", resp.Version, "test-1.2.3")
|
||||
}
|
||||
if resp.TrustMode != string(TrustModeCatalogValidated) {
|
||||
t.Errorf("trust_mode = %q, want %q", resp.TrustMode, TrustModeCatalogValidated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPing_DefaultsTrustModeToCatalogValidated(t *testing.T) {
|
||||
client, cleanup := startTestServer(t, Options{Version: "test"})
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
resp, err := client.Ping(ctx, &pb.PingRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("ping failed: %v", err)
|
||||
}
|
||||
if resp.TrustMode != string(TrustModeCatalogValidated) {
|
||||
t.Errorf("trust_mode default = %q, want %q", resp.TrustMode, TrustModeCatalogValidated)
|
||||
}
|
||||
}
|
||||
|
||||
// As of M1 the Unimplemented path is reserved for predicate /
|
||||
// vector requests (file/range-level pushdown is implemented). Use a
|
||||
// predicate-bearing request to exercise the Unimplemented + stats
|
||||
// detail wire format.
|
||||
func TestPushdown_ReturnsUnimplementedWithStats(t *testing.T) {
|
||||
client, cleanup := startTestServer(t, Options{
|
||||
Version: "test",
|
||||
TrustMode: TrustModeCatalogValidated,
|
||||
})
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &pb.ParquetPushdownRequest{
|
||||
Table: "db.t",
|
||||
SnapshotId: 1,
|
||||
DataFiles: []*pb.DataFileDescriptor{
|
||||
{Path: "s3://b/p.parquet", SizeBytes: 1, RecordCount: 1},
|
||||
},
|
||||
Columns: []*pb.ColumnRef{{FieldId: 1, Path: "id"}},
|
||||
PredicateKind: pb.PredicateKind_PREDICATE_KIND_SUBSTRAIT,
|
||||
Predicate: []byte("bound"),
|
||||
SchemaId: 1,
|
||||
}
|
||||
|
||||
_, err := client.Pushdown(ctx, req)
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
t.Fatalf("error is not a gRPC status: %v", err)
|
||||
}
|
||||
if st.Code() != codes.Unimplemented {
|
||||
t.Fatalf("got code %v, want Unimplemented", st.Code())
|
||||
}
|
||||
|
||||
// Acceptance: stats are attached as a detail on the Unimplemented
|
||||
// status, with the daemon's trust mode and a non-zero elapsed.
|
||||
var stats *pb.PushdownStats
|
||||
for _, d := range st.Details() {
|
||||
if s, ok := d.(*pb.PushdownStats); ok {
|
||||
stats = s
|
||||
break
|
||||
}
|
||||
}
|
||||
if stats == nil {
|
||||
t.Fatal("expected PushdownStats detail on Unimplemented status")
|
||||
}
|
||||
if stats.TrustMode != string(TrustModeCatalogValidated) {
|
||||
t.Errorf("stats.trust_mode = %q, want %q", stats.TrustMode, TrustModeCatalogValidated)
|
||||
}
|
||||
if stats.ServerTimeMicros < 0 {
|
||||
t.Errorf("stats.server_time_micros = %d, want >= 0", stats.ServerTimeMicros)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushdown_RejectsInvalidRequestBeforeUnimplemented(t *testing.T) {
|
||||
client, cleanup := startTestServer(t, Options{Version: "test"})
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Empty data_files: validation should fire and produce
|
||||
// InvalidArgument, not Unimplemented.
|
||||
_, err := client.Pushdown(ctx, &pb.ParquetPushdownRequest{Table: "db.t"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if status.Code(err) != codes.InvalidArgument {
|
||||
t.Fatalf("got %v, want InvalidArgument (err=%v)", status.Code(err), err)
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package parquet_pushdown
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
)
|
||||
|
||||
// statsRecorder accumulates per-request stats and converts to the
|
||||
// wire form when the handler returns. Counts here are scoped to a
|
||||
// single Pushdown call, not process-wide.
|
||||
type statsRecorder struct {
|
||||
start time.Time
|
||||
trustMode TrustMode
|
||||
footerCacheHits int64
|
||||
footerCacheMisses int64
|
||||
indexesUsed []string
|
||||
indexesMissing []string
|
||||
}
|
||||
|
||||
func newStats(trustMode TrustMode) *statsRecorder {
|
||||
return &statsRecorder{start: time.Now(), trustMode: trustMode}
|
||||
}
|
||||
|
||||
func (r *statsRecorder) recordFooterCacheHit() { r.footerCacheHits++ }
|
||||
func (r *statsRecorder) recordFooterCacheMiss() { r.footerCacheMisses++ }
|
||||
|
||||
func (r *statsRecorder) markIndexUsed(kind string) {
|
||||
r.indexesUsed = append(r.indexesUsed, kind)
|
||||
}
|
||||
|
||||
func (r *statsRecorder) markIndexMissing(kind string) {
|
||||
r.indexesMissing = append(r.indexesMissing, kind)
|
||||
}
|
||||
|
||||
func (r *statsRecorder) toProto() *pb.PushdownStats {
|
||||
return &pb.PushdownStats{
|
||||
TrustMode: string(r.trustMode),
|
||||
ServerTimeMicros: time.Since(r.start).Microseconds(),
|
||||
FooterCacheHits: r.footerCacheHits,
|
||||
FooterCacheMisses: r.footerCacheMisses,
|
||||
IndexesUsed: r.indexesUsed,
|
||||
IndexesMissing: r.indexesMissing,
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,6 @@ gen:
|
||||
protoc worker.proto --go_out=./worker_pb --go-grpc_out=./worker_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
|
||||
mkdir -p ./plugin_pb
|
||||
protoc plugin.proto --go_out=./plugin_pb --go-grpc_out=./plugin_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
|
||||
mkdir -p ./parquet_pushdown_pb
|
||||
protoc parquet_pushdown.proto --go_out=./parquet_pushdown_pb --go-grpc_out=./parquet_pushdown_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
|
||||
# protoc filer.proto --java_out=../../other/java/client/src/main/java
|
||||
cp filer.proto ../../other/java/client/src/main/proto
|
||||
cp volume_server.proto master.proto remote.proto ../../seaweed-volume/proto/
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package parquet_pushdown_pb;
|
||||
|
||||
option go_package = "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb";
|
||||
|
||||
// SeaweedParquetPushdown is the gRPC surface of the standalone
|
||||
// `weed pushdown` daemon. See PARQUET_PUSHDOWN_DESIGN.md and
|
||||
// PARQUET_PUSHDOWN_DEV_PLAN.md for the surrounding design.
|
||||
service SeaweedParquetPushdown {
|
||||
// Ping returns daemon liveness information. Cheap; intended for
|
||||
// smoke tests and connector health checks.
|
||||
rpc Ping (PingRequest) returns (PingResponse);
|
||||
|
||||
// Pushdown takes a planner-resolved set of Iceberg data files and
|
||||
// returns the byte ranges, row groups, pages, and (optionally) row
|
||||
// refs that satisfy the request's predicate and vector clauses.
|
||||
// M0 returns Unimplemented; later milestones fill in pruning logic.
|
||||
rpc Pushdown (ParquetPushdownRequest) returns (ParquetPushdownResponse);
|
||||
}
|
||||
|
||||
// -- Ping --------------------------------------------------------------------
|
||||
|
||||
message PingRequest {}
|
||||
|
||||
message PingResponse {
|
||||
string version = 1;
|
||||
// TrustMode the daemon is configured for: "catalog-validated" or
|
||||
// "connector-trusted". Connector-trusted is dev-only.
|
||||
string trust_mode = 2;
|
||||
}
|
||||
|
||||
// -- Request -----------------------------------------------------------------
|
||||
|
||||
message ParquetPushdownRequest {
|
||||
string table = 1;
|
||||
int64 snapshot_id = 2;
|
||||
|
||||
// The authoritative list of files to scan, already resolved by the
|
||||
// client's Iceberg planner. The server validates these against the
|
||||
// catalog when running in catalog-validated trust mode.
|
||||
repeated DataFileDescriptor data_files = 3;
|
||||
|
||||
// Columns to project. Identified by Iceberg field id (preferred)
|
||||
// or path hint (fallback for non-Iceberg-managed Parquet).
|
||||
repeated ColumnRef columns = 4;
|
||||
|
||||
PredicateKind predicate_kind = 5;
|
||||
|
||||
// Predicate is a *bound* expression: every column reference must
|
||||
// resolve to an Iceberg field id (Substrait field-reference IDs
|
||||
// matching schema_id, or Iceberg Expression JSON with id-based
|
||||
// references). Name-only references are rejected.
|
||||
bytes predicate = 6;
|
||||
|
||||
VectorQuery vector_query = 7;
|
||||
|
||||
int32 limit = 8;
|
||||
|
||||
// If true, the response may include per-row refs (RowRef list).
|
||||
// Bounded by max_row_ids.
|
||||
bool request_row_ids = 9;
|
||||
int32 max_row_ids = 10;
|
||||
|
||||
// schema_id is the Iceberg schema id the predicate (and any
|
||||
// ColumnRef.field_id values) are bound to. The server confirms it
|
||||
// matches the snapshot's current_schema_id (or a known historical
|
||||
// schema) before evaluating. Field IDs not present in this schema
|
||||
// cause the request to be rejected.
|
||||
int32 schema_id = 11;
|
||||
}
|
||||
|
||||
message DataFileDescriptor {
|
||||
string path = 1;
|
||||
int64 size_bytes = 2; // Iceberg manifest file_size_in_bytes
|
||||
int64 record_count = 3; // Iceberg manifest record_count
|
||||
string etag = 4; // optional, when no Iceberg manifest
|
||||
|
||||
// Iceberg manifest entry's data_sequence_number; drives
|
||||
// delete-file applicability (NOT file_sequence_number).
|
||||
int64 data_sequence_number = 5;
|
||||
|
||||
// Partition spec id and serialized partition values; required to
|
||||
// match delete-file applicability for partitioned tables.
|
||||
int32 partition_spec_id = 6;
|
||||
bytes partition_values = 7;
|
||||
|
||||
// Position-delete files, equality-delete files, and deletion
|
||||
// vectors that apply to this data file. Discriminated by
|
||||
// DeleteFileRef.content + DeleteFileRef.file_format.
|
||||
repeated DeleteFileRef deletes = 8;
|
||||
}
|
||||
|
||||
message DeleteFileRef {
|
||||
string path = 1;
|
||||
int64 size_bytes = 2;
|
||||
|
||||
// Iceberg manifest entry's data_sequence_number for this delete
|
||||
// file. Applicability rule:
|
||||
// data_file.seq <= delete_file.seq for position deletes / DVs
|
||||
// data_file.seq < delete_file.seq for equality deletes
|
||||
int64 data_sequence_number = 3;
|
||||
|
||||
// Partition spec id and serialized partition values; must match
|
||||
// the data file's partition for the delete to apply.
|
||||
int32 partition_spec_id = 4;
|
||||
bytes partition_values = 5;
|
||||
|
||||
DeleteContent content = 6; // POSITION_DELETES / EQUALITY_DELETES
|
||||
FileFormat file_format = 7; // PARQUET / AVRO / ORC / PUFFIN
|
||||
|
||||
// Required for content == EQUALITY_DELETES, empty otherwise.
|
||||
repeated int32 equality_field_ids = 8;
|
||||
|
||||
// Puffin-only: when content == POSITION_DELETES and file_format
|
||||
// == PUFFIN (deletion vectors), the DV blob lives at
|
||||
// (path, blob_offset, blob_length). blob_crc32 is the Puffin
|
||||
// footer's per-blob CRC, used for tamper detection (not as
|
||||
// identity for cache lookup).
|
||||
int64 blob_offset = 9;
|
||||
int64 blob_length = 10;
|
||||
uint32 blob_crc32 = 11;
|
||||
|
||||
// When this delete file targets one specific data file (mandatory
|
||||
// for v3 deletion vectors). Empty when the delete file may target
|
||||
// many data files.
|
||||
string referenced_data_file = 12;
|
||||
}
|
||||
|
||||
enum DeleteContent {
|
||||
DELETE_CONTENT_UNSPECIFIED = 0;
|
||||
POSITION_DELETES = 1; // Iceberg manifest content=1 (file or DV)
|
||||
EQUALITY_DELETES = 2; // Iceberg manifest content=2
|
||||
// Iceberg v3 deletion vectors are POSITION_DELETES with
|
||||
// file_format == PUFFIN; there is no separate enum value.
|
||||
}
|
||||
|
||||
enum FileFormat {
|
||||
FILE_FORMAT_UNSPECIFIED = 0;
|
||||
FILE_FORMAT_PARQUET = 1;
|
||||
FILE_FORMAT_AVRO = 2;
|
||||
FILE_FORMAT_ORC = 3;
|
||||
FILE_FORMAT_PUFFIN = 4;
|
||||
}
|
||||
|
||||
enum PredicateKind {
|
||||
PREDICATE_KIND_UNSPECIFIED = 0;
|
||||
PREDICATE_KIND_SUBSTRAIT = 1; // Substrait ExtendedExpression protobuf
|
||||
PREDICATE_KIND_ICEBERG = 2; // Iceberg Expression JSON
|
||||
}
|
||||
|
||||
enum VectorMetric {
|
||||
VECTOR_METRIC_UNSPECIFIED = 0;
|
||||
VECTOR_METRIC_L2 = 1;
|
||||
VECTOR_METRIC_COSINE = 2;
|
||||
VECTOR_METRIC_DOT = 3;
|
||||
}
|
||||
|
||||
message VectorQuery {
|
||||
ColumnRef column = 1;
|
||||
repeated float vector = 2;
|
||||
VectorMetric metric = 3;
|
||||
int32 top_k = 4;
|
||||
int32 nprobe = 5;
|
||||
}
|
||||
|
||||
// ColumnRef identifies a column by Iceberg field id (stable across
|
||||
// rename and reordering). Path is an optional hint used only when
|
||||
// field_id == 0 (e.g. non-Iceberg Parquet that has no field ids).
|
||||
message ColumnRef {
|
||||
int32 field_id = 1;
|
||||
string path = 2;
|
||||
}
|
||||
|
||||
// -- Response ----------------------------------------------------------------
|
||||
|
||||
message ParquetPushdownResponse {
|
||||
repeated FileRange file_ranges = 1;
|
||||
repeated RowGroupRef row_groups = 2;
|
||||
repeated PageRef pages = 3;
|
||||
|
||||
// Optional, emitted only when request.request_row_ids is true and
|
||||
// the result fits within request.max_row_ids.
|
||||
repeated ScoredRowRef row_refs = 4;
|
||||
|
||||
// True if a row-ref list was omitted or truncated due to size cap.
|
||||
bool truncated = 5;
|
||||
|
||||
PushdownStats stats = 6;
|
||||
}
|
||||
|
||||
message FileRange {
|
||||
string file = 1;
|
||||
int64 offset = 2;
|
||||
int64 length = 3;
|
||||
}
|
||||
|
||||
message RowGroupRef {
|
||||
string file = 1;
|
||||
int32 row_group = 2;
|
||||
}
|
||||
|
||||
message PageRef {
|
||||
string file = 1;
|
||||
int32 row_group = 2;
|
||||
ColumnRef column = 3;
|
||||
int32 page = 4;
|
||||
int64 offset = 5;
|
||||
int64 length = 6;
|
||||
}
|
||||
|
||||
// RowRef identifies a row by file-absolute position (matching Iceberg
|
||||
// position-delete semantics). row_group is a locality hint, not
|
||||
// authoritative.
|
||||
message RowRef {
|
||||
string file = 1;
|
||||
int32 row_group = 2;
|
||||
int64 file_position = 3;
|
||||
}
|
||||
|
||||
message ScoredRowRef {
|
||||
RowRef ref = 1;
|
||||
// has_score distinguishes "no score available" from "score is
|
||||
// 0.0", which is a legal vector-similarity value (zero L2
|
||||
// distance, zero dot product). Non-vector queries leave
|
||||
// has_score false; vector queries always set it true.
|
||||
bool has_score = 2;
|
||||
float score = 3;
|
||||
}
|
||||
|
||||
message PushdownStats {
|
||||
// The trust mode that serviced this request.
|
||||
string trust_mode = 1;
|
||||
|
||||
// Server-side wall time spent on this request, in microseconds.
|
||||
int64 server_time_micros = 2;
|
||||
|
||||
// Filled in by later milestones as the corresponding subsystems
|
||||
// come online. Names use the design doc's per-feature labels.
|
||||
int64 footer_cache_hits = 3;
|
||||
int64 footer_cache_misses = 4;
|
||||
int64 row_groups_pruned = 5;
|
||||
int64 pages_pruned = 6;
|
||||
int64 bytes_planned_scan = 7;
|
||||
|
||||
// Side indexes consulted vs missing, by index kind ("bloom",
|
||||
// "bitmap", "btree", "page", "vector", ...). Useful both for
|
||||
// observability and for the connector's cost-model feedback loop.
|
||||
repeated string indexes_used = 8;
|
||||
repeated string indexes_missing = 9;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,180 +0,0 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.33.4
|
||||
// source: parquet_pushdown.proto
|
||||
|
||||
package parquet_pushdown_pb
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
SeaweedParquetPushdown_Ping_FullMethodName = "/parquet_pushdown_pb.SeaweedParquetPushdown/Ping"
|
||||
SeaweedParquetPushdown_Pushdown_FullMethodName = "/parquet_pushdown_pb.SeaweedParquetPushdown/Pushdown"
|
||||
)
|
||||
|
||||
// SeaweedParquetPushdownClient is the client API for SeaweedParquetPushdown service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// SeaweedParquetPushdown is the gRPC surface of the standalone
|
||||
// `weed pushdown` daemon. See PARQUET_PUSHDOWN_DESIGN.md and
|
||||
// PARQUET_PUSHDOWN_DEV_PLAN.md for the surrounding design.
|
||||
type SeaweedParquetPushdownClient interface {
|
||||
// Ping returns daemon liveness information. Cheap; intended for
|
||||
// smoke tests and connector health checks.
|
||||
Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error)
|
||||
// Pushdown takes a planner-resolved set of Iceberg data files and
|
||||
// returns the byte ranges, row groups, pages, and (optionally) row
|
||||
// refs that satisfy the request's predicate and vector clauses.
|
||||
// M0 returns Unimplemented; later milestones fill in pruning logic.
|
||||
Pushdown(ctx context.Context, in *ParquetPushdownRequest, opts ...grpc.CallOption) (*ParquetPushdownResponse, error)
|
||||
}
|
||||
|
||||
type seaweedParquetPushdownClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewSeaweedParquetPushdownClient(cc grpc.ClientConnInterface) SeaweedParquetPushdownClient {
|
||||
return &seaweedParquetPushdownClient{cc}
|
||||
}
|
||||
|
||||
func (c *seaweedParquetPushdownClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(PingResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedParquetPushdown_Ping_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedParquetPushdownClient) Pushdown(ctx context.Context, in *ParquetPushdownRequest, opts ...grpc.CallOption) (*ParquetPushdownResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ParquetPushdownResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedParquetPushdown_Pushdown_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SeaweedParquetPushdownServer is the server API for SeaweedParquetPushdown service.
|
||||
// All implementations must embed UnimplementedSeaweedParquetPushdownServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// SeaweedParquetPushdown is the gRPC surface of the standalone
|
||||
// `weed pushdown` daemon. See PARQUET_PUSHDOWN_DESIGN.md and
|
||||
// PARQUET_PUSHDOWN_DEV_PLAN.md for the surrounding design.
|
||||
type SeaweedParquetPushdownServer interface {
|
||||
// Ping returns daemon liveness information. Cheap; intended for
|
||||
// smoke tests and connector health checks.
|
||||
Ping(context.Context, *PingRequest) (*PingResponse, error)
|
||||
// Pushdown takes a planner-resolved set of Iceberg data files and
|
||||
// returns the byte ranges, row groups, pages, and (optionally) row
|
||||
// refs that satisfy the request's predicate and vector clauses.
|
||||
// M0 returns Unimplemented; later milestones fill in pruning logic.
|
||||
Pushdown(context.Context, *ParquetPushdownRequest) (*ParquetPushdownResponse, error)
|
||||
mustEmbedUnimplementedSeaweedParquetPushdownServer()
|
||||
}
|
||||
|
||||
// UnimplementedSeaweedParquetPushdownServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedSeaweedParquetPushdownServer struct{}
|
||||
|
||||
func (UnimplementedSeaweedParquetPushdownServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedParquetPushdownServer) Pushdown(context.Context, *ParquetPushdownRequest) (*ParquetPushdownResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Pushdown not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedParquetPushdownServer) mustEmbedUnimplementedSeaweedParquetPushdownServer() {
|
||||
}
|
||||
func (UnimplementedSeaweedParquetPushdownServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeSeaweedParquetPushdownServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to SeaweedParquetPushdownServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeSeaweedParquetPushdownServer interface {
|
||||
mustEmbedUnimplementedSeaweedParquetPushdownServer()
|
||||
}
|
||||
|
||||
func RegisterSeaweedParquetPushdownServer(s grpc.ServiceRegistrar, srv SeaweedParquetPushdownServer) {
|
||||
// If the following call pancis, it indicates UnimplementedSeaweedParquetPushdownServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&SeaweedParquetPushdown_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _SeaweedParquetPushdown_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(PingRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedParquetPushdownServer).Ping(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedParquetPushdown_Ping_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedParquetPushdownServer).Ping(ctx, req.(*PingRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedParquetPushdown_Pushdown_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ParquetPushdownRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedParquetPushdownServer).Pushdown(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedParquetPushdown_Pushdown_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedParquetPushdownServer).Pushdown(ctx, req.(*ParquetPushdownRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// SeaweedParquetPushdown_ServiceDesc is the grpc.ServiceDesc for SeaweedParquetPushdown service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var SeaweedParquetPushdown_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "parquet_pushdown_pb.SeaweedParquetPushdown",
|
||||
HandlerType: (*SeaweedParquetPushdownServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Ping",
|
||||
Handler: _SeaweedParquetPushdown_Ping_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "Pushdown",
|
||||
Handler: _SeaweedParquetPushdown_Pushdown_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "parquet_pushdown.proto",
|
||||
}
|
||||
+141
-11
@@ -189,10 +189,17 @@ type multipartPartBoundary struct {
|
||||
ETag string `json:"etag"`
|
||||
}
|
||||
|
||||
type multipartSSES3Info struct {
|
||||
keyData []byte
|
||||
key *SSES3Key
|
||||
baseIV []byte
|
||||
}
|
||||
|
||||
type multipartCompletionState struct {
|
||||
deleteEntries []*filer_pb.Entry
|
||||
partEntries map[int][]*filer_pb.Entry
|
||||
pentry *filer_pb.Entry
|
||||
sses3Info *multipartSSES3Info
|
||||
mime string
|
||||
finalParts []*filer_pb.FileChunk
|
||||
offset int64
|
||||
@@ -221,6 +228,125 @@ func completeMultipartResult(r *http.Request, input *s3.CompleteMultipartUploadI
|
||||
return result
|
||||
}
|
||||
|
||||
func extractMultipartSSES3Info(entry *filer_pb.Entry) (*multipartSSES3Info, error) {
|
||||
if entry == nil || entry.Extended == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if encryptionType := string(entry.Extended[s3_constants.SeaweedFSSSES3Encryption]); encryptionType != s3_constants.SSEAlgorithmAES256 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
baseIVEncoded := entry.Extended[s3_constants.SeaweedFSSSES3BaseIV]
|
||||
if len(baseIVEncoded) == 0 {
|
||||
return nil, fmt.Errorf("missing SSE-S3 multipart base IV")
|
||||
}
|
||||
baseIV, err := base64.StdEncoding.DecodeString(string(baseIVEncoded))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode SSE-S3 multipart base IV: %w", err)
|
||||
}
|
||||
if len(baseIV) != s3_constants.AESBlockSize {
|
||||
return nil, fmt.Errorf("invalid SSE-S3 multipart base IV length %d", len(baseIV))
|
||||
}
|
||||
|
||||
keyDataEncoded := entry.Extended[s3_constants.SeaweedFSSSES3KeyData]
|
||||
if len(keyDataEncoded) == 0 {
|
||||
return nil, fmt.Errorf("missing SSE-S3 multipart key data")
|
||||
}
|
||||
keyData, err := base64.StdEncoding.DecodeString(string(keyDataEncoded))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode SSE-S3 multipart key data: %w", err)
|
||||
}
|
||||
|
||||
key, err := DeserializeSSES3Metadata(keyData, GetSSES3KeyManager())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("deserialize SSE-S3 multipart key data: %w", err)
|
||||
}
|
||||
|
||||
return &multipartSSES3Info{
|
||||
keyData: keyData,
|
||||
key: key,
|
||||
baseIV: baseIV,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func completedMultipartChunk(chunk *filer_pb.FileChunk, offset int64, sses3Info *multipartSSES3Info) (*filer_pb.FileChunk, error) {
|
||||
finalChunk := &filer_pb.FileChunk{
|
||||
FileId: chunk.GetFileIdString(),
|
||||
Offset: offset,
|
||||
Size: chunk.Size,
|
||||
ModifiedTsNs: chunk.ModifiedTsNs,
|
||||
CipherKey: chunk.CipherKey,
|
||||
ETag: chunk.ETag,
|
||||
IsCompressed: chunk.IsCompressed,
|
||||
SseType: chunk.SseType,
|
||||
SseMetadata: chunk.SseMetadata,
|
||||
}
|
||||
|
||||
if sses3Info == nil {
|
||||
return finalChunk, nil
|
||||
}
|
||||
if finalChunk.GetSseType() != filer_pb.SSEType_NONE && finalChunk.GetSseType() != filer_pb.SSEType_SSE_S3 {
|
||||
return finalChunk, nil
|
||||
}
|
||||
// Trust existing per-chunk SSE-S3 metadata: if the part went through
|
||||
// putToFiler's chunk loop with a non-nil sseS3Key it carries an offset
|
||||
// derived IV that we cannot recover from the upload-entry alone. We do
|
||||
// not validate that the embedded IV equals calculateIVWithOffset(baseIV,
|
||||
// chunk.Offset); only completely missing metadata is backfilled. This
|
||||
// keeps healthy parts untouched and limits backfill to the cases that
|
||||
// caused #8908.
|
||||
if finalChunk.GetSseType() == filer_pb.SSEType_SSE_S3 && len(finalChunk.GetSseMetadata()) > 0 {
|
||||
return finalChunk, nil
|
||||
}
|
||||
|
||||
// IV uses the chunk's offset within its part, with no partNumber term.
|
||||
// This mirrors the encryption side: putToFiler hardcodes partOffset=0 when
|
||||
// it calls handleSSES3MultipartEncryption for every part, so each part's
|
||||
// encrypted stream begins at IV = calculateIVWithOffset(baseIV, 0) = baseIV.
|
||||
// Each chunk within that stream is then at IV =
|
||||
// calculateIVWithOffset(baseIV, chunk.Offset_part_local). Any deviation
|
||||
// (e.g. adding (partNumber-1)*PartOffsetMultiplier) would produce IVs that
|
||||
// do not match the actual encryption and would corrupt decryption.
|
||||
chunkIV, _ := calculateIVWithOffset(sses3Info.baseIV, chunk.GetOffset())
|
||||
chunkKey := &SSES3Key{
|
||||
Key: sses3Info.key.Key,
|
||||
KeyID: sses3Info.key.KeyID,
|
||||
Algorithm: sses3Info.key.Algorithm,
|
||||
IV: chunkIV,
|
||||
}
|
||||
chunkMetadata, err := SerializeSSES3Metadata(chunkKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serialize SSE-S3 chunk metadata for %s: %w", chunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
finalChunk.SseType = filer_pb.SSEType_SSE_S3
|
||||
finalChunk.SseMetadata = chunkMetadata
|
||||
return finalChunk, nil
|
||||
}
|
||||
|
||||
// applyMultipartSSES3HeadersFromUploadEntry writes the canonical object-level
|
||||
// SSE-S3 attributes (SeaweedFSSSES3Key / X-Amz-Server-Side-Encryption) onto a
|
||||
// completed multipart entry when they are missing. detectPrimarySSEType uses
|
||||
// the object-level X-Amz-Server-Side-Encryption header to recognize SSE-S3 on
|
||||
// inline / small-object reads, and IsSSES3EncryptedInternal requires both keys
|
||||
// to consider an object encrypted at all. Without this, an object whose first
|
||||
// part lacked the canonical attributes (e.g. a part written through a path
|
||||
// that did not set them) would be served as unencrypted on GET.
|
||||
func applyMultipartSSES3HeadersFromUploadEntry(dst *filer_pb.Entry, sses3Info *multipartSSES3Info) {
|
||||
if dst == nil || sses3Info == nil {
|
||||
return
|
||||
}
|
||||
if dst.Extended == nil {
|
||||
dst.Extended = make(map[string][]byte)
|
||||
}
|
||||
if _, exists := dst.Extended[s3_constants.SeaweedFSSSES3Key]; !exists {
|
||||
dst.Extended[s3_constants.SeaweedFSSSES3Key] = sses3Info.keyData
|
||||
}
|
||||
if _, exists := dst.Extended[s3_constants.AmzServerSideEncryption]; !exists {
|
||||
dst.Extended[s3_constants.AmzServerSideEncryption] = []byte(s3_constants.SSEAlgorithmAES256)
|
||||
}
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *s3.CompleteMultipartUploadInput, uploadDirectory, entryName, dirName string, completedPartNumbers []int, completedPartMap map[int][]string, maxPartNo int) (*multipartCompletionState, *CompleteMultipartUploadResult, s3err.ErrorCode) {
|
||||
if entry, err := s3a.resolveObjectEntry(*input.Bucket, *input.Key); err == nil && entry != nil && entry.Extended != nil {
|
||||
if uploadId, ok := entry.Extended[s3_constants.SeaweedFSUploadId]; ok && *input.UploadId == string(uploadId) {
|
||||
@@ -312,6 +438,11 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
if pentry.Attributes != nil {
|
||||
mime = pentry.Attributes.Mime
|
||||
}
|
||||
sses3Info, sses3Err := extractMultipartSSES3Info(pentry)
|
||||
if sses3Err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s %s SSE-S3 metadata error: %v", *input.Bucket, *input.UploadId, sses3Err)
|
||||
return nil, nil, s3err.ErrInternalError
|
||||
}
|
||||
finalParts := make([]*filer_pb.FileChunk, 0)
|
||||
partBoundaries := make([]multipartPartBoundary, 0, len(completedPartNumbers))
|
||||
var offset int64
|
||||
@@ -339,17 +470,12 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
partETag := filer.ETag(entry)
|
||||
|
||||
for _, chunk := range entry.GetChunks() {
|
||||
finalParts = append(finalParts, &filer_pb.FileChunk{
|
||||
FileId: chunk.GetFileIdString(),
|
||||
Offset: offset,
|
||||
Size: chunk.Size,
|
||||
ModifiedTsNs: chunk.ModifiedTsNs,
|
||||
CipherKey: chunk.CipherKey,
|
||||
ETag: chunk.ETag,
|
||||
IsCompressed: chunk.IsCompressed,
|
||||
SseType: chunk.SseType,
|
||||
SseMetadata: chunk.SseMetadata,
|
||||
})
|
||||
finalChunk, chunkErr := completedMultipartChunk(chunk, offset, sses3Info)
|
||||
if chunkErr != nil {
|
||||
glog.Errorf("completeMultipartUpload %s %s SSE-S3 chunk metadata error: %v", *input.Bucket, *input.UploadId, chunkErr)
|
||||
return nil, nil, s3err.ErrInternalError
|
||||
}
|
||||
finalParts = append(finalParts, finalChunk)
|
||||
offset += int64(chunk.Size)
|
||||
}
|
||||
|
||||
@@ -387,6 +513,7 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
deleteEntries: deleteEntries,
|
||||
partEntries: partEntries,
|
||||
pentry: pentry,
|
||||
sses3Info: sses3Info,
|
||||
mime: mime,
|
||||
finalParts: finalParts,
|
||||
offset: offset,
|
||||
@@ -493,6 +620,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
firstPartEntry := completionState.partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(versionEntry, firstPartEntry, "versioned")
|
||||
}
|
||||
applyMultipartSSES3HeadersFromUploadEntry(versionEntry, completionState.sses3Info)
|
||||
if completionState.pentry.Attributes != nil && completionState.pentry.Attributes.Mime != "" {
|
||||
versionEntry.Attributes.Mime = completionState.pentry.Attributes.Mime
|
||||
} else if completionState.mime != "" {
|
||||
@@ -578,6 +706,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
firstPartEntry := completionState.partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(entry, firstPartEntry, "suspended versioning")
|
||||
}
|
||||
applyMultipartSSES3HeadersFromUploadEntry(entry, completionState.sses3Info)
|
||||
// Persist ETag to ensure subsequent HEAD/GET uses the same value
|
||||
entry.Extended[s3_constants.ExtETagKey] = []byte(completionState.multipartETag)
|
||||
// Store composite checksum if computed from per-part checksums
|
||||
@@ -640,6 +769,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
firstPartEntry := completionState.partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(entry, firstPartEntry, "non-versioned")
|
||||
}
|
||||
applyMultipartSSES3HeadersFromUploadEntry(entry, completionState.sses3Info)
|
||||
// Persist ETag to ensure subsequent HEAD/GET uses the same value
|
||||
entry.Extended[s3_constants.ExtETagKey] = []byte(completionState.multipartETag)
|
||||
// Store composite checksum if computed from per-part checksums
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
func TestCompletedMultipartChunkBackfillsSSES3MetadataFromUploadEntry(t *testing.T) {
|
||||
keyManager := initSSES3KeyManagerForTest(t)
|
||||
|
||||
key, err := GenerateSSES3Key()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSSES3Key: %v", err)
|
||||
}
|
||||
keyData, err := SerializeSSES3Metadata(key)
|
||||
if err != nil {
|
||||
t.Fatalf("SerializeSSES3Metadata: %v", err)
|
||||
}
|
||||
|
||||
baseIV := []byte("1234567890abcdef")
|
||||
uploadEntry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.SeaweedFSSSES3Encryption: []byte(s3_constants.SSEAlgorithmAES256),
|
||||
s3_constants.SeaweedFSSSES3BaseIV: []byte(base64.StdEncoding.EncodeToString(baseIV)),
|
||||
s3_constants.SeaweedFSSSES3KeyData: []byte(base64.StdEncoding.EncodeToString(keyData)),
|
||||
},
|
||||
}
|
||||
|
||||
sses3Info, err := extractMultipartSSES3Info(uploadEntry)
|
||||
if err != nil {
|
||||
t.Fatalf("extractMultipartSSES3Info: %v", err)
|
||||
}
|
||||
|
||||
partLocalOffset := int64(8 * 1024 * 1024)
|
||||
finalObjectOffset := int64(40 * 1024 * 1024)
|
||||
chunk := &filer_pb.FileChunk{
|
||||
FileId: "1,abc",
|
||||
Offset: partLocalOffset,
|
||||
Size: 1024,
|
||||
}
|
||||
|
||||
finalChunk, err := completedMultipartChunk(chunk, finalObjectOffset, sses3Info)
|
||||
if err != nil {
|
||||
t.Fatalf("completedMultipartChunk: %v", err)
|
||||
}
|
||||
if finalChunk.GetOffset() != finalObjectOffset {
|
||||
t.Fatalf("final chunk offset = %d, want %d", finalChunk.GetOffset(), finalObjectOffset)
|
||||
}
|
||||
if finalChunk.GetSseType() != filer_pb.SSEType_SSE_S3 {
|
||||
t.Fatalf("final chunk SSE type = %s, want SSE_S3", finalChunk.GetSseType())
|
||||
}
|
||||
if len(finalChunk.GetSseMetadata()) == 0 {
|
||||
t.Fatal("expected final chunk SSE metadata")
|
||||
}
|
||||
|
||||
chunkKey, err := DeserializeSSES3Metadata(finalChunk.GetSseMetadata(), keyManager)
|
||||
if err != nil {
|
||||
t.Fatalf("DeserializeSSES3Metadata: %v", err)
|
||||
}
|
||||
if !bytes.Equal(chunkKey.Key, key.Key) {
|
||||
t.Fatal("chunk metadata key does not match upload key")
|
||||
}
|
||||
expectedIV, _ := calculateIVWithOffset(baseIV, partLocalOffset)
|
||||
if !bytes.Equal(chunkKey.IV, expectedIV) {
|
||||
t.Fatalf("chunk metadata IV = %x, want %x", chunkKey.IV, expectedIV)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletedMultipartChunkPreservesExistingSSES3Metadata(t *testing.T) {
|
||||
existingMetadata := []byte("already-present")
|
||||
chunk := &filer_pb.FileChunk{
|
||||
FileId: "2,abc",
|
||||
Offset: 1024,
|
||||
Size: 2048,
|
||||
SseType: filer_pb.SSEType_SSE_S3,
|
||||
SseMetadata: existingMetadata,
|
||||
}
|
||||
|
||||
finalChunk, err := completedMultipartChunk(chunk, 4096, &multipartSSES3Info{})
|
||||
if err != nil {
|
||||
t.Fatalf("completedMultipartChunk: %v", err)
|
||||
}
|
||||
if !bytes.Equal(finalChunk.GetSseMetadata(), existingMetadata) {
|
||||
t.Fatal("existing SSE-S3 metadata should be preserved")
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyMultipartSSES3HeadersFromUploadEntry pins the canonical object-level
|
||||
// SSE-S3 attributes onto the completed entry: SeaweedFSSSES3Key (used by
|
||||
// IsSSES3EncryptedInternal and the read-side decryption-key lookup) and
|
||||
// X-Amz-Server-Side-Encryption (used by detectPrimarySSEType for non-chunked
|
||||
// reads). Pre-existing values must not be clobbered.
|
||||
func TestApplyMultipartSSES3HeadersFromUploadEntry(t *testing.T) {
|
||||
initSSES3KeyManagerForTest(t)
|
||||
|
||||
key, err := GenerateSSES3Key()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSSES3Key: %v", err)
|
||||
}
|
||||
keyData, err := SerializeSSES3Metadata(key)
|
||||
if err != nil {
|
||||
t.Fatalf("SerializeSSES3Metadata: %v", err)
|
||||
}
|
||||
|
||||
baseIV := []byte("1234567890abcdef")
|
||||
uploadEntry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.SeaweedFSSSES3Encryption: []byte(s3_constants.SSEAlgorithmAES256),
|
||||
s3_constants.SeaweedFSSSES3BaseIV: []byte(base64.StdEncoding.EncodeToString(baseIV)),
|
||||
s3_constants.SeaweedFSSSES3KeyData: []byte(base64.StdEncoding.EncodeToString(keyData)),
|
||||
},
|
||||
}
|
||||
sses3Info, err := extractMultipartSSES3Info(uploadEntry)
|
||||
if err != nil {
|
||||
t.Fatalf("extractMultipartSSES3Info: %v", err)
|
||||
}
|
||||
|
||||
t.Run("backfills missing canonical attributes", func(t *testing.T) {
|
||||
finalEntry := &filer_pb.Entry{Extended: map[string][]byte{}}
|
||||
applyMultipartSSES3HeadersFromUploadEntry(finalEntry, sses3Info)
|
||||
if !bytes.Equal(finalEntry.Extended[s3_constants.SeaweedFSSSES3Key], keyData) {
|
||||
t.Fatal("final entry did not receive object-level SSE-S3 key metadata")
|
||||
}
|
||||
if got := string(finalEntry.Extended[s3_constants.AmzServerSideEncryption]); got != s3_constants.SSEAlgorithmAES256 {
|
||||
t.Fatalf("final entry SSE header = %q, want %q", got, s3_constants.SSEAlgorithmAES256)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("does not clobber existing canonical attributes", func(t *testing.T) {
|
||||
existingKey := []byte("existing-key-bytes")
|
||||
existingHeader := []byte("aws:kms")
|
||||
finalEntry := &filer_pb.Entry{Extended: map[string][]byte{
|
||||
s3_constants.SeaweedFSSSES3Key: existingKey,
|
||||
s3_constants.AmzServerSideEncryption: existingHeader,
|
||||
}}
|
||||
applyMultipartSSES3HeadersFromUploadEntry(finalEntry, sses3Info)
|
||||
if !bytes.Equal(finalEntry.Extended[s3_constants.SeaweedFSSSES3Key], existingKey) {
|
||||
t.Fatal("existing SSE-S3 key was overwritten")
|
||||
}
|
||||
if !bytes.Equal(finalEntry.Extended[s3_constants.AmzServerSideEncryption], existingHeader) {
|
||||
t.Fatal("existing X-Amz-Server-Side-Encryption was overwritten")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nil info is a no-op", func(t *testing.T) {
|
||||
finalEntry := &filer_pb.Entry{Extended: map[string][]byte{}}
|
||||
applyMultipartSSES3HeadersFromUploadEntry(finalEntry, nil)
|
||||
if len(finalEntry.Extended) != 0 {
|
||||
t.Fatalf("nil sses3Info should not write any keys, got %d", len(finalEntry.Extended))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestCompletedMultipartChunkBackfilledIVDecryptsActualCiphertext is a round
|
||||
// trip across the encryption boundary: it encrypts simulated multipart parts
|
||||
// using the same call path putToFiler uses (CreateSSES3EncryptedReaderWithBaseIV
|
||||
// with partOffset=0, then chunked at fixed boundaries), throws away the chunk
|
||||
// level SSE metadata to simulate the bug from #8908, runs completedMultipartChunk
|
||||
// to backfill it, and decrypts each chunk's slice of ciphertext with the
|
||||
// backfilled IV. The plaintext must come back intact.
|
||||
//
|
||||
// Regression coverage for the gemini review on #9224 which suggested using
|
||||
// (partNumber-1)*PartOffsetMultiplier + chunk.Offset for the backfill IV. That
|
||||
// formula does not match what the encryption side actually does (PartOffsetMultiplier
|
||||
// is defined but not used in the write path), so adopting it would silently
|
||||
// produce backfilled IVs that fail to decrypt the bytes on disk.
|
||||
func TestCompletedMultipartChunkBackfilledIVDecryptsActualCiphertext(t *testing.T) {
|
||||
keyManager := initSSES3KeyManagerForTest(t)
|
||||
|
||||
key, err := GenerateSSES3Key()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSSES3Key: %v", err)
|
||||
}
|
||||
keyData, err := SerializeSSES3Metadata(key)
|
||||
if err != nil {
|
||||
t.Fatalf("SerializeSSES3Metadata: %v", err)
|
||||
}
|
||||
|
||||
baseIV := make([]byte, s3_constants.AESBlockSize)
|
||||
if _, err := rand.Read(baseIV); err != nil {
|
||||
t.Fatalf("rand.Read baseIV: %v", err)
|
||||
}
|
||||
|
||||
uploadEntry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.SeaweedFSSSES3Encryption: []byte(s3_constants.SSEAlgorithmAES256),
|
||||
s3_constants.SeaweedFSSSES3BaseIV: []byte(base64.StdEncoding.EncodeToString(baseIV)),
|
||||
s3_constants.SeaweedFSSSES3KeyData: []byte(base64.StdEncoding.EncodeToString(keyData)),
|
||||
},
|
||||
}
|
||||
sses3Info, err := extractMultipartSSES3Info(uploadEntry)
|
||||
if err != nil {
|
||||
t.Fatalf("extractMultipartSSES3Info: %v", err)
|
||||
}
|
||||
|
||||
const chunkSize = int64(8 * 1024 * 1024)
|
||||
|
||||
// Two parts: part 1 spans three internal chunks (offsets 0, 8MB, 16MB),
|
||||
// part 2 spans two (offsets 0, 8MB). Both parts are encrypted independently
|
||||
// with partOffset=0, the way putToFiler invokes the encryption path today.
|
||||
parts := []struct {
|
||||
name string
|
||||
plaintext []byte
|
||||
}{
|
||||
{"part1", makeRandomPlaintext(t, int(chunkSize)*3-1234)},
|
||||
{"part2", makeRandomPlaintext(t, int(chunkSize)*2+5678)},
|
||||
}
|
||||
|
||||
for _, p := range parts {
|
||||
t.Run(p.name, func(t *testing.T) {
|
||||
// Encrypt the part stream the same way handleSSES3MultipartEncryption does.
|
||||
encReader, _, err := CreateSSES3EncryptedReaderWithBaseIV(bytes.NewReader(p.plaintext), key, baseIV, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSSES3EncryptedReaderWithBaseIV: %v", err)
|
||||
}
|
||||
ciphertext, err := io.ReadAll(encReader)
|
||||
if err != nil {
|
||||
t.Fatalf("read encrypted stream: %v", err)
|
||||
}
|
||||
if len(ciphertext) != len(p.plaintext) {
|
||||
t.Fatalf("ciphertext length %d != plaintext length %d", len(ciphertext), len(p.plaintext))
|
||||
}
|
||||
|
||||
// Slice the encrypted stream into chunks the same way UploadReaderInChunks
|
||||
// would, and build FileChunks tagged SseType=NONE to simulate the bug.
|
||||
var bugChunks []*filer_pb.FileChunk
|
||||
for off := int64(0); off < int64(len(ciphertext)); off += chunkSize {
|
||||
end := off + chunkSize
|
||||
if end > int64(len(ciphertext)) {
|
||||
end = int64(len(ciphertext))
|
||||
}
|
||||
bugChunks = append(bugChunks, &filer_pb.FileChunk{
|
||||
FileId: "1,deadbeef",
|
||||
Offset: off,
|
||||
Size: uint64(end - off),
|
||||
// SseType deliberately left at default NONE.
|
||||
})
|
||||
}
|
||||
|
||||
// finalOffset doesn't influence the IV calculation, only the chunk's
|
||||
// position in the assembled object. Use a fake non-zero value to
|
||||
// confirm the function does not accidentally use it for the IV.
|
||||
const finalOffset int64 = 1 << 40
|
||||
|
||||
for _, bugChunk := range bugChunks {
|
||||
finalChunk, err := completedMultipartChunk(bugChunk, finalOffset+bugChunk.Offset, sses3Info)
|
||||
if err != nil {
|
||||
t.Fatalf("completedMultipartChunk(offset=%d): %v", bugChunk.Offset, err)
|
||||
}
|
||||
if finalChunk.GetSseType() != filer_pb.SSEType_SSE_S3 {
|
||||
t.Fatalf("chunk@%d not retagged SSE_S3", bugChunk.Offset)
|
||||
}
|
||||
meta, err := DeserializeSSES3Metadata(finalChunk.GetSseMetadata(), keyManager)
|
||||
if err != nil {
|
||||
t.Fatalf("DeserializeSSES3Metadata(chunk@%d): %v", bugChunk.Offset, err)
|
||||
}
|
||||
|
||||
cipherSlice := ciphertext[bugChunk.Offset : bugChunk.Offset+int64(bugChunk.Size)]
|
||||
wantPlain := p.plaintext[bugChunk.Offset : bugChunk.Offset+int64(bugChunk.Size)]
|
||||
|
||||
decReader, err := CreateSSES3DecryptedReader(bytes.NewReader(cipherSlice), key, meta.IV)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSSES3DecryptedReader(chunk@%d): %v", bugChunk.Offset, err)
|
||||
}
|
||||
gotPlain, err := io.ReadAll(decReader)
|
||||
if err != nil {
|
||||
t.Fatalf("read decrypted chunk@%d: %v", bugChunk.Offset, err)
|
||||
}
|
||||
if !bytes.Equal(gotPlain, wantPlain) {
|
||||
t.Fatalf("chunk@%d: backfilled IV produced wrong plaintext (first mismatch byte at %d)",
|
||||
bugChunk.Offset, firstMismatch(gotPlain, wantPlain))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCompletedMultipartChunkRejectsPartNumberMultiplierFormula is a guard
|
||||
// against re-introducing the gemini review's suggested formula, which would
|
||||
// produce IVs incompatible with the encryption side. The test simulates what
|
||||
// would happen if the backfill used (partNumber-1)*PartOffsetMultiplier as an
|
||||
// extra offset term: the resulting IV does not decrypt the actual ciphertext.
|
||||
func TestCompletedMultipartChunkRejectsPartNumberMultiplierFormula(t *testing.T) {
|
||||
key, err := GenerateSSES3Key()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSSES3Key: %v", err)
|
||||
}
|
||||
baseIV := make([]byte, s3_constants.AESBlockSize)
|
||||
if _, err := rand.Read(baseIV); err != nil {
|
||||
t.Fatalf("rand.Read baseIV: %v", err)
|
||||
}
|
||||
|
||||
plaintext := makeRandomPlaintext(t, 4096)
|
||||
|
||||
encReader, _, err := CreateSSES3EncryptedReaderWithBaseIV(bytes.NewReader(plaintext), key, baseIV, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSSES3EncryptedReaderWithBaseIV: %v", err)
|
||||
}
|
||||
ciphertext, err := io.ReadAll(encReader)
|
||||
if err != nil {
|
||||
t.Fatalf("read encrypted stream: %v", err)
|
||||
}
|
||||
|
||||
// "partNumber=2" with PartOffsetMultiplier added would shift the IV by 8GB.
|
||||
wrongIV, _ := calculateIVWithOffset(baseIV, s3_constants.PartOffsetMultiplier+0)
|
||||
|
||||
decReader, err := CreateSSES3DecryptedReader(bytes.NewReader(ciphertext), key, wrongIV)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSSES3DecryptedReader: %v", err)
|
||||
}
|
||||
got, err := io.ReadAll(decReader)
|
||||
if err != nil {
|
||||
t.Fatalf("read decrypted: %v", err)
|
||||
}
|
||||
if bytes.Equal(got, plaintext) {
|
||||
t.Fatal("partNumber-multiplier IV decrypted plaintext correctly; the backfill formula must NOT include this term")
|
||||
}
|
||||
}
|
||||
|
||||
func makeRandomPlaintext(t *testing.T, n int) []byte {
|
||||
t.Helper()
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
t.Fatalf("rand.Read: %v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func firstMismatch(a, b []byte) int {
|
||||
n := len(a)
|
||||
if len(b) < n {
|
||||
n = len(b)
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
if a[i] != b[i] {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -489,9 +489,10 @@ func TestBuildMultipartSSES3Reader_InvalidIVLength(t *testing.T) {
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
closed := false
|
||||
fetchCalled := false
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
return &closeTrackingReadCloser{Reader: bytes.NewReader([]byte("whatever")), closed: &closed}, nil
|
||||
fetchCalled = true
|
||||
return io.NopCloser(bytes.NewReader([]byte("whatever"))), nil
|
||||
}
|
||||
|
||||
chunks := []*filer_pb.FileChunk{
|
||||
@@ -508,27 +509,35 @@ func TestBuildMultipartSSES3Reader_InvalidIVLength(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid IV length, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "invalid IV length") {
|
||||
t.Errorf("expected 'invalid IV length' in error, got: %v", err)
|
||||
// ValidateIV's error format is "invalid <name> length: ...";
|
||||
// match on the part of the message that's stable across the
|
||||
// shared helper's wording.
|
||||
if !strings.Contains(err.Error(), "IV length") {
|
||||
t.Errorf("expected 'IV length' in error, got: %v", err)
|
||||
}
|
||||
if !closed {
|
||||
t.Error("chunk reader for the bad chunk was not closed on error")
|
||||
// Validation runs upfront before any chunk fetch, so no volume-server
|
||||
// HTTP connection should have been opened on the failure path.
|
||||
if fetchCalled {
|
||||
t.Error("fetchChunk was called for an invalid-IV chunk; metadata validation should fail before any fetch")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildMultipartSSES3Reader_ClosesAppendedOnError verifies that when a
|
||||
// later chunk fails (e.g., malformed metadata), readers already appended for
|
||||
// earlier valid chunks are closed so volume-server HTTP connections do not leak.
|
||||
func TestBuildMultipartSSES3Reader_ClosesAppendedOnError(t *testing.T) {
|
||||
// TestBuildMultipartSSES3Reader_RejectsBadChunkBeforeAnyFetch verifies that
|
||||
// when any chunk's metadata is malformed, the helper returns an error WITHOUT
|
||||
// having opened a volume-server HTTP connection for any chunk. Per-chunk
|
||||
// metadata is validated upfront precisely so a bad chunk in position N does
|
||||
// not leak open HTTP responses for chunks 0..N-1 (the original eager
|
||||
// implementation depended on a closeAppendedReaders cleanup path; this test
|
||||
// pins the stronger contract: nothing is opened in the first place).
|
||||
func TestBuildMultipartSSES3Reader_RejectsBadChunkBeforeAnyFetch(t *testing.T) {
|
||||
keyManager := initSSES3KeyManagerForTest(t)
|
||||
|
||||
// First chunk: valid SSE-S3 chunk.
|
||||
cipher1, meta1 := encryptSSES3Part(t, []byte("first chunk plaintext"))
|
||||
|
||||
// Second chunk: missing per-chunk metadata, triggers error after first is
|
||||
// already appended.
|
||||
// Second chunk: missing per-chunk metadata, triggers error.
|
||||
chunks := []*filer_pb.FileChunk{
|
||||
{
|
||||
FileId: "1,good",
|
||||
@@ -546,36 +555,20 @@ func TestBuildMultipartSSES3Reader_ClosesAppendedOnError(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
firstClosed := false
|
||||
secondClosed := false
|
||||
fetched := map[string]int{}
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
switch c.GetFileIdString() {
|
||||
case "1,good":
|
||||
return &closeTrackingReadCloser{Reader: bytes.NewReader(cipher1), closed: &firstClosed}, nil
|
||||
case "2,bad":
|
||||
return &closeTrackingReadCloser{Reader: bytes.NewReader([]byte("x")), closed: &secondClosed}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected chunk %s", c.GetFileIdString())
|
||||
fetched[c.GetFileIdString()]++
|
||||
return io.NopCloser(bytes.NewReader([]byte("x"))), nil
|
||||
}
|
||||
|
||||
_, err := buildMultipartSSES3Reader(chunks, keyManager, fetch)
|
||||
if err == nil {
|
||||
t.Fatal("expected error from missing chunk metadata, got nil")
|
||||
}
|
||||
if !firstClosed {
|
||||
t.Error("previously appended chunk reader was not closed on error")
|
||||
if !strings.Contains(err.Error(), "missing per-chunk metadata") {
|
||||
t.Errorf("expected 'missing per-chunk metadata' in error, got: %v", err)
|
||||
}
|
||||
if !secondClosed {
|
||||
t.Error("chunk reader for the failing chunk was not closed on error")
|
||||
if len(fetched) != 0 {
|
||||
t.Errorf("expected no chunks fetched on validation failure, got %v", fetched)
|
||||
}
|
||||
}
|
||||
|
||||
type closeTrackingReadCloser struct {
|
||||
io.Reader
|
||||
closed *bool
|
||||
}
|
||||
|
||||
func (r *closeTrackingReadCloser) Close() error {
|
||||
*r.closed = true
|
||||
return nil
|
||||
}
|
||||
@@ -353,7 +353,7 @@ func (e *EmbeddedIamApi) GetUser(s3cfg *iam_pb.S3ApiConfiguration, userName stri
|
||||
}
|
||||
|
||||
// UpdateUser updates an IAM user.
|
||||
func (e *EmbeddedIamApi) UpdateUser(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamUpdateUserResponse, *iamError) {
|
||||
func (e *EmbeddedIamApi) UpdateUser(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamUpdateUserResponse, *iamError) {
|
||||
resp := &iamUpdateUserResponse{}
|
||||
userName := values.Get("UserName")
|
||||
newUserName := values.Get("NewUserName")
|
||||
@@ -385,6 +385,44 @@ func (e *EmbeddedIamApi) UpdateUser(s3cfg *iam_pb.S3ApiConfiguration, values url
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate the credential store's view of this user before the rename
|
||||
// takes effect. Stores with referential integrity (Postgres) MUST
|
||||
// implement UserRenamer: per-row Put / Get / Delete migration would
|
||||
// violate the FK on user_inline_policies(username) at statement time
|
||||
// because the new users row does not exist yet. UserRenamer does the
|
||||
// rename, credential re-pointing and inline-policy re-pointing inside
|
||||
// a single transaction.
|
||||
//
|
||||
// For stores that don't have FK enforcement (memory, filer_etc) the
|
||||
// renamer is also implemented as a plain rebinding so the regression
|
||||
// test exercises the same code path.
|
||||
if e.credentialManager != nil {
|
||||
switch supported, err := e.credentialManager.RenameUser(ctx, userName, newUserName); {
|
||||
case err != nil:
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("rename user %s -> %s: %w", userName, newUserName, err)}
|
||||
case !supported:
|
||||
// Fallback: copy the inline policies under the new name and
|
||||
// let the subsequent SaveConfiguration prune CASCADE the old
|
||||
// rows. Only safe for stores without FK enforcement.
|
||||
policyNames, err := e.credentialManager.ListUserInlinePolicies(ctx, userName)
|
||||
if err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("list inline policies for %s: %w", userName, err)}
|
||||
}
|
||||
for _, policyName := range policyNames {
|
||||
doc, err := e.credentialManager.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
if err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("read inline policy %s for %s: %w", policyName, userName, err)}
|
||||
}
|
||||
if doc == nil {
|
||||
continue
|
||||
}
|
||||
if err := e.credentialManager.PutUserInlinePolicy(ctx, newUserName, policyName, *doc); err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("copy inline policy %s to %s: %w", policyName, newUserName, err)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sourceIdent.Name = newUserName
|
||||
// Update group membership references
|
||||
for _, g := range s3cfg.Groups {
|
||||
@@ -2167,7 +2205,7 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
changed = false
|
||||
case "UpdateUser":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.UpdateUser(s3cfg, values)
|
||||
response, iamErr = e.UpdateUser(ctx, s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
|
||||
@@ -862,6 +862,46 @@ func TestEmbeddedIamUpdateUser(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, response.Code)
|
||||
}
|
||||
|
||||
// TestEmbeddedIamUpdateUserPreservesInlinePolicies makes sure renaming a
|
||||
// user keeps that user's stored inline policies under the new name.
|
||||
// Without the explicit policy migration in UpdateUser, SaveConfiguration
|
||||
// prunes the old name and CASCADE drops the policies.
|
||||
func TestEmbeddedIamUpdateUserPreservesInlinePolicies(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
const (
|
||||
oldName = "RenameMe"
|
||||
newName = "Renamed"
|
||||
policyName = "ReadBucket"
|
||||
)
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: oldName}},
|
||||
}
|
||||
doc := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{{
|
||||
Effect: policy_engine.PolicyEffectAllow,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::bucket/*"),
|
||||
}},
|
||||
}
|
||||
require.NoError(t, api.credentialManager.PutUserInlinePolicy(context.Background(), oldName, policyName, doc))
|
||||
|
||||
params := &iam.UpdateUserInput{NewUserName: aws.String(newName), UserName: aws.String(oldName)}
|
||||
req, _ := iam.New(session.New()).UpdateUserRequest(params)
|
||||
_ = req.Build()
|
||||
out := iamUpdateUserResponse{}
|
||||
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, response.Code)
|
||||
|
||||
got, err := api.credentialManager.GetUserInlinePolicy(context.Background(), newName, policyName)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got, "inline policy should have been migrated to the new username")
|
||||
assert.Equal(t, doc.Version, got.Version)
|
||||
require.Len(t, got.Statement, 1)
|
||||
assert.Equal(t, policy_engine.PolicyEffectAllow, got.Statement[0].Effect)
|
||||
}
|
||||
|
||||
// TestEmbeddedIamDeleteUser tests deleting a user
|
||||
func TestEmbeddedIamDeleteUser(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// TestBuildMultipartSSEKMSReader_RejectsBadIVBeforeAnyFetch pins the contract
|
||||
// that a per-chunk SSE-KMS metadata blob with a missing or wrong-length IV is
|
||||
// rejected during preparation, before any volume-server fetch fires.
|
||||
//
|
||||
// DeserializeSSEKMSMetadata only proves the JSON parses; it leaves the
|
||||
// kmsKey.IV field at whatever the metadata actually carried. CreateSSEKMSDecryptedReader
|
||||
// does call ValidateIV, but only when the wrap closure runs -- after the
|
||||
// chunk's HTTP body has already been opened. The lazy reader's whole point
|
||||
// is to never start an HTTP fetch for a chunk we know we cannot decrypt, so
|
||||
// IV validation must happen in the prep loop. This test is the regression
|
||||
// guard for that, addressing CodeRabbit review feedback on PR #9228.
|
||||
func TestBuildMultipartSSEKMSReader_RejectsBadIVBeforeAnyFetch(t *testing.T) {
|
||||
makeMetadata := func(iv []byte) []byte {
|
||||
t.Helper()
|
||||
key := &SSEKMSKey{
|
||||
KeyID: "test-kms-key",
|
||||
EncryptedDataKey: bytes.Repeat([]byte{0x42}, 32),
|
||||
IV: iv,
|
||||
}
|
||||
md, err := SerializeSSEKMSMetadata(key)
|
||||
if err != nil {
|
||||
t.Fatalf("SerializeSSEKMSMetadata: %v", err)
|
||||
}
|
||||
return md
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
iv []byte
|
||||
expectErr string
|
||||
}{
|
||||
{"missing IV", nil, "invalid"},
|
||||
{"empty IV", []byte{}, "invalid"},
|
||||
{"short IV", []byte("too-short"), "invalid"}, // 9 bytes, not 16
|
||||
{"long IV", bytes.Repeat([]byte{1}, 32), "invalid"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fetchCalled := false
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
fetchCalled = true
|
||||
return io.NopCloser(bytes.NewReader([]byte("ignored"))), nil
|
||||
}
|
||||
|
||||
chunks := []*filer_pb.FileChunk{
|
||||
{
|
||||
FileId: "1,bad-iv",
|
||||
Offset: 0,
|
||||
Size: 8,
|
||||
SseType: filer_pb.SSEType_SSE_KMS,
|
||||
SseMetadata: makeMetadata(tc.iv),
|
||||
},
|
||||
}
|
||||
|
||||
_, err := buildMultipartSSEKMSReader(chunks, fetch)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid SSE-KMS IV, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.expectErr) {
|
||||
t.Errorf("expected %q in error, got: %v", tc.expectErr, err)
|
||||
}
|
||||
// The whole point of upfront validation: no HTTP fetch must fire
|
||||
// for a chunk that fails the metadata gate.
|
||||
if fetchCalled {
|
||||
t.Error("fetchChunk was called for a chunk with invalid IV; metadata validation must run before any fetch")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildMultipartSSEKMSReader_RejectsMissingMetadataBeforeAnyFetch verifies
|
||||
// that a chunk tagged SSE-KMS but with no SseMetadata bytes is rejected during
|
||||
// preparation, also without firing a fetch. Mirrors the SSE-S3 contract pinned
|
||||
// by TestBuildMultipartSSES3Reader_RejectsBadChunkBeforeAnyFetch.
|
||||
func TestBuildMultipartSSEKMSReader_RejectsMissingMetadataBeforeAnyFetch(t *testing.T) {
|
||||
fetched := map[string]int{}
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
fetched[c.GetFileIdString()]++
|
||||
return io.NopCloser(bytes.NewReader([]byte("ignored"))), nil
|
||||
}
|
||||
|
||||
// First chunk has valid SSE-KMS metadata; second chunk is tagged SSE-KMS
|
||||
// but has no metadata blob. The eager pre-#9228 implementation would have
|
||||
// opened chunk 0's HTTP body before discovering chunk 1's problem; the
|
||||
// lazy implementation must reject up front and leave both alone.
|
||||
validKey := &SSEKMSKey{
|
||||
KeyID: "test-kms-key",
|
||||
EncryptedDataKey: bytes.Repeat([]byte{0x42}, 32),
|
||||
IV: make([]byte, s3_constants.AESBlockSize),
|
||||
}
|
||||
if _, err := rand.Read(validKey.IV); err != nil {
|
||||
t.Fatalf("rand.Read: %v", err)
|
||||
}
|
||||
validMeta, err := SerializeSSEKMSMetadata(validKey)
|
||||
if err != nil {
|
||||
t.Fatalf("SerializeSSEKMSMetadata: %v", err)
|
||||
}
|
||||
|
||||
chunks := []*filer_pb.FileChunk{
|
||||
{
|
||||
FileId: "1,good",
|
||||
Offset: 0,
|
||||
Size: 16,
|
||||
SseType: filer_pb.SSEType_SSE_KMS,
|
||||
SseMetadata: validMeta,
|
||||
},
|
||||
{
|
||||
FileId: "2,no-metadata",
|
||||
Offset: 16,
|
||||
Size: 16,
|
||||
SseType: filer_pb.SSEType_SSE_KMS,
|
||||
SseMetadata: nil, // triggers "missing per-chunk metadata"
|
||||
},
|
||||
}
|
||||
|
||||
_, err = buildMultipartSSEKMSReader(chunks, fetch)
|
||||
if err == nil {
|
||||
t.Fatal("expected error from missing chunk metadata, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "missing per-chunk metadata") {
|
||||
t.Errorf("expected 'missing per-chunk metadata' in error, got: %v", err)
|
||||
}
|
||||
if len(fetched) != 0 {
|
||||
t.Errorf("expected no chunks fetched on validation failure, got %v", fetched)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildMultipartSSEKMSReader_RejectsUnparseableMetadataBeforeAnyFetch
|
||||
// covers the prep-loop branch where SseMetadata is non-empty but JSON-malformed
|
||||
// so DeserializeSSEKMSMetadata itself returns an error. Same contract: no
|
||||
// fetch fires.
|
||||
func TestBuildMultipartSSEKMSReader_RejectsUnparseableMetadataBeforeAnyFetch(t *testing.T) {
|
||||
fetchCalled := false
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
fetchCalled = true
|
||||
return io.NopCloser(bytes.NewReader([]byte("ignored"))), nil
|
||||
}
|
||||
|
||||
chunks := []*filer_pb.FileChunk{
|
||||
{
|
||||
FileId: "1,garbage",
|
||||
Offset: 0,
|
||||
Size: 8,
|
||||
SseType: filer_pb.SSEType_SSE_KMS,
|
||||
SseMetadata: []byte("{not-json"),
|
||||
},
|
||||
}
|
||||
|
||||
_, err := buildMultipartSSEKMSReader(chunks, fetch)
|
||||
if err == nil {
|
||||
t.Fatal("expected error from unparseable SSE-KMS metadata, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "deserialize SSE-KMS metadata") {
|
||||
t.Errorf("expected 'deserialize SSE-KMS metadata' in error, got: %v", err)
|
||||
}
|
||||
if fetchCalled {
|
||||
t.Error("fetchChunk was called for a chunk with garbage metadata; deserialize must fail before any fetch")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildMultipartSSEKMSReader_SortsByOffset verifies that the prep loop
|
||||
// reorders chunks by Offset before constructing the lazy reader, matching
|
||||
// the documented contract and the SSE-S3 helper.
|
||||
//
|
||||
// Driving the reader's Read() to observe fetch order does not work as a full
|
||||
// ordering check: CreateSSEKMSDecryptedReader requires a live KMS provider to
|
||||
// unwrap the encrypted DEK, which is unavailable in this unit test, so the
|
||||
// wrap closure fails on the first chunk and the lazy reader marks itself
|
||||
// finished -- only one fetch is ever observed. Instead, since the lazy
|
||||
// reader and its prepared chunks live in the same package, we type-assert
|
||||
// the returned reader to *lazyMultipartChunkReader and inspect the prepared
|
||||
// chunks slice directly. This is a stronger check (the entire ordering, not
|
||||
// just the first element) and does not depend on KMS availability.
|
||||
func TestBuildMultipartSSEKMSReader_SortsByOffset(t *testing.T) {
|
||||
makeChunk := func(fid string, offset int64) *filer_pb.FileChunk {
|
||||
key := &SSEKMSKey{
|
||||
KeyID: "test-kms-key",
|
||||
EncryptedDataKey: bytes.Repeat([]byte{0x42}, 32),
|
||||
IV: bytes.Repeat([]byte{0x10}, s3_constants.AESBlockSize),
|
||||
}
|
||||
meta, err := SerializeSSEKMSMetadata(key)
|
||||
if err != nil {
|
||||
t.Fatalf("SerializeSSEKMSMetadata: %v", err)
|
||||
}
|
||||
return &filer_pb.FileChunk{
|
||||
FileId: fid,
|
||||
Offset: offset,
|
||||
Size: 1,
|
||||
SseType: filer_pb.SSEType_SSE_KMS,
|
||||
SseMetadata: meta,
|
||||
}
|
||||
}
|
||||
chunks := []*filer_pb.FileChunk{
|
||||
makeChunk("c2", 200),
|
||||
makeChunk("c0", 0),
|
||||
makeChunk("c1", 100),
|
||||
}
|
||||
|
||||
fetchCalled := false
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
fetchCalled = true
|
||||
return nil, fmt.Errorf("fetch must not be called: ordering is checked via prepared chunks")
|
||||
}
|
||||
|
||||
reader, err := buildMultipartSSEKMSReader(chunks, fetch)
|
||||
if err != nil {
|
||||
t.Fatalf("buildMultipartSSEKMSReader: %v", err)
|
||||
}
|
||||
if fetchCalled {
|
||||
t.Fatal("fetch must not be invoked during prep; ordering is verified statically")
|
||||
}
|
||||
|
||||
lazy, ok := reader.(*lazyMultipartChunkReader)
|
||||
if !ok {
|
||||
t.Fatalf("expected *lazyMultipartChunkReader, got %T", reader)
|
||||
}
|
||||
if len(lazy.chunks) != 3 {
|
||||
t.Fatalf("expected 3 prepared chunks, got %d", len(lazy.chunks))
|
||||
}
|
||||
gotOrder := []string{
|
||||
lazy.chunks[0].chunk.GetFileIdString(),
|
||||
lazy.chunks[1].chunk.GetFileIdString(),
|
||||
lazy.chunks[2].chunk.GetFileIdString(),
|
||||
}
|
||||
wantOrder := []string{"c0", "c1", "c2"}
|
||||
for i, want := range wantOrder {
|
||||
if gotOrder[i] != want {
|
||||
t.Errorf("prepared chunks not in offset order: got %v, want %v", gotOrder, wantOrder)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
+266
-266
@@ -1648,44 +1648,15 @@ func (s3a *S3ApiServer) decryptSSEKMSChunkView(ctx context.Context, fileChunk *f
|
||||
return nil, fmt.Errorf("failed to fetch full chunk: %w", err)
|
||||
}
|
||||
|
||||
// IMPORTANT: Calculate adjusted IV using ChunkOffset
|
||||
// SSE-KMS uses base IV + offset calculation (unlike SSE-C which uses random IVs)
|
||||
// This reconstructs the same IV that was used during encryption
|
||||
var adjustedIV []byte
|
||||
var ivSkip int
|
||||
if sseKMSKey.ChunkOffset > 0 {
|
||||
adjustedIV, ivSkip = calculateIVWithOffset(sseKMSKey.IV, sseKMSKey.ChunkOffset)
|
||||
} else {
|
||||
adjustedIV = sseKMSKey.IV
|
||||
ivSkip = 0
|
||||
}
|
||||
|
||||
adjustedKey := &SSEKMSKey{
|
||||
KeyID: sseKMSKey.KeyID,
|
||||
EncryptedDataKey: sseKMSKey.EncryptedDataKey,
|
||||
EncryptionContext: sseKMSKey.EncryptionContext,
|
||||
BucketKeyEnabled: sseKMSKey.BucketKeyEnabled,
|
||||
IV: adjustedIV,
|
||||
ChunkOffset: sseKMSKey.ChunkOffset,
|
||||
}
|
||||
|
||||
decryptedReader, decryptErr := CreateSSEKMSDecryptedReader(fullChunkReader, adjustedKey)
|
||||
// CreateSSEKMSDecryptedReader applies ChunkOffset to the stored base IV.
|
||||
// Passing a pre-adjusted IV here would apply the offset twice and corrupt
|
||||
// range reads that cross multipart chunk boundaries.
|
||||
decryptedReader, decryptErr := CreateSSEKMSDecryptedReader(fullChunkReader, sseKMSKey)
|
||||
if decryptErr != nil {
|
||||
fullChunkReader.Close()
|
||||
return nil, fmt.Errorf("failed to create KMS decrypted reader: %w", decryptErr)
|
||||
}
|
||||
|
||||
// CRITICAL: Skip intra-block bytes from CTR decryption (non-block-aligned offset handling)
|
||||
if ivSkip > 0 {
|
||||
_, err = io.CopyN(io.Discard, decryptedReader, int64(ivSkip))
|
||||
if err != nil {
|
||||
if closer, ok := decryptedReader.(io.Closer); ok {
|
||||
closer.Close()
|
||||
}
|
||||
return nil, fmt.Errorf("failed to skip intra-block bytes (%d): %w", ivSkip, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Skip to position and limit to ViewSize
|
||||
if chunkView.OffsetInChunk > 0 {
|
||||
_, err = io.CopyN(io.Discard, decryptedReader, chunkView.OffsetInChunk)
|
||||
@@ -2592,10 +2563,22 @@ func (s3a *S3ApiServer) detectPrimarySSEType(entry *filer_pb.Entry) string {
|
||||
// createMultipartSSECDecryptedReaderDirect creates a reader that decrypts each chunk independently for multipart SSE-C objects (direct volume path)
|
||||
// Note: encryptedStream parameter is unused (always nil) as this function fetches chunks directly to avoid double I/O.
|
||||
// It's kept in the signature for API consistency with non-Direct versions.
|
||||
//
|
||||
// Per-chunk metadata is validated upfront (so a malformed chunk fails fast
|
||||
// without opening any HTTP connections); chunk fetches happen LAZILY through
|
||||
// lazyMultipartChunkReader, so at most one volume-server connection is open
|
||||
// at a time. See buildMultipartSSES3Reader for the rationale (issue #8908).
|
||||
//
|
||||
// SSE-C multipart behavior (differs from SSE-KMS/SSE-S3):
|
||||
// - Upload: CreateSSECEncryptedReader generates a RANDOM IV per part (no base IV + offset).
|
||||
// - Metadata: PartOffset tracks position within the encrypted stream.
|
||||
// - Decryption: use stored IV and advance the CTR stream by PartOffset.
|
||||
//
|
||||
// SSE-KMS/SSE-S3 instead use base IV + calculateIVWithOffset(partOffset) at
|
||||
// encryption time. CopyObject currently applies calculateIVWithOffset to SSE-C
|
||||
// as well, which may be incorrect (TODO: investigate consistency).
|
||||
func (s3a *S3ApiServer) createMultipartSSECDecryptedReaderDirect(ctx context.Context, encryptedStream io.ReadCloser, customerKey *SSECustomerKey, entry *filer_pb.Entry) (io.Reader, error) {
|
||||
// Close the original encrypted stream since chunks are fetched individually.
|
||||
// Defer so the stream is closed on every return path (including error
|
||||
// returns from inside the per-chunk loop), matching the SSE-S3 helper.
|
||||
if encryptedStream != nil {
|
||||
defer encryptedStream.Close()
|
||||
}
|
||||
@@ -2609,192 +2592,135 @@ func (s3a *S3ApiServer) createMultipartSSECDecryptedReaderDirect(ctx context.Con
|
||||
return chunks[i].GetOffset() < chunks[j].GetOffset()
|
||||
})
|
||||
|
||||
// Create readers for each chunk, decrypting them independently
|
||||
readers := make([]io.Reader, 0, len(chunks))
|
||||
|
||||
// Close any readers already appended to `readers` on error paths, to avoid
|
||||
// leaking volume-server HTTP connections.
|
||||
closeAppendedReaders := func() {
|
||||
for _, r := range readers {
|
||||
if closer, ok := r.(io.Closer); ok {
|
||||
closer.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
preparedChunks := make([]preparedMultipartChunk, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
// Get this chunk's encrypted data
|
||||
chunkReader, err := s3a.createEncryptedChunkReader(ctx, chunk)
|
||||
if chunk.GetSseType() != filer_pb.SSEType_SSE_C {
|
||||
preparedChunks = append(preparedChunks, preparedMultipartChunk{chunk: chunk})
|
||||
continue
|
||||
}
|
||||
if len(chunk.GetSseMetadata()) == 0 {
|
||||
return nil, fmt.Errorf("SSE-C chunk %s missing per-chunk metadata", chunk.GetFileIdString())
|
||||
}
|
||||
ssecMetadata, err := DeserializeSSECMetadata(chunk.GetSseMetadata())
|
||||
if err != nil {
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to create chunk reader: %v", err)
|
||||
return nil, fmt.Errorf("failed to deserialize SSE-C metadata for chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
// Handle based on chunk's encryption type
|
||||
if chunk.GetSseType() == filer_pb.SSEType_SSE_C {
|
||||
// Check if this chunk has per-chunk SSE-C metadata
|
||||
if len(chunk.GetSseMetadata()) == 0 {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("SSE-C chunk %s missing per-chunk metadata", chunk.GetFileIdString())
|
||||
}
|
||||
|
||||
// Deserialize the SSE-C metadata
|
||||
ssecMetadata, err := DeserializeSSECMetadata(chunk.GetSseMetadata())
|
||||
if err != nil {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to deserialize SSE-C metadata for chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
// Decode the IV from the metadata
|
||||
chunkIV, err := base64.StdEncoding.DecodeString(ssecMetadata.IV)
|
||||
if err != nil {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to decode IV for SSE-C chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
// Guard cipher.NewCTR against a missing/short IV (base64 decode of
|
||||
// an empty or malformed field would otherwise reach it and panic).
|
||||
if len(chunkIV) != s3_constants.AESBlockSize {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("SSE-C chunk %s has invalid IV length %d (expected %d)",
|
||||
chunk.GetFileIdString(), len(chunkIV), s3_constants.AESBlockSize)
|
||||
}
|
||||
|
||||
glog.V(4).Infof("Decrypting SSE-C chunk %s with IV=%x, PartOffset=%d",
|
||||
chunk.GetFileIdString(), chunkIV[:8], ssecMetadata.PartOffset)
|
||||
|
||||
// Note: SSE-C multipart behavior (differs from SSE-KMS/SSE-S3):
|
||||
// - Upload: CreateSSECEncryptedReader generates RANDOM IV per part (no base IV + offset)
|
||||
// - Metadata: PartOffset tracks position within the encrypted stream
|
||||
// - Decryption: Use stored IV and advance CTR stream by PartOffset
|
||||
//
|
||||
// This differs from:
|
||||
// - SSE-KMS/SSE-S3: Use base IV + calculateIVWithOffset(partOffset) during encryption
|
||||
// - CopyObject: Applies calculateIVWithOffset to SSE-C (which may be incorrect)
|
||||
//
|
||||
// TODO: Investigate CopyObject SSE-C PartOffset handling for consistency
|
||||
partOffset := ssecMetadata.PartOffset
|
||||
if partOffset < 0 {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("invalid SSE-C part offset %d for chunk %s", partOffset, chunk.GetFileIdString())
|
||||
}
|
||||
decryptedChunkReader, decErr := CreateSSECDecryptedReaderWithOffset(chunkReader, customerKey, chunkIV, uint64(partOffset))
|
||||
if decErr != nil {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to decrypt chunk: %v", decErr)
|
||||
}
|
||||
|
||||
// Use the streaming decrypted reader directly
|
||||
readers = append(readers, struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{
|
||||
Reader: decryptedChunkReader,
|
||||
Closer: chunkReader,
|
||||
})
|
||||
glog.V(4).Infof("Added streaming decrypted reader for SSE-C chunk %s", chunk.GetFileIdString())
|
||||
} else {
|
||||
// Non-SSE-C chunk, use as-is
|
||||
readers = append(readers, chunkReader)
|
||||
glog.V(4).Infof("Added non-encrypted reader for chunk %s", chunk.GetFileIdString())
|
||||
chunkIV, err := base64.StdEncoding.DecodeString(ssecMetadata.IV)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode IV for SSE-C chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
// Guard cipher.NewCTR against a missing/short IV (base64 decode of
|
||||
// an empty or malformed field would otherwise reach it and panic).
|
||||
// Uses the shared ValidateIV helper so all three SSE prep paths
|
||||
// (SSE-S3, SSE-KMS, SSE-C) enforce IV length identically.
|
||||
if err := ValidateIV(chunkIV, fmt.Sprintf("SSE-C chunk %s IV", chunk.GetFileIdString())); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ssecMetadata.PartOffset < 0 {
|
||||
return nil, fmt.Errorf("invalid SSE-C part offset %d for chunk %s", ssecMetadata.PartOffset, chunk.GetFileIdString())
|
||||
}
|
||||
// Capture per-chunk values into the wrap closure.
|
||||
fileId := chunk.GetFileIdString()
|
||||
ivCopy := chunkIV
|
||||
partOffset := uint64(ssecMetadata.PartOffset)
|
||||
preparedChunks = append(preparedChunks, preparedMultipartChunk{
|
||||
chunk: chunk,
|
||||
wrap: func(raw io.ReadCloser) (io.Reader, error) {
|
||||
glog.V(4).Infof("Decrypting SSE-C chunk %s with IV=%x, PartOffset=%d",
|
||||
fileId, ivCopy[:8], partOffset)
|
||||
dec, decErr := CreateSSECDecryptedReaderWithOffset(raw, customerKey, ivCopy, partOffset)
|
||||
if decErr != nil {
|
||||
return nil, fmt.Errorf("failed to decrypt chunk: %v", decErr)
|
||||
}
|
||||
return dec, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return NewMultipartSSEReader(readers), nil
|
||||
return &lazyMultipartChunkReader{
|
||||
chunks: preparedChunks,
|
||||
fetch: func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
return s3a.createEncryptedChunkReader(ctx, c)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// createMultipartSSEKMSDecryptedReaderDirect creates a reader that decrypts each chunk independently for multipart SSE-KMS objects (direct volume path)
|
||||
// Note: encryptedStream parameter is unused (always nil) as this function fetches chunks directly to avoid double I/O.
|
||||
// It's kept in the signature for API consistency with non-Direct versions.
|
||||
//
|
||||
// Per-chunk metadata is validated upfront (so a malformed chunk fails fast
|
||||
// without opening any HTTP connections); chunk fetches happen LAZILY through
|
||||
// lazyMultipartChunkReader, so at most one volume-server connection is open
|
||||
// at a time. See buildMultipartSSES3Reader for the rationale (issue #8908).
|
||||
func (s3a *S3ApiServer) createMultipartSSEKMSDecryptedReaderDirect(ctx context.Context, encryptedStream io.ReadCloser, entry *filer_pb.Entry) (io.Reader, error) {
|
||||
// Close the original encrypted stream since chunks are fetched individually.
|
||||
// Defer so the stream is closed on every return path (including error
|
||||
// returns from inside the per-chunk loop), matching the SSE-S3 helper.
|
||||
if encryptedStream != nil {
|
||||
defer encryptedStream.Close()
|
||||
}
|
||||
|
||||
// Sort a copy of the slice so entry.Chunks is not reordered (other code
|
||||
// paths, e.g. ETag computation, can rely on the original chunk order).
|
||||
// IV length is validated inside CreateSSEKMSDecryptedReader via ValidateIV.
|
||||
originalChunks := entry.GetChunks()
|
||||
chunks := make([]*filer_pb.FileChunk, len(originalChunks))
|
||||
copy(chunks, originalChunks)
|
||||
sort.Slice(chunks, func(i, j int) bool {
|
||||
return chunks[i].GetOffset() < chunks[j].GetOffset()
|
||||
return buildMultipartSSEKMSReader(entry.GetChunks(), func(chunk *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
return s3a.createEncryptedChunkReader(ctx, chunk)
|
||||
})
|
||||
}
|
||||
|
||||
// buildMultipartSSEKMSReader composes a decrypted reader from a set of
|
||||
// multipart SSE-KMS chunks. Mirrors buildMultipartSSES3Reader: chunks are
|
||||
// validated upfront (per-chunk metadata parses, IV has the right length) and
|
||||
// fetched + decrypted lazily through lazyMultipartChunkReader, so at most one
|
||||
// volume-server HTTP body is live at a time. Exposed as a free function so
|
||||
// tests can inject a mock chunk fetcher and pin the "no fetch on bad
|
||||
// metadata" contract without spinning up an S3ApiServer.
|
||||
func buildMultipartSSEKMSReader(chunks []*filer_pb.FileChunk, fetchChunk func(*filer_pb.FileChunk) (io.ReadCloser, error)) (io.Reader, error) {
|
||||
sortedChunks := make([]*filer_pb.FileChunk, len(chunks))
|
||||
copy(sortedChunks, chunks)
|
||||
sort.Slice(sortedChunks, func(i, j int) bool {
|
||||
return sortedChunks[i].GetOffset() < sortedChunks[j].GetOffset()
|
||||
})
|
||||
|
||||
// Create readers for each chunk, decrypting them independently
|
||||
readers := make([]io.Reader, 0, len(chunks))
|
||||
|
||||
// Close any readers already appended to `readers` on error paths, to avoid
|
||||
// leaking volume-server HTTP connections.
|
||||
closeAppendedReaders := func() {
|
||||
for _, r := range readers {
|
||||
if closer, ok := r.(io.Closer); ok {
|
||||
closer.Close()
|
||||
}
|
||||
preparedChunks := make([]preparedMultipartChunk, 0, len(sortedChunks))
|
||||
for _, chunk := range sortedChunks {
|
||||
if chunk.GetSseType() != filer_pb.SSEType_SSE_KMS {
|
||||
preparedChunks = append(preparedChunks, preparedMultipartChunk{chunk: chunk})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
for _, chunk := range chunks {
|
||||
// Get this chunk's encrypted data
|
||||
chunkReader, err := s3a.createEncryptedChunkReader(ctx, chunk)
|
||||
if len(chunk.GetSseMetadata()) == 0 {
|
||||
return nil, fmt.Errorf("SSE-KMS chunk %s missing per-chunk metadata", chunk.GetFileIdString())
|
||||
}
|
||||
kmsKey, err := DeserializeSSEKMSMetadata(chunk.GetSseMetadata())
|
||||
if err != nil {
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to create chunk reader: %v", err)
|
||||
return nil, fmt.Errorf("failed to deserialize SSE-KMS metadata for chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
// Handle based on chunk's encryption type
|
||||
if chunk.GetSseType() == filer_pb.SSEType_SSE_KMS {
|
||||
// Check if this chunk has per-chunk SSE-KMS metadata
|
||||
if len(chunk.GetSseMetadata()) == 0 {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("SSE-KMS chunk %s missing per-chunk metadata", chunk.GetFileIdString())
|
||||
}
|
||||
|
||||
// Use the per-chunk SSE-KMS metadata
|
||||
kmsKey, err := DeserializeSSEKMSMetadata(chunk.GetSseMetadata())
|
||||
if err != nil {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to deserialize SSE-KMS metadata for chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
glog.V(4).Infof("Decrypting SSE-KMS chunk %s with KeyID=%s",
|
||||
chunk.GetFileIdString(), kmsKey.KeyID)
|
||||
|
||||
// Create decrypted reader for this chunk
|
||||
decryptedChunkReader, decErr := CreateSSEKMSDecryptedReader(chunkReader, kmsKey)
|
||||
if decErr != nil {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to decrypt chunk: %v", decErr)
|
||||
}
|
||||
|
||||
// Use the streaming decrypted reader directly
|
||||
readers = append(readers, struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{
|
||||
Reader: decryptedChunkReader,
|
||||
Closer: chunkReader,
|
||||
})
|
||||
glog.V(4).Infof("Added streaming decrypted reader for SSE-KMS chunk %s", chunk.GetFileIdString())
|
||||
} else {
|
||||
// Non-SSE-KMS chunk, use as-is
|
||||
readers = append(readers, chunkReader)
|
||||
glog.V(4).Infof("Added non-encrypted reader for chunk %s", chunk.GetFileIdString())
|
||||
// Validate IV length up front, mirroring the SSE-S3 / SSE-C
|
||||
// preparation paths. CreateSSEKMSDecryptedReader does call
|
||||
// ValidateIV internally, but only when the wrap closure runs --
|
||||
// after the chunk's volume-server fetch has already started. We
|
||||
// want the "reject malformed chunks before any fetch" contract to
|
||||
// hold for SSE-KMS too, so a missing or short IV must fail here
|
||||
// in the prep loop rather than turn into a mid-stream error.
|
||||
if err := ValidateIV(kmsKey.IV, fmt.Sprintf("SSE-KMS chunk %s IV", chunk.GetFileIdString())); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Capture kmsKey and chunk into the wrap closure so each prepared
|
||||
// entry decrypts with its own per-chunk SSE-KMS key.
|
||||
fileId := chunk.GetFileIdString()
|
||||
preparedChunks = append(preparedChunks, preparedMultipartChunk{
|
||||
chunk: chunk,
|
||||
wrap: func(raw io.ReadCloser) (io.Reader, error) {
|
||||
glog.V(4).Infof("Decrypting SSE-KMS chunk %s with KeyID=%s", fileId, kmsKey.KeyID)
|
||||
dec, decErr := CreateSSEKMSDecryptedReader(raw, kmsKey)
|
||||
if decErr != nil {
|
||||
return nil, fmt.Errorf("failed to decrypt chunk: %v", decErr)
|
||||
}
|
||||
return dec, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return NewMultipartSSEReader(readers), nil
|
||||
return &lazyMultipartChunkReader{
|
||||
chunks: preparedChunks,
|
||||
fetch: fetchChunk,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// createMultipartSSES3DecryptedReaderDirect creates a reader that decrypts each chunk independently for multipart SSE-S3 objects (direct volume path)
|
||||
@@ -2815,6 +2741,15 @@ func (s3a *S3ApiServer) createMultipartSSES3DecryptedReaderDirect(ctx context.Co
|
||||
// SSE-S3 chunks. Chunks are fetched via fetchChunk and decrypted using their
|
||||
// per-chunk metadata (each multipart part has its own DEK and IV). Exposed as a
|
||||
// standalone helper so tests can inject a mock chunk fetcher.
|
||||
//
|
||||
// All per-chunk metadata is validated upfront so a malformed chunk fails fast
|
||||
// without opening any HTTP connections to volume servers. The actual chunk
|
||||
// fetch and decryption happens LAZILY as the returned reader is read: at most
|
||||
// one chunk's HTTP connection is open at a time. Eagerly opening every chunk's
|
||||
// HTTP response (the previous behavior) caused later chunks' connections to
|
||||
// sit idle while earlier chunks were still being consumed, which under load
|
||||
// could trip volume-server idle/keepalive limits and yield truncated reads
|
||||
// (issue #8908).
|
||||
func buildMultipartSSES3Reader(chunks []*filer_pb.FileChunk, keyManager *SSES3KeyManager, fetchChunk func(*filer_pb.FileChunk) (io.ReadCloser, error)) (io.Reader, error) {
|
||||
// Sort a copy of the slice so callers do not observe their input chunks
|
||||
// reordered (the backing array is shared with entry.Chunks, which other
|
||||
@@ -2825,82 +2760,147 @@ func buildMultipartSSES3Reader(chunks []*filer_pb.FileChunk, keyManager *SSES3Ke
|
||||
return sortedChunks[i].GetOffset() < sortedChunks[j].GetOffset()
|
||||
})
|
||||
|
||||
// Create readers for each chunk, decrypting them independently
|
||||
readers := make([]io.Reader, 0, len(sortedChunks))
|
||||
|
||||
// Close any readers already appended to `readers` on error paths, to avoid
|
||||
// leaking volume-server HTTP connections.
|
||||
closeAppendedReaders := func() {
|
||||
for _, r := range readers {
|
||||
if closer, ok := r.(io.Closer); ok {
|
||||
closer.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate every chunk's SSE-S3 metadata before returning a reader. This
|
||||
// keeps the eager-validation contract that callers and tests rely on
|
||||
// (malformed metadata fails immediately), without holding open any
|
||||
// volume-server HTTP connections.
|
||||
preparedChunks := make([]preparedMultipartChunk, 0, len(sortedChunks))
|
||||
for _, chunk := range sortedChunks {
|
||||
// Get this chunk's encrypted data
|
||||
chunkReader, err := fetchChunk(chunk)
|
||||
if chunk.GetSseType() != filer_pb.SSEType_SSE_S3 {
|
||||
preparedChunks = append(preparedChunks, preparedMultipartChunk{chunk: chunk})
|
||||
continue
|
||||
}
|
||||
if len(chunk.GetSseMetadata()) == 0 {
|
||||
return nil, fmt.Errorf("SSE-S3 chunk %s missing per-chunk metadata", chunk.GetFileIdString())
|
||||
}
|
||||
meta, err := DeserializeSSES3Metadata(chunk.GetSseMetadata(), keyManager)
|
||||
if err != nil {
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to create chunk reader: %v", err)
|
||||
return nil, fmt.Errorf("failed to deserialize SSE-S3 metadata for chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
// Handle based on chunk's encryption type
|
||||
if chunk.GetSseType() == filer_pb.SSEType_SSE_S3 {
|
||||
// Check if this chunk has per-chunk SSE-S3 metadata
|
||||
if len(chunk.GetSseMetadata()) == 0 {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("SSE-S3 chunk %s missing per-chunk metadata", chunk.GetFileIdString())
|
||||
}
|
||||
|
||||
// Deserialize the per-chunk SSE-S3 metadata to get the IV
|
||||
chunkSSES3Metadata, err := DeserializeSSES3Metadata(chunk.GetSseMetadata(), keyManager)
|
||||
if err != nil {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to deserialize SSE-S3 metadata for chunk %s: %v", chunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
// Use the IV from the chunk metadata. DeserializeSSES3Metadata does
|
||||
// not require an IV, so validate the length here before it reaches
|
||||
// cipher.NewCTR, which would otherwise panic on a nil or short IV.
|
||||
iv := chunkSSES3Metadata.IV
|
||||
if len(iv) != s3_constants.AESBlockSize {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("SSE-S3 chunk %s has invalid IV length %d (expected %d)",
|
||||
chunk.GetFileIdString(), len(iv), s3_constants.AESBlockSize)
|
||||
}
|
||||
glog.V(4).Infof("Decrypting SSE-S3 chunk %s with KeyID=%s, IV length=%d",
|
||||
chunk.GetFileIdString(), chunkSSES3Metadata.KeyID, len(iv))
|
||||
|
||||
// Create decrypted reader for this chunk
|
||||
decryptedChunkReader, decErr := CreateSSES3DecryptedReader(chunkReader, chunkSSES3Metadata, iv)
|
||||
if decErr != nil {
|
||||
chunkReader.Close()
|
||||
closeAppendedReaders()
|
||||
return nil, fmt.Errorf("failed to decrypt SSE-S3 chunk: %v", decErr)
|
||||
}
|
||||
|
||||
// Use the streaming decrypted reader directly
|
||||
readers = append(readers, struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{
|
||||
Reader: decryptedChunkReader,
|
||||
Closer: chunkReader,
|
||||
})
|
||||
glog.V(4).Infof("Added streaming decrypted reader for SSE-S3 chunk %s", chunk.GetFileIdString())
|
||||
} else {
|
||||
// Non-SSE-S3 chunk, use as-is
|
||||
readers = append(readers, chunkReader)
|
||||
glog.V(4).Infof("Added non-encrypted reader for chunk %s", chunk.GetFileIdString())
|
||||
// DeserializeSSES3Metadata does not require an IV, so validate the
|
||||
// length here before it reaches cipher.NewCTR, which would otherwise
|
||||
// panic on a nil or short IV. Uses the shared ValidateIV helper so
|
||||
// all three SSE prep paths (SSE-S3, SSE-KMS, SSE-C) enforce IV
|
||||
// length identically.
|
||||
if err := ValidateIV(meta.IV, fmt.Sprintf("SSE-S3 chunk %s IV", chunk.GetFileIdString())); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Capture meta and chunk by-value into the wrap closure so each
|
||||
// prepared entry decrypts with its own per-chunk key + IV.
|
||||
fileId := chunk.GetFileIdString()
|
||||
preparedChunks = append(preparedChunks, preparedMultipartChunk{
|
||||
chunk: chunk,
|
||||
wrap: func(raw io.ReadCloser) (io.Reader, error) {
|
||||
glog.V(4).Infof("Decrypting SSE-S3 chunk %s with KeyID=%s, IV length=%d",
|
||||
fileId, meta.KeyID, len(meta.IV))
|
||||
dec, err := CreateSSES3DecryptedReader(raw, meta, meta.IV)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decrypt SSE-S3 chunk: %v", err)
|
||||
}
|
||||
return dec, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return NewMultipartSSEReader(readers), nil
|
||||
return &lazyMultipartChunkReader{
|
||||
chunks: preparedChunks,
|
||||
fetch: fetchChunk,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// preparedMultipartChunk pairs a chunk with the per-SSE wrapping logic the
|
||||
// lazy reader applies to its raw HTTP body. wrap is nil for chunks that
|
||||
// stream as-is (no SSE on the chunk, even though the object is multipart-SSE);
|
||||
// otherwise wrap is the SSE-specific decryption setup, which receives the
|
||||
// already-opened raw chunk body and returns the plaintext reader.
|
||||
type preparedMultipartChunk struct {
|
||||
chunk *filer_pb.FileChunk
|
||||
wrap func(raw io.ReadCloser) (io.Reader, error)
|
||||
}
|
||||
|
||||
// lazyMultipartChunkReader streams a sequence of multipart chunks one at a
|
||||
// time. It opens each chunk's underlying HTTP fetch (and applies the
|
||||
// SSE-specific decryption wrapper) only when the previous chunk has been
|
||||
// fully consumed, so volume-server connections do not pile up for large
|
||||
// objects. This is the same shape used by all three SSE multipart read
|
||||
// paths (SSE-S3, SSE-KMS, SSE-C); only the per-chunk wrap closure differs.
|
||||
type lazyMultipartChunkReader struct {
|
||||
chunks []preparedMultipartChunk
|
||||
fetch func(*filer_pb.FileChunk) (io.ReadCloser, error)
|
||||
idx int
|
||||
current io.Reader // current chunk's plaintext reader (or raw reader for non-SSE chunks)
|
||||
closer io.Closer // current chunk's underlying HTTP body, to close on advance/Close
|
||||
finished bool
|
||||
}
|
||||
|
||||
func (l *lazyMultipartChunkReader) Read(p []byte) (int, error) {
|
||||
for {
|
||||
if l.finished {
|
||||
return 0, io.EOF
|
||||
}
|
||||
if l.current == nil {
|
||||
if l.idx >= len(l.chunks) {
|
||||
l.finished = true
|
||||
return 0, io.EOF
|
||||
}
|
||||
pc := l.chunks[l.idx]
|
||||
l.idx++
|
||||
chunkReader, err := l.fetch(pc.chunk)
|
||||
if err != nil {
|
||||
l.finished = true
|
||||
return 0, fmt.Errorf("failed to create chunk reader: %v", err)
|
||||
}
|
||||
if pc.wrap == nil {
|
||||
// Non-SSE chunk in an otherwise SSE-multipart object: stream
|
||||
// raw bytes through.
|
||||
l.current = chunkReader
|
||||
l.closer = chunkReader
|
||||
glog.V(4).Infof("Streaming non-encrypted chunk %s", pc.chunk.GetFileIdString())
|
||||
} else {
|
||||
wrapped, wrapErr := pc.wrap(chunkReader)
|
||||
if wrapErr != nil {
|
||||
chunkReader.Close()
|
||||
l.finished = true
|
||||
return 0, wrapErr
|
||||
}
|
||||
l.current = wrapped
|
||||
l.closer = chunkReader
|
||||
}
|
||||
}
|
||||
n, err := l.current.Read(p)
|
||||
if err == io.EOF {
|
||||
closeErr := l.closer.Close()
|
||||
l.current = nil
|
||||
l.closer = nil
|
||||
if n > 0 {
|
||||
return n, nil
|
||||
}
|
||||
if closeErr != nil {
|
||||
glog.V(2).Infof("Error closing chunk reader: %v", closeErr)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
// Non-EOF read error: the underlying chunk body is in an
|
||||
// indeterminate state. Mark ourselves finished so a retried
|
||||
// Read does not try to drain the same broken stream; let
|
||||
// Close() release the chunk body. This matches the failure
|
||||
// semantics of the fetch and wrap error paths above.
|
||||
l.finished = true
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
|
||||
func (l *lazyMultipartChunkReader) Close() error {
|
||||
l.finished = true
|
||||
if l.closer != nil {
|
||||
err := l.closer.Close()
|
||||
l.current = nil
|
||||
l.closer = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// createEncryptedChunkReader creates a reader for a single encrypted chunk
|
||||
|
||||
@@ -161,6 +161,27 @@ func TestSSEKMSDecryptChunkView_RequiresOffsetAdjustment(t *testing.T) {
|
||||
t.Logf("✓ SSE-KMS decryption with offset adjustment successful")
|
||||
}
|
||||
|
||||
// ANTI-TEST: Decrypt after applying the offset twice (incorrect range path behavior)
|
||||
doubleAdjustedIV, doubleSkip := calculateIVWithOffset(adjustedIV, chunkOffset)
|
||||
blockDoubleWrong, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create cipher for double-adjusted decryption: %v", err)
|
||||
}
|
||||
|
||||
decryptedDoubleWrong := make([]byte, len(ciphertext))
|
||||
streamDoubleWrong := cipher.NewCTR(blockDoubleWrong, doubleAdjustedIV)
|
||||
if doubleSkip > 0 {
|
||||
dummy := make([]byte, doubleSkip)
|
||||
streamDoubleWrong.XORKeyStream(dummy, dummy)
|
||||
}
|
||||
streamDoubleWrong.XORKeyStream(decryptedDoubleWrong, ciphertext)
|
||||
|
||||
if bytes.Equal(decryptedDoubleWrong, plaintext) {
|
||||
t.Errorf("CRITICAL: Double-adjusted IV produced correct plaintext! SSE-KMS chunk offset must be applied exactly once.")
|
||||
} else {
|
||||
t.Logf("✓ Verified: double-adjusted IV produces corrupted data (range path must not pre-adjust)")
|
||||
}
|
||||
|
||||
// ANTI-TEST: Decrypt using base IV directly (incorrect for SSE-KMS)
|
||||
blockWrong, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// TestMultipartSSES3RealisticEndToEnd reproduces the production multipart SSE-S3
|
||||
// flow where ALL parts share the same DEK and baseIV (the upload-init key/IV),
|
||||
// and each part is encrypted with partOffset=0. Each part is then chunked at 8MB
|
||||
// boundaries the way UploadReaderInChunks does. After completion, the chunks
|
||||
// have global offsets but per-chunk stored IVs derived from part-local offsets.
|
||||
//
|
||||
// buildMultipartSSES3Reader is then run on the assembled chunks; the
|
||||
// concatenated decrypted output must equal the concatenation of the part
|
||||
// plaintexts. This is the round trip that fails in #8908 if anything in the
|
||||
// encrypt or decrypt path is inconsistent.
|
||||
func TestMultipartSSES3RealisticEndToEnd(t *testing.T) {
|
||||
keyManager := initSSES3KeyManagerForTest(t)
|
||||
|
||||
// One DEK and one baseIV, shared by all parts (the upload-init values).
|
||||
key, err := GenerateSSES3Key()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSSES3Key: %v", err)
|
||||
}
|
||||
baseIV := make([]byte, s3_constants.AESBlockSize)
|
||||
if _, err := rand.Read(baseIV); err != nil {
|
||||
t.Fatalf("rand.Read baseIV: %v", err)
|
||||
}
|
||||
|
||||
const chunkSize = int64(8 * 1024 * 1024)
|
||||
|
||||
// Realistic mix of part sizes: small (one chunk), exact 8MB, >8MB (two
|
||||
// chunks), much larger (multiple chunks).
|
||||
partSizes := []int{
|
||||
5 * 1024 * 1024, // 5MB (single chunk)
|
||||
8 * 1024 * 1024, // 8MB exactly (single chunk, full)
|
||||
8*1024*1024 + 123, // crosses chunk boundary (two chunks)
|
||||
17 * 1024 * 1024, // three chunks
|
||||
1234, // tiny
|
||||
}
|
||||
|
||||
parts := make([][]byte, len(partSizes))
|
||||
for i, n := range partSizes {
|
||||
parts[i] = makeRandomPlaintext(t, n)
|
||||
}
|
||||
|
||||
// Build the chunks list the way completion would produce it: encrypt each
|
||||
// part with partOffset=0, slice the ciphertext at chunkSize boundaries,
|
||||
// store per-chunk metadata IV = calculateIVWithOffset(baseIV, partLocalOff),
|
||||
// then assign GLOBAL offsets to the FileChunk.
|
||||
type chunkBlob struct {
|
||||
fid string
|
||||
ciphertext []byte
|
||||
}
|
||||
var chunks []*filer_pb.FileChunk
|
||||
chunkData := map[string][]byte{}
|
||||
var globalOffset int64
|
||||
for partIdx, partPlaintext := range parts {
|
||||
encReader, _, err := CreateSSES3EncryptedReaderWithBaseIV(bytes.NewReader(partPlaintext), key, baseIV, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSSES3EncryptedReaderWithBaseIV(part %d): %v", partIdx, err)
|
||||
}
|
||||
ciphertext, err := io.ReadAll(encReader)
|
||||
if err != nil {
|
||||
t.Fatalf("read encrypted part %d: %v", partIdx, err)
|
||||
}
|
||||
|
||||
for partLocalOff := int64(0); partLocalOff < int64(len(ciphertext)); partLocalOff += chunkSize {
|
||||
end := partLocalOff + chunkSize
|
||||
if end > int64(len(ciphertext)) {
|
||||
end = int64(len(ciphertext))
|
||||
}
|
||||
cipherSlice := ciphertext[partLocalOff:end]
|
||||
|
||||
chunkIV, _ := calculateIVWithOffset(baseIV, partLocalOff)
|
||||
chunkKey := &SSES3Key{
|
||||
Key: key.Key,
|
||||
KeyID: key.KeyID,
|
||||
Algorithm: key.Algorithm,
|
||||
IV: chunkIV,
|
||||
}
|
||||
meta, err := SerializeSSES3Metadata(chunkKey)
|
||||
if err != nil {
|
||||
t.Fatalf("SerializeSSES3Metadata(part %d off %d): %v", partIdx, partLocalOff, err)
|
||||
}
|
||||
|
||||
fid := fmt.Sprintf("%d,%d", partIdx+1, partLocalOff)
|
||||
chunks = append(chunks, &filer_pb.FileChunk{
|
||||
FileId: fid,
|
||||
Offset: globalOffset, // global offset assigned at completion
|
||||
Size: uint64(end - partLocalOff),
|
||||
SseType: filer_pb.SSEType_SSE_S3,
|
||||
SseMetadata: meta,
|
||||
})
|
||||
chunkData[fid] = cipherSlice
|
||||
globalOffset += end - partLocalOff
|
||||
}
|
||||
}
|
||||
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
data, ok := chunkData[c.GetFileIdString()]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected chunk %s", c.GetFileIdString())
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(data)), nil
|
||||
}
|
||||
|
||||
reader, err := buildMultipartSSES3Reader(chunks, keyManager, fetch)
|
||||
if err != nil {
|
||||
t.Fatalf("buildMultipartSSES3Reader: %v", err)
|
||||
}
|
||||
got, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll decrypted output: %v", err)
|
||||
}
|
||||
|
||||
want := bytes.Join(parts, nil)
|
||||
if !bytes.Equal(got, want) {
|
||||
idx := firstMismatch(got, want)
|
||||
end := idx + 32
|
||||
if end > len(got) {
|
||||
end = len(got)
|
||||
}
|
||||
if end > len(want) {
|
||||
end = len(want)
|
||||
}
|
||||
t.Fatalf("decrypted output mismatch at byte %d (total len got=%d want=%d)\n got: %x\nwant: %x",
|
||||
idx, len(got), len(want), got[idx:end], want[idx:end])
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildMultipartSSES3Reader_LazyChunkFetch pins the lazy behavior of
|
||||
// buildMultipartSSES3Reader: chunk N's HTTP fetch only happens after chunk
|
||||
// N-1 has been fully consumed. The original eager loop opened every chunk's
|
||||
// HTTP response upfront and held them open while io.MultiReader walked
|
||||
// through readers[0]; for objects with many chunks (e.g. a 200MB Docker image
|
||||
// blob), this could trip volume-server idle/keepalive limits and produce
|
||||
// truncated reads at the client (issue #8908).
|
||||
//
|
||||
// The test installs a fetch hook that tracks how many chunks have been
|
||||
// opened and when each one is closed, and verifies:
|
||||
// - At any point during streaming, at most one chunk's reader is open.
|
||||
// - The number of opened chunks grows as bytes are read out, not upfront.
|
||||
// - All chunks are closed when the outer reader is fully drained.
|
||||
func TestBuildMultipartSSES3Reader_LazyChunkFetch(t *testing.T) {
|
||||
keyManager := initSSES3KeyManagerForTest(t)
|
||||
|
||||
key, err := GenerateSSES3Key()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSSES3Key: %v", err)
|
||||
}
|
||||
baseIV := make([]byte, s3_constants.AESBlockSize)
|
||||
if _, err := rand.Read(baseIV); err != nil {
|
||||
t.Fatalf("rand.Read baseIV: %v", err)
|
||||
}
|
||||
|
||||
// Many small chunks (mirrors many-part Docker Registry uploads).
|
||||
const numChunks = 8
|
||||
const chunkPayload = 1024
|
||||
plaintexts := make([][]byte, numChunks)
|
||||
chunkData := map[string][]byte{}
|
||||
chunks := make([]*filer_pb.FileChunk, 0, numChunks)
|
||||
for i := 0; i < numChunks; i++ {
|
||||
plaintexts[i] = makeRandomPlaintext(t, chunkPayload)
|
||||
|
||||
// Encrypt as a fresh "part" with partOffset=0 (matching putToFiler).
|
||||
encReader, _, err := CreateSSES3EncryptedReaderWithBaseIV(bytes.NewReader(plaintexts[i]), key, baseIV, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt chunk %d: %v", i, err)
|
||||
}
|
||||
ciphertext, err := io.ReadAll(encReader)
|
||||
if err != nil {
|
||||
t.Fatalf("read ciphertext %d: %v", i, err)
|
||||
}
|
||||
|
||||
chunkIV, _ := calculateIVWithOffset(baseIV, 0)
|
||||
chunkKey := &SSES3Key{
|
||||
Key: key.Key,
|
||||
KeyID: key.KeyID,
|
||||
Algorithm: key.Algorithm,
|
||||
IV: chunkIV,
|
||||
}
|
||||
meta, err := SerializeSSES3Metadata(chunkKey)
|
||||
if err != nil {
|
||||
t.Fatalf("serialize meta %d: %v", i, err)
|
||||
}
|
||||
|
||||
fid := fmt.Sprintf("vol,c%d", i)
|
||||
chunks = append(chunks, &filer_pb.FileChunk{
|
||||
FileId: fid,
|
||||
Offset: int64(i) * chunkPayload,
|
||||
Size: uint64(chunkPayload),
|
||||
SseType: filer_pb.SSEType_SSE_S3,
|
||||
SseMetadata: meta,
|
||||
})
|
||||
chunkData[fid] = ciphertext
|
||||
}
|
||||
|
||||
var openCount int64 // total opens
|
||||
var liveCount int64 // currently open
|
||||
var maxLive int64
|
||||
|
||||
fetch := func(c *filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
atomic.AddInt64(&openCount, 1)
|
||||
if live := atomic.AddInt64(&liveCount, 1); live > atomic.LoadInt64(&maxLive) {
|
||||
atomic.StoreInt64(&maxLive, live)
|
||||
}
|
||||
data, ok := chunkData[c.GetFileIdString()]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected chunk %s", c.GetFileIdString())
|
||||
}
|
||||
return &liveTrackingReadCloser{Reader: bytes.NewReader(data), live: &liveCount}, nil
|
||||
}
|
||||
|
||||
reader, err := buildMultipartSSES3Reader(chunks, keyManager, fetch)
|
||||
if err != nil {
|
||||
t.Fatalf("buildMultipartSSES3Reader: %v", err)
|
||||
}
|
||||
|
||||
// Construction alone must not have opened any chunk reader.
|
||||
if got := atomic.LoadInt64(&openCount); got != 0 {
|
||||
t.Fatalf("expected no chunks opened before any Read, got %d", got)
|
||||
}
|
||||
|
||||
// Read first byte: should open chunk 0 only.
|
||||
one := make([]byte, 1)
|
||||
if n, err := reader.Read(one); n != 1 || err != nil {
|
||||
t.Fatalf("first Read: n=%d err=%v", n, err)
|
||||
}
|
||||
if got := atomic.LoadInt64(&openCount); got != 1 {
|
||||
t.Errorf("after first byte, expected 1 chunk opened, got %d", got)
|
||||
}
|
||||
if got := atomic.LoadInt64(&liveCount); got != 1 {
|
||||
t.Errorf("after first byte, expected 1 chunk live, got %d", got)
|
||||
}
|
||||
|
||||
// Drain the rest.
|
||||
rest, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
t.Fatalf("drain: %v", err)
|
||||
}
|
||||
got := append(one, rest...)
|
||||
want := bytes.Join(plaintexts, nil)
|
||||
if !bytes.Equal(got, want) {
|
||||
idx := firstMismatch(got, want)
|
||||
t.Fatalf("decrypted output mismatch at byte %d (got len %d, want len %d)", idx, len(got), len(want))
|
||||
}
|
||||
if got := atomic.LoadInt64(&openCount); got != int64(numChunks) {
|
||||
t.Errorf("expected exactly %d chunk opens after drain, got %d", numChunks, got)
|
||||
}
|
||||
if got := atomic.LoadInt64(&maxLive); got > 1 {
|
||||
t.Errorf("expected at most 1 chunk reader live at a time (lazy), saw peak of %d", got)
|
||||
}
|
||||
if got := atomic.LoadInt64(&liveCount); got != 0 {
|
||||
t.Errorf("expected all chunks closed after drain, %d still live", got)
|
||||
}
|
||||
}
|
||||
|
||||
type liveTrackingReadCloser struct {
|
||||
io.Reader
|
||||
live *int64
|
||||
once bool
|
||||
}
|
||||
|
||||
func (r *liveTrackingReadCloser) Close() error {
|
||||
if r.once {
|
||||
return nil
|
||||
}
|
||||
r.once = true
|
||||
atomic.AddInt64(r.live, -1)
|
||||
return nil
|
||||
}
|
||||
@@ -16,6 +16,23 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Per-DB caps on goleveldb's open SST file cache. The library default is 500
|
||||
// per DB, but a volume server hosts one DB per volume — easily thousands —
|
||||
// so the per-DB default sums into FD exhaustion (`open .../00000N.log: too
|
||||
// many open files`) even with generous ulimits, especially when leveldb is
|
||||
// rotating its WAL.
|
||||
//
|
||||
// The trade-off: a larger cache lowers re-open overhead on cold reads, a
|
||||
// smaller cache bounds total FD usage. CompactionTableSizeMultiplier=10
|
||||
// already keeps SST counts low (~10x larger SSTs => ~10x fewer files), so
|
||||
// even the small-volume cap is enough to keep the working set hot while
|
||||
// leaving headroom for thousands of co-resident DBs.
|
||||
const (
|
||||
LevelDbOpenFilesCacheCapacity = 16
|
||||
LevelDbMediumOpenFilesCacheCapacity = 32
|
||||
LevelDbLargeOpenFilesCacheCapacity = 64
|
||||
)
|
||||
|
||||
func loadVolumeWithoutIndex(dirname string, collection string, id needle.VolumeId, needleMapKind NeedleMapKind, ver needle.Version) (v *Volume, err error) {
|
||||
v = &Volume{dir: dirname, Collection: collection, Id: id}
|
||||
v.SuperBlock = super_block.SuperBlock{}
|
||||
@@ -196,9 +213,10 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
}
|
||||
case NeedleMapLevelDb:
|
||||
opts := &opt.Options{
|
||||
BlockCacheCapacity: 2 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 1 * 1024 * 1024, // default value is 4MiB
|
||||
CompactionTableSizeMultiplier: 10, // default value is 1
|
||||
BlockCacheCapacity: 2 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 1 * 1024 * 1024, // default value is 4MiB
|
||||
CompactionTableSizeMultiplier: 10, // default value is 1
|
||||
OpenFilesCacheCapacity: LevelDbOpenFilesCacheCapacity, // see package-level docs
|
||||
}
|
||||
if v.tmpNm != nil {
|
||||
glog.V(0).Infoln("updating leveldb index", v.FileName(".ldb"))
|
||||
@@ -211,9 +229,10 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
}
|
||||
case NeedleMapLevelDbMedium:
|
||||
opts := &opt.Options{
|
||||
BlockCacheCapacity: 4 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 2 * 1024 * 1024, // default value is 4MiB
|
||||
CompactionTableSizeMultiplier: 10, // default value is 1
|
||||
BlockCacheCapacity: 4 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 2 * 1024 * 1024, // default value is 4MiB
|
||||
CompactionTableSizeMultiplier: 10, // default value is 1
|
||||
OpenFilesCacheCapacity: LevelDbMediumOpenFilesCacheCapacity, // see package-level docs
|
||||
}
|
||||
if v.tmpNm != nil {
|
||||
glog.V(0).Infoln("updating leveldb medium index", v.FileName(".ldb"))
|
||||
@@ -226,9 +245,10 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
}
|
||||
case NeedleMapLevelDbLarge:
|
||||
opts := &opt.Options{
|
||||
BlockCacheCapacity: 8 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 4 * 1024 * 1024, // default value is 4MiB
|
||||
CompactionTableSizeMultiplier: 10, // default value is 1
|
||||
BlockCacheCapacity: 8 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 4 * 1024 * 1024, // default value is 4MiB
|
||||
CompactionTableSizeMultiplier: 10, // default value is 1
|
||||
OpenFilesCacheCapacity: LevelDbLargeOpenFilesCacheCapacity, // see package-level docs
|
||||
}
|
||||
if v.tmpNm != nil {
|
||||
glog.V(0).Infoln("updating leveldb large index", v.FileName(".ldb"))
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// Package pgxutil holds shared helpers for opening *sql.DB handles backed
|
||||
// by jackc/pgx, used by the postgres filer and credential stores so they
|
||||
// stay consistent on connection setup, mTLS handling and PgBouncer
|
||||
// compatibility.
|
||||
package pgxutil
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
// DSNOptions describes the parameters used to assemble a libpq-style
|
||||
// keyword=value connection string. Empty fields are omitted.
|
||||
type DSNOptions struct {
|
||||
Hostname string
|
||||
Port int
|
||||
User string
|
||||
Password string
|
||||
Database string
|
||||
Schema string
|
||||
SSLMode string
|
||||
SSLCert string
|
||||
SSLKey string
|
||||
SSLRootCert string
|
||||
SSLCRL string
|
||||
// PgBouncerCompatible toggles two things at the caller's site: the
|
||||
// search_path is omitted from the DSN (PgBouncer rejects it under
|
||||
// transaction pooling) and OpenDB is told to use the simple query
|
||||
// protocol.
|
||||
PgBouncerCompatible bool
|
||||
}
|
||||
|
||||
// quoteDSNValue wraps v per the libpq keyword/value rules: empty values
|
||||
// and values containing whitespace, single quotes, or backslashes are
|
||||
// single-quoted with internal `'` and `\` escaped. Plain alphanumeric
|
||||
// values are returned unchanged. See PostgreSQL docs §"Connection Strings".
|
||||
func quoteDSNValue(v string) string {
|
||||
if v == "" {
|
||||
return "''"
|
||||
}
|
||||
needsQuote := false
|
||||
for i := 0; i < len(v); i++ {
|
||||
c := v[i]
|
||||
if c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\'' || c == '\\' {
|
||||
needsQuote = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !needsQuote {
|
||||
return v
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(len(v) + 2)
|
||||
b.WriteByte('\'')
|
||||
for i := 0; i < len(v); i++ {
|
||||
c := v[i]
|
||||
if c == '\'' || c == '\\' {
|
||||
b.WriteByte('\\')
|
||||
}
|
||||
b.WriteByte(c)
|
||||
}
|
||||
b.WriteByte('\'')
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// BuildDSN assembles two libpq-style connection strings from opts: the
|
||||
// real DSN passed to pgx, and an adapted copy with the password redacted
|
||||
// for use in error messages and logs. Values containing spaces, single
|
||||
// quotes, or backslashes are quoted per libpq rules so passwords and
|
||||
// cert paths sourced from secret managers can carry arbitrary characters
|
||||
// without breaking pgx.ParseConfig.
|
||||
func BuildDSN(opts DSNOptions) (dsn, adaptedDSN string) {
|
||||
dsn = "connect_timeout=30"
|
||||
if opts.Hostname != "" {
|
||||
dsn += " host=" + quoteDSNValue(opts.Hostname)
|
||||
}
|
||||
if opts.Port != 0 {
|
||||
dsn += " port=" + strconv.Itoa(opts.Port)
|
||||
}
|
||||
if opts.SSLMode != "" {
|
||||
dsn += " sslmode=" + quoteDSNValue(opts.SSLMode)
|
||||
}
|
||||
if opts.SSLCert != "" {
|
||||
dsn += " sslcert=" + quoteDSNValue(opts.SSLCert)
|
||||
}
|
||||
if opts.SSLKey != "" {
|
||||
dsn += " sslkey=" + quoteDSNValue(opts.SSLKey)
|
||||
}
|
||||
if opts.SSLRootCert != "" {
|
||||
dsn += " sslrootcert=" + quoteDSNValue(opts.SSLRootCert)
|
||||
}
|
||||
if opts.SSLCRL != "" {
|
||||
dsn += " sslcrl=" + quoteDSNValue(opts.SSLCRL)
|
||||
}
|
||||
if opts.User != "" {
|
||||
dsn += " user=" + quoteDSNValue(opts.User)
|
||||
}
|
||||
adaptedDSN = dsn
|
||||
if opts.Password != "" {
|
||||
dsn += " password=" + quoteDSNValue(opts.Password)
|
||||
adaptedDSN += " password=ADAPTED"
|
||||
}
|
||||
if opts.Database != "" {
|
||||
dsn += " dbname=" + quoteDSNValue(opts.Database)
|
||||
adaptedDSN += " dbname=" + quoteDSNValue(opts.Database)
|
||||
}
|
||||
if opts.Schema != "" && !opts.PgBouncerCompatible {
|
||||
dsn += " search_path=" + quoteDSNValue(opts.Schema)
|
||||
adaptedDSN += " search_path=" + quoteDSNValue(opts.Schema)
|
||||
}
|
||||
return dsn, adaptedDSN
|
||||
}
|
||||
|
||||
// OpenDB parses dsn into a pgx ConnConfig, applies PgBouncer compatibility
|
||||
// settings when requested, opens a *sql.DB via stdlib.OpenDB, and verifies
|
||||
// it with Ping.
|
||||
//
|
||||
// In pgx/v5 the prefer_simple_protocol DSN parameter was removed, so simple
|
||||
// protocol mode must be configured on the ConnConfig via DefaultQueryExecMode.
|
||||
// We use stdlib.OpenDB(config) rather than RegisterConnConfig + sql.Open so
|
||||
// we don't leak entries in stdlib's global connection config map on either
|
||||
// success or failure paths.
|
||||
//
|
||||
// adaptedDSN is used only for error messages (the caller is expected to
|
||||
// have redacted any password).
|
||||
func OpenDB(dsn, adaptedDSN string, pgbouncerCompatible bool, maxIdle, maxOpen, maxLifetimeSeconds int) (*sql.DB, error) {
|
||||
connConfig, parseErr := pgx.ParseConfig(dsn)
|
||||
if parseErr != nil {
|
||||
return nil, fmt.Errorf("can not parse connection config for %s error:%v", adaptedDSN, parseErr)
|
||||
}
|
||||
|
||||
// PgBouncer compatibility: use the simple query protocol and disable
|
||||
// statement caching. This avoids prepared statement issues with
|
||||
// PgBouncer's transaction pooling mode.
|
||||
if pgbouncerCompatible {
|
||||
connConfig.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
|
||||
connConfig.StatementCacheCapacity = 0
|
||||
connConfig.DescriptionCacheCapacity = 0
|
||||
}
|
||||
|
||||
db := stdlib.OpenDB(*connConfig)
|
||||
db.SetMaxIdleConns(maxIdle)
|
||||
db.SetMaxOpenConns(maxOpen)
|
||||
db.SetConnMaxLifetime(time.Duration(maxLifetimeSeconds) * time.Second)
|
||||
|
||||
if err := db.Ping(); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("connect to %s error:%v", adaptedDSN, err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package pgxutil
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestQuoteDSNValue(t *testing.T) {
|
||||
cases := []struct {
|
||||
in, want string
|
||||
}{
|
||||
{"", "''"},
|
||||
{"plain", "plain"},
|
||||
{"with space", "'with space'"},
|
||||
{"it's", `'it\'s'`},
|
||||
{`back\slash`, `'back\\slash'`},
|
||||
{`mix it's \and spaces`, `'mix it\'s \\and spaces'`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := quoteDSNValue(c.in); got != c.want {
|
||||
t.Errorf("quoteDSNValue(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildDSN_QuotesProblematicValues verifies that the assembled DSN
|
||||
// stays parseable by pgx when values contain spaces, single quotes or
|
||||
// backslashes — the kind of password/cert paths a secret manager can
|
||||
// hand us in production.
|
||||
func TestBuildDSN_QuotesProblematicValues(t *testing.T) {
|
||||
opts := DSNOptions{
|
||||
Hostname: "db.example.com",
|
||||
Port: 5432,
|
||||
User: "iam user",
|
||||
Password: `p@ss it's word\\`,
|
||||
Database: "weed",
|
||||
Schema: "public",
|
||||
SSLMode: "disable",
|
||||
}
|
||||
dsn, adapted := BuildDSN(opts)
|
||||
if strings.Contains(adapted, opts.Password) {
|
||||
t.Errorf("adapted DSN must redact the password, got %q", adapted)
|
||||
}
|
||||
cfg, err := pgx.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("pgx.ParseConfig rejected the assembled DSN: %v\nDSN: %s", err, dsn)
|
||||
}
|
||||
if cfg.User != opts.User {
|
||||
t.Errorf("User: got %q want %q", cfg.User, opts.User)
|
||||
}
|
||||
if cfg.Password != opts.Password {
|
||||
t.Errorf("Password: got %q want %q", cfg.Password, opts.Password)
|
||||
}
|
||||
if cfg.Database != opts.Database {
|
||||
t.Errorf("Database: got %q want %q", cfg.Database, opts.Database)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(21)
|
||||
MINOR_VERSION = int32(22)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
Reference in new issue
Block a user