mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-28 23:27:05 +01:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a730efea6 | ||
|
|
b6dd48403e | ||
|
|
8cc3e299fc | ||
|
|
92bd112cfd | ||
|
|
4f1178e0ba | ||
|
|
071d9d2f3c |
No files matched your search
@@ -439,117 +439,6 @@ jobs:
|
||||
path: test/s3tables/catalog_clickhouse/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
olake-iceberg-catalog-tests:
|
||||
name: OLake Iceberg Catalog Integration Tests (${{ matrix.tag }})
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# Pinned baseline, and latest so new OLake releases are exercised
|
||||
# without a code change. OLake's Iceberg writer is a Java sidecar
|
||||
# whose Iceberg version moves independently of the Go release, so
|
||||
# the latest leg is the one that catches library drift.
|
||||
- olake-image: olakego/source-postgres:v0.10.1
|
||||
tag: "v0.10.1"
|
||||
- olake-image: olakego/source-postgres:latest
|
||||
tag: latest
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
id: go
|
||||
|
||||
- name: Configure Docker Hub mirror
|
||||
run: |
|
||||
echo '{"registry-mirrors": ["https://mirror.gcr.io"]}' | sudo tee /etc/docker/daemon.json
|
||||
sudo systemctl restart docker
|
||||
|
||||
- name: Pre-pull images
|
||||
run: |
|
||||
pull() { for i in 1 2 3; do docker pull "$1" && return 0; sleep 15; done; return 1; }
|
||||
pull ${{ matrix.olake-image }}
|
||||
pull postgres:16
|
||||
pull python:3.11-slim
|
||||
|
||||
- name: Run go mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
go install -buildvcs=false ./weed
|
||||
|
||||
- name: Run OLake Iceberg Catalog Integration Tests
|
||||
timeout-minutes: 25
|
||||
working-directory: test/s3tables/catalog_olake
|
||||
env:
|
||||
OLAKE_IMAGE: ${{ matrix.olake-image }}
|
||||
run: |
|
||||
set -x
|
||||
set -o pipefail
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
docker info
|
||||
echo "=== Starting OLake Iceberg Catalog Tests ==="
|
||||
|
||||
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
|
||||
echo "OLake Iceberg catalog integration tests failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# The suite skips itself when Docker is unavailable, so a green job is not
|
||||
# by itself evidence that anything ran. Assert execution explicitly.
|
||||
- name: Assert the suite actually ran
|
||||
working-directory: test/s3tables/catalog_olake
|
||||
run: |
|
||||
log=test-output.log
|
||||
if [ ! -f "$log" ]; then
|
||||
echo "::error::no test-output.log; the suite did not run"
|
||||
exit 1
|
||||
fi
|
||||
passes=$(grep -c '^--- PASS' "$log" || true)
|
||||
skips=$(grep -c '^--- SKIP' "$log" || true)
|
||||
echo "top-level PASS=$passes SKIP=$skips"
|
||||
if [ "$skips" -gt 0 ]; then
|
||||
echo "::error::the OLake suite skipped $skips top-level test(s); the environment it needs was not provisioned, so this job proves nothing"
|
||||
grep '^--- SKIP' "$log" | head -20
|
||||
exit 1
|
||||
fi
|
||||
if [ "$passes" -lt 1 ]; then
|
||||
echo "::error::the OLake suite recorded no passing top-level test"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Show test output on failure
|
||||
if: failure()
|
||||
working-directory: test/s3tables/catalog_olake
|
||||
run: |
|
||||
echo "=== Test Output ==="
|
||||
if [ -f test-output.log ]; then
|
||||
tail -200 test-output.log
|
||||
fi
|
||||
|
||||
echo "=== Process information ==="
|
||||
ps aux | grep -E "(weed|test|docker|olake|postgres)" || true
|
||||
echo "=== Containers ==="
|
||||
docker ps -a | head -30 || true
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: olake-iceberg-catalog-test-logs-${{ matrix.tag }}
|
||||
path: test/s3tables/catalog_olake/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
polaris-integration-tests:
|
||||
name: Polaris Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
@@ -21,7 +21,6 @@ One `weed` binary serves an S3 object store, a POSIX file system, and a lakehous
|
||||
|
||||
- [Download Binaries for different platforms](https://github.com/seaweedfs/seaweedfs/releases/latest)
|
||||
- [Wiki Documentation](https://github.com/seaweedfs/seaweedfs/wiki)
|
||||
- [HTTP REST API](REST_API.md) for the filer, master, and volume servers
|
||||
- Community: [Slack](https://join.slack.com/t/seaweedfs/shared_invite/enQtMzI4MTMwMjU2MzA3LTEyYzZmZWYzOGQ3MDJlZWMzYmI0OTE4OTJiZjJjODBmMzUxNmYwODg0YjY3MTNlMjBmZDQ1NzQ5NDJhZWI2ZmY), [Twitter](https://twitter.com/SeaweedFS), [Telegram](https://t.me/Seaweedfs), [Reddit](https://www.reddit.com/r/SeaweedFS/), [Mailing List](https://groups.google.com/d/forum/seaweedfs)
|
||||
- [SeaweedFS White Paper](https://github.com/seaweedfs/seaweedfs/wiki/SeaweedFS_Architecture.pdf) and introduction slides: [2025.5](https://docs.google.com/presentation/d/1tdkp45J01oRV68dIm4yoTXKJDof-EhainlA0LMXexQE/edit?usp=sharing), [2021.5](https://docs.google.com/presentation/d/1DcxKWlINc-HNCjhYeERkpGXXm6nTCES8mi2W5G0Z4Ts/edit?usp=sharing), [2019.3](https://www.slideshare.net/chrislusf/seaweedfs-introduction)
|
||||
|
||||
|
||||
-344
@@ -1,344 +0,0 @@
|
||||
# SeaweedFS HTTP REST API
|
||||
|
||||
SeaweedFS exposes three HTTP surfaces:
|
||||
|
||||
| Service | Default port | Addressing |
|
||||
|---------|--------------|------------|
|
||||
| Filer | 8888 | File system paths (`/dir/name`) |
|
||||
| Master | 9333 | File id assignment and cluster topology |
|
||||
| Volume server | 8080 | File content by file id (`vid,fid`) |
|
||||
|
||||
Most clients only need the filer API (paths) or the S3 API. The master and
|
||||
volume APIs are the lower-level blob store interface.
|
||||
|
||||
Conventions applying to all three:
|
||||
|
||||
- Responses are JSON unless noted otherwise. Append `&pretty=y` to pretty-print.
|
||||
- A file id (`fid`) has the form `volumeId,fileKeyCookie`, e.g. `3,01637037d6`.
|
||||
An optional suffix selects a reserved id from a `count` assignment
|
||||
(`3,01637037d6_1`, `_2`, ...), and an optional extension
|
||||
(`3,01637037d6.jpg`) sets the content type on reads.
|
||||
- `replication` is a 3-digit replica placement `xyz`: `x` copies in other
|
||||
data centers, `y` on other racks in the same data center, `z` on other
|
||||
volume servers on the same rack. `000` = no replication, `001` = one copy
|
||||
on the same rack, `010` = one copy on a different rack, `100` = one copy in
|
||||
another data center, `200` = two copies in two other data centers, `110` =
|
||||
one copy in another data center plus one on another rack.
|
||||
- `ttl` units: `m` minute, `h` hour, `d` day, `w` week, `M` month, `y` year.
|
||||
|
||||
## Filer API (port 8888)
|
||||
|
||||
The filer presents a POSIX-like namespace over the volume servers.
|
||||
|
||||
### Upload a file
|
||||
|
||||
```bash
|
||||
# PUT the raw body to the target path
|
||||
curl -T /home/chris/myphoto.jpg "http://localhost:8888/dir/myphoto.jpg"
|
||||
|
||||
# or POST as multipart form (the part filename becomes the entry name)
|
||||
curl -F file=@/home/chris/myphoto.jpg "http://localhost:8888/dir/"
|
||||
```
|
||||
|
||||
Response `201 Created`:
|
||||
|
||||
```json
|
||||
{"name":"myphoto.jpg","size":43234,"eTag":"0x6c656...","mtime":"...","chunks":[...]}
|
||||
```
|
||||
|
||||
Query parameters:
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `collection` | collection name | empty |
|
||||
| `replication` | replica placement code | filer default |
|
||||
| `ttl` | file expiration, e.g. `3d` | never |
|
||||
| `disk` | disk type to store on | filer default |
|
||||
| `fsync` | `true` fsyncs on the volume server | false |
|
||||
| `dataCenter` | preferred data center | empty |
|
||||
| `rack` | preferred rack | empty |
|
||||
| `dataNode` | preferred volume server | empty |
|
||||
| `saveInside` | store small content inside the metadata instead of a volume | false |
|
||||
| `maxMB` | split the upload into chunks of this many MB | filer `-maxMB` |
|
||||
| `mode` | unix permission bits, e.g. `0644` | `0660` |
|
||||
| `op` | `append` appends to an existing file | overwrite |
|
||||
| `skipCheckParentDir` | `true` skips the parent-directory existence check | false |
|
||||
|
||||
### Create a directory
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:8888/dir/newdir/"
|
||||
```
|
||||
|
||||
A POST to a path ending in `/` with no content creates the directory,
|
||||
including missing parents.
|
||||
|
||||
### Read a file
|
||||
|
||||
```bash
|
||||
curl "http://localhost:8888/dir/myphoto.jpg"
|
||||
```
|
||||
|
||||
Supports `Range` requests (`Accept-Ranges: bytes`), `ETag`, and the
|
||||
`If-None-Match` / `If-Modified-Since` conditional headers. `HEAD` returns
|
||||
headers only. Entry headers stored as extended attributes are echoed back,
|
||||
minus internal `Seaweed-` and `xattr-` keys.
|
||||
|
||||
Entry metadata instead of content:
|
||||
|
||||
```bash
|
||||
curl "http://localhost:8888/dir/myphoto.jpg?metadata=true"
|
||||
```
|
||||
|
||||
`metadata=true&resolveManifest=true` additionally resolves chunked-manifest
|
||||
entries into their real chunk list.
|
||||
|
||||
### List a directory
|
||||
|
||||
```bash
|
||||
curl -H "Accept: application/json" "http://localhost:8888/dir/?limit=10&lastFileName=a.jpg"
|
||||
```
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `limit` | max entries per page | filer `-dirListLimit` |
|
||||
| `lastFileName` | resume listing after this entry name | empty |
|
||||
| `namePattern` | include only names matching the wildcard | empty |
|
||||
| `namePatternExclude` | exclude names matching the wildcard | empty |
|
||||
|
||||
The JSON response carries `Path`, `Entries`, `Limit`, `LastFileName`,
|
||||
`ShouldDisplayLoadMore`, and `EmptyFolder`. Without the `Accept` header the
|
||||
filer renders its HTML browser.
|
||||
|
||||
### Move and copy
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:8888/dir/newname.jpg?mv.from=/dir/myphoto.jpg"
|
||||
curl -X POST "http://localhost:8888/dir/copy.jpg?cp.from=/dir/myphoto.jpg"
|
||||
```
|
||||
|
||||
`mv.from` renames or moves the source to the request path (`204 No Content`).
|
||||
`cp.from` copies it.
|
||||
|
||||
### Append
|
||||
|
||||
```bash
|
||||
curl -T chunk2.bin "http://localhost:8888/dir/file.bin?op=append"
|
||||
```
|
||||
|
||||
### Delete
|
||||
|
||||
```bash
|
||||
curl -X DELETE "http://localhost:8888/dir/myphoto.jpg"
|
||||
curl -X DELETE "http://localhost:8888/dir/?recursive=true"
|
||||
```
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `recursive` | delete a non-empty directory tree | false; when the filer runs with `filer.options.recursive_delete=true`, deletes are recursive unless `recursive=false` |
|
||||
| `ignoreRecursiveError` | keep deleting remaining entries after an error | false |
|
||||
| `skipChunkDeletion` | remove only the metadata, keep volume data | false |
|
||||
|
||||
### Tagging
|
||||
|
||||
Tags are carried as `Seaweed-`-prefixed request headers, not query
|
||||
parameters; `?tagging` selects the tagging handler and `?tagging=K1,K2`
|
||||
lists the keys to remove. Header names are canonicalized on write
|
||||
(`Seaweed-k1` is stored as `Seaweed-K1`), and the delete list is matched
|
||||
case-sensitively against the stored names.
|
||||
|
||||
```bash
|
||||
curl -X PUT -H "Seaweed-k1: v1" -H "Seaweed-k2: v2" "http://localhost:8888/dir/file.jpg?tagging"
|
||||
curl -X DELETE "http://localhost:8888/dir/file.jpg?tagging=K1,K2"
|
||||
```
|
||||
|
||||
### Read by file id
|
||||
|
||||
```bash
|
||||
curl "http://localhost:8888/?proxyChunkId=3,01637037d6"
|
||||
```
|
||||
|
||||
The filer proxies the chunk read to the right volume server, so only the
|
||||
filer port needs to be exposed.
|
||||
|
||||
### Resumable uploads
|
||||
|
||||
The filer serves the [TUS protocol](https://tus.io/) for resumable uploads
|
||||
(`POST`, `PATCH`, `HEAD` on upload URLs). It is enabled by default at
|
||||
`/.tus`; `-tusBasePath` changes the endpoint base path.
|
||||
|
||||
### Health
|
||||
|
||||
`GET /healthz` and `GET /readyz` return `200 OK`.
|
||||
|
||||
## Master API (port 9333)
|
||||
|
||||
Write-affecting endpoints are automatically proxied to the current leader, so
|
||||
any master in the quorum can serve them.
|
||||
|
||||
### Assign a file id
|
||||
|
||||
```bash
|
||||
curl "http://localhost:9333/dir/assign?count=1&replication=001&collection=turbo&dataCenter=dc1&ttl=3d&disk=ssd"
|
||||
{"count":1,"fid":"3,01637037d6","url":"127.0.0.1:8080","publicUrl":"localhost:8080"}
|
||||
```
|
||||
|
||||
Upload the file content to `http://<url>/<fid>` afterwards. With `count>1`,
|
||||
use `<fid>_1`, `<fid>_2`, ... for the additional ids.
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `count` | file ids to reserve | 1 |
|
||||
| `collection` | collection name | empty |
|
||||
| `dataCenter` | preferred data center | empty |
|
||||
| `rack` | preferred rack | empty |
|
||||
| `dataNode` | preferred volume server | empty |
|
||||
| `replication` | replica placement | master `-defaultReplication` |
|
||||
| `ttl` | file expiration, e.g. `3d` | never |
|
||||
| `disk` | disk type | empty |
|
||||
| `dataSize` | expected file size in bytes | 0 |
|
||||
| `preallocate` | bytes to preallocate for new volumes | master `-volumePreallocate` |
|
||||
| `writableVolumeCount` | grow this many volumes when none are writable | master default |
|
||||
| `memoryMapMaxSizeMb` | memory-mapped file size (Windows) | 0 |
|
||||
|
||||
### Look up a volume or file id
|
||||
|
||||
```bash
|
||||
curl "http://localhost:9333/dir/lookup?volumeId=3"
|
||||
{"locations":[{"url":"localhost:8080","publicUrl":"localhost:8080"}]}
|
||||
```
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `volumeId` | volume id; a full `vid,fid` is accepted too | required |
|
||||
| `fileId` | like `volumeId`, but also returns a write JWT when security is on | empty |
|
||||
| `collection` | speeds up the lookup | empty |
|
||||
| `read` | `yes` generates a read JWT instead of a write JWT | empty |
|
||||
|
||||
### Store a file in one call
|
||||
|
||||
```bash
|
||||
curl -F file=@/home/chris/report.pdf "http://localhost:9333/submit?collection=turbo&replication=001"
|
||||
{"fileName":"report.pdf","fid":"3,01637037d6","fileUrl":"localhost:8080/3,01637037d6","size":43234,"eTag":"0x6c656..."}
|
||||
```
|
||||
|
||||
`POST /submit` accepts multipart file data plus the `dir/assign` placement
|
||||
parameters (`count`, `collection`, `dataCenter`, `rack`, `replication`,
|
||||
`ttl`, `disk`), assigns a file id, uploads to the volume server, and returns
|
||||
the result.
|
||||
|
||||
### Redirect to a file
|
||||
|
||||
```bash
|
||||
curl -v "http://localhost:9333/3,01637037d6"
|
||||
```
|
||||
|
||||
`GET /{fileId}` answers `308 Permanent Redirect` to a volume server holding
|
||||
the file, preserving the query string (e.g. image-resize parameters).
|
||||
|
||||
### Cluster status
|
||||
|
||||
```bash
|
||||
curl "http://localhost:9333/dir/status?pretty=y" # full topology tree
|
||||
curl "http://localhost:9333/vol/status?pretty=y" # every volume on every node
|
||||
curl "http://localhost:9333/collection/info?collection=turbo"
|
||||
curl "http://localhost:9333/collection/info?collection=turbo&detail=true"
|
||||
```
|
||||
|
||||
`collection/info` returns aggregated `TotalSize`, `FileCount`, `UsedSize`,
|
||||
`VolumeCount`; `detail=true` splits them per volume layout.
|
||||
|
||||
### Grow volumes
|
||||
|
||||
```bash
|
||||
curl "http://localhost:9333/vol/grow?count=4&replication=001&collection=turbo&ttl=5d&disk=ssd&dataCenter=dc1&rack=rack1"
|
||||
{"count":4}
|
||||
```
|
||||
|
||||
`count` is required; the placement parameters match `dir/assign`. One volume
|
||||
serves one write at a time, so pre-allocated volumes raise write concurrency.
|
||||
|
||||
### Vacuum deleted space
|
||||
|
||||
```bash
|
||||
curl "http://localhost:9333/vol/vacuum?garbageThreshold=0.4"
|
||||
```
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `garbageThreshold` | minimum deleted-bytes ratio before a volume is compacted | master `-garbageThreshold` (0.3) |
|
||||
|
||||
Vacuuming makes a volume read-only, copies live needles to a new volume, and
|
||||
swaps it in.
|
||||
|
||||
### Delete a collection
|
||||
|
||||
```bash
|
||||
curl "http://localhost:9333/col/delete?collection=benchmark"
|
||||
```
|
||||
|
||||
Deletes all volumes of the collection, including erasure-coded shards.
|
||||
`204 No Content` on success.
|
||||
|
||||
### Health
|
||||
|
||||
```bash
|
||||
curl -I "http://localhost:9333/healthz" # liveness
|
||||
curl -I "http://localhost:9333/readyz" # readiness
|
||||
curl "http://localhost:9333/" # web UI
|
||||
```
|
||||
|
||||
## Volume server API (port 8080)
|
||||
|
||||
The volume server stores file content by file id. Clients normally get the
|
||||
volume URL from `dir/assign` or `dir/lookup`.
|
||||
|
||||
### Upload
|
||||
|
||||
```bash
|
||||
curl -F file=@/home/chris/myphoto.jpg "http://127.0.0.1:8080/3,01637037d6"
|
||||
{"name":"myphoto.jpg","size":43234,"eTag":"0x6c656...","mime":"image/jpeg","contentMd5":"..."}
|
||||
```
|
||||
|
||||
PUT or POST the body (or a multipart `file` part) to `/{vid},{fid}`.
|
||||
`204 No Content` is returned when the content is unchanged. `?ts=<unix>`
|
||||
sets the stored modification time.
|
||||
|
||||
### Read
|
||||
|
||||
```bash
|
||||
curl "http://127.0.0.1:8080/3,01637037d6"
|
||||
curl "http://127.0.0.1:8080/3,01637037d6.jpg" # sets Content-Type from the extension
|
||||
```
|
||||
|
||||
Supports `Range` and `HEAD`. Image files can be resized server-side:
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `width`, `height` | resize bounds in pixels |
|
||||
| `mode` | `fit` (contain) or `fill` (cover); omitted resizes to `width`/`height` |
|
||||
| `crop_x1`, `crop_y1`, `crop_x2`, `crop_y2` | explicit crop rectangle |
|
||||
| `cm` | `false` returns the chunk-manifest blob instead of resolving it |
|
||||
| `readDeleted` | `true` reads soft-deleted needles |
|
||||
| `collection` | passed through redirects for the right volume |
|
||||
|
||||
### Delete
|
||||
|
||||
```bash
|
||||
curl -X DELETE "http://127.0.0.1:8080/3,01637037d6"
|
||||
{"size":43234}
|
||||
```
|
||||
|
||||
`?ts=<unix>` sets the deletion timestamp. Replicated volumes propagate the
|
||||
delete to every replica.
|
||||
|
||||
### Status
|
||||
|
||||
```bash
|
||||
curl "http://localhost:8080/status?pretty=y" # disk and volume inventory
|
||||
curl -I "http://localhost:8080/healthz" # liveness/readiness
|
||||
```
|
||||
|
||||
`OPTIONS` preflights answer CORS headers. When `-port.public` differs from
|
||||
`-port`, the volume server opens a separate read-only public listener on
|
||||
that port; `-publicUrl` sets the address it advertises to clients.
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.48"
|
||||
appVersion: "4.47"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.48.0
|
||||
version: 4.47.1
|
||||
+1016
-1021
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 53 KiB |
Generated
-1
@@ -4555,7 +4555,6 @@ dependencies = [
|
||||
"aws-config",
|
||||
"aws-credential-types",
|
||||
"aws-sdk-s3",
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-types",
|
||||
"axum",
|
||||
"base64",
|
||||
|
||||
@@ -157,9 +157,6 @@ windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
# Already a transitive dependency of aws-sdk-s3 at a single locked version;
|
||||
# needed directly only for the canned HttpClient in remote_storage::s3 tests.
|
||||
aws-smithy-runtime-api = "1"
|
||||
|
||||
[build-dependencies]
|
||||
tonic-prost-build = "0.14"
|
||||
|
||||
@@ -259,10 +259,6 @@ message VolumeDeleteRequest {
|
||||
// when true, do not remove the cloud-tier object backing the volume.
|
||||
// used for moves where another server is taking over the same .vif.
|
||||
bool keep_remote_data = 3;
|
||||
// when true, delete only if every needle is deleted: the volume held
|
||||
// data once but nothing is live anymore. Passing either check,
|
||||
// only_empty or this one, is enough to delete.
|
||||
bool only_garbage = 4;
|
||||
}
|
||||
message VolumeDeleteResponse {
|
||||
}
|
||||
@@ -475,7 +471,6 @@ message VolumeEcShardsDeleteRequest {
|
||||
repeated uint32 shard_ids = 3;
|
||||
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
uint32 delete_generations_older_than = 6; // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
|
||||
}
|
||||
message VolumeEcShardsDeleteResponse {
|
||||
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
|
||||
+104
-507
@@ -178,22 +178,12 @@ pub struct Cli {
|
||||
pub min_free_space: String,
|
||||
|
||||
/// Inflight upload data wait timeout of volume servers.
|
||||
/// Go `time.Duration` syntax: `300ms`, `1.5h`, `2h45m`; a bare number other than `0` is rejected.
|
||||
#[arg(
|
||||
long = "inflightUploadDataTimeout",
|
||||
default_value = "60s",
|
||||
value_parser = parse_go_duration
|
||||
)]
|
||||
pub inflight_upload_data_timeout: std::time::Duration,
|
||||
#[arg(long = "inflightUploadDataTimeout", default_value = "60s")]
|
||||
pub inflight_upload_data_timeout: String,
|
||||
|
||||
/// Inflight download data wait timeout of volume servers.
|
||||
/// Go `time.Duration` syntax: `300ms`, `1.5h`, `2h45m`; a bare number other than `0` is rejected.
|
||||
#[arg(
|
||||
long = "inflightDownloadDataTimeout",
|
||||
default_value = "60s",
|
||||
value_parser = parse_go_duration
|
||||
)]
|
||||
pub inflight_download_data_timeout: std::time::Duration,
|
||||
#[arg(long = "inflightDownloadDataTimeout", default_value = "60s")]
|
||||
pub inflight_download_data_timeout: String,
|
||||
|
||||
/// <experimental> if true, prevents slow reads from blocking other requests,
|
||||
/// but large file read P99 latency will increase.
|
||||
@@ -481,214 +471,99 @@ fn find_options_arg(args: &[String]) -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// Parse a duration with Go's `time.ParseDuration` grammar, as Go's
|
||||
/// `flag.Duration` flags do: `[0-9]*(\.[0-9]*)?<unit>` repeated, units
|
||||
/// `ns`/`us`/`µs`/`μs`/`ms`/`s`/`m`/`h`. A bare `0` is the only unit-less
|
||||
/// value; a leading sign parses in Go but a negative has no
|
||||
/// `std::time::Duration`, so it is an error, not a clamp.
|
||||
fn parse_go_duration(s: &str) -> Result<std::time::Duration, String> {
|
||||
let orig = s;
|
||||
let invalid = || format!("time: invalid duration {:?}", orig);
|
||||
|
||||
let mut s = s;
|
||||
if let Some(rest) = s.strip_prefix('-') {
|
||||
if rest.is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
return Err(format!("negative duration {:?} is not supported", orig));
|
||||
}
|
||||
if let Some(rest) = s.strip_prefix('+') {
|
||||
s = rest;
|
||||
}
|
||||
if s == "0" {
|
||||
return Ok(std::time::Duration::ZERO);
|
||||
}
|
||||
if s.is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
// Go bounds the total by 1<<63 (int64 nanoseconds): overflow is an error.
|
||||
const MAX: u64 = 1 << 63;
|
||||
let mut total: u64 = 0;
|
||||
let mut bytes = s.as_bytes();
|
||||
while !bytes.is_empty() {
|
||||
if !(bytes[0] == b'.' || bytes[0].is_ascii_digit()) {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
// Consume [0-9]*
|
||||
let mut i = 0;
|
||||
let mut v: u64 = 0;
|
||||
while i < bytes.len() && bytes[i].is_ascii_digit() {
|
||||
v = v
|
||||
.checked_mul(10)
|
||||
.and_then(|v| v.checked_add(u64::from(bytes[i] - b'0')))
|
||||
.filter(|v| *v <= MAX)
|
||||
.ok_or_else(invalid)?;
|
||||
i += 1;
|
||||
}
|
||||
let pre = i != 0;
|
||||
bytes = &bytes[i..];
|
||||
|
||||
// Consume (\.[0-9]*)?
|
||||
let mut f: u64 = 0;
|
||||
let mut scale: f64 = 1.0;
|
||||
let mut post = false;
|
||||
if let Some((b'.', rest)) = bytes.split_first() {
|
||||
bytes = rest;
|
||||
let mut i = 0;
|
||||
let mut overflow = false;
|
||||
while i < bytes.len() && bytes[i].is_ascii_digit() {
|
||||
if !overflow {
|
||||
// Like Go's leadingFraction, digits past ~19 are dropped.
|
||||
match f
|
||||
.checked_mul(10)
|
||||
.and_then(|f| f.checked_add(u64::from(bytes[i] - b'0')))
|
||||
.filter(|f| *f <= MAX)
|
||||
{
|
||||
Some(next) => {
|
||||
f = next;
|
||||
scale *= 10.0;
|
||||
}
|
||||
None => overflow = true,
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
post = i != 0;
|
||||
bytes = &bytes[i..];
|
||||
}
|
||||
if !pre && !post {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
// Consume the unit: everything up to the next digit or '.'.
|
||||
let unit_len = bytes
|
||||
.iter()
|
||||
.position(|c| *c == b'.' || c.is_ascii_digit())
|
||||
.unwrap_or(bytes.len());
|
||||
if unit_len == 0 {
|
||||
return Err(format!("time: missing unit in duration {:?}", orig));
|
||||
}
|
||||
// The boundary is an ASCII byte or the end, so it is a char boundary.
|
||||
let unit = std::str::from_utf8(&bytes[..unit_len]).map_err(|_| invalid())?;
|
||||
bytes = &bytes[unit_len..];
|
||||
let unit_nanos: u64 = match unit {
|
||||
"ns" => 1,
|
||||
"us" | "\u{00b5}s" | "\u{03bc}s" => 1_000,
|
||||
"ms" => 1_000_000,
|
||||
"s" => 1_000_000_000,
|
||||
"m" => 60 * 1_000_000_000,
|
||||
"h" => 3600 * 1_000_000_000,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"time: unknown unit {:?} in duration {:?}",
|
||||
unit, orig
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if v > MAX / unit_nanos {
|
||||
return Err(invalid());
|
||||
}
|
||||
v *= unit_nanos;
|
||||
if f > 0 {
|
||||
// Go's float math, so `1.5h` rounds the same way on both sides.
|
||||
v += (f as f64 * (unit_nanos as f64 / scale)) as u64;
|
||||
if v > MAX {
|
||||
return Err(invalid());
|
||||
}
|
||||
}
|
||||
total = total
|
||||
.checked_add(v)
|
||||
.filter(|t| *t <= MAX)
|
||||
.ok_or_else(invalid)?;
|
||||
}
|
||||
if total > MAX - 1 {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(std::time::Duration::from_nanos(total))
|
||||
}
|
||||
|
||||
/// Byte-size suffixes of Go's `util.ParseBytes`, lower-cased: SI (`kb`, `k`)
|
||||
/// and IEC (`kib`, `ki`) forms, `b`, and no suffix.
|
||||
fn byte_unit_multiplier(unit: &str) -> Option<u64> {
|
||||
const K: u64 = 1_000;
|
||||
const KI: u64 = 1 << 10;
|
||||
Some(match unit {
|
||||
"" | "b" => 1,
|
||||
"kb" | "k" => K,
|
||||
"kib" | "ki" => KI,
|
||||
"mb" | "m" => K * K,
|
||||
"mib" | "mi" => KI * KI,
|
||||
"gb" | "g" => K * K * K,
|
||||
"gib" | "gi" => KI * KI * KI,
|
||||
"tb" | "t" => K * K * K * K,
|
||||
"tib" | "ti" => KI * KI * KI * KI,
|
||||
"pb" | "p" => K * K * K * K * K,
|
||||
"pib" | "pi" => KI * KI * KI * KI * KI,
|
||||
"eb" | "e" => K * K * K * K * K * K,
|
||||
"eib" | "ei" => KI * KI * KI * KI * KI * KI,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse a human-readable byte count with Go's `util.ParseBytes` grammar:
|
||||
/// decimal number, optional whitespace, then a [`byte_unit_multiplier`]
|
||||
/// suffix, case-insensitive. `10GiB` → 10737418240, `1.5TB` → 1500000000000.
|
||||
///
|
||||
/// Thousands commas parse as in Go but never arrive from `-minFreeSpace`,
|
||||
/// which is split on commas into per-directory entries first.
|
||||
fn parse_bytes(s: &str) -> Result<u64, String> {
|
||||
let digits_end = s
|
||||
.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == ','))
|
||||
.unwrap_or(s.len());
|
||||
let num = s[..digits_end].replace(',', "");
|
||||
let value: f64 = num
|
||||
.parse()
|
||||
.map_err(|e| format!("invalid byte size {:?}: {}", s, e))?;
|
||||
let unit = s[digits_end..].trim().to_lowercase();
|
||||
let multiplier =
|
||||
byte_unit_multiplier(&unit).ok_or_else(|| format!("unhandled size name: {}", unit))?;
|
||||
let bytes = value * multiplier as f64;
|
||||
if bytes >= u64::MAX as f64 {
|
||||
return Err(format!("too large: {}", s));
|
||||
}
|
||||
Ok(bytes as u64)
|
||||
}
|
||||
|
||||
/// Parse one `-minFreeSpace` entry like Go's `util.ParseMinFreeSpace()`: a
|
||||
/// plain number is a percentage in `0..=100`, anything else a byte size
|
||||
/// above 100 bytes. `150` errors rather than reading as bytes.
|
||||
fn parse_min_free_space(s: &str) -> Result<MinFreeSpace, String> {
|
||||
/// Parse a duration string like "60s", "5m", "1h" into a std::time::Duration.
|
||||
fn parse_duration(s: &str) -> std::time::Duration {
|
||||
let s = s.trim();
|
||||
if let Ok(percent) = s.parse::<f64>() {
|
||||
// Go's range check lets NaN through; rejecting it is the one
|
||||
// intentional difference.
|
||||
if !(0.0..=100.0).contains(&percent) {
|
||||
return Err(format!("minFreeSpace is invalid: {:?}", s));
|
||||
}
|
||||
return Ok(MinFreeSpace::Percent(percent));
|
||||
if s.is_empty() {
|
||||
return std::time::Duration::from_secs(60);
|
||||
}
|
||||
match parse_bytes(s) {
|
||||
Ok(bytes) if bytes > 100 => Ok(MinFreeSpace::Bytes(bytes)),
|
||||
_ => Err(format!("minFreeSpace is invalid: {:?}", s)),
|
||||
if let Some(secs) = s.strip_suffix('s')
|
||||
&& let Ok(v) = secs.parse::<u64>()
|
||||
{
|
||||
return std::time::Duration::from_secs(v);
|
||||
}
|
||||
if let Some(mins) = s.strip_suffix('m')
|
||||
&& let Ok(v) = mins.parse::<u64>()
|
||||
&& let Some(seconds) = v.checked_mul(60)
|
||||
{
|
||||
return std::time::Duration::from_secs(seconds);
|
||||
}
|
||||
if let Some(hours) = s.strip_suffix('h')
|
||||
&& let Ok(v) = hours.parse::<u64>()
|
||||
&& let Some(seconds) = v.checked_mul(3600)
|
||||
{
|
||||
return std::time::Duration::from_secs(seconds);
|
||||
}
|
||||
// Fallback: try parsing as raw seconds
|
||||
if let Ok(v) = s.parse::<u64>() {
|
||||
return std::time::Duration::from_secs(v);
|
||||
}
|
||||
std::time::Duration::from_secs(60)
|
||||
}
|
||||
|
||||
/// Parse minFreeSpace / minFreeSpacePercent like Go's
|
||||
/// `util.MustParseMinFreeSpace()`: `--minFreeSpace` wins when set, and any
|
||||
/// invalid comma-separated entry fails the whole list.
|
||||
fn parse_min_free_spaces(
|
||||
min_free_space: &str,
|
||||
min_free_space_percent: &str,
|
||||
) -> Result<Vec<MinFreeSpace>, String> {
|
||||
/// Parse minFreeSpace / minFreeSpacePercent into MinFreeSpace values.
|
||||
/// Mirrors Go's `util.MustParseMinFreeSpace()`.
|
||||
fn parse_min_free_spaces(min_free_space: &str, min_free_space_percent: &str) -> Vec<MinFreeSpace> {
|
||||
// If --minFreeSpace is provided, use it (takes precedence).
|
||||
let source = if !min_free_space.is_empty() {
|
||||
min_free_space
|
||||
} else {
|
||||
min_free_space_percent
|
||||
};
|
||||
source.split(',').map(parse_min_free_space).collect()
|
||||
|
||||
source
|
||||
.split(',')
|
||||
.map(|s| {
|
||||
let s = s.trim();
|
||||
// Try parsing as a percentage (value <= 100)
|
||||
if let Ok(v) = s.parse::<f64>() {
|
||||
if v <= 100.0 {
|
||||
return MinFreeSpace::Percent(v);
|
||||
}
|
||||
// Treat as bytes if > 100
|
||||
return MinFreeSpace::Bytes(v as u64);
|
||||
}
|
||||
// Try parsing human-readable bytes: e.g. "10GiB", "500MiB", "1TiB"
|
||||
let s_upper = s.to_uppercase();
|
||||
if let Some(rest) = s_upper.strip_suffix("TIB")
|
||||
&& let Ok(v) = rest.trim().parse::<f64>()
|
||||
{
|
||||
return MinFreeSpace::Bytes((v * 1024.0 * 1024.0 * 1024.0 * 1024.0) as u64);
|
||||
}
|
||||
if let Some(rest) = s_upper.strip_suffix("GIB")
|
||||
&& let Ok(v) = rest.trim().parse::<f64>()
|
||||
{
|
||||
return MinFreeSpace::Bytes((v * 1024.0 * 1024.0 * 1024.0) as u64);
|
||||
}
|
||||
if let Some(rest) = s_upper.strip_suffix("MIB")
|
||||
&& let Ok(v) = rest.trim().parse::<f64>()
|
||||
{
|
||||
return MinFreeSpace::Bytes((v * 1024.0 * 1024.0) as u64);
|
||||
}
|
||||
if let Some(rest) = s_upper.strip_suffix("KIB")
|
||||
&& let Ok(v) = rest.trim().parse::<f64>()
|
||||
{
|
||||
return MinFreeSpace::Bytes((v * 1024.0) as u64);
|
||||
}
|
||||
if let Some(rest) = s_upper.strip_suffix("TB")
|
||||
&& let Ok(v) = rest.trim().parse::<f64>()
|
||||
{
|
||||
return MinFreeSpace::Bytes((v * 1_000_000_000_000.0) as u64);
|
||||
}
|
||||
if let Some(rest) = s_upper.strip_suffix("GB")
|
||||
&& let Ok(v) = rest.trim().parse::<f64>()
|
||||
{
|
||||
return MinFreeSpace::Bytes((v * 1_000_000_000.0) as u64);
|
||||
}
|
||||
if let Some(rest) = s_upper.strip_suffix("MB")
|
||||
&& let Ok(v) = rest.trim().parse::<f64>()
|
||||
{
|
||||
return MinFreeSpace::Bytes((v * 1_000_000.0) as u64);
|
||||
}
|
||||
// Default: 1%
|
||||
MinFreeSpace::Percent(1.0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Parse comma-separated tag groups like "fast:ssd,archive" into per-folder tag vectors.
|
||||
@@ -782,9 +657,7 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
|
||||
|
||||
// Parse min free spaces
|
||||
let mut min_free_spaces =
|
||||
parse_min_free_spaces(&cli.min_free_space, &cli.min_free_space_percent).unwrap_or_else(
|
||||
|e| panic!("The value specified in -minFreeSpace not a valid value: {e}"),
|
||||
);
|
||||
parse_min_free_spaces(&cli.min_free_space, &cli.min_free_space_percent);
|
||||
if min_free_spaces.len() == 1 && folder_count > 1 {
|
||||
let v = min_free_spaces[0].clone();
|
||||
min_free_spaces.resize(folder_count, v);
|
||||
@@ -899,6 +772,10 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
|
||||
.collect();
|
||||
white_list.extend(sec.guard_white_list.iter().cloned());
|
||||
|
||||
// Parse durations
|
||||
let inflight_upload_data_timeout = parse_duration(&cli.inflight_upload_data_timeout);
|
||||
let inflight_download_data_timeout = parse_duration(&cli.inflight_download_data_timeout);
|
||||
|
||||
VolumeServerConfig {
|
||||
port: cli.port,
|
||||
grpc_port,
|
||||
@@ -930,8 +807,8 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
|
||||
file_size_limit_bytes: cli.file_size_limit_mb as i64 * 1024 * 1024,
|
||||
concurrent_upload_limit: cli.concurrent_upload_limit_mb as i64 * 1024 * 1024,
|
||||
concurrent_download_limit: cli.concurrent_download_limit_mb as i64 * 1024 * 1024,
|
||||
inflight_upload_data_timeout: cli.inflight_upload_data_timeout,
|
||||
inflight_download_data_timeout: cli.inflight_download_data_timeout,
|
||||
inflight_upload_data_timeout,
|
||||
inflight_download_data_timeout,
|
||||
has_slow_read: cli.has_slow_read,
|
||||
read_buffer_size_mb: cli.read_buffer_size_mb,
|
||||
ldb_timeout: cli.ldb_timeout,
|
||||
@@ -1383,224 +1260,25 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_go_duration_accepts_go_grammar() {
|
||||
use std::time::Duration;
|
||||
let cases = [
|
||||
("60s", Duration::from_secs(60)),
|
||||
("5m", Duration::from_secs(300)),
|
||||
("1h", Duration::from_secs(3600)),
|
||||
("1.5h", Duration::from_secs(5400)),
|
||||
("2h45m", Duration::from_secs(2 * 3600 + 45 * 60)),
|
||||
("300ms", Duration::from_millis(300)),
|
||||
("1.5s", Duration::from_millis(1500)),
|
||||
("250us", Duration::from_micros(250)),
|
||||
("250\u{00b5}s", Duration::from_micros(250)),
|
||||
("250\u{03bc}s", Duration::from_micros(250)),
|
||||
("7ns", Duration::from_nanos(7)),
|
||||
(".5s", Duration::from_millis(500)),
|
||||
("5.s", Duration::from_secs(5)),
|
||||
("+10s", Duration::from_secs(10)),
|
||||
("0", Duration::ZERO),
|
||||
("0s", Duration::ZERO),
|
||||
// Go: fraction digits past the 19th are ignored, not an error.
|
||||
("1.00000000000000000001s", Duration::from_secs(1)),
|
||||
];
|
||||
for (input, expected) in cases {
|
||||
assert_eq!(parse_go_duration(input), Ok(expected), "input={:?}", input);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_go_duration_rejects_what_go_rejects() {
|
||||
// Each of these makes Go's flag.Duration fail flag parsing; the old
|
||||
// Rust parser turned them all into the 60 s default.
|
||||
let rejected = [
|
||||
"30", // bare number other than 0
|
||||
"30sec", // unknown unit
|
||||
"abc", // no number at all
|
||||
"", // empty
|
||||
"1h ", // trailing space is not a unit
|
||||
"s", // unit without number
|
||||
".s", // dot without digits
|
||||
"1.5", // fraction without unit
|
||||
"1h-30m", // sign is only allowed at the front
|
||||
"-", // sign alone
|
||||
"5124095576030432h", // overflows int64 nanoseconds
|
||||
"307445734561825861m", // overflows int64 nanoseconds
|
||||
"9223372036854775808ns", // 1<<63, one past int64
|
||||
];
|
||||
for input in rejected {
|
||||
let result = parse_go_duration(input);
|
||||
assert!(result.is_err(), "input={:?} parsed as {:?}", input, result);
|
||||
let message = result.unwrap_err();
|
||||
assert!(
|
||||
message.contains(&format!("{:?}", input)) || input.is_empty(),
|
||||
"error for {:?} does not name the value: {}",
|
||||
input,
|
||||
message
|
||||
);
|
||||
}
|
||||
// Largest value Go accepts: 1<<63 - 1 nanoseconds.
|
||||
fn test_parse_duration() {
|
||||
assert_eq!(parse_duration("60s"), std::time::Duration::from_secs(60));
|
||||
assert_eq!(parse_duration("5m"), std::time::Duration::from_secs(300));
|
||||
assert_eq!(parse_duration("1h"), std::time::Duration::from_secs(3600));
|
||||
assert_eq!(parse_duration("30"), std::time::Duration::from_secs(30));
|
||||
assert_eq!(parse_duration(""), std::time::Duration::from_secs(60));
|
||||
assert_eq!(
|
||||
parse_go_duration("9223372036854775807ns"),
|
||||
Ok(std::time::Duration::from_nanos(i64::MAX as u64))
|
||||
);
|
||||
// Go accepts negatives; std::time::Duration cannot, so it errors.
|
||||
let negative = parse_go_duration("-1s").unwrap_err();
|
||||
assert!(negative.contains("negative"), "{}", negative);
|
||||
}
|
||||
|
||||
/// Clap refuses the flag so the process exits with a usage error, exactly
|
||||
/// where Go's flag package does.
|
||||
#[test]
|
||||
fn test_cli_rejects_invalid_duration_flags() {
|
||||
for value in ["30sec", "abc", "30"] {
|
||||
let result = Cli::try_parse_from(["bin", "--inflightUploadDataTimeout", value]);
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"--inflightUploadDataTimeout={} was accepted as {:?}",
|
||||
value,
|
||||
result.map(|cli| cli.inflight_upload_data_timeout)
|
||||
);
|
||||
let err = Cli::try_parse_from(["bin", "--inflightDownloadDataTimeout", value])
|
||||
.err()
|
||||
.unwrap_or_else(|| panic!("--inflightDownloadDataTimeout={} was accepted", value));
|
||||
assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
|
||||
assert!(err.to_string().contains(value), "{}", err);
|
||||
}
|
||||
let cli = Cli::parse_from(["bin", "--inflightUploadDataTimeout", "1.5h"]);
|
||||
assert_eq!(
|
||||
cli.inflight_upload_data_timeout,
|
||||
std::time::Duration::from_secs(5400)
|
||||
);
|
||||
// The default still parses through the same grammar.
|
||||
let cli = Cli::parse_from(["bin"]);
|
||||
assert_eq!(
|
||||
cli.inflight_upload_data_timeout,
|
||||
parse_duration("307445734561825861m"),
|
||||
std::time::Duration::from_secs(60)
|
||||
);
|
||||
assert_eq!(
|
||||
cli.inflight_download_data_timeout,
|
||||
parse_duration("5124095576030432h"),
|
||||
std::time::Duration::from_secs(60)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_bytes_matches_go_parse_bytes() {
|
||||
// Expected values are what Go's util.ParseBytes returns (weed/util/bytes_test.go).
|
||||
let cases: [(&str, u64); 14] = [
|
||||
("42", 42),
|
||||
("42MB", 42_000_000),
|
||||
("42 MB", 42_000_000),
|
||||
("42 mib", 44_040_192),
|
||||
("42M", 42_000_000),
|
||||
("100Ki", 100 * 1024),
|
||||
("10GiB", 10 * 1024 * 1024 * 1024),
|
||||
("10gib", 10 * 1024 * 1024 * 1024),
|
||||
("10GB", 10_000_000_000),
|
||||
("1.5TB", 1_500_000_000_000),
|
||||
// Go's ParseBytes accepts thousands commas; the -minFreeSpace flag
|
||||
// never delivers one (see test_min_free_space_flag_commas_are_list_separators).
|
||||
("1,024MB", 1_024_000_000),
|
||||
("1,024", 1024),
|
||||
("1PiB", 1 << 50),
|
||||
("1eb", 1_000_000_000_000_000_000),
|
||||
];
|
||||
for (input, expected) in cases {
|
||||
assert_eq!(parse_bytes(input), Ok(expected), "input={:?}", input);
|
||||
}
|
||||
for input in [
|
||||
"10GiBx",
|
||||
"GiB",
|
||||
"",
|
||||
"-5GB",
|
||||
"1.2.3GB",
|
||||
"10 Gi B",
|
||||
"99999999999999999999EB",
|
||||
] {
|
||||
assert!(
|
||||
parse_bytes(input).is_err(),
|
||||
"input={:?} was accepted",
|
||||
input
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_percent(result: Result<MinFreeSpace, String>, expected: f64, input: &str) {
|
||||
match result {
|
||||
Ok(MinFreeSpace::Percent(v)) => {
|
||||
assert!(
|
||||
(v - expected).abs() < f64::EPSILON,
|
||||
"input={:?}: {}",
|
||||
input,
|
||||
v
|
||||
)
|
||||
}
|
||||
other => panic!(
|
||||
"input={:?}: expected Percent({}), got {:?}",
|
||||
input, expected, other
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_bytes(result: Result<MinFreeSpace, String>, expected: u64, input: &str) {
|
||||
match result {
|
||||
Ok(MinFreeSpace::Bytes(v)) => assert_eq!(v, expected, "input={:?}", input),
|
||||
other => panic!(
|
||||
"input={:?}: expected Bytes({}), got {:?}",
|
||||
input, expected, other
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_min_free_space_matches_go() {
|
||||
// Fixtures from weed/util/minfreespace_test.go plus the byte-unit table.
|
||||
expect_percent(parse_min_free_space("42"), 42.0, "42");
|
||||
expect_percent(parse_min_free_space(" 42 "), 42.0, " 42 ");
|
||||
expect_percent(parse_min_free_space("50"), 50.0, "50");
|
||||
expect_percent(parse_min_free_space("100"), 100.0, "100");
|
||||
expect_percent(parse_min_free_space("0"), 0.0, "0");
|
||||
expect_percent(parse_min_free_space("2.5"), 2.5, "2.5");
|
||||
expect_bytes(parse_min_free_space("100Ki"), 100 * 1024, "100Ki");
|
||||
expect_bytes(parse_min_free_space("100GiB"), 100 << 30, "100GiB");
|
||||
expect_bytes(parse_min_free_space("42M"), 42_000_000, "42M");
|
||||
expect_bytes(parse_min_free_space(" 42M "), 42_000_000, " 42M ");
|
||||
expect_bytes(parse_min_free_space("10GiB"), 10 << 30, "10GiB");
|
||||
expect_bytes(parse_min_free_space("10gib"), 10 << 30, "10gib");
|
||||
expect_bytes(parse_min_free_space("1.5TB"), 1_500_000_000_000, "1.5TB");
|
||||
// Comma inputs never arrive whole from the flag; see
|
||||
// test_min_free_space_flag_commas_are_list_separators.
|
||||
expect_bytes(parse_min_free_space("1,024MB"), 1_024_000_000, "1,024MB");
|
||||
expect_bytes(parse_min_free_space("1,000"), 1000, "1,000");
|
||||
|
||||
// Go: percent outside 0..=100, or a byte size of at most 100 bytes.
|
||||
for input in [
|
||||
"150", "101", "-1", "1e3", "inf", "nan", "100B", "50B", "0B", "10GiBx", "", "abc",
|
||||
"10 Gi B",
|
||||
] {
|
||||
let result = parse_min_free_space(input);
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"input={:?} was accepted as {:?}",
|
||||
input,
|
||||
result
|
||||
);
|
||||
assert!(
|
||||
result
|
||||
.as_ref()
|
||||
.unwrap_err()
|
||||
.contains(&format!("{:?}", input.trim())),
|
||||
"error for {:?} does not name the value: {:?}",
|
||||
input,
|
||||
result
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_min_free_spaces_percent() {
|
||||
let result = parse_min_free_spaces("", "1").unwrap();
|
||||
let result = parse_min_free_spaces("", "1");
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
MinFreeSpace::Percent(v) => assert!((v - 1.0).abs() < f64::EPSILON),
|
||||
@@ -1610,7 +1288,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_parse_min_free_spaces_bytes() {
|
||||
let result = parse_min_free_spaces("10GiB", "").unwrap();
|
||||
let result = parse_min_free_spaces("10GiB", "");
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
MinFreeSpace::Bytes(v) => assert_eq!(*v, 10 * 1024 * 1024 * 1024),
|
||||
@@ -1618,87 +1296,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_min_free_spaces_list_and_precedence() {
|
||||
// --minFreeSpace wins over --minFreeSpacePercent, as in Go's EmptyTo().
|
||||
let result = parse_min_free_spaces("5, 10GiB", "1").unwrap();
|
||||
assert_eq!(result.len(), 2);
|
||||
assert!(matches!(result[0], MinFreeSpace::Percent(v) if v == 5.0));
|
||||
assert!(matches!(result[1], MinFreeSpace::Bytes(v) if v == 10 << 30));
|
||||
// One bad entry fails the whole list and names that entry.
|
||||
let err = parse_min_free_spaces("5,10GiBx", "1").unwrap_err();
|
||||
assert!(err.contains("\"10GiBx\""), "{}", err);
|
||||
// Both flags empty: Go fatals (ParseMinFreeSpace("") fails) rather than
|
||||
// assuming 1%.
|
||||
assert!(parse_min_free_spaces("", "").is_err());
|
||||
}
|
||||
|
||||
/// A comma in `-minFreeSpace` separates per-directory entries, as in Go's
|
||||
/// `MustParseMinFreeSpace`: `1,024MB` is `1` (percent) and `024MB`, and
|
||||
/// one `-dir` fails the count check.
|
||||
#[test]
|
||||
fn test_min_free_space_flag_commas_are_list_separators() {
|
||||
let result = parse_min_free_spaces("1,024MB", "").unwrap();
|
||||
assert_eq!(result.len(), 2, "{result:?}");
|
||||
assert!(
|
||||
matches!(result[0], MinFreeSpace::Percent(v) if v == 1.0),
|
||||
"{result:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(result[1], MinFreeSpace::Bytes(v) if v == 24_000_000),
|
||||
"{result:?}"
|
||||
);
|
||||
|
||||
let _guard = process_state_lock();
|
||||
let cli = Cli::parse_from(["bin", "--dir", "/tmp/a", "--minFreeSpace", "1,024MB"]);
|
||||
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
resolve_config_with_env(cli, &|_| None).min_free_spaces
|
||||
}));
|
||||
assert!(
|
||||
outcome.is_err(),
|
||||
"one -dir with two minFreeSpace entries must abort"
|
||||
);
|
||||
}
|
||||
|
||||
/// Negative control at the startup layer: resolving the config with an
|
||||
/// invalid --minFreeSpace must abort, as Go's MustParseMinFreeSpace does.
|
||||
#[test]
|
||||
fn test_resolve_config_rejects_invalid_min_free_space() {
|
||||
// The security-config search reads the working directory.
|
||||
let _guard = process_state_lock();
|
||||
for (flag, value) in [
|
||||
("--minFreeSpace", "10GiBx"),
|
||||
("--minFreeSpace", "150"),
|
||||
("--minFreeSpace", "50B"),
|
||||
("--minFreeSpacePercent", "150"),
|
||||
("--minFreeSpacePercent", "abc"),
|
||||
] {
|
||||
let cli = Cli::parse_from(["bin", flag, value]);
|
||||
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
resolve_config_with_env(cli, &|_| None).min_free_spaces
|
||||
}));
|
||||
let payload = match outcome {
|
||||
Ok(spaces) => panic!("{}={} was accepted as {:?}", flag, value, spaces),
|
||||
Err(payload) => payload,
|
||||
};
|
||||
let message = payload
|
||||
.downcast_ref::<String>()
|
||||
.cloned()
|
||||
.or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
|
||||
.unwrap_or_default();
|
||||
assert!(
|
||||
message.contains("-minFreeSpace") && message.contains(value),
|
||||
"{}={}: unexpected panic message {:?}",
|
||||
flag,
|
||||
value,
|
||||
message
|
||||
);
|
||||
}
|
||||
let cfg =
|
||||
resolve_config_with_env(Cli::parse_from(["bin", "--minFreeSpace", "100"]), &|_| None);
|
||||
assert!(matches!(cfg.min_free_spaces[0], MinFreeSpace::Percent(v) if v == 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_volume_tags_single() {
|
||||
let tags = parse_volume_tags("fast:ssd", 3);
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::config::{BehaviorVersion, Credentials, Region};
|
||||
use aws_sdk_s3::error::{DisplayErrorContext, SdkError};
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
|
||||
use super::{RemoteEntry, RemoteStorageClient, RemoteStorageError};
|
||||
@@ -26,23 +25,6 @@ impl S3RemoteStorageClient {
|
||||
endpoint: &str,
|
||||
force_path_style: bool,
|
||||
) -> Self {
|
||||
let client = Client::from_conf(
|
||||
Self::config_builder(access_key, secret_key, region, endpoint, force_path_style)
|
||||
.build(),
|
||||
);
|
||||
|
||||
S3RemoteStorageClient { client, conf }
|
||||
}
|
||||
|
||||
/// Build the SDK config for the given credentials and endpoint. Split out so
|
||||
/// tests can attach a canned HTTP client before building the [`Client`].
|
||||
fn config_builder(
|
||||
access_key: &str,
|
||||
secret_key: &str,
|
||||
region: &str,
|
||||
endpoint: &str,
|
||||
force_path_style: bool,
|
||||
) -> aws_sdk_s3::config::Builder {
|
||||
let region = if region.is_empty() {
|
||||
"us-east-1"
|
||||
} else {
|
||||
@@ -67,7 +49,9 @@ impl S3RemoteStorageClient {
|
||||
s3_config = s3_config.endpoint_url(endpoint);
|
||||
}
|
||||
|
||||
s3_config
|
||||
let client = Client::from_conf(s3_config.build());
|
||||
|
||||
S3RemoteStorageClient { client, conf }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,14 +75,13 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
req = req.range(format!("bytes={}-", offset));
|
||||
}
|
||||
|
||||
let resp = req.send().await.map_err(|e| match e {
|
||||
// Go compares `aerr.Code()` to NoSuchKey on GET
|
||||
// (s3_storage_client.go:436): a bare 404 maps to "NotFound"
|
||||
// and stays a generic error, as it does here.
|
||||
SdkError::ServiceError(ref se) if se.err().is_no_such_key() => {
|
||||
let resp = req.send().await.map_err(|e| {
|
||||
let msg = format!("{}", e);
|
||||
if msg.contains("NoSuchKey") || msg.contains("404") {
|
||||
RemoteStorageError::ObjectNotFound(format!("{}/{}", loc.bucket, key))
|
||||
} else {
|
||||
RemoteStorageError::Other(format!("s3 get object: {}", e))
|
||||
}
|
||||
e => RemoteStorageError::Other(format!("s3 get object: {}", DisplayErrorContext(&e))),
|
||||
})?;
|
||||
|
||||
let data = resp
|
||||
@@ -125,9 +108,7 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
.body(ByteStream::from(data.to_vec()))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
RemoteStorageError::Other(format!("s3 put object: {}", DisplayErrorContext(&e)))
|
||||
})?;
|
||||
.map_err(|e| RemoteStorageError::Other(format!("s3 put object: {}", e)))?;
|
||||
|
||||
Ok(RemoteEntry {
|
||||
size: data.len() as i64,
|
||||
@@ -153,18 +134,13 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
// Go checks only the raw HTTP status on HEAD
|
||||
// (s3_storage_client.go:373): a HEAD response carries no
|
||||
// error body, so a 404 is not-found whatever code the SDK
|
||||
// assigns, and a non-404 is not.
|
||||
SdkError::ServiceError(ref se) if se.raw().status().as_u16() == 404 => {
|
||||
.map_err(|e| {
|
||||
let msg = format!("{}", e);
|
||||
if msg.contains("404") || msg.contains("NotFound") {
|
||||
RemoteStorageError::ObjectNotFound(format!("{}/{}", loc.bucket, key))
|
||||
} else {
|
||||
RemoteStorageError::Other(format!("s3 head object: {}", e))
|
||||
}
|
||||
e => RemoteStorageError::Other(format!(
|
||||
"s3 head object: {}",
|
||||
DisplayErrorContext(&e)
|
||||
)),
|
||||
})?;
|
||||
|
||||
Ok(RemoteEntry {
|
||||
@@ -184,17 +160,18 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
RemoteStorageError::Other(format!("s3 delete object: {}", DisplayErrorContext(&e)))
|
||||
})?;
|
||||
.map_err(|e| RemoteStorageError::Other(format!("s3 delete object: {}", e)))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_buckets(&self) -> Result<Vec<String>, RemoteStorageError> {
|
||||
let resp = self.client.list_buckets().send().await.map_err(|e| {
|
||||
RemoteStorageError::Other(format!("s3 list buckets: {}", DisplayErrorContext(&e)))
|
||||
})?;
|
||||
let resp = self
|
||||
.client
|
||||
.list_buckets()
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| RemoteStorageError::Other(format!("s3 list buckets: {}", e)))?;
|
||||
|
||||
Ok(resp
|
||||
.buckets()
|
||||
@@ -207,178 +184,3 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
&self.conf
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use aws_sdk_s3::config::http::{HttpRequest, HttpResponse};
|
||||
use aws_sdk_s3::config::retry::RetryConfig;
|
||||
use aws_sdk_s3::config::{HttpClient, RuntimeComponents};
|
||||
use aws_sdk_s3::primitives::SdkBody;
|
||||
use aws_smithy_runtime_api::client::http::{
|
||||
HttpConnector, HttpConnectorFuture, HttpConnectorSettings, SharedHttpConnector,
|
||||
};
|
||||
use aws_smithy_runtime_api::http::StatusCode;
|
||||
|
||||
/// An SDK HTTP client that answers every request with one canned response,
|
||||
/// so the error-mapping paths can be exercised without a network or a
|
||||
/// running S3 server.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct CannedResponse {
|
||||
pub(crate) status: u16,
|
||||
pub(crate) body: &'static str,
|
||||
}
|
||||
|
||||
impl HttpConnector for CannedResponse {
|
||||
fn call(&self, _request: HttpRequest) -> HttpConnectorFuture {
|
||||
let status = StatusCode::try_from(self.status).expect("valid HTTP status");
|
||||
HttpConnectorFuture::ready(Ok(HttpResponse::new(status, SdkBody::from(self.body))))
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpClient for CannedResponse {
|
||||
fn http_connector(
|
||||
&self,
|
||||
_settings: &HttpConnectorSettings,
|
||||
_components: &RuntimeComponents,
|
||||
) -> SharedHttpConnector {
|
||||
SharedHttpConnector::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn client_with(status: u16, body: &'static str) -> S3RemoteStorageClient {
|
||||
let config = S3RemoteStorageClient::config_builder(
|
||||
"AKIATEST",
|
||||
"secret",
|
||||
"us-east-1",
|
||||
"http://127.0.0.1:1",
|
||||
true,
|
||||
)
|
||||
.http_client(CannedResponse { status, body })
|
||||
.retry_config(RetryConfig::disabled())
|
||||
.build();
|
||||
S3RemoteStorageClient {
|
||||
client: Client::from_conf(config),
|
||||
conf: RemoteConf::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn location() -> RemoteStorageLocation {
|
||||
RemoteStorageLocation {
|
||||
name: "remote".to_string(),
|
||||
bucket: "bucket".to_string(),
|
||||
path: "/dir/missing".to_string(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const NO_SUCH_KEY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Error><Code>NoSuchKey</Code><Message>The specified key does not exist.</Message><Key>dir/missing</Key></Error>"#;
|
||||
|
||||
const NOT_FOUND_BODY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Error><Code>NotFound</Code><Message>Not Found</Message></Error>"#;
|
||||
|
||||
const ACCESS_DENIED: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Error><Code>AccessDenied</Code><Message>Access Denied</Message></Error>"#;
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_no_such_key_is_object_not_found() {
|
||||
let err = client_with(404, NO_SUCH_KEY)
|
||||
.read_file(&location(), 0, 0)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, RemoteStorageError::ObjectNotFound(path) if path == "bucket/dir/missing"),
|
||||
"expected ObjectNotFound, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_bare_404_is_not_object_not_found() {
|
||||
// Go compares codes, not statuses, on GET: a body-less 404 stays generic.
|
||||
let err = client_with(404, "")
|
||||
.read_file(&location(), 0, 0)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, RemoteStorageError::Other(_)),
|
||||
"expected Other, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn head_404_is_object_not_found() {
|
||||
let err = client_with(404, "")
|
||||
.stat_file(&location())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, RemoteStorageError::ObjectNotFound(path) if path == "bucket/dir/missing"),
|
||||
"expected ObjectNotFound, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn head_404_with_foreign_error_body_is_object_not_found() {
|
||||
// The raw status check makes a 404 not-found whatever body it carries.
|
||||
let err = client_with(404, NO_SUCH_KEY)
|
||||
.stat_file(&location())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, RemoteStorageError::ObjectNotFound(_)),
|
||||
"expected ObjectNotFound, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn head_not_found_code_on_a_non_404_status_is_not_object_not_found() {
|
||||
// A NotFound body on a non-404 status stays an error, as in Go.
|
||||
let err = client_with(400, NOT_FOUND_BODY)
|
||||
.stat_file(&location())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, RemoteStorageError::Other(msg) if msg.contains("NotFound")),
|
||||
"expected Other naming the code, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_access_denied_keeps_service_error_code() {
|
||||
let err = client_with(403, ACCESS_DENIED)
|
||||
.read_file(&location(), 0, 0)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let msg = err.to_string();
|
||||
assert!(
|
||||
matches!(err, RemoteStorageError::Other(_)),
|
||||
"expected Other, got {err:?}"
|
||||
);
|
||||
assert!(
|
||||
msg.contains("AccessDenied"),
|
||||
"message should carry the S3 error code, got: {msg}"
|
||||
);
|
||||
assert!(
|
||||
!msg.ends_with("service error"),
|
||||
"message should not be the bare SdkError Display, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn head_access_denied_keeps_service_error_code() {
|
||||
let err = client_with(403, ACCESS_DENIED)
|
||||
.stat_file(&location())
|
||||
.await
|
||||
.unwrap_err();
|
||||
let msg = err.to_string();
|
||||
assert!(
|
||||
matches!(err, RemoteStorageError::Other(_)),
|
||||
"expected Other, got {err:?}"
|
||||
);
|
||||
assert!(
|
||||
msg.contains("AccessDenied"),
|
||||
"message should carry the S3 error code, got: {msg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,7 @@ use std::future::Future;
|
||||
use std::sync::{Arc, OnceLock, RwLock};
|
||||
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::config::http::HttpResponse;
|
||||
use aws_sdk_s3::config::{BehaviorVersion, Credentials, Region};
|
||||
use aws_sdk_s3::error::{DisplayErrorContext, SdkError};
|
||||
use aws_sdk_s3::operation::get_object::GetObjectError;
|
||||
use aws_sdk_s3::operation::head_object::HeadObjectError;
|
||||
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -20,53 +16,6 @@ use tokio::sync::Semaphore;
|
||||
/// Concurrency limit for multipart upload/download (matches Go's s3manager).
|
||||
const CONCURRENCY: usize = 5;
|
||||
|
||||
/// A tier transfer failure. The variant is what callers match on; the
|
||||
/// message is the operator-facing text.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TierError {
|
||||
/// The remote object does not exist.
|
||||
#[error("{0}")]
|
||||
NotFound(String),
|
||||
/// An S3 request or a local file operation failed.
|
||||
#[error("{0}")]
|
||||
Io(String),
|
||||
/// The tier I/O runtime could not be built or dropped the task.
|
||||
#[error("{0}")]
|
||||
RuntimeUnavailable(String),
|
||||
/// The progress callback asked to stop.
|
||||
#[error("{0}")]
|
||||
Aborted(String),
|
||||
}
|
||||
|
||||
// Not-found rules as in remote_storage/s3.rs: HEAD by the raw 404 status,
|
||||
// GET by the NoSuchKey code only.
|
||||
fn head_object_error(key: &str, e: SdkError<HeadObjectError, HttpResponse>) -> TierError {
|
||||
let message = format!("failed to head object {}: {}", key, DisplayErrorContext(&e));
|
||||
match e {
|
||||
SdkError::ServiceError(ref se) if se.raw().status().as_u16() == 404 => {
|
||||
TierError::NotFound(message)
|
||||
}
|
||||
_ => TierError::Io(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_object_error(
|
||||
key: &str,
|
||||
range: &str,
|
||||
e: SdkError<GetObjectError, HttpResponse>,
|
||||
) -> TierError {
|
||||
let message = format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
);
|
||||
match e {
|
||||
SdkError::ServiceError(ref se) if se.err().is_no_such_key() => TierError::NotFound(message),
|
||||
_ => TierError::Io(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for an S3 tier backend.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct S3TierConfig {
|
||||
@@ -140,7 +89,7 @@ impl S3TierBackend {
|
||||
&self,
|
||||
file_path: &str,
|
||||
progress_fn: F,
|
||||
) -> Result<(String, u64), TierError>
|
||||
) -> Result<(String, u64), String>
|
||||
where
|
||||
F: FnMut(i64, f32) -> Result<(), String> + Send + Sync + 'static,
|
||||
{
|
||||
@@ -148,7 +97,7 @@ impl S3TierBackend {
|
||||
|
||||
let metadata = tokio::fs::metadata(file_path)
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to stat file {}: {}", file_path, e)))?;
|
||||
.map_err(|e| format!("failed to stat file {}: {}", file_path, e))?;
|
||||
let file_size = metadata.len();
|
||||
|
||||
// Calculate part size: start at 64MB, scale up for very large files (matches Go)
|
||||
@@ -170,16 +119,11 @@ impl S3TierBackend {
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!(
|
||||
"failed to create multipart upload: {}",
|
||||
DisplayErrorContext(&e)
|
||||
))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to create multipart upload: {}", e))?;
|
||||
|
||||
let upload_id = create_resp
|
||||
.upload_id()
|
||||
.ok_or_else(|| TierError::Io("no upload_id in multipart upload response".to_string()))?
|
||||
.ok_or_else(|| "no upload_id in multipart upload response".to_string())?
|
||||
.to_string();
|
||||
|
||||
// Build list of (part_number, offset, size) for all parts
|
||||
@@ -215,21 +159,19 @@ impl S3TierBackend {
|
||||
let _permit = sem
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("semaphore error: {}", e)))?;
|
||||
.map_err(|e| format!("semaphore error: {}", e))?;
|
||||
|
||||
// Read this part's data from the file at the correct offset
|
||||
let mut file = tokio::fs::File::open(&fp)
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to open file {}: {}", fp, e)))?;
|
||||
.map_err(|e| format!("failed to open file {}: {}", fp, e))?;
|
||||
file.seek(std::io::SeekFrom::Start(off))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to seek to offset {}: {}", off, e))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to seek to offset {}: {}", off, e))?;
|
||||
let mut buf = vec![0u8; size];
|
||||
file.read_exact(&mut buf).await.map_err(|e| {
|
||||
TierError::Io(format!("failed to read file at offset {}: {}", off, e))
|
||||
})?;
|
||||
file.read_exact(&mut buf)
|
||||
.await
|
||||
.map_err(|e| format!("failed to read file at offset {}: {}", off, e))?;
|
||||
|
||||
let upload_part_resp = client
|
||||
.upload_part()
|
||||
@@ -241,12 +183,7 @@ impl S3TierBackend {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!(
|
||||
"failed to upload part {} at offset {}: {}",
|
||||
pn,
|
||||
off,
|
||||
DisplayErrorContext(&e)
|
||||
))
|
||||
format!("failed to upload part {} at offset {}: {}", pn, off, e)
|
||||
})?;
|
||||
|
||||
let e_tag = upload_part_resp.e_tag().unwrap_or_default().to_string();
|
||||
@@ -265,9 +202,9 @@ impl S3TierBackend {
|
||||
};
|
||||
(guard.1)(uploaded as i64, pct)
|
||||
};
|
||||
progress_result.map_err(TierError::Aborted)?;
|
||||
progress_result?;
|
||||
|
||||
Ok::<_, TierError>(
|
||||
Ok::<_, String>(
|
||||
CompletedPart::builder()
|
||||
.e_tag(e_tag)
|
||||
.part_number(pn)
|
||||
@@ -282,7 +219,7 @@ impl S3TierBackend {
|
||||
for handle in handles {
|
||||
let part = handle
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("upload task panicked: {}", e)))??;
|
||||
.map_err(|e| format!("upload task panicked: {}", e))??;
|
||||
completed_parts.push(part);
|
||||
}
|
||||
|
||||
@@ -299,14 +236,9 @@ impl S3TierBackend {
|
||||
.multipart_upload(completed_upload)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!(
|
||||
"failed to complete multipart upload: {}",
|
||||
DisplayErrorContext(&e)
|
||||
))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to complete multipart upload: {}", e))?;
|
||||
|
||||
Ok::<(), TierError>(())
|
||||
Ok::<(), String>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
@@ -349,7 +281,7 @@ impl S3TierBackend {
|
||||
dest_path: &str,
|
||||
key: &str,
|
||||
progress_fn: F,
|
||||
) -> Result<u64, TierError>
|
||||
) -> Result<u64, String>
|
||||
where
|
||||
F: FnMut(i64, f32) -> Result<(), String> + Send + Sync + 'static,
|
||||
{
|
||||
@@ -361,7 +293,7 @@ impl S3TierBackend {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| head_object_error(key, e))?;
|
||||
.map_err(|e| format!("failed to head object {}: {}", key, e))?;
|
||||
|
||||
let file_size = head_resp.content_length().unwrap_or(0) as u64;
|
||||
|
||||
@@ -373,12 +305,10 @@ impl S3TierBackend {
|
||||
.truncate(true)
|
||||
.open(dest_path)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to open dest file {}: {}", dest_path, e))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to open dest file {}: {}", dest_path, e))?;
|
||||
file.set_len(file_size)
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to set file length: {}", e)))?;
|
||||
.map_err(|e| format!("failed to set file length: {}", e))?;
|
||||
}
|
||||
|
||||
let part_size: u64 = 64 * 1024 * 1024;
|
||||
@@ -414,7 +344,7 @@ impl S3TierBackend {
|
||||
let _permit = sem
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("semaphore error: {}", e)))?;
|
||||
.map_err(|e| format!("semaphore error: {}", e))?;
|
||||
|
||||
let end = off + size - 1;
|
||||
let range = format!("bytes={}-{}", off, end);
|
||||
@@ -426,13 +356,13 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| get_object_error(&key, &range, e))?;
|
||||
.map_err(|e| format!("failed to get object {} range {}: {}", key, range, e))?;
|
||||
|
||||
let body = get_resp
|
||||
.body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to read body: {}", e)))?;
|
||||
.map_err(|e| format!("failed to read body: {}", e))?;
|
||||
let bytes = body.into_bytes();
|
||||
|
||||
// Write at the correct offset (like Go's WriteAt)
|
||||
@@ -440,17 +370,13 @@ impl S3TierBackend {
|
||||
.write(true)
|
||||
.open(&dp)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to open dest file {}: {}", dp, e))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to open dest file {}: {}", dp, e))?;
|
||||
file.seek(std::io::SeekFrom::Start(off))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to seek to offset {}: {}", off, e))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to seek to offset {}: {}", off, e))?;
|
||||
file.write_all(&bytes)
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to write to {}: {}", dp, e)))?;
|
||||
.map_err(|e| format!("failed to write to {}: {}", dp, e))?;
|
||||
|
||||
// Report progress. The lock is released before the result is
|
||||
// propagated so an aborting callback cannot poison the mutex
|
||||
@@ -466,9 +392,9 @@ impl S3TierBackend {
|
||||
};
|
||||
(guard.1)(downloaded as i64, pct)
|
||||
};
|
||||
progress_result.map_err(TierError::Aborted)?;
|
||||
progress_result?;
|
||||
|
||||
Ok::<_, TierError>(())
|
||||
Ok::<_, String>(())
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -476,7 +402,7 @@ impl S3TierBackend {
|
||||
for handle in handles {
|
||||
handle
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("download task panicked: {}", e)))??;
|
||||
.map_err(|e| format!("download task panicked: {}", e))??;
|
||||
}
|
||||
|
||||
// fsync the file so its content is durable before the caller trims the .vif
|
||||
@@ -485,21 +411,16 @@ impl S3TierBackend {
|
||||
.write(true)
|
||||
.open(dest_path)
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to open {} for fsync: {}", dest_path, e)))?;
|
||||
.map_err(|e| format!("failed to open {} for fsync: {}", dest_path, e))?;
|
||||
synced
|
||||
.sync_all()
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to fsync {}: {}", dest_path, e)))?;
|
||||
.map_err(|e| format!("failed to fsync {}: {}", dest_path, e))?;
|
||||
|
||||
Ok(file_size)
|
||||
}
|
||||
|
||||
pub async fn read_range(
|
||||
&self,
|
||||
key: &str,
|
||||
offset: u64,
|
||||
size: usize,
|
||||
) -> Result<Vec<u8>, TierError> {
|
||||
pub async fn read_range(&self, key: &str, offset: u64, size: usize) -> Result<Vec<u8>, String> {
|
||||
let end = offset + (size as u64).saturating_sub(1);
|
||||
let range = format!("bytes={}-{}", offset, end);
|
||||
let resp = self
|
||||
@@ -510,35 +431,29 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| get_object_error(key, &range, e))?;
|
||||
.map_err(|e| format!("failed to get object {} range {}: {}", key, range, e))?;
|
||||
|
||||
let body = resp
|
||||
.body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| TierError::Io(format!("failed to read object {} body: {}", key, e)))?;
|
||||
.map_err(|e| format!("failed to read object {} body: {}", key, e))?;
|
||||
Ok(body.into_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Delete a file from S3.
|
||||
pub async fn delete_file(&self, key: &str) -> Result<(), TierError> {
|
||||
pub async fn delete_file(&self, key: &str) -> Result<(), String> {
|
||||
self.client
|
||||
.delete_object()
|
||||
.bucket(&self.bucket)
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!(
|
||||
"failed to delete object {}: {}",
|
||||
key,
|
||||
DisplayErrorContext(&e)
|
||||
))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to delete object {}: {}", key, e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete_file_blocking(&self, key: &str) -> Result<(), TierError> {
|
||||
pub fn delete_file_blocking(&self, key: &str) -> Result<(), String> {
|
||||
let client = self.client.clone();
|
||||
let bucket = self.bucket.clone();
|
||||
let key = key.to_string();
|
||||
@@ -549,13 +464,7 @@ impl S3TierBackend {
|
||||
.key(&key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!(
|
||||
"failed to delete object {}: {}",
|
||||
key,
|
||||
DisplayErrorContext(&e)
|
||||
))
|
||||
})?;
|
||||
.map_err(|e| format!("failed to delete object {}: {}", key, e))?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -565,7 +474,7 @@ impl S3TierBackend {
|
||||
key: &str,
|
||||
offset: u64,
|
||||
size: usize,
|
||||
) -> Result<Vec<u8>, TierError> {
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let client = self.client.clone();
|
||||
let bucket = self.bucket.clone();
|
||||
let key = key.to_string();
|
||||
@@ -579,12 +488,13 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| get_object_error(&key, &range, e))?;
|
||||
.map_err(|e| format!("failed to get object {} range {}: {}", key, range, e))?;
|
||||
|
||||
let body =
|
||||
resp.body.collect().await.map_err(|e| {
|
||||
TierError::Io(format!("failed to read object {} body: {}", key, e))
|
||||
})?;
|
||||
let body = resp
|
||||
.body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| format!("failed to read object {} body: {}", key, e))?;
|
||||
Ok(body.into_bytes().to_vec())
|
||||
})
|
||||
}
|
||||
@@ -645,279 +555,18 @@ pub fn global_s3_tier_registry() -> &'static RwLock<S3TierRegistry> {
|
||||
GLOBAL_S3_TIER_REGISTRY.get_or_init(|| RwLock::new(S3TierRegistry::new()))
|
||||
}
|
||||
|
||||
/// The one process-wide runtime for tiered-S3 I/O issued from synchronous
|
||||
/// storage code. A per-call runtime tore down the SDK's pooled connections
|
||||
/// after every 64 KiB chunk, re-dialing TLS per read; a long-lived runtime
|
||||
/// keeps the pool warm.
|
||||
///
|
||||
/// Built on first use. A build failure is returned, not cached or panicked:
|
||||
/// callers sit inside `Volume::destroy` and needle reads, whose own error
|
||||
/// paths must run, and a later call may succeed.
|
||||
static TIER_RUNTIME: std::sync::Mutex<Option<tokio::runtime::Runtime>> =
|
||||
std::sync::Mutex::new(None);
|
||||
|
||||
fn tier_handle() -> Result<tokio::runtime::Handle, TierError> {
|
||||
let mut slot = TIER_RUNTIME
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if slot.is_none() {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.thread_name("tier-io")
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
TierError::RuntimeUnavailable(format!(
|
||||
"failed to build the tier I/O tokio runtime: {}",
|
||||
e
|
||||
))
|
||||
})?;
|
||||
*slot = Some(runtime);
|
||||
}
|
||||
Ok(slot.as_ref().expect("just initialised").handle().clone())
|
||||
}
|
||||
|
||||
/// Run `future` on the tier runtime and block the calling thread until it
|
||||
/// finishes. The caller may be a worker of *another* tokio runtime, so this
|
||||
/// waits on a channel rather than `Handle::block_on`, which panics when
|
||||
/// called from inside any runtime context.
|
||||
fn block_on_tier_future<F, T>(future: F) -> Result<T, TierError>
|
||||
fn block_on_tier_future<F, T>(future: F) -> Result<T, String>
|
||||
where
|
||||
F: Future<Output = Result<T, TierError>> + Send + 'static,
|
||||
F: Future<Output = Result<T, String>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let handle = tier_handle()?;
|
||||
let task = handle.spawn(future);
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
||||
handle.spawn(async move {
|
||||
// The receiver only goes away if the caller was unwound; nothing to
|
||||
// report then.
|
||||
let _ = tx.send(task.await);
|
||||
});
|
||||
match rx.recv() {
|
||||
Ok(Ok(result)) => result,
|
||||
Ok(Err(join_error)) => Err(describe_join_error(join_error)),
|
||||
Err(_) => Err(TierError::RuntimeUnavailable(
|
||||
"tier I/O runtime dropped the task before it finished".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a `JoinError` into a message that keeps the panic payload, so an
|
||||
/// SDK panic surfaces as "boom" rather than a fixed "thread panicked".
|
||||
fn describe_join_error(join_error: tokio::task::JoinError) -> TierError {
|
||||
if join_error.is_panic() {
|
||||
let payload = join_error.into_panic();
|
||||
let message = if let Some(s) = payload.downcast_ref::<&str>() {
|
||||
(*s).to_string()
|
||||
} else if let Some(s) = payload.downcast_ref::<String>() {
|
||||
s.clone()
|
||||
} else {
|
||||
"non-string panic payload".to_string()
|
||||
};
|
||||
TierError::Io(format!("tier I/O task panicked: {}", message))
|
||||
} else {
|
||||
TierError::RuntimeUnavailable(format!("tier I/O task failed: {}", join_error))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::remote_storage::s3::tests::{CannedResponse, NO_SUCH_KEY};
|
||||
use std::collections::HashSet;
|
||||
use tokio::runtime::Handle;
|
||||
|
||||
fn probe() -> Result<(tokio::runtime::Id, Option<String>), TierError> {
|
||||
block_on_tier_future(async {
|
||||
Ok((
|
||||
Handle::current().id(),
|
||||
std::thread::current().name().map(str::to_string),
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_on_tier_future_reuses_one_runtime() {
|
||||
let (first_runtime, first_thread) = probe().expect("first call");
|
||||
let (second_runtime, second_thread) = probe().expect("second call");
|
||||
assert_eq!(
|
||||
first_runtime, second_runtime,
|
||||
"each call must run on the same long-lived tier runtime"
|
||||
);
|
||||
assert_eq!(first_thread.as_deref(), Some("tier-io"));
|
||||
assert_eq!(second_thread.as_deref(), Some("tier-io"));
|
||||
|
||||
let mut runtimes = HashSet::new();
|
||||
for _ in 0..20 {
|
||||
let (id, _) = probe().expect("probe");
|
||||
runtimes.insert(id);
|
||||
}
|
||||
assert_eq!(runtimes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_on_tier_future_returns_the_value_and_the_error() {
|
||||
assert_eq!(block_on_tier_future(async { Ok(7u32) }).unwrap(), 7);
|
||||
let err = block_on_tier_future::<_, u32>(async { Err(TierError::NotFound("nope".into())) })
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, TierError::NotFound(m) if m == "nope"),
|
||||
"{err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_on_tier_future_works_from_a_std_thread() {
|
||||
let (id, _) = std::thread::spawn(probe)
|
||||
.join()
|
||||
.expect("probe thread")
|
||||
.expect("probe");
|
||||
assert_eq!(id, tier_handle().expect("tier runtime").id());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn block_on_tier_future_works_from_spawn_blocking() {
|
||||
let (id, _) = tokio::task::spawn_blocking(probe)
|
||||
.await
|
||||
.expect("spawn_blocking")
|
||||
.expect("probe");
|
||||
assert_eq!(id, tier_handle().expect("tier runtime").id());
|
||||
assert_ne!(id, Handle::current().id());
|
||||
}
|
||||
|
||||
// Called straight from another runtime's async context: the case that
|
||||
// would panic with `Handle::block_on` ("Cannot start a runtime from
|
||||
// within a runtime").
|
||||
#[tokio::test]
|
||||
async fn block_on_tier_future_works_from_a_current_thread_runtime() {
|
||||
let (id, _) = probe().expect("probe");
|
||||
assert_eq!(id, tier_handle().expect("tier runtime").id());
|
||||
assert_ne!(id, Handle::current().id());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn block_on_tier_future_works_from_a_multi_thread_runtime_worker() {
|
||||
let (id, _) = probe().expect("probe");
|
||||
assert_eq!(id, tier_handle().expect("tier runtime").id());
|
||||
assert_ne!(id, Handle::current().id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_on_tier_future_reports_the_panic_payload() {
|
||||
let err = block_on_tier_future::<_, ()>(async {
|
||||
if std::hint::black_box(true) {
|
||||
panic!("boom {}", 42);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("a panicking future must be an error");
|
||||
assert!(matches!(err, TierError::Io(_)), "got: {err:?}");
|
||||
assert!(err.to_string().contains("boom 42"), "got: {err}");
|
||||
assert!(err.to_string().contains("panicked"), "got: {err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_on_tier_future_reports_a_str_panic_payload() {
|
||||
let err = block_on_tier_future::<_, ()>(async {
|
||||
if std::hint::black_box(true) {
|
||||
panic!("static boom");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("a panicking future must be an error");
|
||||
assert!(err.to_string().contains("static boom"), "got: {err}");
|
||||
}
|
||||
|
||||
fn backend_answering(status: u16, body: &'static str) -> S3TierBackend {
|
||||
let config = aws_sdk_s3::Config::builder()
|
||||
.behavior_version(BehaviorVersion::latest())
|
||||
.region(Region::new("us-east-1"))
|
||||
.credentials_provider(Credentials::new("AKIATEST", "secret", None, None, "test"))
|
||||
.endpoint_url("http://127.0.0.1:1")
|
||||
.force_path_style(true)
|
||||
.http_client(CannedResponse { status, body })
|
||||
.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
|
||||
.build();
|
||||
S3TierBackend {
|
||||
client: Client::from_conf(config),
|
||||
bucket: "bucket".to_string(),
|
||||
storage_class: "STANDARD".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_head_404_is_not_found() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dest = tmp.path().join("1.dat");
|
||||
let err = backend_answering(404, "")
|
||||
.download_file(dest.to_str().unwrap(), "missing", |_, _| Ok(()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.starts_with("failed to head object missing: "),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_head_403_is_io() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dest = tmp.path().join("1.dat");
|
||||
let err = backend_answering(403, "")
|
||||
.download_file(dest.to_str().unwrap(), "denied", |_, _| Ok(()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::Io(_)), "{err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_range_no_such_key_is_not_found() {
|
||||
let err = backend_answering(404, NO_SUCH_KEY)
|
||||
.read_range("missing", 0, 8)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.starts_with("failed to get object missing range bytes=0-7: "),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_range_bare_404_is_io() {
|
||||
// As in Go, GET is not-found by the NoSuchKey code, not the status.
|
||||
let err = backend_answering(404, "")
|
||||
.read_range("missing", 0, 8)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::Io(_)), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_range_blocking_no_such_key_is_not_found() {
|
||||
let err = backend_answering(404, NO_SUCH_KEY)
|
||||
.read_range_blocking("missing", 0, 8)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_name_to_type_id_splits_on_dot() {
|
||||
assert_eq!(
|
||||
backend_name_to_type_id("s3"),
|
||||
("s3".to_string(), "default".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
backend_name_to_type_id("s3.eu"),
|
||||
("s3".to_string(), "eu".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
backend_name_to_type_id("s3.a.b"),
|
||||
(String::new(), String::new())
|
||||
);
|
||||
}
|
||||
std::thread::spawn(move || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(|e| format!("failed to build tokio runtime: {}", e))?;
|
||||
runtime.block_on(future)
|
||||
})
|
||||
.join()
|
||||
.map_err(|_| "tier runtime thread panicked".to_string())?
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,7 +21,6 @@ use super::volume_server::{VolumeServerState, normalize_outgoing_http_url, to_ht
|
||||
use crate::config::ReadMode;
|
||||
use crate::metrics;
|
||||
use crate::pb::volume_server_pb;
|
||||
use crate::storage::needle::CRC;
|
||||
use crate::storage::needle::needle::Needle;
|
||||
use crate::storage::types::*;
|
||||
|
||||
@@ -143,78 +142,6 @@ const STREAMING_THRESHOLD: u32 = 1024 * 1024; // 1 MB
|
||||
/// Default chunk size for streaming reads from the dat file.
|
||||
const DEFAULT_STREAMING_CHUNK_SIZE: usize = 64 * 1024; // 64 KB
|
||||
|
||||
/// Whether a GET/HEAD can be answered from the needle meta and the data file.
|
||||
#[derive(Clone, Copy)]
|
||||
struct SourceReadRequest {
|
||||
is_head: bool,
|
||||
has_range: bool,
|
||||
has_image_ops: bool,
|
||||
bypass_cm: bool,
|
||||
}
|
||||
|
||||
impl SourceReadRequest {
|
||||
/// The payload can be served as stored.
|
||||
fn direct(&self, n: &Needle) -> bool {
|
||||
!n.is_compressed() && !(n.is_chunk_manifest() && !self.bypass_cm) && !self.has_image_ops
|
||||
}
|
||||
|
||||
/// HEAD, a range, or a stream.
|
||||
fn served_from_source(&self, n: &Needle) -> bool {
|
||||
self.is_head || (self.direct(n) && (self.has_range || n.data_size > STREAMING_THRESHOLD))
|
||||
}
|
||||
|
||||
/// Meta first only if the needle could be served from source; its data
|
||||
/// size is below its index size.
|
||||
fn try_meta_first(&self, size: Size) -> bool {
|
||||
self.is_head
|
||||
|| (!self.has_image_ops && (self.has_range || size.0 > STREAMING_THRESHOLD as i32))
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking part of a GET/HEAD: the store guard is dropped before any needle
|
||||
/// I/O, so a slow or tiered read cannot park store writers. `Ok(None)` is a
|
||||
/// cookie mismatch.
|
||||
fn read_needle_for_get(
|
||||
state: &VolumeServerState,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
cookie: Cookie,
|
||||
read_deleted: bool,
|
||||
request: SourceReadRequest,
|
||||
) -> Result<
|
||||
Option<(Needle, Option<crate::storage::volume::NeedleStreamInfo>)>,
|
||||
crate::storage::volume::VolumeError,
|
||||
> {
|
||||
let mut plan = state
|
||||
.store
|
||||
.read()
|
||||
.unwrap()
|
||||
.needle_read_plan(vid, needle_id, read_deleted)?;
|
||||
let blank = || Needle {
|
||||
id: needle_id,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
let mut n = blank();
|
||||
if request.try_meta_first(plan.size()) {
|
||||
plan.read_meta(&mut n)?;
|
||||
if n.cookie != cookie {
|
||||
return Ok(None);
|
||||
}
|
||||
if request.served_from_source(&n) {
|
||||
let info = plan.into_stream_info(&n);
|
||||
return Ok(Some((n, Some(info))));
|
||||
}
|
||||
// Compressed or a chunk manifest: the payload is needed after all.
|
||||
n = blank();
|
||||
}
|
||||
plan.read_full(&mut n)?;
|
||||
if n.cookie != cookie {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some((n, None)))
|
||||
}
|
||||
|
||||
/// A body that streams needle data from the dat file in chunks using pread,
|
||||
/// avoiding loading the entire payload into memory at once.
|
||||
struct StreamingBody {
|
||||
@@ -240,10 +167,6 @@ struct StreamingBody {
|
||||
/// Compaction revision at the time of the initial read; if the volume's revision
|
||||
/// changes between chunks, the needle may have moved and we must re-lookup its offset.
|
||||
compaction_revision: u16,
|
||||
/// Checksum stored in the needle tail.
|
||||
expected_checksum: u32,
|
||||
/// Running checksum over the emitted data.
|
||||
crc: CRC,
|
||||
}
|
||||
|
||||
impl http_body::Body for StreamingBody {
|
||||
@@ -264,32 +187,7 @@ impl http_body::Body for StreamingBody {
|
||||
match result {
|
||||
Ok(Ok(chunk)) => {
|
||||
let len = chunk.len();
|
||||
self.crc = self.crc.update(&chunk);
|
||||
self.pos += len;
|
||||
// The last frame is held back until the checksum verifies
|
||||
// (Go parity: readNeedleDataInto). On a mismatch it is
|
||||
// never emitted, so the response ends short of the declared
|
||||
// Content-Length and the reader sees a failed transfer.
|
||||
if self.pos >= self.data_size as usize {
|
||||
let ok = self.expected_checksum == self.crc.0
|
||||
|| self.expected_checksum == self.crc.legacy_value();
|
||||
if !ok {
|
||||
metrics::HANDLER_COUNTER
|
||||
.with_label_values(&[metrics::ERROR_CRC])
|
||||
.inc();
|
||||
return std::task::Poll::Ready(Some(Err(
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"needle data checksum {} expected {} for needle {}",
|
||||
self.crc.0,
|
||||
self.expected_checksum,
|
||||
self.needle_id
|
||||
),
|
||||
),
|
||||
)));
|
||||
}
|
||||
}
|
||||
return std::task::Poll::Ready(Some(Ok(http_body::Frame::data(
|
||||
chunk,
|
||||
))));
|
||||
@@ -313,9 +211,6 @@ impl http_body::Body for StreamingBody {
|
||||
let relookup_result = {
|
||||
let store = self.server_state.store.read().unwrap();
|
||||
if let Some((_, vol)) = store.find_volume(self.volume_id) {
|
||||
if let Some(e) = vol.unavailable_error() {
|
||||
return std::task::Poll::Ready(Some(Err(std::io::Error::other(e))));
|
||||
}
|
||||
if vol.super_block.compaction_revision != self.compaction_revision {
|
||||
// Compaction occurred — re-lookup the needle's data offset
|
||||
Some(vol.re_lookup_needle_data_offset(self.needle_id))
|
||||
@@ -1184,7 +1079,11 @@ async fn get_or_head_handler_inner(
|
||||
|
||||
// Read needle — branching between regular volume and EC volume paths.
|
||||
// EC volumes always do a full read (no streaming/meta-only).
|
||||
let n: Needle;
|
||||
let mut n = Needle {
|
||||
id: needle_id,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
|
||||
let read_deleted = query.read_deleted.as_deref() == Some("true");
|
||||
let has_range = headers.contains_key(header::RANGE);
|
||||
@@ -1261,49 +1160,24 @@ async fn get_or_head_handler_inner(
|
||||
can_handle_range_from_source = false;
|
||||
} else {
|
||||
// ---- Regular volume read path (with streaming support) ----
|
||||
bypass_cm = query.cm.as_deref() == Some("false");
|
||||
track_download = download_guard.is_some();
|
||||
let request_kind = SourceReadRequest {
|
||||
is_head: method == Method::HEAD,
|
||||
has_range,
|
||||
has_image_ops,
|
||||
bypass_cm,
|
||||
};
|
||||
|
||||
let read_state = state.clone();
|
||||
let read = tokio::task::spawn_blocking(move || {
|
||||
read_needle_for_get(
|
||||
&read_state,
|
||||
vid,
|
||||
needle_id,
|
||||
cookie,
|
||||
read_deleted,
|
||||
request_kind,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
(n, stream_info) = match read {
|
||||
Ok(Ok(Some(found))) => found,
|
||||
// Cookie mismatch
|
||||
Ok(Ok(None)) => return StatusCode::NOT_FOUND.into_response(),
|
||||
Ok(Err(
|
||||
crate::storage::volume::VolumeError::NotFound
|
||||
| crate::storage::volume::VolumeError::Deleted,
|
||||
)) => {
|
||||
// Try meta-only read first for potential streaming
|
||||
let store = state.store.read().unwrap();
|
||||
let si_result = store.read_volume_needle_stream_info(vid, &mut n, read_deleted);
|
||||
stream_info = match si_result {
|
||||
Ok(info) => Some(info),
|
||||
Err(crate::storage::volume::VolumeError::StreamingUnsupported) => None,
|
||||
Err(crate::storage::volume::VolumeError::NotFound) => {
|
||||
metrics::HANDLER_COUNTER
|
||||
.with_label_values(&[metrics::ERROR_GET_NOT_FOUND])
|
||||
.inc();
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
Err(crate::storage::volume::VolumeError::Deleted) => {
|
||||
metrics::HANDLER_COUNTER
|
||||
.with_label_values(&[metrics::ERROR_GET_INTERNAL])
|
||||
.with_label_values(&[metrics::ERROR_GET_NOT_FOUND])
|
||||
.inc();
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("read error: {}", e),
|
||||
)
|
||||
.into_response();
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
metrics::HANDLER_COUNTER
|
||||
@@ -1316,9 +1190,19 @@ async fn get_or_head_handler_inner(
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
drop(store);
|
||||
|
||||
// Stream info is only returned for a reply served from the data file.
|
||||
let can_direct_source_read = stream_info.is_some() && request_kind.direct(&n);
|
||||
// Validate cookie
|
||||
if n.cookie != cookie {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
|
||||
bypass_cm = query.cm.as_deref() == Some("false");
|
||||
track_download = download_guard.is_some();
|
||||
let can_direct_source_read = stream_info.is_some()
|
||||
&& !n.is_compressed()
|
||||
&& !(n.is_chunk_manifest() && !bypass_cm)
|
||||
&& !has_image_ops;
|
||||
|
||||
// Determine if we can stream (large, direct-source eligible, no range)
|
||||
can_stream = can_direct_source_read
|
||||
@@ -1329,6 +1213,41 @@ async fn get_or_head_handler_inner(
|
||||
// Go uses meta-only reads for all HEAD requests, regardless of compression/chunked files.
|
||||
can_handle_head_from_meta = stream_info.is_some() && method == Method::HEAD;
|
||||
can_handle_range_from_source = can_direct_source_read && has_range;
|
||||
|
||||
// For chunk manifest or any non-streaming path, we need the full data.
|
||||
// If we can't stream, do a full read now.
|
||||
if !can_stream && !can_handle_head_from_meta && !can_handle_range_from_source {
|
||||
// Re-read with full data
|
||||
let mut n_full = Needle {
|
||||
id: needle_id,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
let store = state.store.read().unwrap();
|
||||
match store.read_volume_needle_opt(vid, &mut n_full, read_deleted) {
|
||||
Ok(count) => {
|
||||
if count < 0 {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
}
|
||||
Err(crate::storage::volume::VolumeError::NotFound) => {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Err(crate::storage::volume::VolumeError::Deleted) => {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("read error: {}", e),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
drop(store);
|
||||
// Use the full needle from here (it has the same metadata + data)
|
||||
n = n_full;
|
||||
}
|
||||
}
|
||||
|
||||
// Build ETag and Last-Modified BEFORE conditional checks and chunk manifest expansion
|
||||
@@ -1590,8 +1509,6 @@ async fn get_or_head_handler_inner(
|
||||
volume_id: info.volume_id,
|
||||
needle_id: info.needle_id,
|
||||
compaction_revision: info.compaction_revision,
|
||||
expected_checksum: info.checksum,
|
||||
crc: CRC(0),
|
||||
};
|
||||
|
||||
let body = Body::new(streaming);
|
||||
@@ -1613,19 +1530,12 @@ async fn get_or_head_handler_inner(
|
||||
&& let (Some(range_header), Some(info)) = (headers.get(header::RANGE), stream_info)
|
||||
&& let Ok(range_str) = range_header.to_str()
|
||||
{
|
||||
let range_str = range_str.to_string();
|
||||
let tracking = track_download.then(|| state.clone());
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
handle_range_request_from_source(&range_str, info, response_headers, tracking)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("range read error: {}", e),
|
||||
)
|
||||
.into_response()
|
||||
});
|
||||
return handle_range_request_from_source(
|
||||
range_str,
|
||||
info,
|
||||
response_headers,
|
||||
track_download.then(|| state.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Buffered path: small files, compressed, images, range requests ----
|
||||
@@ -2751,15 +2661,8 @@ pub async fn post_handler(
|
||||
// sees it the same way the primary did.
|
||||
let fsync = form_value("fsync").as_deref() == Some("true");
|
||||
|
||||
// Go computes the checksum while building the needle (CreateNeedleFromRequest).
|
||||
// The write queue takes the needle away, so the response fields that come
|
||||
// from it are read here, before the write, rather than from a copy.
|
||||
n.checksum = crate::storage::needle::crc::CRC::new(&n.data);
|
||||
let needle_etag = n.etag();
|
||||
let needle_has_name = n.has_name();
|
||||
|
||||
let write_result = if let Some(wq) = state.write_queue.get() {
|
||||
wq.submit(vid, n, fsync).await
|
||||
wq.submit(vid, n.clone(), fsync).await
|
||||
} else {
|
||||
let mut store = state.store.write().unwrap();
|
||||
store.write_volume_needle(vid, &mut n, fsync)
|
||||
@@ -2810,22 +2713,22 @@ pub async fn post_handler(
|
||||
let resp = match write_result {
|
||||
Ok((_offset, _size, is_unchanged)) => {
|
||||
if is_unchanged {
|
||||
let etag = format!("\"{}\"", needle_etag);
|
||||
let etag = format!("\"{}\"", n.etag());
|
||||
(StatusCode::NO_CONTENT, [(header::ETAG, etag)]).into_response()
|
||||
} else {
|
||||
// Go only includes contentMd5 when the client provided Content-MD5
|
||||
let result = UploadResult {
|
||||
name: if needle_has_name {
|
||||
name: if n.has_name() {
|
||||
filename.clone()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
size: original_data_size, // H3: use original size, not compressed
|
||||
etag: needle_etag.clone(),
|
||||
etag: n.etag(),
|
||||
mime: mime_type.clone(),
|
||||
content_md5: original_content_md5.clone(),
|
||||
};
|
||||
let etag = needle_etag;
|
||||
let etag = n.etag();
|
||||
let etag_header = if etag.starts_with('"') {
|
||||
etag.clone()
|
||||
} else {
|
||||
@@ -4670,405 +4573,4 @@ mod tests {
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
fn streaming_test_state() -> Arc<VolumeServerState> {
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::store::Store;
|
||||
test_state_with_store(Store::new(NeedleMapKind::InMemory))
|
||||
}
|
||||
|
||||
fn test_state_with_store(store: crate::storage::store::Store) -> Arc<VolumeServerState> {
|
||||
use crate::security::{Guard, SigningKey};
|
||||
use crate::server::volume_server::RuntimeMetricsConfig;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32};
|
||||
|
||||
Arc::new(VolumeServerState {
|
||||
store: RwLock::new(store),
|
||||
guard: RwLock::new(Guard::new(
|
||||
&[],
|
||||
SigningKey(vec![]),
|
||||
0,
|
||||
SigningKey(vec![]),
|
||||
0,
|
||||
)),
|
||||
is_stopping: RwLock::new(false),
|
||||
maintenance: AtomicBool::new(false),
|
||||
state_version: AtomicU32::new(0),
|
||||
concurrent_upload_limit: 0,
|
||||
concurrent_download_limit: 0,
|
||||
inflight_upload_data_timeout: std::time::Duration::ZERO,
|
||||
inflight_download_data_timeout: std::time::Duration::ZERO,
|
||||
inflight_upload_bytes: AtomicI64::new(0),
|
||||
inflight_download_bytes: AtomicI64::new(0),
|
||||
upload_notify: tokio::sync::Notify::new(),
|
||||
download_notify: tokio::sync::Notify::new(),
|
||||
data_center: String::new(),
|
||||
rack: String::new(),
|
||||
file_size_limit_bytes: 0,
|
||||
maintenance_byte_per_second: 0,
|
||||
is_heartbeating: AtomicBool::new(false),
|
||||
has_master: false,
|
||||
pre_stop_seconds: 0,
|
||||
volume_state_notify: tokio::sync::Notify::new(),
|
||||
write_queue: std::sync::OnceLock::new(),
|
||||
read_mode: crate::config::ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: String::new(),
|
||||
master_urls: Vec::new(),
|
||||
seed_master_set: std::collections::HashSet::new(),
|
||||
current_master_url: tokio::sync::RwLock::new(String::new()),
|
||||
self_url: String::new(),
|
||||
http_client: reqwest::Client::new(),
|
||||
outgoing_http_scheme: "http".to_string(),
|
||||
outgoing_grpc_tls: None,
|
||||
metrics_runtime: RwLock::new(RuntimeMetricsConfig::default()),
|
||||
metrics_notify: tokio::sync::Notify::new(),
|
||||
fix_jpg_orientation: false,
|
||||
has_slow_read: false,
|
||||
read_buffer_size_bytes: 4 * 1024 * 1024,
|
||||
security_file: String::new(),
|
||||
cli_white_list: vec![],
|
||||
state_file_path: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Go's readNeedleDataInto holds back the last chunk of a whole-needle read
|
||||
/// until the checksum verifies; a streamed needle that fails its CRC must
|
||||
/// likewise end short of the declared length instead of looking complete.
|
||||
#[tokio::test]
|
||||
async fn test_streaming_body_checksum_failure_drops_last_chunk() {
|
||||
use futures::StreamExt;
|
||||
use std::io::Write;
|
||||
|
||||
let data: Vec<u8> = (0..10_000u32).map(|i| (i % 251) as u8).collect();
|
||||
let mut tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
tmp.write_all(&data).unwrap();
|
||||
let file = tmp.reopen().unwrap();
|
||||
|
||||
let control = Arc::new(crate::storage::volume::DataFileAccessControl::default());
|
||||
let mk_body = |expected_checksum: u32, file: &std::fs::File| StreamingBody {
|
||||
source: crate::storage::volume::NeedleStreamSource::Local(file.try_clone().unwrap()),
|
||||
data_offset: 0,
|
||||
data_size: data.len() as u32,
|
||||
pos: 0,
|
||||
chunk_size: 4096,
|
||||
data_file_access_control: control.clone(),
|
||||
hold_read_lock_for_stream: true,
|
||||
_held_read_lease: None,
|
||||
pending: None,
|
||||
state: None,
|
||||
tracked_bytes: 0,
|
||||
server_state: streaming_test_state(),
|
||||
volume_id: VolumeId(1),
|
||||
needle_id: NeedleId(7),
|
||||
compaction_revision: 0,
|
||||
expected_checksum,
|
||||
crc: CRC(0),
|
||||
};
|
||||
|
||||
// Healthy needle: every byte is delivered.
|
||||
let body = Body::new(mk_body(CRC::new(&data).0, &file));
|
||||
let mut stream = body.into_data_stream();
|
||||
let mut got = 0usize;
|
||||
while let Some(item) = stream.next().await {
|
||||
got += item.expect("healthy stream errored").len();
|
||||
}
|
||||
assert_eq!(got, data.len());
|
||||
|
||||
// Corrupted needle: the last chunk fails the checksum and is never
|
||||
// emitted — the body ends short of the data size.
|
||||
let body = Body::new(mk_body(CRC::new(&data).0 ^ 0xff, &file));
|
||||
let mut stream = body.into_data_stream();
|
||||
let mut got = 0usize;
|
||||
let mut saw_err = false;
|
||||
while let Some(item) = stream.next().await {
|
||||
match item {
|
||||
Ok(bytes) => got += bytes.len(),
|
||||
Err(e) => {
|
||||
assert!(
|
||||
e.to_string().contains("checksum"),
|
||||
"unexpected stream error: {e}"
|
||||
);
|
||||
saw_err = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(saw_err, "corrupted stream must fail");
|
||||
assert!(got < data.len(), "delivered {got} of {} bytes", data.len());
|
||||
}
|
||||
|
||||
const TEST_COOKIE: u32 = 0x1234_5678;
|
||||
|
||||
/// State whose store holds volume 1 in `tmp`.
|
||||
fn volume_test_state(tmp: &tempfile::TempDir) -> Arc<VolumeServerState> {
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::store::Store;
|
||||
use crate::storage::volume::VolumeSpec;
|
||||
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
crate::config::MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
test_state_with_store(store)
|
||||
}
|
||||
|
||||
/// Write a needle to volume 1 and return its URL path.
|
||||
fn put_test_needle(state: &VolumeServerState, id: u64, data: &[u8]) -> String {
|
||||
put_test_needle_with(state, id, data, |_| {})
|
||||
}
|
||||
|
||||
fn put_test_needle_with(
|
||||
state: &VolumeServerState,
|
||||
id: u64,
|
||||
data: &[u8],
|
||||
prepare: impl FnOnce(&mut Needle),
|
||||
) -> String {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(TEST_COOKIE),
|
||||
data: data.to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
prepare(&mut n);
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.write_volume_needle(VolumeId(1), &mut n, false)
|
||||
.unwrap();
|
||||
format!("/1,{:x}{:08x}", id, TEST_COOKIE)
|
||||
}
|
||||
|
||||
async fn send_read(
|
||||
state: &Arc<VolumeServerState>,
|
||||
method: Method,
|
||||
path: &str,
|
||||
range: Option<&str>,
|
||||
) -> (StatusCode, HeaderMap, Vec<u8>) {
|
||||
use tower::ServiceExt;
|
||||
let mut req = Request::builder().method(method).uri(path);
|
||||
if let Some(range) = range {
|
||||
req = req.header(header::RANGE, range);
|
||||
}
|
||||
let resp = super::super::volume_server::build_public_router(state.clone())
|
||||
.oneshot(req.body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let status = resp.status();
|
||||
let headers = resp.headers().clone();
|
||||
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
(status, headers, body)
|
||||
}
|
||||
|
||||
/// A GET whose needle read is parked must not hold the store lock: a
|
||||
/// writer, here a real append to the same volume, must get through.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_get_needle_read_runs_off_the_store_lock() {
|
||||
use crate::storage::volume::needle_read_hook;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
const ID: u64 = 0x6e7a_0001;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let data = b"parked needle".to_vec();
|
||||
let path = put_test_needle(&state, ID, &data);
|
||||
|
||||
let (entered_tx, entered_rx) = mpsc::channel::<()>();
|
||||
let (release_tx, release_rx) = mpsc::channel::<()>();
|
||||
let release_rx = Mutex::new(release_rx);
|
||||
let _hook = needle_read_hook::register(NeedleId(ID), move |_| {
|
||||
let _ = entered_tx.send(());
|
||||
// Returns once released, or at once when the sender is gone.
|
||||
let _ = release_rx.lock().unwrap().recv();
|
||||
});
|
||||
|
||||
let get = tokio::spawn({
|
||||
let state = state.clone();
|
||||
async move { send_read(&state, Method::GET, &path, None).await }
|
||||
});
|
||||
tokio::task::spawn_blocking(move || entered_rx.recv_timeout(Duration::from_secs(10)))
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the GET never reached its needle read");
|
||||
|
||||
let try_write_ok = state.store.try_write().is_ok();
|
||||
let (wrote_tx, wrote_rx) = mpsc::channel();
|
||||
std::thread::spawn({
|
||||
let state = state.clone();
|
||||
move || {
|
||||
put_test_needle(&state, ID + 1, b"written meanwhile");
|
||||
let _ = wrote_tx.send(());
|
||||
}
|
||||
});
|
||||
let write_done = tokio::task::spawn_blocking(move || {
|
||||
wrote_rx.recv_timeout(Duration::from_secs(5)).is_ok()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
drop(release_tx);
|
||||
|
||||
assert!(
|
||||
try_write_ok,
|
||||
"a parked GET read must not hold the store lock"
|
||||
);
|
||||
assert!(write_done, "an append must not wait for a parked GET read");
|
||||
let (status, _, body) = get.await.unwrap();
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, data);
|
||||
}
|
||||
|
||||
/// A small needle is read from disk once, not once for its meta and
|
||||
/// again in full; a large one never reads its payload before streaming.
|
||||
#[tokio::test]
|
||||
async fn test_get_reads_small_needle_once_and_large_needle_meta_only() {
|
||||
use crate::storage::volume::needle_read_hook;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const SMALL: u64 = 0x6e7a_0101;
|
||||
const LARGE: u64 = 0x6e7a_0102;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let small = b"small needle".to_vec();
|
||||
let large: Vec<u8> = (0..(STREAMING_THRESHOLD as usize + 4096))
|
||||
.map(|i| (i % 251) as u8)
|
||||
.collect();
|
||||
let small_path = put_test_needle(&state, SMALL, &small);
|
||||
let large_path = put_test_needle(&state, LARGE, &large);
|
||||
|
||||
let small_reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let large_reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let _small_hook = needle_read_hook::register(NeedleId(SMALL), {
|
||||
let reads = small_reads.clone();
|
||||
move |len| reads.lock().unwrap().push(len)
|
||||
});
|
||||
let _large_hook = needle_read_hook::register(NeedleId(LARGE), {
|
||||
let reads = large_reads.clone();
|
||||
move |len| reads.lock().unwrap().push(len)
|
||||
});
|
||||
|
||||
let (status, _, body) = send_read(&state, Method::GET, &small_path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, small);
|
||||
let reads = small_reads.lock().unwrap().clone();
|
||||
assert_eq!(reads.len(), 1, "reads of the small needle: {reads:?}");
|
||||
|
||||
let (status, _, body) = send_read(&state, Method::GET, &large_path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, large);
|
||||
let reads = large_reads.lock().unwrap().clone();
|
||||
assert!(
|
||||
!reads.is_empty() && reads.iter().all(|&len| len < 64 * 1024),
|
||||
"the large needle's payload must not be read before streaming: {reads:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// HEAD and ranged reads keep answering from the needle meta and the
|
||||
/// data file, and a missing or wrong-cookie needle is still a 404.
|
||||
#[tokio::test]
|
||||
async fn test_get_head_range_and_not_found_after_single_read() {
|
||||
const ID: u64 = 0x6e7a_0201;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let data: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
|
||||
let path = put_test_needle(&state, ID, &data);
|
||||
|
||||
let (status, headers, body) = send_read(&state, Method::HEAD, &path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(body.is_empty());
|
||||
assert_eq!(headers[header::CONTENT_LENGTH], data.len().to_string());
|
||||
assert!(headers.contains_key(header::ETAG));
|
||||
|
||||
let (status, headers, body) =
|
||||
send_read(&state, Method::GET, &path, Some("bytes=10-19")).await;
|
||||
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
|
||||
assert_eq!(body, &data[10..20]);
|
||||
assert_eq!(
|
||||
headers["Content-Range"],
|
||||
format!("bytes 10-19/{}", data.len())
|
||||
);
|
||||
|
||||
let wrong_cookie = format!("/1,{:x}{:08x}", ID, TEST_COOKIE ^ 1);
|
||||
let (status, _, _) = send_read(&state, Method::GET, &wrong_cookie, None).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
let missing = format!("/1,{:x}{:08x}", ID + 1, TEST_COOKIE);
|
||||
let (status, _, _) = send_read(&state, Method::GET, &missing, None).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
/// A large compressed needle cannot be streamed as stored: its meta is
|
||||
/// read first, then the payload exactly once.
|
||||
#[tokio::test]
|
||||
async fn test_get_large_compressed_needle_reads_payload_once() {
|
||||
use crate::storage::volume::needle_read_hook;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const ID: u64 = 0x6e7a_0301;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
// Incompressible, so the stored gzip stays above the stream threshold.
|
||||
let mut x = 0x2545_f491_u32;
|
||||
let plain: Vec<u8> = (0..(STREAMING_THRESHOLD as usize + 64 * 1024))
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
x as u8
|
||||
})
|
||||
.collect();
|
||||
let gz = try_gzip_data(&plain).unwrap();
|
||||
assert!(gz.len() > STREAMING_THRESHOLD as usize);
|
||||
let path = put_test_needle_with(&state, ID, &gz, |n| n.set_is_compressed());
|
||||
|
||||
let reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let _hook = needle_read_hook::register(NeedleId(ID), {
|
||||
let reads = reads.clone();
|
||||
move |len| reads.lock().unwrap().push(len)
|
||||
});
|
||||
let (status, _, body) = send_read(&state, Method::GET, &path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, plain);
|
||||
let reads = reads.lock().unwrap().clone();
|
||||
let full = reads.iter().filter(|&&len| len >= gz.len()).count();
|
||||
assert_eq!(full, 1, "reads: {reads:?}");
|
||||
}
|
||||
|
||||
/// The single full read still verifies the needle checksum.
|
||||
#[tokio::test]
|
||||
async fn test_get_small_needle_with_bad_checksum_fails() {
|
||||
const ID: u64 = 0x6e7a_0401;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let data = b"checksummed payload, to be corrupted".to_vec();
|
||||
let path = put_test_needle(&state, ID, &data);
|
||||
|
||||
let dat = tmp.path().join("1.dat");
|
||||
let mut bytes = std::fs::read(&dat).unwrap();
|
||||
let at = bytes
|
||||
.windows(data.len())
|
||||
.position(|w| w == data.as_slice())
|
||||
.unwrap();
|
||||
bytes[at] ^= 0xff;
|
||||
std::fs::write(&dat, bytes).unwrap();
|
||||
|
||||
let (status, _, _) = send_read(&state, Method::GET, &path, None).await;
|
||||
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,8 @@ use crate::storage::volume_report_hash::report_hash;
|
||||
|
||||
const DUPLICATE_UUID_RETRY_MESSAGE: &str = "duplicate UUIDs detected, retrying connection";
|
||||
const MAX_DUPLICATE_UUID_RETRIES: u32 = 3;
|
||||
const MAX_TTL_VOLUME_REMOVAL_DELAY: u32 = 10;
|
||||
|
||||
/// Configuration for the heartbeat client.
|
||||
#[derive(Clone)]
|
||||
pub struct HeartbeatConfig {
|
||||
pub ip: String,
|
||||
pub port: u16,
|
||||
@@ -398,8 +396,7 @@ async fn do_heartbeat(
|
||||
state.store.read().unwrap().volume_report.reset();
|
||||
|
||||
// Keep track of what we sent, to generate delta updates
|
||||
let (initial_hb, initial_volumes) =
|
||||
off_runtime(config, state, collect_heartbeat_with_snapshot).await?;
|
||||
let (initial_hb, initial_volumes) = collect_heartbeat_with_snapshot(config, state);
|
||||
let mut last_volumes: HashMap<u32, VolumeIdentity> = volume_identities(&initial_volumes);
|
||||
let mut last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
@@ -465,8 +462,7 @@ async fn do_heartbeat(
|
||||
};
|
||||
if changed {
|
||||
let (adjusted_hb, adjusted_volumes) =
|
||||
off_runtime(config, state, collect_heartbeat_with_snapshot)
|
||||
.await?;
|
||||
collect_heartbeat_with_snapshot(config, state);
|
||||
last_volumes = volume_identities(&adjusted_volumes);
|
||||
last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
@@ -500,8 +496,7 @@ async fn do_heartbeat(
|
||||
let s = state.store.read().unwrap();
|
||||
s.maybe_adjust_volume_max();
|
||||
}
|
||||
let (current_hb, current_volumes) =
|
||||
off_runtime(config, state, collect_heartbeat_with_snapshot).await?;
|
||||
let (current_hb, current_volumes) = collect_heartbeat_with_snapshot(config, state);
|
||||
last_volumes = volume_identities(¤t_volumes);
|
||||
last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
@@ -530,7 +525,7 @@ async fn do_heartbeat(
|
||||
info!("Heartbeat stopping");
|
||||
return Ok(None);
|
||||
}
|
||||
let held_volumes = off_runtime(config, state, collect_volume_snapshot).await?;
|
||||
let held_volumes = collect_volume_snapshot(config, state);
|
||||
let current_volumes = volume_identities(&held_volumes);
|
||||
let current_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
@@ -786,16 +781,6 @@ fn volume_identities(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs a store pass on the blocking pool: it stats every volume's files.
|
||||
async fn off_runtime<T: Send + 'static>(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
pass: fn(&HeartbeatConfig, &Arc<VolumeServerState>) -> T,
|
||||
) -> Result<T, tokio::task::JoinError> {
|
||||
let (config, state) = (config.clone(), state.clone());
|
||||
tokio::task::spawn_blocking(move || pass(&config, &state)).await
|
||||
}
|
||||
|
||||
/// Collect volume information into a Heartbeat message.
|
||||
fn collect_heartbeat_with_snapshot(
|
||||
config: &HeartbeatConfig,
|
||||
@@ -804,32 +789,15 @@ fn collect_heartbeat_with_snapshot(
|
||||
master_pb::Heartbeat,
|
||||
Vec<master_pb::VolumeInformationMessage>,
|
||||
) {
|
||||
let (_, expired_ec) = state.store.read().unwrap().find_expired_ec_volumes();
|
||||
let mut deleted_ec_shards = Vec::new();
|
||||
if !expired_ec.is_empty() {
|
||||
deleted_ec_shards = state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.remove_expired_ec_volumes(expired_ec)
|
||||
.0;
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
let store_id = state.store.read().unwrap().id.clone();
|
||||
read_phase_hook::park(read_phase_hook::Point::BeforeVolumePass, &store_id);
|
||||
}
|
||||
let (heartbeat, volumes, actions) = {
|
||||
let store = state.store.read().unwrap();
|
||||
#[cfg(test)]
|
||||
read_phase_hook::park(read_phase_hook::Point::VolumePass, &store.id);
|
||||
// Taken with the volume list: a shard mounted since the EC phase must
|
||||
// not go out as "no EC shards", which clears it on the master.
|
||||
let has_no_ec_shards = !has_reportable_ec_shards(&store);
|
||||
build_heartbeat_with_ec_status(config, &store, deleted_ec_shards, has_no_ec_shards, true)
|
||||
};
|
||||
apply_volume_actions(state, actions);
|
||||
(heartbeat, volumes)
|
||||
let mut store = state.store.write().unwrap();
|
||||
let (ec_shards, deleted_ec_shards) = store.delete_expired_ec_volumes();
|
||||
build_heartbeat_with_ec_status(
|
||||
config,
|
||||
&mut store,
|
||||
deleted_ec_shards,
|
||||
ec_shards.is_empty(),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// Lists the volumes the server holds without touching reporting state or
|
||||
@@ -839,100 +807,8 @@ fn collect_volume_snapshot(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> Vec<master_pb::VolumeInformationMessage> {
|
||||
let (_, volumes, actions) = build_heartbeat_with_ec_status(
|
||||
config,
|
||||
&state.store.read().unwrap(),
|
||||
Vec::new(),
|
||||
true,
|
||||
false,
|
||||
);
|
||||
apply_volume_actions(state, actions);
|
||||
volumes
|
||||
}
|
||||
|
||||
/// Store changes a heartbeat pass decides on under the read lock, applied
|
||||
/// under a short write lock afterwards. Entries are (disk index, volume id).
|
||||
#[derive(Default)]
|
||||
struct VolumeActions {
|
||||
delete_expired: Vec<(usize, VolumeId)>,
|
||||
quarantine: Vec<(usize, VolumeId)>,
|
||||
}
|
||||
|
||||
fn apply_volume_actions(state: &VolumeServerState, actions: VolumeActions) {
|
||||
if actions.delete_expired.is_empty() && actions.quarantine.is_empty() {
|
||||
return;
|
||||
}
|
||||
apply_volume_actions_to(&mut state.store.write().unwrap(), actions);
|
||||
}
|
||||
|
||||
/// Each target is re-checked: it may have been written to, replaced or removed
|
||||
/// since the read pass chose it.
|
||||
fn apply_volume_actions_to(store: &mut Store, actions: VolumeActions) {
|
||||
let volume_size_limit = store.volume_size_limit.load(Ordering::Relaxed);
|
||||
for (disk_id, vid) in actions.delete_expired {
|
||||
let Some(loc) = store.locations.get_mut(disk_id) else {
|
||||
continue;
|
||||
};
|
||||
let still_expired = loc.find_volume(vid).is_some_and(|vol| {
|
||||
!vol.should_quarantine()
|
||||
&& vol.is_expired(vol.dat_file_size().unwrap_or(0), volume_size_limit)
|
||||
&& vol.is_expired_long_enough(MAX_TTL_VOLUME_REMOVAL_DELAY)
|
||||
});
|
||||
if still_expired {
|
||||
let _ = loc.delete_volume(vid, false, false, false);
|
||||
}
|
||||
}
|
||||
for (disk_id, vid) in actions.quarantine {
|
||||
if let Some(vol) = store
|
||||
.locations
|
||||
.get_mut(disk_id)
|
||||
.and_then(|loc| loc.find_volume_mut(vid))
|
||||
&& vol.should_quarantine()
|
||||
{
|
||||
vol.set_no_write_or_delete(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod read_phase_hook {
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use tokio::sync::oneshot::Sender;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub(super) enum Point {
|
||||
/// Between the EC phase and the volume pass, holding no lock.
|
||||
BeforeVolumePass,
|
||||
/// Inside the volume pass, holding the store read lock.
|
||||
VolumePass,
|
||||
}
|
||||
|
||||
type Park = (Point, String, Sender<()>, Receiver<()>);
|
||||
static ARMED: Mutex<Vec<Park>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Parks the next pass over the store with this id at `point`, announcing
|
||||
/// itself on `entered` and waiting until `release` is dropped.
|
||||
pub(super) fn arm(point: Point, store_id: &str, entered: Sender<()>, release: Receiver<()>) {
|
||||
ARMED
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((point, store_id.to_string(), entered, release));
|
||||
}
|
||||
|
||||
pub(super) fn park(point: Point, store_id: &str) {
|
||||
let armed = {
|
||||
let mut armed = ARMED.lock().unwrap();
|
||||
armed
|
||||
.iter()
|
||||
.position(|(p, id, _, _)| *p == point && !id.is_empty() && id == store_id)
|
||||
.map(|i| armed.swap_remove(i))
|
||||
};
|
||||
if let Some((_, _, entered, release)) = armed {
|
||||
let _ = entered.send(());
|
||||
let _ = release.recv();
|
||||
}
|
||||
}
|
||||
let mut store = state.store.write().unwrap();
|
||||
build_heartbeat_with_ec_status(config, &mut store, Vec::new(), true, false).1
|
||||
}
|
||||
|
||||
/// The heartbeat alone, without the volume snapshot the send loop pairs it
|
||||
@@ -975,42 +851,27 @@ fn collect_location_metadata(
|
||||
(location_uuids, disk_tags)
|
||||
}
|
||||
|
||||
/// Whether a heartbeat would report any EC shard: Go's non-empty
|
||||
/// `ecVolumeMessages` from `deleteExpiredEcVolumes`.
|
||||
fn has_reportable_ec_shards(store: &Store) -> bool {
|
||||
store.locations.iter().any(|loc| {
|
||||
loc.ec_volumes().any(|(_, ec_vol)| {
|
||||
!ec_vol.is_time_to_destroy()
|
||||
&& !ec_vol.should_quarantine()
|
||||
&& ec_vol.shards.iter().any(Option::is_some)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn build_heartbeat(config: &HeartbeatConfig, store: &mut Store) -> master_pb::Heartbeat {
|
||||
let has_no_ec_shards = collect_live_ec_shards(store, false).is_empty();
|
||||
let (heartbeat, _, actions) =
|
||||
build_heartbeat_with_ec_status(config, store, Vec::new(), has_no_ec_shards, true);
|
||||
apply_volume_actions_to(store, actions);
|
||||
heartbeat
|
||||
build_heartbeat_with_ec_status(config, store, Vec::new(), has_no_ec_shards, true).0
|
||||
}
|
||||
|
||||
/// Returns the heartbeat to send, every volume held, and the store changes
|
||||
/// the pass decided on. The caller derives mount and unmount deltas by diffing
|
||||
/// successive snapshots, so it must not be handed the partial list a heartbeat
|
||||
/// may carry.
|
||||
/// Returns the heartbeat to send and, separately, every volume held. The
|
||||
/// caller derives mount and unmount deltas by diffing successive snapshots, so
|
||||
/// it must not be handed the partial list a heartbeat may carry.
|
||||
fn build_heartbeat_with_ec_status(
|
||||
config: &HeartbeatConfig,
|
||||
store: &Store,
|
||||
store: &mut Store,
|
||||
deleted_ec_shards: Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
has_no_ec_shards: bool,
|
||||
commit_report: bool,
|
||||
) -> (
|
||||
master_pb::Heartbeat,
|
||||
Vec<master_pb::VolumeInformationMessage>,
|
||||
VolumeActions,
|
||||
) {
|
||||
const MAX_TTL_VOLUME_REMOVAL_DELAY: u32 = 10;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ReadOnlyCounts {
|
||||
is_read_only: u32,
|
||||
@@ -1040,9 +901,8 @@ fn build_heartbeat_with_ec_status(
|
||||
|
||||
// Per-disk effective max for DiskTag, captured alongside the per-type sum.
|
||||
let mut disk_max_by_id = vec![0i32; store.locations.len()];
|
||||
let mut actions = VolumeActions::default();
|
||||
|
||||
for (disk_id, loc) in store.locations.iter().enumerate() {
|
||||
for (disk_id, loc) in store.locations.iter_mut().enumerate() {
|
||||
let disk_type_str = loc.disk_type.to_string();
|
||||
let mut effective_max_count = loc.max_volume_count.load(Ordering::Relaxed);
|
||||
if loc.is_disk_space_low.load(Ordering::Relaxed) {
|
||||
@@ -1066,6 +926,8 @@ fn build_heartbeat_with_ec_status(
|
||||
*disk_free_bytes.entry(disk_type_str).or_insert(0) +=
|
||||
loc.disk_free_bytes.load(Ordering::Relaxed);
|
||||
|
||||
let mut delete_vids = Vec::new();
|
||||
let mut quarantine_vids: Vec<VolumeId> = Vec::new();
|
||||
for (_, vol) in loc.iter_volumes() {
|
||||
let cur_max = vol.max_file_key();
|
||||
if cur_max > max_file_key {
|
||||
@@ -1085,7 +947,7 @@ fn build_heartbeat_with_ec_status(
|
||||
);
|
||||
}
|
||||
quarantined_volumes += 1;
|
||||
actions.quarantine.push((disk_id, vol.id));
|
||||
quarantine_vids.push(vol.id);
|
||||
continue;
|
||||
} else if !vol.is_expired(volume_size, volume_size_limit) {
|
||||
// Detect phantom volumes: the .dat was unlinked from disk but is still
|
||||
@@ -1153,7 +1015,7 @@ fn build_heartbeat_with_ec_status(
|
||||
}
|
||||
volumes.push(volume_message);
|
||||
} else if vol.is_expired_long_enough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
|
||||
actions.delete_expired.push((disk_id, vol.id));
|
||||
delete_vids.push(vol.id);
|
||||
should_delete_volume = true;
|
||||
}
|
||||
|
||||
@@ -1184,6 +1046,16 @@ fn build_heartbeat_with_ec_status(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for vid in delete_vids {
|
||||
let _ = loc.delete_volume(vid, false, false);
|
||||
}
|
||||
|
||||
for vid in quarantine_vids {
|
||||
if let Some(vol) = loc.find_volume_mut(vid) {
|
||||
vol.set_no_write_or_delete(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update disk size and read-only gauges
|
||||
@@ -1280,7 +1152,7 @@ fn build_heartbeat_with_ec_status(
|
||||
disk_tags,
|
||||
..Default::default()
|
||||
};
|
||||
(heartbeat, volumes, actions)
|
||||
(heartbeat, volumes)
|
||||
}
|
||||
|
||||
fn collect_live_ec_shards(
|
||||
@@ -1713,7 +1585,7 @@ mod tests {
|
||||
|
||||
// What the notify path does: collect a snapshot, send a message of its own.
|
||||
let snapshot =
|
||||
build_heartbeat_with_ec_status(&test_config(), &store, Vec::new(), true, false).1;
|
||||
build_heartbeat_with_ec_status(&test_config(), &mut store, Vec::new(), true, false).1;
|
||||
assert_eq!(snapshot.len(), 3);
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
@@ -1906,7 +1778,7 @@ mod tests {
|
||||
1.0
|
||||
);
|
||||
|
||||
assert!(store.unmount_volume(VolumeId(21)).unwrap());
|
||||
assert!(store.unmount_volume(VolumeId(21)));
|
||||
build_heartbeat(&test_config(), &mut store);
|
||||
|
||||
assert_eq!(
|
||||
@@ -1977,8 +1849,6 @@ mod tests {
|
||||
|
||||
let shard_path = format!("{}/ec_metrics_case_27.ec00", dir);
|
||||
std::fs::write(&shard_path, b"ec-shard").unwrap();
|
||||
// An EC volume needs its .ecx to mount.
|
||||
std::fs::write(format!("{}/ec_metrics_case_27.ecx", dir), [0u8; 16]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(VolumeId(27), "ec_metrics_case", &[0], "")
|
||||
.unwrap();
|
||||
@@ -2023,8 +1893,6 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(format!("{}/expired_heartbeat_ec_31.ec00", dir), b"expired").unwrap();
|
||||
// An EC volume needs its .ecx to mount.
|
||||
std::fs::write(format!("{}/expired_heartbeat_ec_31.ecx", dir), [0u8; 16]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(VolumeId(31), "expired_heartbeat_ec", &[0], "")
|
||||
.unwrap();
|
||||
@@ -2140,235 +2008,6 @@ mod tests {
|
||||
assert!(volume.is_no_write_or_delete());
|
||||
}
|
||||
|
||||
// The pass only reads the store, so it must not shut out the readers that
|
||||
// serve traffic while it stats every volume.
|
||||
#[tokio::test]
|
||||
async fn test_heartbeat_collection_leaves_the_store_readable() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
|
||||
store.id = "heartbeat-read-phase-park".to_string();
|
||||
let state = test_state_with_store(store);
|
||||
|
||||
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
|
||||
read_phase_hook::arm(
|
||||
read_phase_hook::Point::VolumePass,
|
||||
"heartbeat-read-phase-park",
|
||||
entered_tx,
|
||||
release_rx,
|
||||
);
|
||||
let collection = {
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move {
|
||||
off_runtime(&test_config(), &state, collect_heartbeat_with_snapshot).await
|
||||
})
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(10), entered_rx)
|
||||
.await
|
||||
.expect("the pass never reached its read phase")
|
||||
.unwrap();
|
||||
|
||||
let readable = state.store.try_read().is_ok();
|
||||
drop(release_tx);
|
||||
let (heartbeat, volumes) = collection.await.unwrap().unwrap();
|
||||
|
||||
assert!(readable, "a parked heartbeat pass shut out store readers");
|
||||
assert_eq!(heartbeat.volumes.len(), 2);
|
||||
assert_eq!(volumes.len(), 2);
|
||||
}
|
||||
|
||||
// What the read pass decided on can go stale before the write lock is
|
||||
// taken: each action must re-check its target, not act on whatever now
|
||||
// holds the id.
|
||||
#[test]
|
||||
fn test_volume_actions_skip_volumes_changed_since_the_read_pass() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
8,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store.volume_size_limit.store(1, Ordering::Relaxed);
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
for id in [61, 62, 63] {
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(id),
|
||||
DiskType::HardDrive,
|
||||
&VolumeSpec {
|
||||
collection: "stale_action_case",
|
||||
ttl: Some(crate::storage::needle::ttl::TTL::read("20m").unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let (_, volume) = store.find_volume_mut(VolumeId(id)).unwrap();
|
||||
volume.set_last_io_error_for_test(None);
|
||||
volume.set_last_modified_ts_for_test(now.saturating_sub(60 * 60));
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(volume.dat_path())
|
||||
.unwrap()
|
||||
.set_len((crate::storage::super_block::SUPER_BLOCK_SIZE + 1) as u64)
|
||||
.unwrap();
|
||||
}
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(64),
|
||||
DiskType::HardDrive,
|
||||
&VolumeSpec {
|
||||
collection: "stale_action_case",
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let (_, volume) = store.find_volume_mut(VolumeId(64)).unwrap();
|
||||
volume.set_last_io_error_for_test(Some("input/output error"));
|
||||
|
||||
let (heartbeat, _, actions) =
|
||||
build_heartbeat_with_ec_status(&test_config(), &store, Vec::new(), true, true);
|
||||
assert!(heartbeat.volumes.is_empty());
|
||||
assert_eq!(actions.delete_expired.len(), 3);
|
||||
assert_eq!(actions.quarantine, vec![(0, VolumeId(64))]);
|
||||
|
||||
// Between the phases: 61 is deleted by someone else, 62 and 64 are
|
||||
// replaced by fresh copies under the same ids; 63 is left alone.
|
||||
store
|
||||
.delete_volume(VolumeId(61), false, false, false)
|
||||
.unwrap();
|
||||
for id in [62, 64] {
|
||||
store
|
||||
.delete_volume(VolumeId(id), false, false, false)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(id),
|
||||
DiskType::HardDrive,
|
||||
&VolumeSpec {
|
||||
collection: "stale_action_case",
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
apply_volume_actions_to(&mut store, actions);
|
||||
|
||||
assert!(!store.has_volume(VolumeId(61)));
|
||||
assert!(store.has_volume(VolumeId(62)), "a fresh copy was deleted");
|
||||
assert!(
|
||||
!store.has_volume(VolumeId(63)),
|
||||
"the expired volume survived"
|
||||
);
|
||||
let (_, fresh) = store.find_volume(VolumeId(64)).unwrap();
|
||||
assert!(
|
||||
!fresh.is_no_write_or_delete(),
|
||||
"a fresh copy was quarantined"
|
||||
);
|
||||
}
|
||||
|
||||
// A shard mounted after the EC phase is held when the volume list is
|
||||
// taken; reporting "no EC shards" alongside it would clear it on the master.
|
||||
#[tokio::test]
|
||||
async fn test_ec_shard_mounted_after_the_ec_phase_is_not_reported_absent() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
let mut store = reporting_store(dir, 1);
|
||||
store.id = "heartbeat-ec-mount-between-passes".to_string();
|
||||
let state = test_state_with_store(store);
|
||||
std::fs::write(format!("{}/ec_mount_race_73.ec00", dir), b"shard").unwrap();
|
||||
std::fs::write(format!("{}/ec_mount_race_73.ecx", dir), [0u8; 16]).unwrap();
|
||||
|
||||
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
|
||||
read_phase_hook::arm(
|
||||
read_phase_hook::Point::BeforeVolumePass,
|
||||
"heartbeat-ec-mount-between-passes",
|
||||
entered_tx,
|
||||
release_rx,
|
||||
);
|
||||
let collection = {
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move {
|
||||
off_runtime(&test_config(), &state, collect_heartbeat_with_snapshot).await
|
||||
})
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(10), entered_rx)
|
||||
.await
|
||||
.expect("the pass never finished its EC phase")
|
||||
.unwrap();
|
||||
|
||||
state.store.write().unwrap().locations[0]
|
||||
.mount_ec_shards(VolumeId(73), "ec_mount_race", &[0], "")
|
||||
.unwrap();
|
||||
drop(release_tx);
|
||||
let (heartbeat, _) = collection.await.unwrap().unwrap();
|
||||
|
||||
assert!(
|
||||
!heartbeat.has_no_ec_shards,
|
||||
"a mounted EC shard was reported absent"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expired_ec_volume_gone_before_removal_is_not_reported_deleted() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
8,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
for id in [71, 72] {
|
||||
std::fs::write(format!("{}/stale_ec_case_{}.ec00", dir, id), b"expired").unwrap();
|
||||
std::fs::write(format!("{}/stale_ec_case_{}.ecx", dir, id), [0u8; 16]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(VolumeId(id), "stale_ec_case", &[0], "")
|
||||
.unwrap();
|
||||
store
|
||||
.find_ec_volume_mut(VolumeId(id))
|
||||
.unwrap()
|
||||
.expire_at_sec = 1;
|
||||
}
|
||||
|
||||
let (ec_shards, mut expired) = store.find_expired_ec_volumes();
|
||||
expired.sort();
|
||||
assert!(ec_shards.is_empty());
|
||||
assert_eq!(expired, vec![(0, VolumeId(71)), (0, VolumeId(72))]);
|
||||
|
||||
// Between the phases: 71 is destroyed by someone else, 72 is remounted
|
||||
// without an expiry.
|
||||
store.remove_ec_volume(VolumeId(71)).unwrap().destroy();
|
||||
store.remove_ec_volume(VolumeId(72)).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(VolumeId(72), "stale_ec_case", &[0], "")
|
||||
.unwrap();
|
||||
let (deleted, still_held) = store.remove_expired_ec_volumes(expired);
|
||||
|
||||
assert!(deleted.is_empty());
|
||||
assert_eq!(still_held.len(), 1);
|
||||
assert_eq!(still_held[0].id, 72);
|
||||
assert!(store.has_ec_volume(VolumeId(72)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_includes_remote_storage_name_and_key() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
@@ -2555,8 +2194,6 @@ mod tests {
|
||||
let previous = collect_ec_shard_delta_messages(&store);
|
||||
|
||||
std::fs::write(format!("{}/ec_delta_case_81.ec00", dir), b"delta").unwrap();
|
||||
// An EC volume needs its .ecx to mount.
|
||||
std::fs::write(format!("{}/ec_delta_case_81.ecx", dir), [0u8; 16]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(VolumeId(81), "ec_delta_case", &[0], "")
|
||||
.unwrap();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use tonic::Status;
|
||||
|
||||
use crate::remote_storage::s3_tier::TierError;
|
||||
use crate::storage::volume::VolumeError;
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -24,9 +23,7 @@ impl From<VolumeError> for Status {
|
||||
fn from(err: VolumeError) -> Self {
|
||||
let message = err.to_string();
|
||||
match err {
|
||||
VolumeError::NotFound
|
||||
| VolumeError::VolumeNotFound(_)
|
||||
| VolumeError::Tier(TierError::NotFound(_)) => Status::not_found(message),
|
||||
VolumeError::NotFound | VolumeError::VolumeNotFound(_) => Status::not_found(message),
|
||||
VolumeError::ReadOnly | VolumeError::NotEmpty => Status::failed_precondition(message),
|
||||
VolumeError::InsufficientSpace { .. } => Status::resource_exhausted(message),
|
||||
VolumeError::AlreadyExists => Status::already_exists(message),
|
||||
@@ -80,27 +77,6 @@ mod tests {
|
||||
);
|
||||
assert_eq!(code(VolumeError::AlreadyExists), Code::AlreadyExists);
|
||||
assert_eq!(code(VolumeError::NotInitialized), Code::Internal);
|
||||
assert_eq!(
|
||||
code(TierError::NotFound("gone".into()).into()),
|
||||
Code::NotFound
|
||||
);
|
||||
for tier in [
|
||||
TierError::Io("io".into()),
|
||||
TierError::RuntimeUnavailable("rt".into()),
|
||||
TierError::Aborted("bye".into()),
|
||||
] {
|
||||
assert_eq!(code(tier.into()), Code::Internal);
|
||||
}
|
||||
|
||||
let status = status_with_context(
|
||||
"backend s3.default copy file /data/1.dat",
|
||||
TierError::NotFound("failed to head object k: NotFound".into()).into(),
|
||||
);
|
||||
assert_eq!(status.code(), Code::NotFound);
|
||||
assert_eq!(
|
||||
status.message(),
|
||||
"backend s3.default copy file /data/1.dat: failed to head object k: NotFound"
|
||||
);
|
||||
|
||||
let status = status_with_context(
|
||||
"compact volume 7",
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::storage::erasure_coding::ec_shard::{
|
||||
DATA_SHARDS_COUNT, ERASURE_CODING_LARGE_BLOCK_SIZE, ERASURE_CODING_SMALL_BLOCK_SIZE,
|
||||
EcVolumeShard, ShardId,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_volume::{EcVolume, is_usable_ecx_file};
|
||||
use crate::storage::erasure_coding::ec_volume::EcVolume;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
use crate::storage::types::*;
|
||||
@@ -479,13 +479,6 @@ impl DiskLocation {
|
||||
if self.idx_directory != self.directory {
|
||||
remove_bitrot_sidecars(&idx_base)?;
|
||||
}
|
||||
|
||||
// Staged 2PC generations (<base>.ecNN.v<N>, versioned .ecx/.ecj/.vif)
|
||||
// belong to this volume's EC state too; leaving them orphans the files.
|
||||
crate::storage::erasure_coding::ec_shard::remove_ec_generation_files(&base, 0)?;
|
||||
if self.idx_directory != self.directory {
|
||||
crate::storage::erasure_coding::ec_shard::remove_ec_generation_files(&idx_base, 0)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -605,20 +598,13 @@ impl DiskLocation {
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
only_empty: bool,
|
||||
only_garbage: bool,
|
||||
keep_remote_data: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
// Refuse before removing: a refused destroy must leave it mounted.
|
||||
if let Some(v) = self.volumes.get(&vid)
|
||||
&& v.is_compacting()
|
||||
{
|
||||
return Err(v.compacting_error());
|
||||
}
|
||||
if let Some(mut v) = self.volumes.remove(&vid) {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&v.collection, "volume"])
|
||||
.dec();
|
||||
v.destroy(only_empty, only_garbage, keep_remote_data)?;
|
||||
v.destroy(only_empty, keep_remote_data)?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(VolumeError::NotFound)
|
||||
@@ -639,7 +625,7 @@ impl DiskLocation {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&v.collection, "volume"])
|
||||
.dec();
|
||||
if let Err(e) = v.destroy(false, false, false) {
|
||||
if let Err(e) = v.destroy(false, false) {
|
||||
warn!(volume_id = vid.0, error = %e, "delete collection: failed to destroy volume");
|
||||
}
|
||||
}
|
||||
@@ -793,17 +779,21 @@ impl DiskLocation {
|
||||
/// Mirrors `DiskLocation.HasEcxFileOnDisk` in
|
||||
/// `weed/storage/disk_location_ec.go`. Skips entries that are
|
||||
/// directories so a stray dir named `<collection>_<vid>.ecx` doesn't
|
||||
/// register as a present index file. A 0-byte `.ecx` is a corrupt stub
|
||||
/// left by a failed EC distribute copy; it must not steer placement
|
||||
/// toward this disk, so it counts as absent (Go requires `Size() > 0`).
|
||||
/// register as a present index file.
|
||||
pub fn has_ecx_file_on_disk(&self, collection: &str, vid: VolumeId) -> bool {
|
||||
let idx_base = volume_file_name(&self.idx_directory, collection, vid);
|
||||
if is_usable_ecx_file(&format!("{}.ecx", idx_base)) {
|
||||
let idx_path = format!("{}.ecx", idx_base);
|
||||
if let Ok(meta) = fs::metadata(&idx_path)
|
||||
&& !meta.is_dir()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if self.idx_directory != self.directory {
|
||||
let data_base = volume_file_name(&self.directory, collection, vid);
|
||||
if is_usable_ecx_file(&format!("{}.ecx", data_base)) {
|
||||
let data_path = format!("{}.ecx", data_base);
|
||||
if let Ok(meta) = fs::metadata(&data_path)
|
||||
&& !meta.is_dir()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -815,20 +805,6 @@ impl DiskLocation {
|
||||
self.ec_volumes.remove(&vid)
|
||||
}
|
||||
|
||||
/// Drop the in-memory EC volume for vid and close its descriptors without
|
||||
/// deleting files, so a following unlink frees the inodes instead of
|
||||
/// leaving open fds serving the old bytes. Mirrors Go's unloadEcVolume.
|
||||
pub fn unload_ec_volume(&mut self, vid: VolumeId) {
|
||||
if let Some(mut ec_vol) = self.ec_volumes.remove(&vid) {
|
||||
for _ in 0..ec_vol.shard_count() {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&ec_vol.collection, "ec_shards"])
|
||||
.dec();
|
||||
}
|
||||
ec_vol.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Mount EC shards for a volume on this location.
|
||||
///
|
||||
/// `source_disk_type` is the source volume's disk type carried on the
|
||||
@@ -1761,7 +1737,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(loc.volumes_len(), 2);
|
||||
|
||||
loc.delete_volume(VolumeId(1), false, false, false).unwrap();
|
||||
loc.delete_volume(VolumeId(1), false, false).unwrap();
|
||||
assert_eq!(loc.volumes_len(), 1);
|
||||
assert!(loc.find_volume(VolumeId(1)).is_none());
|
||||
}
|
||||
@@ -1814,34 +1790,6 @@ mod tests {
|
||||
assert!(loc.find_volume(VolumeId(3)).is_some());
|
||||
}
|
||||
|
||||
/// A 0-byte `.ecx` is the stub a failed EC distribute copy leaves behind.
|
||||
/// Go's HasEcxFileOnDisk requires Size() > 0 so the stub cannot pin
|
||||
/// placement to a disk that has no usable index.
|
||||
#[test]
|
||||
fn test_has_ecx_file_on_disk_ignores_zero_byte_stub() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let data = tmp.path().join("data");
|
||||
let idx = tmp.path().join("idx");
|
||||
fs::create_dir_all(&data).unwrap();
|
||||
fs::create_dir_all(&idx).unwrap();
|
||||
let loc = DiskLocation::new(
|
||||
data.to_str().unwrap(),
|
||||
idx.to_str().unwrap(),
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
fs::write(idx.join("pics_7.ecx"), b"").unwrap();
|
||||
assert!(!loc.has_ecx_file_on_disk("pics", VolumeId(7)));
|
||||
|
||||
// A real index in the data dir still counts, stub or no stub.
|
||||
fs::write(data.join("pics_7.ecx"), [0u8; 16]).unwrap();
|
||||
assert!(loc.has_ecx_file_on_disk("pics", VolumeId(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_disk_location_delete_collection_removes_ec_volumes() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
@@ -1858,8 +1806,6 @@ mod tests {
|
||||
|
||||
let shard_path = format!("{}/pics_7.ec00", dir);
|
||||
std::fs::write(&shard_path, b"ec-shard").unwrap();
|
||||
// An EC volume needs its .ecx to mount.
|
||||
std::fs::write(format!("{}/pics_7.ecx", dir), [0u8; 16]).unwrap();
|
||||
|
||||
loc.mount_ec_shards(VolumeId(7), "pics", &[0], "").unwrap();
|
||||
assert!(loc.has_ec_volume(VolumeId(7)));
|
||||
@@ -1897,7 +1843,6 @@ mod tests {
|
||||
// mount_ec_shards with source_disk_type="ssd" — simulating the
|
||||
// VolumeEcShardsMount RPC path.
|
||||
std::fs::write(format!("{}/pics_7.ec00", dir), b"ec-shard").unwrap();
|
||||
std::fs::write(format!("{}/pics_7.ecx", dir), [0u8; 16]).unwrap();
|
||||
loc.mount_ec_shards(VolumeId(7), "pics", &[0], "ssd")
|
||||
.unwrap();
|
||||
{
|
||||
@@ -1997,7 +1942,6 @@ mod tests {
|
||||
// A collection name unique to this test: the gauge is process-global
|
||||
// and sibling tests running in parallel touch other labels.
|
||||
std::fs::write(format!("{}/dupmount_11.ec00", dir), b"shard bytes").unwrap();
|
||||
std::fs::write(format!("{}/dupmount_11.ecx", dir), [0u8; 16]).unwrap();
|
||||
let gauge = crate::metrics::VOLUME_GAUGE.with_label_values(&["dupmount", "ec_shards"]);
|
||||
let before = gauge.get();
|
||||
|
||||
|
||||
@@ -195,104 +195,6 @@ impl ShardBits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the generation of a 2PC-staged `<base>.v<N>` file: `None` means the
|
||||
/// name is not a generation file of `base`.
|
||||
pub fn ec_file_generation(name: &str, base: &str) -> Option<u32> {
|
||||
let suffix = name.strip_prefix(&format!("{}.v", base))?;
|
||||
match suffix.parse::<u32>() {
|
||||
Ok(g) if g > 0 => Some(g),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes 2PC generation files staged under `base`:
|
||||
/// `<base>.ecNN.v<N>`, `<base>.ecx.v<N>`, `<base>.ecj.v<N>`, `<base>.ecsum.v<N>`
|
||||
/// and `<base>.vif.v<N>`. `generations_older_than == 0` removes every
|
||||
/// generation; otherwise only generations strictly below it. Returns the
|
||||
/// first real removal failure. Mirrors Go's `RemoveEcGenerationFiles`.
|
||||
pub fn remove_ec_generation_files(base: &str, generations_older_than: u32) -> io::Result<()> {
|
||||
let path = std::path::Path::new(base);
|
||||
let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let ec_prefix = format!("{}.ec", fname.to_string_lossy());
|
||||
let vif_name = format!("{}.vif", fname.to_string_lossy());
|
||||
let mut first_err: Option<io::Error> = None;
|
||||
let mut record = |res: io::Result<()>| {
|
||||
if let Err(e) = res
|
||||
&& first_err.is_none()
|
||||
{
|
||||
first_err = Some(e);
|
||||
}
|
||||
};
|
||||
match fs::read_dir(parent) {
|
||||
Ok(entries) => {
|
||||
for entry in entries {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(e) => {
|
||||
// A skipped entry means an incomplete sweep; report it
|
||||
// instead of pretending the cleanup finished.
|
||||
record(Err(e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Some((artifact, _)) = name.rsplit_once(".v") else {
|
||||
continue;
|
||||
};
|
||||
if artifact != vif_name && !artifact.starts_with(&ec_prefix) {
|
||||
continue;
|
||||
}
|
||||
let Some(generation) = ec_file_generation(&name, artifact) else {
|
||||
continue;
|
||||
};
|
||||
if generations_older_than > 0 && generation >= generations_older_than {
|
||||
continue;
|
||||
}
|
||||
record(match fs::remove_file(entry.path()) {
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => record(Err(e)),
|
||||
Err(_) => {}
|
||||
}
|
||||
match first_err {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes every staged generation `<shard_file>.v<N>` of one shard file.
|
||||
/// Returns true when at least one generation file was removed.
|
||||
pub fn remove_ec_shard_generations(shard_file: &str) -> io::Result<bool> {
|
||||
let path = std::path::Path::new(shard_file);
|
||||
let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let fname = fname.to_string_lossy().into_owned();
|
||||
let mut removed = false;
|
||||
match fs::read_dir(parent) {
|
||||
Ok(entries) => {
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if ec_file_generation(&name, &fname).is_some() {
|
||||
match fs::remove_file(entry.path()) {
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
|
||||
_ => removed = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
|
||||
Err(_) => {}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -383,26 +383,8 @@ pub fn validate_block_size(block_size: i64) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Size of the `.ecx` at `path`, or `None` when it is absent or a directory.
|
||||
/// Mirrors Go's `statEcxSize`.
|
||||
pub(crate) fn ecx_file_size(path: &str) -> Option<u64> {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) if !meta.is_dir() => Some(meta.len()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is an `.ecx` that can steer placement, ownership or a copy:
|
||||
/// a regular file with content. A 0-byte `.ecx` is what a failed EC distribute
|
||||
/// copy leaves behind, and Go treats it as absent at every such decision
|
||||
/// (`HasEcxFileOnDisk`, `findEcxIdxDirForVolume`, `indexEcxOwners`) so the scan
|
||||
/// moves on to a sibling disk that may hold a valid index.
|
||||
pub(crate) fn is_usable_ecx_file(path: &str) -> bool {
|
||||
ecx_file_size(path).is_some_and(|size| size > 0)
|
||||
}
|
||||
|
||||
impl EcVolume {
|
||||
/// Create a new EcVolume. Opens the .ecx index (required) and the .ecj journal.
|
||||
/// Create a new EcVolume. Loads .ecx index and .ecj journal if present.
|
||||
pub fn new(
|
||||
dir: &str,
|
||||
dir_idx: &str,
|
||||
@@ -485,62 +467,27 @@ impl EcVolume {
|
||||
|
||||
// Open .ecx file (sorted index) in read/write mode for in-place deletion marking.
|
||||
// Matches Go which opens ecx for writing via MarkNeedleDeleted.
|
||||
//
|
||||
// Resolve it the way Go's NewEcVolume does: prefer a non-empty copy,
|
||||
// the one co-located with the shard data first, then the caller's
|
||||
// index directory — either the shared -dir.idx dir or a sibling disk
|
||||
// that owns the .ecx when this disk holds only a 0-byte stub left by an
|
||||
// interrupted copy. A 0-byte .ecx is also a legitimate empty index, so
|
||||
// it yields only to a non-empty copy elsewhere, never to a mere
|
||||
// absence. No .ecx at all fails the mount with NotFound (Go wraps
|
||||
// os.ErrNotExist): an EcVolume without an index would advertise shards
|
||||
// that no read can ever serve.
|
||||
let local_ecx = format!(
|
||||
"{}.ecx",
|
||||
crate::storage::volume::volume_file_name(dir, collection, volume_id)
|
||||
);
|
||||
let shared_ecx = vol.ecx_file_name();
|
||||
let local_size = ecx_file_size(&local_ecx);
|
||||
let shared_size = if dir_idx != dir {
|
||||
ecx_file_size(&shared_ecx)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let use_local = match (local_size, shared_size) {
|
||||
(Some(n), _) if n > 0 => true,
|
||||
(_, Some(n)) if n > 0 => {
|
||||
tracing::debug!(
|
||||
let ecx_path = vol.ecx_file_name();
|
||||
if std::path::Path::new(&ecx_path).exists() {
|
||||
let file = open_volume_file(OpenOptions::new().read(true).write(true), &ecx_path)?;
|
||||
vol.ecx_file_size = file.metadata()?.len() as i64;
|
||||
vol.ecx_file = Some(file);
|
||||
} else if dir_idx != dir {
|
||||
// Fall back to data directory if .ecx was created before -dir.idx was configured
|
||||
let data_base = crate::storage::volume::volume_file_name(dir, collection, volume_id);
|
||||
let fallback_ecx = format!("{}.ecx", data_base);
|
||||
if std::path::Path::new(&fallback_ecx).exists() {
|
||||
tracing::info!(
|
||||
volume_id = volume_id.0,
|
||||
"ecx not local at {}, using {}",
|
||||
local_ecx,
|
||||
shared_ecx
|
||||
"ecx file not found in idx dir, falling back to data dir"
|
||||
);
|
||||
false
|
||||
let file =
|
||||
open_volume_file(OpenOptions::new().read(true).write(true), &fallback_ecx)?;
|
||||
vol.ecx_file_size = file.metadata()?.len() as i64;
|
||||
vol.ecx_file = Some(file);
|
||||
vol.ecx_actual_dir = dir.to_string();
|
||||
}
|
||||
// Only 0-byte copies exist: an empty index, local first.
|
||||
(Some(_), _) => true,
|
||||
(None, Some(_)) => false,
|
||||
(None, None) => {
|
||||
let tried = if dir_idx != dir {
|
||||
format!("{} (or {})", local_ecx, shared_ecx)
|
||||
} else {
|
||||
local_ecx
|
||||
};
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("cannot open ec volume index {}: not found", tried),
|
||||
));
|
||||
}
|
||||
};
|
||||
let ecx_path = if use_local {
|
||||
vol.ecx_actual_dir = dir.to_string();
|
||||
local_ecx
|
||||
} else {
|
||||
shared_ecx
|
||||
};
|
||||
let file = open_volume_file(OpenOptions::new().read(true).write(true), &ecx_path)?;
|
||||
vol.ecx_file_size = file.metadata()?.len() as i64;
|
||||
vol.ecx_file = Some(file);
|
||||
}
|
||||
|
||||
// Open .ecj file (deletion journal) — use ecx_actual_dir for consistency.
|
||||
// Note: Go does NOT replay .ecj into .ecx at volume load (RebuildEcxFile
|
||||
@@ -1917,63 +1864,6 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// Go's NewEcVolume fails with os.ErrNotExist when neither directory has an
|
||||
/// `.ecx`. Mounting anyway advertises shards every read then fails on with
|
||||
/// "ecx file not open", and zeroes the size `add_shard`'s 0-byte guard needs.
|
||||
#[test]
|
||||
fn test_new_without_ecx_is_not_found() {
|
||||
let data = TempDir::new().unwrap();
|
||||
let idx = TempDir::new().unwrap();
|
||||
let (dir, dir_idx) = (data.path().to_str().unwrap(), idx.path().to_str().unwrap());
|
||||
std::fs::write(format!("{}/7.ec00", dir), b"shard").unwrap();
|
||||
|
||||
for idx_dir in [dir, dir_idx] {
|
||||
let err = EcVolume::new(dir, idx_dir, "", VolumeId(7))
|
||||
.err()
|
||||
.expect("an EC volume without an .ecx must not mount");
|
||||
assert_eq!(err.kind(), io::ErrorKind::NotFound, "{}", err);
|
||||
}
|
||||
}
|
||||
|
||||
/// A 0-byte `.ecx` stub left by an interrupted copy yields to a non-empty
|
||||
/// copy in the other directory, whichever side the stub is on.
|
||||
#[test]
|
||||
fn test_new_prefers_non_empty_ecx_over_zero_byte_stub() {
|
||||
for stub_in_idx_dir in [true, false] {
|
||||
let data = TempDir::new().unwrap();
|
||||
let idx = TempDir::new().unwrap();
|
||||
let (dir, dir_idx) = (data.path().to_str().unwrap(), idx.path().to_str().unwrap());
|
||||
let (stub_dir, valid_dir) = if stub_in_idx_dir {
|
||||
(dir_idx, dir)
|
||||
} else {
|
||||
(dir, dir_idx)
|
||||
};
|
||||
std::fs::write(format!("{}/7.ecx", stub_dir), b"").unwrap();
|
||||
std::fs::write(
|
||||
format!("{}/7.ecx", valid_dir),
|
||||
vec![0u8; NEEDLE_MAP_ENTRY_SIZE],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vol = EcVolume::new(dir, dir_idx, "", VolumeId(7)).unwrap();
|
||||
assert_eq!(vol.ecx_actual_dir(), valid_dir);
|
||||
assert_eq!(vol.ecx_file_size, NEEDLE_MAP_ENTRY_SIZE as i64);
|
||||
}
|
||||
}
|
||||
|
||||
/// With no other copy a 0-byte `.ecx` is a legitimate empty index (a volume
|
||||
/// whose needles were all deleted before encoding) and still mounts, as in Go.
|
||||
#[test]
|
||||
fn test_new_accepts_lone_zero_byte_ecx_as_empty_index() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
std::fs::write(format!("{}/7.ecx", dir), b"").unwrap();
|
||||
|
||||
let vol = EcVolume::new(dir, dir, "", VolumeId(7)).unwrap();
|
||||
assert_eq!(vol.ecx_file_size, 0);
|
||||
assert!(!is_usable_ecx_file(&vol.ecx_file_name()));
|
||||
}
|
||||
|
||||
/// `destroy()` must remove co-located `.ecsum` sidecars (Go Destroy parity).
|
||||
/// Without this, `collection.delete` leaves orphaned bitrot files that
|
||||
/// inflate EC-health scanners after the shards are gone.
|
||||
|
||||
@@ -21,26 +21,12 @@ where
|
||||
let mut buf = vec![0u8; NEEDLE_MAP_ENTRY_SIZE * ROWS_TO_READ];
|
||||
|
||||
loop {
|
||||
// Fill the batch before decoding: `read` may return a count that is
|
||||
// not a multiple of the entry size, and a split entry would misalign
|
||||
// every later row. Go is immune: `ReadAt` fills or errors.
|
||||
let mut count = 0;
|
||||
let mut eof = false;
|
||||
while count < buf.len() {
|
||||
match reader.read(&mut buf[count..]) {
|
||||
Ok(0) => {
|
||||
eof = true;
|
||||
break;
|
||||
}
|
||||
Ok(n) => count += n,
|
||||
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => {
|
||||
eof = true;
|
||||
break;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
let count = match reader.read(&mut buf) {
|
||||
Ok(0) => return Ok(()),
|
||||
Ok(n) => n,
|
||||
Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(()),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let mut i = 0;
|
||||
while i + NEEDLE_MAP_ENTRY_SIZE <= count {
|
||||
@@ -48,11 +34,6 @@ where
|
||||
f(key, offset, size)?;
|
||||
i += NEEDLE_MAP_ENTRY_SIZE;
|
||||
}
|
||||
|
||||
// A trailing partial entry at EOF is ignored, as Go does on `io.EOF`.
|
||||
if eof {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,111 +177,6 @@ mod tests {
|
||||
data
|
||||
}
|
||||
|
||||
/// Reader that hands back at most `chunk` bytes per `read`. 7 is coprime
|
||||
/// with the 17-byte entry size, so nearly every read ends mid-entry. With
|
||||
/// `interrupts`, every other call fails with `ErrorKind::Interrupted`.
|
||||
struct ShortReader {
|
||||
inner: Cursor<Vec<u8>>,
|
||||
chunk: usize,
|
||||
interrupts: bool,
|
||||
interrupt_next: bool,
|
||||
}
|
||||
|
||||
impl ShortReader {
|
||||
fn new(data: Vec<u8>, interrupts: bool) -> Self {
|
||||
ShortReader {
|
||||
inner: Cursor::new(data),
|
||||
chunk: 7,
|
||||
interrupts,
|
||||
interrupt_next: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for ShortReader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if self.interrupt_next {
|
||||
self.interrupt_next = false;
|
||||
return Err(io::Error::from(io::ErrorKind::Interrupted));
|
||||
}
|
||||
self.interrupt_next = self.interrupts;
|
||||
let n = buf.len().min(self.chunk);
|
||||
self.inner.read(&mut buf[..n])
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for ShortReader {
|
||||
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||
self.inner.seek(pos)
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_all<R: Read + Seek>(reader: &mut R, start_from: u64) -> Vec<(NeedleId, i64, Size)> {
|
||||
let mut collected = Vec::new();
|
||||
walk_index_file(reader, start_from, |key, offset, size| {
|
||||
collected.push((key, offset.to_actual_offset(), size));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
collected
|
||||
}
|
||||
|
||||
/// More than one ROWS_TO_READ batch, so the walk crosses a buffer refill.
|
||||
fn many_entries() -> Vec<(NeedleId, Offset, Size)> {
|
||||
(0..(ROWS_TO_READ as u64 * 2 + 37))
|
||||
.map(|i| {
|
||||
(
|
||||
NeedleId(i * 7 + 1),
|
||||
Offset::from_actual_offset(i as i64 * 128),
|
||||
Size(i as i32 + 1),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_walk_index_file_short_reads_keep_alignment() {
|
||||
let data = idx_bytes(&many_entries());
|
||||
let expected = walk_all(&mut Cursor::new(data.clone()), 0);
|
||||
assert_eq!(expected.len(), ROWS_TO_READ * 2 + 37);
|
||||
|
||||
let mut short = ShortReader::new(data, false);
|
||||
assert_eq!(walk_all(&mut short, 0), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_walk_index_file_retries_interrupted_reads() {
|
||||
let data = idx_bytes(&many_entries());
|
||||
let expected = walk_all(&mut Cursor::new(data.clone()), 0);
|
||||
|
||||
let mut short = ShortReader::new(data, true);
|
||||
assert_eq!(walk_all(&mut short, 0), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_walk_index_file_short_reads_start_from() {
|
||||
let data = idx_bytes(&many_entries());
|
||||
let expected = walk_all(&mut Cursor::new(data.clone()), 0);
|
||||
|
||||
let start = ROWS_TO_READ as u64 + 5;
|
||||
let mut short = ShortReader::new(data, false);
|
||||
assert_eq!(walk_all(&mut short, start), expected[start as usize..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_walk_index_file_ignores_trailing_partial_entry() {
|
||||
// A torn final entry is dropped without an error, as Go does on io.EOF.
|
||||
let entries = many_entries();
|
||||
let mut data = idx_bytes(&entries);
|
||||
data.extend_from_slice(&[0xAB; NEEDLE_MAP_ENTRY_SIZE - 1]);
|
||||
|
||||
let expected = walk_all(&mut Cursor::new(idx_bytes(&entries)), 0);
|
||||
assert_eq!(walk_all(&mut Cursor::new(data.clone()), 0), expected);
|
||||
|
||||
let mut short = ShortReader::new(data, false);
|
||||
assert_eq!(walk_all(&mut short, 0), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_index_file_clean() {
|
||||
let data = idx_bytes(&[
|
||||
|
||||
@@ -247,8 +247,6 @@ impl CompactNeedleMap {
|
||||
pub fn load_from_idx<R: Read + Seek>(reader: &mut R, version: Version) -> io::Result<Self> {
|
||||
let mut nm = CompactNeedleMap::new();
|
||||
idx::walk_index_file(reader, 0, |key, offset, size| {
|
||||
// A read-only load attaches no writer, so this is its only size.
|
||||
nm.idx_file_offset += NEEDLE_MAP_ENTRY_SIZE as u64;
|
||||
nm.metric.maybe_set_max_needle_end(offset, size, version);
|
||||
if offset.is_zero() || size.is_deleted() {
|
||||
nm.delete_from_map(key);
|
||||
@@ -1388,18 +1386,6 @@ impl NeedleMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Skew the live file count away from what the `.idx` holds, so tests
|
||||
/// can build a volume whose reported count disagrees with a reload.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn add_file_count_for_test(&self, delta: i64) {
|
||||
let metric = match self {
|
||||
NeedleMap::InMemory(nm) => &nm.metric,
|
||||
NeedleMap::Redb(nm) => &nm.metric,
|
||||
NeedleMap::SortedFile(_) => panic!("sorted-file needle maps are read-only"),
|
||||
};
|
||||
metric.file_count.fetch_add(delta, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Largest (offset + actual size) seen during the load walk; 0 if the
|
||||
/// map is empty. Used at volume load to detect .idx entries that
|
||||
/// reference past the end of .dat (issue #8928) without a second scan.
|
||||
|
||||
@@ -13,12 +13,12 @@ use crate::config::MinFreeSpace;
|
||||
use crate::pb::master_pb;
|
||||
use crate::storage::disk_location::DiskLocation;
|
||||
use crate::storage::erasure_coding::ec_shard::{EcVolumeShard, MAX_SHARD_COUNT, ShardId};
|
||||
use crate::storage::erasure_coding::ec_volume::{EcVolume, is_usable_ecx_file};
|
||||
use crate::storage::erasure_coding::ec_volume::EcVolume;
|
||||
use crate::storage::needle::needle::Needle;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume::{CompactionJob, VifVolumeInfo, VolumeError, VolumeSpec};
|
||||
use crate::storage::volume::{VifVolumeInfo, VolumeError, VolumeSpec};
|
||||
|
||||
/// Top-level storage manager containing all disk locations and their volumes.
|
||||
pub struct Store {
|
||||
@@ -225,13 +225,7 @@ impl Store {
|
||||
/// Find a free location matching a predicate.
|
||||
/// Matches Go's Store.FindFreeLocation: picks the matching location with the
|
||||
/// most remaining volume capacity, while skipping low-disk locations.
|
||||
/// `replace_vid` names a volume about to be replaced: the slot it holds on
|
||||
/// a location counts as free there.
|
||||
pub fn find_free_location_predicate<F>(
|
||||
&self,
|
||||
pred: F,
|
||||
replace_vid: Option<VolumeId>,
|
||||
) -> Option<usize>
|
||||
pub fn find_free_location_predicate<F>(&self, pred: F) -> Option<usize>
|
||||
where
|
||||
F: Fn(&DiskLocation) -> bool,
|
||||
{
|
||||
@@ -247,12 +241,8 @@ impl Store {
|
||||
let effective_free = if max == 0 {
|
||||
i64::MAX
|
||||
} else {
|
||||
let mut free_slots = max - loc.volumes_len() as i64;
|
||||
if replace_vid.is_some_and(|vid| loc.find_volume(vid).is_some()) {
|
||||
free_slots += 1;
|
||||
}
|
||||
let free_count =
|
||||
free_slots * DATA_SHARDS_COUNT as i64 - loc.ec_shard_count() as i64;
|
||||
let free_count = (max - loc.volumes_len() as i64) * DATA_SHARDS_COUNT as i64
|
||||
- loc.ec_shard_count() as i64;
|
||||
free_count / DATA_SHARDS_COUNT as i64
|
||||
};
|
||||
if effective_free <= 0 {
|
||||
@@ -405,31 +395,24 @@ impl Store {
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
only_empty: bool,
|
||||
only_garbage: bool,
|
||||
keep_remote_data: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
for loc in &mut self.locations {
|
||||
if loc.find_volume(vid).is_some() {
|
||||
return loc.delete_volume(vid, only_empty, only_garbage, keep_remote_data);
|
||||
return loc.delete_volume(vid, only_empty, keep_remote_data);
|
||||
}
|
||||
}
|
||||
Err(VolumeError::NotFound)
|
||||
}
|
||||
|
||||
/// Unload (unmount) a volume without deleting its files. Refused while
|
||||
/// compacting, since a remount could start a second copy into .cpd.
|
||||
pub fn unmount_volume(&mut self, vid: VolumeId) -> Result<bool, VolumeError> {
|
||||
if let Some((_, v)) = self.find_volume(vid)
|
||||
&& v.is_compacting()
|
||||
{
|
||||
return Err(v.compacting_error());
|
||||
}
|
||||
/// Unload (unmount) a volume without deleting its files.
|
||||
pub fn unmount_volume(&mut self, vid: VolumeId) -> bool {
|
||||
for loc in &mut self.locations {
|
||||
if loc.unload_volume(vid).is_some() {
|
||||
return Ok(true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
false
|
||||
}
|
||||
|
||||
/// Reports whether any local volume or EC shard is currently quarantined
|
||||
@@ -715,15 +698,15 @@ impl Store {
|
||||
vol.read_needle_opt(n, read_deleted)
|
||||
}
|
||||
|
||||
/// Resolve a needle read under this guard, to run after it is released.
|
||||
pub(crate) fn needle_read_plan(
|
||||
/// Read needle metadata and return streaming info for large file reads.
|
||||
pub fn read_volume_needle_stream_info(
|
||||
&self,
|
||||
vid: VolumeId,
|
||||
id: NeedleId,
|
||||
n: &mut Needle,
|
||||
read_deleted: bool,
|
||||
) -> Result<crate::storage::volume::NeedleReadPlan, VolumeError> {
|
||||
) -> Result<crate::storage::volume::NeedleStreamInfo, VolumeError> {
|
||||
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
|
||||
vol.needle_read_plan(id, read_deleted)
|
||||
vol.read_needle_stream_info(n, read_deleted)
|
||||
}
|
||||
|
||||
/// Re-lookup a needle's data-file offset after compaction may have moved it.
|
||||
@@ -922,88 +905,18 @@ impl Store {
|
||||
shard_id: ShardId,
|
||||
source_disk_type: &str,
|
||||
) -> Result<(), VolumeError> {
|
||||
// The .ecx may live on a different disk than the shard being mounted
|
||||
// (ec.balance / ec.rebuild can spread shards across sibling disks), so
|
||||
// look up its owner once and point EcVolume::new at the directory that
|
||||
// really has it — Go's MountEcShards does the same. Without an index
|
||||
// anywhere the mount fails instead of advertising an unreadable shard.
|
||||
let ecx_idx_dir = self.find_ecx_idx_dir_for_volume(collection, vid);
|
||||
// Keep going past a disk that cannot mount the shard: an interrupted
|
||||
// move can leave an unusable copy on one disk and a good one on the
|
||||
// next. Like Go, a NotFound just means "not this disk"; anything else
|
||||
// is collected so an all-disks-fail error names every disk tried.
|
||||
let mut failures: Vec<(String, VolumeError)> = Vec::new();
|
||||
for loc in &mut self.locations {
|
||||
// Check if the shard file exists on this location
|
||||
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
|
||||
if !std::path::Path::new(&shard.file_name()).exists() {
|
||||
continue;
|
||||
}
|
||||
// If this disk owns the .ecx its own idx dir is the right answer;
|
||||
// only a disk without a usable .ecx is pointed at the owner's.
|
||||
let idx_dir = match &ecx_idx_dir {
|
||||
Some(owner_dir)
|
||||
if loc.idx_directory != *owner_dir
|
||||
&& loc.directory != *owner_dir
|
||||
&& !loc.has_ecx_file_on_disk(collection, vid) =>
|
||||
{
|
||||
owner_dir.clone()
|
||||
}
|
||||
_ => loc.idx_directory.clone(),
|
||||
};
|
||||
match loc.mount_ec_shards_with_idx_dir(
|
||||
vid,
|
||||
collection,
|
||||
&[shard_id],
|
||||
&idx_dir,
|
||||
source_disk_type,
|
||||
) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(VolumeError::Io(e)) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => failures.push((loc.directory.clone(), e)),
|
||||
if std::path::Path::new(&shard.file_name()).exists() {
|
||||
loc.mount_ec_shards(vid, collection, &[shard_id], source_disk_type)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if failures.is_empty() {
|
||||
let what = if ecx_idx_dir.is_none() {
|
||||
": no .ecx index found on any local disk"
|
||||
} else {
|
||||
" not found on disk"
|
||||
};
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("MountEcShards {}.{}{}", vid, shard_id, what),
|
||||
)));
|
||||
}
|
||||
let tried = failures
|
||||
.iter()
|
||||
.map(|(dir, e)| format!("{}: {}", dir, e))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
Err(VolumeError::Io(io::Error::other(format!(
|
||||
"MountEcShards {}.{} load failures: {}",
|
||||
vid, shard_id, tried
|
||||
))))
|
||||
}
|
||||
|
||||
/// The directory holding a usable `.ecx` for (collection, vid) on any local
|
||||
/// disk, index directory before data directory. A 0-byte `.ecx` is a stub
|
||||
/// from a failed copy and counts as absent, so the scan continues to a
|
||||
/// sibling disk. Mirrors Go's `Store.findEcxIdxDirForVolume`.
|
||||
fn find_ecx_idx_dir_for_volume(&self, collection: &str, vid: VolumeId) -> Option<String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for loc in &self.locations {
|
||||
for scan in [&loc.idx_directory, &loc.directory] {
|
||||
// A shared -dir.idx is only stat'd once per call.
|
||||
if scan.is_empty() || !seen.insert(scan.clone()) {
|
||||
continue;
|
||||
}
|
||||
let base = crate::storage::volume::volume_file_name(scan, collection, vid);
|
||||
if is_usable_ecx_file(&format!("{}.ecx", base)) {
|
||||
return Some(scan.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("MountEcShards {}.{} not found on disk", vid, shard_id),
|
||||
)))
|
||||
}
|
||||
|
||||
/// Unmount EC shards for a volume (batch).
|
||||
@@ -1221,29 +1134,44 @@ impl Store {
|
||||
) -> (
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
) {
|
||||
let (mut ec_shards, expired) = self.find_expired_ec_volumes();
|
||||
let (deleted, still_held) = self.remove_expired_ec_volumes(expired);
|
||||
ec_shards.extend(still_held);
|
||||
(ec_shards, deleted)
|
||||
}
|
||||
|
||||
/// The read half of `delete_expired_ec_volumes`: the shards to report, and
|
||||
/// the expired EC volumes, by disk index, for `remove_expired_ec_volumes`.
|
||||
pub fn find_expired_ec_volumes(
|
||||
&self,
|
||||
) -> (
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<(usize, VolumeId)>,
|
||||
) {
|
||||
let mut ec_shards = Vec::new();
|
||||
let mut expired = Vec::new();
|
||||
let mut deleted = Vec::new();
|
||||
|
||||
for (disk_id, loc) in self.locations.iter().enumerate() {
|
||||
for (disk_id, loc) in self.locations.iter_mut().enumerate() {
|
||||
let mut expired_vids = Vec::new();
|
||||
let mut io_quarantined_vids = Vec::new();
|
||||
for (vid, ec_vol) in loc.ec_volumes() {
|
||||
if ec_vol.is_time_to_destroy() {
|
||||
expired.push((disk_id, *vid));
|
||||
expired_vids.push(*vid);
|
||||
} else if ec_vol.should_quarantine() {
|
||||
io_quarantined_vids.push(*vid);
|
||||
} else {
|
||||
ec_shards
|
||||
.extend(ec_vol.to_volume_ec_shard_information_messages(disk_id as u32));
|
||||
}
|
||||
}
|
||||
|
||||
for vid in expired_vids {
|
||||
let messages = loc
|
||||
.find_ec_volume(vid)
|
||||
.map(|ec_vol| ec_vol.to_volume_ec_shard_information_messages(disk_id as u32))
|
||||
.unwrap_or_default();
|
||||
if let Some(mut ec_vol) = loc.remove_ec_volume(vid) {
|
||||
for _ in 0..ec_vol.shard_count() {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&ec_vol.collection, "ec_shards"])
|
||||
.dec();
|
||||
}
|
||||
ec_vol.destroy();
|
||||
deleted.extend(messages);
|
||||
} else {
|
||||
ec_shards.extend(messages);
|
||||
}
|
||||
}
|
||||
|
||||
for vid in io_quarantined_vids {
|
||||
if let Some(ec_vol) = loc.find_ec_volume(vid) {
|
||||
let (_, io_count, quarantined) = ec_vol.get_io_error_state();
|
||||
if !quarantined {
|
||||
ec_vol.mark_io_quarantined();
|
||||
@@ -1253,51 +1181,11 @@ impl Store {
|
||||
"ec volume quarantined after consecutive IO errors"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
ec_shards
|
||||
.extend(ec_vol.to_volume_ec_shard_information_messages(disk_id as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(ec_shards, expired)
|
||||
}
|
||||
|
||||
/// The write half of `delete_expired_ec_volumes`: destroys each volume that
|
||||
/// is still there and still expired, returning the shards deleted and the
|
||||
/// shards of any that no longer qualify.
|
||||
pub fn remove_expired_ec_volumes(
|
||||
&mut self,
|
||||
expired: Vec<(usize, VolumeId)>,
|
||||
) -> (
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
) {
|
||||
let mut deleted = Vec::new();
|
||||
let mut still_held = Vec::new();
|
||||
for (disk_id, vid) in expired {
|
||||
let Some(loc) = self.locations.get_mut(disk_id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(ec_vol) = loc.find_ec_volume(vid) else {
|
||||
continue;
|
||||
};
|
||||
let messages = ec_vol.to_volume_ec_shard_information_messages(disk_id as u32);
|
||||
if !ec_vol.is_time_to_destroy() {
|
||||
still_held.extend(messages);
|
||||
continue;
|
||||
}
|
||||
if let Some(mut ec_vol) = loc.remove_ec_volume(vid) {
|
||||
for _ in 0..ec_vol.shard_count() {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&ec_vol.collection, "ec_shards"])
|
||||
.dec();
|
||||
}
|
||||
ec_vol.destroy();
|
||||
deleted.extend(messages);
|
||||
}
|
||||
}
|
||||
(deleted, still_held)
|
||||
(ec_shards, deleted)
|
||||
}
|
||||
|
||||
/// Remove an EC volume from whichever location has it.
|
||||
@@ -1310,66 +1198,28 @@ impl Store {
|
||||
None
|
||||
}
|
||||
|
||||
/// Drop any in-memory EC volume for vid from EVERY disk and close its
|
||||
/// descriptors without deleting files. Unlike remove_ec_volume this does not
|
||||
/// stop at the first disk: a split-disk volume is registered on each disk
|
||||
/// holding a shard. Mirrors Go's Store.UnloadEcVolume.
|
||||
pub fn unload_ec_volume(&mut self, vid: VolumeId) {
|
||||
for loc in &mut self.locations {
|
||||
loc.unload_ec_volume(vid);
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the location index containing EC files for a volume.
|
||||
pub fn find_ec_location(&self, vid: VolumeId, collection: &str) -> Option<usize> {
|
||||
for (i, loc) in self.locations.iter().enumerate() {
|
||||
let base = crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
|
||||
let ecx_path = format!("{}.ecx", base);
|
||||
// A 0-byte .ecx is a failed-copy stub, not an index (Go requires
|
||||
// Size() > 0); keep looking for a disk with a real one.
|
||||
if is_usable_ecx_file(&ecx_path) {
|
||||
if std::path::Path::new(&ecx_path).exists() {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Delete EC shard files from disk. Staged-generation removal failures are
|
||||
/// retained and returned after every location has been processed, so a
|
||||
/// failed sweep never masquerades as a successful delete.
|
||||
pub fn delete_ec_shards(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
collection: &str,
|
||||
shard_ids: &[ShardId],
|
||||
) -> std::io::Result<()> {
|
||||
/// Delete EC shard files from disk.
|
||||
pub fn delete_ec_shards(&mut self, vid: VolumeId, collection: &str, shard_ids: &[ShardId]) {
|
||||
// Delete shard files from disk, tracking which locations actually held one.
|
||||
let mut deleted_at = vec![false; self.locations.len()];
|
||||
let mut first_err: Option<std::io::Error> = None;
|
||||
for (i, loc) in self.locations.iter().enumerate() {
|
||||
for &shard_id in shard_ids {
|
||||
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
|
||||
if std::fs::remove_file(shard.file_name()).is_ok() {
|
||||
deleted_at[i] = true;
|
||||
}
|
||||
// The shard and every 2PC generation of it (<name>.v<N>) are
|
||||
// removed: the shard must not live on this disk at all.
|
||||
match crate::storage::erasure_coding::ec_shard::remove_ec_shard_generations(
|
||||
&shard.file_name(),
|
||||
) {
|
||||
Ok(true) => deleted_at[i] = true,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"failed to remove staged generations of {}: {}",
|
||||
shard.file_name(),
|
||||
e
|
||||
);
|
||||
if first_err.is_none() {
|
||||
first_err = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1441,11 +1291,6 @@ impl Store {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match first_err {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// True if `loc` still has any on-disk EC shard for this volume. An
|
||||
@@ -1519,25 +1364,12 @@ impl Store {
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
preallocate: u64,
|
||||
_max_bytes_per_second: i64,
|
||||
max_bytes_per_second: i64,
|
||||
progress_fn: F,
|
||||
) -> Result<(), VolumeError>
|
||||
where
|
||||
F: Fn(i64) -> bool,
|
||||
{
|
||||
match self.begin_compact_volume(vid, preallocate)? {
|
||||
Some(job) => job.run(progress_fn),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `compact_volume` that needs the store: check free space and
|
||||
/// start the compaction. The returned job runs without the store lock.
|
||||
pub(crate) fn begin_compact_volume(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
preallocate: u64,
|
||||
) -> Result<Option<CompactionJob>, VolumeError> {
|
||||
// Required space matches Go's CompactVolume check: the larger of the
|
||||
// requested preallocation and the estimated volume size.
|
||||
let (loc_idx, space_needed) = {
|
||||
@@ -1561,7 +1393,7 @@ impl Store {
|
||||
let (_, v) = self
|
||||
.find_volume_mut(vid)
|
||||
.ok_or(VolumeError::VolumeNotFound(vid))?;
|
||||
v.begin_compact_by_index()
|
||||
v.compact_by_index(preallocate, max_bytes_per_second, progress_fn)
|
||||
}
|
||||
|
||||
/// Commit a completed compaction: swap files and reload.
|
||||
@@ -1640,35 +1472,10 @@ fn load_vif_volume_info(path: &str) -> Result<VifVolumeInfo, VolumeError> {
|
||||
)))
|
||||
}
|
||||
|
||||
/// Mirrors Go's SaveVolumeInfo: a read-only .vif fails the save, and the
|
||||
/// file is replaced atomically so a failed write keeps the previous
|
||||
/// metadata intact.
|
||||
pub(crate) fn save_vif_volume_info(path: &str, info: &VifVolumeInfo) -> Result<(), VolumeError> {
|
||||
if std::fs::metadata(path).is_ok_and(|m| m.permissions().readonly()) {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("failed to check {} not writable", path),
|
||||
)));
|
||||
}
|
||||
fn save_vif_volume_info(path: &str, info: &VifVolumeInfo) -> Result<(), VolumeError> {
|
||||
let content = serde_json::to_string_pretty(info)
|
||||
.map_err(|e| VolumeError::Io(io::Error::other(e.to_string())))?;
|
||||
static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
let tmp = format!(
|
||||
"{}.tmp.{}.{}",
|
||||
path,
|
||||
std::process::id(),
|
||||
TMP_SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
);
|
||||
let write = (|| -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
let mut f = std::fs::File::create(&tmp)?;
|
||||
f.write_all(content.as_bytes())?;
|
||||
f.sync_all()
|
||||
})();
|
||||
if let Err(e) = write.and_then(|()| std::fs::rename(&tmp, path)) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e.into());
|
||||
}
|
||||
std::fs::write(path, content)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1861,7 +1668,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(7), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(7)).unwrap());
|
||||
assert!(store.unmount_volume(VolumeId(7)));
|
||||
|
||||
store.mount_volume_by_id(VolumeId(7), Some("coll")).unwrap();
|
||||
assert!(store.find_volume(VolumeId(7)).is_some());
|
||||
@@ -1903,7 +1710,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(9), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(9)).unwrap());
|
||||
assert!(store.unmount_volume(VolumeId(9)));
|
||||
|
||||
// The hint is accepted and mounts the volume.
|
||||
store
|
||||
@@ -1948,7 +1755,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(11), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(11)).unwrap());
|
||||
assert!(store.unmount_volume(VolumeId(11)));
|
||||
|
||||
// Simulate an interrupted copy: drop a .note marker.
|
||||
let base = volume_file_name(dir, "coll", VolumeId(11));
|
||||
@@ -2005,7 +1812,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(13), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(13)).unwrap());
|
||||
assert!(store.unmount_volume(VolumeId(13)));
|
||||
|
||||
// No hint: the fallback scan finds the sidecar on disk 0 first (skip,
|
||||
// no .dat), then the real .dat on disk 1 (mount).
|
||||
@@ -2060,7 +1867,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(15), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(15)).unwrap());
|
||||
assert!(store.unmount_volume(VolumeId(15)));
|
||||
// Clear the low-space flag so mount_volume_by_id considers disk 0.
|
||||
store.locations[0]
|
||||
.is_disk_space_low
|
||||
@@ -2437,7 +2244,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let selected =
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive, None);
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive);
|
||||
assert_eq!(selected, Some(1));
|
||||
|
||||
store.locations[1]
|
||||
@@ -2445,7 +2252,7 @@ mod tests {
|
||||
.store(true, Ordering::Relaxed);
|
||||
|
||||
let selected =
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive, None);
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive);
|
||||
assert_eq!(selected, Some(0));
|
||||
}
|
||||
|
||||
@@ -2456,8 +2263,6 @@ mod tests {
|
||||
let mut store = make_test_store(&[dir]);
|
||||
|
||||
std::fs::write(format!("{}/expired_ec_case_9.ec00", dir), b"expired").unwrap();
|
||||
// An EC volume needs its .ecx to mount.
|
||||
std::fs::write(format!("{}/expired_ec_case_9.ecx", dir), [0u8; 16]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(VolumeId(9), "expired_ec_case", &[0], "")
|
||||
.unwrap();
|
||||
@@ -2568,162 +2373,6 @@ mod tests {
|
||||
assert_eq!(v.dat_file_size().unwrap(), volume_size);
|
||||
}
|
||||
|
||||
fn write_test_needle(store: &mut Store, vid: VolumeId, id: u64, data: &[u8]) {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
data_size: data.len() as u32,
|
||||
data: data.to_vec(),
|
||||
..Needle::default()
|
||||
};
|
||||
store.write_volume_needle(vid, &mut n, true).unwrap();
|
||||
}
|
||||
|
||||
fn read_test_needle(store: &Store, vid: VolumeId, id: u64) -> Result<Vec<u8>, VolumeError> {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
..Needle::default()
|
||||
};
|
||||
store.read_volume_needle(vid, &mut n)?;
|
||||
Ok(n.data)
|
||||
}
|
||||
|
||||
/// While a compaction copy runs off the store lock, nothing may pull the
|
||||
/// volume's files out from under it or start a second copy into .cpd.
|
||||
#[test]
|
||||
fn test_compaction_in_flight_guards_the_volume() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let other = TempDir::new().unwrap();
|
||||
let mut store = make_test_store(&[dir]);
|
||||
let vid = VolumeId(1);
|
||||
store
|
||||
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
for i in 1..=3u64 {
|
||||
write_test_needle(&mut store, vid, i, format!("data-{i}").as_bytes());
|
||||
}
|
||||
let revision = {
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
v.super_block.compaction_revision
|
||||
};
|
||||
|
||||
let job = store
|
||||
.begin_compact_volume(vid, 0)
|
||||
.unwrap()
|
||||
.expect("the first compaction claims the volume");
|
||||
|
||||
assert!(store.begin_compact_volume(vid, 0).unwrap().is_none());
|
||||
assert!(store.unmount_volume(vid).is_err());
|
||||
assert!(store.delete_volume(vid, false, false, false).is_err());
|
||||
store.delete_collection("").unwrap();
|
||||
assert!(store.cleanup_compact_volume(vid).is_err());
|
||||
let (_, v) = store.find_volume_mut(vid).unwrap();
|
||||
assert!(v.relocate_index_to(other.path().to_str().unwrap()).is_err());
|
||||
// Go parity: a commit that finds the volume compacting is a no-op.
|
||||
store.commit_compact_volume(vid).unwrap();
|
||||
|
||||
let (_, v) = store.find_volume(vid).expect("still mounted");
|
||||
assert!(v.is_compacting());
|
||||
assert_eq!(v.super_block.compaction_revision, revision);
|
||||
|
||||
job.run(|_| true).unwrap();
|
||||
assert!(!store.find_volume(vid).unwrap().1.is_compacting());
|
||||
store.commit_compact_volume(vid).unwrap();
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
assert_eq!(v.super_block.compaction_revision, revision + 1);
|
||||
assert!(store.unmount_volume(vid).unwrap());
|
||||
}
|
||||
|
||||
/// Writes, overwrites and deletes that land while the copy is parked
|
||||
/// off the store lock must all survive the commit via makeup_diff.
|
||||
fn check_writes_during_compaction_survive_commit(kind: NeedleMapKind) {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut store = Store::new(kind);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let vid = VolumeId(1);
|
||||
store
|
||||
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
assert_eq!(
|
||||
v.live_meta_idx_size_for_test().is_some(),
|
||||
kind == NeedleMapKind::Redb
|
||||
);
|
||||
for i in 1..=6u64 {
|
||||
write_test_needle(&mut store, vid, i, format!("data-{i}").as_bytes());
|
||||
}
|
||||
let mut del = Needle {
|
||||
id: NeedleId(2),
|
||||
cookie: Cookie(2),
|
||||
..Needle::default()
|
||||
};
|
||||
store.delete_volume_needle(vid, &mut del).unwrap();
|
||||
let revision = {
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
v.super_block.compaction_revision
|
||||
};
|
||||
|
||||
let job = store.begin_compact_volume(vid, 0).unwrap().unwrap();
|
||||
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
|
||||
let copy = std::thread::spawn(move || {
|
||||
job.run(move |_| {
|
||||
let _ = entered_tx.send(());
|
||||
let _ = release_rx.recv();
|
||||
true
|
||||
})
|
||||
});
|
||||
entered_rx.recv().unwrap();
|
||||
|
||||
write_test_needle(&mut store, vid, 99, b"late-write");
|
||||
write_test_needle(&mut store, vid, 3, b"overwritten");
|
||||
let mut del = Needle {
|
||||
id: NeedleId(4),
|
||||
cookie: Cookie(4),
|
||||
..Needle::default()
|
||||
};
|
||||
store.delete_volume_needle(vid, &mut del).unwrap();
|
||||
|
||||
drop(release_tx);
|
||||
copy.join().unwrap().unwrap();
|
||||
store.commit_compact_volume(vid).unwrap();
|
||||
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
assert_eq!(v.super_block.compaction_revision, revision + 1);
|
||||
assert_eq!(read_test_needle(&store, vid, 99).unwrap(), b"late-write");
|
||||
assert_eq!(read_test_needle(&store, vid, 3).unwrap(), b"overwritten");
|
||||
assert!(read_test_needle(&store, vid, 4).is_err());
|
||||
assert!(read_test_needle(&store, vid, 2).is_err());
|
||||
for i in [1u64, 5, 6] {
|
||||
assert_eq!(
|
||||
read_test_needle(&store, vid, i).unwrap(),
|
||||
format!("data-{i}").as_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_writes_during_compaction_survive_commit_in_memory() {
|
||||
check_writes_during_compaction_survive_commit(NeedleMapKind::InMemory);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_writes_during_compaction_survive_commit_redb() {
|
||||
check_writes_during_compaction_survive_commit(NeedleMapKind::Redb);
|
||||
}
|
||||
|
||||
/// Build a Store with N HDD disk locations under a single TempDir.
|
||||
/// Returns the store and the TempDir guard so callers keep the dirs
|
||||
/// alive for the test's lifetime.
|
||||
@@ -2794,13 +2443,13 @@ mod tests {
|
||||
std::fs::write(format!("{}.ecsum", base1), b"x").unwrap();
|
||||
|
||||
// Disk 1 still has .ec01 afterwards: both sidecars survive.
|
||||
store.delete_ec_shards(vid, collection, &[0]).unwrap();
|
||||
store.delete_ec_shards(vid, collection, &[0]);
|
||||
assert!(std::path::Path::new(&format!("{}.ecsum", base0)).exists());
|
||||
assert!(std::path::Path::new(&format!("{}.ecsum", base1)).exists());
|
||||
|
||||
// Disk 1's last shard goes: its sidecar is orphaned and removed, but
|
||||
// disk 0 was never touched by either delete and keeps its sidecar.
|
||||
store.delete_ec_shards(vid, collection, &[1]).unwrap();
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
assert!(!std::path::Path::new(&format!("{}.ec01", base1)).exists());
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ecsum", base1)).exists(),
|
||||
@@ -2845,13 +2494,13 @@ mod tests {
|
||||
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecsum", idx_base), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[0]).unwrap();
|
||||
store.delete_ec_shards(vid, collection, &[0]);
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
|
||||
"shared idx sidecar must survive while a sibling disk still has shards"
|
||||
);
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[1]).unwrap();
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
|
||||
"shared idx sidecar should go with the last location's last shard"
|
||||
@@ -2874,7 +2523,7 @@ mod tests {
|
||||
std::fs::write(format!("{}.vif", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.idx", base1), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[0, 1]).unwrap();
|
||||
store.delete_ec_shards(vid, collection, &[0, 1]);
|
||||
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.vif", base0)).exists(),
|
||||
@@ -2886,34 +2535,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Deleting a shard removes its staged 2PC generations (<name>.v<N>) too:
|
||||
/// a shard evicted off a disk leaves nothing (Go
|
||||
/// deleteEcShardIdsForEachLocation).
|
||||
#[test]
|
||||
fn test_delete_ec_shards_removes_staged_generations() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(1);
|
||||
let collection = "c";
|
||||
let vid = VolumeId(7);
|
||||
let base = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec05", base), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec05.v2", base), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecx", base), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[5]).unwrap();
|
||||
|
||||
assert!(!std::path::Path::new(&format!("{}.ec05", base)).exists());
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ec05.v2", base)).exists(),
|
||||
"staged generations of a deleted shard must go with it"
|
||||
);
|
||||
assert!(std::path::Path::new(&format!("{}.ec00", base)).exists());
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.ecx", base)).exists(),
|
||||
"index must survive while shards remain"
|
||||
);
|
||||
}
|
||||
|
||||
/// An already-mounted EC volume on disk 1 must win over a stray
|
||||
/// `.ecx` on disk 2. Protects the post-startup steady state from
|
||||
/// being perturbed by leftover index files from a prior failed move.
|
||||
@@ -2932,14 +2553,6 @@ mod tests {
|
||||
b"shard data",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
format!(
|
||||
"{}/{}_{}.ecx",
|
||||
store.locations[1].directory, collection, vid.0
|
||||
),
|
||||
vec![0u8; 20],
|
||||
)
|
||||
.unwrap();
|
||||
store.locations[1]
|
||||
.mount_ec_shards(vid, collection, &[0], "")
|
||||
.unwrap();
|
||||
@@ -3015,14 +2628,6 @@ mod tests {
|
||||
b"shard data",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
format!(
|
||||
"{}/{}_{}.ecx",
|
||||
store.locations[1].directory, collection, vid.0
|
||||
),
|
||||
vec![0u8; 20],
|
||||
)
|
||||
.unwrap();
|
||||
store.locations[1]
|
||||
.mount_ec_shards(vid, collection, &[0], "")
|
||||
.unwrap();
|
||||
@@ -3056,14 +2661,12 @@ mod tests {
|
||||
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec01", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecx", base0), vec![0u8; 20]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(vid, collection, &[0, 1], "")
|
||||
.unwrap();
|
||||
|
||||
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec02", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecx", base1), vec![0u8; 20]).unwrap();
|
||||
store.locations[1]
|
||||
.mount_ec_shards(vid, collection, &[2], "")
|
||||
.unwrap();
|
||||
@@ -3103,7 +2706,6 @@ mod tests {
|
||||
|
||||
let base = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(vid, collection, &[0], "")
|
||||
.unwrap();
|
||||
@@ -3115,7 +2717,6 @@ mod tests {
|
||||
for shard_id in &filler_shards {
|
||||
std::fs::write(format!("{}.ec{:02}", filler_base, shard_id), b"x").unwrap();
|
||||
}
|
||||
std::fs::write(format!("{}.ecx", filler_base), vec![0u8; 20]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(filler, collection, &filler_shards, "")
|
||||
.unwrap();
|
||||
@@ -3133,106 +2734,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Per-shard `VolumeEcShardsMount` with no `.ecx` on any local disk must
|
||||
/// fail (Go: "no .ecx index found on any local disk") rather than register
|
||||
/// a volume whose every read dies with "ecx file not open".
|
||||
#[test]
|
||||
fn test_mount_ec_shard_without_ecx_fails_and_advertises_nothing() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(2);
|
||||
let collection = "grafana-loki";
|
||||
let vid = VolumeId(12121);
|
||||
let base = volume_file_name(&store.locations[1].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base), b"x").unwrap();
|
||||
|
||||
let err = store
|
||||
.mount_ec_shard(vid, collection, 0, "")
|
||||
.expect_err("a shard without an index must not mount");
|
||||
assert!(
|
||||
matches!(&err, VolumeError::Io(e) if e.kind() == io::ErrorKind::NotFound),
|
||||
"got {:?}",
|
||||
err
|
||||
);
|
||||
assert!(store.find_ec_volume(vid).is_none());
|
||||
}
|
||||
|
||||
/// An interrupted move can leave a 0-byte shard on one disk and the good
|
||||
/// copy on the next. The first disk's failure must not end the scan (Go's
|
||||
/// MountEcShards keeps going), and nothing of the failed attempt may stay
|
||||
/// registered.
|
||||
#[test]
|
||||
fn test_mount_ec_shard_continues_past_a_disk_that_cannot_mount() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(2);
|
||||
let collection = "grafana-loki";
|
||||
let vid = VolumeId(13132);
|
||||
for loc in &store.locations {
|
||||
let base = volume_file_name(&loc.directory, collection, vid);
|
||||
std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap();
|
||||
}
|
||||
let bad = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", bad), b"").unwrap();
|
||||
let good = volume_file_name(&store.locations[1].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", good), b"x").unwrap();
|
||||
|
||||
store.mount_ec_shard(vid, collection, 0, "").unwrap();
|
||||
|
||||
assert!(store.locations[0].find_ec_volume(vid).is_none());
|
||||
assert!(store.locations[1].find_ec_volume(vid).unwrap().has_shard(0));
|
||||
}
|
||||
|
||||
/// When every disk holding the shard fails, the error names each of them.
|
||||
#[test]
|
||||
fn test_mount_ec_shard_reports_every_failing_disk() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(2);
|
||||
let collection = "grafana-loki";
|
||||
let vid = VolumeId(13133);
|
||||
for loc in &store.locations {
|
||||
let base = volume_file_name(&loc.directory, collection, vid);
|
||||
std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap();
|
||||
std::fs::write(format!("{}.ec00", base), b"").unwrap();
|
||||
}
|
||||
|
||||
let err = store
|
||||
.mount_ec_shard(vid, collection, 0, "")
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
for loc in &store.locations {
|
||||
assert!(
|
||||
err.contains(&loc.directory),
|
||||
"{} missing from: {}",
|
||||
loc.directory,
|
||||
err
|
||||
);
|
||||
assert!(loc.find_ec_volume(vid).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.ecx` may sit on a sibling disk of the one holding the shard; the
|
||||
/// per-shard mount routes EcVolume::new at the owner's directory, skipping
|
||||
/// a 0-byte stub on the way (Go's findEcxIdxDirForVolume).
|
||||
#[test]
|
||||
fn test_mount_ec_shard_uses_valid_ecx_on_sibling_disk() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(3);
|
||||
let collection = "grafana-loki";
|
||||
let vid = VolumeId(13131);
|
||||
let stub = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ecx", stub), b"").unwrap();
|
||||
let owner_dir = store.locations[1].directory.clone();
|
||||
let owner = volume_file_name(&owner_dir, collection, vid);
|
||||
std::fs::write(format!("{}.ecx", owner), vec![0u8; 20]).unwrap();
|
||||
let shard = volume_file_name(&store.locations[2].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", shard), b"x").unwrap();
|
||||
|
||||
// The stub is not a location for the batch path either.
|
||||
assert_eq!(store.find_ec_location(vid, collection), Some(1));
|
||||
|
||||
store.mount_ec_shard(vid, collection, 0, "").unwrap();
|
||||
let ec_vol = store.locations[2]
|
||||
.find_ec_volume(vid)
|
||||
.expect("mounted on the shard's disk");
|
||||
assert_eq!(ec_vol.ecx_actual_dir(), owner_dir);
|
||||
}
|
||||
|
||||
/// Mixed-owner batch contract: a batch whose requested shards are
|
||||
/// already owned by different disks reports every owner, so
|
||||
/// `volume_ec_shards_copy` can refuse it rather than rank the owners
|
||||
@@ -3246,13 +2747,11 @@ mod tests {
|
||||
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec01", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecx", base0), vec![0u8; 20]).unwrap();
|
||||
store.locations[0]
|
||||
.mount_ec_shards(vid, collection, &[0, 1], "")
|
||||
.unwrap();
|
||||
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec02", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecx", base1), vec![0u8; 20]).unwrap();
|
||||
store.locations[1]
|
||||
.mount_ec_shards(vid, collection, &[2], "")
|
||||
.unwrap();
|
||||
|
||||
@@ -131,12 +131,6 @@ impl Store {
|
||||
let Some(base) = name.strip_suffix(".ecx") else {
|
||||
continue;
|
||||
};
|
||||
// A 0-byte .ecx is a corrupt stub from a failed copy, not a
|
||||
// credible owner — skip it so the scan keeps looking for a
|
||||
// real index on a sibling disk (Go's indexEcxOwners).
|
||||
if !ent.metadata().is_ok_and(|m| m.len() > 0) {
|
||||
continue;
|
||||
}
|
||||
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
|
||||
continue;
|
||||
};
|
||||
@@ -423,33 +417,4 @@ mod tests {
|
||||
let post = fs::read(dir0.join(format!("{}_{}.ecx", collection, vid))).unwrap();
|
||||
assert_eq!(post, ecx_local, "mirror overwrote dir0's existing .ecx");
|
||||
}
|
||||
|
||||
/// The mirror shares Go's indexEcxOwners, which skips a 0-byte `.ecx`:
|
||||
/// a stub must not be chosen as the source to mirror from.
|
||||
#[test]
|
||||
fn mirror_owner_index_skips_zero_byte_ecx() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir0 = tmp.path().join("data0");
|
||||
let dir1 = tmp.path().join("data1");
|
||||
fs::create_dir_all(&dir0).unwrap();
|
||||
fs::create_dir_all(&dir1).unwrap();
|
||||
|
||||
let collection = "video-recordings";
|
||||
let vid = 4123u32;
|
||||
plant_ecx(&dir0, collection, vid, b"");
|
||||
plant_ecx(&dir1, collection, vid, &[0xA1u8; 20]);
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
add_loc(&mut store, &dir0);
|
||||
add_loc(&mut store, &dir1);
|
||||
|
||||
let owners = store.index_ecx_owners_for_mirror();
|
||||
let owner = owners
|
||||
.get(&EcKey {
|
||||
collection: collection.to_string(),
|
||||
vid: VolumeId(vid),
|
||||
})
|
||||
.expect("the valid .ecx on disk 1 must be indexed");
|
||||
assert_eq!(owner.location, 1);
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,6 @@ pub(crate) struct EcVolumeMissingIndex {
|
||||
pub data_dir: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn ec_local_ecx_path(dir: &str, collection: &str, vid: VolumeId) -> String {
|
||||
if collection.is_empty() {
|
||||
format!("{}/{}.ecx", dir, vid.0)
|
||||
@@ -118,9 +117,10 @@ impl Store {
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// A 0-byte local stub is not a mirrored index (Go gates this fast
|
||||
// path on HasEcxFileOnDisk); mount against the owner instead.
|
||||
let use_local_idx = loc.has_ecx_file_on_disk(&key.collection, key.vid);
|
||||
let local_ecx = ec_local_ecx_path(&loc.idx_directory, &key.collection, key.vid);
|
||||
let local_ecx_in_data = ec_local_ecx_path(&loc.directory, &key.collection, key.vid);
|
||||
let use_local_idx = std::path::Path::new(&local_ecx).exists()
|
||||
|| std::path::Path::new(&local_ecx_in_data).exists();
|
||||
|
||||
if !use_local_idx && owner.location == loc_idx && owner.idx_dir == loc.idx_directory
|
||||
{
|
||||
@@ -422,12 +422,6 @@ impl Store {
|
||||
let Some(base) = name.strip_suffix(".ecx") else {
|
||||
continue;
|
||||
};
|
||||
// A 0-byte .ecx is a corrupt stub from a failed copy, not a
|
||||
// credible owner — skip it so the scan keeps looking for a
|
||||
// real index on a sibling disk (Go's indexEcxOwners).
|
||||
if !ent.metadata().is_ok_and(|m| m.len() > 0) {
|
||||
continue;
|
||||
}
|
||||
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
|
||||
continue;
|
||||
};
|
||||
@@ -645,34 +639,6 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A 0-byte `.ecx` is not a credible owner (Go's indexEcxOwners skips
|
||||
/// it): picking the stub would hide the valid index on the sibling disk.
|
||||
#[test]
|
||||
fn test_index_ecx_owners_skips_zero_byte_stub() {
|
||||
let (store, _tmp) = make_test_store(2, None);
|
||||
let d0 = store.locations[0].directory.clone();
|
||||
let d1 = store.locations[1].directory.clone();
|
||||
std::fs::write(ec_local_ecx_path(&d0, "pics", VolumeId(7)), b"").unwrap();
|
||||
write_index_files(&d1, "pics", 7, 10, 4);
|
||||
|
||||
let owners = store.index_ecx_owners();
|
||||
let owner = owners
|
||||
.get(&EcKey {
|
||||
collection: "pics".to_string(),
|
||||
vid: VolumeId(7),
|
||||
})
|
||||
.expect("the valid .ecx on disk 1 must be indexed");
|
||||
assert_eq!(owner.location, 1);
|
||||
assert_eq!(owner.idx_dir, d1);
|
||||
|
||||
// A stub with no real index anywhere owns nothing.
|
||||
std::fs::write(ec_local_ecx_path(&d0, "pics", VolumeId(8)), b"").unwrap();
|
||||
assert!(!store.index_ecx_owners().contains_key(&EcKey {
|
||||
collection: "pics".to_string(),
|
||||
vid: VolumeId(8),
|
||||
}));
|
||||
}
|
||||
|
||||
/// An empty `.dat` (<= a superblock, i.e. zero needles) for an EC volume
|
||||
/// is a leftover stub from the pre-fix loader. It must be swept on startup,
|
||||
/// not loaded as a phantom empty volume. With the same vid's stub on two
|
||||
@@ -1005,56 +971,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// dir0 holds orphan shards next to a 0-byte `.ecx` stub from a failed
|
||||
/// copy; the real index is on dir1. The stub must not count as a
|
||||
/// locally-mirrored index (Go gates that fast path on HasEcxFileOnDisk),
|
||||
/// or the shards get registered against an empty index.
|
||||
#[test]
|
||||
fn test_reconcile_ignores_zero_byte_local_ecx_stub() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir0 = tmp.path().join("data0");
|
||||
let dir1 = tmp.path().join("data1");
|
||||
std::fs::create_dir_all(&dir0).unwrap();
|
||||
std::fs::create_dir_all(&dir1).unwrap();
|
||||
|
||||
let collection = "grafana-loki";
|
||||
let vid = 1094u32;
|
||||
|
||||
write_shard(dir0.to_str().unwrap(), collection, vid, 0);
|
||||
write_shard(dir1.to_str().unwrap(), collection, vid, 1);
|
||||
write_index_files(dir1.to_str().unwrap(), collection, vid, 10, 4);
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
for dir in [&dir0, &dir1] {
|
||||
store
|
||||
.add_location(
|
||||
dir.to_str().unwrap(),
|
||||
dir.to_str().unwrap(),
|
||||
100,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
// Plant the stub after the startup scan so only the reconcile decision
|
||||
// is under test, then drop dir0's mount and reconcile again.
|
||||
store.locations[0].remove_ec_volume(VolumeId(vid));
|
||||
std::fs::write(
|
||||
ec_local_ecx_path(dir0.to_str().unwrap(), collection, VolumeId(vid)),
|
||||
b"",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
store.reconcile_ec_shards_across_disks();
|
||||
|
||||
let ev0 = store.locations[0]
|
||||
.find_ec_volume(VolumeId(vid))
|
||||
.expect("dir0's shard must be mounted against the owner's index");
|
||||
assert!(ev0.has_shard(0));
|
||||
assert_eq!(ev0.ecx_actual_dir(), dir1.to_str().unwrap());
|
||||
}
|
||||
|
||||
/// PR 9244 review case: idx_directory is configured but the
|
||||
/// owner's .ecx / .ecj / .vif live in the owner's data dir
|
||||
/// (the legacy "written before -dir.idx was set" layout). The
|
||||
@@ -1476,7 +1392,7 @@ mod tests {
|
||||
let vid = VolumeId(7004);
|
||||
let collection = "grafana-loki";
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[1]).unwrap();
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
|
||||
// Shard 1 file is gone on disk 1.
|
||||
let p1 = format!(
|
||||
|
||||
+529
-1060
File diff suppressed because it is too large.
Load diff
@@ -1255,102 +1255,3 @@ async fn non_ascii_fid_and_ttl_are_rejected_not_panicked() {
|
||||
"a non-ASCII ttl must behave like any other invalid ttl, not panic"
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// The write queue answers an upload with the needle's real ETag
|
||||
//
|
||||
// The queue worker computes the CRC on the needle it was handed, so the handler
|
||||
// has to know the checksum before it submits. Without that every queued upload
|
||||
// came back as "00000000". The direct path is the reference: same payload, same
|
||||
// ETag, for a plain body and for one the handler gzips before storing.
|
||||
// ============================================================================
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_queue_upload_returns_same_etag_as_direct_write() {
|
||||
use seaweed_volume::server::write_queue::WriteQueue;
|
||||
|
||||
let (direct_state, _direct_tmp) = test_state();
|
||||
let (queued_state, _queued_tmp) = test_state();
|
||||
let wq = WriteQueue::new(queued_state.clone(), 128);
|
||||
let _ = queued_state.write_queue.set(wq);
|
||||
|
||||
let compressible = "seaweedfs ".repeat(200).into_bytes();
|
||||
let uploads: [(&str, &[u8]); 2] = [
|
||||
("/1,01637037d6", b"hello, seaweedfs!"),
|
||||
("/1/02637037d6/notes.txt", &compressible),
|
||||
];
|
||||
|
||||
for (uri, payload) in uploads {
|
||||
let mut etags = Vec::new();
|
||||
for state in [&direct_state, &queued_state] {
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri)
|
||||
.body(Body::from(payload.to_vec()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::CREATED);
|
||||
|
||||
let header = response
|
||||
.headers()
|
||||
.get("ETag")
|
||||
.expect("upload response has no ETag")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let body = body_bytes(response).await;
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&body).expect("POST response is not valid JSON");
|
||||
let etag = json["eTag"].as_str().unwrap().to_string();
|
||||
assert_eq!(header, format!("\"{}\"", etag));
|
||||
etags.push(etag);
|
||||
}
|
||||
assert_ne!(etags[0], "00000000", "{}: direct ETag is the zero CRC", uri);
|
||||
assert_eq!(
|
||||
etags[1], etags[0],
|
||||
"{}: queued upload must return the direct path's ETag",
|
||||
uri
|
||||
);
|
||||
}
|
||||
|
||||
// The second upload really was stored gzipped, so its ETag is the CRC of
|
||||
// the compressed bytes on both paths.
|
||||
let app = build_admin_router(queued_state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(uploads[1].0)
|
||||
.header("Accept-Encoding", "gzip")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["Content-Encoding"], "gzip");
|
||||
|
||||
// Re-uploading the same bytes is the unchanged path: 204 with the same ETag.
|
||||
let (uri, payload) = uploads[0];
|
||||
let mut etags = Vec::new();
|
||||
for state in [&direct_state, &queued_state] {
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri)
|
||||
.body(Body::from(payload.to_vec()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NO_CONTENT);
|
||||
etags.push(response.headers()["ETag"].to_str().unwrap().to_string());
|
||||
}
|
||||
assert_eq!(etags[1], etags[0], "unchanged upload ETag differs");
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
# Strict Iceberg reader used by the OLake integration test. PyIceberg is
|
||||
# deliberate here: it rejects manifests that omit the spec's field ids and
|
||||
# parquet without either field ids or a name mapping, so a passing read proves
|
||||
# the catalog served something every engine can consume -- not just something
|
||||
# OLake itself can read back.
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN pip install --no-cache-dir "pyiceberg[s3fs]==0.11.1" "pyarrow==25.0.0"
|
||||
|
||||
COPY inspect_table.py /app/
|
||||
|
||||
ENTRYPOINT ["python3", "/app/inspect_table.py"]
|
||||
@@ -1,104 +0,0 @@
|
||||
# OLake Iceberg Catalog Integration Test
|
||||
|
||||
An integration test for [OLake](https://github.com/datazip-inc/olake) against
|
||||
SeaweedFS's Iceberg REST Catalog, in the same shape as `catalog_clickhouse`.
|
||||
|
||||
## Why OLake, given we already test five engines
|
||||
|
||||
Two things here are covered by nothing else in this directory.
|
||||
|
||||
**It is a strict Java Iceberg client.** OLake does not write Iceberg from Go —
|
||||
its Go process spawns a Java sidecar over gRPC and writes through the official
|
||||
Apache Iceberg library, because the Go library has no equality deletes and CDC
|
||||
needs them. So this test exercises the client class that
|
||||
`weed/s3api/iceberg/metadata_compliance.go` exists to serve: the one
|
||||
that fails with *"Cannot parse missing long current-snapshot-id"* when the
|
||||
catalog omits spec-required keys that `iceberg-go` strips via `omitempty`.
|
||||
|
||||
**It produces equality deletes.** OLake is a CDC tool. Its upsert path commits
|
||||
`operation=overwrite` with an equality-delete file, and a delete manifest
|
||||
alongside the data manifests. ClickHouse, StarRocks, Doris and DuckDB all only
|
||||
append.
|
||||
|
||||
## What it asserts
|
||||
|
||||
`TestOLakeIcebergCatalog` runs six subtests against a `weed mini` cluster with
|
||||
a pre-created table bucket and a Postgres source:
|
||||
|
||||
| Subtest | What a failure means |
|
||||
|---|---|
|
||||
| `CheckDestination` | `olake check` did not reach `SUCCEEDED`, or it passed without ever loading `org.apache.iceberg.rest.RESTSessionCatalog` — the second case means the destination was never actually contacted. |
|
||||
| `Discover` | OLake could not enumerate the source table, or wrote no `streams.json`. |
|
||||
| `FullSyncAppendsRows` | The sync read fewer than the three seeded rows, or committed no Iceberg snapshot. |
|
||||
| `StrictReaderSeesRows` | PyIceberg could not read back what the Java writer committed, or the values differ. This is the data path, not just metadata. |
|
||||
| `UpsertProducesEqualityDelete` | After an `UPDATE` and a re-sync, no snapshot recorded an overwrite carrying equality deletes, or the current snapshot has no delete manifest. |
|
||||
| `CompliantWriterNeedsNoRepair` | The catalog rewrote a manifest the official Iceberg Java writer produced. That is a regression in the repair gate, not a problem with OLake. |
|
||||
|
||||
## The one thing this test deliberately does not check
|
||||
|
||||
It does **not** assert that a reader sees the updated row and no duplicate.
|
||||
|
||||
PyIceberg refuses to scan a table carrying equality deletes
|
||||
([apache/iceberg#6568](https://github.com/apache/iceberg/issues/6568)) while
|
||||
reading its metadata perfectly well — so a rows-mode read after the upsert would
|
||||
raise, not pass. The alternative is an engine that applies equality deletes,
|
||||
which for StarRocks means a 3 GB image and 12 GB of RAM in CI.
|
||||
|
||||
The line drawn instead: **recording the commit correctly is the catalog's
|
||||
contract; applying deletes on read is the query engine's.** The metadata
|
||||
assertions cover our half.
|
||||
|
||||
This was verified once by hand outside CI, on 2026-09-23, with StarRocks 4.1.4
|
||||
attached to the same catalog: after the upsert it read 3 rows / 3 distinct ids
|
||||
with `id=1` showing the updated value and `_op_type=u`. If someone later wants
|
||||
that inside the gate, add a reader that supports equality deletes — **do not**
|
||||
"upgrade" this test to a PyIceberg rows-mode read after the upsert. It would not
|
||||
pass; and if PyIceberg ever starts silently skipping deletes instead of raising,
|
||||
it would pass by not looking.
|
||||
|
||||
## What the config proves
|
||||
|
||||
Nothing in the destination config is SeaweedFS-specific:
|
||||
|
||||
```json
|
||||
{
|
||||
"catalog_type": "rest",
|
||||
"rest_catalog_url": "http://HOST:ICEBERG_PORT",
|
||||
"iceberg_s3_path": "s3://olake-tables",
|
||||
"s3_endpoint": "http://HOST:S3_PORT",
|
||||
"rest_auth_type": "oauth2",
|
||||
"oauth2_uri": "http://HOST:ICEBERG_PORT/v1/oauth/tokens",
|
||||
"credential": "ACCESS_KEY:SECRET_KEY"
|
||||
}
|
||||
```
|
||||
|
||||
`catalog_type` is the generic `rest`, auth is the standard OAuth2
|
||||
client-credentials flow, and `s3_path_style` does not even need setting —
|
||||
OLake turns it on by itself whenever `s3_endpoint` is non-empty. As of
|
||||
OLake v0.10.1 this works with no change on either side.
|
||||
|
||||
## Running it
|
||||
|
||||
```sh
|
||||
go test ./test/s3tables/catalog_olake/ -run TestOLakeIcebergCatalog -v -timeout 25m
|
||||
```
|
||||
|
||||
Needs Docker and a `weed` binary (at `weed/weed` under the repo root, or on
|
||||
`PATH`). Takes about 35 seconds. It skips rather than fails when Docker is
|
||||
absent, and `SEAWEEDFS_SKIP_OLAKE_TESTS=1` skips it outright.
|
||||
|
||||
Overrides: `OLAKE_IMAGE` (default `olakego/source-postgres:latest`),
|
||||
`POSTGRES_IMAGE` (default `postgres:16`).
|
||||
|
||||
## In CI
|
||||
|
||||
Runs as `olake-iceberg-catalog-tests` in `.github/workflows/s3-tables-tests.yml`,
|
||||
on a matrix of a pinned image plus `latest` — the same shape the ClickHouse job
|
||||
uses, and for the same reason: OLake's Iceberg writer is a Java sidecar whose
|
||||
library version moves independently of the Go release, so the `latest` leg is
|
||||
what catches drift in the client rather than in OLake itself.
|
||||
|
||||
The job asserts the suite actually ran — at least one top-level `--- PASS` and
|
||||
zero `--- SKIP` — rather than trusting a green exit. This suite skips itself
|
||||
when Docker is unavailable, and a skipped suite reporting success is how a gate
|
||||
quietly stops being one.
|
||||
@@ -1,91 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inspect an Iceberg table written by OLake, through the SeaweedFS REST catalog.
|
||||
|
||||
Two modes, because a strict reader cannot do both:
|
||||
|
||||
rows -- scan the table and print "id,region,amount" per row, ordered by
|
||||
id. Only valid while the table has no equality deletes.
|
||||
snapshots -- print one line per snapshot with its operation and delete-file
|
||||
counters, plus the manifest content kinds of the current
|
||||
snapshot.
|
||||
|
||||
The split exists because PyIceberg refuses to scan a table carrying equality
|
||||
deletes (apache/iceberg#6568) while reading its metadata perfectly well. OLake
|
||||
is a CDC tool, so its upsert path produces exactly those deletes -- asserting
|
||||
the commit landed is the catalog's concern, and applying deletes on read is the
|
||||
query engine's.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from pyiceberg.catalog import load_catalog
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("mode", choices=["rows", "snapshots"])
|
||||
p.add_argument("--catalog-url", required=True)
|
||||
p.add_argument("--warehouse", required=True)
|
||||
p.add_argument("--prefix", required=True)
|
||||
p.add_argument("--s3-endpoint", required=True)
|
||||
p.add_argument("--access-key", required=True)
|
||||
p.add_argument("--secret-key", required=True)
|
||||
p.add_argument("--region", default="us-east-1")
|
||||
p.add_argument("--namespace", action="append", required=True)
|
||||
p.add_argument("--table", required=True)
|
||||
args = p.parse_args()
|
||||
|
||||
catalog = load_catalog(
|
||||
"rest",
|
||||
**{
|
||||
"type": "rest",
|
||||
"uri": args.catalog_url,
|
||||
"warehouse": args.warehouse,
|
||||
"prefix": args.prefix,
|
||||
"credential": f"{args.access_key}:{args.secret_key}",
|
||||
"s3.access-key-id": args.access_key,
|
||||
"s3.secret-access-key": args.secret_key,
|
||||
"s3.endpoint": args.s3_endpoint,
|
||||
"s3.region": args.region,
|
||||
"s3.path-style-access": "true",
|
||||
},
|
||||
)
|
||||
|
||||
table = catalog.load_table(tuple(args.namespace) + (args.table,))
|
||||
|
||||
if args.mode == "rows":
|
||||
data = table.scan().to_arrow().to_pydict()
|
||||
# amount is decimal(10,2) in Postgres but arrives here as a float, whose
|
||||
# repr drops trailing zeros (120.5, not 120.50). Format it to the source
|
||||
# scale so the expected values in the Go test stay readable.
|
||||
for row_id, region, amount in sorted(
|
||||
zip(data["id"], data["region"], data["amount"])
|
||||
):
|
||||
print("%s,%s,%.2f" % (row_id, region, float(amount)))
|
||||
return 0
|
||||
|
||||
print("format-version=%d" % table.metadata.format_version)
|
||||
ids = table.metadata.schemas[-1].identifier_field_ids
|
||||
print("identifier-field-ids=%s" % ",".join(str(i) for i in ids))
|
||||
for snap in table.metadata.snapshots:
|
||||
s = snap.summary
|
||||
print(
|
||||
"snapshot operation=%s total-delete-files=%s added-delete-files=%s "
|
||||
"added-equality-deletes=%s total-records=%s"
|
||||
% (
|
||||
s.operation,
|
||||
s.get("total-delete-files", "0"),
|
||||
s.get("added-delete-files", "0"),
|
||||
s.get("added-equality-deletes", "0"),
|
||||
s.get("total-records", "0"),
|
||||
)
|
||||
)
|
||||
current = table.current_snapshot()
|
||||
kinds = [str(m.content).rsplit(".", 1)[-1] for m in current.manifests(table.io)]
|
||||
print("current-manifest-kinds=%s" % ",".join(kinds))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,623 +0,0 @@
|
||||
// Package catalog_olake provides an integration test for OLake
|
||||
// (github.com/datazip-inc/olake) against the SeaweedFS Iceberg REST Catalog.
|
||||
//
|
||||
// OLake matters here for two reasons that no other engine in this directory
|
||||
// covers. First, it does not write Iceberg from Go: it spawns a Java sidecar
|
||||
// over gRPC and writes through the official Apache Iceberg library, so this is
|
||||
// a strict Java client -- the class that iceberg/metadata_compliance.go exists
|
||||
// to serve. Second, it is a CDC tool, so its upsert path emits equality
|
||||
// deletes, which neither the ClickHouse nor the Doris test exercises.
|
||||
package catalog_olake
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
const (
|
||||
olakeDefaultImage = "olakego/source-postgres:latest"
|
||||
postgresDefaultImage = "postgres:16"
|
||||
readerImage = "seaweedfs-olake-reader:test"
|
||||
|
||||
tableBucketName = "olake-tables"
|
||||
sourceDatabase = "olakedb"
|
||||
sourceUser = "olake"
|
||||
sourcePassword = "olakepw"
|
||||
|
||||
// OLake derives the destination namespace from the source: it joins the
|
||||
// connector name, database and schema. Asserting the derived name rather
|
||||
// than configuring one keeps the test honest about what OLake actually
|
||||
// does with our catalog.
|
||||
expectedNamespace = "postgres_olakedb_public"
|
||||
expectedTable = "orders"
|
||||
|
||||
postgresStartTimeout = 90 * time.Second
|
||||
olakeRunTimeout = 6 * time.Minute
|
||||
)
|
||||
|
||||
type TestEnvironment struct {
|
||||
seaweedDir string
|
||||
weedBinary string
|
||||
dataDir string
|
||||
configDir string
|
||||
bindIP string
|
||||
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
volumePort int
|
||||
volumeGrpcPort int
|
||||
filerPort int
|
||||
filerGrpcPort int
|
||||
s3Port int
|
||||
s3GrpcPort int
|
||||
icebergPort int
|
||||
postgresPort int
|
||||
|
||||
accessKey string
|
||||
secretKey string
|
||||
|
||||
weedProcess *exec.Cmd
|
||||
weedCancel func()
|
||||
postgresContainer string
|
||||
}
|
||||
|
||||
func TestOLakeIcebergCatalog(t *testing.T) {
|
||||
requireOLakeRuntime(t)
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
env.StartSeaweedFS(t)
|
||||
env.startPostgres(t)
|
||||
env.seedSource(t)
|
||||
|
||||
buildReaderImage(t)
|
||||
env.writeOLakeConfigs(t)
|
||||
|
||||
t.Run("CheckDestination", func(t *testing.T) {
|
||||
out := env.runOLake(t, "check",
|
||||
"--config", "/mnt/config/source.json",
|
||||
"--destination", "/mnt/config/destination.json")
|
||||
if !strings.Contains(out, `"status":"SUCCEEDED"`) {
|
||||
t.Fatalf("olake check did not report SUCCEEDED.\n%s", tailLines(out, 40))
|
||||
}
|
||||
// The Java sidecar, not the Go process, is what talks to our catalog.
|
||||
// If this line is missing the check passed without exercising the
|
||||
// Iceberg REST path at all.
|
||||
if !strings.Contains(out, "org.apache.iceberg.rest.RESTSessionCatalog") {
|
||||
t.Errorf("check passed but never loaded the Iceberg REST catalog; "+
|
||||
"the destination may not have been contacted.\n%s", tailLines(out, 40))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Discover", func(t *testing.T) {
|
||||
out := env.runOLake(t, "discover",
|
||||
"--config", "/mnt/config/source.json",
|
||||
"--destination", "/mnt/config/destination.json")
|
||||
if !strings.Contains(out, `"stream_name":"`+expectedTable+`"`) {
|
||||
t.Fatalf("discover did not report the %s stream.\n%s", expectedTable, tailLines(out, 20))
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(env.configDir, "streams.json")); err != nil {
|
||||
t.Fatalf("discover did not write streams.json: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("FullSyncAppendsRows", func(t *testing.T) {
|
||||
out := env.runOLake(t, "sync",
|
||||
"--config", "/mnt/config/source.json",
|
||||
"--destination", "/mnt/config/destination.json",
|
||||
"--streams", "/mnt/config/streams.json",
|
||||
"--state", "/mnt/config/state.json")
|
||||
if !strings.Contains(out, "Total records read: 3") {
|
||||
t.Fatalf("sync did not read the three seeded rows.\n%s", tailLines(out, 30))
|
||||
}
|
||||
if !strings.Contains(out, "Committed snapshot") {
|
||||
t.Fatalf("sync never committed an Iceberg snapshot.\n%s", tailLines(out, 30))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("StrictReaderSeesRows", func(t *testing.T) {
|
||||
rows := env.readTable(t, "rows")
|
||||
want := []string{"1,us-east,120.50", "2,us-west,87.20", "3,eu-west,210.00"}
|
||||
got := nonEmptyLines(rows)
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("PyIceberg read %d rows, want %d.\n%s", len(got), len(want), rows)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Errorf("row %d = %q, want %q", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("UpsertProducesEqualityDelete", func(t *testing.T) {
|
||||
// Push the row past the incremental cursor so the next sync re-emits it
|
||||
// as an update rather than skipping it.
|
||||
env.execSQL(t, "UPDATE orders SET amount=999.99, region='ap-south' WHERE id=1")
|
||||
|
||||
out := env.runOLake(t, "sync",
|
||||
"--config", "/mnt/config/source.json",
|
||||
"--destination", "/mnt/config/destination.json",
|
||||
"--streams", "/mnt/config/streams.json",
|
||||
"--state", "/mnt/config/state.json")
|
||||
if !strings.Contains(out, "delete files") {
|
||||
t.Fatalf("re-sync committed no delete files.\n%s", tailLines(out, 30))
|
||||
}
|
||||
|
||||
meta := env.readTable(t, "snapshots")
|
||||
if !strings.Contains(meta, "format-version=2") {
|
||||
t.Errorf("expected Iceberg format-version 2, got:\n%s", meta)
|
||||
}
|
||||
if !strings.Contains(meta, "identifier-field-ids=") ||
|
||||
strings.Contains(meta, "identifier-field-ids=\n") {
|
||||
t.Errorf("table carries no identifier fields, so OLake could not "+
|
||||
"have upserted:\n%s", meta)
|
||||
}
|
||||
|
||||
var sawOverwrite bool
|
||||
for _, line := range nonEmptyLines(meta) {
|
||||
if !strings.HasPrefix(line, "snapshot operation=") {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(line, "operation=Operation.OVERWRITE") &&
|
||||
!strings.Contains(line, "added-equality-deletes=0") {
|
||||
sawOverwrite = true
|
||||
}
|
||||
}
|
||||
if !sawOverwrite {
|
||||
t.Errorf("no snapshot recorded an overwrite carrying equality "+
|
||||
"deletes:\n%s", meta)
|
||||
}
|
||||
if !strings.Contains(meta, "current-manifest-kinds=") ||
|
||||
!strings.Contains(meta, "DELETES") {
|
||||
t.Errorf("current snapshot has no delete manifest:\n%s", meta)
|
||||
}
|
||||
// Deliberately NOT asserted here: that a reader sees the updated value
|
||||
// and no duplicate row. PyIceberg refuses to scan a table carrying
|
||||
// equality deletes (apache/iceberg#6568), so a rows-mode read would
|
||||
// fail rather than pass, and swapping in an engine that can apply them
|
||||
// costs this test a multi-gigabyte image. Applying deletes on read is
|
||||
// the engine's contract; recording the commit correctly is ours, and
|
||||
// that is what the assertions above cover. See the README.
|
||||
})
|
||||
|
||||
t.Run("CompliantWriterNeedsNoRepair", func(t *testing.T) {
|
||||
names := env.listTableMetadata(t)
|
||||
if len(names) == 0 {
|
||||
t.Fatalf("no metadata files found for %s.%s", expectedNamespace, expectedTable)
|
||||
}
|
||||
for _, n := range names {
|
||||
if strings.HasPrefix(n, "repaired-") {
|
||||
t.Errorf("catalog repaired a manifest written by OLake (%s); "+
|
||||
"the official Iceberg Java writer is expected to be "+
|
||||
"spec-compliant, so this is a regression in the repair "+
|
||||
"gate rather than in OLake", n)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
t.Helper()
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get working directory: %v", err)
|
||||
}
|
||||
|
||||
seaweedDir := wd
|
||||
for i := 0; i < 6; i++ {
|
||||
if _, err := os.Stat(filepath.Join(seaweedDir, "go.mod")); err == nil {
|
||||
break
|
||||
}
|
||||
seaweedDir = filepath.Dir(seaweedDir)
|
||||
}
|
||||
|
||||
weedBinary := filepath.Join(seaweedDir, "weed", "weed")
|
||||
if info, err := os.Stat(weedBinary); err != nil || info.IsDir() {
|
||||
weedBinary = filepath.Join(seaweedDir, "weed", "weed", "weed")
|
||||
if info, err := os.Stat(weedBinary); err != nil || info.IsDir() {
|
||||
weedBinary = "weed"
|
||||
if _, err := exec.LookPath(weedBinary); err != nil {
|
||||
t.Skip("weed binary not found, skipping integration test")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dataDir, err := os.MkdirTemp("", "seaweed-olake-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
configDir := filepath.Join(dataDir, "olake")
|
||||
if err := os.MkdirAll(configDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create config dir: %v", err)
|
||||
}
|
||||
|
||||
// 9 for the mini cluster, 1 for the Postgres source mapped on the host.
|
||||
ports := testutil.MustAllocatePorts(t, 10)
|
||||
|
||||
return &TestEnvironment{
|
||||
seaweedDir: seaweedDir,
|
||||
weedBinary: weedBinary,
|
||||
dataDir: dataDir,
|
||||
configDir: configDir,
|
||||
bindIP: testutil.FindBindIP(),
|
||||
masterPort: ports[0],
|
||||
masterGrpcPort: ports[1],
|
||||
volumePort: ports[2],
|
||||
volumeGrpcPort: ports[3],
|
||||
filerPort: ports[4],
|
||||
filerGrpcPort: ports[5],
|
||||
s3Port: ports[6],
|
||||
s3GrpcPort: ports[7],
|
||||
icebergPort: ports[8],
|
||||
postgresPort: ports[9],
|
||||
accessKey: "AKIAIOSFODNN7EXAMPLE",
|
||||
secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
iamConfigPath, err := testutil.WriteIAMConfig(env.dataDir, env.accessKey, env.secretKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create IAM config: %v", err)
|
||||
}
|
||||
|
||||
cmd := exec.Command(env.weedBinary, "mini",
|
||||
"-master.port", fmt.Sprintf("%d", env.masterPort),
|
||||
"-master.port.grpc", fmt.Sprintf("%d", env.masterGrpcPort),
|
||||
"-volume.port", fmt.Sprintf("%d", env.volumePort),
|
||||
"-volume.port.grpc", fmt.Sprintf("%d", env.volumeGrpcPort),
|
||||
"-filer.port", fmt.Sprintf("%d", env.filerPort),
|
||||
"-filer.port.grpc", fmt.Sprintf("%d", env.filerGrpcPort),
|
||||
"-s3.port", fmt.Sprintf("%d", env.s3Port),
|
||||
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
|
||||
"-s3.port.iceberg", fmt.Sprintf("%d", env.icebergPort),
|
||||
"-s3.config", iamConfigPath,
|
||||
// Pre-create the table bucket the way an operator would, rather than
|
||||
// reaching for the S3 Tables control plane from the test.
|
||||
"-tableBucket", tableBucketName,
|
||||
"-ip", env.bindIP,
|
||||
"-ip.bind", "0.0.0.0",
|
||||
"-dir", env.dataDir,
|
||||
)
|
||||
cmd.Dir = env.dataDir
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Env = append(os.Environ(),
|
||||
"AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
)
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("Failed to start SeaweedFS: %v", err)
|
||||
}
|
||||
env.weedProcess = cmd
|
||||
env.weedCancel = func() {
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/v1/config", env.bindIP, env.icebergPort)
|
||||
if !waitForService(url, 45*time.Second) {
|
||||
t.Fatalf("Iceberg REST API did not become ready at %s", url)
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) startPostgres(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
name := fmt.Sprintf("olake-pg-%d", env.postgresPort)
|
||||
_ = exec.Command("docker", "rm", "-f", name).Run()
|
||||
|
||||
cmd := exec.Command("docker", "run", "-d", "--name", name,
|
||||
"-e", "POSTGRES_USER="+sourceUser,
|
||||
"-e", "POSTGRES_PASSWORD="+sourcePassword,
|
||||
"-e", "POSTGRES_DB="+sourceDatabase,
|
||||
"-p", fmt.Sprintf("%d:5432", env.postgresPort),
|
||||
postgresImage(),
|
||||
)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to start Postgres: %v\n%s", err, out)
|
||||
}
|
||||
env.postgresContainer = name
|
||||
|
||||
deadline := time.Now().Add(postgresStartTimeout)
|
||||
for time.Now().Before(deadline) {
|
||||
probe := exec.Command("docker", "exec", name,
|
||||
"pg_isready", "-U", sourceUser, "-d", sourceDatabase)
|
||||
if err := probe.Run(); err == nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
t.Fatalf("Postgres did not become ready within %s", postgresStartTimeout)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) seedSource(t *testing.T) {
|
||||
t.Helper()
|
||||
env.execSQL(t, `
|
||||
CREATE TABLE orders (
|
||||
id int PRIMARY KEY,
|
||||
region text,
|
||||
amount numeric(10,2),
|
||||
order_ts timestamp
|
||||
);
|
||||
INSERT INTO orders VALUES
|
||||
(1,'us-east',120.50,'2026-07-27 09:15'),
|
||||
(2,'us-west', 87.20,'2026-07-27 09:20'),
|
||||
(3,'eu-west',210.00,'2026-07-27 09:31');
|
||||
ALTER TABLE orders REPLICA IDENTITY FULL;`)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) execSQL(t *testing.T, sqlText string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("docker", "exec", env.postgresContainer,
|
||||
"psql", "-v", "ON_ERROR_STOP=1", "-U", sourceUser, "-d", sourceDatabase,
|
||||
"-c", sqlText)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("psql failed: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// writeOLakeConfigs writes the source and destination configs. The destination
|
||||
// is the point of this test: nothing in it is SeaweedFS-specific. catalog_type
|
||||
// is the generic "rest", auth is the standard OAuth2 client-credentials flow,
|
||||
// and path-style access is not even set here because OLake turns it on by
|
||||
// itself whenever s3_endpoint is non-empty.
|
||||
func (env *TestEnvironment) writeOLakeConfigs(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
source := map[string]any{
|
||||
"host": env.bindIP,
|
||||
"port": env.postgresPort,
|
||||
"database": sourceDatabase,
|
||||
"username": sourceUser,
|
||||
"password": sourcePassword,
|
||||
"jdbc_url_params": map[string]any{},
|
||||
"ssl": map[string]any{"mode": "disable"},
|
||||
"update_method": map[string]any{"type": "Standalone"},
|
||||
"max_threads": 2,
|
||||
"retry_count": 0,
|
||||
}
|
||||
|
||||
catalogURL := fmt.Sprintf("http://%s:%d", env.bindIP, env.icebergPort)
|
||||
destination := map[string]any{
|
||||
"type": "ICEBERG",
|
||||
"writer": map[string]any{
|
||||
"catalog_type": "rest",
|
||||
"rest_catalog_url": catalogURL,
|
||||
"catalog_name": "olake",
|
||||
"iceberg_s3_path": "s3://" + tableBucketName,
|
||||
"s3_endpoint": fmt.Sprintf("http://%s:%d", env.bindIP, env.s3Port),
|
||||
"s3_use_ssl": false,
|
||||
"s3_path_style": true,
|
||||
"aws_region": "us-east-1",
|
||||
"aws_access_key": env.accessKey,
|
||||
"aws_secret_key": env.secretKey,
|
||||
"rest_auth_type": "oauth2",
|
||||
"oauth2_uri": catalogURL + "/v1/oauth/tokens",
|
||||
"credential": env.accessKey + ":" + env.secretKey,
|
||||
},
|
||||
}
|
||||
|
||||
writeJSON(t, filepath.Join(env.configDir, "source.json"), source)
|
||||
writeJSON(t, filepath.Join(env.configDir, "destination.json"), destination)
|
||||
if err := os.WriteFile(filepath.Join(env.configDir, "state.json"), []byte("{}\n"), 0644); err != nil {
|
||||
t.Fatalf("Failed to write state.json: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) runOLake(t *testing.T, args ...string) string {
|
||||
t.Helper()
|
||||
|
||||
full := append([]string{
|
||||
"run", "--rm",
|
||||
"-v", dockerMount(env.configDir) + ":/mnt/config",
|
||||
olakeImage(),
|
||||
}, args...)
|
||||
|
||||
cmd := exec.Command("docker", full...)
|
||||
done := make(chan struct{})
|
||||
var out []byte
|
||||
var err error
|
||||
go func() {
|
||||
out, err = cmd.CombinedOutput()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(olakeRunTimeout):
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
t.Fatalf("olake %s did not finish within %s", args[0], olakeRunTimeout)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("olake %s failed: %v\n%s", args[0], err, tailLines(string(out), 40))
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) readTable(t *testing.T, mode string) string {
|
||||
t.Helper()
|
||||
|
||||
cmd := exec.Command("docker", "run", "--rm", readerImage, mode,
|
||||
"--catalog-url", fmt.Sprintf("http://%s:%d", env.bindIP, env.icebergPort),
|
||||
"--warehouse", "s3://"+tableBucketName,
|
||||
"--prefix", tableBucketName,
|
||||
"--s3-endpoint", fmt.Sprintf("http://%s:%d", env.bindIP, env.s3Port),
|
||||
"--access-key", env.accessKey,
|
||||
"--secret-key", env.secretKey,
|
||||
"--namespace", expectedNamespace,
|
||||
"--table", expectedTable,
|
||||
)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("reader (%s) failed: %v\n%s", mode, err, tailLines(string(out), 30))
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// listTableMetadata lists the table's metadata directory through the filer so
|
||||
// the repair assertion looks at real objects rather than at what the catalog
|
||||
// reports about itself.
|
||||
func (env *TestEnvironment) listTableMetadata(t *testing.T) []string {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/buckets/%s/%s/%s/metadata/?limit=200",
|
||||
env.bindIP, env.filerPort, tableBucketName, expectedNamespace, expectedTable)
|
||||
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to build filer request: %v", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("filer listing failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("filer listing returned %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var parsed struct {
|
||||
Entries []struct {
|
||||
FullPath string `json:"FullPath"`
|
||||
} `json:"Entries"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
t.Fatalf("Failed to parse filer listing: %v\n%s", err, body)
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(parsed.Entries))
|
||||
for _, e := range parsed.Entries {
|
||||
names = append(names, e.FullPath[strings.LastIndex(e.FullPath, "/")+1:])
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if env.postgresContainer != "" {
|
||||
_ = exec.Command("docker", "rm", "-f", env.postgresContainer).Run()
|
||||
}
|
||||
if env.weedCancel != nil {
|
||||
env.weedCancel()
|
||||
}
|
||||
if env.weedProcess != nil {
|
||||
_ = env.weedProcess.Wait()
|
||||
}
|
||||
if env.dataDir != "" {
|
||||
_ = os.RemoveAll(env.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
func buildReaderImage(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get working directory: %v", err)
|
||||
}
|
||||
cmd := exec.Command("docker", "build",
|
||||
"-f", filepath.Join(wd, "Dockerfile.reader"),
|
||||
"-t", readerImage, wd)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to build reader image: %v\n%s", err, tailLines(string(out), 30))
|
||||
}
|
||||
}
|
||||
|
||||
func olakeImage() string {
|
||||
if v := os.Getenv("OLAKE_IMAGE"); v != "" {
|
||||
return v
|
||||
}
|
||||
return olakeDefaultImage
|
||||
}
|
||||
|
||||
func postgresImage() string {
|
||||
if v := os.Getenv("POSTGRES_IMAGE"); v != "" {
|
||||
return v
|
||||
}
|
||||
return postgresDefaultImage
|
||||
}
|
||||
|
||||
func requireOLakeRuntime(t *testing.T) {
|
||||
t.Helper()
|
||||
if os.Getenv("SEAWEEDFS_SKIP_OLAKE_TESTS") != "" {
|
||||
t.Skip("SEAWEEDFS_SKIP_OLAKE_TESTS set")
|
||||
}
|
||||
if _, err := exec.LookPath("docker"); err != nil {
|
||||
t.Skip("docker not available, skipping OLake integration test")
|
||||
}
|
||||
if err := exec.Command("docker", "info").Run(); err != nil {
|
||||
t.Skip("docker daemon not reachable, skipping OLake integration test")
|
||||
}
|
||||
}
|
||||
|
||||
func waitForService(url string, timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
client := &http.Client{Timeout: 3 * time.Second}
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := client.Get(url)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode < 500 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func writeJSON(t *testing.T, path string, v any) {
|
||||
t.Helper()
|
||||
body, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal %s: %v", path, err)
|
||||
}
|
||||
if err := os.WriteFile(path, append(body, '\n'), 0644); err != nil {
|
||||
t.Fatalf("Failed to write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// dockerMount normalises a host path for a -v bind mount. Docker Desktop
|
||||
// accepts forward slashes on Windows; the native separator it does not.
|
||||
func dockerMount(path string) string {
|
||||
return strings.ReplaceAll(path, `\`, "/")
|
||||
}
|
||||
|
||||
func nonEmptyLines(s string) []string {
|
||||
var out []string
|
||||
for _, line := range strings.Split(s, "\n") {
|
||||
if trimmed := strings.TrimSpace(line); trimmed != "" {
|
||||
out = append(out, trimmed)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func tailLines(s string, n int) string {
|
||||
lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
|
||||
if len(lines) > n {
|
||||
lines = lines[len(lines)-n:]
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
+12
-68
@@ -3,7 +3,6 @@ package cluster
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -28,7 +27,6 @@ type LockClient struct {
|
||||
// correct: the filer forwards to the real primary as a fallback.
|
||||
ringMu sync.RWMutex
|
||||
ring *lock_manager.HashRing
|
||||
ringServers []pb.ServerAddress
|
||||
ringVersion int64
|
||||
|
||||
// priorRing is the ring before the most recent change, kept for priorWindow so a
|
||||
@@ -37,24 +35,15 @@ type LockClient struct {
|
||||
priorRing *lock_manager.HashRing
|
||||
ringChangedAt time.Time
|
||||
priorWindow time.Duration
|
||||
|
||||
// noLockServerRetryPeriod bounds retries when every filer reports "no
|
||||
// lock server found": an empty lock ring is a systemic fault that waiting
|
||||
// on a lock holder cannot resolve, unlike ordinary contention. The bound
|
||||
// is long enough to ride out a master leader change (ring reset + fresh
|
||||
// snapshot) but short enough that a write fails instead of hanging
|
||||
// forever.
|
||||
noLockServerRetryPeriod time.Duration
|
||||
}
|
||||
|
||||
func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *LockClient {
|
||||
return &LockClient{
|
||||
grpcDialOption: grpcDialOption,
|
||||
maxLockDuration: 5 * time.Second,
|
||||
sleepDuration: 2473 * time.Millisecond,
|
||||
seedFiler: seedFiler,
|
||||
priorWindow: 5 * time.Second,
|
||||
noLockServerRetryPeriod: 15 * time.Second,
|
||||
grpcDialOption: grpcDialOption,
|
||||
maxLockDuration: 5 * time.Second,
|
||||
sleepDuration: 2473 * time.Millisecond,
|
||||
seedFiler: seedFiler,
|
||||
priorWindow: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,16 +58,10 @@ func (lc *LockClient) SetRing(servers []pb.ServerAddress, version int64) {
|
||||
return
|
||||
}
|
||||
lc.ringVersion = version
|
||||
sorted := slices.Clone(servers)
|
||||
slices.Sort(sorted)
|
||||
if slices.Equal(sorted, lc.ringServers) {
|
||||
return
|
||||
}
|
||||
lc.ringServers = sorted
|
||||
// Build a fresh ring (not an in-place mutation) so the outgoing ring survives as
|
||||
// priorRing with its own servers for the cooling-off window.
|
||||
newRing := lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
|
||||
newRing.SetServers(sorted)
|
||||
newRing.SetServers(servers)
|
||||
if lc.ring != nil {
|
||||
lc.priorRing = lc.ring
|
||||
lc.ringChangedAt = time.Now()
|
||||
@@ -86,18 +69,6 @@ func (lc *LockClient) SetRing(servers []pb.ServerAddress, version int64) {
|
||||
lc.ring = newRing
|
||||
}
|
||||
|
||||
// ResetRing clears only the version gate so the first update from a
|
||||
// different master applies unconditionally: ring versions are per-master
|
||||
// monotonic and a high version accepted from a former leader must not
|
||||
// reject the new leader's snapshot. The last ring keeps routing during the
|
||||
// gap rather than falling back to the seed filer, and the arriving ring
|
||||
// becomes the prior ring for the cooling-off window.
|
||||
func (lc *LockClient) ResetRing() {
|
||||
lc.ringMu.Lock()
|
||||
defer lc.ringMu.Unlock()
|
||||
lc.ringVersion = 0
|
||||
}
|
||||
|
||||
// hostForKey returns the filer that should own key per the current ring view,
|
||||
// falling back to the seed filer when no view has been received yet.
|
||||
func (lc *LockClient) hostForKey(key string) pb.ServerAddress {
|
||||
@@ -162,9 +133,7 @@ type LiveLock struct {
|
||||
consecutiveFailures int // Track connection failures to trigger fallback
|
||||
}
|
||||
|
||||
// NewShortLivedLock creates a lock with a 5-second duration.
|
||||
// It returns nil when the lock cannot be acquired because no lock server
|
||||
// exists; ordinary contention is still waited out.
|
||||
// NewShortLivedLock creates a lock with a 5-second duration
|
||||
func (lc *LockClient) NewShortLivedLock(key string, owner string) (lock *LiveLock) {
|
||||
lock = &LiveLock{
|
||||
key: key,
|
||||
@@ -175,10 +144,7 @@ func (lc *LockClient) NewShortLivedLock(key string, owner string) (lock *LiveLoc
|
||||
self: owner,
|
||||
lc: lc,
|
||||
}
|
||||
if err := lock.retryUntilLocked(5 * time.Second); err != nil {
|
||||
glog.Warningf("create lock %s: %v", key, err)
|
||||
return nil
|
||||
}
|
||||
lock.retryUntilLocked(5 * time.Second)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -201,10 +167,7 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
lockTTL: lockTTL,
|
||||
}
|
||||
// Block until acquired
|
||||
if err := lock.retryUntilLocked(lockTTL); err != nil {
|
||||
glog.Warningf("create lock %s: %v", key, err)
|
||||
return nil
|
||||
}
|
||||
lock.retryUntilLocked(lockTTL)
|
||||
// Start renewal goroutine using a ticker for interruptible sleep
|
||||
lock.renewalDone = make(chan struct{})
|
||||
go func() {
|
||||
@@ -303,31 +266,12 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
// several seconds): when a holder on another mount releases the lock, the
|
||||
// waiter must pick it up promptly, otherwise cross-mount write handoff stalls
|
||||
// long enough to time out clients.
|
||||
func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) error {
|
||||
var unavailableSince time.Time
|
||||
func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) {
|
||||
for lock.renewToken == "" {
|
||||
err := lock.AttemptToLock(lockDuration)
|
||||
if err == nil {
|
||||
unavailableSince = time.Time{}
|
||||
continue
|
||||
}
|
||||
glog.V(1).Infof("create lock %s: %v", lock.key, err)
|
||||
if strings.Contains(err.Error(), "lock already owned") {
|
||||
// Ordinary contention: a reachable server holds the lock, so
|
||||
// waiting is the point and has no bound.
|
||||
unavailableSince = time.Time{}
|
||||
continue
|
||||
}
|
||||
// Anything else — "no lock server found", a dead ring member refusing
|
||||
// connections — is a systemic fault waiting cannot fix; give up once
|
||||
// it persists past the retry period.
|
||||
if unavailableSince.IsZero() {
|
||||
unavailableSince = time.Now()
|
||||
} else if time.Since(unavailableSince) > lock.lc.noLockServerRetryPeriod {
|
||||
return err
|
||||
if err := lock.AttemptToLock(lockDuration); err != nil {
|
||||
glog.V(1).Infof("create lock %s: %v", lock.key, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// The gateway must resolve a lock key to the same primary the filers do,
|
||||
@@ -157,135 +152,6 @@ func TestLockClientPriorOwnerForKeyExpires(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A master change clears the version gate so the new leader's (lower-versioned)
|
||||
// snapshot applies — versions are only comparable within one master's stream.
|
||||
func TestLockClientResetRing(t *testing.T) {
|
||||
lc := NewLockClient(nil, "seed:8888")
|
||||
|
||||
lc.SetRing([]pb.ServerAddress{"filer-a:8888", "filer-b:8888"}, 100)
|
||||
lc.ResetRing()
|
||||
|
||||
// The last ring keeps routing during the gap; only version acceptance
|
||||
// is reset so the new leader's (lower-versioned) snapshot applies.
|
||||
if got := lc.hostForKey("k"); got == "seed:8888" {
|
||||
t.Fatal("expected the previous ring to keep routing after reset")
|
||||
}
|
||||
lc.SetRing([]pb.ServerAddress{"filer-z:8888"}, 50)
|
||||
if got := lc.hostForKey("k"); got != "filer-z:8888" {
|
||||
t.Fatalf("lower version from new master not applied, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
type noLockServerFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
}
|
||||
|
||||
func (s *noLockServerFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{Error: lock_manager.NoLockServerError.Error()}, nil
|
||||
}
|
||||
|
||||
// When every filer reports an empty lock ring, lock acquisition must fail
|
||||
// after a bounded period instead of hanging the write forever.
|
||||
func TestNewShortLivedLockFailsFastOnNoLockServer(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, &noLockServerFiler{})
|
||||
go grpcServer.Serve(listener)
|
||||
defer grpcServer.Stop()
|
||||
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
host, port, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
// "host:httpPort.grpcPort" dials the fake filer's port directly.
|
||||
lc := NewLockClient(dialOption, pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
lc.noLockServerRetryPeriod = 200 * time.Millisecond
|
||||
|
||||
start := time.Now()
|
||||
lock := lc.NewShortLivedLock("test-key", "test-owner")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if lock != nil {
|
||||
t.Fatal("expected nil lock when no lock server exists")
|
||||
}
|
||||
if elapsed > 10*time.Second {
|
||||
t.Fatalf("lock acquisition took %v, expected fail-fast", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
type contendedLockFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
}
|
||||
|
||||
func (s *contendedLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{Error: "lock already owned by someone"}, nil
|
||||
}
|
||||
|
||||
// A lock held by another owner is ordinary contention: acquisition waits it
|
||||
// out rather than failing on the unavailability bound.
|
||||
func TestNewShortLivedLockWaitsOutContention(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, &contendedLockFiler{})
|
||||
go grpcServer.Serve(listener)
|
||||
defer grpcServer.Stop()
|
||||
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
host, port, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
lc := NewLockClient(dialOption, pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
lc.noLockServerRetryPeriod = 200 * time.Millisecond
|
||||
|
||||
done := make(chan *LiveLock, 1)
|
||||
go func() {
|
||||
done <- lc.NewShortLivedLock("test-key", "test-owner")
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("ordinary lock contention must not hit the unavailability bound")
|
||||
case <-time.After(3 * lc.noLockServerRetryPeriod):
|
||||
}
|
||||
}
|
||||
|
||||
// A ring member that refuses connections is unavailability, not contention:
|
||||
// acquisition fails on the same bound as "no lock server found".
|
||||
func TestNewShortLivedLockFailsFastOnUnreachableFiler(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
addr := listener.Addr().String()
|
||||
listener.Close()
|
||||
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
lc := NewLockClient(dialOption, pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
lc.noLockServerRetryPeriod = 200 * time.Millisecond
|
||||
|
||||
start := time.Now()
|
||||
lock := lc.NewShortLivedLock("test-key", "test-owner")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if lock != nil {
|
||||
t.Fatal("expected nil lock when the ring member is unreachable")
|
||||
}
|
||||
if elapsed > 10*time.Second {
|
||||
t.Fatalf("lock acquisition took %v, expected fail-fast", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// LiveLock.generation is a fencing token written and read with 64-bit atomic
|
||||
// operations. On 32-bit platforms (GOARCH=386 and GOARCH=arm) a 64-bit atomic
|
||||
// op requires an 8-byte-aligned address, which Go only guarantees for the
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package lock_manager
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -55,14 +54,6 @@ func (r *LockRing) SetSnapshot(servers []pb.ServerAddress, version int64) bool {
|
||||
r.Unlock()
|
||||
return false
|
||||
}
|
||||
// An unchanged member list is only a version refresh: installing it as a
|
||||
// new snapshot would run the topology-change callback and restart the
|
||||
// prior-owner window on every periodic rebroadcast.
|
||||
if len(r.snapshots) > 0 && slices.Equal(servers, r.snapshots[0].servers) {
|
||||
r.version = version
|
||||
r.Unlock()
|
||||
return true
|
||||
}
|
||||
r.version = version
|
||||
// Update the ring while holding the lock so version and ring state
|
||||
// are always consistent — prevents a concurrent SetSnapshot from
|
||||
@@ -83,19 +74,6 @@ func (r *LockRing) SetSnapshot(servers []pb.ServerAddress, version int64) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Reset clears only the version gate so the first update from a different
|
||||
// master always applies: ring versions are per-master monotonic, and a high
|
||||
// version accepted from a former leader must not reject the new leader's
|
||||
// view. The ring itself stays installed — writes keep routing to the last
|
||||
// known owner during the gap instead of every filer treating itself as the
|
||||
// owner, and the arriving snapshot transitions off it with the usual
|
||||
// prior-owner window.
|
||||
func (r *LockRing) Reset() {
|
||||
r.Lock()
|
||||
defer r.Unlock()
|
||||
r.version = 0
|
||||
}
|
||||
|
||||
// Version returns the current ring version.
|
||||
func (r *LockRing) Version() int64 {
|
||||
r.RLock()
|
||||
|
||||
@@ -96,42 +96,3 @@ func TestLockRing_VersionRejectsStale(t *testing.T) {
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, 1, len(r.GetSnapshot()))
|
||||
}
|
||||
|
||||
func TestLockRing_SetSnapshotUnchangedOnlyBumpsVersion(t *testing.T) {
|
||||
r := NewLockRing(100 * time.Millisecond)
|
||||
callbacks := 0
|
||||
r.SetTakeSnapshotCallback(func(snapshot []pb.ServerAddress) { callbacks++ })
|
||||
|
||||
assert.True(t, r.SetSnapshot([]pb.ServerAddress{"a:1", "b:2"}, 100))
|
||||
assert.Equal(t, 1, callbacks)
|
||||
|
||||
// A periodic rebroadcast with the same members refreshes the version
|
||||
// without a new snapshot or another topology-change callback.
|
||||
assert.True(t, r.SetSnapshot([]pb.ServerAddress{"b:2", "a:1"}, 200))
|
||||
assert.Equal(t, int64(200), r.Version())
|
||||
assert.Equal(t, 1, r.GetSnapshotCount())
|
||||
assert.Equal(t, 1, callbacks, "unchanged ring must not fire the topology callback")
|
||||
|
||||
assert.True(t, r.SetSnapshot([]pb.ServerAddress{"a:1", "b:2", "c:3"}, 300))
|
||||
assert.Equal(t, 2, callbacks)
|
||||
}
|
||||
|
||||
func TestLockRing_Reset(t *testing.T) {
|
||||
r := NewLockRing(100 * time.Millisecond)
|
||||
|
||||
// A high version accepted from a former leader must not reject the new
|
||||
// leader's view once the client has moved masters.
|
||||
ok := r.SetSnapshot([]pb.ServerAddress{"a:1", "b:2"}, 100)
|
||||
assert.True(t, ok)
|
||||
|
||||
r.Reset()
|
||||
assert.Equal(t, int64(0), r.Version())
|
||||
// The operational ring survives the reset: writes keep routing to the
|
||||
// last known owner until the new leader's snapshot arrives.
|
||||
assert.Equal(t, 2, len(r.GetSnapshot()))
|
||||
assert.NotEqual(t, "", string(r.GetPrimary("key")))
|
||||
|
||||
ok = r.SetSnapshot([]pb.ServerAddress{"c:1"}, 50)
|
||||
assert.True(t, ok, "lower version from a different master must apply after reset")
|
||||
assert.Equal(t, 1, len(r.GetSnapshot()))
|
||||
}
|
||||
@@ -11,38 +11,29 @@ import (
|
||||
|
||||
const LockRingStabilizationInterval = 1 * time.Second
|
||||
|
||||
// LockRingRebroadcastInterval is how often the ring is re-sent even when
|
||||
// membership has not changed. Broadcasts are otherwise purely event-driven,
|
||||
// so a single lost or poisoned update would be permanent without this.
|
||||
const LockRingRebroadcastInterval = 30 * time.Second
|
||||
|
||||
// LockRingManager tracks filer membership for the distributed lock ring.
|
||||
// It batches rapid topology changes (e.g., node drop + join) with a
|
||||
// stabilization timer, then broadcasts the complete member list atomically
|
||||
// so filers receive a single consistent ring update instead of multiple
|
||||
// intermediate states.
|
||||
type LockRingManager struct {
|
||||
mu sync.Mutex
|
||||
members map[FilerGroupName]map[pb.ServerAddress]struct{}
|
||||
version map[FilerGroupName]int64
|
||||
lastBroadcast map[FilerGroupName]*master_pb.LockRingUpdate
|
||||
pendingTimer map[FilerGroupName]*time.Timer
|
||||
rebroadcastTimer map[FilerGroupName]*time.Timer
|
||||
broadcastFn func(resp *master_pb.KeepConnectedResponse)
|
||||
stabilizeDelay time.Duration
|
||||
rebroadcastInterval time.Duration
|
||||
mu sync.Mutex
|
||||
members map[FilerGroupName]map[pb.ServerAddress]struct{}
|
||||
version map[FilerGroupName]int64
|
||||
lastBroadcast map[FilerGroupName]*master_pb.LockRingUpdate
|
||||
pendingTimer map[FilerGroupName]*time.Timer
|
||||
broadcastFn func(resp *master_pb.KeepConnectedResponse)
|
||||
stabilizeDelay time.Duration
|
||||
}
|
||||
|
||||
func NewLockRingManager(broadcastFn func(resp *master_pb.KeepConnectedResponse)) *LockRingManager {
|
||||
return &LockRingManager{
|
||||
members: make(map[FilerGroupName]map[pb.ServerAddress]struct{}),
|
||||
version: make(map[FilerGroupName]int64),
|
||||
lastBroadcast: make(map[FilerGroupName]*master_pb.LockRingUpdate),
|
||||
pendingTimer: make(map[FilerGroupName]*time.Timer),
|
||||
rebroadcastTimer: make(map[FilerGroupName]*time.Timer),
|
||||
broadcastFn: broadcastFn,
|
||||
stabilizeDelay: LockRingStabilizationInterval,
|
||||
rebroadcastInterval: LockRingRebroadcastInterval,
|
||||
members: make(map[FilerGroupName]map[pb.ServerAddress]struct{}),
|
||||
version: make(map[FilerGroupName]int64),
|
||||
lastBroadcast: make(map[FilerGroupName]*master_pb.LockRingUpdate),
|
||||
pendingTimer: make(map[FilerGroupName]*time.Timer),
|
||||
broadcastFn: broadcastFn,
|
||||
stabilizeDelay: LockRingStabilizationInterval,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,64 +116,16 @@ func (lrm *LockRingManager) scheduleBroadcast(filerGroup FilerGroupName) {
|
||||
|
||||
func (lrm *LockRingManager) doBroadcast(filerGroup FilerGroupName) {
|
||||
lrm.mu.Lock()
|
||||
delete(lrm.pendingTimer, filerGroup)
|
||||
lrm.mu.Unlock()
|
||||
lrm.emit(filerGroup)
|
||||
}
|
||||
|
||||
// rebroadcast re-sends the current ring unless a membership broadcast is
|
||||
// still stabilizing — emitting mid-window would publish an intermediate
|
||||
// topology that the pending timer immediately replaces. The check and the
|
||||
// update must sit in one critical section or a membership change can slip
|
||||
// a pending timer in between.
|
||||
func (lrm *LockRingManager) rebroadcast(filerGroup FilerGroupName) {
|
||||
lrm.mu.Lock()
|
||||
var update *master_pb.LockRingUpdate
|
||||
if _, pending := lrm.pendingTimer[filerGroup]; !pending {
|
||||
update = lrm.nextBroadcastUpdate(filerGroup)
|
||||
}
|
||||
lrm.mu.Unlock()
|
||||
lrm.sendUpdate(filerGroup, update)
|
||||
}
|
||||
|
||||
func (lrm *LockRingManager) emit(filerGroup FilerGroupName) {
|
||||
lrm.mu.Lock()
|
||||
update := lrm.nextBroadcastUpdate(filerGroup)
|
||||
lrm.mu.Unlock()
|
||||
lrm.sendUpdate(filerGroup, update)
|
||||
}
|
||||
|
||||
func (lrm *LockRingManager) sendUpdate(filerGroup FilerGroupName, update *master_pb.LockRingUpdate) {
|
||||
if update == nil {
|
||||
return
|
||||
}
|
||||
glog.V(0).Infof("LockRing: broadcasting ring update for group %q version %d: %v", filerGroup, update.Version, update.Servers)
|
||||
if lrm.broadcastFn != nil {
|
||||
lrm.broadcastFn(&master_pb.KeepConnectedResponse{
|
||||
LockRingUpdate: update,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// nextBroadcastUpdate stamps the current members into an update and re-arms
|
||||
// the periodic rebroadcast. It returns nil for an empty member list: an empty
|
||||
// lock ring is never usable, so a late "last member removed" event from a
|
||||
// former leader must not propagate and wedge every lock client. The last
|
||||
// non-empty broadcast stays in lastBroadcast for reconnecting clients.
|
||||
// Caller must hold lrm.mu.
|
||||
func (lrm *LockRingManager) nextBroadcastUpdate(filerGroup FilerGroupName) *master_pb.LockRingUpdate {
|
||||
members := lrm.members[filerGroup]
|
||||
if len(members) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Use wall-clock nanoseconds so the version survives master restarts
|
||||
// without persistence — a restarted master produces a version greater
|
||||
// than any pre-restart value (assuming clocks don't jump backward).
|
||||
version := time.Now().UnixNano()
|
||||
lrm.version[filerGroup] = version
|
||||
servers := make([]string, 0, len(members))
|
||||
for addr := range members {
|
||||
servers = append(servers, string(addr))
|
||||
servers := make([]string, 0)
|
||||
if members, ok := lrm.members[filerGroup]; ok {
|
||||
for addr := range members {
|
||||
servers = append(servers, string(addr))
|
||||
}
|
||||
}
|
||||
update := &master_pb.LockRingUpdate{
|
||||
FilerGroup: string(filerGroup),
|
||||
@@ -190,13 +133,16 @@ func (lrm *LockRingManager) nextBroadcastUpdate(filerGroup FilerGroupName) *mast
|
||||
Version: version,
|
||||
}
|
||||
lrm.lastBroadcast[filerGroup] = update
|
||||
if timer, ok := lrm.rebroadcastTimer[filerGroup]; ok {
|
||||
timer.Stop()
|
||||
delete(lrm.pendingTimer, filerGroup)
|
||||
lrm.mu.Unlock()
|
||||
|
||||
glog.V(0).Infof("LockRing: broadcasting ring update for group %q version %d: %v", filerGroup, version, servers)
|
||||
|
||||
if lrm.broadcastFn != nil {
|
||||
lrm.broadcastFn(&master_pb.KeepConnectedResponse{
|
||||
LockRingUpdate: update,
|
||||
})
|
||||
}
|
||||
lrm.rebroadcastTimer[filerGroup] = time.AfterFunc(lrm.rebroadcastInterval, func() {
|
||||
lrm.rebroadcast(filerGroup)
|
||||
})
|
||||
return update
|
||||
}
|
||||
|
||||
// FlushPending fires any pending timer immediately (for testing or shutdown).
|
||||
|
||||
@@ -213,111 +213,6 @@ func TestLockRingManager_NoBroadcastWithoutFn(t *testing.T) {
|
||||
time.Sleep(50 * time.Millisecond) // should not panic
|
||||
}
|
||||
|
||||
func TestLockRingManager_EmptyRingNotBroadcast(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var broadcasts []*master_pb.LockRingUpdate
|
||||
|
||||
lrm := NewLockRingManager(func(resp *master_pb.KeepConnectedResponse) {
|
||||
mu.Lock()
|
||||
if resp.LockRingUpdate != nil {
|
||||
broadcasts = append(broadcasts, resp.LockRingUpdate)
|
||||
}
|
||||
mu.Unlock()
|
||||
})
|
||||
lrm.stabilizeDelay = 50 * time.Millisecond
|
||||
|
||||
group := FilerGroupName("default")
|
||||
|
||||
lrm.AddServer(group, "filer1:8888")
|
||||
lrm.FlushPending(group)
|
||||
|
||||
mu.Lock()
|
||||
broadcasts = nil
|
||||
mu.Unlock()
|
||||
|
||||
// Removing the last member must not propagate an empty ring.
|
||||
lrm.RemoveServer(group, "filer1:8888")
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
mu.Lock()
|
||||
assert.Equal(t, 0, len(broadcasts), "empty ring must not be broadcast")
|
||||
mu.Unlock()
|
||||
|
||||
// The last non-empty snapshot is still served to reconnecting clients.
|
||||
update := lrm.GetLastUpdate(group)
|
||||
require.NotNil(t, update)
|
||||
assert.Equal(t, []string{"filer1:8888"}, update.Servers)
|
||||
}
|
||||
|
||||
func TestLockRingManager_PeriodicRebroadcast(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var broadcasts []*master_pb.LockRingUpdate
|
||||
|
||||
lrm := NewLockRingManager(func(resp *master_pb.KeepConnectedResponse) {
|
||||
mu.Lock()
|
||||
if resp.LockRingUpdate != nil {
|
||||
broadcasts = append(broadcasts, resp.LockRingUpdate)
|
||||
}
|
||||
mu.Unlock()
|
||||
})
|
||||
lrm.stabilizeDelay = 20 * time.Millisecond
|
||||
lrm.rebroadcastInterval = 60 * time.Millisecond
|
||||
|
||||
group := FilerGroupName("default")
|
||||
lrm.AddServer(group, "filer1:8888")
|
||||
|
||||
// Without any further membership change, the ring keeps being re-sent so
|
||||
// a lost or poisoned update cannot be permanent.
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
mu.Lock()
|
||||
require.GreaterOrEqual(t, len(broadcasts), 2, "ring should rebroadcast periodically")
|
||||
for i := 1; i < len(broadcasts); i++ {
|
||||
assert.Greater(t, broadcasts[i].Version, broadcasts[i-1].Version)
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
func TestLockRingManager_RebroadcastDefersToPendingStabilization(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var broadcasts []*master_pb.LockRingUpdate
|
||||
|
||||
lrm := NewLockRingManager(func(resp *master_pb.KeepConnectedResponse) {
|
||||
mu.Lock()
|
||||
if resp.LockRingUpdate != nil {
|
||||
broadcasts = append(broadcasts, resp.LockRingUpdate)
|
||||
}
|
||||
mu.Unlock()
|
||||
})
|
||||
lrm.stabilizeDelay = 100 * time.Millisecond
|
||||
lrm.rebroadcastInterval = 30 * time.Millisecond
|
||||
|
||||
group := FilerGroupName("default")
|
||||
lrm.AddServer(group, "filer1:8888")
|
||||
lrm.FlushPending(group)
|
||||
|
||||
mu.Lock()
|
||||
require.Len(t, broadcasts, 1)
|
||||
mu.Unlock()
|
||||
|
||||
// A membership change just before the periodic tick: the rebroadcast must
|
||||
// not publish the unsettled ring ahead of the stabilization timer.
|
||||
lrm.RemoveServer(group, "filer1:8888")
|
||||
lrm.AddServer(group, "filer2:8888")
|
||||
time.Sleep(2 * lrm.rebroadcastInterval)
|
||||
|
||||
mu.Lock()
|
||||
assert.Len(t, broadcasts, 1, "rebroadcast during stabilization should be deferred")
|
||||
mu.Unlock()
|
||||
|
||||
time.Sleep(2 * lrm.stabilizeDelay)
|
||||
|
||||
mu.Lock()
|
||||
require.GreaterOrEqual(t, len(broadcasts), 2)
|
||||
assert.Equal(t, []string{"filer2:8888"}, broadcasts[1].Servers)
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
func TestLockRingManager_GetLastUpdateReturnsBroadcastState(t *testing.T) {
|
||||
lrm := NewLockRingManager(nil)
|
||||
|
||||
|
||||
@@ -156,7 +156,7 @@ func backupFromLocation(volumeServer pb.ServerAddress, grpcDialOption grpc.DialO
|
||||
|
||||
// If local volume is larger than remote, recreate it
|
||||
if datSize > stats.TailOffset {
|
||||
if err := v.Destroy(false, false, false); err != nil {
|
||||
if err := v.Destroy(false, false); err != nil {
|
||||
v.Close()
|
||||
return fmt.Errorf("destroying volume: %w", err), false
|
||||
}
|
||||
|
||||
+17
-23
@@ -46,19 +46,17 @@ const (
|
||||
)
|
||||
|
||||
type MasterOptions struct {
|
||||
port *int
|
||||
portGrpc *int
|
||||
ip *string
|
||||
ipBind *string
|
||||
metaFolder *string
|
||||
peers *string
|
||||
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
|
||||
volumeSizeLimitMB *uint
|
||||
fileSizeLimitMB *int
|
||||
volumePreallocate *bool
|
||||
maxParallelVacuumPerServer *int
|
||||
vacuumIntervalSeconds *int
|
||||
vacuumDeleteEmptyAfterSeconds *int
|
||||
port *int
|
||||
portGrpc *int
|
||||
ip *string
|
||||
ipBind *string
|
||||
metaFolder *string
|
||||
peers *string
|
||||
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
|
||||
volumeSizeLimitMB *uint
|
||||
fileSizeLimitMB *int
|
||||
volumePreallocate *bool
|
||||
maxParallelVacuumPerServer *int
|
||||
// pulseSeconds *int
|
||||
defaultReplication *string
|
||||
garbageThreshold *float64
|
||||
@@ -95,8 +93,6 @@ func init() {
|
||||
m.fileSizeLimitMB = cmdMaster.Flag.Int("fileSizeLimitMB", 256, "limit the file size accepted by /submit, should match the volume servers' -fileSizeLimitMB (-volume.fileSizeLimitMB under weed server or weed mini, which set this for you)")
|
||||
m.volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
m.maxParallelVacuumPerServer = cmdMaster.Flag.Int("maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel per volume server")
|
||||
m.vacuumIntervalSeconds = cmdMaster.Flag.Int("vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
m.vacuumDeleteEmptyAfterSeconds = cmdMaster.Flag.Int("vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
// m.pulseSeconds = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
|
||||
m.defaultReplication = cmdMaster.Flag.String("defaultReplication", "", "Default replication type if not specified.")
|
||||
m.garbageThreshold = cmdMaster.Flag.Float64("garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
|
||||
@@ -471,14 +467,12 @@ func peerIndex(self pb.ServerAddress, peers []pb.ServerAddress) int {
|
||||
func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOption {
|
||||
masterAddress := pb.NewServerAddress(*m.ip, *m.port, *m.portGrpc)
|
||||
return &weed_server.MasterOption{
|
||||
Master: masterAddress,
|
||||
MetaFolder: *m.metaFolder,
|
||||
VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
|
||||
FileSizeLimitMB: *m.fileSizeLimitMB,
|
||||
VolumePreallocate: *m.volumePreallocate,
|
||||
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
|
||||
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
|
||||
VacuumDeleteEmptyAfterSeconds: *m.vacuumDeleteEmptyAfterSeconds,
|
||||
Master: masterAddress,
|
||||
MetaFolder: *m.metaFolder,
|
||||
VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
|
||||
FileSizeLimitMB: *m.fileSizeLimitMB,
|
||||
VolumePreallocate: *m.volumePreallocate,
|
||||
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
|
||||
// PulseSeconds: *m.pulseSeconds,
|
||||
DefaultReplicaPlacement: *m.defaultReplication,
|
||||
GarbageThreshold: *m.garbageThreshold,
|
||||
|
||||
@@ -47,8 +47,6 @@ func init() {
|
||||
mf.metricsIntervalSec = aws.Int(0)
|
||||
mf.raftResumeState = aws.Bool(false)
|
||||
mf.maxParallelVacuumPerServer = aws.Int(1)
|
||||
mf.vacuumIntervalSeconds = aws.Int(840)
|
||||
mf.vacuumDeleteEmptyAfterSeconds = aws.Int(0)
|
||||
mf.telemetryUrl = aws.String("https://telemetry.seaweedfs.com/api/collect")
|
||||
mf.telemetryEnabled = aws.Bool(false)
|
||||
}
|
||||
|
||||
@@ -427,8 +427,6 @@ func initMiniMasterFlags() {
|
||||
miniMasterOptions.volumeSizeLimitMB = cmdMini.Flag.Uint("master.volumeSizeLimitMB", defaultMiniVolumeSizeMB, "Master stops directing writes to oversized volumes (default: 128MB for mini)")
|
||||
miniMasterOptions.volumePreallocate = cmdMini.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
miniMasterOptions.maxParallelVacuumPerServer = cmdMini.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
|
||||
miniMasterOptions.vacuumIntervalSeconds = cmdMini.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
miniMasterOptions.vacuumDeleteEmptyAfterSeconds = cmdMini.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
miniMasterOptions.defaultReplication = cmdMini.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
|
||||
miniMasterOptions.garbageThreshold = cmdMini.Flag.Float64("master.garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
|
||||
miniMasterOptions.metricsAddress = cmdMini.Flag.String("master.metrics.address", "", "Prometheus gateway address")
|
||||
|
||||
@@ -618,7 +618,6 @@ func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer) {
|
||||
lanceRouter.Use(util_http.EscapeSemicolonsInQuery)
|
||||
|
||||
lanceServer := lance.NewServer(s3ApiServer, s3ApiServer)
|
||||
lanceServer.SetCredentialValidator(s3ApiServer)
|
||||
if s3opt.icebergCredentialRole != nil && *s3opt.icebergCredentialRole != "" {
|
||||
lanceServer.SetCredentialVendor(lanceCredentialVendor{s3ApiServer})
|
||||
}
|
||||
|
||||
@@ -41,7 +41,6 @@ copy_2 = 6 # create 2 x 6 = 12 actual volumes
|
||||
copy_3 = 3 # create 3 x 3 = 9 actual volumes
|
||||
copy_other = 1 # create n x 1 = n actual volumes
|
||||
threshold = 0.9 # create threshold
|
||||
reservation_timeout = "5m"# capacity reservation timeout before unreleased reservations expire
|
||||
disable = false # disables volume growth if true
|
||||
|
||||
# configuration flags for replication
|
||||
|
||||
@@ -98,8 +98,6 @@ func init() {
|
||||
masterOptions.volumeSizeLimitMB = cmdServer.Flag.Uint("master.volumeSizeLimitMB", util.DefaultVolumeSizeLimitMB, "Master stops directing writes to oversized volumes.")
|
||||
masterOptions.volumePreallocate = cmdServer.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
masterOptions.maxParallelVacuumPerServer = cmdServer.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
|
||||
masterOptions.vacuumIntervalSeconds = cmdServer.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
masterOptions.vacuumDeleteEmptyAfterSeconds = cmdServer.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
masterOptions.defaultReplication = cmdServer.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
|
||||
masterOptions.garbageThreshold = cmdServer.Flag.Float64("master.garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
|
||||
masterOptions.metricsAddress = cmdServer.Flag.String("master.metrics.address", "", "Prometheus gateway address")
|
||||
|
||||
@@ -43,7 +43,7 @@ func markVolumeReplicaWritable(ctx context.Context, grpcDialOption grpc.DialOpti
|
||||
// deleteVolume removes the volume from sourceVolumeServer via the canonical
|
||||
// volume_move helper.
|
||||
func deleteVolume(ctx context.Context, grpcDialOption grpc.DialOption, volumeId needle.VolumeId, sourceVolumeServer pb.ServerAddress, onlyEmpty bool, keepRemoteData bool) (err error) {
|
||||
return volume_move.NewMover(grpcDialOption).DeleteVolume(ctx, volumeId, sourceVolumeServer, onlyEmpty, false, keepRemoteData)
|
||||
return volume_move.NewMover(grpcDialOption).DeleteVolume(ctx, volumeId, sourceVolumeServer, onlyEmpty, keepRemoteData)
|
||||
}
|
||||
|
||||
func ChunkVolumeIds(volumeIds []needle.VolumeId, batchSize int) [][]needle.VolumeId {
|
||||
|
||||
+2
-19
@@ -7,7 +7,6 @@ import (
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
||||
@@ -74,11 +73,6 @@ type Filer struct {
|
||||
EmptyFolderCleanupDelay time.Duration
|
||||
persistedLogCache *persistedLogCache
|
||||
metaLogInflight metaLogInflight
|
||||
remoteTombstones *remoteDeletionTombstones
|
||||
// remoteTombstonesDone, when non-nil, is closed once the startup tombstone
|
||||
// rebuild finishes; lazy remote reads wait on it so a pending delete
|
||||
// cannot resurrect in the gap.
|
||||
remoteTombstonesDone atomic.Pointer[chan struct{}]
|
||||
}
|
||||
|
||||
func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerHost pb.ServerAddress, filerGroup string, collection string, replication string, dataCenter string, maxFilenameLength uint32, notifyFn func()) *Filer {
|
||||
@@ -94,7 +88,6 @@ func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerH
|
||||
deletionQuit: make(chan struct{}),
|
||||
DeletionRetryQueue: NewDeletionRetryQueue(),
|
||||
persistedLogCache: newPersistedLogCache(persistedLogCacheMaxBytes),
|
||||
remoteTombstones: newRemoteDeletionTombstones(),
|
||||
}
|
||||
if f.UniqueFilerId < 0 {
|
||||
f.UniqueFilerId = -f.UniqueFilerId
|
||||
@@ -181,10 +174,6 @@ func (f *Filer) AggregateFromPeers(self pb.ServerAddress, existingNodes []*maste
|
||||
glog.V(0).Infof("LockRing: applying master ring update v%d: %v", update.Version, servers)
|
||||
f.Dlm.LockRing.SetSnapshot(servers, update.Version)
|
||||
})
|
||||
f.MasterClient.SetOnMasterChangeFn(func(previous, current pb.ServerAddress) {
|
||||
glog.V(0).Infof("LockRing: master changed %s -> %s, resetting ring", previous, current)
|
||||
f.Dlm.LockRing.Reset()
|
||||
})
|
||||
|
||||
// Subscribe to the local filer first: its events reach the aggregated
|
||||
// buffer only through this subscription, and the peer watermarks must
|
||||
@@ -276,13 +265,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
|
||||
oldEntry := existing
|
||||
if oldEntry == nil {
|
||||
var findErr error
|
||||
oldEntry, findErr = f.FindEntry(ctx, entry.FullPath)
|
||||
if o_excl && findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) {
|
||||
// An exclusive create cannot decide whether the path exists when
|
||||
// the lookup itself failed; proceeding would upsert over it.
|
||||
return fmt.Errorf("find entry %s: %w", entry.FullPath, findErr)
|
||||
}
|
||||
oldEntry, _ = f.FindEntry(ctx, entry.FullPath)
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -606,7 +589,7 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
|
||||
lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) (bool, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.V(1).InfofCtx(ctx, "listing %q canceled: %v", p, ctx.Err())
|
||||
glog.Errorf("Context is done.")
|
||||
return false, fmt.Errorf("context canceled: %w", ctx.Err())
|
||||
default:
|
||||
if entry.TtlSec > 0 && !entry.IsDirectory() {
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
@@ -97,7 +96,7 @@ func newFilerWithFakeMaster(t *testing.T) (*Filer, *hookedStore, *collectionDele
|
||||
|
||||
mc := wdclient.NewMasterClient(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
"", cluster.FilerType, pb.ServerAddress("localhost:0"), "", "",
|
||||
"test", cluster.FilerType, pb.ServerAddress("localhost:0"), "", "",
|
||||
*pb.NewServiceDiscoveryFromMap(map[string]pb.ServerAddress{"m": masterAddress}),
|
||||
)
|
||||
|
||||
@@ -182,206 +181,3 @@ func TestDeleteEntryMetaAndDataDeletesCollectionWhenTheRequestIsCancelledMidDele
|
||||
t.Error("the bucket entry survived the delete")
|
||||
}
|
||||
}
|
||||
|
||||
func seedBucket(t *testing.T, store *hookedStore, path util.FullPath) {
|
||||
t.Helper()
|
||||
if err := store.InsertEntry(context.Background(), &Entry{
|
||||
FullPath: path,
|
||||
Attr: Attr{Mode: os.ModeDir | 0755},
|
||||
}); err != nil {
|
||||
t.Fatalf("seed bucket %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Two buckets resolving to one collection: deleting either must leave the
|
||||
// collection for the other. Previously the delete dropped the collection
|
||||
// named after the bucket regardless of where its data actually lived.
|
||||
func TestDeleteBucketKeepsSharedCollection(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets",
|
||||
Collection: "shared",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/a"))
|
||||
seedBucket(t, store, util.FullPath("/buckets/b"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/a", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
t.Fatalf("shared collection was deleted: %q", call.name)
|
||||
default:
|
||||
}
|
||||
if store.getEntry("/buckets/b") == nil {
|
||||
t.Error("the surviving bucket's entry is gone")
|
||||
}
|
||||
}
|
||||
|
||||
// A bucket named after a collection other buckets resolve to is still just a
|
||||
// bucket: deleting it must not take the shared collection down with it.
|
||||
func TestDeleteBucketNamedAfterSharedCollection(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets",
|
||||
Collection: "shared",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/shared"))
|
||||
seedBucket(t, store, util.FullPath("/buckets/other"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/shared", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
t.Fatalf("collection backing other buckets was deleted: %q", call.name)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// A rule pointing a non-bucket path at the same collection keeps it: the
|
||||
// collection serves files the bucket delete must not orphan.
|
||||
func TestDeleteBucketKeepsCollectionUsedByNonBucketPath(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/a",
|
||||
Collection: "cold",
|
||||
})
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/archives",
|
||||
Collection: "cold",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/a"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/a", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
t.Fatalf("collection used by /archives was deleted: %q", call.name)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// A broad prefix rule covering the whole tree keeps the collection even for a
|
||||
// lone bucket: the same collection backs non-bucket paths too.
|
||||
func TestDeleteBucketKeepsCollectionFromBroadRule(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/",
|
||||
Collection: "everything",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/a"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/a", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
t.Fatalf("collection from a / rule was deleted: %q", call.name)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// A bucket resolving to the filer's default collection keeps it: rule-less
|
||||
// writes outside buckets land there too, so it is never one bucket's alone.
|
||||
func TestDeleteBucketKeepsDefaultCollection(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.metaLogCollection = "everything"
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/a",
|
||||
Collection: "everything",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/a"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/a", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
t.Fatalf("the filer's default collection was deleted: %q", call.name)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// A rule nested under a surviving bucket keeps the collection: the other
|
||||
// bucket resolves elsewhere at its root, but objects deeper inside it still
|
||||
// land in the shared collection.
|
||||
func TestDeleteBucketKeepsCollectionFromNestedSiblingRule(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/a",
|
||||
Collection: "shared",
|
||||
})
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/b/deep",
|
||||
Collection: "shared",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/a"))
|
||||
seedBucket(t, store, util.FullPath("/buckets/b"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/a", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
t.Fatalf("collection used under /buckets/b/deep was deleted: %q", call.name)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// A grouped gateway writes to <group>_<bucket> regardless of the storage
|
||||
// rules, so that is the collection the delete must drop -- and a rule-named
|
||||
// collection the bucket never used must survive.
|
||||
func TestDeleteBucketUnderFilerGroup(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.MasterClient.FilerGroup = "tenant1"
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/photos",
|
||||
Collection: "archive",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/photos"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/photos", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
if call.name != "tenant1_photos" {
|
||||
t.Fatalf("CollectionDelete = %q, want %q", call.name, "tenant1_photos")
|
||||
}
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatal("CollectionDelete never reached the master")
|
||||
}
|
||||
}
|
||||
|
||||
// A collection only the deleted bucket resolves to is dropped under its real
|
||||
// name, so a dedicated custom collection does not leak its volumes.
|
||||
func TestDeleteBucketDeletesResolvedCollection(t *testing.T) {
|
||||
f, store, master := newFilerWithFakeMaster(t)
|
||||
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/only",
|
||||
Collection: "custom",
|
||||
})
|
||||
seedBucket(t, store, util.FullPath("/buckets/only"))
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/only", true, false, true, false, nil, 0); err != nil {
|
||||
t.Fatalf("DeleteEntryMetaAndData: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case call := <-master.calls:
|
||||
if call.name != "custom" {
|
||||
t.Fatalf("CollectionDelete = %q, want %q", call.name, "custom")
|
||||
}
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatal("CollectionDelete never reached the master")
|
||||
}
|
||||
}
|
||||
@@ -68,10 +68,6 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
return nil
|
||||
}
|
||||
isDeleteCollection := f.IsBucket(entry)
|
||||
collectionName := ""
|
||||
if isDeleteCollection {
|
||||
collectionName = f.bucketCollection(ctx, entry.Name())
|
||||
}
|
||||
if entry.IsDirectory() {
|
||||
// delete the folder children, not including the folder itself
|
||||
err = f.doBatchDeleteFolderMetaAndData(ctx, entry, isRecursive, ignoreRecursiveError, shouldDeleteChunks && !isDeleteCollection, isDeleteCollection, isFromOtherCluster, signatures, func(hardLinkIds []HardLinkId) error {
|
||||
@@ -106,18 +102,17 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
}
|
||||
|
||||
if isDeleteCollection {
|
||||
if collectionName != "" {
|
||||
// the entry is already gone: a caller that hung up must not leave the
|
||||
// collection behind, so this cleanup outlives the request -- bounded all
|
||||
// the same, or a master that is down parks this handler indefinitely and
|
||||
// every client retry behind it parks another
|
||||
collectionCtx, cancelCollection := context.WithTimeout(context.WithoutCancel(ctx), collectionDeleteTimeout)
|
||||
f.DoDeleteCollection(collectionCtx, collectionName)
|
||||
cancelCollection()
|
||||
}
|
||||
collectionName := entry.Name()
|
||||
// the entry is already gone: a caller that hung up must not leave the
|
||||
// collection behind, so this cleanup outlives the request -- bounded all
|
||||
// the same, or a master that is down parks this handler indefinitely and
|
||||
// every client retry behind it parks another
|
||||
collectionCtx, cancelCollection := context.WithTimeout(context.WithoutCancel(ctx), collectionDeleteTimeout)
|
||||
f.DoDeleteCollection(collectionCtx, collectionName)
|
||||
cancelCollection()
|
||||
// drop bucket-labeled series held by this process; the S3 gateway
|
||||
// only cleans its own registry
|
||||
stats.DeleteBucketMetrics(entry.Name())
|
||||
stats.DeleteBucketMetrics(collectionName)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -125,15 +120,6 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
|
||||
func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry, isRecursive, ignoreRecursiveError, shouldDeleteChunks, isDeletingBucket, isFromOtherCluster bool, signatures []int32, onHardLinkIdsFn OnHardLinkIdsFunc) (err error) {
|
||||
|
||||
var dirTombstoneTs int64
|
||||
if isRecursive {
|
||||
// Tombstone the directory before its children: when the store drops
|
||||
// the subtree without listing it, or a child error aborts the walk,
|
||||
// the ancestor tombstone still covers every descendant.
|
||||
dirTombstoneTs = time.Now().UnixNano()
|
||||
f.noteRemoteDeletion(entry.FullPath, true, dirTombstoneTs)
|
||||
}
|
||||
|
||||
//collect all the chunks of this layer and delete them together at the end
|
||||
var chunksToDelete []*filer_pb.FileChunk
|
||||
lastFileName := ""
|
||||
@@ -143,9 +129,6 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
for {
|
||||
entries, _, err := f.ListDirectoryEntries(ctx, entry.FullPath, lastFileName, includeLastFile, PaginationSize, "", "", "")
|
||||
if err != nil {
|
||||
// nothing was deleted; a leftover tombstone would hide the
|
||||
// still-existing remote children
|
||||
f.unnoteRemoteDeletion(entry.FullPath, dirTombstoneTs)
|
||||
glog.ErrorfCtx(ctx, "list folder %s: %v", entry.FullPath, err)
|
||||
return fmt.Errorf("list folder %s: %v", entry.FullPath, err)
|
||||
}
|
||||
@@ -157,7 +140,6 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
|
||||
for _, sub := range entries {
|
||||
lastFileName = sub.Name()
|
||||
f.noteRemoteDeletion(sub.FullPath, sub.IsDirectory(), time.Now().UnixNano())
|
||||
if sub.IsDirectory() {
|
||||
subIsDeletingBucket := f.IsBucket(sub)
|
||||
err = f.doBatchDeleteFolderMetaAndData(ctx, sub, isRecursive, ignoreRecursiveError, shouldDeleteChunks, subIsDeletingBucket, isFromOtherCluster, nil, onHardLinkIdsFn)
|
||||
@@ -220,8 +202,6 @@ func (f *Filer) doDeleteEntryMetaAndData(ctx context.Context, entry *Entry, shou
|
||||
}
|
||||
}
|
||||
|
||||
f.noteRemoteDeletion(entry.FullPath, entry.IsDirectory(), time.Now().UnixNano())
|
||||
|
||||
if storeDeletionErr := f.Store.DeleteOneEntry(ctx, entry); storeDeletionErr != nil {
|
||||
return fmt.Errorf("filer store delete: %w", storeDeletionErr)
|
||||
}
|
||||
@@ -241,75 +221,6 @@ func (f *Filer) doDeleteEntryMetaAndData(ctx context.Context, entry *Entry, shou
|
||||
// DeleteCollection, still has retry budget left.
|
||||
const collectionDeleteTimeout = 15 * time.Second
|
||||
|
||||
// bucketCollection resolves the collection a bucket's objects land in
|
||||
// through the same chain the write path uses -- a grouped gateway's explicit
|
||||
// collection, then the storage rules, then the bucket name -- and reports it
|
||||
// only when nothing outside the bucket can still route into it. A shared
|
||||
// collection must survive the bucket delete: dropping it removes volumes
|
||||
// other paths still write to. A listing failure keeps the collection, the
|
||||
// safe side of an unknown.
|
||||
func (f *Filer) bucketCollection(ctx context.Context, bucket string) (collection string) {
|
||||
bucketDir := f.DirBucketsPath + "/" + bucket + "/"
|
||||
resolve := func(dir, name string) string {
|
||||
if f.MasterClient != nil {
|
||||
if group := f.MasterClient.FilerGroup; group != "" {
|
||||
return group + "_" + name
|
||||
}
|
||||
}
|
||||
return util.Nvl(f.FilerConf.MatchStorageRule(dir).Collection, name)
|
||||
}
|
||||
collection = resolve(bucketDir, bucket)
|
||||
|
||||
// Rule-less writes outside buckets fall back to the filer's default
|
||||
// collection, so a bucket resolving there shares it with them.
|
||||
if collection == f.metaLogCollection {
|
||||
return ""
|
||||
}
|
||||
|
||||
// A rule whose prefix escapes the bucket can route other paths into the
|
||||
// same collection, including prefixes nested under surviving buckets.
|
||||
for _, rule := range f.FilerConf.ToProto().Locations {
|
||||
prefix := strings.TrimSuffix(rule.LocationPrefix, "/") + "/"
|
||||
if strings.HasPrefix(prefix, bucketDir) {
|
||||
continue
|
||||
}
|
||||
if f.FilerConf.MatchStorageRule(prefix).Collection == collection {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
siblings, err := f.listBuckets(ctx)
|
||||
if err != nil {
|
||||
glog.ErrorfCtx(ctx, "list buckets for collection check: %v", err)
|
||||
return ""
|
||||
}
|
||||
for _, sibling := range siblings {
|
||||
if sibling != bucket && resolve(f.DirBucketsPath+"/"+sibling+"/", sibling) == collection {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return collection
|
||||
}
|
||||
|
||||
func (f *Filer) listBuckets(ctx context.Context) (buckets []string, err error) {
|
||||
lastFileName := ""
|
||||
for {
|
||||
entries, _, listErr := f.ListDirectoryEntries(ctx, util.FullPath(f.DirBucketsPath), lastFileName, false, PaginationSize, "", "", "")
|
||||
if listErr != nil {
|
||||
return nil, listErr
|
||||
}
|
||||
for _, entry := range entries {
|
||||
lastFileName = entry.Name()
|
||||
if f.IsBucket(entry) {
|
||||
buckets = append(buckets, entry.Name())
|
||||
}
|
||||
}
|
||||
if len(entries) < PaginationSize {
|
||||
return buckets, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) DoDeleteCollection(ctx context.Context, collectionName string) (err error) {
|
||||
|
||||
return f.MasterClient.WithClient(ctx, false, func(client master_pb.SeaweedClient) error {
|
||||
|
||||
@@ -2,13 +2,11 @@ package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -103,57 +101,6 @@ func TestCreateEntryAssignsInodesToAutoCreatedParents(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateEntryOExclPreservesExistingEntry(t *testing.T) {
|
||||
f, store := newTestFilerWithStubStore()
|
||||
|
||||
original := &Entry{
|
||||
FullPath: util.FullPath("/buckets/my-bucket"),
|
||||
Attr: Attr{Mode: os.ModeDir | 0o777},
|
||||
Extended: map[string][]byte{
|
||||
"lifecycle": []byte(`<LifecycleConfiguration/>`),
|
||||
"owner": []byte("alice"),
|
||||
},
|
||||
}
|
||||
require.NoError(t, store.InsertEntry(context.Background(), original))
|
||||
|
||||
replacement := &Entry{
|
||||
FullPath: util.FullPath("/buckets/my-bucket"),
|
||||
Attr: Attr{Mode: os.ModeDir | 0o777},
|
||||
}
|
||||
err := f.CreateEntry(context.Background(), replacement, original, true, false, nil, false, f.MaxFilenameLength)
|
||||
require.ErrorIs(t, err, filer_pb.ErrEntryAlreadyExists)
|
||||
|
||||
stored, findErr := store.FindEntry(context.Background(), original.FullPath)
|
||||
require.NoError(t, findErr)
|
||||
assert.Equal(t, original.Extended, stored.Extended)
|
||||
}
|
||||
|
||||
func TestCreateEntryOExclFailsOnLookupError(t *testing.T) {
|
||||
f, store := newTestFilerWithStubStore()
|
||||
|
||||
original := &Entry{
|
||||
FullPath: util.FullPath("/buckets/my-bucket"),
|
||||
Attr: Attr{Mode: os.ModeDir | 0o777},
|
||||
Extended: map[string][]byte{"owner": []byte("alice")},
|
||||
}
|
||||
require.NoError(t, store.InsertEntry(context.Background(), original))
|
||||
|
||||
// a failed lookup must not masquerade as "not found": without the check
|
||||
// the insert path would upsert over the stored bucket entry
|
||||
store.findErr = errors.New("transient store failure")
|
||||
err := f.CreateEntry(context.Background(), &Entry{
|
||||
FullPath: util.FullPath("/buckets/my-bucket"),
|
||||
Attr: Attr{Mode: os.ModeDir | 0o777},
|
||||
}, nil, true, false, nil, false, f.MaxFilenameLength)
|
||||
require.Error(t, err)
|
||||
assert.NotErrorIs(t, err, filer_pb.ErrEntryAlreadyExists)
|
||||
|
||||
store.findErr = nil
|
||||
stored, findErr := store.FindEntry(context.Background(), original.FullPath)
|
||||
require.NoError(t, findErr)
|
||||
assert.Equal(t, original.Extended, stored.Extended)
|
||||
}
|
||||
|
||||
func TestUpdateEntryPreservesExistingInode(t *testing.T) {
|
||||
f, store := newTestFilerWithStubStore()
|
||||
|
||||
|
||||
@@ -7,10 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
@@ -46,21 +43,6 @@ func (f *Filer) maybeLazyFetchFromRemote(ctx context.Context, p util.FullPath) (
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// A startup tombstone rebuild may still be replaying the meta log; wait
|
||||
// for it so a pending delete cannot resurrect here.
|
||||
if done := f.remoteTombstonesDone.Load(); done != nil {
|
||||
select {
|
||||
case <-*done:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
if f.isRemoteDeletionPending(ctx, p, mountDir) {
|
||||
glog.V(2).InfofCtx(ctx, "maybeLazyFetchFromRemote: %s deleted locally, remote delete pending", p)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
remoteConf, found := f.RemoteStorage.FindRemoteStorageConf(p)
|
||||
if !found {
|
||||
return nil, nil
|
||||
@@ -121,27 +103,10 @@ func (f *Filer) maybeLazyFetchFromRemote(ctx context.Context, p util.FullPath) (
|
||||
persistBaseCtx, cancelPersist := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancelPersist()
|
||||
persistCtx := context.WithValue(persistBaseCtx, lazyFetchContextKey{}, true)
|
||||
// A delete may have landed while StatFile was in flight; re-check so
|
||||
// the fetched object cannot resurrect a path whose delete is pending.
|
||||
if f.isRemoteDeletionPending(persistCtx, p, mountDir) {
|
||||
glog.V(2).InfofCtx(ctx, "maybeLazyFetchFromRemote: %s deleted during remote stat", p)
|
||||
return lazyFetchResult{nil}, nil
|
||||
}
|
||||
saveErr := f.CreateEntry(persistCtx, entry, nil, false, false, nil, true, f.MaxFilenameLength)
|
||||
if saveErr != nil {
|
||||
glog.Warningf("maybeLazyFetchFromRemote: failed to persist filer entry for %s: %v", p, saveErr)
|
||||
f.lazyFetchGroup.Forget(key)
|
||||
return lazyFetchResult{entry}, nil
|
||||
}
|
||||
|
||||
// A delete records its tombstone before removing the entry, so a
|
||||
// tombstone visible now means the insert raced a delete that already
|
||||
// ran: retract the persisted entry so the path stays deleted.
|
||||
if f.isRemoteDeletionPending(persistCtx, p, mountDir) {
|
||||
glog.V(2).InfofCtx(ctx, "maybeLazyFetchFromRemote: %s deleted while persisting", p)
|
||||
f.lazyFetchGroup.Forget(key)
|
||||
f.retractLazyRemoteEntry(persistCtx, entry)
|
||||
return lazyFetchResult{nil}, nil
|
||||
}
|
||||
|
||||
return lazyFetchResult{entry}, nil
|
||||
@@ -157,25 +122,6 @@ func (f *Filer) maybeLazyFetchFromRemote(ctx context.Context, p util.FullPath) (
|
||||
return result.entry, nil
|
||||
}
|
||||
|
||||
// retractLazyRemoteEntry deletes the entry at entry.FullPath only when it is
|
||||
// still the entry a lazy remote read just materialized — a concurrent write
|
||||
// may have replaced it, and deleting by path alone would take that write down.
|
||||
func (f *Filer) retractLazyRemoteEntry(ctx context.Context, entry *Entry) {
|
||||
existing, findErr := f.FindEntry(ctx, entry.FullPath)
|
||||
if findErr != nil || existing == nil {
|
||||
return
|
||||
}
|
||||
// The stored entry must still be exactly what this read materialized —
|
||||
// an intervening write (appended chunks, touched attributes) means a
|
||||
// real update owns the path now.
|
||||
if !proto.Equal(existing.ToProtoEntry(), entry.ToProtoEntry()) {
|
||||
return
|
||||
}
|
||||
if err := f.doDeleteEntryMetaAndData(ctx, existing, false, false, nil); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
glog.Warningf("retractLazyRemoteEntry %s: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) maybeDeleteFromRemote(ctx context.Context, entry *Entry) (bool, error) {
|
||||
if entry == nil || f.RemoteStorage == nil {
|
||||
return false, nil
|
||||
|
||||
@@ -56,14 +56,6 @@ func (f *Filer) maybeLazyListFromRemote(ctx context.Context, p util.FullPath) {
|
||||
}
|
||||
}
|
||||
|
||||
if done := f.remoteTombstonesDone.Load(); done != nil {
|
||||
select {
|
||||
case <-*done:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Lazy listing is opt-in: disabled when TTL is 0
|
||||
if remoteLoc.ListingCacheTtlSeconds <= 0 {
|
||||
return
|
||||
@@ -117,10 +109,6 @@ func (f *Filer) maybeLazyListFromRemote(ctx context.Context, p util.FullPath) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if existingEntry == nil && f.isRemoteDeletionPending(persistCtx, childPath, mountDir) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if existingEntry != nil {
|
||||
// Merge: update remote metadata while preserving local state
|
||||
// (Chunks, Extended, Uid/Gid/Mode, etc.)
|
||||
@@ -173,9 +161,6 @@ func (f *Filer) maybeLazyListFromRemote(ctx context.Context, p util.FullPath) {
|
||||
}
|
||||
if saveErr := f.CreateEntry(persistCtx, entry, nil, false, false, nil, true, f.MaxFilenameLength); saveErr != nil {
|
||||
glog.Warningf("maybeLazyListFromRemote: persist %s: %v", childPath, saveErr)
|
||||
} else if f.isRemoteDeletionPending(persistCtx, childPath, mountDir) {
|
||||
// a delete landed between the check above and the insert
|
||||
f.retractLazyRemoteEntry(persistCtx, entry)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -34,7 +34,6 @@ type stubFilerStore struct {
|
||||
entries map[string]*Entry
|
||||
kv map[string][]byte
|
||||
insertErr error
|
||||
findErr error
|
||||
deleteErrByPath map[string]error
|
||||
}
|
||||
|
||||
@@ -175,9 +174,6 @@ func (s *stubFilerStore) UpdateEntry(_ context.Context, entry *Entry) error {
|
||||
func (s *stubFilerStore) FindEntry(_ context.Context, p util.FullPath) (*Entry, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.findErr != nil {
|
||||
return nil, s.findErr
|
||||
}
|
||||
if e, ok := s.entries[string(p)]; ok {
|
||||
return e, nil
|
||||
}
|
||||
@@ -283,7 +279,6 @@ func newTestFiler(t *testing.T, store *stubFilerStore, rs *FilerRemoteStorage) *
|
||||
MasterClient: mc,
|
||||
FileIdDeletionQueue: util.NewUnboundedQueue(),
|
||||
deletionQuit: make(chan struct{}),
|
||||
remoteTombstones: newRemoteDeletionTombstones(),
|
||||
LocalMetaLogBuffer: log_buffer.NewLogBuffer("test", time.Minute,
|
||||
func(*log_buffer.LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, func() {}),
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ func (f *Filer) onMetadataChangeEvent(event *filer_pb.SubscribeMetadataResponse)
|
||||
f.maybeReloadRemoteStorageConfigurationAndMapping(event)
|
||||
f.onBucketEvents(event)
|
||||
f.onEmptyFolderCleanupEvents(event)
|
||||
f.onRemoteDeletionEvents(event)
|
||||
}
|
||||
|
||||
func (f *Filer) onBucketEvents(event *filer_pb.SubscribeMetadataResponse) {
|
||||
|
||||
@@ -104,23 +104,3 @@ func TestExpiredFileIsDeletedOnRead(t *testing.T) {
|
||||
require.ErrorIs(t, err, filer_pb.ErrNotFound,
|
||||
"native TTL lookup should remove the expired metadata row")
|
||||
}
|
||||
|
||||
func TestListDirectoryEntriesContextCanceled(t *testing.T) {
|
||||
f, store := newTestFilerWithStubStore()
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, store.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/dir/file1.txt"),
|
||||
Attr: Attr{Mode: 0o644},
|
||||
}))
|
||||
|
||||
canceledCtx, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
|
||||
_, _, err := f.doListDirectoryEntries(canceledCtx, util.FullPath("/dir"), "", false, 10, "", func(entry *Entry) (bool, error) {
|
||||
return true, nil
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "context canceled")
|
||||
}
|
||||
|
||||
@@ -1,423 +0,0 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
// remoteDeletionTombstoneTTL bounds a tombstone when no write-back sync
|
||||
// offset ever confirms the remote delete. A remote object re-created
|
||||
// outside the filer at a deleted path stays hidden for this long.
|
||||
remoteDeletionTombstoneTTL = 24 * time.Hour
|
||||
// remoteDeletionTombstoneLimit bounds tracked paths; past it new
|
||||
// tombstones are dropped after an expired sweep still leaves no room.
|
||||
remoteDeletionTombstoneLimit = 1 << 16
|
||||
)
|
||||
|
||||
// remoteDeletionTombstones tracks paths deleted under a remote mount whose
|
||||
// remote object may still exist because the write-back daemon has not
|
||||
// consumed the delete event yet. A lazy remote fetch or listing must not
|
||||
// resurrect them. A tombstone lifts when the path is written again, when the
|
||||
// mount's persisted sync offset passes the delete event, or on TTL.
|
||||
//
|
||||
// Tombstones recorded before their metadata event lands (the synchronous
|
||||
// delete path) are marked pending: the sync offset orders against event
|
||||
// timestamps, which only the event itself knows, so a pending tombstone can
|
||||
// only be lifted by the event confirming it or by TTL. Once the event stamps
|
||||
// the real timestamp the tombstone is releasable by the offset.
|
||||
type remoteDeletionTombstones struct {
|
||||
mu sync.Mutex
|
||||
files map[string]int64 // file path -> delete event TsNs
|
||||
dirs map[string]int64 // deleted directory path -> event TsNs; covers its subtree
|
||||
pending map[string]bool // tombstone path recorded ahead of its event
|
||||
}
|
||||
|
||||
func newRemoteDeletionTombstones() *remoteDeletionTombstones {
|
||||
return &remoteDeletionTombstones{
|
||||
files: make(map[string]int64),
|
||||
dirs: make(map[string]int64),
|
||||
pending: make(map[string]bool),
|
||||
}
|
||||
}
|
||||
|
||||
// add records a tombstone ahead of its metadata event — the timestamp is the
|
||||
// local delete time, a lower bound the sync offset cannot order against.
|
||||
func (t *remoteDeletionTombstones) add(path string, isDir bool, tsNs int64) {
|
||||
t.upsert(path, isDir, tsNs, false)
|
||||
}
|
||||
|
||||
// addFromEvent records a tombstone stamped by the delete event itself, so the
|
||||
// mount's sync offset can release it once the daemon passes that event.
|
||||
func (t *remoteDeletionTombstones) addFromEvent(path string, isDir bool, tsNs int64) {
|
||||
t.upsert(path, isDir, tsNs, true)
|
||||
}
|
||||
|
||||
func (t *remoteDeletionTombstones) upsert(path string, isDir bool, tsNs int64, fromEvent bool) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
// An ancestor directory tombstone at least as new already covers the
|
||||
// path; recording it again only spends capacity.
|
||||
for p := path; ; {
|
||||
i := strings.LastIndexByte(p, '/')
|
||||
if i <= 0 {
|
||||
break
|
||||
}
|
||||
p = p[:i]
|
||||
if ancestorTs, ok := t.dirs[p]; ok && ancestorTs >= tsNs {
|
||||
return
|
||||
}
|
||||
}
|
||||
m := t.files
|
||||
if isDir {
|
||||
m = t.dirs
|
||||
}
|
||||
if cur, ok := m[path]; ok {
|
||||
if tsNs > cur {
|
||||
m[path] = tsNs
|
||||
if !fromEvent {
|
||||
// a newer local delete restamps the tombstone ahead of its
|
||||
// event — the offset cannot vouch for it until the event lands
|
||||
t.pending[path] = true
|
||||
}
|
||||
}
|
||||
if fromEvent && m[path] == tsNs {
|
||||
delete(t.pending, path)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(t.files)+len(t.dirs) >= remoteDeletionTombstoneLimit {
|
||||
t.evictExpiredLocked(time.Now().UnixNano())
|
||||
if len(t.files)+len(t.dirs) >= remoteDeletionTombstoneLimit {
|
||||
glog.V(0).Infof("remote deletion tombstones full (%d), skipping %s", remoteDeletionTombstoneLimit, path)
|
||||
return
|
||||
}
|
||||
}
|
||||
m[path] = tsNs
|
||||
if fromEvent {
|
||||
delete(t.pending, path)
|
||||
} else {
|
||||
t.pending[path] = true
|
||||
}
|
||||
if isDir {
|
||||
t.dropCoveredLocked(path, tsNs)
|
||||
}
|
||||
}
|
||||
|
||||
// dropCoveredLocked removes descendant tombstones a new directory tombstone
|
||||
// subsumes: their deletes predate it, so the ancestor already hides those
|
||||
// remote objects. Descendants deleted later keep their own tombstone.
|
||||
// Caller must hold t.mu.
|
||||
func (t *remoteDeletionTombstones) dropCoveredLocked(dirPath string, tsNs int64) {
|
||||
prefix := dirPath + "/"
|
||||
for p, ts := range t.files {
|
||||
if ts <= tsNs && strings.HasPrefix(p, prefix) {
|
||||
delete(t.files, p)
|
||||
delete(t.pending, p)
|
||||
}
|
||||
}
|
||||
for p, ts := range t.dirs {
|
||||
if ts <= tsNs && strings.HasPrefix(p, prefix) {
|
||||
delete(t.dirs, p)
|
||||
delete(t.pending, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// drop removes the exact tombstone recorded for path, e.g. when the delete
|
||||
// that recorded it fails before touching anything.
|
||||
func (t *remoteDeletionTombstones) drop(path string, tsNs int64) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if cur, ok := t.dirs[path]; ok && cur <= tsNs {
|
||||
delete(t.dirs, path)
|
||||
delete(t.pending, path)
|
||||
}
|
||||
if cur, ok := t.files[path]; ok && cur <= tsNs {
|
||||
delete(t.files, path)
|
||||
delete(t.pending, path)
|
||||
}
|
||||
}
|
||||
|
||||
// clear drops a file tombstone when a write at the path is at least as new as
|
||||
// the delete; a replayed older create must not lift a newer delete.
|
||||
func (t *remoteDeletionTombstones) clear(path string, tsNs int64) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if cur, ok := t.files[path]; ok && tsNs >= cur {
|
||||
delete(t.files, path)
|
||||
delete(t.pending, path)
|
||||
}
|
||||
}
|
||||
|
||||
// blockedSince returns the newest delete timestamp governing path — its own
|
||||
// file tombstone or one from a deleted ancestor directory — and whether that
|
||||
// tombstone is still waiting for its event. 0 means clear.
|
||||
func (t *remoteDeletionTombstones) blockedSince(path string) (tsNs int64, pending bool) {
|
||||
if t == nil {
|
||||
return 0, false
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if ts, ok := t.files[path]; ok {
|
||||
tsNs = ts
|
||||
pending = t.pending[path]
|
||||
}
|
||||
for p := path; ; {
|
||||
if ts, ok := t.dirs[p]; ok && ts > tsNs {
|
||||
tsNs = ts
|
||||
pending = t.pending[p]
|
||||
}
|
||||
i := strings.LastIndexByte(p, '/')
|
||||
if i <= 0 {
|
||||
break
|
||||
}
|
||||
p = p[:i]
|
||||
}
|
||||
return tsNs, pending
|
||||
}
|
||||
|
||||
// releaseThrough drops the tombstones governing path that are no newer than
|
||||
// tsNs, once their remote deletes are confirmed consumed.
|
||||
func (t *remoteDeletionTombstones) releaseThrough(path string, tsNs int64) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if cur, ok := t.files[path]; ok && cur <= tsNs {
|
||||
delete(t.files, path)
|
||||
delete(t.pending, path)
|
||||
}
|
||||
for p := path; ; {
|
||||
if cur, ok := t.dirs[p]; ok && cur <= tsNs {
|
||||
delete(t.dirs, p)
|
||||
delete(t.pending, p)
|
||||
}
|
||||
i := strings.LastIndexByte(p, '/')
|
||||
if i <= 0 {
|
||||
break
|
||||
}
|
||||
p = p[:i]
|
||||
}
|
||||
}
|
||||
|
||||
func (t *remoteDeletionTombstones) evictExpiredLocked(nowNs int64) {
|
||||
for p, ts := range t.files {
|
||||
if nowNs-ts >= int64(remoteDeletionTombstoneTTL) {
|
||||
delete(t.files, p)
|
||||
delete(t.pending, p)
|
||||
}
|
||||
}
|
||||
for p, ts := range t.dirs {
|
||||
if nowNs-ts >= int64(remoteDeletionTombstoneTTL) {
|
||||
delete(t.dirs, p)
|
||||
delete(t.pending, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// noteRemoteDeletion records a delete of path under a remote mount so lazy
|
||||
// remote reads skip it until the remote delete is confirmed.
|
||||
func (f *Filer) noteRemoteDeletion(p util.FullPath, isDir bool, tsNs int64) {
|
||||
if f.RemoteStorage == nil || f.remoteTombstones == nil {
|
||||
return
|
||||
}
|
||||
if _, remoteLoc := f.RemoteStorage.FindMountDirectory(p); remoteLoc == nil {
|
||||
return
|
||||
}
|
||||
f.remoteTombstones.add(string(p), isDir, tsNs)
|
||||
}
|
||||
|
||||
// unnoteRemoteDeletion retracts a tombstone when the delete that recorded it
|
||||
// fails before touching anything under path.
|
||||
func (f *Filer) unnoteRemoteDeletion(p util.FullPath, tsNs int64) {
|
||||
if f.remoteTombstones == nil {
|
||||
return
|
||||
}
|
||||
f.remoteTombstones.drop(string(p), tsNs)
|
||||
}
|
||||
|
||||
// isRemoteDeletionPending reports whether a remote write-back delete for p is
|
||||
// still owed: p was deleted under mountDir and neither a rewrite, the mount's
|
||||
// sync offset, nor the TTL has lifted the tombstone.
|
||||
func (f *Filer) isRemoteDeletionPending(ctx context.Context, p util.FullPath, mountDir util.FullPath) bool {
|
||||
if f.remoteTombstones == nil {
|
||||
return false
|
||||
}
|
||||
tsNs, pending := f.remoteTombstones.blockedSince(string(p))
|
||||
if tsNs == 0 {
|
||||
return false
|
||||
}
|
||||
if pending {
|
||||
// Recorded ahead of its delete event — the write-back offset cannot
|
||||
// vouch for it yet; only the TTL lifts it.
|
||||
if f.remoteDeletionExpired(tsNs) {
|
||||
f.remoteTombstones.releaseThrough(string(p), tsNs)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if f.remoteDeletionConsumed(ctx, mountDir, tsNs) {
|
||||
f.remoteTombstones.releaseThrough(string(p), tsNs)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (f *Filer) remoteDeletionExpired(tsNs int64) bool {
|
||||
return time.Now().UnixNano()-tsNs >= int64(remoteDeletionTombstoneTTL)
|
||||
}
|
||||
|
||||
func (f *Filer) remoteDeletionConsumed(ctx context.Context, mountDir util.FullPath, tsNs int64) bool {
|
||||
if f.remoteDeletionExpired(tsNs) {
|
||||
return true
|
||||
}
|
||||
offset, err := f.readRemoteSyncOffset(ctx, mountDir)
|
||||
return err == nil && offset >= tsNs
|
||||
}
|
||||
|
||||
// readRemoteSyncOffset reads the write-back daemon's persisted watermark for
|
||||
// mountDir straight from the local store: every event at or below it has been
|
||||
// applied to the remote.
|
||||
func (f *Filer) readRemoteSyncOffset(ctx context.Context, mountDir util.FullPath) (int64, error) {
|
||||
value, err := f.Store.KvGet(ctx, remote_storage.SyncOffsetKey(string(mountDir)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(value) < 8 {
|
||||
return 0, nil
|
||||
}
|
||||
return int64(util.BytesToUint64(value)), nil
|
||||
}
|
||||
|
||||
// RebuildRemoteDeletionTombstones gates lazy remote reads and replays the
|
||||
// persisted metadata log from the oldest write-back offset across mounts,
|
||||
// restoring tombstones for deletes committed before a restart but not yet
|
||||
// applied to the remote. Every filer writes its log files under the same
|
||||
// directory, so pending peer deletes replay too; only events still inside
|
||||
// the unflushed buffer tail are missed. The gate is set synchronously so no
|
||||
// lazy read can slip in before replay starts, and it stays closed until a
|
||||
// replay succeeds.
|
||||
func (f *Filer) RebuildRemoteDeletionTombstones(ctx context.Context) {
|
||||
if f.RemoteStorage == nil || f.remoteTombstones == nil {
|
||||
return
|
||||
}
|
||||
mounts := f.RemoteStorage.MountedDirectories()
|
||||
if len(mounts) == 0 {
|
||||
return
|
||||
}
|
||||
done := make(chan struct{})
|
||||
f.remoteTombstonesDone.Store(&done)
|
||||
go f.rebuildRemoteDeletionTombstones(ctx, mounts, done)
|
||||
}
|
||||
|
||||
func (f *Filer) rebuildRemoteDeletionTombstones(ctx context.Context, mounts []util.FullPath, done chan struct{}) {
|
||||
// the replay itself lists directories; do not let it wait on its own gate
|
||||
ctx = context.WithValue(ctx, lazyFetchContextKey{}, true)
|
||||
startTsNs := f.remoteDeletionRebuildStartTsNs(ctx, mounts)
|
||||
openGate := func() {
|
||||
close(done)
|
||||
f.remoteTombstonesDone.Store(nil)
|
||||
}
|
||||
// Deletes made after startup are recorded through the live delete and
|
||||
// event paths, so replay can only be missing deletes committed before
|
||||
// the restart — and those have all crossed the tombstone TTL once this
|
||||
// deadline passes. Holding the gate longer protects nothing.
|
||||
replayDeadline := time.Now().Add(remoteDeletionTombstoneTTL)
|
||||
backoff := 2 * time.Second
|
||||
for {
|
||||
_, _, err := f.ReadPersistedLogBuffer(ctx, log_buffer.NewMessagePosition(startTsNs, 0), 0,
|
||||
func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
event := &filer_pb.SubscribeMetadataResponse{}
|
||||
if err := proto.Unmarshal(logEntry.Data, event); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
f.onRemoteDeletionEvents(event)
|
||||
return false, nil
|
||||
})
|
||||
if err == nil {
|
||||
openGate()
|
||||
return
|
||||
}
|
||||
glog.WarningfCtx(ctx, "rebuild remote deletion tombstones: %v", err)
|
||||
if !time.Now().Before(replayDeadline) {
|
||||
glog.ErrorfCtx(ctx, "rebuild remote deletion tombstones: giving up after %v", remoteDeletionTombstoneTTL)
|
||||
openGate()
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
if backoff < time.Minute {
|
||||
backoff *= 2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remoteDeletionRebuildStartTsNs returns the oldest write-back offset across
|
||||
// mounts — the earliest event the daemon may not have applied. Mounts without
|
||||
// a recorded offset replay from the TTL floor: events older than it would
|
||||
// build tombstones that are already expired.
|
||||
func (f *Filer) remoteDeletionRebuildStartTsNs(ctx context.Context, mounts []util.FullPath) int64 {
|
||||
startTsNs := int64(math.MaxInt64)
|
||||
for _, dir := range mounts {
|
||||
offset, err := f.readRemoteSyncOffset(ctx, dir)
|
||||
if err != nil {
|
||||
glog.WarningfCtx(ctx, "read remote sync offset for %s: %v", dir, err)
|
||||
offset = 0
|
||||
}
|
||||
if offset < startTsNs {
|
||||
startTsNs = offset
|
||||
}
|
||||
}
|
||||
ttlFloor := time.Now().Add(-remoteDeletionTombstoneTTL).UnixNano()
|
||||
if startTsNs == int64(math.MaxInt64) || startTsNs < ttlFloor {
|
||||
return ttlFloor
|
||||
}
|
||||
return startTsNs
|
||||
}
|
||||
|
||||
// onRemoteDeletionEvents folds peer and local metadata events into the
|
||||
// tombstone set: a delete or rename source is tombstoned at the event
|
||||
// timestamp, a create/update/rename target lifts a file tombstone.
|
||||
func (f *Filer) onRemoteDeletionEvents(event *filer_pb.SubscribeMetadataResponse) {
|
||||
message := event.EventNotification
|
||||
if message == nil {
|
||||
return
|
||||
}
|
||||
if message.OldEntry != nil {
|
||||
sourcePath := filer_pb.MetadataEventSourceFullPath(event)
|
||||
if message.NewEntry == nil || sourcePath != filer_pb.MetadataEventTargetFullPath(event) {
|
||||
if f.RemoteStorage != nil && f.remoteTombstones != nil {
|
||||
if _, remoteLoc := f.RemoteStorage.FindMountDirectory(util.FullPath(sourcePath)); remoteLoc != nil {
|
||||
f.remoteTombstones.addFromEvent(sourcePath, message.OldEntry.IsDirectory, event.TsNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if message.NewEntry != nil {
|
||||
f.remoteTombstones.clear(filer_pb.MetadataEventTargetFullPath(event), event.TsNs)
|
||||
}
|
||||
}
|
||||
@@ -1,437 +0,0 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newMountedTestFiler(t *testing.T, storageType string, stub remote_storage.RemoteStorageClient, listingTtlSeconds int32) (*Filer, *stubFilerStore) {
|
||||
t.Helper()
|
||||
if stub != nil {
|
||||
t.Cleanup(registerStubMaker(t, storageType, stub))
|
||||
}
|
||||
conf := &remote_pb.RemoteConf{Name: "tombstonestore", Type: storageType}
|
||||
rs := NewFilerRemoteStorage()
|
||||
rs.storageNameToConf[conf.Name] = conf
|
||||
rs.mapDirectoryToRemoteStorage("/buckets/mybucket", &remote_pb.RemoteStorageLocation{
|
||||
Name: "tombstonestore",
|
||||
Bucket: "mybucket",
|
||||
Path: "/",
|
||||
ListingCacheTtlSeconds: listingTtlSeconds,
|
||||
})
|
||||
store := newStubFilerStore()
|
||||
return newTestFiler(t, store, rs), store
|
||||
}
|
||||
|
||||
func putRemoteSyncOffset(t *testing.T, store *stubFilerStore, dir string, offsetTsNs int64) {
|
||||
t.Helper()
|
||||
buf := make([]byte, 8)
|
||||
util.Uint64toBytes(buf, uint64(offsetTsNs))
|
||||
require.NoError(t, store.KvPut(context.Background(), remote_storage.SyncOffsetKey(dir), buf))
|
||||
}
|
||||
|
||||
func TestRemoteDeletionTombstones_BlocksAndReleases(t *testing.T) {
|
||||
tombs := newRemoteDeletionTombstones()
|
||||
|
||||
tombs.addFromEvent("/m/a.txt", false, 100)
|
||||
ts, _ := tombs.blockedSince("/m/a.txt")
|
||||
assert.Equal(t, int64(100), ts)
|
||||
ts, _ = tombs.blockedSince("/m/b.txt")
|
||||
assert.Zero(t, ts)
|
||||
|
||||
// a delete of a directory blocks its whole subtree
|
||||
tombs.addFromEvent("/m/dir", true, 200)
|
||||
ts, _ = tombs.blockedSince("/m/dir")
|
||||
assert.Equal(t, int64(200), ts)
|
||||
ts, _ = tombs.blockedSince("/m/dir/deep/x.txt")
|
||||
assert.Equal(t, int64(200), ts)
|
||||
ts, _ = tombs.blockedSince("/m/dirx/y.txt")
|
||||
assert.Zero(t, ts)
|
||||
|
||||
// a rewrite at or after the delete lifts only that file's tombstone
|
||||
tombs.clear("/m/a.txt", 100)
|
||||
ts, _ = tombs.blockedSince("/m/a.txt")
|
||||
assert.Zero(t, ts)
|
||||
tombs.addFromEvent("/m/a.txt", false, 300)
|
||||
tombs.clear("/m/a.txt", 250)
|
||||
ts, _ = tombs.blockedSince("/m/a.txt")
|
||||
assert.Equal(t, int64(300), ts, "older create must not lift newer delete")
|
||||
|
||||
tombs.releaseThrough("/m/dir/deep/x.txt", 200)
|
||||
ts, _ = tombs.blockedSince("/m/dir/deep/x.txt")
|
||||
assert.Zero(t, ts)
|
||||
ts, _ = tombs.blockedSince("/m/dir")
|
||||
assert.Zero(t, ts)
|
||||
}
|
||||
|
||||
func TestRemoteDeletionTombstones_AncestorSubsumesAndCovers(t *testing.T) {
|
||||
tombs := newRemoteDeletionTombstones()
|
||||
|
||||
// a child tombstone recorded before its ancestor is dropped once the
|
||||
// ancestor's newer delete covers the whole subtree
|
||||
tombs.addFromEvent("/m/dir/a.txt", false, 100)
|
||||
tombs.addFromEvent("/m/dir", true, 200)
|
||||
ts, _ := tombs.blockedSince("/m/dir")
|
||||
assert.Equal(t, int64(200), ts)
|
||||
ts, _ = tombs.blockedSince("/m/dir/a.txt")
|
||||
assert.Equal(t, int64(200), ts)
|
||||
_, exists := tombs.files["/m/dir/a.txt"]
|
||||
assert.False(t, exists, "descendant tombstone is subsumed by the ancestor")
|
||||
|
||||
// adds under the covered subtree are skipped while the ancestor stands
|
||||
tombs.addFromEvent("/m/dir/b.txt", false, 150)
|
||||
_, exists = tombs.files["/m/dir/b.txt"]
|
||||
assert.False(t, exists)
|
||||
// ...but a child deleted after the ancestor still records its own tombstone
|
||||
tombs.addFromEvent("/m/dir/c.txt", false, 300)
|
||||
ts, _ = tombs.blockedSince("/m/dir/c.txt")
|
||||
assert.Equal(t, int64(300), ts)
|
||||
}
|
||||
|
||||
func TestRemoteDeletionTombstones_PendingIgnoresOffset(t *testing.T) {
|
||||
f, store := newMountedTestFiler(t, "stub_tomb_pending_offset", nil, 0)
|
||||
|
||||
// recorded before its event lands: a later event may already have moved
|
||||
// the mount's watermark past the local timestamp, so the offset cannot
|
||||
// vouch for this delete yet
|
||||
filePath := "/buckets/mybucket/dir/a.txt"
|
||||
now := time.Now().UnixNano()
|
||||
f.noteRemoteDeletion(util.FullPath(filePath), false, now)
|
||||
putRemoteSyncOffset(t, store, "/buckets/mybucket", now+100)
|
||||
assert.True(t, f.isRemoteDeletionPending(context.Background(), util.FullPath(filePath), "/buckets/mybucket"))
|
||||
|
||||
// once the delete event stamps the real timestamp, the watermark releases it
|
||||
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/mybucket/dir",
|
||||
TsNs: now + 50,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "a.txt"},
|
||||
},
|
||||
})
|
||||
assert.False(t, f.isRemoteDeletionPending(context.Background(), util.FullPath(filePath), "/buckets/mybucket"))
|
||||
}
|
||||
|
||||
func TestRemoteDeletionTombstones_RaisedLocalTombstoneIsPendingAgain(t *testing.T) {
|
||||
tombs := newRemoteDeletionTombstones()
|
||||
|
||||
tombs.addFromEvent("/m/a.txt", false, 100)
|
||||
_, pending := tombs.blockedSince("/m/a.txt")
|
||||
assert.False(t, pending)
|
||||
|
||||
// a newer local delete restamps the tombstone before its own event
|
||||
// lands, so the write-back offset cannot vouch for it yet
|
||||
tombs.add("/m/a.txt", false, 200)
|
||||
_, pending = tombs.blockedSince("/m/a.txt")
|
||||
assert.True(t, pending)
|
||||
|
||||
// once that delete's event confirms the new timestamp it releases normally
|
||||
tombs.addFromEvent("/m/a.txt", false, 200)
|
||||
_, pending = tombs.blockedSince("/m/a.txt")
|
||||
assert.False(t, pending)
|
||||
}
|
||||
|
||||
func TestMaybeLazyFetchFromRemote_SkipsTombstonedPath(t *testing.T) {
|
||||
const storageType = "stub_tomb_fetch"
|
||||
stub := &countingRemoteClient{
|
||||
stubRemoteClient: stubRemoteClient{
|
||||
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 11},
|
||||
},
|
||||
}
|
||||
f, _ := newMountedTestFiler(t, storageType, stub, 0)
|
||||
|
||||
// a delete under the mount tombstones the path; the remote object is
|
||||
// still there until the write-back daemon consumes the delete event
|
||||
filePath := util.FullPath("/buckets/mybucket/dir/a.txt")
|
||||
f.noteRemoteDeletion(filePath, false, time.Now().UnixNano())
|
||||
|
||||
entry, err := f.maybeLazyFetchFromRemote(context.Background(), filePath)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
assert.Equal(t, 0, stub.statCalls, "the remote object must not even be consulted")
|
||||
}
|
||||
|
||||
func TestMaybeLazyFetchFromRemote_NewerRemoteMtimeStillBlocked(t *testing.T) {
|
||||
const storageType = "stub_tomb_regen"
|
||||
stub := &countingRemoteClient{
|
||||
stubRemoteClient: stubRemoteClient{
|
||||
statResult: &filer_pb.RemoteEntry{RemoteMtime: time.Now().Unix() + 60, RemoteSize: 11},
|
||||
},
|
||||
}
|
||||
f, _ := newMountedTestFiler(t, storageType, stub, 0)
|
||||
|
||||
// a remote object whose mtime postdates the delete is still hidden: the
|
||||
// remote clock cannot distinguish a new generation from the pending
|
||||
// delete's target
|
||||
filePath := util.FullPath("/buckets/mybucket/dir/a.txt")
|
||||
f.noteRemoteDeletion(filePath, false, time.Now().UnixNano())
|
||||
|
||||
entry, err := f.maybeLazyFetchFromRemote(context.Background(), filePath)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
assert.Equal(t, 0, stub.statCalls)
|
||||
}
|
||||
|
||||
func TestMaybeLazyFetchFromRemote_SyncOffsetReleasesTombstone(t *testing.T) {
|
||||
const storageType = "stub_tomb_release"
|
||||
stub := &countingRemoteClient{
|
||||
stubRemoteClient: stubRemoteClient{
|
||||
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 11},
|
||||
},
|
||||
}
|
||||
f, store := newMountedTestFiler(t, storageType, stub, 0)
|
||||
|
||||
filePath := util.FullPath("/buckets/mybucket/dir/a.txt")
|
||||
deleteTsNs := time.Now().UnixNano()
|
||||
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/mybucket/dir",
|
||||
TsNs: deleteTsNs,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "a.txt"},
|
||||
},
|
||||
})
|
||||
|
||||
// the daemon's persisted watermark is behind the delete: still blocked
|
||||
putRemoteSyncOffset(t, store, "/buckets/mybucket", deleteTsNs-1)
|
||||
entry, err := f.maybeLazyFetchFromRemote(context.Background(), filePath)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
assert.Equal(t, 0, stub.statCalls)
|
||||
|
||||
// once the watermark reaches the delete event's own timestamp, the
|
||||
// remote delete has landed and the lookup may consult the remote again
|
||||
putRemoteSyncOffset(t, store, "/buckets/mybucket", deleteTsNs)
|
||||
entry, err = f.maybeLazyFetchFromRemote(context.Background(), filePath)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
assert.Equal(t, 1, stub.statCalls)
|
||||
}
|
||||
|
||||
func TestDeleteEntryMetaAndData_TombstonesPath(t *testing.T) {
|
||||
const storageType = "stub_tomb_delete"
|
||||
stub := &countingRemoteClient{
|
||||
stubRemoteClient: stubRemoteClient{
|
||||
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 11},
|
||||
},
|
||||
}
|
||||
f, store := newMountedTestFiler(t, storageType, stub, 0)
|
||||
|
||||
filePath := util.FullPath("/buckets/mybucket/dir/a.txt")
|
||||
store.entries[string(filePath)] = &Entry{
|
||||
FullPath: filePath,
|
||||
Attr: Attr{
|
||||
Mtime: time.Unix(1700000000, 0),
|
||||
Crtime: time.Unix(1700000000, 0),
|
||||
Mode: 0644,
|
||||
FileSize: 11,
|
||||
},
|
||||
}
|
||||
|
||||
require.NoError(t, f.DeleteEntryMetaAndData(context.Background(), filePath, false, false, false, false, nil, 0))
|
||||
|
||||
// the deleted path must not resurrect through the lazy fetch even while
|
||||
// the remote object is still present
|
||||
entry, err := f.FindEntry(context.Background(), filePath)
|
||||
assert.ErrorIs(t, err, filer_pb.ErrNotFound)
|
||||
assert.Nil(t, entry)
|
||||
assert.Equal(t, 0, stub.statCalls)
|
||||
|
||||
// a peer-observed create at the path lifts the tombstone
|
||||
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/mybucket/dir",
|
||||
TsNs: time.Now().UnixNano(),
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{Name: "a.txt"},
|
||||
},
|
||||
})
|
||||
entry, err = f.maybeLazyFetchFromRemote(context.Background(), filePath)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
assert.Equal(t, 1, stub.statCalls)
|
||||
}
|
||||
|
||||
func TestOnMetadataChangeEvent_PeerDeleteTombstones(t *testing.T) {
|
||||
const storageType = "stub_tomb_peer"
|
||||
stub := &countingRemoteClient{
|
||||
stubRemoteClient: stubRemoteClient{
|
||||
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 11},
|
||||
},
|
||||
}
|
||||
f, _ := newMountedTestFiler(t, storageType, stub, 0)
|
||||
|
||||
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/mybucket/dir",
|
||||
TsNs: time.Now().UnixNano(),
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "a.txt"},
|
||||
},
|
||||
})
|
||||
|
||||
entry, err := f.maybeLazyFetchFromRemote(context.Background(), "/buckets/mybucket/dir/a.txt")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
assert.Equal(t, 0, stub.statCalls)
|
||||
}
|
||||
|
||||
func TestOnMetadataChangeEvent_PeerDirDeleteTombstonesSubtree(t *testing.T) {
|
||||
const storageType = "stub_tomb_peer_dir"
|
||||
stub := &countingRemoteClient{
|
||||
stubRemoteClient: stubRemoteClient{
|
||||
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 11},
|
||||
},
|
||||
}
|
||||
f, _ := newMountedTestFiler(t, storageType, stub, 0)
|
||||
|
||||
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/mybucket",
|
||||
TsNs: time.Now().UnixNano(),
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "dir", IsDirectory: true},
|
||||
},
|
||||
})
|
||||
|
||||
entry, err := f.maybeLazyFetchFromRemote(context.Background(), "/buckets/mybucket/dir/deep/a.txt")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
assert.Equal(t, 0, stub.statCalls)
|
||||
}
|
||||
|
||||
func TestMaybeLazyListFromRemote_SkipsTombstonedChild(t *testing.T) {
|
||||
const storageType = "stub_tomb_list"
|
||||
stub := &stubRemoteClient{
|
||||
listDirFn: func(loc *remote_pb.RemoteStorageLocation, visitFn remote_storage.VisitFunc) error {
|
||||
if err := visitFn("/", "deleted.txt", false, &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 10}); err != nil {
|
||||
return err
|
||||
}
|
||||
return visitFn("/", "fresh.txt", false, &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 20})
|
||||
},
|
||||
}
|
||||
f, store := newMountedTestFiler(t, storageType, stub, 300)
|
||||
|
||||
f.noteRemoteDeletion("/buckets/mybucket/deleted.txt", false, time.Now().UnixNano())
|
||||
|
||||
f.maybeLazyListFromRemote(context.Background(), util.FullPath("/buckets/mybucket"))
|
||||
assert.Equal(t, 1, stub.listDirCalls)
|
||||
|
||||
assert.Nil(t, store.getEntry("/buckets/mybucket/deleted.txt"), "deleted child must not resurrect through a listing")
|
||||
require.NotNil(t, store.getEntry("/buckets/mybucket/fresh.txt"), "other remote objects still list")
|
||||
}
|
||||
|
||||
func TestMaybeLazyListFromRemote_RecreatedDirStillHidesChildren(t *testing.T) {
|
||||
const storageType = "stub_tomb_recreate"
|
||||
deleteTs := time.Now().UnixNano()
|
||||
stub := &stubRemoteClient{
|
||||
listDirFn: func(loc *remote_pb.RemoteStorageLocation, visitFn remote_storage.VisitFunc) error {
|
||||
if err := visitFn("/", "stale.txt", false, &filer_pb.RemoteEntry{RemoteMtime: deleteTs/int64(time.Second) - 10, RemoteSize: 10}); err != nil {
|
||||
return err
|
||||
}
|
||||
return visitFn("/", "fresh.txt", false, &filer_pb.RemoteEntry{RemoteMtime: deleteTs/int64(time.Second) + 10, RemoteSize: 20})
|
||||
},
|
||||
}
|
||||
f, store := newMountedTestFiler(t, storageType, stub, 300)
|
||||
|
||||
// the directory is deleted then recreated; its remote children stay
|
||||
// hidden — old or new mtime alike — until the remote delete lands
|
||||
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/mybucket",
|
||||
TsNs: deleteTs,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "dir", IsDirectory: true},
|
||||
},
|
||||
})
|
||||
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/mybucket",
|
||||
TsNs: deleteTs + 1,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{Name: "dir", IsDirectory: true},
|
||||
},
|
||||
})
|
||||
|
||||
f.maybeLazyListFromRemote(context.Background(), util.FullPath("/buckets/mybucket/dir"))
|
||||
|
||||
assert.Nil(t, store.getEntry("/buckets/mybucket/dir/stale.txt"))
|
||||
assert.Nil(t, store.getEntry("/buckets/mybucket/dir/fresh.txt"))
|
||||
|
||||
// after the write-back daemon confirms the remote delete, listing merges again
|
||||
f.remoteTombstones.releaseThrough("/buckets/mybucket/dir/stale.txt", deleteTs)
|
||||
delete(store.getEntry("/buckets/mybucket/dir").Extended, xattrRemoteListingSyncedAt)
|
||||
f.maybeLazyListFromRemote(context.Background(), util.FullPath("/buckets/mybucket/dir"))
|
||||
assert.NotNil(t, store.getEntry("/buckets/mybucket/dir/stale.txt"))
|
||||
assert.NotNil(t, store.getEntry("/buckets/mybucket/dir/fresh.txt"))
|
||||
}
|
||||
|
||||
func TestRemoteDeletionRebuildStartTsNs_UsesOldestMountOffset(t *testing.T) {
|
||||
f, store := newMountedTestFiler(t, "stub_rebuild", nil, 0)
|
||||
f.RemoteStorage.mapDirectoryToRemoteStorage("/buckets/other", &remote_pb.RemoteStorageLocation{
|
||||
Name: "tombstonestore", Bucket: "other", Path: "/",
|
||||
})
|
||||
mounts := f.RemoteStorage.MountedDirectories()
|
||||
require.Len(t, mounts, 2)
|
||||
|
||||
now := time.Now().UnixNano()
|
||||
putRemoteSyncOffset(t, store, "/buckets/mybucket", now-200)
|
||||
putRemoteSyncOffset(t, store, "/buckets/other", now-300)
|
||||
assert.Equal(t, now-300, f.remoteDeletionRebuildStartTsNs(context.Background(), mounts),
|
||||
"rebuild must replay from the least-synced mount")
|
||||
|
||||
// a mount whose offset was never written replays only within the TTL
|
||||
require.NoError(t, store.KvDelete(context.Background(), remote_storage.SyncOffsetKey("/buckets/other")))
|
||||
floor := f.remoteDeletionRebuildStartTsNs(context.Background(), mounts)
|
||||
assert.GreaterOrEqual(t, floor, time.Now().Add(-remoteDeletionTombstoneTTL-time.Second).UnixNano())
|
||||
|
||||
// an offset older than the TTL floor is raised to it
|
||||
putRemoteSyncOffset(t, store, "/buckets/other", time.Now().Add(-remoteDeletionTombstoneTTL-time.Hour).UnixNano())
|
||||
assert.Greater(t, f.remoteDeletionRebuildStartTsNs(context.Background(), mounts),
|
||||
time.Now().Add(-remoteDeletionTombstoneTTL-time.Hour).UnixNano())
|
||||
}
|
||||
|
||||
func TestRebuildRemoteDeletionTombstones_EmptyLogReleasesGate(t *testing.T) {
|
||||
f, _ := newMountedTestFiler(t, "stub_rebuild_empty", nil, 0)
|
||||
|
||||
f.RebuildRemoteDeletionTombstones(context.Background())
|
||||
done := f.remoteTombstonesDone.Load()
|
||||
require.NotNil(t, done, "the gate must be set synchronously")
|
||||
|
||||
select {
|
||||
case <-*done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("rebuild never released the gate")
|
||||
}
|
||||
assert.Nil(t, f.remoteTombstonesDone.Load())
|
||||
ts, _ := f.remoteTombstones.blockedSince("/buckets/mybucket/a.txt")
|
||||
assert.Zero(t, ts)
|
||||
}
|
||||
|
||||
func TestMaybeLazyFetchFromRemote_WaitsForRebuild(t *testing.T) {
|
||||
const storageType = "stub_tomb_pending"
|
||||
stub := &countingRemoteClient{
|
||||
stubRemoteClient: stubRemoteClient{
|
||||
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 10},
|
||||
},
|
||||
}
|
||||
f, _ := newMountedTestFiler(t, storageType, stub, 0)
|
||||
|
||||
// an unfinished rebuild blocks the fetch until the context gives up
|
||||
gate := make(chan struct{})
|
||||
f.remoteTombstonesDone.Store(&gate)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
entry, err := f.maybeLazyFetchFromRemote(ctx, "/buckets/mybucket/a.txt")
|
||||
assert.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
assert.Nil(t, entry)
|
||||
assert.Equal(t, 0, stub.statCalls)
|
||||
|
||||
// once the rebuild finishes, the fetch proceeds
|
||||
close(gate)
|
||||
entry, err = f.maybeLazyFetchFromRemote(context.Background(), "/buckets/mybucket/a.txt")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
assert.Equal(t, 1, stub.statCalls)
|
||||
}
|
||||
+12
-22
@@ -32,9 +32,7 @@ type ChunkReadAt struct {
|
||||
fileSize int64
|
||||
readerCache *ReaderCache
|
||||
readerPattern *ReaderPattern
|
||||
lastChunkMu sync.Mutex // guards lastChunkFid; mount issues concurrent ReadAt calls
|
||||
lastChunkFid string
|
||||
stream chunkStream // chunk this reader is positioned in, pinned in the shared readerCache
|
||||
prefetchCount int // Number of chunks to prefetch ahead during sequential reads
|
||||
ctx context.Context // Context used for cancellation during chunk read operations
|
||||
}
|
||||
@@ -169,17 +167,10 @@ func (c *ChunkReadAt) Size() int64 {
|
||||
}
|
||||
|
||||
func (c *ChunkReadAt) Close() error {
|
||||
c.ReleaseStream()
|
||||
c.readerCache.destroy()
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReleaseStream drops this reader's hold on the chunk it is positioned in.
|
||||
// Unlike Close it leaves the (possibly shared) ReaderCache intact.
|
||||
func (c *ChunkReadAt) ReleaseStream() {
|
||||
c.readerCache.releaseStream(&c.stream)
|
||||
}
|
||||
|
||||
func (c *ChunkReadAt) ReadAt(p []byte, offset int64) (n int, err error) {
|
||||
|
||||
c.readerPattern.MonitorReadAt(offset, len(p))
|
||||
@@ -350,7 +341,6 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
|
||||
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
|
||||
|
||||
if c.readerPattern.IsRandomMode() {
|
||||
c.readerCache.releaseStream(&c.stream)
|
||||
n, err := c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
|
||||
if n > 0 {
|
||||
return n, err
|
||||
@@ -360,20 +350,20 @@ func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunk
|
||||
}
|
||||
|
||||
shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache()
|
||||
// The previous chunk is released through the stream pin rather than
|
||||
// UnCache: the buffer is shared, and other streams may still be reading it.
|
||||
n, err = c.readerCache.readChunkAt(ctx, &c.stream, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
|
||||
c.lastChunkMu.Lock()
|
||||
enteredChunk := c.lastChunkFid != chunkView.FileId
|
||||
c.lastChunkFid = chunkView.FileId
|
||||
c.lastChunkMu.Unlock()
|
||||
if enteredChunk && chunkView.OffsetInChunk == 0 { // start of a new chunk
|
||||
if nextChunkViews != nil && c.prefetchCount > 0 {
|
||||
// Prefetch multiple chunks ahead for better sequential read throughput
|
||||
// This keeps the network pipeline full with parallel chunk fetches
|
||||
c.readerCache.MaybeCache(nextChunkViews, c.prefetchCount)
|
||||
n, err = c.readerCache.ReadChunkAt(ctx, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
|
||||
if c.lastChunkFid != chunkView.FileId {
|
||||
if chunkView.OffsetInChunk == 0 { // start of a new chunk
|
||||
if c.lastChunkFid != "" {
|
||||
c.readerCache.UnCache(c.lastChunkFid)
|
||||
}
|
||||
if nextChunkViews != nil && c.prefetchCount > 0 {
|
||||
// Prefetch multiple chunks ahead for better sequential read throughput
|
||||
// This keeps the network pipeline full with parallel chunk fetches
|
||||
c.readerCache.MaybeCache(nextChunkViews, c.prefetchCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
c.lastChunkFid = chunkView.FileId
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// Two streams (e.g. two S3 GETs) reading the same object through one shared
|
||||
// ReaderCache, interleaved in small slices, must share each chunk download:
|
||||
// one stream finishing a chunk, or moving on to the next one, must not drop a
|
||||
// buffer the other stream is still reading.
|
||||
func TestChunkReadAtConcurrentStreamsShareChunks(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
const chunkCount = 3
|
||||
const sliceSize = 16 << 10
|
||||
|
||||
var mu sync.Mutex
|
||||
fetches := map[string]int{}
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
mu.Lock()
|
||||
fetches[fileId]++
|
||||
mu.Unlock()
|
||||
for i := range buffer {
|
||||
buffer[i] = fileId[len(fileId)-1]
|
||||
}
|
||||
return len(buffer), nil
|
||||
}
|
||||
|
||||
newStream := func() *ChunkReadAt {
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
for i := 0; i < chunkCount; i++ {
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: int64(i * chunkSize),
|
||||
StopOffset: int64((i + 1) * chunkSize),
|
||||
Value: &ChunkView{
|
||||
FileId: fmt.Sprintf("chunk%d", i),
|
||||
ViewSize: chunkSize,
|
||||
ViewOffset: int64(i * chunkSize),
|
||||
ChunkSize: chunkSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
return NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
|
||||
}
|
||||
streams := []*ChunkReadAt{newStream(), newStream()}
|
||||
|
||||
// The streams alternate slice by slice, the second one lagging one slice
|
||||
// behind, so the leader always finishes a chunk while the follower is
|
||||
// still inside it.
|
||||
offsets := make([]int64, len(streams))
|
||||
offsets[1] = -sliceSize
|
||||
for offsets[1] < chunkSize*chunkCount {
|
||||
for i, stream := range streams {
|
||||
if offsets[i] < 0 || offsets[i] >= chunkSize*chunkCount {
|
||||
offsets[i] += sliceSize
|
||||
continue
|
||||
}
|
||||
buf := make([]byte, sliceSize)
|
||||
n, err := stream.ReadAt(buf, offsets[i])
|
||||
if (err != nil && err != io.EOF) || n != sliceSize {
|
||||
t.Fatalf("stream %d at %d: n=%d err=%v", i, offsets[i], n, err)
|
||||
}
|
||||
if want := byte('0' + offsets[i]/chunkSize); buf[0] != want || buf[n-1] != want {
|
||||
t.Fatalf("stream %d at %d: got %q, want %q", i, offsets[i], buf[0], want)
|
||||
}
|
||||
offsets[i] += sliceSize
|
||||
}
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
for i := 0; i < chunkCount; i++ {
|
||||
fileId := fmt.Sprintf("chunk%d", i)
|
||||
if fetches[fileId] != 1 {
|
||||
t.Errorf("%s fetched %d times for two concurrent streams, want 1", fileId, fetches[fileId])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newStreamTestReaderCache(chunkCache chunk_cache.ChunkCache) *ReaderCache {
|
||||
rc := NewReaderCache(64, chunkCache, func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
return len(buffer), nil
|
||||
}
|
||||
return rc
|
||||
}
|
||||
|
||||
func isRetained(rc *ReaderCache, fileId string) bool {
|
||||
rc.Lock()
|
||||
defer rc.Unlock()
|
||||
_, found := rc.downloaders[fileId]
|
||||
return found
|
||||
}
|
||||
|
||||
// A stream moving on to a chunk served from the chunk cache must still
|
||||
// release the chunk it was positioned in before.
|
||||
func TestChunkStreamReleasesPreviousChunkOnCacheHit(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
cache.SetChunk("chunk1", make([]byte, 4<<10))
|
||||
rc := newStreamTestReaderCache(cache)
|
||||
defer rc.destroy()
|
||||
|
||||
stream := &chunkStream{}
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, true); err != nil || n == 0 {
|
||||
t.Fatalf("cache hit read: n=%d err=%v", n, err)
|
||||
}
|
||||
if isRetained(rc, "chunk0") {
|
||||
t.Fatal("chunk0 still retained after the stream moved on to a cached chunk")
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk the stream leaves while another read is in flight must be dropped
|
||||
// once that read ends, even if it did not read the chunk to the end.
|
||||
func TestChunkStreamDropsLeftChunkAfterInFlightRead(t *testing.T) {
|
||||
rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache())
|
||||
defer rc.destroy()
|
||||
|
||||
stream := &chunkStream{}
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Another reader is in the middle of a partial read of chunk0.
|
||||
rc.Lock()
|
||||
other := rc.downloaders["chunk0"]
|
||||
other.wg.Add(1)
|
||||
atomic.AddInt32(&other.readers, 1)
|
||||
rc.Unlock()
|
||||
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !isRetained(rc, "chunk0") {
|
||||
t.Fatal("chunk0 dropped while a read was still in flight")
|
||||
}
|
||||
|
||||
// The in-flight read ends without reaching the end of the chunk.
|
||||
other.wg.Done()
|
||||
atomic.AddInt32(&other.readers, -1)
|
||||
rc.removeConsumed(other)
|
||||
if isRetained(rc, "chunk0") {
|
||||
t.Fatal("chunk0 retained after the stream left it and the last read ended")
|
||||
}
|
||||
}
|
||||
|
||||
// Concurrent ReadAt calls on one ChunkReadAt (as mount does) share its stream
|
||||
// pin; they must neither race on it nor leak or double-release pins.
|
||||
func TestChunkStreamConcurrentReadsOnOneReader(t *testing.T) {
|
||||
const chunkSize = 16 << 10
|
||||
const chunkCount = 4
|
||||
const sliceSize = 4 << 10
|
||||
rc := newStreamTestReaderCache((*chunk_cache.TieredChunkCache)(nil))
|
||||
defer rc.destroy()
|
||||
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
for i := 0; i < chunkCount; i++ {
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: int64(i * chunkSize),
|
||||
StopOffset: int64((i + 1) * chunkSize),
|
||||
Value: &ChunkView{
|
||||
FileId: fmt.Sprintf("chunk%d", i),
|
||||
ViewSize: chunkSize,
|
||||
ViewOffset: int64(i * chunkSize),
|
||||
ChunkSize: chunkSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for g := 0; g < 8; g++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for offset := int64(0); offset < chunkSize*chunkCount; offset += sliceSize {
|
||||
if _, err := reader.ReadAt(make([]byte, sliceSize), offset); err != nil && err != io.EOF {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Finishing the last chunk releases the stream's final pin.
|
||||
if _, err := reader.ReadAt(make([]byte, sliceSize), chunkSize*chunkCount-sliceSize); err != nil && err != io.EOF {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rc.Lock()
|
||||
defer rc.Unlock()
|
||||
for fileId, cacher := range rc.downloaders {
|
||||
t.Errorf("%s retained after all reads finished: pins=%d readers=%d", fileId, atomic.LoadInt32(&cacher.pins), atomic.LoadInt32(&cacher.readers))
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk a stream is positioned in must outlast downloader-limit eviction:
|
||||
// otherwise a busy cache drops the buffer mid-stream and forces a refetch.
|
||||
func TestChunkReadAtPinnedChunkSurvivesEviction(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
|
||||
var fetches int32
|
||||
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
if fileId == "chunk0" {
|
||||
atomic.AddInt32(&fetches, 1)
|
||||
}
|
||||
return len(buffer), nil
|
||||
}
|
||||
|
||||
stream := &chunkStream{}
|
||||
buf := make([]byte, 16<<10)
|
||||
// One slice in: the stream is positioned in chunk0 but has not left it.
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Fill the downloader map past its limit with unpinned chunks.
|
||||
for _, fileId := range []string{"chunk1", "chunk2", "chunk3"} {
|
||||
if _, err := rc.ReadChunkAt(context.Background(), buf, fileId, nil, false, 0, chunkSize, true); err != nil {
|
||||
t.Fatalf("read %s: %v", fileId, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The stream's next slice must come from the still-pinned buffer.
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 16<<10, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := atomic.LoadInt32(&fetches); got != 1 {
|
||||
t.Errorf("chunk0 fetched %d times, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// When every downloader is pinned the limit still applies: the oldest pinned
|
||||
// buffer is evicted so abandoned streams cannot grow memory past the limit.
|
||||
func TestChunkReadAtPinnedEvictionFallsBackWhenAllPinned(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
return len(buffer), nil
|
||||
}
|
||||
|
||||
buf := make([]byte, 16<<10)
|
||||
streamA := &chunkStream{}
|
||||
streamB := &chunkStream{}
|
||||
if _, err := rc.readChunkAt(context.Background(), streamA, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := rc.readChunkAt(context.Background(), streamB, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Every downloader is now pinned; the next chunk must still get in.
|
||||
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if isRetained(rc, "chunk0") {
|
||||
t.Fatal("oldest pinned downloader was not evicted past the limit")
|
||||
}
|
||||
if !isRetained(rc, "chunk2") {
|
||||
t.Fatal("new downloader missing after pinned fallback eviction")
|
||||
}
|
||||
}
|
||||
+9
-128
@@ -35,8 +35,6 @@ type SingleChunkCacher struct {
|
||||
completedTimeNew int64
|
||||
readers int32
|
||||
consumed int32
|
||||
pins int32 // streams currently positioned inside this chunk
|
||||
left int32 // set once the last pinning stream moved on
|
||||
sync.Mutex
|
||||
parent *ReaderCache
|
||||
chunkFileId string
|
||||
@@ -114,19 +112,7 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
|
||||
return
|
||||
}
|
||||
|
||||
// chunkStream is one sequential reader's position in a shared ReaderCache.
|
||||
// The chunk it is reading stays pinned until the stream reads it to the end or
|
||||
// moves elsewhere, so another stream finishing or leaving the same chunk does
|
||||
// not drop the buffer from under it.
|
||||
type chunkStream struct {
|
||||
cacher *SingleChunkCacher
|
||||
}
|
||||
|
||||
func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
|
||||
return rc.readChunkAt(ctx, nil, buffer, fileId, cipherKey, isGzipped, offset, chunkSize, shouldCache)
|
||||
}
|
||||
|
||||
func (rc *ReaderCache) readChunkAt(ctx context.Context, stream *chunkStream, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
|
||||
retry:
|
||||
rc.Lock()
|
||||
|
||||
@@ -144,11 +130,8 @@ retry:
|
||||
// start wg.Wait() on a zero counter while this read is about to register.
|
||||
cacher.wg.Add(1)
|
||||
atomic.AddInt32(&cacher.readers, 1)
|
||||
previous := stream.pin(cacher)
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
n, err := cacher.readChunkAt(ctx, buffer, offset)
|
||||
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
|
||||
if n > 0 || err != nil {
|
||||
return n, err
|
||||
}
|
||||
@@ -161,34 +144,19 @@ retry:
|
||||
if shouldCache || rc.lookupFileIdFn == nil {
|
||||
n, err := rc.chunkCache.ReadChunkAt(buffer, fileId, uint64(offset))
|
||||
if n > 0 {
|
||||
// Served from the chunk cache: the stream has left its pinned chunk.
|
||||
previous := stream.unpinLocked()
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
|
||||
// clean up old downloaders; prefer one no stream is positioned in, but
|
||||
// fall back to a pinned one so abandoned pins cannot bypass the limit
|
||||
// clean up old downloaders
|
||||
if len(rc.downloaders) >= rc.limit {
|
||||
oldestFid, oldestTime := "", time.Now().UnixNano()
|
||||
pinnedFid, pinnedTime := "", int64(0)
|
||||
for fid, downloader := range rc.downloaders {
|
||||
completedTime := atomic.LoadInt64(&downloader.completedTimeNew)
|
||||
if completedTime <= 0 {
|
||||
continue
|
||||
if completedTime > 0 && completedTime < oldestTime {
|
||||
oldestFid, oldestTime = fid, completedTime
|
||||
}
|
||||
if atomic.LoadInt32(&downloader.pins) == 0 {
|
||||
if completedTime < oldestTime {
|
||||
oldestFid, oldestTime = fid, completedTime
|
||||
}
|
||||
} else if pinnedFid == "" || completedTime < pinnedTime {
|
||||
pinnedFid, pinnedTime = fid, completedTime
|
||||
}
|
||||
}
|
||||
if oldestFid == "" {
|
||||
oldestFid = pinnedFid
|
||||
}
|
||||
if oldestFid != "" {
|
||||
oldDownloader := rc.downloaders[oldestFid]
|
||||
@@ -207,77 +175,9 @@ retry:
|
||||
rc.downloaders[fileId] = cacher
|
||||
cacher.wg.Add(1)
|
||||
atomic.AddInt32(&cacher.readers, 1)
|
||||
previous := stream.pin(cacher)
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
|
||||
n, err := cacher.readChunkAt(ctx, buffer, offset)
|
||||
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// pin makes cacher the stream's current chunk and returns the chunk it was
|
||||
// pinned to before, which the caller unpins once the ReaderCache lock is
|
||||
// released. The stream is only touched under the ReaderCache lock, since
|
||||
// concurrent ReadAt calls on one ChunkReadAt share it.
|
||||
func (stream *chunkStream) pin(cacher *SingleChunkCacher) (previous *SingleChunkCacher) {
|
||||
if stream == nil || stream.cacher == cacher {
|
||||
return nil
|
||||
}
|
||||
previous = stream.cacher
|
||||
stream.cacher = cacher
|
||||
atomic.AddInt32(&cacher.pins, 1)
|
||||
return previous
|
||||
}
|
||||
|
||||
// unpinLocked detaches the stream from its chunk and returns that chunk for
|
||||
// the caller to unpin once the ReaderCache lock is released.
|
||||
func (stream *chunkStream) unpinLocked() (previous *SingleChunkCacher) {
|
||||
if stream == nil {
|
||||
return nil
|
||||
}
|
||||
previous = stream.cacher
|
||||
stream.cacher = nil
|
||||
return previous
|
||||
}
|
||||
|
||||
// releaseIfFinished unpins the stream's chunk once the stream has read it to
|
||||
// the end, since the stream will not come back to it.
|
||||
func (rc *ReaderCache) releaseIfFinished(stream *chunkStream, cacher *SingleChunkCacher, offset int64, n int, err error, chunkSize int) {
|
||||
if stream == nil || err != nil || offset+int64(n) < int64(chunkSize) {
|
||||
return
|
||||
}
|
||||
var previous *SingleChunkCacher
|
||||
rc.Lock()
|
||||
if stream.cacher == cacher {
|
||||
previous = stream.unpinLocked()
|
||||
}
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
}
|
||||
|
||||
// releaseStream unpins whatever chunk the stream is positioned in.
|
||||
func (rc *ReaderCache) releaseStream(stream *chunkStream) {
|
||||
if stream == nil {
|
||||
return
|
||||
}
|
||||
rc.Lock()
|
||||
previous := stream.unpinLocked()
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
}
|
||||
|
||||
// unpin drops one stream's pin. Once no stream is positioned in the chunk it
|
||||
// is dropped like UnCache would, as soon as no read is in progress either:
|
||||
// here if none is, otherwise by the last read's removeConsumed.
|
||||
func (rc *ReaderCache) unpin(downloader *SingleChunkCacher) {
|
||||
if downloader == nil {
|
||||
return
|
||||
}
|
||||
if atomic.AddInt32(&downloader.pins, -1) == 0 {
|
||||
atomic.StoreInt32(&downloader.left, 1)
|
||||
}
|
||||
rc.removeConsumed(downloader)
|
||||
return cacher.readChunkAt(ctx, buffer, offset)
|
||||
}
|
||||
|
||||
func (rc *ReaderCache) UnCache(fileId string) {
|
||||
@@ -302,34 +202,15 @@ func (rc *ReaderCache) remove(downloader *SingleChunkCacher) {
|
||||
}
|
||||
}
|
||||
|
||||
// removeUnpinned drops a cacher only while no stream is positioned in it.
|
||||
// Budget eviction picks its victim under the budget lock, so the pin check
|
||||
// and the map removal must happen together under the ReaderCache lock.
|
||||
func (rc *ReaderCache) removeUnpinned(downloader *SingleChunkCacher) (removed bool) {
|
||||
rc.Lock()
|
||||
removed = rc.downloaders[downloader.chunkFileId] == downloader &&
|
||||
atomic.LoadInt32(&downloader.pins) == 0
|
||||
if removed {
|
||||
delete(rc.downloaders, downloader.chunkFileId)
|
||||
}
|
||||
rc.Unlock()
|
||||
if removed {
|
||||
downloader.destroy()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// removeConsumed drops a cacher once its buffer was fully read, or the
|
||||
// streams positioned in it have left, and no readers remain attached or
|
||||
// pinned. The checks run under the ReaderCache lock so a reader attaching
|
||||
// at the same time either wins (the cacher stays and that reader's detach
|
||||
// retries the removal) or misses the map and refetches.
|
||||
// removeConsumed drops a cacher once its buffer was fully read and no
|
||||
// readers remain attached. The checks run under the ReaderCache lock so a
|
||||
// reader attaching at the same time either wins (the cacher stays and that
|
||||
// reader's detach retries the removal) or misses the map and refetches.
|
||||
func (rc *ReaderCache) removeConsumed(downloader *SingleChunkCacher) {
|
||||
rc.Lock()
|
||||
removed := rc.downloaders[downloader.chunkFileId] == downloader &&
|
||||
atomic.LoadInt32(&downloader.readers) == 0 &&
|
||||
atomic.LoadInt32(&downloader.pins) == 0 &&
|
||||
(atomic.LoadInt32(&downloader.consumed) != 0 || atomic.LoadInt32(&downloader.left) != 0)
|
||||
atomic.LoadInt32(&downloader.consumed) != 0
|
||||
if removed {
|
||||
delete(rc.downloaders, downloader.chunkFileId)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/mem"
|
||||
)
|
||||
@@ -52,39 +51,12 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error {
|
||||
b.Unlock()
|
||||
return nil
|
||||
}
|
||||
// Prefer evicting an idle chunk no stream is positioned in; fall back
|
||||
// to the oldest pinned one so abandoned pins cannot block the budget.
|
||||
var victim *SingleChunkCacher
|
||||
var entry *list.Element
|
||||
pinnedVictim := false
|
||||
for e := b.idle.Front(); e != nil; e = e.Next() {
|
||||
c := e.Value.(*SingleChunkCacher)
|
||||
if atomic.LoadInt32(&c.pins) == 0 {
|
||||
victim, entry = c, e
|
||||
pinnedVictim = false
|
||||
break
|
||||
}
|
||||
if victim == nil {
|
||||
victim, entry = c, e
|
||||
pinnedVictim = true
|
||||
}
|
||||
}
|
||||
if entry != nil {
|
||||
if entry := b.idle.Front(); entry != nil {
|
||||
victim := entry.Value.(*SingleChunkCacher)
|
||||
b.idle.Remove(entry)
|
||||
delete(b.idleEntries, victim)
|
||||
b.Unlock()
|
||||
if pinnedVictim {
|
||||
victim.parent.remove(victim)
|
||||
} else if !victim.parent.removeUnpinned(victim) {
|
||||
// The victim was pinned between selection and removal: keep it
|
||||
// evictable so a pin abandoned in that gap cannot wedge the
|
||||
// budget, then retry the selection.
|
||||
b.Lock()
|
||||
if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil {
|
||||
b.idleEntries[victim] = b.idle.PushBack(victim)
|
||||
}
|
||||
b.Unlock()
|
||||
}
|
||||
victim.parent.remove(victim)
|
||||
continue
|
||||
}
|
||||
changed := b.changed
|
||||
|
||||
@@ -36,7 +36,6 @@ type FilerRemoteStorage struct {
|
||||
// whenever /etc/remote changes
|
||||
mu sync.RWMutex
|
||||
rules ptrie.Trie[*remote_pb.RemoteStorageLocation]
|
||||
mountDirs []util.FullPath
|
||||
storageNameToConf map[string]*remote_pb.RemoteConf
|
||||
// confValidator, when set, is applied to every RemoteConf as it is loaded
|
||||
// from /etc/remote. A conf that fails is dropped from storageNameToConf so
|
||||
@@ -88,13 +87,11 @@ func (rs *FilerRemoteStorage) LoadRemoteStorageConfigurationsAndMapping(filer *F
|
||||
// build into fresh containers so an unmounted directory disappears instead
|
||||
// of lingering in the trie, which has no way to drop a key
|
||||
rules := ptrie.New[*remote_pb.RemoteStorageLocation]()
|
||||
var mountDirs []util.FullPath
|
||||
storageNameToConf := make(map[string]*remote_pb.RemoteConf)
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.Name() == REMOTE_STORAGE_MOUNT_FILE {
|
||||
mountDirs, err = loadRemoteStorageMountMapping(rules, entry.Content)
|
||||
if err != nil {
|
||||
if err := loadRemoteStorageMountMapping(rules, entry.Content); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
@@ -120,46 +117,27 @@ func (rs *FilerRemoteStorage) LoadRemoteStorageConfigurationsAndMapping(filer *F
|
||||
}
|
||||
|
||||
rs.mu.Lock()
|
||||
rs.rules, rs.mountDirs, rs.storageNameToConf = rules, mountDirs, storageNameToConf
|
||||
rs.rules, rs.storageNameToConf = rules, storageNameToConf
|
||||
rs.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadRemoteStorageMountMapping(rules ptrie.Trie[*remote_pb.RemoteStorageLocation], data []byte) (mountDirs []util.FullPath, err error) {
|
||||
func loadRemoteStorageMountMapping(rules ptrie.Trie[*remote_pb.RemoteStorageLocation], data []byte) (err error) {
|
||||
mappings := &remote_pb.RemoteStorageMapping{}
|
||||
if err := proto.Unmarshal(data, mappings); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s/%s: %v", DirectoryEtcRemote, REMOTE_STORAGE_MOUNT_FILE, err)
|
||||
return fmt.Errorf("unmarshal %s/%s: %v", DirectoryEtcRemote, REMOTE_STORAGE_MOUNT_FILE, err)
|
||||
}
|
||||
for dir, storageLocation := range mappings.Mappings {
|
||||
putDirectoryToRemoteStorage(rules, util.FullPath(dir), storageLocation)
|
||||
mountDirs = append(mountDirs, util.FullPath(dir))
|
||||
}
|
||||
return mountDirs, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rs *FilerRemoteStorage) mapDirectoryToRemoteStorage(dir util.FullPath, loc *remote_pb.RemoteStorageLocation) {
|
||||
rs.mu.Lock()
|
||||
defer rs.mu.Unlock()
|
||||
putDirectoryToRemoteStorage(rs.rules, dir, loc)
|
||||
found := false
|
||||
for _, d := range rs.mountDirs {
|
||||
if d == dir {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
rs.mountDirs = append(rs.mountDirs, dir)
|
||||
}
|
||||
}
|
||||
|
||||
// MountedDirectories returns the directories currently mapped to remote
|
||||
// storage, for callers that must reason about every mount rather than one path.
|
||||
func (rs *FilerRemoteStorage) MountedDirectories() []util.FullPath {
|
||||
rs.mu.RLock()
|
||||
defer rs.mu.RUnlock()
|
||||
return append([]util.FullPath(nil), rs.mountDirs...)
|
||||
}
|
||||
|
||||
func putDirectoryToRemoteStorage(rules ptrie.Trie[*remote_pb.RemoteStorageLocation], dir util.FullPath, loc *remote_pb.RemoteStorageLocation) {
|
||||
|
||||
@@ -123,10 +123,9 @@ func genericCopyRoleDefinition(role *RoleDefinition) *RoleDefinition {
|
||||
}
|
||||
|
||||
result := &RoleDefinition{
|
||||
RoleName: role.RoleName,
|
||||
RoleArn: role.RoleArn,
|
||||
Description: role.Description,
|
||||
MaxSessionDuration: role.MaxSessionDuration,
|
||||
RoleName: role.RoleName,
|
||||
RoleArn: role.RoleArn,
|
||||
Description: role.Description,
|
||||
}
|
||||
|
||||
// Deep copy trust policy if it exists
|
||||
|
||||
@@ -942,7 +942,7 @@ func (m *IAMManager) AssumeRoleWithWebIdentity(ctx context.Context, request *sts
|
||||
// Apply role-level MaxSessionDuration cap. The STS service still applies
|
||||
// the global MaxSessionLength and the source-token-expiry cap on top of
|
||||
// this; per-role takes precedence whenever it is the tightest bound.
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration, m.defaultTokenDurationSeconds(), m.maxSessionLengthSeconds())
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
|
||||
|
||||
// Use STS service to assume the role
|
||||
return m.stsService.AssumeRoleWithWebIdentity(ctx, request)
|
||||
@@ -1005,54 +1005,22 @@ func extractIssuerFromJWT(token string) (string, error) {
|
||||
return iss, nil
|
||||
}
|
||||
|
||||
// capDurationByRole returns the session duration clamped to the role's
|
||||
// MaxSessionDuration. An omitted DurationSeconds resolves to the configured
|
||||
// default first, so the role bound caps defaults and explicit values alike.
|
||||
// A nil request is only materialized when something tightened the default
|
||||
// and the explicit value still passes the service's own input validation —
|
||||
// everything else is left nil so the service resolves the default and its
|
||||
// MaxSessionLength cap itself.
|
||||
func capDurationByRole(requested *int64, roleMax, defaultSec, serviceMaxSec int64) *int64 {
|
||||
if requested != nil {
|
||||
d := *requested
|
||||
if roleMax > 0 && d > roleMax {
|
||||
d = roleMax
|
||||
}
|
||||
return &d
|
||||
// capDurationByRole returns the requested duration clamped to the role's
|
||||
// MaxSessionDuration. A nil requested duration is left nil so the STS
|
||||
// service's calculateSessionDuration applies the global default (typically
|
||||
// 1 hour) — substituting the role's max here would silently mint a 12h
|
||||
// session for any caller who omitted DurationSeconds, which AWS does not
|
||||
// do. The role-max upper bound still applies in the downstream cap chain
|
||||
// once the request has a concrete duration.
|
||||
func capDurationByRole(requested *int64, roleMax int64) *int64 {
|
||||
if roleMax <= 0 || requested == nil {
|
||||
return requested
|
||||
}
|
||||
d := defaultSec
|
||||
if roleMax > 0 && d > roleMax {
|
||||
d = roleMax
|
||||
if *requested > roleMax {
|
||||
v := roleMax
|
||||
return &v
|
||||
}
|
||||
if d > serviceMaxSec {
|
||||
d = serviceMaxSec
|
||||
}
|
||||
if d < 900 && roleMax > 0 {
|
||||
d = 900
|
||||
}
|
||||
if d >= defaultSec || d < 900 {
|
||||
return nil
|
||||
}
|
||||
return &d
|
||||
}
|
||||
|
||||
func (m *IAMManager) defaultTokenDurationSeconds() int64 {
|
||||
if m.stsService == nil || m.stsService.Config == nil {
|
||||
return sts.DefaultTokenDuration
|
||||
}
|
||||
return int64(m.stsService.Config.TokenDuration.Duration / time.Second)
|
||||
}
|
||||
|
||||
// maxSessionLengthSeconds mirrors validateSessionDurationSeconds so a
|
||||
// materialized default stays inside the bound the service will enforce.
|
||||
func (m *IAMManager) maxSessionLengthSeconds() int64 {
|
||||
maxSec := int64(sts.DefaultMaxSessionLength)
|
||||
if m.stsService != nil && m.stsService.Config != nil && m.stsService.Config.MaxSessionLength.Duration > 0 {
|
||||
if configured := int64(m.stsService.Config.MaxSessionLength.Duration / time.Second); configured >= 900 {
|
||||
maxSec = configured
|
||||
}
|
||||
}
|
||||
return maxSec
|
||||
return requested
|
||||
}
|
||||
|
||||
// AssumeRoleWithCredentials assumes a role using credentials (LDAP)
|
||||
@@ -1076,7 +1044,7 @@ func (m *IAMManager) AssumeRoleWithCredentials(ctx context.Context, request *sts
|
||||
}
|
||||
|
||||
// Apply role-level MaxSessionDuration cap.
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration, m.defaultTokenDurationSeconds(), m.maxSessionLengthSeconds())
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
|
||||
|
||||
// Use STS service to assume the role
|
||||
return m.stsService.AssumeRoleWithCredentials(ctx, request)
|
||||
|
||||
@@ -6,27 +6,21 @@ func intPtr(v int64) *int64 { return &v }
|
||||
|
||||
func TestCapDurationByRole(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
requested *int64
|
||||
roleMax int64
|
||||
defaultSec int64
|
||||
serviceMaxSec int64
|
||||
want *int64
|
||||
name string
|
||||
requested *int64
|
||||
roleMax int64
|
||||
want *int64
|
||||
}{
|
||||
{"no cap, no request -> nil keeps service default", nil, 0, 3600, 43200, nil},
|
||||
{"no cap, with request", intPtr(7200), 0, 3600, 43200, intPtr(7200)},
|
||||
{"cap below default, no request -> cap", nil, 1800, 3600, 43200, intPtr(1800)},
|
||||
{"cap above default, no request -> nil", nil, 43200, 3600, 43200, nil},
|
||||
{"request below cap -> request", intPtr(1800), 3600, 900, 43200, intPtr(1800)},
|
||||
{"request equal cap -> request", intPtr(3600), 3600, 900, 43200, intPtr(3600)},
|
||||
{"request above cap -> cap", intPtr(43200), 3600, 900, 43200, intPtr(3600)},
|
||||
{"default above service max -> service cap materialized", nil, 0, 7200, 3600, intPtr(3600)},
|
||||
{"role bound above service max -> service cap still applies", nil, 40000, 43200, 3600, intPtr(3600)},
|
||||
{"role bound below service floor -> tightest issuable", nil, 500, 3600, 43200, intPtr(900)},
|
||||
{"no cap, no request", nil, 0, nil},
|
||||
{"no cap, with request", intPtr(7200), 0, intPtr(7200)},
|
||||
{"cap only, no request -> nil so STS default applies", nil, 3600, nil},
|
||||
{"request below cap -> request", intPtr(1800), 3600, intPtr(1800)},
|
||||
{"request equal cap -> request", intPtr(3600), 3600, intPtr(3600)},
|
||||
{"request above cap -> cap", intPtr(43200), 3600, intPtr(3600)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := capDurationByRole(tc.requested, tc.roleMax, tc.defaultSec, tc.serviceMaxSec)
|
||||
got := capDurationByRole(tc.requested, tc.roleMax)
|
||||
switch {
|
||||
case got == nil && tc.want == nil:
|
||||
return
|
||||
|
||||
@@ -112,10 +112,9 @@ func copyRoleDefinition(original *RoleDefinition) *RoleDefinition {
|
||||
}
|
||||
|
||||
copied := &RoleDefinition{
|
||||
RoleName: original.RoleName,
|
||||
RoleArn: original.RoleArn,
|
||||
Description: original.Description,
|
||||
MaxSessionDuration: original.MaxSessionDuration,
|
||||
RoleName: original.RoleName,
|
||||
RoleArn: original.RoleArn,
|
||||
Description: original.Description,
|
||||
}
|
||||
|
||||
// Deep copy trust policy if it exists
|
||||
|
||||
@@ -604,7 +604,7 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
}
|
||||
|
||||
// 4. Calculate session duration
|
||||
sessionDuration := s.CalculateSessionDuration(request.DurationSeconds)
|
||||
sessionDuration := s.calculateSessionDuration(request.DurationSeconds)
|
||||
expiresAt := time.Now().Add(sessionDuration)
|
||||
|
||||
// 5. Generate session ID and credentials
|
||||
@@ -769,7 +769,7 @@ func (s *STSService) AssumeRoleWithCredentials(ctx context.Context, request *Ass
|
||||
func (s *STSService) issueSession(roleArn, roleSessionName, sessionPolicy string,
|
||||
durationSeconds *int64, providerName, subject string) (*AssumeRoleResponse, error) {
|
||||
|
||||
sessionDuration := s.CalculateSessionDuration(durationSeconds)
|
||||
sessionDuration := s.calculateSessionDuration(durationSeconds)
|
||||
expiresAt := time.Now().Add(sessionDuration)
|
||||
|
||||
sessionId, err := GenerateSessionId()
|
||||
@@ -1120,11 +1120,11 @@ func (s *STSService) validateRoleAssumptionForCredentials(ctx context.Context, r
|
||||
return nil
|
||||
}
|
||||
|
||||
// CalculateSessionDuration returns the requested DurationSeconds, or the
|
||||
// calculateSessionDuration returns the requested DurationSeconds, or the
|
||||
// configured TokenDuration default, capped at MaxSessionLength. The source
|
||||
// token's exp deliberately plays no part: per AWS semantics the session
|
||||
// outlives the (already verified) web identity token.
|
||||
func (s *STSService) CalculateSessionDuration(durationSeconds *int64) time.Duration {
|
||||
func (s *STSService) calculateSessionDuration(durationSeconds *int64) time.Duration {
|
||||
var duration time.Duration
|
||||
if durationSeconds != nil {
|
||||
duration = time.Duration(*durationSeconds) * time.Second
|
||||
|
||||
@@ -30,8 +30,8 @@ func TestCalculateSessionDuration(t *testing.T) {
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := svc.CalculateSessionDuration(tc.durationSeconds); got != tc.want {
|
||||
t.Errorf("CalculateSessionDuration(%v) = %v, want %v", tc.durationSeconds, got, tc.want)
|
||||
if got := svc.calculateSessionDuration(tc.durationSeconds); got != tc.want {
|
||||
t.Errorf("calculateSessionDuration(%v) = %v, want %v", tc.durationSeconds, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -211,9 +211,6 @@ func (fh *FileHandle) AddChunks(chunks []*filer_pb.FileChunk) {
|
||||
}
|
||||
|
||||
func (fh *FileHandle) ReleaseHandle() {
|
||||
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("ReleaseHandle", fh.fh, util.ExclusiveLock)
|
||||
defer fh.wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
|
||||
|
||||
// Release distributed lock before cleaning up, so other mounts can
|
||||
// proceed as soon as this handle is done flushing.
|
||||
if fh.dlmLock != nil {
|
||||
@@ -222,6 +219,9 @@ func (fh *FileHandle) ReleaseHandle() {
|
||||
glog.V(1).Infof("DLM lock released for inode %d", fh.inode)
|
||||
}
|
||||
|
||||
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("ReleaseHandle", fh.fh, util.ExclusiveLock)
|
||||
defer fh.wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
|
||||
|
||||
if fh.entryChunkGroup != nil {
|
||||
_ = fh.entryChunkGroup.Close()
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -73,26 +72,10 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
return code
|
||||
}
|
||||
|
||||
// Acquire the DLM lock before the filer create: a lock failure after an
|
||||
// eager create would return EAGAIN while the file stays persisted.
|
||||
var dlmLock *cluster.LiveLock
|
||||
if wfs.lockClient != nil {
|
||||
owner := fmt.Sprintf("mount-%d", wfs.signature)
|
||||
dlmLock = wfs.lockClient.NewBlockingLongLivedLock(
|
||||
string(entryFullPath), owner, lock_manager.LiveLockTTL,
|
||||
)
|
||||
if dlmLock == nil {
|
||||
return fuse.Status(syscall.EAGAIN)
|
||||
}
|
||||
}
|
||||
|
||||
inode, newEntry, code = wfs.createRegularFile(dirFullPath, name, in.Mode, in.Uid, in.Gid, 0, !wfs.option.EagerFilerCreate, true)
|
||||
if code == fuse.Status(syscall.EEXIST) && in.Flags&syscall.O_EXCL == 0 {
|
||||
// Race: another process created the file between our check and create.
|
||||
// Reopen the winner's entry; AcquireHandle takes its own lock.
|
||||
if dlmLock != nil {
|
||||
dlmLock.Stop()
|
||||
}
|
||||
// Reopen the winner's entry.
|
||||
newEntry, _, code = wfs.maybeLoadEntry(entryFullPath)
|
||||
if code != fuse.OK {
|
||||
return code
|
||||
@@ -117,9 +100,6 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
out.OpenFlags = 0
|
||||
return fuse.OK
|
||||
} else if code != fuse.OK {
|
||||
if dlmLock != nil {
|
||||
dlmLock.Stop()
|
||||
}
|
||||
return code
|
||||
} else {
|
||||
inode = wfs.inodeToPath.Lookup(entryFullPath, newEntry.Attributes.Crtime, false, false, inode, true)
|
||||
@@ -142,15 +122,15 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
// persisted the entry, so its handle starts clean.
|
||||
fileHandle.dirtyMetadata = !wfs.option.EagerFilerCreate
|
||||
|
||||
// Create bypasses AcquireHandle, so attach the lock acquired above.
|
||||
// A surviving handle may already hold one; ours is redundant then.
|
||||
if dlmLock != nil {
|
||||
if fileHandle.dlmLock == nil {
|
||||
fileHandle.dlmLock = dlmLock
|
||||
glog.V(1).Infof("DLM lock acquired for new file %s", entryFullPath)
|
||||
} else {
|
||||
dlmLock.Stop()
|
||||
}
|
||||
// Acquire DLM lock for new file creation (Create bypasses AcquireHandle
|
||||
// so we must acquire the lock here). Always lock on Create since file
|
||||
// creation is inherently a write operation.
|
||||
if wfs.lockClient != nil && fileHandle.dlmLock == nil {
|
||||
owner := fmt.Sprintf("mount-%d", wfs.signature)
|
||||
fileHandle.dlmLock = wfs.lockClient.NewBlockingLongLivedLock(
|
||||
string(entryFullPath), owner, lock_manager.LiveLockTTL,
|
||||
)
|
||||
glog.V(1).Infof("DLM lock acquired for new file %s", entryFullPath)
|
||||
}
|
||||
|
||||
out.Fh = uint64(fileHandle.fh)
|
||||
|
||||
@@ -2,7 +2,6 @@ package mount
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
@@ -78,12 +77,6 @@ func (wfs *WFS) AcquireHandle(inode uint64, flags, uid, gid uint32) (fileHandle
|
||||
fileHandle.dlmLock = wfs.lockClient.NewBlockingLongLivedLock(
|
||||
string(path), owner, lock_manager.LiveLockTTL,
|
||||
)
|
||||
if fileHandle.dlmLock == nil {
|
||||
// No lock server is reachable: proceeding would silently drop
|
||||
// cross-mount write serialization, so fail the open instead.
|
||||
wfs.fhMap.ReleaseByHandle(fileHandle.fh)
|
||||
return nil, fuse.Status(syscall.EAGAIN)
|
||||
}
|
||||
glog.V(1).Infof("DLM lock acquired for %s", path)
|
||||
}
|
||||
return fileHandle, fuse.OK
|
||||
|
||||
+48
-126
@@ -9,7 +9,6 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -17,10 +16,10 @@ import (
|
||||
)
|
||||
|
||||
// doRename tries the streaming mux first, falling back to unary on transport errors.
|
||||
func (wfs *WFS) doRename(ctx context.Context, request *filer_pb.StreamRenameEntryRequest, oldPath, newPath util.FullPath, newPathLock **cluster.LiveLock) error {
|
||||
func (wfs *WFS) doRename(ctx context.Context, request *filer_pb.StreamRenameEntryRequest, oldPath, newPath util.FullPath) error {
|
||||
if wfs.streamMutate != nil && wfs.streamMutate.IsAvailable() {
|
||||
err := wfs.streamMutate.Rename(ctx, request, func(resp *filer_pb.StreamRenameEntryResponse) error {
|
||||
return wfs.handleRenameResponse(ctx, resp, newPath, newPathLock)
|
||||
return wfs.handleRenameResponse(ctx, resp)
|
||||
})
|
||||
if err == nil || !errors.Is(err, ErrStreamTransport) {
|
||||
return err // success or application error
|
||||
@@ -40,7 +39,7 @@ func (wfs *WFS) doRename(ctx context.Context, request *filer_pb.StreamRenameEntr
|
||||
}
|
||||
return fmt.Errorf("dir Rename %s => %s receive: %v", oldPath, newPath, recvErr)
|
||||
}
|
||||
if err := wfs.handleRenameResponse(ctx, resp, newPath, newPathLock); err != nil {
|
||||
if err := wfs.handleRenameResponse(ctx, resp); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -241,102 +240,6 @@ func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string
|
||||
|
||||
glog.V(4).Infof("dir Rename %s => %s", oldPath, newPath)
|
||||
|
||||
// Acquire DLM locks on both old and new paths to prevent another mount
|
||||
// from opening either path for writing during the rename. Lock in
|
||||
// sorted order to prevent deadlocks when two mounts rename in opposite
|
||||
// directions (A→B vs B→A).
|
||||
//
|
||||
// Skip the old-path lock if this mount already holds it via an open
|
||||
// file handle (otherwise we'd deadlock trying to re-acquire our own lock).
|
||||
// Acquiring before the handle marks below keeps a lock failure from
|
||||
// leaving source handles flagged for a rename that never happened.
|
||||
var heldLocks []*cluster.LiveLock
|
||||
var newPathLock *cluster.LiveLock
|
||||
if wfs.lockClient != nil {
|
||||
// A handle open on the target holds its lock; claiming it up front
|
||||
// keeps the path locked through the rename (its close would otherwise
|
||||
// release it mid-flight) without waiting on our own ownership.
|
||||
var newPathLockFh *FileHandle
|
||||
defer func() {
|
||||
for _, l := range heldLocks {
|
||||
l.Stop()
|
||||
}
|
||||
if newPathLock != nil {
|
||||
// Never adopted by a migrated handle — return it to the
|
||||
// handle it came from if that is still open.
|
||||
if newPathLockFh != nil {
|
||||
if cur, ok := wfs.fhMap.FindFileHandle(newPathLockFh.inode); ok && cur == newPathLockFh {
|
||||
lk := wfs.fhLockTable.AcquireLock("renameDLM", cur.fh, util.ExclusiveLock)
|
||||
if cur.dlmLock == nil {
|
||||
cur.dlmLock = newPathLock
|
||||
newPathLock = nil
|
||||
}
|
||||
wfs.fhLockTable.ReleaseLock(cur.fh, lk)
|
||||
}
|
||||
}
|
||||
if newPathLock != nil {
|
||||
newPathLock.Stop()
|
||||
}
|
||||
}
|
||||
}()
|
||||
owner := fmt.Sprintf("mount-%d", wfs.signature)
|
||||
|
||||
// Check if the source file handle already holds a DLM lock on oldPath
|
||||
oldPathAlreadyLocked := false
|
||||
sourceInode, sourceMapped := wfs.inodeToPath.GetInode(oldPath)
|
||||
if !sourceMapped && oldEntry != nil && oldEntry.Attributes != nil {
|
||||
sourceInode = oldEntry.Attributes.Inode
|
||||
}
|
||||
if sourceInode != 0 {
|
||||
if fh, ok := wfs.fhMap.FindFileHandle(sourceInode); ok {
|
||||
lk := wfs.fhLockTable.AcquireLock("renameDLM", fh.fh, util.ExclusiveLock)
|
||||
oldPathAlreadyLocked = fh.dlmLock != nil
|
||||
wfs.fhLockTable.ReleaseLock(fh.fh, lk)
|
||||
}
|
||||
}
|
||||
targetInode, targetMapped := wfs.inodeToPath.GetInode(newPath)
|
||||
if !targetMapped && newEntry != nil && newEntry.Attributes != nil {
|
||||
targetInode = newEntry.Attributes.Inode
|
||||
}
|
||||
if targetInode != 0 && targetInode != sourceInode {
|
||||
if targetFh, ok := wfs.fhMap.FindFileHandle(targetInode); ok {
|
||||
targetFhLock := wfs.fhLockTable.AcquireLock("renameDLM", targetFh.fh, util.ExclusiveLock)
|
||||
if targetFh.dlmLock != nil {
|
||||
newPathLock = targetFh.dlmLock
|
||||
targetFh.dlmLock = nil
|
||||
newPathLockFh = targetFh
|
||||
}
|
||||
wfs.fhLockTable.ReleaseLock(targetFh.fh, targetFhLock)
|
||||
}
|
||||
}
|
||||
|
||||
// Determine which paths need new DLM locks
|
||||
pathsToLock := []string{}
|
||||
if newPathLock == nil {
|
||||
pathsToLock = append(pathsToLock, string(newPath))
|
||||
}
|
||||
if !oldPathAlreadyLocked && string(oldPath) != string(newPath) {
|
||||
pathsToLock = append(pathsToLock, string(oldPath))
|
||||
}
|
||||
// Sort for consistent lock ordering
|
||||
if len(pathsToLock) == 2 && pathsToLock[0] > pathsToLock[1] {
|
||||
pathsToLock[0], pathsToLock[1] = pathsToLock[1], pathsToLock[0]
|
||||
}
|
||||
|
||||
for _, p := range pathsToLock {
|
||||
dlmLock := wfs.lockClient.NewBlockingLongLivedLock(p, owner, lock_manager.LiveLockTTL)
|
||||
if dlmLock == nil {
|
||||
return fuse.Status(syscall.EAGAIN)
|
||||
}
|
||||
if p == string(newPath) {
|
||||
newPathLock = dlmLock
|
||||
} else {
|
||||
heldLocks = append(heldLocks, dlmLock)
|
||||
}
|
||||
}
|
||||
glog.V(1).Infof("DLM locks acquired for rename %s => %s (oldPathAlreadyLocked=%v)", oldPath, newPath, oldPathAlreadyLocked)
|
||||
}
|
||||
|
||||
// Ensure the source file's metadata exists on the filer before renaming.
|
||||
// Two cases can leave the entry only in the local cache:
|
||||
// 1. deferFilerCreate=true — file handle still open, dirtyMetadata set.
|
||||
@@ -397,6 +300,41 @@ func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string
|
||||
}
|
||||
}
|
||||
|
||||
// Acquire DLM locks on both old and new paths to prevent another mount
|
||||
// from opening either path for writing during the rename. Lock in
|
||||
// sorted order to prevent deadlocks when two mounts rename in opposite
|
||||
// directions (A→B vs B→A).
|
||||
//
|
||||
// Skip the old-path lock if this mount already holds it via an open
|
||||
// file handle (otherwise we'd deadlock trying to re-acquire our own lock).
|
||||
if wfs.lockClient != nil {
|
||||
owner := fmt.Sprintf("mount-%d", wfs.signature)
|
||||
|
||||
// Check if the source file handle already holds a DLM lock on oldPath
|
||||
oldPathAlreadyLocked := false
|
||||
if sourceInode, found := wfs.inodeToPath.GetInode(oldPath); found {
|
||||
if fh, ok := wfs.fhMap.FindFileHandle(sourceInode); ok && fh.dlmLock != nil {
|
||||
oldPathAlreadyLocked = true
|
||||
}
|
||||
}
|
||||
|
||||
// Determine which paths need new DLM locks
|
||||
pathsToLock := []string{string(newPath)}
|
||||
if !oldPathAlreadyLocked {
|
||||
pathsToLock = append(pathsToLock, string(oldPath))
|
||||
}
|
||||
// Sort for consistent lock ordering
|
||||
if len(pathsToLock) == 2 && pathsToLock[0] > pathsToLock[1] {
|
||||
pathsToLock[0], pathsToLock[1] = pathsToLock[1], pathsToLock[0]
|
||||
}
|
||||
|
||||
for _, p := range pathsToLock {
|
||||
dlmLock := wfs.lockClient.NewBlockingLongLivedLock(p, owner, lock_manager.LiveLockTTL)
|
||||
defer dlmLock.Stop()
|
||||
}
|
||||
glog.V(1).Infof("DLM locks acquired for rename %s => %s (oldPathAlreadyLocked=%v)", oldPath, newPath, oldPathAlreadyLocked)
|
||||
}
|
||||
|
||||
// update remote filer
|
||||
request := &filer_pb.StreamRenameEntryRequest{
|
||||
OldDirectory: string(oldDir),
|
||||
@@ -407,7 +345,7 @@ func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err := wfs.doRename(ctx, request, oldPath, newPath, &newPathLock)
|
||||
err := wfs.doRename(ctx, request, oldPath, newPath)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("Rename %s => %s: %v", oldPath, newPath, err)
|
||||
// Map error strings to FUSE status codes. String matching is used
|
||||
@@ -439,7 +377,7 @@ func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string
|
||||
|
||||
}
|
||||
|
||||
func (wfs *WFS) handleRenameResponse(ctx context.Context, resp *filer_pb.StreamRenameEntryResponse, renameNewPath util.FullPath, renameNewPathLock **cluster.LiveLock) error {
|
||||
func (wfs *WFS) handleRenameResponse(ctx context.Context, resp *filer_pb.StreamRenameEntryResponse) error {
|
||||
// comes from filer StreamRenameEntry, can only be create or delete entry
|
||||
|
||||
glog.V(4).Infof("dir Rename %+v", resp.EventNotification)
|
||||
@@ -473,32 +411,16 @@ func (wfs *WFS) handleRenameResponse(ctx context.Context, resp *filer_pb.StreamR
|
||||
// Migrate the DLM lock from old path to new path so the
|
||||
// lock key matches the current file location. Hold the
|
||||
// fhLockTable to prevent ReleaseHandle from concurrently
|
||||
// stopping the lock during migration. Acquire before
|
||||
// releasing: a failed migration keeps the old lock rather
|
||||
// than leaving the handle unlocked.
|
||||
if wfs.lockClient != nil && oldPath != newPath {
|
||||
// stopping the lock during migration.
|
||||
if wfs.lockClient != nil {
|
||||
fhActiveLock := wfs.fhLockTable.AcquireLock("renameDLM", fh.fh, util.ExclusiveLock)
|
||||
if fh.dlmLock != nil {
|
||||
var newLock *cluster.LiveLock
|
||||
if newPath == renameNewPath && renameNewPathLock != nil && *renameNewPathLock != nil {
|
||||
// The rename already holds a lock on the target;
|
||||
// adopt it — re-acquiring our own lock would block
|
||||
// until this handle is released.
|
||||
newLock = *renameNewPathLock
|
||||
*renameNewPathLock = nil
|
||||
} else {
|
||||
owner := fmt.Sprintf("mount-%d", wfs.signature)
|
||||
newLock = wfs.lockClient.NewBlockingLongLivedLock(
|
||||
string(newPath), owner, lock_manager.LiveLockTTL,
|
||||
)
|
||||
}
|
||||
if newLock != nil {
|
||||
fh.dlmLock.Stop()
|
||||
fh.dlmLock = newLock
|
||||
glog.V(1).Infof("DLM lock migrated from %s to %s", oldPath, newPath)
|
||||
} else {
|
||||
glog.Warningf("DLM lock migration to %s failed; keeping lock on %s", newPath, oldPath)
|
||||
}
|
||||
owner := fmt.Sprintf("mount-%d", wfs.signature)
|
||||
fh.dlmLock.Stop()
|
||||
fh.dlmLock = wfs.lockClient.NewBlockingLongLivedLock(
|
||||
string(newPath), owner, lock_manager.LiveLockTTL,
|
||||
)
|
||||
glog.V(1).Infof("DLM lock migrated from %s to %s", oldPath, newPath)
|
||||
}
|
||||
wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ func TestHandleRenameResponseLeavesUncachedTargetOutOfCache(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
if err := wfs.handleRenameResponse(context.Background(), resp, targetPath, nil); err != nil {
|
||||
if err := wfs.handleRenameResponse(context.Background(), resp); err != nil {
|
||||
t.Fatalf("handle rename response: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -194,12 +194,11 @@ func NewUploaderWithHttpClient(httpClient HTTPClient) *Uploader {
|
||||
}
|
||||
}
|
||||
|
||||
func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, host string, auth security.EncodedJwt, fsync bool, err error), uploadOption *UploadOption, data []byte) (fileId string, uploadResult *UploadResult, err error) {
|
||||
func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, host string, auth security.EncodedJwt, err error), uploadOption *UploadOption, data []byte) (fileId string, uploadResult *UploadResult, err error) {
|
||||
doUploadFunc := func() error {
|
||||
var host string
|
||||
var auth security.EncodedJwt
|
||||
var fsync bool
|
||||
fileId, host, auth, fsync, err = assignFn()
|
||||
fileId, host, auth, err = assignFn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -209,9 +208,6 @@ func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, ho
|
||||
genUrl = func(host, fileId string) string { return fmt.Sprintf("http://%s/%s", host, fileId) }
|
||||
}
|
||||
uploadOption.UploadUrl = genUrl(host, fileId)
|
||||
if fsync {
|
||||
uploadOption.UploadUrl = util_http.AppendQueryParameter(uploadOption.UploadUrl, "fsync", "true")
|
||||
}
|
||||
uploadOption.Jwt = auth
|
||||
if util_http.IsProxyChunkUrl(uploadOption.UploadUrl) {
|
||||
// The request addresses the filer, which authorizes it and mints the
|
||||
@@ -267,7 +263,7 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
|
||||
uploadOption.Md5 = base64.StdEncoding.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
fileId, uploadResult, err = uploader.uploadWithRetryData(func() (fileId string, host string, auth security.EncodedJwt, fsync bool, err error) {
|
||||
fileId, uploadResult, err = uploader.uploadWithRetryData(func() (fileId string, host string, auth security.EncodedJwt, err error) {
|
||||
// grpc assign volume
|
||||
if grpcAssignErr := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
assignCtx, assignCancel := context.WithTimeout(context.Background(), assignVolumeTimeout)
|
||||
@@ -282,7 +278,6 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
|
||||
}
|
||||
|
||||
fileId, auth = resp.FileId, security.EncodedJwt(resp.Auth)
|
||||
fsync = resp.Fsync
|
||||
loc := resp.Location
|
||||
host = filerClient.AdjustedUrl(loc)
|
||||
|
||||
|
||||
@@ -95,12 +95,12 @@ func TestUploadWithRetryDataReassignsOnVolumeSizeExceeded(t *testing.T) {
|
||||
uploader := newUploader(httpClient)
|
||||
|
||||
assignCalls := 0
|
||||
fileID, uploadResult, err := uploader.uploadWithRetryData(func() (string, string, security.EncodedJwt, bool, error) {
|
||||
fileID, uploadResult, err := uploader.uploadWithRetryData(func() (string, string, security.EncodedJwt, error) {
|
||||
assignCalls++
|
||||
if assignCalls == 1 {
|
||||
return "1,first", "volume-a", "", false, nil
|
||||
return "1,first", "volume-a", "", nil
|
||||
}
|
||||
return "2,second", "volume-b", "", false, nil
|
||||
return "2,second", "volume-b", "", nil
|
||||
}, &UploadOption{Filename: "test.bin"}, []byte("abc"))
|
||||
|
||||
if err != nil {
|
||||
@@ -143,12 +143,12 @@ func TestUploadWithRetryDataReassignsOnReplicaWriteFailure(t *testing.T) {
|
||||
uploader := newUploader(httpClient)
|
||||
|
||||
assignCalls := 0
|
||||
fileID, uploadResult, err := uploader.uploadWithRetryData(func() (string, string, security.EncodedJwt, bool, error) {
|
||||
fileID, uploadResult, err := uploader.uploadWithRetryData(func() (string, string, security.EncodedJwt, error) {
|
||||
assignCalls++
|
||||
if assignCalls == 1 {
|
||||
return "1,first", "volume-a", "", false, nil
|
||||
return "1,first", "volume-a", "", nil
|
||||
}
|
||||
return "2,second", "volume-b", "", false, nil
|
||||
return "2,second", "volume-b", "", nil
|
||||
}, &UploadOption{Filename: "test.bin"}, []byte("abc"))
|
||||
|
||||
if err != nil {
|
||||
@@ -199,64 +199,6 @@ func (c *bodyCapturingHTTPClient) Do(req *http.Request) (*http.Response, error)
|
||||
}, nil
|
||||
}
|
||||
|
||||
type fsyncAssignClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
response *filer_pb.AssignVolumeResponse
|
||||
}
|
||||
|
||||
func (c *fsyncAssignClient) AssignVolume(context.Context, *filer_pb.AssignVolumeRequest, ...grpc.CallOption) (*filer_pb.AssignVolumeResponse, error) {
|
||||
return c.response, nil
|
||||
}
|
||||
|
||||
func (c *fsyncAssignClient) WithFilerClient(_ bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return fn(c)
|
||||
}
|
||||
func (c *fsyncAssignClient) AdjustedUrl(loc *filer_pb.Location) string { return loc.GetUrl() }
|
||||
func (c *fsyncAssignClient) GetDataCenter() string { return "" }
|
||||
|
||||
func TestUploadWithRetryAppendsFsyncWhenAssigned(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
proxy bool
|
||||
}{
|
||||
{name: "direct"},
|
||||
{name: "filer proxy", proxy: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
const fileID = "1,0123456789"
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if gotFsync := r.URL.Query().Get("fsync"); gotFsync != "true" {
|
||||
t.Errorf("upload fsync = %q, want true when assignment requires fsync", gotFsync)
|
||||
}
|
||||
if tc.proxy {
|
||||
if got := r.URL.Query().Get("proxyChunkId"); got != fileID {
|
||||
t.Errorf("proxyChunkId = %q, want %q", got, fileID)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = io.WriteString(w, `{"size":3}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
host := strings.TrimPrefix(server.URL, "http://")
|
||||
client := &fsyncAssignClient{response: &filer_pb.AssignVolumeResponse{
|
||||
FileId: fileID,
|
||||
Location: &filer_pb.Location{Url: host},
|
||||
Fsync: true,
|
||||
}}
|
||||
option := &UploadOption{}
|
||||
if tc.proxy {
|
||||
option.GenUploadUrl = GenUploadUrlProxy(host)
|
||||
}
|
||||
_, _, err, _ := newUploader(server.Client()).UploadWithRetry(client,
|
||||
&filer_pb.AssignVolumeRequest{Path: "/bucket/object"}, option, strings.NewReader("abc"))
|
||||
if err != nil {
|
||||
t.Fatalf("upload failed: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// hangingAssignSeaweedClient is a SeaweedFilerClient whose AssignVolume blocks
|
||||
// until its context is done, so a test can prove UploadWithRetry bounds the RPC.
|
||||
type hangingAssignSeaweedClient struct {
|
||||
|
||||
@@ -116,7 +116,7 @@ func (m *Mover) LiveMoveVolume(ctx context.Context, volumeId needle.VolumeId, so
|
||||
if cleanupTarget {
|
||||
// The target copy may be missing tailed entries; remove it so
|
||||
// the source stays the only replica.
|
||||
if dErr := m.DeleteVolume(cleanupCtx, volumeId, target, false, false, true); dErr != nil {
|
||||
if dErr := m.DeleteVolume(cleanupCtx, volumeId, target, false, true); dErr != nil {
|
||||
// Restoring the source while the stale target stays mounted
|
||||
// risks divergent replicas; keep the source readonly. A
|
||||
// re-run refuses while the copy exists, so name the fix.
|
||||
@@ -232,7 +232,7 @@ func (m *Mover) LiveMoveVolume(ctx context.Context, volumeId needle.VolumeId, so
|
||||
opts.Progress(90, fmt.Sprintf("deleting volume %d from %s", volumeId, source))
|
||||
fmt.Fprintf(opts.Writer, "deleting volume %d from %s\n", volumeId, source)
|
||||
sourceDeleteStarted = true
|
||||
if err = m.DeleteVolume(ctx, volumeId, source, false, false, true); err != nil {
|
||||
if err = m.DeleteVolume(ctx, volumeId, source, false, true); err != nil {
|
||||
return fmt.Errorf("delete volume %d from %s: %v", volumeId, source, err)
|
||||
}
|
||||
|
||||
@@ -415,12 +415,11 @@ func (m *Mover) ReadVolumeFileStatus(ctx context.Context, volumeId needle.Volume
|
||||
// DeleteVolume removes the volume from server. When keepRemoteData is true, the
|
||||
// cloud-tier object backing the volume is left intact — used on the source side
|
||||
// of a move where another server is taking over the same .vif.
|
||||
func (m *Mover) DeleteVolume(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, onlyEmpty bool, onlyGarbage bool, keepRemoteData bool) error {
|
||||
func (m *Mover) DeleteVolume(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, onlyEmpty bool, keepRemoteData bool) error {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
_, deleteErr := client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
OnlyEmpty: onlyEmpty,
|
||||
OnlyGarbage: onlyGarbage,
|
||||
KeepRemoteData: keepRemoteData,
|
||||
})
|
||||
return deleteErr
|
||||
|
||||
@@ -259,10 +259,6 @@ message VolumeDeleteRequest {
|
||||
// when true, do not remove the cloud-tier object backing the volume.
|
||||
// used for moves where another server is taking over the same .vif.
|
||||
bool keep_remote_data = 3;
|
||||
// when true, delete only if every needle is deleted: the volume held
|
||||
// data once but nothing is live anymore. Passing either check,
|
||||
// only_empty or this one, is enough to delete.
|
||||
bool only_garbage = 4;
|
||||
}
|
||||
message VolumeDeleteResponse {
|
||||
}
|
||||
@@ -477,7 +473,6 @@ message VolumeEcShardsDeleteRequest {
|
||||
repeated uint32 shard_ids = 3;
|
||||
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
uint32 delete_generations_older_than = 6; // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
|
||||
}
|
||||
message VolumeEcShardsDeleteResponse {
|
||||
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v3.21.12
|
||||
// protoc v6.33.4
|
||||
// source: volume_server.proto
|
||||
|
||||
package volume_server_pb
|
||||
@@ -1468,12 +1468,8 @@ type VolumeDeleteRequest struct {
|
||||
// when true, do not remove the cloud-tier object backing the volume.
|
||||
// used for moves where another server is taking over the same .vif.
|
||||
KeepRemoteData bool `protobuf:"varint,3,opt,name=keep_remote_data,json=keepRemoteData,proto3" json:"keep_remote_data,omitempty"`
|
||||
// when true, delete only if every needle is deleted: the volume held
|
||||
// data once but nothing is live anymore. Passing either check,
|
||||
// only_empty or this one, is enough to delete.
|
||||
OnlyGarbage bool `protobuf:"varint,4,opt,name=only_garbage,json=onlyGarbage,proto3" json:"only_garbage,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VolumeDeleteRequest) Reset() {
|
||||
@@ -1527,13 +1523,6 @@ func (x *VolumeDeleteRequest) GetKeepRemoteData() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *VolumeDeleteRequest) GetOnlyGarbage() bool {
|
||||
if x != nil {
|
||||
return x.OnlyGarbage
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type VolumeDeleteResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -3733,15 +3722,14 @@ func (*VolumeEcShardsCopyResponse) Descriptor() ([]byte, []int) {
|
||||
}
|
||||
|
||||
type VolumeEcShardsDeleteRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
FullTeardown bool `protobuf:"varint,4,opt,name=full_teardown,json=fullTeardown,proto3" json:"full_teardown,omitempty"` // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
EncodeTsNs int64 `protobuf:"varint,5,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
DeleteGenerationsOlderThan uint32 `protobuf:"varint,6,opt,name=delete_generations_older_than,json=deleteGenerationsOlderThan,proto3" json:"delete_generations_older_than,omitempty"` // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
FullTeardown bool `protobuf:"varint,4,opt,name=full_teardown,json=fullTeardown,proto3" json:"full_teardown,omitempty"` // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
EncodeTsNs int64 `protobuf:"varint,5,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsDeleteRequest) Reset() {
|
||||
@@ -3809,13 +3797,6 @@ func (x *VolumeEcShardsDeleteRequest) GetEncodeTsNs() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsDeleteRequest) GetDeleteGenerationsOlderThan() uint32 {
|
||||
if x != nil {
|
||||
return x.DeleteGenerationsOlderThan
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type VolumeEcShardsDeleteResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
FullTeardownDone bool `protobuf:"varint,1,opt,name=full_teardown_done,json=fullTeardownDone,proto3" json:"full_teardown_done,omitempty"` // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
@@ -7343,13 +7324,12 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\x15VolumeUnmountResponse\"<\n" +
|
||||
"\x1dVolumeConsolidateIndexRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\" \n" +
|
||||
"\x1eVolumeConsolidateIndexResponse\"\x9e\x01\n" +
|
||||
"\x1eVolumeConsolidateIndexResponse\"{\n" +
|
||||
"\x13VolumeDeleteRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1d\n" +
|
||||
"\n" +
|
||||
"only_empty\x18\x02 \x01(\bR\tonlyEmpty\x12(\n" +
|
||||
"\x10keep_remote_data\x18\x03 \x01(\bR\x0ekeepRemoteData\x12!\n" +
|
||||
"\fonly_garbage\x18\x04 \x01(\bR\vonlyGarbage\"\x16\n" +
|
||||
"\x10keep_remote_data\x18\x03 \x01(\bR\x0ekeepRemoteData\"\x16\n" +
|
||||
"\x14VolumeDeleteResponse\"q\n" +
|
||||
"\x19VolumeMarkReadonlyRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x18\n" +
|
||||
@@ -7514,7 +7494,7 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\x0fcopy_ecsum_file\x18\t \x01(\bR\rcopyEcsumFile\x12+\n" +
|
||||
"\x12io_byte_per_second\x18\n" +
|
||||
" \x01(\x03R\x0fioBytePerSecond\"\x1c\n" +
|
||||
"\x1aVolumeEcShardsCopyResponse\"\x81\x02\n" +
|
||||
"\x1aVolumeEcShardsCopyResponse\"\xbe\x01\n" +
|
||||
"\x1bVolumeEcShardsDeleteRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" +
|
||||
"\n" +
|
||||
@@ -7523,8 +7503,7 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\x12#\n" +
|
||||
"\rfull_teardown\x18\x04 \x01(\bR\ffullTeardown\x12 \n" +
|
||||
"\fencode_ts_ns\x18\x05 \x01(\x03R\n" +
|
||||
"encodeTsNs\x12A\n" +
|
||||
"\x1ddelete_generations_older_than\x18\x06 \x01(\rR\x1adeleteGenerationsOlderThan\"L\n" +
|
||||
"encodeTsNs\"L\n" +
|
||||
"\x1cVolumeEcShardsDeleteResponse\x12,\n" +
|
||||
"\x12full_teardown_done\x18\x01 \x01(\bR\x10fullTeardownDone\"\xd4\x01\n" +
|
||||
"\x1aVolumeEcShardsMountRequest\x12\x1b\n" +
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v3.21.12
|
||||
// - protoc v6.33.4
|
||||
// source: volume_server.proto
|
||||
|
||||
package volume_server_pb
|
||||
@@ -74,7 +74,7 @@ const (
|
||||
//
|
||||
// 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.
|
||||
type VolumeServerClient interface {
|
||||
//Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
// Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
BatchDelete(ctx context.Context, in *BatchDeleteRequest, opts ...grpc.CallOption) (*BatchDeleteResponse, error)
|
||||
VacuumVolumeCheck(ctx context.Context, in *VacuumVolumeCheckRequest, opts ...grpc.CallOption) (*VacuumVolumeCheckResponse, error)
|
||||
VacuumVolumeCompact(ctx context.Context, in *VacuumVolumeCompactRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[VacuumVolumeCompactResponse], error)
|
||||
@@ -727,7 +727,7 @@ func (c *volumeServerClient) Ping(ctx context.Context, in *PingRequest, opts ...
|
||||
// All implementations must embed UnimplementedVolumeServerServer
|
||||
// for forward compatibility.
|
||||
type VolumeServerServer interface {
|
||||
//Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
// Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
BatchDelete(context.Context, *BatchDeleteRequest) (*BatchDeleteResponse, error)
|
||||
VacuumVolumeCheck(context.Context, *VacuumVolumeCheckRequest) (*VacuumVolumeCheckResponse, error)
|
||||
VacuumVolumeCompact(*VacuumVolumeCompactRequest, grpc.ServerStreamingServer[VacuumVolumeCompactResponse]) error
|
||||
|
||||
@@ -14,19 +14,15 @@ const (
|
||||
SyncKeyPrefix = "remote.sync."
|
||||
)
|
||||
|
||||
// SyncOffsetKey is the filer store key holding the write-back sync watermark
|
||||
// for a mounted directory.
|
||||
func SyncOffsetKey(dir string) []byte {
|
||||
syncKey := make([]byte, len(SyncKeyPrefix)+4)
|
||||
copy(syncKey, SyncKeyPrefix)
|
||||
util.Uint32toBytes(syncKey[len(SyncKeyPrefix):], uint32(util.HashStringToLong(dir)))
|
||||
return syncKey
|
||||
}
|
||||
|
||||
func GetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir string) (lastOffsetTsNs int64, readErr error) {
|
||||
|
||||
dirHash := uint32(util.HashStringToLong(dir))
|
||||
|
||||
readErr = pb.WithFilerClient(false, 0, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.KvGet(context.Background(), &filer_pb.KvGetRequest{Key: SyncOffsetKey(dir)})
|
||||
syncKey := []byte(SyncKeyPrefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(SyncKeyPrefix):len(SyncKeyPrefix)+4], dirHash)
|
||||
|
||||
resp, err := client.KvGet(context.Background(), &filer_pb.KvGetRequest{Key: syncKey})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -49,13 +45,18 @@ func GetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir s
|
||||
|
||||
func SetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir string, offsetTsNs int64) error {
|
||||
|
||||
dirHash := uint32(util.HashStringToLong(dir))
|
||||
|
||||
return pb.WithFilerClient(false, 0, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
syncKey := []byte(SyncKeyPrefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(SyncKeyPrefix):len(SyncKeyPrefix)+4], dirHash)
|
||||
|
||||
valueBuf := make([]byte, 8)
|
||||
util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
|
||||
|
||||
resp, err := client.KvPut(context.Background(), &filer_pb.KvPutRequest{
|
||||
Key: SyncOffsetKey(dir),
|
||||
Key: syncKey,
|
||||
Value: valueBuf,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -144,43 +144,6 @@ func TestAuditRequesterIdentityEmptyForNonFederatedSession(t *testing.T) {
|
||||
assert.Empty(t, log.RequesterIdentity, "non-federated session must not surface the session id as a requester_identity")
|
||||
}
|
||||
|
||||
// Authentication resolves the identity before the policy verdict, so a denied
|
||||
// request still has a requester and the audit entry must name it. See issue
|
||||
// #11474.
|
||||
func TestAuditRequesterForDeniedRequest(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{
|
||||
Name: "read_only_user",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "readonly_access_key", SecretKey: "readonly_secret_key"}},
|
||||
Actions: []string{"Read", "List"},
|
||||
}},
|
||||
}))
|
||||
|
||||
denied, err := newTestRequest(http.MethodDelete, "http://s3/bucket/obj", 0, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, signRequestV4(denied, "readonly_access_key", "readonly_secret_key"))
|
||||
denied = s3_constants.EnsureIdentityHolder(denied)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
iam.Auth(func(http.ResponseWriter, *http.Request) {
|
||||
t.Error("denied request must not reach the handler")
|
||||
}, s3_constants.ACTION_WRITE)(rec, denied)
|
||||
|
||||
require.Equal(t, http.StatusForbidden, rec.Code)
|
||||
log := s3err.GetAccessLog(denied, rec.Code, s3err.ErrAccessDenied)
|
||||
assert.Equal(t, "read_only_user", log.Requester, "denied request must still audit the requester")
|
||||
assert.Equal(t, "arn:aws:iam::"+defaultAccountID+":user/read_only_user", log.RequesterArn)
|
||||
|
||||
anonymous := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodDelete, "http://s3/bucket/obj", nil))
|
||||
rec = httptest.NewRecorder()
|
||||
iam.handleAuthResult(rec, anonymous, nil, s3err.ErrAccessDenied, func(http.ResponseWriter, *http.Request) {
|
||||
t.Error("denied request must not reach the handler")
|
||||
})
|
||||
log = s3err.GetAccessLog(anonymous, rec.Code, s3err.ErrAccessDenied)
|
||||
assert.Empty(t, log.Requester, "unauthenticated denial must not attribute a requester")
|
||||
}
|
||||
|
||||
// A JWT-authenticated identity carries no PrincipalArn of its own — the auth
|
||||
// layer hands the principal over in a request header — so the audit entry has to
|
||||
// resolve the ARN the same way policy evaluation does.
|
||||
|
||||
@@ -1565,10 +1565,7 @@ func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) htt
|
||||
return
|
||||
}
|
||||
|
||||
// authRequestWithAuthType keeps the resolved identity when authN
|
||||
// succeeds but authZ denies, so the denied request still audits its
|
||||
// requester; a failed authN resolves no identity at all.
|
||||
identity, errCode, _ := iam.authRequestWithAuthType(r, action)
|
||||
identity, errCode := iam.authRequest(r, action)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.V(3).Infof("auth error: %v", errCode)
|
||||
}
|
||||
@@ -1634,12 +1631,11 @@ func recordIdentityInContext(r *http.Request, identity *Identity) context.Contex
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) handleAuthResult(w http.ResponseWriter, r *http.Request, identity *Identity, errCode s3err.ErrorCode, f http.HandlerFunc) {
|
||||
// Store the authenticated identity in request context (secure, cannot be spoofed)
|
||||
// even on the deny path so audit records for rejected requests keep requester attribution
|
||||
if identity != nil && identity.Name != "" {
|
||||
r = r.WithContext(recordIdentityInContext(r, identity))
|
||||
}
|
||||
if errCode == s3err.ErrNone {
|
||||
// Store the authenticated identity in request context (secure, cannot be spoofed)
|
||||
if identity != nil && identity.Name != "" {
|
||||
r = r.WithContext(recordIdentityInContext(r, identity))
|
||||
}
|
||||
f(w, r)
|
||||
return
|
||||
}
|
||||
@@ -1753,23 +1749,6 @@ func (iam *IdentityAccessManagement) authenticateRequestInternal(r *http.Request
|
||||
return identity, s3Err, reqAuthType
|
||||
}
|
||||
|
||||
// isBucketListingRequest reports whether the request lists bucket contents:
|
||||
// the ACTION_LIST routes, and ListMultipartUploads (GET ?uploads), which the
|
||||
// router registers under ACTION_READ without an object-path constraint.
|
||||
// GET /bucket/key?uploads therefore also reaches the listing handler. Route
|
||||
// vars are used so a prefix promoted into the authorization object does not
|
||||
// hide the bucket-level shape.
|
||||
func isBucketListingRequest(r *http.Request, action Action) bool {
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
return true
|
||||
}
|
||||
if r.Method != http.MethodGet || r.URL == nil || !r.URL.Query().Has("uploads") {
|
||||
return false
|
||||
}
|
||||
_, object := s3_constants.GetBucketAndObject(r)
|
||||
return object == "" || object == "/"
|
||||
}
|
||||
|
||||
// authRequestWithAuthType authenticates and then authorizes a request for a given action.
|
||||
func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, action Action) (*Identity, s3err.ErrorCode, authType) {
|
||||
identity, s3Err, reqAuthType := iam.authenticateRequestInternal(r)
|
||||
@@ -1780,13 +1759,13 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
prefix := s3_constants.GetPrefix(r)
|
||||
|
||||
// For bucket listings, use prefix for permission checking if available:
|
||||
// the aws cli, s3api, and boto3 carry the key scope in ?prefix= rather
|
||||
// than the URL path. Other actions must not promote it — a bucket-level
|
||||
// request has no object, and a promoted prefix would let an object-scoped
|
||||
// grant (e.g. Write:bucket/*) authorize bucket-subresource operations
|
||||
// like ?versioning or ?lifecycle as if they were object writes.
|
||||
if isBucketListingRequest(r, action) && (object == "" || object == "/") && prefix != "" {
|
||||
// For List operations, use prefix for permission checking if available
|
||||
if action == s3_constants.ACTION_LIST && object == "" && prefix != "" {
|
||||
// List operation with prefix - check permission for the prefix path
|
||||
object = prefix
|
||||
} else if (object == "/" || object == "") && prefix != "" {
|
||||
// Using the aws cli with s3, and s3api, and with boto3, the object is often set to "/" or empty
|
||||
// but the prefix is set to the actual object key for permission checking
|
||||
object = prefix
|
||||
}
|
||||
|
||||
@@ -1827,11 +1806,11 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
|
||||
if identity != nil {
|
||||
claims = identity.Claims
|
||||
}
|
||||
// Bucket listings are bucket-level; the prefix promoted into
|
||||
// object (for the legacy CanDo path) must not scope the resource
|
||||
// ARN. Prefix is matched via the s3:prefix Condition.
|
||||
// List is bucket-level; the prefix promoted into object (for the
|
||||
// legacy CanDo path) must not scope the resource ARN. Prefix is
|
||||
// matched via the s3:prefix Condition.
|
||||
policyObject := object
|
||||
if isBucketListingRequest(r, action) {
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
policyObject = ""
|
||||
}
|
||||
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, policyObject, string(action), principal, r, claims, nil)
|
||||
@@ -2534,12 +2513,11 @@ func (iam *IdentityAccessManagement) evaluateAttachedIAMPolicies(r *http.Request
|
||||
return attachedIAMPolicyNoMatch
|
||||
}
|
||||
|
||||
// Bucket listings are bucket-level; the prefix promoted into object (for
|
||||
// the legacy CanDo path) must not scope the resource ARN or the resolved
|
||||
// action (e.g. ListBucketVersions on ?versions). Prefix is matched via
|
||||
// s3:prefix.
|
||||
// List is bucket-level; the prefix promoted into object (for the legacy
|
||||
// CanDo path) must not scope the resource ARN or the resolved action
|
||||
// (e.g. ListBucketVersions on ?versions). Prefix is matched via s3:prefix.
|
||||
resourceObject := object
|
||||
if isBucketListingRequest(r, action) {
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
resourceObject = ""
|
||||
}
|
||||
resource := buildResourceARN(bucket, resourceObject)
|
||||
@@ -3039,11 +3017,11 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity
|
||||
// check evaluates the same action and resource ARN as the policy engine.
|
||||
func resolveS3AuthTarget(action Action, bucket, object string, r *http.Request) (s3Action, resourceArn string) {
|
||||
resourceObjectKey := object
|
||||
if isBucketListingRequest(r, action) {
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
resourceObjectKey = ""
|
||||
}
|
||||
resourceArn = buildS3ResourceArn(bucket, resourceObjectKey)
|
||||
s3Action = ResolveS3Action(r, string(action), bucket, resourceObjectKey)
|
||||
s3Action = ResolveS3Action(r, string(action), bucket, object)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -124,54 +124,3 @@ func TestAttachedPolicyExplicitDenyOverridesNativeAdmin(t *testing.T) {
|
||||
assert.Equal(t, s3err.ErrAccessDenied, errCode,
|
||||
"explicit Deny in an attached policy must override native Admin")
|
||||
}
|
||||
|
||||
// GET ?uploads lists multipart uploads at bucket level but routes under Read,
|
||||
// so the prefix promoted into object must not change the evaluated action or
|
||||
// resource: an explicit Deny on s3:ListBucketMultipartUploads must still
|
||||
// constrain a native admin, and an Allow on the bucket ARN must satisfy a
|
||||
// plain attached-policy identity.
|
||||
func TestMultipartListingResolvesBucketAction(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
denyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Deny", "Action": "s3:ListBucketMultipartUploads", "Resource": "arn:aws:s3:::mybucket"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, iam.PutPolicy("DenyUploadsListing", string(denyDoc)))
|
||||
allowDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:ListBucketMultipartUploads", "Resource": "arn:aws:s3:::mybucket"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, iam.PutPolicy("AllowUploadsListing", string(allowDoc)))
|
||||
|
||||
uploadsReq := func() *http.Request {
|
||||
return httptest.NewRequest(http.MethodGet, "/mybucket?uploads&prefix=x/", nil)
|
||||
}
|
||||
admin := &Identity{
|
||||
Name: "admin",
|
||||
Account: &Account{DisplayName: "admin", Id: "admin"},
|
||||
Actions: []Action{s3_constants.ACTION_ADMIN},
|
||||
PolicyNames: []string{"DenyUploadsListing"},
|
||||
PrincipalArn: "arn:aws:iam::111122223333:user/admin",
|
||||
}
|
||||
reader := &Identity{
|
||||
Name: "reader",
|
||||
Account: &Account{DisplayName: "reader", Id: "reader"},
|
||||
PolicyNames: []string{"AllowUploadsListing"},
|
||||
PrincipalArn: "arn:aws:iam::111122223333:user/reader",
|
||||
}
|
||||
|
||||
// object carries the promoted prefix, matching authRequestWithAuthType
|
||||
assert.Equal(t, s3err.ErrAccessDenied,
|
||||
iam.VerifyActionPermission(uploadsReq(), admin, s3_constants.ACTION_READ, "mybucket", "x/"),
|
||||
"explicit Deny on the uploads listing must override native Admin")
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
iam.VerifyActionPermission(uploadsReq(), reader, s3_constants.ACTION_READ, "mybucket", "x/"),
|
||||
"s3:ListBucketMultipartUploads on the bucket must allow the uploads listing")
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -558,108 +557,3 @@ func TestRealSDKSignerWithForwardedHeaders(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// GHSA-8rrx-349w-6396: ?prefix= was promoted into the object for every action,
|
||||
// so PUT /cache?versioning&prefix=x authorized as Write:cache/x. An identity
|
||||
// holding only Write:cache/* could then change bucket versioning, lifecycle,
|
||||
// cors, and object-lock configuration.
|
||||
func TestPrefixParameterDoesNotEscalateBucketActions(t *testing.T) {
|
||||
resetMemoryStore()
|
||||
defer resetMemoryStore()
|
||||
|
||||
configContent := `{
|
||||
"identities": [
|
||||
{"name":"admin","credentials":[{"accessKey":"ADMINKEY","secretKey":"adminsecret0000000000000000000001"}],"actions":["Admin"]},
|
||||
{"name":"writer","credentials":[{"accessKey":"WRITERKEY","secretKey":"writersecret000000000000000000001"}],"actions":["Read:cache","Write:cache/*","List:cache"]},
|
||||
{"name":"uploadreader","credentials":[{"accessKey":"UPREADERKEY","secretKey":"upreadersecret00000000000000001"}],"actions":["Read:cache/uploads/*"]},
|
||||
{"name":"policywriter","credentials":[{"accessKey":"POLICYKEY","secretKey":"policysecret00000000000000000001"}],"policyNames":["WriterPolicy"]},
|
||||
{"name":"uploadlister","credentials":[{"accessKey":"UPLISTERKEY","secretKey":"uplistersecret00000000000000001"}],"policyNames":["UploadsPolicy"]},
|
||||
{"name":"getonly","credentials":[{"accessKey":"GETONLYKEY","secretKey":"getonlysecret0000000000000000001"}],"policyNames":["GetOnlyPolicy"]}
|
||||
],
|
||||
"policies":[
|
||||
{"name":"WriterPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::cache/*\"]}]}"},
|
||||
{"name":"UploadsPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::cache\"]}]}"},
|
||||
{"name":"GetOnlyPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::cache/*\"]}]}"}
|
||||
]
|
||||
}`
|
||||
tmpFile, err := os.CreateTemp("", "s3-config-*.json")
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(tmpFile.Name())
|
||||
_, err = tmpFile.Write([]byte(configContent))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, tmpFile.Close())
|
||||
|
||||
iam := NewIdentityAccessManagementWithStore(&S3ApiServerOption{Config: tmpFile.Name()}, nil, "memory")
|
||||
require.True(t, iam.isEnabled(), "Auth should be enabled")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
access string
|
||||
secret string
|
||||
object string
|
||||
query string
|
||||
action Action
|
||||
want s3err.ErrorCode
|
||||
}{
|
||||
{"writer put object", "WRITERKEY", "writersecret000000000000000000001", "key", "", s3_constants.ACTION_WRITE, s3err.ErrNone},
|
||||
{"writer put versioning", "WRITERKEY", "writersecret000000000000000000001", "", "versioning", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"writer put versioning with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "versioning&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"writer put lifecycle with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "lifecycle&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"writer list with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "list-type=2&prefix=x", s3_constants.ACTION_LIST, s3err.ErrNone},
|
||||
{"policywriter put object", "POLICYKEY", "policysecret00000000000000000001", "key", "", s3_constants.ACTION_WRITE, s3err.ErrNone},
|
||||
{"policywriter put versioning with prefix", "POLICYKEY", "policysecret00000000000000000001", "", "versioning&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"uploadreader lists uploads under prefix", "UPREADERKEY", "upreadersecret00000000000000001", "", "uploads&prefix=uploads/foo", s3_constants.ACTION_READ, s3err.ErrNone},
|
||||
{"uploadreader cannot list outside prefix", "UPREADERKEY", "upreadersecret00000000000000001", "", "uploads&prefix=other/", s3_constants.ACTION_READ, s3err.ErrAccessDenied},
|
||||
{"uploadlister lists uploads", "UPLISTERKEY", "uplistersecret00000000000000001", "", "uploads&prefix=x", s3_constants.ACTION_READ, s3err.ErrNone},
|
||||
{"getonly cannot list uploads", "GETONLYKEY", "getonlysecret0000000000000000001", "", "uploads&prefix=x", s3_constants.ACTION_READ, s3err.ErrAccessDenied},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
url := "http://localhost:8333/cache"
|
||||
if tc.object != "" {
|
||||
url += "/" + tc.object
|
||||
}
|
||||
if tc.query != "" {
|
||||
url += "?" + tc.query
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPut, url, nil)
|
||||
if tc.action == s3_constants.ACTION_LIST || tc.action == s3_constants.ACTION_READ {
|
||||
r.Method = http.MethodGet
|
||||
}
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "cache", "object": tc.object})
|
||||
require.NoError(t, signRawHTTPRequest(context.Background(), r, tc.access, tc.secret, "us-east-1"))
|
||||
|
||||
_, errCode := iam.authRequest(r, tc.action)
|
||||
assert.Equal(t, tc.want, errCode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The admin explicit-deny path resolves the same action and resource the
|
||||
// policy engine sees, so a promoted prefix must not hide a listing variant:
|
||||
// ?uploads resolves s3:ListBucketMultipartUploads on the bucket ARN, and
|
||||
// ?versions resolves s3:ListBucketVersions, both at bucket level.
|
||||
func TestResolveS3AuthTarget_BucketListings(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
url string
|
||||
action Action
|
||||
object string
|
||||
wantAction string
|
||||
wantResource string
|
||||
}{
|
||||
{"uploads listing keeps its action", "/cache?uploads&prefix=uploads/", s3_constants.ACTION_READ, "uploads/",
|
||||
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS, "arn:aws:s3:::cache"},
|
||||
{"versions listing keeps its action", "/cache?versions&prefix=a/", s3_constants.ACTION_LIST, "a/",
|
||||
s3_constants.S3_ACTION_LIST_BUCKET_VERSIONS, "arn:aws:s3:::cache"},
|
||||
{"plain list keeps its action", "/cache?list-type=2&prefix=a/", s3_constants.ACTION_LIST, "a/",
|
||||
s3_constants.S3_ACTION_LIST_BUCKET, "arn:aws:s3:::cache"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodGet, tt.url, nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "cache"})
|
||||
action, resource := resolveS3AuthTarget(tt.action, "cache", tt.object, r)
|
||||
assert.Equal(t, tt.wantAction, action)
|
||||
assert.Equal(t, tt.wantResource, resource)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1388,15 +1388,7 @@ func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListP
|
||||
StorageClass: aws.String("STANDARD"),
|
||||
}
|
||||
|
||||
// part files are "%04d_<uuid>.part" (legacy "%04d.part"). '_' sorts after
|
||||
// '.', so an exclusive start at "%04d.part" still returns the marker part
|
||||
// and a page of max-parts=1 never advances. The next part number sorts
|
||||
// past both name shapes of the marker part.
|
||||
if *input.PartNumberMarker >= math.MaxInt64 {
|
||||
output.IsTruncated = aws.Bool(false)
|
||||
return output, s3err.ErrNone
|
||||
}
|
||||
entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d", *input.PartNumberMarker+1), true, uint32(*input.MaxParts))
|
||||
entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d%s", *input.PartNumberMarker, multipartExt), false, uint32(*input.MaxParts))
|
||||
if err != nil {
|
||||
// A store that reports the missing upload directory as not-found means
|
||||
// the upload is gone (completed or aborted), not a store error.
|
||||
@@ -1419,10 +1411,6 @@ func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListP
|
||||
glog.Errorf("listObjectParts %s %s parse %s: %v", *input.Bucket, *input.UploadId, entry.Name, err)
|
||||
continue
|
||||
}
|
||||
// the marker is exclusive even if a store ignores startFrom
|
||||
if partNumber <= int(*input.PartNumberMarker) {
|
||||
continue
|
||||
}
|
||||
|
||||
partETag := getEtagFromEntry(entry)
|
||||
part := &s3.Part{
|
||||
@@ -1440,12 +1428,6 @@ func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListP
|
||||
}
|
||||
}
|
||||
|
||||
// a page that surfaced no parts has no next page to claim
|
||||
if len(output.Part) == 0 {
|
||||
output.IsTruncated = aws.Bool(false)
|
||||
output.NextPartNumberMarker = nil
|
||||
}
|
||||
|
||||
glog.V(2).Infof("listObjectParts: Returning %d parts for uploadId=%s", len(output.Part), *input.UploadId)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -112,152 +106,6 @@ func TestEvaluateIAMPolicies_ListBucketVersionsWithPrefix(t *testing.T) {
|
||||
"s3:ListBucketVersions must still resolve when listing with a prefix")
|
||||
}
|
||||
|
||||
// GET ?uploads routes under ACTION_READ, not ACTION_LIST, but it is a bucket
|
||||
// listing: a promoted prefix must not resolve it to s3:GetObject, and only
|
||||
// s3:ListBucketMultipartUploads on the bucket ARN may allow it.
|
||||
func TestEvaluateIAMPolicies_ListMultipartUploadsWithPrefix(t *testing.T) {
|
||||
const bucket = "test-bucket"
|
||||
|
||||
iam := &IdentityAccessManagement{}
|
||||
require.NoError(t, iam.PutPolicy("list-uploads", mustPolicy(t, map[string]any{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]any{{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:ListBucketMultipartUploads",
|
||||
"Resource": "arn:aws:s3:::" + bucket,
|
||||
}},
|
||||
})))
|
||||
require.NoError(t, iam.PutPolicy("get-object", mustPolicy(t, map[string]any{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]any{{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:GetObject",
|
||||
"Resource": "arn:aws:s3:::" + bucket + "/*",
|
||||
}},
|
||||
})))
|
||||
|
||||
uploadsReader := &Identity{
|
||||
Name: "dave",
|
||||
Account: &AccountAdmin,
|
||||
PolicyNames: []string{"list-uploads"},
|
||||
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
|
||||
}
|
||||
getReader := &Identity{
|
||||
Name: "erin",
|
||||
Account: &AccountAdmin,
|
||||
PolicyNames: []string{"get-object"},
|
||||
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
|
||||
}
|
||||
|
||||
r := httptest.NewRequest("GET", "/"+bucket+"?uploads&prefix=uploads/", nil)
|
||||
require.True(t, iam.evaluateIAMPolicies(r, uploadsReader, s3_constants.ACTION_READ, bucket, "uploads/"),
|
||||
"s3:ListBucketMultipartUploads on the bucket must allow the uploads listing")
|
||||
require.False(t, iam.evaluateIAMPolicies(r, getReader, s3_constants.ACTION_READ, bucket, "uploads/"),
|
||||
"s3:GetObject must not satisfy the uploads listing")
|
||||
}
|
||||
|
||||
// The IAM-integration authorizer must resolve the listing variant the same way
|
||||
// evaluateIAMPolicies does: a prefix promoted into the object argument is not
|
||||
// part of the request URL, so ?versions&prefix=... still resolves to
|
||||
// s3:ListBucketVersions and an s3:ListBucket grant must not cover it.
|
||||
func TestAuthorizeAction_ListVersionsWithPromotedPrefix(t *testing.T) {
|
||||
const bucket = "test-bucket"
|
||||
|
||||
ctx := context.Background()
|
||||
iamManager := integration.NewIAMManager()
|
||||
require.NoError(t, iamManager.Initialize(&integration.IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
|
||||
Roles: &integration.RoleStoreConfig{StoreType: "memory"},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListBucketOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:ListBucket"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket},
|
||||
Condition: map[string]map[string]interface{}{"StringLike": {"s3:prefix": "b/*"}},
|
||||
}},
|
||||
}))
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListVersionsOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:ListBucketVersions"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket},
|
||||
}},
|
||||
}))
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListUploadsOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:ListBucketMultipartUploads"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket},
|
||||
}},
|
||||
}))
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "GetObjectOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket + "/*"},
|
||||
}},
|
||||
}))
|
||||
|
||||
s3iam := NewS3IAMIntegration(iamManager, "localhost:8888")
|
||||
reader := &IAMIdentity{
|
||||
Name: "reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/reader",
|
||||
PolicyNames: []string{"ListBucketOnly"},
|
||||
}
|
||||
|
||||
versionsReq := httptest.NewRequest("GET", "/"+bucket+"?versions&prefix=b/", nil)
|
||||
// object carries the promoted prefix, matching authRequestWithAuthType
|
||||
require.Equal(t, s3err.ErrAccessDenied,
|
||||
s3iam.AuthorizeAction(ctx, reader, s3_constants.ACTION_LIST, bucket, "b/", versionsReq),
|
||||
"an s3:ListBucket grant must not cover ?versions listing")
|
||||
|
||||
listReq := httptest.NewRequest("GET", "/"+bucket+"?list-type=2&prefix=b/", nil)
|
||||
require.Equal(t, s3err.ErrNone,
|
||||
s3iam.AuthorizeAction(ctx, reader, s3_constants.ACTION_LIST, bucket, "b/", listReq),
|
||||
"s3:ListBucket with a matching s3:prefix still lists")
|
||||
|
||||
versionsReader := &IAMIdentity{
|
||||
Name: "versions-reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/versions-reader",
|
||||
PolicyNames: []string{"ListVersionsOnly"},
|
||||
}
|
||||
require.Equal(t, s3err.ErrNone,
|
||||
s3iam.AuthorizeAction(ctx, versionsReader, s3_constants.ACTION_LIST, bucket, "b/", versionsReq),
|
||||
"s3:ListBucketVersions allows the versions listing")
|
||||
|
||||
// GET ?uploads routes under ACTION_READ; a promoted prefix must still
|
||||
// resolve it to s3:ListBucketMultipartUploads, not s3:GetObject.
|
||||
uploadsReq := httptest.NewRequest("GET", "/"+bucket+"?uploads&prefix=b/", nil)
|
||||
uploadsReader := &IAMIdentity{
|
||||
Name: "uploads-reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/uploads-reader",
|
||||
PolicyNames: []string{"ListUploadsOnly"},
|
||||
}
|
||||
require.Equal(t, s3err.ErrNone,
|
||||
s3iam.AuthorizeAction(ctx, uploadsReader, s3_constants.ACTION_READ, bucket, "b/", uploadsReq),
|
||||
"s3:ListBucketMultipartUploads allows the uploads listing")
|
||||
getReader := &IAMIdentity{
|
||||
Name: "get-reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/get-reader",
|
||||
PolicyNames: []string{"GetObjectOnly"},
|
||||
}
|
||||
require.Equal(t, s3err.ErrAccessDenied,
|
||||
s3iam.AuthorizeAction(ctx, getReader, s3_constants.ACTION_READ, bucket, "b/", uploadsReq),
|
||||
"s3:GetObject must not satisfy the uploads listing")
|
||||
}
|
||||
|
||||
func mustPolicy(t *testing.T, doc map[string]any) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(doc)
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
package lance
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v5"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
// OAuthTokenResponse is the response for POST /oauth/token.
|
||||
type OAuthTokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
}
|
||||
|
||||
// OAuthErrorResponse is the error response for the OAuth endpoint.
|
||||
type OAuthErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Description string `json:"error_description,omitempty"`
|
||||
}
|
||||
|
||||
// LanceClaims are JWT claims for Lance catalog OAuth tokens.
|
||||
type LanceClaims struct {
|
||||
IdentityName string `json:"identity_name"`
|
||||
AccessKey string `json:"access_key"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
const defaultOauthTokenExpiry = 3600
|
||||
|
||||
// maxOauthTokenExpiry bounds the configured TTL so seconds-to-Duration
|
||||
// conversions cannot overflow into already-expired tokens.
|
||||
const maxOauthTokenExpiry = 365 * 24 * 3600
|
||||
|
||||
const grantTypeClientCredentials = "client_credentials"
|
||||
|
||||
// oauthExpirySeconds returns the OAuth token TTL. Lance clients hold a static
|
||||
// Authorization header and cannot refresh on 401, so deployments can raise
|
||||
// this to survive beyond the default hour.
|
||||
func oauthExpirySeconds() int {
|
||||
if v := os.Getenv("LANCE_OAUTH_TOKEN_EXPIRY"); v != "" {
|
||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil && n > 0 {
|
||||
if n > maxOauthTokenExpiry {
|
||||
return maxOauthTokenExpiry
|
||||
}
|
||||
return int(n)
|
||||
}
|
||||
}
|
||||
return defaultOauthTokenExpiry
|
||||
}
|
||||
|
||||
// handleOAuthTokens implements the OAuth2 client_credentials flow.
|
||||
// POST /oauth/token
|
||||
func (s *Server) handleOAuthTokens(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBody)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
writeOAuthError(w, http.StatusBadRequest, "invalid_request", "Could not parse form body")
|
||||
return
|
||||
}
|
||||
|
||||
// Reject credentials in query string to prevent leaking secrets into logs and caches.
|
||||
if r.URL.Query().Get("client_secret") != "" {
|
||||
writeOAuthError(w, http.StatusBadRequest, "invalid_request", "client_secret must not be sent in the URL")
|
||||
return
|
||||
}
|
||||
|
||||
if grantType := r.PostFormValue("grant_type"); grantType != grantTypeClientCredentials {
|
||||
writeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type",
|
||||
fmt.Sprintf("Unsupported grant_type: %s", grantType))
|
||||
return
|
||||
}
|
||||
|
||||
clientID := r.PostFormValue("client_id")
|
||||
clientSecret := r.PostFormValue("client_secret")
|
||||
|
||||
// Also support HTTP Basic auth per OAuth2 spec
|
||||
if clientID == "" && clientSecret == "" {
|
||||
var ok bool
|
||||
clientID, clientSecret, ok = r.BasicAuth()
|
||||
if !ok {
|
||||
writeInvalidClient(w, "Missing client credentials")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if clientID == "" || clientSecret == "" {
|
||||
writeInvalidClient(w, "Missing client_id or client_secret")
|
||||
return
|
||||
}
|
||||
|
||||
if s.credentialValidator == nil {
|
||||
writeOAuthError(w, http.StatusInternalServerError, "server_error", "Credential validation not configured")
|
||||
return
|
||||
}
|
||||
|
||||
identityName, _, err := s.credentialValidator.ValidateS3Credential(clientID, clientSecret)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Lance OAuth: credential validation failed for client_id=%s: %v", clientID, err)
|
||||
writeInvalidClient(w, "Invalid client credentials")
|
||||
return
|
||||
}
|
||||
|
||||
tokenString, err := mintToken(identityName, clientID, clientSecret, oauthExpirySeconds())
|
||||
if err != nil {
|
||||
glog.Errorf("Lance OAuth: failed to sign token: %v", err)
|
||||
writeOAuthError(w, http.StatusInternalServerError, "server_error", "Failed to generate token")
|
||||
return
|
||||
}
|
||||
|
||||
resp := OAuthTokenResponse{
|
||||
AccessToken: tokenString,
|
||||
TokenType: "bearer",
|
||||
ExpiresIn: oauthExpirySeconds(),
|
||||
Scope: r.PostFormValue("scope"),
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// mintToken issues a signed access token for the given identity and
|
||||
// credential, valid for ttlSeconds.
|
||||
func mintToken(identityName, accessKey, secret string, ttlSeconds int) (string, error) {
|
||||
signingKey := deriveSigningKey(accessKey, secret)
|
||||
now := time.Now()
|
||||
claims := LanceClaims{
|
||||
IdentityName: identityName,
|
||||
AccessKey: accessKey,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttlSeconds) * time.Second)),
|
||||
Issuer: "seaweedfs-lance",
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(signingKey)
|
||||
}
|
||||
|
||||
// authenticateBearer validates a Bearer token from the Authorization header.
|
||||
// Returns the identity name, identity object, and whether auth succeeded.
|
||||
func (s *Server) authenticateBearer(r *http.Request) (string, interface{}, bool) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth == "" {
|
||||
return "", nil, false
|
||||
}
|
||||
if !strings.HasPrefix(strings.ToLower(auth), "bearer ") {
|
||||
return "", nil, false
|
||||
}
|
||||
tokenString := strings.TrimSpace(auth[7:])
|
||||
if tokenString == "" {
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
if s.credentialValidator == nil {
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
// Parse the token without verification first to get the access key,
|
||||
// then look up the exact credential to verify the signature.
|
||||
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
|
||||
unverified := &LanceClaims{}
|
||||
_, _, err := parser.ParseUnverified(tokenString, unverified)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Lance OAuth: failed to parse token: %v", err)
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
if unverified.AccessKey == "" {
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
identityName, identity, secretKey, err := s.credentialValidator.GetCredentialByAccessKey(unverified.AccessKey)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Lance OAuth: failed to get credential for access key: %v", err)
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
signingKey := deriveSigningKey(unverified.AccessKey, secretKey)
|
||||
claims := &LanceClaims{}
|
||||
verified, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return signingKey, nil
|
||||
})
|
||||
if err != nil || !verified.Valid {
|
||||
glog.V(2).Infof("Lance OAuth: token verification failed: %v", err)
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
return identityName, identity, true
|
||||
}
|
||||
|
||||
// authenticateApiKey validates an x-api-key header carrying an S3 credential
|
||||
// as "access_key:secret_key". Unlike a Bearer token it does not expire, which
|
||||
// suits clients that hold static headers.
|
||||
func (s *Server) authenticateApiKey(apiKey string) (string, interface{}, bool) {
|
||||
if s.credentialValidator == nil {
|
||||
return "", nil, false
|
||||
}
|
||||
accessKey, secretKey, ok := strings.Cut(apiKey, ":")
|
||||
if !ok || accessKey == "" || secretKey == "" {
|
||||
return "", nil, false
|
||||
}
|
||||
identityName, identity, err := s.credentialValidator.ValidateS3Credential(accessKey, secretKey)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Lance x-api-key: credential validation failed: %v", err)
|
||||
return "", nil, false
|
||||
}
|
||||
return identityName, identity, true
|
||||
}
|
||||
|
||||
// deriveSigningKey derives a signing key from the access key and secret using HMAC-SHA256.
|
||||
// Including the access key prevents cross-credential token forgery when two
|
||||
// credentials happen to share the same secret.
|
||||
func deriveSigningKey(accessKey, secret string) []byte {
|
||||
h := hmac.New(sha256.New, []byte("seaweedfs-lance-oauth"))
|
||||
h.Write([]byte(accessKey))
|
||||
h.Write([]byte{0}) // null separator
|
||||
h.Write([]byte(secret))
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
// writeInvalidClient answers 401 with the Basic challenge RFC 6749 §5.2
|
||||
// requires, so a client knows which scheme to retry with.
|
||||
func writeInvalidClient(w http.ResponseWriter, description string) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="lance"`)
|
||||
writeOAuthError(w, http.StatusUnauthorized, "invalid_client", description)
|
||||
}
|
||||
|
||||
func writeOAuthError(w http.ResponseWriter, status int, errCode, description string) {
|
||||
resp := OAuthErrorResponse{
|
||||
Error: errCode,
|
||||
Description: description,
|
||||
}
|
||||
writeJSON(w, status, resp)
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
package lance
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
type mockCredentialValidator struct {
|
||||
credentials map[string]string // accessKey -> secretKey
|
||||
identities map[string]string // accessKey -> identityName
|
||||
}
|
||||
|
||||
func (m *mockCredentialValidator) ValidateS3Credential(accessKey, secretKey string) (string, interface{}, error) {
|
||||
expected, ok := m.credentials[accessKey]
|
||||
if !ok {
|
||||
return "", nil, fmt.Errorf("access key not found")
|
||||
}
|
||||
if expected != secretKey {
|
||||
return "", nil, fmt.Errorf("invalid secret key")
|
||||
}
|
||||
return m.identities[accessKey], nil, nil
|
||||
}
|
||||
|
||||
func (m *mockCredentialValidator) GetCredentialByAccessKey(accessKey string) (string, interface{}, string, error) {
|
||||
secret, ok := m.credentials[accessKey]
|
||||
if !ok {
|
||||
return "", nil, "", fmt.Errorf("access key not found")
|
||||
}
|
||||
return m.identities[accessKey], nil, secret, nil
|
||||
}
|
||||
|
||||
func newTestServerWithOAuth() *Server {
|
||||
return &Server{
|
||||
credentialValidator: &mockCredentialValidator{
|
||||
credentials: map[string]string{"AKID123": "secret456"},
|
||||
identities: map[string]string{"AKID123": "testuser"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type mockS3Authenticator struct {
|
||||
called bool
|
||||
errCode s3err.ErrorCode
|
||||
}
|
||||
|
||||
func (m *mockS3Authenticator) AuthenticateRequest(r *http.Request) (string, interface{}, s3err.ErrorCode) {
|
||||
m.called = true
|
||||
if m.errCode != s3err.ErrNone {
|
||||
return "", nil, m.errCode
|
||||
}
|
||||
return "s3user", nil, s3err.ErrNone
|
||||
}
|
||||
|
||||
func (m *mockS3Authenticator) DefaultAllow() bool { return false }
|
||||
|
||||
func mintTestToken(t *testing.T, accessKey, secret string, issuedAt, expiresAt time.Time) string {
|
||||
t.Helper()
|
||||
key := deriveSigningKey(accessKey, secret)
|
||||
claims := LanceClaims{
|
||||
IdentityName: "testuser",
|
||||
AccessKey: accessKey,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(issuedAt),
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
Issuer: "seaweedfs-lance",
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
signed, err := token.SignedString(key)
|
||||
if err != nil {
|
||||
t.Fatalf("sign token: %v", err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
|
||||
func TestHandleOAuthTokens_Success(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
|
||||
body := "grant_type=client_credentials&client_id=AKID123&client_secret=secret456"
|
||||
req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
s.handleOAuthTokens(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp OAuthTokenResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.TokenType != "bearer" {
|
||||
t.Errorf("expected token_type=bearer, got %s", resp.TokenType)
|
||||
}
|
||||
if resp.AccessToken == "" {
|
||||
t.Error("expected non-empty access_token")
|
||||
}
|
||||
if resp.ExpiresIn != oauthExpirySeconds() {
|
||||
t.Errorf("expected expires_in=%d, got %d", oauthExpirySeconds(), resp.ExpiresIn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleOAuthTokens_InvalidCredentials(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
|
||||
body := "grant_type=client_credentials&client_id=AKID123&client_secret=wrongsecret"
|
||||
req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
s.handleOAuthTokens(w, req)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if wa := w.Header().Get("WWW-Authenticate"); wa != `Basic realm="lance"` {
|
||||
t.Fatalf("WWW-Authenticate = %q, want Basic challenge", wa)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleOAuthTokens_OversizedBody(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
|
||||
body := "grant_type=client_credentials&client_id=" + strings.Repeat("x", maxRequestBody)
|
||||
req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
s.handleOAuthTokens(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleOAuthTokens_UnsupportedGrantType(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
|
||||
body := "grant_type=authorization_code&client_id=AKID123&client_secret=secret456"
|
||||
req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
s.handleOAuthTokens(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerTokenRoundTrip(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
|
||||
body := "grant_type=client_credentials&client_id=AKID123&client_secret=secret456"
|
||||
req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
s.handleOAuthTokens(w, req)
|
||||
|
||||
var resp OAuthTokenResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authReq := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
authReq.Header.Set("Authorization", "Bearer "+resp.AccessToken)
|
||||
|
||||
identityName, _, ok := s.authenticateBearer(authReq)
|
||||
if !ok {
|
||||
t.Fatal("expected Bearer auth to succeed")
|
||||
}
|
||||
if identityName != "testuser" {
|
||||
t.Errorf("expected identity 'testuser', got '%s'", identityName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerTokenInvalid(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer invalid-token")
|
||||
|
||||
_, _, ok := s.authenticateBearer(req)
|
||||
if ok {
|
||||
t.Error("expected Bearer auth to fail with invalid token")
|
||||
}
|
||||
}
|
||||
|
||||
// The issue-11430 reproduction: behind an auth-enabled gateway, a catalog
|
||||
// request with no signature is denied, but the same request carrying a Bearer
|
||||
// token minted from S3 credentials must pass.
|
||||
func TestAuthBearerRunsHandler(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
auth := &mockS3Authenticator{errCode: s3err.ErrAccessDenied}
|
||||
s.authenticator = auth
|
||||
now := time.Now()
|
||||
fresh := mintTestToken(t, "AKID123", "secret456", now, now.Add(time.Hour))
|
||||
|
||||
var gotIdentity string
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotIdentity = s3_constants.GetIdentityNameFromContext(r)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+fresh)
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("fresh Bearer: status = %d, want 200", rec.Code)
|
||||
}
|
||||
if auth.called {
|
||||
t.Fatalf("fresh Bearer should not need the S3 authenticator")
|
||||
}
|
||||
if gotIdentity != "testuser" {
|
||||
t.Fatalf("identity in context = %q, want testuser", gotIdentity)
|
||||
}
|
||||
}
|
||||
|
||||
// An expired or malformed Bearer token answers 401 rather than falling
|
||||
// through to the S3 authenticator, which would misread the header as SigV4.
|
||||
func TestAuthExpiredBearerReturns401(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
auth := &mockS3Authenticator{errCode: s3err.ErrAccessDenied}
|
||||
s.authenticator = auth
|
||||
now := time.Now()
|
||||
expired := mintTestToken(t, "AKID123", "secret456", now.Add(-2*time.Hour), now.Add(-1*time.Hour))
|
||||
|
||||
var handlerCalled bool
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
handlerCalled = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
for _, scheme := range []string{"Bearer", "bearer", "BEARER"} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
req.Header.Set("Authorization", scheme+" "+expired)
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("scheme %q: status = %d, want 401", scheme, rec.Code)
|
||||
}
|
||||
if wa := rec.Header().Get("WWW-Authenticate"); wa != "Bearer" {
|
||||
t.Fatalf("scheme %q: WWW-Authenticate = %q, want Bearer", scheme, wa)
|
||||
}
|
||||
}
|
||||
if auth.called {
|
||||
t.Fatalf("expired Bearer must not fall through to the S3 authenticator")
|
||||
}
|
||||
if handlerCalled {
|
||||
t.Fatalf("handler must not run for an expired token")
|
||||
}
|
||||
}
|
||||
|
||||
// x-api-key carries "access_key:secret_key" straight to the catalog, with no
|
||||
// token to mint or expire - the header form LanceDB documents for API keys.
|
||||
func TestAuthApiKeyRunsHandler(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
auth := &mockS3Authenticator{errCode: s3err.ErrAccessDenied}
|
||||
s.authenticator = auth
|
||||
|
||||
var gotIdentity string
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotIdentity = s3_constants.GetIdentityNameFromContext(r)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
req.Header.Set("x-api-key", "AKID123:secret456")
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("x-api-key: status = %d, want 200", rec.Code)
|
||||
}
|
||||
if gotIdentity != "testuser" {
|
||||
t.Fatalf("identity in context = %q, want testuser", gotIdentity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthApiKeyInvalid(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
auth := &mockS3Authenticator{errCode: s3err.ErrAccessDenied}
|
||||
s.authenticator = auth
|
||||
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
for _, key := range []string{"AKID123:wrongsecret", "AKID123", ":secret456", "unknown:key"} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
req.Header.Set("x-api-key", key)
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("x-api-key %q: status = %d, want 401", key, rec.Code)
|
||||
}
|
||||
}
|
||||
if auth.called {
|
||||
t.Fatalf("bad x-api-key must not fall through to the S3 authenticator")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthNoBearerStillUsesS3Authenticator(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
auth := &mockS3Authenticator{errCode: s3err.ErrNone}
|
||||
s.authenticator = auth
|
||||
|
||||
var handlerCalled bool
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
handlerCalled = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if !auth.called {
|
||||
t.Fatalf("request without Bearer header must use the S3 authenticator")
|
||||
}
|
||||
if rec.Code != http.StatusOK || !handlerCalled {
|
||||
t.Fatalf("status = %d, handler called = %v", rec.Code, handlerCalled)
|
||||
}
|
||||
}
|
||||
+10
-68
@@ -3,7 +3,6 @@ package lance
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
@@ -24,18 +23,6 @@ type S3Authenticator interface {
|
||||
DefaultAllow() bool
|
||||
}
|
||||
|
||||
// CredentialValidator validates S3 access key / secret key pairs
|
||||
// and provides credential lookup for OAuth token verification.
|
||||
type CredentialValidator interface {
|
||||
// ValidateS3Credential checks if the access key and secret key are valid.
|
||||
// Returns the identity name and identity object on success.
|
||||
ValidateS3Credential(accessKey, secretKey string) (identityName string, identity interface{}, err error)
|
||||
// GetCredentialByAccessKey looks up a credential by access key.
|
||||
// Returns the identity name, identity object, and secret key.
|
||||
// Used for verifying Bearer tokens signed with a specific credential.
|
||||
GetCredentialByAccessKey(accessKey string) (identityName string, identity interface{}, secretKey string, err error)
|
||||
}
|
||||
|
||||
// VendedCredentials are short-lived S3 credentials scoped to one table.
|
||||
type VendedCredentials struct {
|
||||
AccessKeyID string
|
||||
@@ -53,13 +40,12 @@ type CredentialVendor interface {
|
||||
|
||||
// Server implements the Lance Namespace REST spec.
|
||||
type Server struct {
|
||||
filerClient FilerClient
|
||||
tablesManager *s3tables.Manager
|
||||
authenticator S3Authenticator
|
||||
credentialValidator CredentialValidator
|
||||
credentialVendor CredentialVendor
|
||||
s3Endpoint string
|
||||
s3Region string
|
||||
filerClient FilerClient
|
||||
tablesManager *s3tables.Manager
|
||||
authenticator S3Authenticator
|
||||
credentialVendor CredentialVendor
|
||||
s3Endpoint string
|
||||
s3Region string
|
||||
}
|
||||
|
||||
// NewServer creates a Lance namespace server over the given filer.
|
||||
@@ -77,11 +63,6 @@ func NewServer(filerClient FilerClient, authenticator S3Authenticator) *Server {
|
||||
}
|
||||
}
|
||||
|
||||
// SetCredentialValidator sets the credential validator for OAuth token support.
|
||||
func (s *Server) SetCredentialValidator(cv CredentialValidator) {
|
||||
s.credentialValidator = cv
|
||||
}
|
||||
|
||||
// SetCredentialVendor enables storage_options credential vending for clients
|
||||
// that ask for it with vend_credentials.
|
||||
func (s *Server) SetCredentialVendor(vendor CredentialVendor) {
|
||||
@@ -106,9 +87,6 @@ func (s *Server) SetS3Region(region string) {
|
||||
func (s *Server) RegisterRoutes(router *mux.Router) {
|
||||
router.Use(loggingMiddleware)
|
||||
|
||||
// OAuth2 token endpoint - no auth needed (this IS the auth endpoint)
|
||||
router.HandleFunc("/oauth/token", s.handleOAuthTokens).Methods(http.MethodPost)
|
||||
|
||||
router.HandleFunc("/v1/namespace/{id}/create", s.Auth(s.handleCreateNamespace)).Methods(http.MethodPost)
|
||||
router.HandleFunc("/v1/namespace/{id}/list", s.Auth(s.handleListNamespaces)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/namespace/{id}/describe", s.Auth(s.handleDescribeNamespace)).Methods(http.MethodPost)
|
||||
@@ -146,7 +124,7 @@ func (s *Server) RegisterRoutes(router *mux.Router) {
|
||||
}
|
||||
|
||||
router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
glog.V(2).Infof("lance: no route for %s %s", r.Method, r.URL.EscapedPath())
|
||||
glog.V(2).Infof("lance: no route for %s %s", r.Method, r.RequestURI)
|
||||
writeError(w, r, http.StatusNotFound, codeUnsupported, "no such operation")
|
||||
})
|
||||
|
||||
@@ -160,52 +138,16 @@ func (s *Server) handleUnsupported(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
glog.V(2).Infof("lance request: %s %s from %s", r.Method, r.URL.EscapedPath(), r.RemoteAddr)
|
||||
glog.V(2).Infof("lance request: %s %s from %s", r.Method, r.RequestURI, r.RemoteAddr)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Auth authenticates the caller and puts the identity in the request context.
|
||||
// Lance clients authenticate the catalog with a Bearer token or an x-api-key
|
||||
// header; the S3 authenticator stays for callers that can SigV4-sign.
|
||||
// The Lance spec maps identity onto the same headers the S3 authenticator
|
||||
// already understands, so SigV4 and bearer tokens both keep working.
|
||||
func (s *Server) Auth(handler http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// A request carrying a Bearer token is a Lance REST client. An invalid
|
||||
// or expired token gets 401 immediately; falling through to the S3
|
||||
// authenticator would parse the header as SigV4 and fail with a
|
||||
// different error that clients cannot act on.
|
||||
// The auth scheme is case-insensitive (RFC 7235).
|
||||
if strings.HasPrefix(strings.ToLower(r.Header.Get("Authorization")), "bearer ") {
|
||||
if identityName, identity, ok := s.authenticateBearer(r); ok {
|
||||
ctx := r.Context()
|
||||
ctx = s3_constants.SetIdentityNameInContext(ctx, identityName)
|
||||
if identity != nil {
|
||||
ctx = s3_constants.SetIdentityInContext(ctx, identity)
|
||||
}
|
||||
r = r.WithContext(ctx)
|
||||
handler(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
writeError(w, r, http.StatusUnauthorized, codeUnauthenticated, "Bearer token is invalid or expired")
|
||||
return
|
||||
}
|
||||
|
||||
if apiKey := r.Header.Get("x-api-key"); apiKey != "" {
|
||||
if identityName, identity, ok := s.authenticateApiKey(apiKey); ok {
|
||||
ctx := r.Context()
|
||||
ctx = s3_constants.SetIdentityNameInContext(ctx, identityName)
|
||||
if identity != nil {
|
||||
ctx = s3_constants.SetIdentityInContext(ctx, identity)
|
||||
}
|
||||
r = r.WithContext(ctx)
|
||||
handler(w, r)
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusUnauthorized, codeUnauthenticated, "invalid x-api-key")
|
||||
return
|
||||
}
|
||||
|
||||
if s.authenticator == nil {
|
||||
writeError(w, r, http.StatusUnauthorized, codeUnauthenticated, "authentication required")
|
||||
return
|
||||
|
||||
@@ -33,22 +33,6 @@ func ResolveS3Action(r *http.Request, baseAction string, bucket string, object s
|
||||
return baseAction
|
||||
}
|
||||
|
||||
// Dedicated object-lock actions already name the operation — a query
|
||||
// parameter must not re-map them. In particular the governance-bypass
|
||||
// check authorizes against a synthetic DELETE ?versionId request, whose
|
||||
// shape would otherwise resolve to s3:DeleteObjectVersion and satisfy
|
||||
// the bypass check with the delete-version permission alone.
|
||||
switch baseAction {
|
||||
case s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION,
|
||||
s3_constants.ACTION_GET_OBJECT_RETENTION,
|
||||
s3_constants.ACTION_PUT_OBJECT_RETENTION,
|
||||
s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD,
|
||||
s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD,
|
||||
s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG,
|
||||
s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG:
|
||||
return mapBaseActionToS3Format(baseAction)
|
||||
}
|
||||
|
||||
if r == nil || r.URL == nil {
|
||||
// No HTTP context available: fall back to coarse-grained mapping
|
||||
// This ensures consistent behavior and avoids returning empty strings
|
||||
|
||||
@@ -212,47 +212,6 @@ func TestResolveS3Action_Quota(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Dedicated object-lock actions already name the operation being authorized;
|
||||
// competing query parameters must not re-map them. Notably the synthetic
|
||||
// DELETE ?versionId request behind the governance-bypass check must stay
|
||||
// s3:BypassGovernanceRetention rather than resolving to s3:DeleteObjectVersion.
|
||||
func TestResolveS3ActionDedicatedObjectLockActions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
object string
|
||||
query string
|
||||
baseAction string
|
||||
want string
|
||||
}{
|
||||
{"bypass on versioned delete shape", http.MethodDelete, "key", "versionId=abc123",
|
||||
s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION, s3_constants.S3_ACTION_BYPASS_GOVERNANCE},
|
||||
{"bypass on batch delete shape", http.MethodPost, "", "delete",
|
||||
s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION, s3_constants.S3_ACTION_BYPASS_GOVERNANCE},
|
||||
{"get retention with versionId", http.MethodGet, "key", "retention&versionId=abc123",
|
||||
s3_constants.ACTION_GET_OBJECT_RETENTION, s3_constants.S3_ACTION_GET_OBJECT_RETENTION},
|
||||
{"put retention with versionId", http.MethodPut, "key", "retention&versionId=abc123",
|
||||
s3_constants.ACTION_PUT_OBJECT_RETENTION, s3_constants.S3_ACTION_PUT_OBJECT_RETENTION},
|
||||
{"get legal hold with versionId", http.MethodGet, "key", "legal-hold&versionId=abc123",
|
||||
s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD, s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD},
|
||||
{"put legal hold with versionId", http.MethodPut, "key", "legal-hold&versionId=abc123",
|
||||
s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD, s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD},
|
||||
{"get object-lock config", http.MethodGet, "", "object-lock&versioning",
|
||||
s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG, s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK},
|
||||
{"put object-lock config", http.MethodPut, "", "object-lock",
|
||||
s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG, s3_constants.S3_ACTION_PUT_BUCKET_OBJECT_LOCK},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
|
||||
if got := ResolveS3Action(r, tt.baseAction, "bucket", tt.object); got != tt.want {
|
||||
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A base action naming another service carries no S3 request shape, so a query
|
||||
// parameter on the request must not redirect it to an S3 action.
|
||||
func TestResolveS3ActionKeepsNonS3Service(t *testing.T) {
|
||||
|
||||
@@ -222,7 +222,7 @@ func (s3iam *S3IAMIntegration) AuthorizeAction(ctx context.Context, identity *IA
|
||||
// resource ARN stays at bucket level (matching AWS ListBucket semantics).
|
||||
// See https://github.com/seaweedfs/seaweedfs/issues/8969
|
||||
resourceObjectKey := objectKey
|
||||
if isBucketListingRequest(r, action) {
|
||||
if action == "List" {
|
||||
listPrefix := r.URL.Query().Get("prefix")
|
||||
if listPrefix != "" {
|
||||
requestContext["s3:prefix"] = listPrefix
|
||||
@@ -258,10 +258,8 @@ func (s3iam *S3IAMIntegration) AuthorizeAction(ctx context.Context, identity *IA
|
||||
}
|
||||
}
|
||||
|
||||
// Determine the specific S3 action based on the HTTP request details. The
|
||||
// prefix promoted into objectKey is not part of the URL; resolve against
|
||||
// the bucket-level object so ?versions and ?uploads keep their own action.
|
||||
specificAction := ResolveS3Action(r, string(action), bucket, resourceObjectKey)
|
||||
// Determine the specific S3 action based on the HTTP request details
|
||||
specificAction := ResolveS3Action(r, string(action), bucket, objectKey)
|
||||
|
||||
// Create action request
|
||||
actionRequest := &integration.ActionRequest{
|
||||
|
||||
@@ -1,343 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type fakeBucketDeleteFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
entriesByDir map[string][]*filer_pb.Entry
|
||||
deleteReq *filer_pb.DeleteEntryRequest
|
||||
}
|
||||
|
||||
func (f *fakeBucketDeleteFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
entries, ok := f.entriesByDir[req.Directory]
|
||||
if !ok {
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Name == req.Name {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: e}, nil
|
||||
}
|
||||
}
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeBucketDeleteFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
|
||||
entries := f.entriesByDir[req.Directory]
|
||||
if inPrefix := req.Prefix; inPrefix != "" && inPrefix != "/" {
|
||||
filtered := make([]*filer_pb.Entry, 0)
|
||||
for _, e := range entries {
|
||||
if strings.HasPrefix(e.Name, inPrefix) {
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
}
|
||||
entries = filtered
|
||||
}
|
||||
if req.StartFromFileName != "" {
|
||||
filtered := make([]*filer_pb.Entry, 0)
|
||||
for _, e := range entries {
|
||||
if e.Name > req.StartFromFileName || (req.InclusiveStartFrom && e.Name == req.StartFromFileName) {
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
}
|
||||
entries = filtered
|
||||
}
|
||||
if req.Limit > 0 && int(req.Limit) < len(entries) {
|
||||
entries = entries[:req.Limit]
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeBucketDeleteFiler) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) {
|
||||
f.deleteReq = req
|
||||
return &filer_pb.DeleteEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func newBucketDeleteTestServer(t *testing.T, f *fakeBucketDeleteFiler, allowDeleteBucketNotEmpty bool) *S3ApiServer {
|
||||
t.Helper()
|
||||
s3a := newFailoverTestServer(t, startFakeFiler(t, f))
|
||||
s3a.option.BucketsPath = "/buckets"
|
||||
s3a.option.AllowDeleteBucketNotEmpty = allowDeleteBucketNotEmpty
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.iam = &IdentityAccessManagement{}
|
||||
return s3a
|
||||
}
|
||||
|
||||
func TestBucketHasUserObjects_EmptyDirectories(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
entriesByDir map[string][]*filer_pb.Entry
|
||||
wantHasUser bool
|
||||
}{
|
||||
{
|
||||
name: "completely empty bucket",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "bucket with root file",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "file.txt", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "bucket with leftover empty directory from rm --recursive",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data": {},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "bucket with nested leftover empty directories",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: "2026", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data/2026": {},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "bucket with nested directory containing a file",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: "2026", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data/2026": {
|
||||
{Name: "report.pdf", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "bucket with explicit directory object (MIME set)",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "logs", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"}},
|
||||
},
|
||||
"/buckets/b/logs": {},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "bucket with only reserved folders (.uploads, *.versions)",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true},
|
||||
{Name: "oldfile.txt" + s3_constants.VersionsFolder, IsDirectory: true},
|
||||
},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "nested versions-named directories are internal",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "logs", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/logs": {
|
||||
{Name: "foo" + s3_constants.VersionsFolder, IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/logs/foo" + s3_constants.VersionsFolder: {
|
||||
{Name: "v1", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "nested uploads-named directories are internal",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/data/" + s3_constants.MultipartUploadsFolder: {
|
||||
{Name: "part-1", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "directory object with a reserved name counts",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: s3_constants.FolderMimeType}},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "file with a reserved name counts",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "dir", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/dir": {
|
||||
{Name: "data" + s3_constants.VersionsFolder, IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "file with backslash in name",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: `a\b`, IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &fakeBucketDeleteFiler{entriesByDir: tc.entriesByDir}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
|
||||
got, err := s3a.bucketHasUserObjects("b")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.wantHasUser, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketHasUserObjects_DeepEmptyChain(t *testing.T) {
|
||||
entriesByDir := map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {{Name: "d0", IsDirectory: true}},
|
||||
}
|
||||
dir := "/buckets/b/d0"
|
||||
for i := 1; i < 500; i++ {
|
||||
child := fmt.Sprintf("d%d", i)
|
||||
entriesByDir[dir] = []*filer_pb.Entry{{Name: child, IsDirectory: true}}
|
||||
dir = dir + "/" + child
|
||||
}
|
||||
entriesByDir[dir] = []*filer_pb.Entry{}
|
||||
|
||||
f := &fakeBucketDeleteFiler{entriesByDir: entriesByDir}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
|
||||
got, err := s3a.bucketHasUserObjects("b")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, got)
|
||||
}
|
||||
|
||||
func TestDeleteBucketHandler_EmptyDirectoriesAllowedWhenNotEmptyFalse(t *testing.T) {
|
||||
// A bucket that holds only an empty directory leftover from deleted objects
|
||||
// must succeed when AllowDeleteBucketNotEmpty is false.
|
||||
f := &fakeBucketDeleteFiler{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets": {
|
||||
{Name: "repro-bucket", IsDirectory: true},
|
||||
},
|
||||
"/buckets/repro-bucket": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/repro-bucket/data": {},
|
||||
},
|
||||
}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
s3a.bucketConfigCache.Set("repro-bucket", &BucketConfig{Name: "repro-bucket"})
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/repro-bucket", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "repro-bucket"})
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
s3a.DeleteBucketHandler(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusNoContent, rr.Code, "deleting bucket with only empty directory must succeed: %s", rr.Body.String())
|
||||
assert.NotNil(t, f.deleteReq)
|
||||
assert.Equal(t, "/buckets", f.deleteReq.Directory)
|
||||
assert.Equal(t, "repro-bucket", f.deleteReq.Name)
|
||||
assert.True(t, f.deleteReq.IsRecursive)
|
||||
}
|
||||
|
||||
func TestDeleteBucketHandler_RefusesBucketWithFilesWhenNotEmptyFalse(t *testing.T) {
|
||||
f := &fakeBucketDeleteFiler{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets": {
|
||||
{Name: "non-empty-bucket", IsDirectory: true},
|
||||
},
|
||||
"/buckets/non-empty-bucket": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/non-empty-bucket/data": {
|
||||
{Name: "hello.txt", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
s3a.bucketConfigCache.Set("non-empty-bucket", &BucketConfig{Name: "non-empty-bucket"})
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/non-empty-bucket", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "non-empty-bucket"})
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
s3a.DeleteBucketHandler(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusConflict, rr.Code)
|
||||
assert.Contains(t, rr.Body.String(), "<Code>BucketNotEmpty</Code>")
|
||||
assert.Nil(t, f.deleteReq, "delete request must not have been sent to filer")
|
||||
}
|
||||
|
||||
func TestDeleteBucketHandler_RefusesBucketWithDirectoryObjectWhenNotEmptyFalse(t *testing.T) {
|
||||
f := &fakeBucketDeleteFiler{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets": {
|
||||
{Name: "dir-obj-bucket", IsDirectory: true},
|
||||
},
|
||||
"/buckets/dir-obj-bucket": {
|
||||
{Name: "photos", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"}},
|
||||
},
|
||||
"/buckets/dir-obj-bucket/photos": {},
|
||||
},
|
||||
}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
s3a.bucketConfigCache.Set("dir-obj-bucket", &BucketConfig{Name: "dir-obj-bucket"})
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/dir-obj-bucket", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "dir-obj-bucket"})
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
s3a.DeleteBucketHandler(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusConflict, rr.Code)
|
||||
assert.Contains(t, rr.Body.String(), "<Code>BucketNotEmpty</Code>")
|
||||
assert.Nil(t, f.deleteReq, "delete request must not have been sent to filer")
|
||||
}
|
||||
@@ -34,12 +34,20 @@ import (
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// A bucket creation lists collections. The RPC carried no deadline, so a
|
||||
// transient failure anywhere down the chain -- gateway to filer, filer to
|
||||
// master, master to volume server -- held the S3 request open until the client
|
||||
// gave up on it. The budget is taken outside the filer failover walk, so it
|
||||
// covers the whole walk rather than granting each filer a fresh one.
|
||||
const collectionListTimeout = 15 * time.Second
|
||||
// A bucket creation lists collections, and a bucket deletion deletes one.
|
||||
// Neither RPC carried a deadline, so a transient failure anywhere down the chain
|
||||
// -- gateway to filer, filer to master, master to volume server -- held the S3
|
||||
// request open until the client gave up on it. Both budgets are taken outside
|
||||
// the filer failover walk, so they cover the whole walk rather than granting
|
||||
// each filer a fresh one.
|
||||
//
|
||||
// The delete is the shorter of the two: the filer has already spent its own
|
||||
// budget on this collection, under the bucket entry's delete inside s3a.rm, and
|
||||
// this call is the follow-up for when that did not happen.
|
||||
const (
|
||||
collectionListTimeout = 15 * time.Second
|
||||
collectionDeleteTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
func (s3a *S3ApiServer) ListBucketsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -471,8 +479,11 @@ func (s3a *S3ApiServer) DeleteBucketHandler(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
}
|
||||
|
||||
// The filer resolves and drops the bucket's collection inside the delete;
|
||||
// it keeps a shared one rather than risk another bucket's volumes.
|
||||
// Delete bucket directory first, then collection. This order ensures that if
|
||||
// collection deletion fails, the bucket directory is already gone, preventing
|
||||
// the "collection exists but bucket directory missing" inconsistency that blocks
|
||||
// bucket recreation. An orphaned collection is harmless and will be cleaned up
|
||||
// or reused when the bucket is recreated.
|
||||
err := s3a.rm(r.Context(), s3a.option.BucketsPath, bucket, false, true)
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -485,6 +496,36 @@ func (s3a *S3ApiServer) DeleteBucketHandler(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
}
|
||||
|
||||
// Bounded on a background context: the bucket directory is already gone, so
|
||||
// this follow-up must survive a client disconnect, but it must not outlive the
|
||||
// client by an unbounded amount either.
|
||||
deleteCtx, cancelDelete := context.WithTimeout(context.Background(), collectionDeleteTimeout)
|
||||
err = s3a.withFilerClient(deleteCtx, false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
deleteCollectionRequest := &filer_pb.DeleteCollectionRequest{
|
||||
Collection: s3a.getCollectionName(bucket),
|
||||
}
|
||||
|
||||
glog.V(1).Infof("delete collection: %v", deleteCollectionRequest)
|
||||
if _, err := client.DeleteCollection(deleteCtx, deleteCollectionRequest); err != nil {
|
||||
return fmt.Errorf("delete collection %s: %v", bucket, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
timedOut := deleteCtx.Err() != nil
|
||||
cancelDelete()
|
||||
|
||||
if err != nil {
|
||||
// Log but don't fail — the bucket directory is already removed, so the bucket
|
||||
// is effectively deleted. The orphaned collection will be cleaned up or reused.
|
||||
if timedOut {
|
||||
// Our own budget, not a refusal: the master carries on deleting once asked.
|
||||
glog.Warningf("DeleteBucketHandler: stopped waiting for the collection delete for bucket %s: %v", bucket, err)
|
||||
} else {
|
||||
glog.Errorf("DeleteBucketHandler: failed to delete collection for bucket %s: %v", bucket, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up bucket-related caches, locks, and metrics after successful deletion
|
||||
s3a.invalidateBucketConfigCache(bucket)
|
||||
stats_collect.DeleteBucketMetrics(bucket)
|
||||
@@ -503,56 +544,31 @@ func (s3a *S3ApiServer) DeleteBucketHandler(w http.ResponseWriter, r *http.Reque
|
||||
s3err.WriteEmptyResponse(w, r, http.StatusNoContent)
|
||||
}
|
||||
|
||||
// bucketHasUserObjects checks whether a bucket contains any user objects.
|
||||
// Empty directories left behind by deleted objects and internal folders
|
||||
// (.uploads, *.versions) do not count as user objects.
|
||||
// bucketHasUserObjects checks whether a bucket contains any non-special entries.
|
||||
// Special entries (.uploads, *.versions) are internal to S3 and don't count as user objects.
|
||||
func (s3a *S3ApiServer) bucketHasUserObjects(bucket string) (bool, error) {
|
||||
return s3a.dirHasUserObjects(s3a.option.BucketsPath + "/" + bucket)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) dirHasUserObjects(root string) (bool, error) {
|
||||
dirs := []string{root}
|
||||
for len(dirs) > 0 {
|
||||
dir := dirs[len(dirs)-1]
|
||||
dirs = dirs[:len(dirs)-1]
|
||||
startFrom := ""
|
||||
// Start with a small batch — most non-empty buckets have a real object
|
||||
// early; switch to larger batches to page through quickly.
|
||||
limit := uint32(10)
|
||||
for {
|
||||
entries, isLast, err := s3a.list(dir, "", startFrom, false, limit)
|
||||
if err != nil {
|
||||
if isFilerNotFound(err) {
|
||||
break // the directory was deleted between listing and walking it
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
startFrom = entry.Name
|
||||
if entry.Name == "" || entry.Name == "." || entry.Name == ".." || strings.Contains(entry.Name, "/") {
|
||||
continue
|
||||
}
|
||||
if !entry.IsDirectory {
|
||||
return true, nil
|
||||
}
|
||||
// An explicit directory object counts even under a reserved name.
|
||||
if entry.IsDirectoryKeyObject() {
|
||||
return true, nil
|
||||
}
|
||||
// Internal folders are skipped by object listing at every level,
|
||||
// so a directory with a reserved name never counts.
|
||||
if isReservedDirectoryName(entry.Name) {
|
||||
continue
|
||||
}
|
||||
dirs = append(dirs, dir+"/"+entry.Name)
|
||||
}
|
||||
if isLast || len(entries) == 0 {
|
||||
break
|
||||
}
|
||||
limit = 1000
|
||||
bucketPath := s3a.option.BucketsPath + "/" + bucket
|
||||
startFrom := ""
|
||||
// Start with a small batch — most non-empty buckets have a real object early.
|
||||
// If we only find special entries, switch to larger batches to page through quickly.
|
||||
limit := uint32(10)
|
||||
for {
|
||||
entries, isLast, err := s3a.list(bucketPath, "", startFrom, false, limit)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name != s3_constants.MultipartUploadsFolder &&
|
||||
!strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
|
||||
return true, nil
|
||||
}
|
||||
startFrom = entry.Name
|
||||
}
|
||||
if isLast {
|
||||
return false, nil
|
||||
}
|
||||
limit = 1000
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// hasObjectsWithActiveLocks checks if any objects in the bucket have active retention or legal hold
|
||||
@@ -893,24 +909,18 @@ func (s3a *S3ApiServer) AuthWithPublicRead(handler http.HandlerFunc, action Acti
|
||||
|
||||
glog.V(4).Infof("AuthWithPublicRead: bucket=%s, object=%s, authType=%v, isAnonymous=%v", bucket, object, authType, isAnonymous)
|
||||
|
||||
// For anonymous requests, check if bucket allows public read via bucket policies or ACLs
|
||||
// For anonymous requests, check if bucket allows public read via ACLs or bucket policies
|
||||
if isAnonymous {
|
||||
// Loading the bucket config on a cache miss also refreshes the
|
||||
// compiled policy, so a remotely deleted policy cannot leave a
|
||||
// stale verdict in the engine.
|
||||
// First check ACL-based public access
|
||||
isPublic := s3a.isBucketPublicRead(bucket)
|
||||
glog.V(4).Infof("AuthWithPublicRead: bucket=%s, isPublicACL=%v", bucket, isPublic)
|
||||
|
||||
// Object requests are re-evaluated inside Get/HeadObjectHandler
|
||||
// once the entry is fetched, where tag conditions like
|
||||
// s3:ExistingObjectTag/<key> can resolve correctly. Only
|
||||
// bucket-level requests (List, HeadBucket) rely on this check alone.
|
||||
if isPublic && object != "" {
|
||||
if isPublic {
|
||||
glog.V(3).Infof("AuthWithPublicRead: allowing anonymous access to public-read bucket %s (ACL)", bucket)
|
||||
handler(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Check bucket policy for anonymous access using the policy engine
|
||||
principal := "*" // Anonymous principal
|
||||
// Evaluate bucket policy (objectEntry nil - not yet fetched)
|
||||
allowed, evaluated, err := s3a.policyEngine.EvaluatePolicy(bucket, object, string(action), principal, r, nil, nil)
|
||||
@@ -934,13 +944,7 @@ func (s3a *S3ApiServer) AuthWithPublicRead(handler http.HandlerFunc, action Acti
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// No matching policy statement - fall back to the ACL grant
|
||||
if isPublic {
|
||||
glog.V(3).Infof("AuthWithPublicRead: allowing anonymous access to public-read bucket %s (ACL)", bucket)
|
||||
handler(w, r)
|
||||
return
|
||||
}
|
||||
// No matching policy statement - fall through to check ACLs and then IAM auth
|
||||
glog.V(3).Infof("AuthWithPublicRead: no bucket policy match for %s, checking ACLs", bucket)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -14,7 +13,6 @@ import (
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newMiscTestServer(t *testing.T, bucket string) *S3ApiServer {
|
||||
@@ -310,56 +308,3 @@ func TestUploadMissingBucketAutoCreateDisabled(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthWithPublicReadHonorsPolicyDeny(t *testing.T) {
|
||||
const bucket = "public-deny"
|
||||
s3a := newMiscTestServer(t, bucket)
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{Name: bucket, IsPublicRead: true})
|
||||
s3a.policyEngine = NewBucketPolicyEngine()
|
||||
|
||||
called := false
|
||||
handler := s3a.AuthWithPublicRead(func(w http.ResponseWriter, r *http.Request) { called = true }, s3_constants.ACTION_LIST)
|
||||
serve := func() *httptest.ResponseRecorder {
|
||||
called = false
|
||||
rr := httptest.NewRecorder()
|
||||
handler(rr, newBucketRequest(http.MethodGet, bucket, "list-type=2", ""))
|
||||
return rr
|
||||
}
|
||||
setPolicy := func(statements ...string) {
|
||||
doc := `{"Version":"2012-10-17","Statement":[` + strings.Join(statements, ",") + `]}`
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy(bucket, doc))
|
||||
}
|
||||
arn := fmt.Sprintf("arn:aws:s3:::%s", bucket)
|
||||
denyList := fmt.Sprintf(`{"Effect":"Deny","Principal":"*","Action":"s3:ListBucket","Resource":"%s"}`, arn)
|
||||
denyGet := fmt.Sprintf(`{"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"%s/*"}`, arn)
|
||||
allowList := fmt.Sprintf(`{"Effect":"Allow","Principal":"*","Action":"s3:ListBucket","Resource":"%s"}`, arn)
|
||||
|
||||
setPolicy(denyList)
|
||||
rr := serve()
|
||||
require.False(t, called, "anonymous ListObjectsV2 reached the handler despite an explicit ListBucket Deny")
|
||||
require.Equal(t, http.StatusForbidden, rr.Code)
|
||||
|
||||
setPolicy(denyGet)
|
||||
rr = serve()
|
||||
require.True(t, called, "an unrelated Deny must not block the ACL public-read grant")
|
||||
|
||||
setPolicy(denyList, allowList)
|
||||
rr = serve()
|
||||
require.False(t, called, "explicit Deny must beat a matching Allow")
|
||||
|
||||
setPolicy(allowList)
|
||||
rr = serve()
|
||||
require.True(t, called, "explicit Allow must still permit anonymous listing")
|
||||
|
||||
// Object requests defer to the handler's phase-2 recheck, which evaluates
|
||||
// tag conditions against the fetched entry — a tag-conditional Deny must
|
||||
// not terminate them here on a missing value.
|
||||
tagDeny := fmt.Sprintf(`{"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"%s/*","Condition":{"StringNotEquals":{"s3:ExistingObjectTag/classification":"public"}}}`, arn)
|
||||
setPolicy(tagDeny)
|
||||
called = false
|
||||
rr = httptest.NewRecorder()
|
||||
objectReq := newBucketRequest(http.MethodGet, bucket, "", "")
|
||||
objectReq = mux.SetURLVars(objectReq, map[string]string{"bucket": bucket, "object": "secret/x"})
|
||||
s3a.AuthWithPublicRead(func(w http.ResponseWriter, r *http.Request) { called = true }, s3_constants.ACTION_READ)(rr, objectReq)
|
||||
require.True(t, called, "anonymous object request on a public bucket must reach the handler's tag-aware recheck")
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
@@ -44,26 +42,10 @@ func (f *fakePartsFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream fi
|
||||
}
|
||||
// most stores list a missing directory as empty rather than erroring, which
|
||||
// is exactly the behavior under test
|
||||
parts := append([]*filer_pb.Entry(nil), f.parts...)
|
||||
sort.Slice(parts, func(i, j int) bool { return parts[i].Name < parts[j].Name })
|
||||
var sent uint32
|
||||
for _, entry := range parts {
|
||||
name := entry.Name
|
||||
if req.StartFromFileName != "" {
|
||||
if name < req.StartFromFileName {
|
||||
continue
|
||||
}
|
||||
if name == req.StartFromFileName && !req.InclusiveStartFrom {
|
||||
continue
|
||||
}
|
||||
}
|
||||
for _, entry := range f.parts {
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
|
||||
return err
|
||||
}
|
||||
sent++
|
||||
if req.Limit > 0 && sent >= req.Limit {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -168,113 +150,3 @@ func TestListPartsOpenUploadListsParts(t *testing.T) {
|
||||
t.Fatalf("part[0] = %d/%d, want 1/5", *output.Part[0].PartNumber, *output.Part[0].Size)
|
||||
}
|
||||
}
|
||||
|
||||
// S3 part-number-marker is exclusive. Part objects are stored as
|
||||
// NNNN_<uuid>.part, which sorts after the NNNN.part prefix, so a page of
|
||||
// max-parts=1 must advance to the next part number instead of repeating it.
|
||||
func TestListPartsPartNumberMarkerIsExclusive(t *testing.T) {
|
||||
s3a := newListPartsServer(t, &fakePartsFiler{
|
||||
uploadEntry: uploadRecordEntry("open-upload"),
|
||||
parts: []*filer_pb.Entry{
|
||||
partEntry("0001_11111111-1111-1111-1111-111111111111.part", 5),
|
||||
partEntry("0002_22222222-2222-2222-2222-222222222222.part", 5),
|
||||
partEntry("0003_33333333-3333-3333-3333-333333333333.part", 5),
|
||||
},
|
||||
})
|
||||
|
||||
input := listPartsInput("open-upload")
|
||||
input.PartNumberMarker = aws.Int64(1)
|
||||
input.MaxParts = aws.Int64(1)
|
||||
output, code := s3a.listObjectParts(input)
|
||||
if code != s3err.ErrNone {
|
||||
t.Fatalf("code = %v, want ErrNone", code)
|
||||
}
|
||||
if got := partNumbers(output); len(got) != 1 || got[0] != 2 {
|
||||
t.Fatalf("parts = %v, want [2]", got)
|
||||
}
|
||||
if output.IsTruncated == nil || !*output.IsTruncated {
|
||||
t.Fatal("IsTruncated = false, want true")
|
||||
}
|
||||
if output.NextPartNumberMarker == nil || *output.NextPartNumberMarker != 2 {
|
||||
t.Fatalf("NextPartNumberMarker = %v, want 2", output.NextPartNumberMarker)
|
||||
}
|
||||
|
||||
input.MaxParts = aws.Int64(1000)
|
||||
output, code = s3a.listObjectParts(input)
|
||||
if code != s3err.ErrNone {
|
||||
t.Fatalf("code = %v, want ErrNone", code)
|
||||
}
|
||||
if got := partNumbers(output); len(got) != 2 || got[0] != 2 || got[1] != 3 {
|
||||
t.Fatalf("parts = %v, want [2 3]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A client paging one part at a time must walk marker=0 through every part and
|
||||
// terminate: each page returns the next part and a NextPartNumberMarker that
|
||||
// the following page starts strictly after.
|
||||
func TestListPartsPaginationWithUUIDParts(t *testing.T) {
|
||||
s3a := newListPartsServer(t, &fakePartsFiler{
|
||||
uploadEntry: uploadRecordEntry("open-upload"),
|
||||
parts: []*filer_pb.Entry{
|
||||
partEntry("0001_c3a1e204-1111-1111-1111-111111111111.part", 5),
|
||||
partEntry("0002_d4b2f315-2222-2222-2222-222222222222.part", 5),
|
||||
partEntry("0003_e5c3a426-3333-3333-3333-333333333333.part", 5),
|
||||
},
|
||||
})
|
||||
|
||||
input := listPartsInput("open-upload")
|
||||
input.MaxParts = aws.Int64(1)
|
||||
|
||||
for page, want := range []int64{1, 2, 3} {
|
||||
output, code := s3a.listObjectParts(input)
|
||||
if code != s3err.ErrNone {
|
||||
t.Fatalf("page %d code = %v, want ErrNone", page+1, code)
|
||||
}
|
||||
if got := partNumbers(output); len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("page %d parts = %v, want [%d]", page+1, got, want)
|
||||
}
|
||||
if page < 2 {
|
||||
if output.IsTruncated == nil || !*output.IsTruncated {
|
||||
t.Fatalf("page %d IsTruncated = false, want true", page+1)
|
||||
}
|
||||
if output.NextPartNumberMarker == nil || *output.NextPartNumberMarker != want {
|
||||
t.Fatalf("page %d NextPartNumberMarker = %v, want %d", page+1, output.NextPartNumberMarker, want)
|
||||
}
|
||||
input.PartNumberMarker = output.NextPartNumberMarker
|
||||
} else {
|
||||
if output.IsTruncated == nil || *output.IsTruncated {
|
||||
t.Fatalf("page %d IsTruncated = true, want false", page+1)
|
||||
}
|
||||
if output.NextPartNumberMarker != nil {
|
||||
t.Fatalf("page %d NextPartNumberMarker = %v, want nil", page+1, output.NextPartNumberMarker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// a marker at the int64 ceiling cannot be incremented; answer an empty,
|
||||
// untruncated page instead of wrapping the start name negative
|
||||
input.PartNumberMarker = aws.Int64(math.MaxInt64)
|
||||
output, code := s3a.listObjectParts(input)
|
||||
if code != s3err.ErrNone {
|
||||
t.Fatalf("max marker code = %v, want ErrNone", code)
|
||||
}
|
||||
if len(output.Part) != 0 {
|
||||
t.Fatalf("max marker parts = %d, want 0", len(output.Part))
|
||||
}
|
||||
if output.IsTruncated == nil || *output.IsTruncated {
|
||||
t.Fatal("max marker IsTruncated = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func partNumbers(output *ListPartsResult) []int64 {
|
||||
if output == nil {
|
||||
return nil
|
||||
}
|
||||
nums := make([]int64, len(output.Part))
|
||||
for i, part := range output.Part {
|
||||
if part.PartNumber != nil {
|
||||
nums[i] = *part.PartNumber
|
||||
}
|
||||
}
|
||||
return nums
|
||||
}
|
||||
@@ -508,10 +508,6 @@ func (s3a *S3ApiServer) handleDirectoryObjectRequest(w http.ResponseWriter, r *h
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return true // Request was handled (with error)
|
||||
} else if dirEntry != nil {
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, string(s3_constants.ACTION_READ), dirEntry.Extended, handlerName); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return true // Request was handled (denied)
|
||||
}
|
||||
glog.V(2).Infof("%s: directory object %s/%s found, serving content", handlerName, bucket, object)
|
||||
s3a.serveDirectoryContent(w, r, dirEntry)
|
||||
return true // Request was handled successfully
|
||||
@@ -1103,7 +1099,6 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
|
||||
tStreamPrep := time.Now()
|
||||
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, offset, size)
|
||||
reader := filer.NewChunkReaderAtFromClient(ctx, s3a.readerCache, chunkViews, totalSize, filer.DefaultPrefetchCount)
|
||||
defer reader.ReleaseStream()
|
||||
streamPrepTime = time.Since(tStreamPrep)
|
||||
|
||||
// A cached chunk whose volume server is down, or whose needle was evicted and
|
||||
|
||||
@@ -813,19 +813,6 @@ func markerSortsBeforePrefix(prefix, marker string) bool {
|
||||
return !strings.HasPrefix(marker, prefix) && marker < prefix
|
||||
}
|
||||
|
||||
// markerSortsPastPrefix reports whether marker lies beyond the last key the
|
||||
// prefix can match. A marker that diverges from the prefix at a larger byte
|
||||
// is after every key under it, so the listing is empty no matter where the
|
||||
// walk would resume.
|
||||
func markerSortsPastPrefix(prefix, marker string) bool {
|
||||
prefix = strings.TrimLeft(prefix, "/")
|
||||
marker = strings.TrimLeft(marker, "/")
|
||||
if marker == "" || prefix == "" {
|
||||
return false
|
||||
}
|
||||
return !strings.HasPrefix(marker, prefix) && marker > prefix
|
||||
}
|
||||
|
||||
// the prefix and marker may be in different directories
|
||||
// normalizePrefixMarker ensures the prefix and marker both starts from the same directory.
|
||||
// prefixEndsOnDelimiter tells the walk that the prefix names one directory, whose own key
|
||||
@@ -925,13 +912,6 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
return // Don't set isTruncated here - let caller decide based on whether more entries exist
|
||||
}
|
||||
|
||||
// A marker past the prefix's range leaves nothing under the prefix to
|
||||
// resume at, and descending into the marker's own directory below would
|
||||
// drop the prefix filter entirely.
|
||||
if markerSortsPastPrefix(prefix, marker) {
|
||||
return
|
||||
}
|
||||
|
||||
if strings.Contains(marker, "/") {
|
||||
subDir, subMarker := toParentAndDescendants(marker)
|
||||
// println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
|
||||
|
||||
@@ -36,75 +36,6 @@ func Test_markerSortsBeforePrefix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A marker that sorts past the prefix leaves no key under the prefix to resume
|
||||
// at, so the listing is empty instead of continuing into later prefixes.
|
||||
func Test_markerSortsPastPrefix(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
prefix string
|
||||
marker string
|
||||
want bool
|
||||
}{
|
||||
{"marker is a later directory", "b/", "c/", true},
|
||||
{"marker is a later key without a slash", "b/", "c", true},
|
||||
{"marker shares the parent dir but sorts past", "data/a", "data/b", true},
|
||||
{"marker diverges after the prefix", "b/", "b0/x", true},
|
||||
{"leading slashes are ignored on both sides", "/b/", "/c/", true},
|
||||
{"empty marker is in range", "b/", "", false},
|
||||
{"empty prefix: every key is in scope", "", "c/", false},
|
||||
{"marker under the prefix resumes inside it", "b/", "b/allowed-1", false},
|
||||
{"marker equal to the prefix stands", "b/", "b/", false},
|
||||
{"partial name prefix: marker under the match set stands", "parent", "parentDir/data/0e", false},
|
||||
{"marker before the prefix is not past it", "b/", "a/", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, markerSortsPastPrefix(tt.prefix, tt.marker), "markerSortsPastPrefix(%q, %q)", tt.prefix, tt.marker)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestListWithMarkerPastPrefix walks the listing the way listFilerEntries does
|
||||
// for a start position past the requested prefix. normalizePrefixMarker hands
|
||||
// such a marker through at the bucket root, where the walk's marker descent
|
||||
// would otherwise drop the prefix filter and continue into a later prefix.
|
||||
func TestListWithMarkerPastPrefix(t *testing.T) {
|
||||
client := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {newDir("a"), newDir("b"), newDir("c")},
|
||||
"/buckets/test/b": {{Name: "allowed-1", Attributes: &filer_pb.FuseAttributes{}}},
|
||||
"/buckets/test/c": {{Name: "other-2", Attributes: &filer_pb.FuseAttributes{}}},
|
||||
"/buckets/test/c/z": {{Name: "deep", Attributes: &filer_pb.FuseAttributes{}}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
marker string
|
||||
want []string
|
||||
}{
|
||||
{"marker is a later directory", "c/", nil},
|
||||
{"marker is a deeper path in a later directory", "c/z", nil},
|
||||
{"marker is a later bare key", "c", nil},
|
||||
{"marker inside the prefix resumes normally", "b/", []string{"allowed-1"}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
requestDir, entryPrefix, entryMarker, prefixEndsOnDelimiter := normalizePrefixMarker("b/", tt.marker)
|
||||
dir := "/buckets/test"
|
||||
if requestDir != "" {
|
||||
dir += "/" + requestDir
|
||||
}
|
||||
seen := listedNames(t, client, listDirectoryRequest{
|
||||
dir: dir,
|
||||
prefix: entryPrefix,
|
||||
marker: entryMarker,
|
||||
bucket: "test",
|
||||
}, &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: prefixEndsOnDelimiter})
|
||||
assert.Equal(t, tt.want, seen)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A marker ending on the delimiter is trimmed to a shorter cutoff for the walk, which no
|
||||
// longer excludes the key the client named, so that key is skipped as it streams.
|
||||
func Test_excludedMarkerKey(t *testing.T) {
|
||||
|
||||
@@ -69,7 +69,7 @@ func (s3a *S3ApiServer) NewMultipartUploadHandler(w http.ResponseWriter, r *http
|
||||
}
|
||||
|
||||
// Validate object lock headers before processing
|
||||
if err := s3a.validateObjectLockHeaders(r, bucket, object, versioningEnabled); err != nil {
|
||||
if err := s3a.validateObjectLockHeaders(r, versioningEnabled); err != nil {
|
||||
glog.V(2).Infof("NewMultipartUploadHandler: object lock header validation failed for bucket %s, object %s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(err))
|
||||
return
|
||||
|
||||
@@ -86,7 +86,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
return
|
||||
}
|
||||
if identity != nil {
|
||||
r = r.WithContext(recordIdentityInContext(r, identity))
|
||||
r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), identity.Name))
|
||||
}
|
||||
|
||||
policyBytes, err := base64.StdEncoding.DecodeString(formValues.Get("Policy"))
|
||||
@@ -160,7 +160,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
if err := s3a.validateObjectLockHeaders(r, bucket, object, objectLockEnabled); err != nil {
|
||||
if err := s3a.validateObjectLockHeaders(r, objectLockEnabled); err != nil {
|
||||
glog.V(2).Infof("PostPolicyBucketHandler: object lock header validation failed for %s/%s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(err))
|
||||
return
|
||||
|
||||
@@ -45,7 +45,6 @@ var (
|
||||
ErrObjectLockModeRequiresDate = errors.New("object lock mode requires retention until date")
|
||||
ErrRetentionDateRequiresMode = errors.New("retention until date requires object lock mode")
|
||||
ErrGovernanceBypassVersioningRequired = errors.New("governance bypass header can only be used on buckets with Object Lock enabled")
|
||||
ErrObjectLockNotAuthorized = errors.New("object lock headers require the corresponding object lock permission")
|
||||
ErrInvalidObjectLockDuration = errors.New("object lock duration must be greater than 0 days")
|
||||
ErrObjectLockDurationExceeded = errors.New("object lock duration exceeds maximum allowed days")
|
||||
ErrObjectLockConfigurationMissingEnabled = errors.New("object lock configuration must specify ObjectLockEnabled")
|
||||
@@ -153,7 +152,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
if validationErr := s3a.validateObjectLockHeaders(r, bucket, object, objectLockEnabled); validationErr != nil {
|
||||
if validationErr := s3a.validateObjectLockHeaders(r, objectLockEnabled); validationErr != nil {
|
||||
glog.V(2).Infof("PutObjectHandler: object lock header validation failed for %s/%s: %v", bucket, object, validationErr)
|
||||
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(validationErr))
|
||||
return
|
||||
@@ -282,7 +281,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
// Validate object lock headers before processing
|
||||
if err := s3a.validateObjectLockHeaders(r, bucket, object, objectLockEnabled); err != nil {
|
||||
if err := s3a.validateObjectLockHeaders(r, objectLockEnabled); err != nil {
|
||||
glog.V(2).Infof("PutObjectHandler: object lock header validation failed for bucket %s, object %s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(err))
|
||||
return
|
||||
@@ -386,11 +385,7 @@ func (s3a *S3ApiServer) withObjectWriteLock(bucket, object string, preconditionF
|
||||
return fn()
|
||||
}
|
||||
|
||||
lock, err := s3a.newObjectWriteLock(bucket, object)
|
||||
if err != nil {
|
||||
glog.Warningf("withObjectWriteLock: %v", err)
|
||||
return s3err.ErrServiceUnavailable
|
||||
}
|
||||
lock := s3a.newObjectWriteLock(bucket, object)
|
||||
if lock == nil {
|
||||
if errCode := runPrecondition(); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
@@ -2130,29 +2125,9 @@ func (s3a *S3ApiServer) applyBucketDefaultRetention(bucket string, entry *filer_
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkObjectLockHeaderPermission reports whether the caller may set object
|
||||
// lock through PutObject-style request headers. On AWS these headers require
|
||||
// the dedicated s3:PutObjectRetention / s3:PutObjectLegalHold permissions;
|
||||
// s3:PutObject alone must not be enough, or any writer can pin data with
|
||||
// COMPLIANCE retention. Without auth there is nothing to check against.
|
||||
func (s3a *S3ApiServer) checkObjectLockHeaderPermission(r *http.Request, bucket, object string, action Action) bool {
|
||||
if s3a.iam == nil || !s3a.iam.isEnabled() {
|
||||
return true
|
||||
}
|
||||
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
|
||||
if identity == nil {
|
||||
var errCode s3err.ErrorCode
|
||||
identity, errCode, _ = s3a.iam.authenticateRequestInternal(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return s3a.iam.authorizeObjectKeyAction(r, identity, r.Method, action, bucket, s3_constants.NormalizeObjectKey(object), "") == s3err.ErrNone
|
||||
}
|
||||
|
||||
// validateObjectLockHeaders validates object lock headers in PUT requests
|
||||
// objectLockEnabled should be true only if the bucket has Object Lock configured
|
||||
func (s3a *S3ApiServer) validateObjectLockHeaders(r *http.Request, bucket, object string, objectLockEnabled bool) error {
|
||||
func (s3a *S3ApiServer) validateObjectLockHeaders(r *http.Request, objectLockEnabled bool) error {
|
||||
// Extract object lock headers from request
|
||||
mode := r.Header.Get(s3_constants.AmzObjectLockMode)
|
||||
retainUntilDateStr := r.Header.Get(s3_constants.AmzObjectLockRetainUntilDate)
|
||||
@@ -2214,17 +2189,6 @@ func (s3a *S3ApiServer) validateObjectLockHeaders(r *http.Request, bucket, objec
|
||||
return ErrGovernanceBypassVersioningRequired
|
||||
}
|
||||
|
||||
if mode != "" || retainUntilDateStr != "" {
|
||||
if !s3a.checkObjectLockHeaderPermission(r, bucket, object, s3_constants.ACTION_PUT_OBJECT_RETENTION) {
|
||||
return ErrObjectLockNotAuthorized
|
||||
}
|
||||
}
|
||||
if legalHold != "" {
|
||||
if !s3a.checkObjectLockHeaderPermission(r, bucket, object, s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD) {
|
||||
return ErrObjectLockNotAuthorized
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2264,8 +2228,6 @@ func mapValidationErrorToS3Error(err error) s3err.ErrorCode {
|
||||
// For governance bypass on non-versioned bucket, return InvalidRequest
|
||||
// This matches the test expectations
|
||||
return s3err.ErrInvalidRequest
|
||||
case errors.Is(err, ErrObjectLockNotAuthorized):
|
||||
return s3err.ErrAccessDenied
|
||||
case errors.Is(err, ErrMalformedXML):
|
||||
// For malformed XML in request body, return MalformedXML
|
||||
// This matches the test expectations for invalid retention mode and legal hold status
|
||||
|
||||
@@ -2,11 +2,9 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
@@ -57,86 +55,6 @@ func TestGovernanceBypassUsesDedicatedAuthorization(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The bypass check authorizes against a synthetic request shaped like the
|
||||
// real one; DELETE ?versionId used to re-resolve to s3:DeleteObjectVersion,
|
||||
// so the delete-version grant silently satisfied the bypass check.
|
||||
func TestGovernanceBypassDoesNotInheritDeleteObjectVersion(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
require.NoError(t, iam.PutPolicy("DeleteVersions",
|
||||
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:DeleteObject","s3:DeleteObjectVersion"],"Resource":"arn:aws:s3:::worm/*"}]}`))
|
||||
require.NoError(t, iam.PutPolicy("BypassGovernance",
|
||||
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:DeleteObject","s3:DeleteObjectVersion","s3:BypassGovernanceRetention"],"Resource":"arn:aws:s3:::worm/*"}]}`))
|
||||
s3a := &S3ApiServer{iam: iam}
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "http://localhost:8333/worm/doc.txt?versionId=abc123", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "worm", "object": "doc.txt"})
|
||||
|
||||
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), &Identity{
|
||||
Name: "deleter",
|
||||
PolicyNames: []string{"DeleteVersions"},
|
||||
Account: &Account{Id: "test-account"},
|
||||
}))
|
||||
if s3a.checkGovernanceBypassPermission(req, "worm", "/doc.txt") {
|
||||
t.Fatal("s3:DeleteObjectVersion alone satisfied the governance bypass check")
|
||||
}
|
||||
|
||||
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), &Identity{
|
||||
Name: "breaker",
|
||||
PolicyNames: []string{"BypassGovernance"},
|
||||
Account: &Account{Id: "test-account"},
|
||||
}))
|
||||
if !s3a.checkGovernanceBypassPermission(req, "worm", "/doc.txt") {
|
||||
t.Fatal("s3:BypassGovernanceRetention did not satisfy the governance bypass check")
|
||||
}
|
||||
}
|
||||
|
||||
// The object-lock request headers on PutObject/CreateMultipartUpload must be
|
||||
// authorized as s3:PutObjectRetention / s3:PutObjectLegalHold; s3:PutObject
|
||||
// alone used to set retention and legal hold on new versions.
|
||||
func TestObjectLockHeadersRequireDedicatedActions(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{isAuthEnabled: true}
|
||||
require.NoError(t, iam.PutPolicy("Writer",
|
||||
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject"],"Resource":"arn:aws:s3:::worm/*"}]}`))
|
||||
require.NoError(t, iam.PutPolicy("Locked",
|
||||
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:PutObjectRetention","s3:PutObjectLegalHold"],"Resource":"arn:aws:s3:::worm/*"}]}`))
|
||||
s3a := &S3ApiServer{iam: iam}
|
||||
|
||||
retainUntil := time.Now().Add(24 * time.Hour).Format(time.RFC3339)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
policy string
|
||||
headers map[string]string
|
||||
wantErr error
|
||||
}{
|
||||
{"writer sets retention", "Writer",
|
||||
map[string]string{s3_constants.AmzObjectLockMode: "COMPLIANCE", s3_constants.AmzObjectLockRetainUntilDate: retainUntil},
|
||||
ErrObjectLockNotAuthorized},
|
||||
{"writer sets legal hold", "Writer",
|
||||
map[string]string{s3_constants.AmzObjectLockLegalHold: s3_constants.LegalHoldOn},
|
||||
ErrObjectLockNotAuthorized},
|
||||
{"writer plain put", "Writer", nil, nil},
|
||||
{"locked principal sets both", "Locked",
|
||||
map[string]string{s3_constants.AmzObjectLockMode: "GOVERNANCE", s3_constants.AmzObjectLockRetainUntilDate: retainUntil, s3_constants.AmzObjectLockLegalHold: s3_constants.LegalHoldOn},
|
||||
nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPut, "http://localhost:8333/worm/doc.txt", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "worm", "object": "doc.txt"})
|
||||
for k, v := range tc.headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), &Identity{
|
||||
Name: "caller",
|
||||
PolicyNames: []string{tc.policy},
|
||||
Account: &Account{Id: "test-account"},
|
||||
}))
|
||||
if err := s3a.validateObjectLockHeaders(req, "worm", "doc.txt", true); !errors.Is(err, tc.wantErr) {
|
||||
t.Errorf("validateObjectLockHeaders() = %v, want %v", err, tc.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGovernanceBypassUsesBodyObjectKey(t *testing.T) {
|
||||
iam := newTestIAM()
|
||||
iam.identities[0].Actions = []Action{
|
||||
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user