mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea1d84477e | ||
|
|
5fdb061c99 | ||
|
|
2f641a63d6 | ||
|
|
80fd3635d2 | ||
|
|
7129e1178e | ||
|
|
3c1e8ca7a8 | ||
|
|
0f3ba98e11 | ||
|
|
80a26020d7 | ||
|
|
5389f61cef | ||
|
|
8ad2f29e3e | ||
|
|
c58bd0dfd3 | ||
|
|
f7680cf812 | ||
|
|
4299fdf578 | ||
|
|
3e9fc9e75b | ||
|
|
afce0a3dd3 | ||
|
|
83d44be0f3 | ||
|
|
975cec9228 | ||
|
|
f31a026b2a | ||
|
|
4914c14982 | ||
|
|
2f6c237238 | ||
|
|
df4995b894 | ||
|
|
b750853c42 | ||
|
|
317e756b9a | ||
|
|
5b79f51e3c | ||
|
|
635f69a821 | ||
|
|
11791fad6a | ||
|
|
56d2f05ccd | ||
|
|
8c1be63c92 | ||
|
|
bb9942c646 | ||
|
|
f0afcf904d | ||
|
|
c1ccbcda13 | ||
|
|
94a68fa9b9 | ||
|
|
b3a8701989 | ||
|
|
b9ad62fc16 |
No files matched your search
@@ -439,6 +439,117 @@ 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,6 +21,7 @@ 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
@@ -0,0 +1,344 @@
|
||||
# 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.
|
||||
+1009
-1016
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,6 +4555,7 @@ dependencies = [
|
||||
"aws-config",
|
||||
"aws-credential-types",
|
||||
"aws-sdk-s3",
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-types",
|
||||
"axum",
|
||||
"base64",
|
||||
|
||||
@@ -157,6 +157,9 @@ 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,6 +259,10 @@ 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 {
|
||||
}
|
||||
|
||||
+506
-103
@@ -178,12 +178,22 @@ pub struct Cli {
|
||||
pub min_free_space: String,
|
||||
|
||||
/// Inflight upload data wait timeout of volume servers.
|
||||
#[arg(long = "inflightUploadDataTimeout", default_value = "60s")]
|
||||
pub inflight_upload_data_timeout: String,
|
||||
/// 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,
|
||||
|
||||
/// Inflight download data wait timeout of volume servers.
|
||||
#[arg(long = "inflightDownloadDataTimeout", default_value = "60s")]
|
||||
pub inflight_download_data_timeout: String,
|
||||
/// 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,
|
||||
|
||||
/// <experimental> if true, prevents slow reads from blocking other requests,
|
||||
/// but large file read P99 latency will increase.
|
||||
@@ -471,99 +481,214 @@ fn find_options_arg(args: &[String]) -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// 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();
|
||||
/// 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 std::time::Duration::from_secs(60);
|
||||
return Err(invalid());
|
||||
}
|
||||
if let Some(secs) = s.strip_suffix('s')
|
||||
&& let Ok(v) = secs.parse::<u64>()
|
||||
{
|
||||
return std::time::Duration::from_secs(v);
|
||||
|
||||
// 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 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 total > MAX - 1 {
|
||||
return Err(invalid());
|
||||
}
|
||||
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)
|
||||
Ok(std::time::Duration::from_nanos(total))
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// 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> {
|
||||
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));
|
||||
}
|
||||
match parse_bytes(s) {
|
||||
Ok(bytes) if bytes > 100 => Ok(MinFreeSpace::Bytes(bytes)),
|
||||
_ => Err(format!("minFreeSpace is invalid: {:?}", s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let source = if !min_free_space.is_empty() {
|
||||
min_free_space
|
||||
} else {
|
||||
min_free_space_percent
|
||||
};
|
||||
|
||||
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()
|
||||
source.split(',').map(parse_min_free_space).collect()
|
||||
}
|
||||
|
||||
/// Parse comma-separated tag groups like "fast:ssd,archive" into per-folder tag vectors.
|
||||
@@ -657,7 +782,9 @@ 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);
|
||||
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}"),
|
||||
);
|
||||
if min_free_spaces.len() == 1 && folder_count > 1 {
|
||||
let v = min_free_spaces[0].clone();
|
||||
min_free_spaces.resize(folder_count, v);
|
||||
@@ -772,10 +899,6 @@ 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,
|
||||
@@ -807,8 +930,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,
|
||||
inflight_download_data_timeout,
|
||||
inflight_upload_data_timeout: cli.inflight_upload_data_timeout,
|
||||
inflight_download_data_timeout: cli.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,
|
||||
@@ -1260,25 +1383,224 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
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));
|
||||
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.
|
||||
assert_eq!(
|
||||
parse_duration("307445734561825861m"),
|
||||
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,
|
||||
std::time::Duration::from_secs(60)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_duration("5124095576030432h"),
|
||||
cli.inflight_download_data_timeout,
|
||||
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");
|
||||
let result = parse_min_free_spaces("", "1").unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
MinFreeSpace::Percent(v) => assert!((v - 1.0).abs() < f64::EPSILON),
|
||||
@@ -1288,7 +1610,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_parse_min_free_spaces_bytes() {
|
||||
let result = parse_min_free_spaces("10GiB", "");
|
||||
let result = parse_min_free_spaces("10GiB", "").unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
MinFreeSpace::Bytes(v) => assert_eq!(*v, 10 * 1024 * 1024 * 1024),
|
||||
@@ -1296,6 +1618,87 @@ 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,6 +4,7 @@
|
||||
|
||||
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};
|
||||
@@ -25,6 +26,23 @@ 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 {
|
||||
@@ -49,9 +67,7 @@ impl S3RemoteStorageClient {
|
||||
s3_config = s3_config.endpoint_url(endpoint);
|
||||
}
|
||||
|
||||
let client = Client::from_conf(s3_config.build());
|
||||
|
||||
S3RemoteStorageClient { client, conf }
|
||||
s3_config
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +91,14 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
req = req.range(format!("bytes={}-", offset));
|
||||
}
|
||||
|
||||
let resp = req.send().await.map_err(|e| {
|
||||
let msg = format!("{}", e);
|
||||
if msg.contains("NoSuchKey") || msg.contains("404") {
|
||||
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() => {
|
||||
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
|
||||
@@ -108,7 +125,9 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
.body(ByteStream::from(data.to_vec()))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| RemoteStorageError::Other(format!("s3 put object: {}", e)))?;
|
||||
.map_err(|e| {
|
||||
RemoteStorageError::Other(format!("s3 put object: {}", DisplayErrorContext(&e)))
|
||||
})?;
|
||||
|
||||
Ok(RemoteEntry {
|
||||
size: data.len() as i64,
|
||||
@@ -134,13 +153,18 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let msg = format!("{}", e);
|
||||
if msg.contains("404") || msg.contains("NotFound") {
|
||||
.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 => {
|
||||
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 {
|
||||
@@ -160,18 +184,17 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| RemoteStorageError::Other(format!("s3 delete object: {}", e)))?;
|
||||
.map_err(|e| {
|
||||
RemoteStorageError::Other(format!("s3 delete object: {}", DisplayErrorContext(&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: {}", e)))?;
|
||||
let resp = self.client.list_buckets().send().await.map_err(|e| {
|
||||
RemoteStorageError::Other(format!("s3 list buckets: {}", DisplayErrorContext(&e)))
|
||||
})?;
|
||||
|
||||
Ok(resp
|
||||
.buckets()
|
||||
@@ -184,3 +207,178 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
&self.conf
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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)]
|
||||
struct CannedResponse {
|
||||
status: u16,
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use std::sync::{Arc, OnceLock, RwLock};
|
||||
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::config::{BehaviorVersion, Credentials, Region};
|
||||
use aws_sdk_s3::error::DisplayErrorContext;
|
||||
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -119,7 +120,12 @@ impl S3TierBackend {
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to create multipart upload: {}", e))?;
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to create multipart upload: {}",
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
|
||||
let upload_id = create_resp
|
||||
.upload_id()
|
||||
@@ -183,7 +189,12 @@ impl S3TierBackend {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!("failed to upload part {} at offset {}: {}", pn, off, e)
|
||||
format!(
|
||||
"failed to upload part {} at offset {}: {}",
|
||||
pn,
|
||||
off,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
|
||||
let e_tag = upload_part_resp.e_tag().unwrap_or_default().to_string();
|
||||
@@ -236,7 +247,12 @@ impl S3TierBackend {
|
||||
.multipart_upload(completed_upload)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to complete multipart upload: {}", e))?;
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to complete multipart upload: {}",
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok::<(), String>(())
|
||||
}
|
||||
@@ -293,7 +309,7 @@ impl S3TierBackend {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to head object {}: {}", key, e))?;
|
||||
.map_err(|e| format!("failed to head object {}: {}", key, DisplayErrorContext(&e)))?;
|
||||
|
||||
let file_size = head_resp.content_length().unwrap_or(0) as u64;
|
||||
|
||||
@@ -356,7 +372,14 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to get object {} range {}: {}", key, range, e))?;
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
|
||||
let body = get_resp
|
||||
.body
|
||||
@@ -431,7 +454,14 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to get object {} range {}: {}", key, range, e))?;
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
|
||||
let body = resp
|
||||
.body
|
||||
@@ -449,7 +479,13 @@ impl S3TierBackend {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to delete object {}: {}", key, e))?;
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to delete object {}: {}",
|
||||
key,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -464,7 +500,13 @@ impl S3TierBackend {
|
||||
.key(&key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to delete object {}: {}", key, e))?;
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to delete object {}: {}",
|
||||
key,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -488,7 +530,14 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to get object {} range {}: {}", key, range, e))?;
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
|
||||
let body = resp
|
||||
.body
|
||||
@@ -555,18 +604,192 @@ 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, String> {
|
||||
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| 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, String>
|
||||
where
|
||||
F: Future<Output = Result<T, String>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
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())?
|
||||
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("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) -> String {
|
||||
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()
|
||||
};
|
||||
format!("tier I/O task panicked: {}", message)
|
||||
} else {
|
||||
format!("tier I/O task failed: {}", join_error)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
use tokio::runtime::Handle;
|
||||
|
||||
fn probe() -> Result<(tokio::runtime::Id, Option<String>), String> {
|
||||
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) }), Ok(7));
|
||||
assert_eq!(
|
||||
block_on_tier_future::<_, u32>(async { Err("nope".to_string()) }),
|
||||
Err("nope".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[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!(err.contains("boom 42"), "got: {err}");
|
||||
assert!(err.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.contains("static boom"), "got: {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())
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,6 +21,7 @@ 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::*;
|
||||
|
||||
@@ -167,6 +168,10 @@ 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 {
|
||||
@@ -187,7 +192,32 @@ 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,
|
||||
))));
|
||||
@@ -211,6 +241,9 @@ 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))
|
||||
@@ -1509,6 +1542,8 @@ 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);
|
||||
@@ -2661,8 +2696,15 @@ 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.clone(), fsync).await
|
||||
wq.submit(vid, n, fsync).await
|
||||
} else {
|
||||
let mut store = state.store.write().unwrap();
|
||||
store.write_volume_needle(vid, &mut n, fsync)
|
||||
@@ -2713,22 +2755,22 @@ pub async fn post_handler(
|
||||
let resp = match write_result {
|
||||
Ok((_offset, _size, is_unchanged)) => {
|
||||
if is_unchanged {
|
||||
let etag = format!("\"{}\"", n.etag());
|
||||
let etag = format!("\"{}\"", needle_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 n.has_name() {
|
||||
name: if needle_has_name {
|
||||
filename.clone()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
size: original_data_size, // H3: use original size, not compressed
|
||||
etag: n.etag(),
|
||||
etag: needle_etag.clone(),
|
||||
mime: mime_type.clone(),
|
||||
content_md5: original_content_md5.clone(),
|
||||
};
|
||||
let etag = n.etag();
|
||||
let etag = needle_etag;
|
||||
let etag_header = if etag.starts_with('"') {
|
||||
etag.clone()
|
||||
} else {
|
||||
@@ -4573,4 +4615,127 @@ mod tests {
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
fn streaming_test_state() -> Arc<VolumeServerState> {
|
||||
use crate::security::{Guard, SigningKey};
|
||||
use crate::server::volume_server::RuntimeMetricsConfig;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::store::Store;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32};
|
||||
|
||||
Arc::new(VolumeServerState {
|
||||
store: RwLock::new(Store::new(NeedleMapKind::InMemory)),
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1048,7 +1048,7 @@ fn build_heartbeat_with_ec_status(
|
||||
}
|
||||
|
||||
for vid in delete_vids {
|
||||
let _ = loc.delete_volume(vid, false, false);
|
||||
let _ = loc.delete_volume(vid, false, false, false);
|
||||
}
|
||||
|
||||
for vid in quarantine_vids {
|
||||
@@ -1849,6 +1849,8 @@ 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();
|
||||
@@ -1893,6 +1895,8 @@ 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();
|
||||
@@ -2194,6 +2198,8 @@ 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();
|
||||
|
||||
@@ -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;
|
||||
use crate::storage::erasure_coding::ec_volume::{EcVolume, is_usable_ecx_file};
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
use crate::storage::types::*;
|
||||
@@ -598,13 +598,14 @@ impl DiskLocation {
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
only_empty: bool,
|
||||
only_garbage: bool,
|
||||
keep_remote_data: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
if let Some(mut v) = self.volumes.remove(&vid) {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&v.collection, "volume"])
|
||||
.dec();
|
||||
v.destroy(only_empty, keep_remote_data)?;
|
||||
v.destroy(only_empty, only_garbage, keep_remote_data)?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(VolumeError::NotFound)
|
||||
@@ -625,7 +626,7 @@ impl DiskLocation {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&v.collection, "volume"])
|
||||
.dec();
|
||||
if let Err(e) = v.destroy(false, false) {
|
||||
if let Err(e) = v.destroy(false, false, false) {
|
||||
warn!(volume_id = vid.0, error = %e, "delete collection: failed to destroy volume");
|
||||
}
|
||||
}
|
||||
@@ -779,21 +780,17 @@ 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.
|
||||
/// 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`).
|
||||
pub fn has_ecx_file_on_disk(&self, collection: &str, vid: VolumeId) -> bool {
|
||||
let idx_base = volume_file_name(&self.idx_directory, collection, vid);
|
||||
let idx_path = format!("{}.ecx", idx_base);
|
||||
if let Ok(meta) = fs::metadata(&idx_path)
|
||||
&& !meta.is_dir()
|
||||
{
|
||||
if is_usable_ecx_file(&format!("{}.ecx", idx_base)) {
|
||||
return true;
|
||||
}
|
||||
if self.idx_directory != self.directory {
|
||||
let data_base = volume_file_name(&self.directory, collection, vid);
|
||||
let data_path = format!("{}.ecx", data_base);
|
||||
if let Ok(meta) = fs::metadata(&data_path)
|
||||
&& !meta.is_dir()
|
||||
{
|
||||
if is_usable_ecx_file(&format!("{}.ecx", data_base)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -805,6 +802,20 @@ 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
|
||||
@@ -1737,7 +1748,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(loc.volumes_len(), 2);
|
||||
|
||||
loc.delete_volume(VolumeId(1), false, false).unwrap();
|
||||
loc.delete_volume(VolumeId(1), false, false, false).unwrap();
|
||||
assert_eq!(loc.volumes_len(), 1);
|
||||
assert!(loc.find_volume(VolumeId(1)).is_none());
|
||||
}
|
||||
@@ -1790,6 +1801,34 @@ 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();
|
||||
@@ -1806,6 +1845,8 @@ 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)));
|
||||
@@ -1843,6 +1884,7 @@ 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();
|
||||
{
|
||||
@@ -1942,6 +1984,7 @@ 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();
|
||||
|
||||
|
||||
@@ -383,8 +383,26 @@ 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. Loads .ecx index and .ecj journal if present.
|
||||
/// Create a new EcVolume. Opens the .ecx index (required) and the .ecj journal.
|
||||
pub fn new(
|
||||
dir: &str,
|
||||
dir_idx: &str,
|
||||
@@ -467,27 +485,62 @@ 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.
|
||||
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!(
|
||||
//
|
||||
// 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!(
|
||||
volume_id = volume_id.0,
|
||||
"ecx file not found in idx dir, falling back to data dir"
|
||||
"ecx not local at {}, using {}",
|
||||
local_ecx,
|
||||
shared_ecx
|
||||
);
|
||||
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();
|
||||
false
|
||||
}
|
||||
}
|
||||
// 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
|
||||
@@ -1864,6 +1917,63 @@ 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,12 +21,26 @@ where
|
||||
let mut buf = vec![0u8; NEEDLE_MAP_ENTRY_SIZE * ROWS_TO_READ];
|
||||
|
||||
loop {
|
||||
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),
|
||||
};
|
||||
// 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 mut i = 0;
|
||||
while i + NEEDLE_MAP_ENTRY_SIZE <= count {
|
||||
@@ -34,6 +48,11 @@ 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(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +196,111 @@ 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(&[
|
||||
|
||||
@@ -13,7 +13,7 @@ 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;
|
||||
use crate::storage::erasure_coding::ec_volume::{EcVolume, is_usable_ecx_file};
|
||||
use crate::storage::needle::needle::Needle;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
@@ -395,11 +395,12 @@ 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, keep_remote_data);
|
||||
return loc.delete_volume(vid, only_empty, only_garbage, keep_remote_data);
|
||||
}
|
||||
}
|
||||
Err(VolumeError::NotFound)
|
||||
@@ -905,18 +906,88 @@ 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() {
|
||||
loc.mount_ec_shards(vid, collection, &[shard_id], source_disk_type)?;
|
||||
return Ok(());
|
||||
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)),
|
||||
}
|
||||
}
|
||||
Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("MountEcShards {}.{} not found on disk", vid, shard_id),
|
||||
)))
|
||||
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
|
||||
}
|
||||
|
||||
/// Unmount EC shards for a volume (batch).
|
||||
@@ -1198,12 +1269,24 @@ 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);
|
||||
if std::path::Path::new(&ecx_path).exists() {
|
||||
// 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) {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
@@ -1472,10 +1555,35 @@ fn load_vif_volume_info(path: &str) -> Result<VifVolumeInfo, VolumeError> {
|
||||
)))
|
||||
}
|
||||
|
||||
fn save_vif_volume_info(path: &str, info: &VifVolumeInfo) -> Result<(), 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),
|
||||
)));
|
||||
}
|
||||
let content = serde_json::to_string_pretty(info)
|
||||
.map_err(|e| VolumeError::Io(io::Error::other(e.to_string())))?;
|
||||
std::fs::write(path, content)?;
|
||||
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());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2263,6 +2371,8 @@ 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();
|
||||
@@ -2553,6 +2663,14 @@ 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();
|
||||
@@ -2628,6 +2746,14 @@ 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();
|
||||
@@ -2661,12 +2787,14 @@ 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();
|
||||
@@ -2706,6 +2834,7 @@ 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();
|
||||
@@ -2717,6 +2846,7 @@ 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();
|
||||
@@ -2734,6 +2864,106 @@ 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
|
||||
@@ -2747,11 +2977,13 @@ 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,6 +131,12 @@ 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;
|
||||
};
|
||||
@@ -417,4 +423,33 @@ 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,6 +37,7 @@ 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)
|
||||
@@ -117,10 +118,9 @@ impl Store {
|
||||
);
|
||||
continue;
|
||||
};
|
||||
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();
|
||||
// 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);
|
||||
|
||||
if !use_local_idx && owner.location == loc_idx && owner.idx_dir == loc.idx_directory
|
||||
{
|
||||
@@ -422,6 +422,12 @@ 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;
|
||||
};
|
||||
@@ -639,6 +645,34 @@ 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
|
||||
@@ -971,6 +1005,56 @@ 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
|
||||
|
||||
@@ -63,6 +63,9 @@ pub enum VolumeError {
|
||||
#[error("volume is read-only")]
|
||||
ReadOnly,
|
||||
|
||||
#[error("volume is unavailable: {0}")]
|
||||
Unavailable(String),
|
||||
|
||||
#[error("volume size limit exceeded: current {current}, limit {limit}")]
|
||||
SizeLimitExceeded { current: u64, limit: u64 },
|
||||
|
||||
@@ -603,6 +606,9 @@ pub struct NeedleStreamInfo {
|
||||
/// streaming, the needle's disk offset must be re-read from the needle map because
|
||||
/// compaction may have moved the needle to a different location.
|
||||
pub compaction_revision: u16,
|
||||
/// Checksum stored in the needle tail, verified once the last chunk has
|
||||
/// been read — before that frame is emitted.
|
||||
pub checksum: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -667,6 +673,8 @@ pub struct Volume {
|
||||
fail_fsync_for_test: bool,
|
||||
#[cfg(test)]
|
||||
fail_idx_sync_for_test: bool,
|
||||
#[cfg(test)]
|
||||
fail_truncate_for_test: bool,
|
||||
needle_map_kind: NeedleMapKind,
|
||||
data_file_access_control: Arc<DataFileAccessControl>,
|
||||
|
||||
@@ -675,6 +683,11 @@ pub struct Volume {
|
||||
no_write_or_delete: bool,
|
||||
no_write_can_delete: bool,
|
||||
|
||||
/// Set when a failed recovery leaves the .dat/index pair unverified: all
|
||||
/// I/O is refused and a `.unavailable` marker keeps the volume quarantined
|
||||
/// across restarts. Mirrors Go's ioUnavailable.
|
||||
io_unavailable: Option<String>,
|
||||
|
||||
/// Shared flag from the parent DiskLocation indicating low disk space.
|
||||
/// Matches Go's `v.location.isDiskSpaceLow` checked in `IsReadOnly()`.
|
||||
pub location_disk_space_low: Arc<AtomicBool>,
|
||||
@@ -757,6 +770,8 @@ impl Volume {
|
||||
fail_fsync_for_test: false,
|
||||
#[cfg(test)]
|
||||
fail_idx_sync_for_test: false,
|
||||
#[cfg(test)]
|
||||
fail_truncate_for_test: false,
|
||||
nm: None,
|
||||
needle_map_kind,
|
||||
data_file_access_control: Arc::new(DataFileAccessControl::default()),
|
||||
@@ -767,6 +782,7 @@ impl Volume {
|
||||
},
|
||||
no_write_or_delete: false,
|
||||
no_write_can_delete: false,
|
||||
io_unavailable: None,
|
||||
location_disk_space_low: Arc::new(AtomicBool::new(false)),
|
||||
last_modified_ts_seconds: 0,
|
||||
last_append_at_ns: 0,
|
||||
@@ -798,12 +814,15 @@ impl Volume {
|
||||
fail_fsync_for_test: false,
|
||||
#[cfg(test)]
|
||||
fail_idx_sync_for_test: false,
|
||||
#[cfg(test)]
|
||||
fail_truncate_for_test: false,
|
||||
nm: None,
|
||||
needle_map_kind: NeedleMapKind::InMemory,
|
||||
data_file_access_control: Arc::new(DataFileAccessControl::default()),
|
||||
super_block: SuperBlock::default(),
|
||||
no_write_or_delete: false,
|
||||
no_write_can_delete: false,
|
||||
io_unavailable: None,
|
||||
location_disk_space_low: Arc::new(AtomicBool::new(false)),
|
||||
last_modified_ts_seconds: 0,
|
||||
last_append_at_ns: 0,
|
||||
@@ -1020,7 +1039,6 @@ impl Volume {
|
||||
// — no extra disk I/O. A violation marks the volume read-only
|
||||
// so vacuum doesn't silently drop reachable data based on a
|
||||
// corrupt .idx left over from a crashed batched write.
|
||||
// See issue #8928.
|
||||
if let Some(ref nm) = self.nm
|
||||
&& let Ok(dat_size) = self.current_dat_file_size()
|
||||
{
|
||||
@@ -1038,6 +1056,8 @@ impl Volume {
|
||||
}
|
||||
}
|
||||
|
||||
self.restore_unavailable();
|
||||
|
||||
// Match Go: if no .vif file existed, create one with version and bytes_offset
|
||||
if !has_volume_info_file {
|
||||
self.volume_info.version = self.super_block.version.0 as u32;
|
||||
@@ -1338,6 +1358,9 @@ impl Volume {
|
||||
/// remote-only tiered volumes whose `.dat` is no longer present locally.
|
||||
pub fn read_dat_slice(&self, offset: u64, size: usize) -> Result<Vec<u8>, VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
let dat_size = self.current_dat_file_size()?;
|
||||
if size == 0 || offset >= dat_size {
|
||||
return Ok(Vec::new());
|
||||
@@ -1425,6 +1448,9 @@ impl Volume {
|
||||
read_option: &mut ReadOption,
|
||||
) -> Result<i32, VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
let nm = self.nm_or_not_found()?;
|
||||
let nv = nm.get(n.id)?.ok_or(VolumeError::NotFound)?;
|
||||
|
||||
@@ -1487,6 +1513,9 @@ impl Volume {
|
||||
size: Size,
|
||||
) -> Result<(), VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
let mut read_option = ReadOption::default();
|
||||
self.read_needle_data_at_unlocked(n, offset, size, &mut read_option)
|
||||
}
|
||||
@@ -1540,6 +1569,9 @@ impl Volume {
|
||||
/// Read raw needle blob at a specific offset.
|
||||
pub fn read_needle_blob(&self, offset: i64, size: Size) -> Result<Vec<u8>, VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
self.read_needle_blob_unlocked(offset, size)
|
||||
}
|
||||
|
||||
@@ -1571,6 +1603,9 @@ impl Volume {
|
||||
size: Size,
|
||||
) -> Result<(), VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
self.read_needle_meta_at_unlocked(n, offset, size)
|
||||
}
|
||||
|
||||
@@ -1685,6 +1720,9 @@ impl Volume {
|
||||
read_deleted: bool,
|
||||
) -> Result<NeedleStreamInfo, VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
let nm = self.nm_or_not_found()?;
|
||||
let nv = nm.get(n.id)?.ok_or(VolumeError::NotFound)?;
|
||||
|
||||
@@ -1776,6 +1814,7 @@ impl Volume {
|
||||
volume_id: self.id,
|
||||
needle_id: n.id,
|
||||
compaction_revision: self.super_block.compaction_revision,
|
||||
checksum: n.checksum.0,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1829,6 +1868,9 @@ impl Volume {
|
||||
fsync: bool,
|
||||
) -> Result<(u64, Size, bool), VolumeError> {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
if self.is_read_only() {
|
||||
return Err(VolumeError::ReadOnly);
|
||||
}
|
||||
@@ -1886,6 +1928,18 @@ impl Volume {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take an unflushed append back off the .dat after its sync failed.
|
||||
fn truncate_dat(&self, len: u64) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if self.fail_truncate_for_test {
|
||||
return Err(io::Error::other("injected truncate failure"));
|
||||
}
|
||||
match self.dat_file.as_ref() {
|
||||
Some(dat_file) => dat_file.set_len(len),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn do_write_request(
|
||||
&mut self,
|
||||
n: &mut Needle,
|
||||
@@ -1951,22 +2005,14 @@ impl Volume {
|
||||
// and undoing it afterwards would double-count the volume's metrics.
|
||||
if fsync && let Err(e) = self.flush_dat() {
|
||||
self.check_read_write_error(Some(&e));
|
||||
let truncated = match self.dat_file.as_ref() {
|
||||
Some(dat_file) => dat_file.set_len(offset),
|
||||
None => Ok(()),
|
||||
};
|
||||
if let Err(te) = truncated {
|
||||
if let Err(te) = self.truncate_dat(offset) {
|
||||
// The rejected record is still on the end. A later append
|
||||
// would bury it mid-file, where the .dat tail check cannot
|
||||
// see it, so stop taking writes instead.
|
||||
self.no_write_or_delete = true;
|
||||
tracing::error!(
|
||||
"volume {}: failed to truncate back to {} after a failed fsync, \
|
||||
marking read only: {}",
|
||||
self.id.0,
|
||||
offset,
|
||||
te
|
||||
);
|
||||
// see it, so the volume fails closed instead.
|
||||
self.mark_io_unavailable(format!(
|
||||
"failed to truncate back to {} after a failed fsync: {}",
|
||||
offset, te
|
||||
));
|
||||
}
|
||||
return Err(VolumeError::Io(e));
|
||||
}
|
||||
@@ -2166,6 +2212,9 @@ impl Volume {
|
||||
/// Delete a needle from the volume.
|
||||
pub fn delete_needle(&mut self, n: &mut Needle) -> Result<Size, VolumeError> {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
if self.no_write_or_delete {
|
||||
return Err(VolumeError::ReadOnly);
|
||||
}
|
||||
@@ -2248,9 +2297,74 @@ impl Volume {
|
||||
pub fn is_read_only(&self) -> bool {
|
||||
self.no_write_or_delete
|
||||
|| self.no_write_can_delete
|
||||
|| self.io_unavailable.is_some()
|
||||
|| self.location_disk_space_low.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The reason the volume refuses all I/O, when a failed recovery left the
|
||||
/// .dat/index pair unverified. Mirrors Go's unavailableError.
|
||||
pub fn unavailable_error(&self) -> Option<VolumeError> {
|
||||
self.io_unavailable
|
||||
.as_ref()
|
||||
.map(|reason| VolumeError::Unavailable(reason.clone()))
|
||||
}
|
||||
|
||||
/// Fail closed after a recovery could not return the volume to a verified
|
||||
/// state: refuse all I/O, leave heartbeats out, and record the state so a
|
||||
/// reload stays unavailable until an operator verifies the volume.
|
||||
fn mark_io_unavailable(&mut self, reason: String) {
|
||||
self.no_write_or_delete = true;
|
||||
self.io_unavailable = Some(reason.clone());
|
||||
self.mark_io_quarantined();
|
||||
if let Err(e) = self.persist_unavailable(&reason) {
|
||||
warn!(
|
||||
volume_id = self.id.0,
|
||||
error = %e,
|
||||
"failed to persist unavailable marker"
|
||||
);
|
||||
}
|
||||
if let Err(e) = self.set_read_only_persist(false, true) {
|
||||
warn!(
|
||||
volume_id = self.id.0,
|
||||
error = %e,
|
||||
"failed to persist unavailable state"
|
||||
);
|
||||
}
|
||||
error!(
|
||||
volume_id = self.id.0,
|
||||
"volume entered unavailable state after failed recovery: {}", reason
|
||||
);
|
||||
}
|
||||
|
||||
fn persist_unavailable(&self, reason: &str) -> io::Result<()> {
|
||||
let marker = self.file_name(".unavailable");
|
||||
let mut f = OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&marker)?;
|
||||
f.write_all(reason.as_bytes())?;
|
||||
f.sync_all()?;
|
||||
drop(f);
|
||||
fsync_dir(&marker)
|
||||
}
|
||||
|
||||
/// Re-arm the state a `.unavailable` marker recorded. The marker is
|
||||
/// deleted manually once the .dat/index pair is verified.
|
||||
fn restore_unavailable(&mut self) {
|
||||
let Ok(reason) = fs::read_to_string(self.file_name(".unavailable")) else {
|
||||
return;
|
||||
};
|
||||
self.no_write_or_delete = true;
|
||||
self.io_unavailable = Some(reason.trim().to_string());
|
||||
self.mark_io_quarantined();
|
||||
warn!(
|
||||
volume_id = self.id.0,
|
||||
"volume is unavailable: {}",
|
||||
reason.trim()
|
||||
);
|
||||
}
|
||||
|
||||
pub fn is_no_write_or_delete(&self) -> bool {
|
||||
self.no_write_or_delete
|
||||
}
|
||||
@@ -2327,6 +2441,9 @@ impl Volume {
|
||||
/// Read all live needles from the volume (for ReadAllNeedles streaming RPC).
|
||||
pub fn read_all_needles(&self) -> Result<Vec<Needle>, VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
let nm = self.nm_or_not_found()?;
|
||||
let version = self.version();
|
||||
let dat_size = self.current_dat_file_size()? as i64;
|
||||
@@ -2410,7 +2527,7 @@ impl Volume {
|
||||
let version = self.version();
|
||||
|
||||
// The deeper-than-tail structural check (every (offset + actual size)
|
||||
// fits inside .dat — issue #8928) is now handled in load() via the
|
||||
// fits inside .dat) is now handled in load() via the
|
||||
// needle map's max_needle_end accumulator, so we don't pay for a
|
||||
// second linear scan of the .idx here.
|
||||
|
||||
@@ -2861,7 +2978,11 @@ impl Volume {
|
||||
"failed to read needle {} on volume {}: {}",
|
||||
needle_id.0, self.id.0, e
|
||||
));
|
||||
} else if size.is_deleted() && n.id != needle_id {
|
||||
} else if n.id != needle_id {
|
||||
// The data CRC does not cover the header: a damaged needle id
|
||||
// still reads clean while every live-needle lookup on this
|
||||
// replica keeps finding the index key here. (Go parity:
|
||||
// the check covers live needles too, not just tombstones.)
|
||||
broken.push(format!(
|
||||
"index key {} does not match needle's Id {} on volume {}",
|
||||
needle_id.0, n.id.0, self.id.0
|
||||
@@ -2894,6 +3015,9 @@ impl Volume {
|
||||
/// dropping its store guard. See `DatScanPlan` for why the offset, the
|
||||
/// handle and the end bound must come from the same guard.
|
||||
pub(crate) fn dat_scan_plan(&self, from_offset: u64) -> Result<DatScanPlan, VolumeError> {
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
let source = if self.dat_file.is_some() {
|
||||
// A fresh open, not `try_clone`: a duplicated handle shares the
|
||||
// file position, and on Windows `read_exact_at` goes through
|
||||
@@ -2991,6 +3115,9 @@ impl Volume {
|
||||
/// surviving until the next restart, then vanishing. Re-attach a writer
|
||||
/// here so writes persist again.
|
||||
pub fn set_writable(&mut self) -> Result<(), VolumeError> {
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
let was_no_write_or_delete = self.no_write_or_delete;
|
||||
let was_no_write_can_delete = self.no_write_can_delete;
|
||||
self.no_write_or_delete = false;
|
||||
@@ -3787,7 +3914,6 @@ impl Volume {
|
||||
// surfaces as a generic Io rather than UnexpectedEof) must
|
||||
// abort so an operator notices, rather than silently
|
||||
// compacting away data that might come back on retry.
|
||||
// See issue #8928.
|
||||
if !is_skippable_needle_read_error(&e) {
|
||||
return Err(VolumeError::Io(io::Error::other(format!(
|
||||
"cannot hydrate needle from file: {}",
|
||||
@@ -4306,8 +4432,19 @@ impl Volume {
|
||||
/// Destroy removes everything related to this volume. When keep_remote_data
|
||||
/// is true the cloud-tier object backing the volume is left intact — used
|
||||
/// by moves where another server is taking over the same .vif.
|
||||
pub fn destroy(&mut self, only_empty: bool, keep_remote_data: bool) -> Result<(), VolumeError> {
|
||||
if only_empty && self.file_count() > 0 {
|
||||
pub fn destroy(
|
||||
&mut self,
|
||||
only_empty: bool,
|
||||
only_garbage: bool,
|
||||
keep_remote_data: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
// Either enabled check may pass: a volume with no live data qualifies
|
||||
// whether it reads empty or as all garbage. Byte counters, not counts:
|
||||
// index rows and live tallies drift apart on reload.
|
||||
let empty_ok = only_empty && self.file_count() == 0;
|
||||
let garbage_ok =
|
||||
only_garbage && self.content_size() > 0 && self.deleted_size() >= self.content_size();
|
||||
if (only_empty || only_garbage) && !empty_ok && !garbage_ok {
|
||||
return Err(VolumeError::NotEmpty);
|
||||
}
|
||||
if self.is_compacting {
|
||||
@@ -4420,6 +4557,11 @@ impl Volume {
|
||||
self.fail_idx_sync_for_test = fail;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn fail_next_truncate_for_test(&mut self, fail: bool) {
|
||||
self.fail_truncate_for_test = fail;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn set_last_modified_ts_for_test(&mut self, ts_seconds: u64) {
|
||||
self.last_modified_ts_seconds = ts_seconds;
|
||||
@@ -4541,7 +4683,16 @@ pub(crate) fn fsync_dir(path: &str) -> io::Result<()> {
|
||||
|
||||
pub(crate) fn remove_volume_files(base: &str, keep_vif: bool) {
|
||||
for ext in &[
|
||||
".dat", ".idx", ".vif", ".sdx", ".cpd", ".cpx", ".cpc", ".note", ".rdb",
|
||||
".dat",
|
||||
".idx",
|
||||
".vif",
|
||||
".sdx",
|
||||
".cpd",
|
||||
".cpx",
|
||||
".cpc",
|
||||
".note",
|
||||
".rdb",
|
||||
".unavailable",
|
||||
] {
|
||||
if *ext == ".vif" && keep_vif {
|
||||
continue;
|
||||
@@ -5106,7 +5257,7 @@ mod tests {
|
||||
let plan = v.dat_scan_plan(sb_size).unwrap();
|
||||
let dat_path = v.file_name(".dat");
|
||||
|
||||
v.destroy(false, false).unwrap();
|
||||
v.destroy(false, false, false).unwrap();
|
||||
assert!(
|
||||
!Path::new(&dat_path).exists(),
|
||||
"precondition: destroy removed .dat"
|
||||
@@ -5553,6 +5704,72 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A failed fsync whose .dat rollback cannot complete leaves the tail
|
||||
/// unverified, so the volume fails closed: reads and writes are refused,
|
||||
/// the state is persisted, and a reload stays quarantined.
|
||||
#[test]
|
||||
fn test_failed_rollback_marks_volume_unavailable() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
v.fail_next_fsync_for_test(true);
|
||||
v.fail_next_truncate_for_test(true);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(0xaa),
|
||||
data: b"never-landed".to_vec(),
|
||||
data_size: 12,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true, true).unwrap_err();
|
||||
v.fail_next_fsync_for_test(false);
|
||||
v.fail_next_truncate_for_test(false);
|
||||
|
||||
assert!(v.is_read_only());
|
||||
assert!(v.unavailable_error().is_some());
|
||||
assert!(
|
||||
v.should_quarantine(),
|
||||
"an unavailable volume must stay out of heartbeats"
|
||||
);
|
||||
assert!(Path::new(&v.file_name(".unavailable")).exists());
|
||||
|
||||
let mut read_n = Needle {
|
||||
id: NeedleId(1),
|
||||
..Needle::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
v.read_needle(&mut read_n),
|
||||
Err(VolumeError::Unavailable(_))
|
||||
));
|
||||
let mut later = Needle {
|
||||
id: NeedleId(2),
|
||||
cookie: Cookie(0xbb),
|
||||
data: b"should-be-refused".to_vec(),
|
||||
data_size: 17,
|
||||
..Needle::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
v.write_needle(&mut later, true, true),
|
||||
Err(VolumeError::Unavailable(_))
|
||||
));
|
||||
assert!(
|
||||
v.set_writable().is_err(),
|
||||
"a manual writable transition must not bypass quarantine"
|
||||
);
|
||||
assert!(v.unavailable_error().is_some());
|
||||
|
||||
let reloaded = reload_volume(dir);
|
||||
assert!(reloaded.unavailable_error().is_some());
|
||||
assert!(reloaded.is_read_only());
|
||||
assert!(reloaded.should_quarantine());
|
||||
let mut read_n = Needle {
|
||||
id: NeedleId(1),
|
||||
..Needle::default()
|
||||
};
|
||||
assert!(reloaded.read_needle(&mut read_n).is_err());
|
||||
}
|
||||
|
||||
/// Same for a needle the failed write introduced: it never becomes visible,
|
||||
/// rather than being published and then tombstoned back out.
|
||||
#[test]
|
||||
@@ -6230,6 +6447,54 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_checks_live_needle_id() {
|
||||
// Mirror of Go's TestScrubVolumeDataChecksLiveNeedleId: a live needle
|
||||
// whose stored id is damaged still reads clean — the data CRC does not
|
||||
// cover the header — so the scrub must catch it via the index key.
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
write_test_needle(&mut v, 1, b"needle data");
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let mut idx_file = File::open(v.file_name(".idx")).unwrap();
|
||||
let mut live_offset = Offset::default();
|
||||
idx::walk_index_file(&mut idx_file, 0, |key, offset, size| {
|
||||
if key == NeedleId(1) && !offset.is_zero() && !size.is_deleted() {
|
||||
live_offset = offset;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_count, broken) = v.scrub().unwrap();
|
||||
assert!(broken.is_empty(), "healthy needle must pass, got {:?}", broken);
|
||||
|
||||
let mut id_bytes = [0u8; NEEDLE_ID_SIZE];
|
||||
NeedleId(99).to_bytes(&mut id_bytes);
|
||||
let mut dat = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(v.file_name(".dat"))
|
||||
.unwrap();
|
||||
dat.seek(SeekFrom::Start(
|
||||
live_offset.to_actual_offset() as u64 + COOKIE_SIZE as u64,
|
||||
))
|
||||
.unwrap();
|
||||
dat.write_all(&id_bytes).unwrap();
|
||||
dat.sync_all().unwrap();
|
||||
|
||||
let (_count, broken) = v.scrub().unwrap();
|
||||
assert!(
|
||||
broken
|
||||
.iter()
|
||||
.any(|e| e.contains("does not match needle's Id")),
|
||||
"scrub should report the corrupted live needle's Id, got {:?}",
|
||||
broken
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_reports_truncated_local_deletion_tombstone() {
|
||||
// Mirror of Go's TestScrubVolumeDataReportsTruncatedLocalDeletionTombstone.
|
||||
@@ -6797,7 +7062,7 @@ mod tests {
|
||||
dat_path = v.file_name(".dat");
|
||||
idx_path = v.file_name(".idx");
|
||||
assert!(Path::new(&dat_path).exists());
|
||||
v.destroy(false, false).unwrap();
|
||||
v.destroy(false, false, false).unwrap();
|
||||
}
|
||||
|
||||
assert!(!Path::new(&dat_path).exists());
|
||||
@@ -7058,7 +7323,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Vacuum compaction must tolerate an .idx entry whose offset points past
|
||||
/// the end of the .dat file (the failure mode in issue #8928). The bad
|
||||
/// the end of the .dat file. The bad
|
||||
/// entry is silently dropped from the resulting .cpx; healthy needles
|
||||
/// survive untouched.
|
||||
#[test]
|
||||
@@ -7125,7 +7390,7 @@ mod tests {
|
||||
|
||||
/// The needle map's max_needle_end accumulator must let volume.load
|
||||
/// detect an .idx whose entries point past the end of the .dat — the
|
||||
/// deeper-than-tail corruption shape from issue #8928 that the existing
|
||||
/// deeper-than-tail corruption shape that the existing
|
||||
/// last-10-entries scan cannot see. The check is populated by the load
|
||||
/// walk and read in volume.load() to flip the volume read-only.
|
||||
#[test]
|
||||
@@ -8591,7 +8856,7 @@ mod tests {
|
||||
assert!(std::path::Path::new(&idx_path).exists());
|
||||
|
||||
// Destroy the volume
|
||||
v.destroy(false, false).unwrap();
|
||||
v.destroy(false, false, false).unwrap();
|
||||
|
||||
// .dat and .idx should be gone
|
||||
assert!(
|
||||
@@ -8644,7 +8909,7 @@ mod tests {
|
||||
assert!(std::path::Path::new(&dat_path).exists());
|
||||
assert!(std::path::Path::new(&idx_path).exists());
|
||||
|
||||
v.destroy(false, false).unwrap();
|
||||
v.destroy(false, false, false).unwrap();
|
||||
|
||||
assert!(
|
||||
!std::path::Path::new(&dat_path).exists(),
|
||||
@@ -8683,7 +8948,7 @@ mod tests {
|
||||
let ecx_path = format!("{}/1.ecx", dir);
|
||||
std::fs::write(&ecx_path, b"ec-index").unwrap();
|
||||
|
||||
v.destroy(false, false).unwrap();
|
||||
v.destroy(false, false, false).unwrap();
|
||||
|
||||
let dat_path = format!("{}/1.dat", dir);
|
||||
let idx_path = format!("{}/1.idx", dir);
|
||||
|
||||
@@ -1255,3 +1255,102 @@ 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");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
# 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"]
|
||||
@@ -0,0 +1,104 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,623 @@
|
||||
// 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")
|
||||
}
|
||||
+68
-12
@@ -3,6 +3,7 @@ package cluster
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -27,6 +28,7 @@ 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
|
||||
@@ -35,15 +37,24 @@ 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,
|
||||
grpcDialOption: grpcDialOption,
|
||||
maxLockDuration: 5 * time.Second,
|
||||
sleepDuration: 2473 * time.Millisecond,
|
||||
seedFiler: seedFiler,
|
||||
priorWindow: 5 * time.Second,
|
||||
noLockServerRetryPeriod: 15 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +69,16 @@ 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(servers)
|
||||
newRing.SetServers(sorted)
|
||||
if lc.ring != nil {
|
||||
lc.priorRing = lc.ring
|
||||
lc.ringChangedAt = time.Now()
|
||||
@@ -69,6 +86,18 @@ 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 {
|
||||
@@ -133,7 +162,9 @@ type LiveLock struct {
|
||||
consecutiveFailures int // Track connection failures to trigger fallback
|
||||
}
|
||||
|
||||
// NewShortLivedLock creates a lock with a 5-second duration
|
||||
// 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.
|
||||
func (lc *LockClient) NewShortLivedLock(key string, owner string) (lock *LiveLock) {
|
||||
lock = &LiveLock{
|
||||
key: key,
|
||||
@@ -144,7 +175,10 @@ func (lc *LockClient) NewShortLivedLock(key string, owner string) (lock *LiveLoc
|
||||
self: owner,
|
||||
lc: lc,
|
||||
}
|
||||
lock.retryUntilLocked(5 * time.Second)
|
||||
if err := lock.retryUntilLocked(5 * time.Second); err != nil {
|
||||
glog.Warningf("create lock %s: %v", key, err)
|
||||
return nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -167,7 +201,10 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
lockTTL: lockTTL,
|
||||
}
|
||||
// Block until acquired
|
||||
lock.retryUntilLocked(lockTTL)
|
||||
if err := lock.retryUntilLocked(lockTTL); err != nil {
|
||||
glog.Warningf("create lock %s: %v", key, err)
|
||||
return nil
|
||||
}
|
||||
// Start renewal goroutine using a ticker for interruptible sleep
|
||||
lock.renewalDone = make(chan struct{})
|
||||
go func() {
|
||||
@@ -266,12 +303,31 @@ 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) {
|
||||
func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) error {
|
||||
var unavailableSince time.Time
|
||||
for lock.renewToken == "" {
|
||||
if err := lock.AttemptToLock(lockDuration); err != nil {
|
||||
glog.V(1).Infof("create lock %s: %v", lock.key, err)
|
||||
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
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
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,
|
||||
@@ -152,6 +157,135 @@ 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,6 +1,7 @@
|
||||
package lock_manager
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -54,6 +55,14 @@ 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
|
||||
@@ -74,6 +83,19 @@ 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,3 +96,42 @@ 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,29 +11,38 @@ 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
|
||||
broadcastFn func(resp *master_pb.KeepConnectedResponse)
|
||||
stabilizeDelay 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
|
||||
rebroadcastTimer map[FilerGroupName]*time.Timer
|
||||
broadcastFn func(resp *master_pb.KeepConnectedResponse)
|
||||
stabilizeDelay time.Duration
|
||||
rebroadcastInterval 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),
|
||||
broadcastFn: broadcastFn,
|
||||
stabilizeDelay: LockRingStabilizationInterval,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,16 +125,64 @@ 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)
|
||||
if members, ok := lrm.members[filerGroup]; ok {
|
||||
for addr := range members {
|
||||
servers = append(servers, string(addr))
|
||||
}
|
||||
servers := make([]string, 0, len(members))
|
||||
for addr := range members {
|
||||
servers = append(servers, string(addr))
|
||||
}
|
||||
update := &master_pb.LockRingUpdate{
|
||||
FilerGroup: string(filerGroup),
|
||||
@@ -133,16 +190,13 @@ func (lrm *LockRingManager) doBroadcast(filerGroup FilerGroupName) {
|
||||
Version: version,
|
||||
}
|
||||
lrm.lastBroadcast[filerGroup] = update
|
||||
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,
|
||||
})
|
||||
if timer, ok := lrm.rebroadcastTimer[filerGroup]; ok {
|
||||
timer.Stop()
|
||||
}
|
||||
lrm.rebroadcastTimer[filerGroup] = time.AfterFunc(lrm.rebroadcastInterval, func() {
|
||||
lrm.rebroadcast(filerGroup)
|
||||
})
|
||||
return update
|
||||
}
|
||||
|
||||
// FlushPending fires any pending timer immediately (for testing or shutdown).
|
||||
|
||||
@@ -213,6 +213,111 @@ 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); err != nil {
|
||||
if err := v.Destroy(false, false, false); err != nil {
|
||||
v.Close()
|
||||
return fmt.Errorf("destroying volume: %w", err), false
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -41,14 +43,6 @@ func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *sour
|
||||
|
||||
var lastLogTsNs = time.Now().UnixNano()
|
||||
processEventFnWithOffset := pb.AddOffsetFunc(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if resp.EventNotification.NewEntry != nil {
|
||||
if *option.storageClass == "" {
|
||||
delete(resp.EventNotification.NewEntry.Extended, s3_constants.AmzStorageClass)
|
||||
} else {
|
||||
resp.EventNotification.NewEntry.Extended[s3_constants.AmzStorageClass] = []byte(*option.storageClass)
|
||||
}
|
||||
}
|
||||
|
||||
processor.AddSyncJob(resp)
|
||||
return nil
|
||||
}, 3*time.Second, func(counter int64, lastTsNs int64) error {
|
||||
@@ -175,10 +169,10 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(parentPath, entryName), remoteStorageMountLocation)
|
||||
if message.NewEntry.IsDirectory {
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, message.NewEntry)
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, *option.storageClass))
|
||||
}
|
||||
glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, message.NewEntry, dest)
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, *option.storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
@@ -213,7 +207,7 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
return client.DeleteFile(dest)
|
||||
}
|
||||
if message.OldEntry != nil && message.NewEntry != nil {
|
||||
return processUpdateEvent(option, filerSource, client, mountedDir, remoteStorageMountLocation, resp)
|
||||
return processUpdateEvent(option, filerSource, *option.storageClass, client, mountedDir, remoteStorageMountLocation, resp)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -224,6 +218,7 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
func processUpdateEvent(
|
||||
filerClient filer_pb.FilerClient,
|
||||
filerSource filer_pb.FilerClient,
|
||||
storageClass string,
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
@@ -244,7 +239,7 @@ func processUpdateEvent(
|
||||
return nil
|
||||
}
|
||||
if message.NewEntry.IsDirectory {
|
||||
return client.WriteDirectory(dest, message.NewEntry)
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, storageClass))
|
||||
}
|
||||
if isMetadataOnlyUpdate(resp.Directory, message) {
|
||||
remoteEntry, err := liveRemoteEntry(filerClient, message.NewParentPath, message.NewEntry)
|
||||
@@ -257,7 +252,7 @@ func processUpdateEvent(
|
||||
}
|
||||
if remoteEntry != nil {
|
||||
glog.V(2).Infof("update meta: %+v", resp)
|
||||
return client.UpdateFileMetadata(dest, message.OldEntry, message.NewEntry)
|
||||
return client.UpdateFileMetadata(dest, message.OldEntry, remoteWriteEntry(message.NewEntry, storageClass))
|
||||
}
|
||||
glog.V(0).Infof("never replicated, uploading %s", remote_storage.FormatLocation(dest))
|
||||
}
|
||||
@@ -277,7 +272,7 @@ func processUpdateEvent(
|
||||
}
|
||||
}
|
||||
}
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, message.NewEntry, dest)
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
@@ -417,16 +412,66 @@ func shouldSendToRemote(entry *filer_pb.Entry) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// remoteWriteEntry returns the entry as remote storage should see it: the
|
||||
// storage class attribute is dropped, or overridden by -storageClass. The
|
||||
// event entry is left untouched so updateLocalEntry still compares the entry
|
||||
// the filer stored.
|
||||
func remoteWriteEntry(entry *filer_pb.Entry, storageClass string) *filer_pb.Entry {
|
||||
clone := proto.Clone(entry).(*filer_pb.Entry)
|
||||
if storageClass == "" {
|
||||
delete(clone.Extended, s3_constants.AmzStorageClass)
|
||||
} else {
|
||||
if clone.Extended == nil {
|
||||
clone.Extended = map[string][]byte{}
|
||||
}
|
||||
clone.Extended[s3_constants.AmzStorageClass] = []byte(storageClass)
|
||||
}
|
||||
return clone
|
||||
}
|
||||
|
||||
// updateLocalEntry stamps the entry an event described with its RemoteEntry.
|
||||
// The write carries IF_ENTRY_EQUAL over the event's entry: the filer deletes
|
||||
// every stored chunk absent from an updated entry, so a snapshot older than
|
||||
// the live entry (the file was rewritten while its upload was in flight, or
|
||||
// the event is a replay) would delete the live chunks. A failed precondition
|
||||
// means the filer moved past this event; the event that superseded it follows
|
||||
// in the log and stamps the current entry, so the stale stamp is skipped the
|
||||
// same way a superseded upload is.
|
||||
func updateLocalEntry(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.Entry, remoteEntry *filer_pb.RemoteEntry) error {
|
||||
remoteEntry.LastLocalSyncTsNs = time.Now().UnixNano()
|
||||
expected := proto.Clone(entry).(*filer_pb.Entry)
|
||||
entry.RemoteEntry = remoteEntry
|
||||
return filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: entry,
|
||||
Condition: ifEntryEqual(expected),
|
||||
})
|
||||
return err
|
||||
})
|
||||
if isFailedPrecondition(err) {
|
||||
glog.Errorf("skipping stale stamp of %s: %v", util.NewFullPath(dir, entry.Name), err)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ifEntryEqual builds the precondition that the stored entry still equals the
|
||||
// one the event described: chunk fids, inline content, and metadata alike.
|
||||
func ifEntryEqual(entry *filer_pb.Entry) *filer_pb.WriteCondition {
|
||||
return &filer_pb.WriteCondition{
|
||||
Clauses: []*filer_pb.WriteCondition_Clause{{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: entry}},
|
||||
}
|
||||
}
|
||||
|
||||
// isFailedPrecondition reports a write condition the filer refused, through
|
||||
// any wrapping WithFilerClient added.
|
||||
func isFailedPrecondition(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
st, ok := status.FromError(err)
|
||||
return ok && st.Code() == codes.FailedPrecondition
|
||||
}
|
||||
|
||||
func isMultipartUploadFile(dir string, name string) bool {
|
||||
|
||||
@@ -16,6 +16,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -684,7 +686,7 @@ func TestRenameWithInheritedRemoteEntryWritesNewKey(t *testing.T) {
|
||||
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{}
|
||||
if err := processUpdateEvent(filerClient, filerClient, remote, mountedDir, mountLoc, resp); err != nil {
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -731,7 +733,7 @@ func TestRenameRemoteOnlyEntrySkipsEmptyUpload(t *testing.T) {
|
||||
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{}
|
||||
if err := processUpdateEvent(filerClient, filerClient, remote, mountedDir, mountLoc, resp); err != nil {
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
@@ -764,7 +766,7 @@ func TestRenameDeleteOldKeyFailureReturnsError(t *testing.T) {
|
||||
deleteErr := errors.New("AccessDenied: Access Denied")
|
||||
remote := &recordingRemote{deleteErr: deleteErr}
|
||||
filerClient := &stubFilerClient{}
|
||||
err := processUpdateEvent(filerClient, filerClient, remote, mountedDir, mountLoc, resp)
|
||||
err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp)
|
||||
if !errors.Is(err, deleteErr) {
|
||||
t.Errorf("err = %v, want the delete failure returned so the event is retried", err)
|
||||
}
|
||||
@@ -800,7 +802,7 @@ func TestRenameDeleteOldKeyNotFoundStillWrites(t *testing.T) {
|
||||
|
||||
remote := &recordingRemote{deleteErr: remote_storage.ErrRemoteObjectNotFound}
|
||||
filerClient := &stubFilerClient{}
|
||||
if err := processUpdateEvent(filerClient, filerClient, remote, mountedDir, mountLoc, resp); err != nil {
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
|
||||
t.Fatalf("err = %v, want nil: an already-deleted old key must not block the write", err)
|
||||
}
|
||||
wantWrite := &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/b/dst/probe.bin"}
|
||||
@@ -808,3 +810,73 @@ func TestRenameDeleteOldKeyNotFoundStillWrites(t *testing.T) {
|
||||
t.Errorf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIfEntryEqualCarriesTheEventEntry(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "f",
|
||||
Content: []byte("inline"),
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{FileId: "3,01a"},
|
||||
{Fid: &filer_pb.FileId{VolumeId: 4, FileKey: 0x2b, Cookie: 0x0c}},
|
||||
},
|
||||
}
|
||||
cond := ifEntryEqual(entry)
|
||||
if len(cond.Clauses) != 1 || cond.Clauses[0].Kind != filer_pb.WriteCondition_IF_ENTRY_EQUAL {
|
||||
t.Fatalf("condition = %v, want one IF_ENTRY_EQUAL clause", cond)
|
||||
}
|
||||
if got := cond.Clauses[0].ExpectedEntry; !proto.Equal(got, entry) {
|
||||
t.Fatalf("expected_entry = %v, want %v", got, entry)
|
||||
}
|
||||
}
|
||||
|
||||
// The remote-bound entry loses (or gains) the storage class attribute while
|
||||
// the event entry keeps it, so IF_ENTRY_EQUAL still sees the entry the filer
|
||||
// stored — otherwise every stamp on an S3-written object reads as stale.
|
||||
func TestRemoteWriteEntryLeavesEventEntryUntouched(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "f",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1},
|
||||
Extended: map[string][]byte{s3_constants.AmzStorageClass: []byte("STANDARD")},
|
||||
}
|
||||
|
||||
stripped := remoteWriteEntry(entry, "")
|
||||
if _, ok := stripped.Extended[s3_constants.AmzStorageClass]; ok {
|
||||
t.Fatalf("remote entry still carries %s", s3_constants.AmzStorageClass)
|
||||
}
|
||||
if string(entry.Extended[s3_constants.AmzStorageClass]) != "STANDARD" {
|
||||
t.Fatalf("event entry Extended mutated: %v", entry.Extended)
|
||||
}
|
||||
|
||||
overridden := remoteWriteEntry(entry, "GLACIER")
|
||||
if got := string(overridden.Extended[s3_constants.AmzStorageClass]); got != "GLACIER" {
|
||||
t.Fatalf("override = %q, want GLACIER", got)
|
||||
}
|
||||
if string(entry.Extended[s3_constants.AmzStorageClass]) != "STANDARD" {
|
||||
t.Fatalf("event entry Extended mutated: %v", entry.Extended)
|
||||
}
|
||||
|
||||
bare := &filer_pb.Entry{Name: "g", Attributes: &filer_pb.FuseAttributes{Mtime: 1}}
|
||||
if got := string(remoteWriteEntry(bare, "GLACIER").Extended[s3_constants.AmzStorageClass]); got != "GLACIER" {
|
||||
t.Fatalf("override on nil Extended = %q, want GLACIER", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsFailedPrecondition(t *testing.T) {
|
||||
refused := status.Error(codes.FailedPrecondition, "precondition failed: /buckets/b/f")
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{"nil", nil, false},
|
||||
{"status", refused, true},
|
||||
{"wrapped status", fmt.Errorf("update entry: %w", refused), true},
|
||||
{"message only", errors.New("rpc error: code = FailedPrecondition desc = precondition failed: /f"), false},
|
||||
{"other", status.Error(codes.Unavailable, "filer down"), false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := isFailedPrecondition(c.err); got != c.want {
|
||||
t.Errorf("%s: isFailedPrecondition = %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,7 @@ type MasterOptions struct {
|
||||
fileSizeLimitMB *int
|
||||
volumePreallocate *bool
|
||||
maxParallelVacuumPerServer *int
|
||||
vacuumIntervalSeconds *int
|
||||
// pulseSeconds *int
|
||||
defaultReplication *string
|
||||
garbageThreshold *float64
|
||||
@@ -93,6 +94,7 @@ 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.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")
|
||||
@@ -473,6 +475,7 @@ func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOp
|
||||
FileSizeLimitMB: *m.fileSizeLimitMB,
|
||||
VolumePreallocate: *m.volumePreallocate,
|
||||
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
|
||||
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
|
||||
// PulseSeconds: *m.pulseSeconds,
|
||||
DefaultReplicaPlacement: *m.defaultReplication,
|
||||
GarbageThreshold: *m.garbageThreshold,
|
||||
|
||||
@@ -47,6 +47,7 @@ func init() {
|
||||
mf.metricsIntervalSec = aws.Int(0)
|
||||
mf.raftResumeState = aws.Bool(false)
|
||||
mf.maxParallelVacuumPerServer = aws.Int(1)
|
||||
mf.vacuumIntervalSeconds = aws.Int(840)
|
||||
mf.telemetryUrl = aws.String("https://telemetry.seaweedfs.com/api/collect")
|
||||
mf.telemetryEnabled = aws.Bool(false)
|
||||
}
|
||||
|
||||
@@ -427,6 +427,7 @@ 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.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,6 +618,7 @@ 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})
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ 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.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, keepRemoteData)
|
||||
return volume_move.NewMover(grpcDialOption).DeleteVolume(ctx, volumeId, sourceVolumeServer, onlyEmpty, false, keepRemoteData)
|
||||
}
|
||||
|
||||
func ChunkVolumeIds(volumeIds []needle.VolumeId, batchSize int) [][]needle.VolumeId {
|
||||
|
||||
+18
-1
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
||||
@@ -73,6 +74,11 @@ 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 {
|
||||
@@ -88,6 +94,7 @@ 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
|
||||
@@ -174,6 +181,10 @@ 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
|
||||
@@ -265,7 +276,13 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
|
||||
oldEntry := existing
|
||||
if oldEntry == nil {
|
||||
oldEntry, _ = f.FindEntry(ctx, entry.FullPath)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -13,6 +13,7 @@ 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"
|
||||
@@ -96,7 +97,7 @@ func newFilerWithFakeMaster(t *testing.T) (*Filer, *hookedStore, *collectionDele
|
||||
|
||||
mc := wdclient.NewMasterClient(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
"test", cluster.FilerType, pb.ServerAddress("localhost:0"), "", "",
|
||||
"", cluster.FilerType, pb.ServerAddress("localhost:0"), "", "",
|
||||
*pb.NewServiceDiscoveryFromMap(map[string]pb.ServerAddress{"m": masterAddress}),
|
||||
)
|
||||
|
||||
@@ -181,3 +182,206 @@ 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,6 +68,10 @@ 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 {
|
||||
@@ -102,17 +106,18 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
}
|
||||
|
||||
if isDeleteCollection {
|
||||
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()
|
||||
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()
|
||||
}
|
||||
// drop bucket-labeled series held by this process; the S3 gateway
|
||||
// only cleans its own registry
|
||||
stats.DeleteBucketMetrics(collectionName)
|
||||
stats.DeleteBucketMetrics(entry.Name())
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -120,6 +125,15 @@ 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 := ""
|
||||
@@ -129,6 +143,9 @@ 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)
|
||||
}
|
||||
@@ -140,6 +157,7 @@ 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)
|
||||
@@ -202,6 +220,8 @@ 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)
|
||||
}
|
||||
@@ -221,6 +241,75 @@ 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,11 +2,13 @@ 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"
|
||||
@@ -101,6 +103,57 @@ 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,7 +7,10 @@ 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"
|
||||
@@ -43,6 +46,21 @@ 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
|
||||
@@ -103,10 +121,27 @@ 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
|
||||
@@ -122,6 +157,25 @@ 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,6 +56,14 @@ 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
|
||||
@@ -109,6 +117,10 @@ 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.)
|
||||
@@ -161,6 +173,9 @@ 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,6 +34,7 @@ type stubFilerStore struct {
|
||||
entries map[string]*Entry
|
||||
kv map[string][]byte
|
||||
insertErr error
|
||||
findErr error
|
||||
deleteErrByPath map[string]error
|
||||
}
|
||||
|
||||
@@ -174,6 +175,9 @@ 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
|
||||
}
|
||||
@@ -279,6 +283,7 @@ 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,6 +15,7 @@ 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) {
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
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)
|
||||
}
|
||||
@@ -36,6 +36,7 @@ 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
|
||||
@@ -87,11 +88,13 @@ 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 {
|
||||
if err := loadRemoteStorageMountMapping(rules, entry.Content); err != nil {
|
||||
mountDirs, err = loadRemoteStorageMountMapping(rules, entry.Content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
@@ -117,27 +120,46 @@ func (rs *FilerRemoteStorage) LoadRemoteStorageConfigurationsAndMapping(filer *F
|
||||
}
|
||||
|
||||
rs.mu.Lock()
|
||||
rs.rules, rs.storageNameToConf = rules, storageNameToConf
|
||||
rs.rules, rs.mountDirs, rs.storageNameToConf = rules, mountDirs, storageNameToConf
|
||||
rs.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadRemoteStorageMountMapping(rules ptrie.Trie[*remote_pb.RemoteStorageLocation], data []byte) (err error) {
|
||||
func loadRemoteStorageMountMapping(rules ptrie.Trie[*remote_pb.RemoteStorageLocation], data []byte) (mountDirs []util.FullPath, err error) {
|
||||
mappings := &remote_pb.RemoteStorageMapping{}
|
||||
if err := proto.Unmarshal(data, mappings); err != nil {
|
||||
return fmt.Errorf("unmarshal %s/%s: %v", DirectoryEtcRemote, REMOTE_STORAGE_MOUNT_FILE, err)
|
||||
return nil, 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 nil
|
||||
return mountDirs, 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) {
|
||||
|
||||
@@ -211,6 +211,9 @@ 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 {
|
||||
@@ -219,9 +222,6 @@ 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,6 +9,7 @@ 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"
|
||||
@@ -72,10 +73,26 @@ 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.
|
||||
// Reopen the winner's entry; AcquireHandle takes its own lock.
|
||||
if dlmLock != nil {
|
||||
dlmLock.Stop()
|
||||
}
|
||||
newEntry, _, code = wfs.maybeLoadEntry(entryFullPath)
|
||||
if code != fuse.OK {
|
||||
return code
|
||||
@@ -100,6 +117,9 @@ 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)
|
||||
@@ -122,15 +142,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
|
||||
|
||||
// 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)
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
|
||||
out.Fh = uint64(fileHandle.fh)
|
||||
|
||||
@@ -2,6 +2,7 @@ package mount
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
@@ -77,6 +78,12 @@ 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
|
||||
|
||||
+126
-48
@@ -9,6 +9,7 @@ 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"
|
||||
@@ -16,10 +17,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) error {
|
||||
func (wfs *WFS) doRename(ctx context.Context, request *filer_pb.StreamRenameEntryRequest, oldPath, newPath util.FullPath, newPathLock **cluster.LiveLock) 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)
|
||||
return wfs.handleRenameResponse(ctx, resp, newPath, newPathLock)
|
||||
})
|
||||
if err == nil || !errors.Is(err, ErrStreamTransport) {
|
||||
return err // success or application error
|
||||
@@ -39,7 +40,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); err != nil {
|
||||
if err := wfs.handleRenameResponse(ctx, resp, newPath, newPathLock); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -240,6 +241,102 @@ 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.
|
||||
@@ -300,41 +397,6 @@ 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),
|
||||
@@ -345,7 +407,7 @@ func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err := wfs.doRename(ctx, request, oldPath, newPath)
|
||||
err := wfs.doRename(ctx, request, oldPath, newPath, &newPathLock)
|
||||
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
|
||||
@@ -377,7 +439,7 @@ func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string
|
||||
|
||||
}
|
||||
|
||||
func (wfs *WFS) handleRenameResponse(ctx context.Context, resp *filer_pb.StreamRenameEntryResponse) error {
|
||||
func (wfs *WFS) handleRenameResponse(ctx context.Context, resp *filer_pb.StreamRenameEntryResponse, renameNewPath util.FullPath, renameNewPathLock **cluster.LiveLock) error {
|
||||
// comes from filer StreamRenameEntry, can only be create or delete entry
|
||||
|
||||
glog.V(4).Infof("dir Rename %+v", resp.EventNotification)
|
||||
@@ -411,16 +473,32 @@ 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.
|
||||
if wfs.lockClient != nil {
|
||||
// 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 {
|
||||
fhActiveLock := wfs.fhLockTable.AcquireLock("renameDLM", fh.fh, util.ExclusiveLock)
|
||||
if fh.dlmLock != nil {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ func TestHandleRenameResponseLeavesUncachedTargetOutOfCache(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
if err := wfs.handleRenameResponse(context.Background(), resp); err != nil {
|
||||
if err := wfs.handleRenameResponse(context.Background(), resp, targetPath, nil); err != nil {
|
||||
t.Fatalf("handle rename response: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -194,11 +194,12 @@ func NewUploaderWithHttpClient(httpClient HTTPClient) *Uploader {
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
doUploadFunc := func() error {
|
||||
var host string
|
||||
var auth security.EncodedJwt
|
||||
fileId, host, auth, err = assignFn()
|
||||
var fsync bool
|
||||
fileId, host, auth, fsync, err = assignFn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -208,6 +209,9 @@ 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
|
||||
@@ -263,7 +267,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, err error) {
|
||||
fileId, uploadResult, err = uploader.uploadWithRetryData(func() (fileId string, host string, auth security.EncodedJwt, fsync bool, err error) {
|
||||
// grpc assign volume
|
||||
if grpcAssignErr := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
assignCtx, assignCancel := context.WithTimeout(context.Background(), assignVolumeTimeout)
|
||||
@@ -278,6 +282,7 @@ 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, error) {
|
||||
fileID, uploadResult, err := uploader.uploadWithRetryData(func() (string, string, security.EncodedJwt, bool, error) {
|
||||
assignCalls++
|
||||
if assignCalls == 1 {
|
||||
return "1,first", "volume-a", "", nil
|
||||
return "1,first", "volume-a", "", false, nil
|
||||
}
|
||||
return "2,second", "volume-b", "", nil
|
||||
return "2,second", "volume-b", "", false, 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, error) {
|
||||
fileID, uploadResult, err := uploader.uploadWithRetryData(func() (string, string, security.EncodedJwt, bool, error) {
|
||||
assignCalls++
|
||||
if assignCalls == 1 {
|
||||
return "1,first", "volume-a", "", nil
|
||||
return "1,first", "volume-a", "", false, nil
|
||||
}
|
||||
return "2,second", "volume-b", "", nil
|
||||
return "2,second", "volume-b", "", false, nil
|
||||
}, &UploadOption{Filename: "test.bin"}, []byte("abc"))
|
||||
|
||||
if err != nil {
|
||||
@@ -199,6 +199,64 @@ 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, true); dErr != nil {
|
||||
if dErr := m.DeleteVolume(cleanupCtx, volumeId, target, false, 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, true); err != nil {
|
||||
if err = m.DeleteVolume(ctx, volumeId, source, false, false, true); err != nil {
|
||||
return fmt.Errorf("delete volume %d from %s: %v", volumeId, source, err)
|
||||
}
|
||||
|
||||
@@ -415,11 +415,12 @@ 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, keepRemoteData bool) error {
|
||||
func (m *Mover) DeleteVolume(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, onlyEmpty bool, onlyGarbage 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
|
||||
|
||||
@@ -281,6 +281,7 @@ message WriteCondition {
|
||||
IF_EXTENDED_NOT_EQUAL = 7; // fail if present and extended[ext_key] == ext_value
|
||||
IF_EXTENDED_TIME_ELAPSED = 8; // fail if present and extended[ext_key] (unix seconds) is in the future
|
||||
IF_CHUNKS_EQUAL = 9; // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
|
||||
IF_ENTRY_EQUAL = 10; // fail unless the stored entry equals expected_entry
|
||||
}
|
||||
// Clause is one primitive comparison. IF_ETAG_MATCH holds when the current
|
||||
// entry's ETag equals any value in etags; IF_ETAG_NOT_MATCH holds when it
|
||||
@@ -309,6 +310,7 @@ message WriteCondition {
|
||||
string gate_key = 7; // IF_EXTENDED_TIME_ELAPSED: only enforce when extended[gate_key] == gate_value
|
||||
string gate_value = 8; // gate value (e.g. retention mode COMPLIANCE for governance bypass)
|
||||
repeated string fids = 9; // chunk fid strings for IF_CHUNKS_EQUAL
|
||||
Entry expected_entry = 10; // whole-entry comparison for IF_ENTRY_EQUAL
|
||||
}
|
||||
repeated Clause clauses = 1; // all must hold (logical AND)
|
||||
}
|
||||
@@ -477,6 +479,7 @@ message UpdateEntryRequest {
|
||||
// the write, under the filer's per-path lock. The caller must route the
|
||||
// key's writes to this entry's owner filer for the check to be authoritative.
|
||||
WriteCondition condition = 6;
|
||||
bool is_moved = 7; // set on a forwarded request so the owner applies it locally
|
||||
}
|
||||
message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
|
||||
+137
-112
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v7.35.0
|
||||
// protoc v3.21.12
|
||||
// source: filer.proto
|
||||
|
||||
package filer_pb
|
||||
@@ -197,31 +197,33 @@ func (PosixLockOp) EnumDescriptor() ([]byte, []int) {
|
||||
type WriteCondition_Kind int32
|
||||
|
||||
const (
|
||||
WriteCondition_NONE WriteCondition_Kind = 0 // unconditional
|
||||
WriteCondition_IF_NOT_EXISTS WriteCondition_Kind = 1 // fail if the entry exists (If-None-Match: *)
|
||||
WriteCondition_IF_EXISTS WriteCondition_Kind = 2 // fail if the entry is absent (If-Match: *)
|
||||
WriteCondition_IF_ETAG_MATCH WriteCondition_Kind = 3 // fail if absent or etag matches none of the set (If-Match)
|
||||
WriteCondition_IF_ETAG_NOT_MATCH WriteCondition_Kind = 4 // fail if present and etag matches any of the set (If-None-Match)
|
||||
WriteCondition_IF_UNMODIFIED_SINCE WriteCondition_Kind = 5 // fail if present and mtime > unix_time
|
||||
WriteCondition_IF_MODIFIED_SINCE WriteCondition_Kind = 6 // fail if present and mtime <= unix_time
|
||||
WriteCondition_IF_EXTENDED_NOT_EQUAL WriteCondition_Kind = 7 // fail if present and extended[ext_key] == ext_value
|
||||
WriteCondition_IF_EXTENDED_TIME_ELAPSED WriteCondition_Kind = 8 // fail if present and extended[ext_key] (unix seconds) is in the future
|
||||
WriteCondition_IF_CHUNKS_EQUAL WriteCondition_Kind = 9 // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
|
||||
WriteCondition_NONE WriteCondition_Kind = 0 // unconditional
|
||||
WriteCondition_IF_NOT_EXISTS WriteCondition_Kind = 1 // fail if the entry exists (If-None-Match: *)
|
||||
WriteCondition_IF_EXISTS WriteCondition_Kind = 2 // fail if the entry is absent (If-Match: *)
|
||||
WriteCondition_IF_ETAG_MATCH WriteCondition_Kind = 3 // fail if absent or etag matches none of the set (If-Match)
|
||||
WriteCondition_IF_ETAG_NOT_MATCH WriteCondition_Kind = 4 // fail if present and etag matches any of the set (If-None-Match)
|
||||
WriteCondition_IF_UNMODIFIED_SINCE WriteCondition_Kind = 5 // fail if present and mtime > unix_time
|
||||
WriteCondition_IF_MODIFIED_SINCE WriteCondition_Kind = 6 // fail if present and mtime <= unix_time
|
||||
WriteCondition_IF_EXTENDED_NOT_EQUAL WriteCondition_Kind = 7 // fail if present and extended[ext_key] == ext_value
|
||||
WriteCondition_IF_EXTENDED_TIME_ELAPSED WriteCondition_Kind = 8 // fail if present and extended[ext_key] (unix seconds) is in the future
|
||||
WriteCondition_IF_CHUNKS_EQUAL WriteCondition_Kind = 9 // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
|
||||
WriteCondition_IF_ENTRY_EQUAL WriteCondition_Kind = 10 // fail unless the stored entry equals expected_entry
|
||||
)
|
||||
|
||||
// Enum value maps for WriteCondition_Kind.
|
||||
var (
|
||||
WriteCondition_Kind_name = map[int32]string{
|
||||
0: "NONE",
|
||||
1: "IF_NOT_EXISTS",
|
||||
2: "IF_EXISTS",
|
||||
3: "IF_ETAG_MATCH",
|
||||
4: "IF_ETAG_NOT_MATCH",
|
||||
5: "IF_UNMODIFIED_SINCE",
|
||||
6: "IF_MODIFIED_SINCE",
|
||||
7: "IF_EXTENDED_NOT_EQUAL",
|
||||
8: "IF_EXTENDED_TIME_ELAPSED",
|
||||
9: "IF_CHUNKS_EQUAL",
|
||||
0: "NONE",
|
||||
1: "IF_NOT_EXISTS",
|
||||
2: "IF_EXISTS",
|
||||
3: "IF_ETAG_MATCH",
|
||||
4: "IF_ETAG_NOT_MATCH",
|
||||
5: "IF_UNMODIFIED_SINCE",
|
||||
6: "IF_MODIFIED_SINCE",
|
||||
7: "IF_EXTENDED_NOT_EQUAL",
|
||||
8: "IF_EXTENDED_TIME_ELAPSED",
|
||||
9: "IF_CHUNKS_EQUAL",
|
||||
10: "IF_ENTRY_EQUAL",
|
||||
}
|
||||
WriteCondition_Kind_value = map[string]int32{
|
||||
"NONE": 0,
|
||||
@@ -234,6 +236,7 @@ var (
|
||||
"IF_EXTENDED_NOT_EQUAL": 7,
|
||||
"IF_EXTENDED_TIME_ELAPSED": 8,
|
||||
"IF_CHUNKS_EQUAL": 9,
|
||||
"IF_ENTRY_EQUAL": 10,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -2375,6 +2378,7 @@ type UpdateEntryRequest struct {
|
||||
// the write, under the filer's per-path lock. The caller must route the
|
||||
// key's writes to this entry's owner filer for the check to be authoritative.
|
||||
Condition *WriteCondition `protobuf:"bytes,6,opt,name=condition,proto3" json:"condition,omitempty"`
|
||||
IsMoved bool `protobuf:"varint,7,opt,name=is_moved,json=isMoved,proto3" json:"is_moved,omitempty"` // set on a forwarded request so the owner applies it locally
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -2451,6 +2455,13 @@ func (x *UpdateEntryRequest) GetCondition() *WriteCondition {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *UpdateEntryRequest) GetIsMoved() bool {
|
||||
if x != nil {
|
||||
return x.IsMoved
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type UpdateEntryResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
MetadataEvent *SubscribeMetadataResponse `protobuf:"bytes,1,opt,name=metadata_event,json=metadataEvent,proto3" json:"metadata_event,omitempty"`
|
||||
@@ -6856,14 +6867,15 @@ func (x *LookupDirectoryEntriesResponse) GetReadAuth() map[string]string {
|
||||
type WriteCondition_Clause struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Kind WriteCondition_Kind `protobuf:"varint,1,opt,name=kind,proto3,enum=filer_pb.WriteCondition_Kind" json:"kind,omitempty"`
|
||||
Etags []string `protobuf:"bytes,2,rep,name=etags,proto3" json:"etags,omitempty"` // ETag set for IF_ETAG_* kinds
|
||||
UnixTime int64 `protobuf:"varint,3,opt,name=unix_time,json=unixTime,proto3" json:"unix_time,omitempty"` // bound (unix seconds) for IF_*_SINCE kinds
|
||||
AllowWeak bool `protobuf:"varint,4,opt,name=allow_weak,json=allowWeak,proto3" json:"allow_weak,omitempty"` // compare ETags ignoring the weak (W/) marker
|
||||
ExtKey string `protobuf:"bytes,5,opt,name=ext_key,json=extKey,proto3" json:"ext_key,omitempty"` // extended attribute name for IF_EXTENDED_* kinds
|
||||
ExtValue string `protobuf:"bytes,6,opt,name=ext_value,json=extValue,proto3" json:"ext_value,omitempty"` // blocking value for IF_EXTENDED_NOT_EQUAL
|
||||
GateKey string `protobuf:"bytes,7,opt,name=gate_key,json=gateKey,proto3" json:"gate_key,omitempty"` // IF_EXTENDED_TIME_ELAPSED: only enforce when extended[gate_key] == gate_value
|
||||
GateValue string `protobuf:"bytes,8,opt,name=gate_value,json=gateValue,proto3" json:"gate_value,omitempty"` // gate value (e.g. retention mode COMPLIANCE for governance bypass)
|
||||
Fids []string `protobuf:"bytes,9,rep,name=fids,proto3" json:"fids,omitempty"` // chunk fid strings for IF_CHUNKS_EQUAL
|
||||
Etags []string `protobuf:"bytes,2,rep,name=etags,proto3" json:"etags,omitempty"` // ETag set for IF_ETAG_* kinds
|
||||
UnixTime int64 `protobuf:"varint,3,opt,name=unix_time,json=unixTime,proto3" json:"unix_time,omitempty"` // bound (unix seconds) for IF_*_SINCE kinds
|
||||
AllowWeak bool `protobuf:"varint,4,opt,name=allow_weak,json=allowWeak,proto3" json:"allow_weak,omitempty"` // compare ETags ignoring the weak (W/) marker
|
||||
ExtKey string `protobuf:"bytes,5,opt,name=ext_key,json=extKey,proto3" json:"ext_key,omitempty"` // extended attribute name for IF_EXTENDED_* kinds
|
||||
ExtValue string `protobuf:"bytes,6,opt,name=ext_value,json=extValue,proto3" json:"ext_value,omitempty"` // blocking value for IF_EXTENDED_NOT_EQUAL
|
||||
GateKey string `protobuf:"bytes,7,opt,name=gate_key,json=gateKey,proto3" json:"gate_key,omitempty"` // IF_EXTENDED_TIME_ELAPSED: only enforce when extended[gate_key] == gate_value
|
||||
GateValue string `protobuf:"bytes,8,opt,name=gate_value,json=gateValue,proto3" json:"gate_value,omitempty"` // gate value (e.g. retention mode COMPLIANCE for governance bypass)
|
||||
Fids []string `protobuf:"bytes,9,rep,name=fids,proto3" json:"fids,omitempty"` // chunk fid strings for IF_CHUNKS_EQUAL
|
||||
ExpectedEntry *Entry `protobuf:"bytes,10,opt,name=expected_entry,json=expectedEntry,proto3" json:"expected_entry,omitempty"` // whole-entry comparison for IF_ENTRY_EQUAL
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -6961,6 +6973,13 @@ func (x *WriteCondition_Clause) GetFids() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *WriteCondition_Clause) GetExpectedEntry() *Entry {
|
||||
if x != nil {
|
||||
return x.ExpectedEntry
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// if found, send the exact address
|
||||
// if not found, send the full list of existing brokers
|
||||
type LocateBrokerResponse_Resource struct {
|
||||
@@ -7301,9 +7320,9 @@ const file_filer_proto_rawDesc = "" +
|
||||
"signatures\x12=\n" +
|
||||
"\x1bskip_check_parent_directory\x18\x06 \x01(\bR\x18skipCheckParentDirectory\x126\n" +
|
||||
"\tcondition\x18\a \x01(\v2\x18.filer_pb.WriteConditionR\tcondition\x12\x19\n" +
|
||||
"\bis_moved\x18\b \x01(\bR\aisMoved\"\xbc\x04\n" +
|
||||
"\bis_moved\x18\b \x01(\bR\aisMoved\"\x88\x05\n" +
|
||||
"\x0eWriteCondition\x129\n" +
|
||||
"\aclauses\x18\x01 \x03(\v2\x1f.filer_pb.WriteCondition.ClauseR\aclauses\x1a\x91\x02\n" +
|
||||
"\aclauses\x18\x01 \x03(\v2\x1f.filer_pb.WriteCondition.ClauseR\aclauses\x1a\xc9\x02\n" +
|
||||
"\x06Clause\x121\n" +
|
||||
"\x04kind\x18\x01 \x01(\x0e2\x1d.filer_pb.WriteCondition.KindR\x04kind\x12\x14\n" +
|
||||
"\x05etags\x18\x02 \x03(\tR\x05etags\x12\x1b\n" +
|
||||
@@ -7315,7 +7334,9 @@ const file_filer_proto_rawDesc = "" +
|
||||
"\bgate_key\x18\a \x01(\tR\agateKey\x12\x1d\n" +
|
||||
"\n" +
|
||||
"gate_value\x18\b \x01(\tR\tgateValue\x12\x12\n" +
|
||||
"\x04fids\x18\t \x03(\tR\x04fids\"\xda\x01\n" +
|
||||
"\x04fids\x18\t \x03(\tR\x04fids\x126\n" +
|
||||
"\x0eexpected_entry\x18\n" +
|
||||
" \x01(\v2\x0f.filer_pb.EntryR\rexpectedEntry\"\xee\x01\n" +
|
||||
"\x04Kind\x12\b\n" +
|
||||
"\x04NONE\x10\x00\x12\x11\n" +
|
||||
"\rIF_NOT_EXISTS\x10\x01\x12\r\n" +
|
||||
@@ -7326,7 +7347,9 @@ const file_filer_proto_rawDesc = "" +
|
||||
"\x11IF_MODIFIED_SINCE\x10\x06\x12\x19\n" +
|
||||
"\x15IF_EXTENDED_NOT_EQUAL\x10\a\x12\x1c\n" +
|
||||
"\x18IF_EXTENDED_TIME_ELAPSED\x10\b\x12\x13\n" +
|
||||
"\x0fIF_CHUNKS_EQUAL\x10\t\"\xa2\x05\n" +
|
||||
"\x0fIF_CHUNKS_EQUAL\x10\t\x12\x12\n" +
|
||||
"\x0eIF_ENTRY_EQUAL\x10\n" +
|
||||
"\"\xa2\x05\n" +
|
||||
"\x0eObjectMutation\x121\n" +
|
||||
"\x04type\x18\x01 \x01(\x0e2\x1d.filer_pb.ObjectMutation.TypeR\x04type\x12\x1c\n" +
|
||||
"\tdirectory\x18\x02 \x01(\tR\tdirectory\x12\x12\n" +
|
||||
@@ -7414,7 +7437,7 @@ const file_filer_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"error_code\x18\x03 \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\x12\x1a\n" +
|
||||
"\tlog_ts_ns\x18\x04 \x01(\x03R\alogTsNs\x12#\n" +
|
||||
"\rlog_signature\x18\x05 \x01(\x05R\flogSignature\"\x8a\x03\n" +
|
||||
"\rlog_signature\x18\x05 \x01(\x05R\flogSignature\"\xa5\x03\n" +
|
||||
"\x12UpdateEntryRequest\x12\x1c\n" +
|
||||
"\tdirectory\x18\x01 \x01(\tR\tdirectory\x12%\n" +
|
||||
"\x05entry\x18\x02 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x121\n" +
|
||||
@@ -7423,7 +7446,8 @@ const file_filer_proto_rawDesc = "" +
|
||||
"signatures\x18\x04 \x03(\x05R\n" +
|
||||
"signatures\x12_\n" +
|
||||
"\x11expected_extended\x18\x05 \x03(\v22.filer_pb.UpdateEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x126\n" +
|
||||
"\tcondition\x18\x06 \x01(\v2\x18.filer_pb.WriteConditionR\tcondition\x1aC\n" +
|
||||
"\tcondition\x18\x06 \x01(\v2\x18.filer_pb.WriteConditionR\tcondition\x12\x19\n" +
|
||||
"\bis_moved\x18\a \x01(\bR\aisMoved\x1aC\n" +
|
||||
"\x15ExpectedExtendedEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"\xa2\x01\n" +
|
||||
@@ -8072,83 +8096,84 @@ var file_filer_proto_depIdxs = []int32{
|
||||
107, // 67: filer_pb.LookupDirectoryEntriesResponse.locations_map:type_name -> filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry
|
||||
108, // 68: filer_pb.LookupDirectoryEntriesResponse.read_auth:type_name -> filer_pb.LookupDirectoryEntriesResponse.ReadAuthEntry
|
||||
3, // 69: filer_pb.WriteCondition.Clause.kind:type_name -> filer_pb.WriteCondition.Kind
|
||||
44, // 70: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
44, // 71: filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
5, // 72: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
|
||||
96, // 73: filer_pb.SeaweedFiler.LookupDirectoryEntries:input_type -> filer_pb.LookupDirectoryEntriesRequest
|
||||
7, // 74: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
|
||||
17, // 75: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
|
||||
29, // 76: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
|
||||
31, // 77: filer_pb.SeaweedFiler.TouchAccessTime:input_type -> filer_pb.TouchAccessTimeRequest
|
||||
33, // 78: filer_pb.SeaweedFiler.AppendToEntry:input_type -> filer_pb.AppendToEntryRequest
|
||||
35, // 79: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
|
||||
21, // 80: filer_pb.SeaweedFiler.ObjectTransaction:input_type -> filer_pb.ObjectTransactionRequest
|
||||
26, // 81: filer_pb.SeaweedFiler.ObjectTransactionBatch:input_type -> filer_pb.ObjectTransactionBatchRequest
|
||||
24, // 82: filer_pb.SeaweedFiler.PosixLock:input_type -> filer_pb.PosixLockRequest
|
||||
37, // 83: filer_pb.SeaweedFiler.AtomicRenameEntry:input_type -> filer_pb.AtomicRenameEntryRequest
|
||||
39, // 84: filer_pb.SeaweedFiler.StreamRenameEntry:input_type -> filer_pb.StreamRenameEntryRequest
|
||||
89, // 85: filer_pb.SeaweedFiler.StreamMutateEntry:input_type -> filer_pb.StreamMutateEntryRequest
|
||||
41, // 86: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
|
||||
43, // 87: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
|
||||
48, // 88: filer_pb.SeaweedFiler.CollectionList:input_type -> filer_pb.CollectionListRequest
|
||||
50, // 89: filer_pb.SeaweedFiler.DeleteCollection:input_type -> filer_pb.DeleteCollectionRequest
|
||||
52, // 90: filer_pb.SeaweedFiler.Statistics:input_type -> filer_pb.StatisticsRequest
|
||||
54, // 91: filer_pb.SeaweedFiler.Ping:input_type -> filer_pb.PingRequest
|
||||
56, // 92: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
|
||||
64, // 93: filer_pb.SeaweedFiler.TraverseBfsMetadata:input_type -> filer_pb.TraverseBfsMetadataRequest
|
||||
58, // 94: filer_pb.SeaweedFiler.SubscribeMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
58, // 95: filer_pb.SeaweedFiler.SubscribeLocalMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
60, // 96: filer_pb.SeaweedFiler.ListMetadataSubscribers:input_type -> filer_pb.ListMetadataSubscribersRequest
|
||||
71, // 97: filer_pb.SeaweedFiler.KvGet:input_type -> filer_pb.KvGetRequest
|
||||
73, // 98: filer_pb.SeaweedFiler.KvPut:input_type -> filer_pb.KvPutRequest
|
||||
76, // 99: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:input_type -> filer_pb.CacheRemoteObjectToLocalClusterRequest
|
||||
78, // 100: filer_pb.SeaweedFiler.DistributedLock:input_type -> filer_pb.LockRequest
|
||||
80, // 101: filer_pb.SeaweedFiler.DistributedUnlock:input_type -> filer_pb.UnlockRequest
|
||||
82, // 102: filer_pb.SeaweedFiler.FindLockOwner:input_type -> filer_pb.FindLockOwnerRequest
|
||||
85, // 103: filer_pb.SeaweedFiler.TransferLocks:input_type -> filer_pb.TransferLocksRequest
|
||||
87, // 104: filer_pb.SeaweedFiler.ReplicateLock:input_type -> filer_pb.ReplicateLockRequest
|
||||
91, // 105: filer_pb.SeaweedFiler.MountRegister:input_type -> filer_pb.MountRegisterRequest
|
||||
93, // 106: filer_pb.SeaweedFiler.MountList:input_type -> filer_pb.MountListRequest
|
||||
6, // 107: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
|
||||
98, // 108: filer_pb.SeaweedFiler.LookupDirectoryEntries:output_type -> filer_pb.LookupDirectoryEntriesResponse
|
||||
8, // 109: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
|
||||
28, // 110: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
|
||||
30, // 111: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
|
||||
32, // 112: filer_pb.SeaweedFiler.TouchAccessTime:output_type -> filer_pb.TouchAccessTimeResponse
|
||||
34, // 113: filer_pb.SeaweedFiler.AppendToEntry:output_type -> filer_pb.AppendToEntryResponse
|
||||
36, // 114: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
|
||||
22, // 115: filer_pb.SeaweedFiler.ObjectTransaction:output_type -> filer_pb.ObjectTransactionResponse
|
||||
27, // 116: filer_pb.SeaweedFiler.ObjectTransactionBatch:output_type -> filer_pb.ObjectTransactionBatchResponse
|
||||
25, // 117: filer_pb.SeaweedFiler.PosixLock:output_type -> filer_pb.PosixLockResponse
|
||||
38, // 118: filer_pb.SeaweedFiler.AtomicRenameEntry:output_type -> filer_pb.AtomicRenameEntryResponse
|
||||
40, // 119: filer_pb.SeaweedFiler.StreamRenameEntry:output_type -> filer_pb.StreamRenameEntryResponse
|
||||
90, // 120: filer_pb.SeaweedFiler.StreamMutateEntry:output_type -> filer_pb.StreamMutateEntryResponse
|
||||
42, // 121: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
|
||||
46, // 122: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
|
||||
49, // 123: filer_pb.SeaweedFiler.CollectionList:output_type -> filer_pb.CollectionListResponse
|
||||
51, // 124: filer_pb.SeaweedFiler.DeleteCollection:output_type -> filer_pb.DeleteCollectionResponse
|
||||
53, // 125: filer_pb.SeaweedFiler.Statistics:output_type -> filer_pb.StatisticsResponse
|
||||
55, // 126: filer_pb.SeaweedFiler.Ping:output_type -> filer_pb.PingResponse
|
||||
57, // 127: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
|
||||
65, // 128: filer_pb.SeaweedFiler.TraverseBfsMetadata:output_type -> filer_pb.TraverseBfsMetadataResponse
|
||||
59, // 129: filer_pb.SeaweedFiler.SubscribeMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
59, // 130: filer_pb.SeaweedFiler.SubscribeLocalMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
61, // 131: filer_pb.SeaweedFiler.ListMetadataSubscribers:output_type -> filer_pb.ListMetadataSubscribersResponse
|
||||
72, // 132: filer_pb.SeaweedFiler.KvGet:output_type -> filer_pb.KvGetResponse
|
||||
74, // 133: filer_pb.SeaweedFiler.KvPut:output_type -> filer_pb.KvPutResponse
|
||||
77, // 134: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:output_type -> filer_pb.CacheRemoteObjectToLocalClusterResponse
|
||||
79, // 135: filer_pb.SeaweedFiler.DistributedLock:output_type -> filer_pb.LockResponse
|
||||
81, // 136: filer_pb.SeaweedFiler.DistributedUnlock:output_type -> filer_pb.UnlockResponse
|
||||
83, // 137: filer_pb.SeaweedFiler.FindLockOwner:output_type -> filer_pb.FindLockOwnerResponse
|
||||
86, // 138: filer_pb.SeaweedFiler.TransferLocks:output_type -> filer_pb.TransferLocksResponse
|
||||
88, // 139: filer_pb.SeaweedFiler.ReplicateLock:output_type -> filer_pb.ReplicateLockResponse
|
||||
92, // 140: filer_pb.SeaweedFiler.MountRegister:output_type -> filer_pb.MountRegisterResponse
|
||||
94, // 141: filer_pb.SeaweedFiler.MountList:output_type -> filer_pb.MountListResponse
|
||||
107, // [107:142] is the sub-list for method output_type
|
||||
72, // [72:107] is the sub-list for method input_type
|
||||
72, // [72:72] is the sub-list for extension type_name
|
||||
72, // [72:72] is the sub-list for extension extendee
|
||||
0, // [0:72] is the sub-list for field type_name
|
||||
10, // 70: filer_pb.WriteCondition.Clause.expected_entry:type_name -> filer_pb.Entry
|
||||
44, // 71: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
44, // 72: filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
5, // 73: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
|
||||
96, // 74: filer_pb.SeaweedFiler.LookupDirectoryEntries:input_type -> filer_pb.LookupDirectoryEntriesRequest
|
||||
7, // 75: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
|
||||
17, // 76: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
|
||||
29, // 77: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
|
||||
31, // 78: filer_pb.SeaweedFiler.TouchAccessTime:input_type -> filer_pb.TouchAccessTimeRequest
|
||||
33, // 79: filer_pb.SeaweedFiler.AppendToEntry:input_type -> filer_pb.AppendToEntryRequest
|
||||
35, // 80: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
|
||||
21, // 81: filer_pb.SeaweedFiler.ObjectTransaction:input_type -> filer_pb.ObjectTransactionRequest
|
||||
26, // 82: filer_pb.SeaweedFiler.ObjectTransactionBatch:input_type -> filer_pb.ObjectTransactionBatchRequest
|
||||
24, // 83: filer_pb.SeaweedFiler.PosixLock:input_type -> filer_pb.PosixLockRequest
|
||||
37, // 84: filer_pb.SeaweedFiler.AtomicRenameEntry:input_type -> filer_pb.AtomicRenameEntryRequest
|
||||
39, // 85: filer_pb.SeaweedFiler.StreamRenameEntry:input_type -> filer_pb.StreamRenameEntryRequest
|
||||
89, // 86: filer_pb.SeaweedFiler.StreamMutateEntry:input_type -> filer_pb.StreamMutateEntryRequest
|
||||
41, // 87: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
|
||||
43, // 88: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
|
||||
48, // 89: filer_pb.SeaweedFiler.CollectionList:input_type -> filer_pb.CollectionListRequest
|
||||
50, // 90: filer_pb.SeaweedFiler.DeleteCollection:input_type -> filer_pb.DeleteCollectionRequest
|
||||
52, // 91: filer_pb.SeaweedFiler.Statistics:input_type -> filer_pb.StatisticsRequest
|
||||
54, // 92: filer_pb.SeaweedFiler.Ping:input_type -> filer_pb.PingRequest
|
||||
56, // 93: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
|
||||
64, // 94: filer_pb.SeaweedFiler.TraverseBfsMetadata:input_type -> filer_pb.TraverseBfsMetadataRequest
|
||||
58, // 95: filer_pb.SeaweedFiler.SubscribeMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
58, // 96: filer_pb.SeaweedFiler.SubscribeLocalMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
60, // 97: filer_pb.SeaweedFiler.ListMetadataSubscribers:input_type -> filer_pb.ListMetadataSubscribersRequest
|
||||
71, // 98: filer_pb.SeaweedFiler.KvGet:input_type -> filer_pb.KvGetRequest
|
||||
73, // 99: filer_pb.SeaweedFiler.KvPut:input_type -> filer_pb.KvPutRequest
|
||||
76, // 100: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:input_type -> filer_pb.CacheRemoteObjectToLocalClusterRequest
|
||||
78, // 101: filer_pb.SeaweedFiler.DistributedLock:input_type -> filer_pb.LockRequest
|
||||
80, // 102: filer_pb.SeaweedFiler.DistributedUnlock:input_type -> filer_pb.UnlockRequest
|
||||
82, // 103: filer_pb.SeaweedFiler.FindLockOwner:input_type -> filer_pb.FindLockOwnerRequest
|
||||
85, // 104: filer_pb.SeaweedFiler.TransferLocks:input_type -> filer_pb.TransferLocksRequest
|
||||
87, // 105: filer_pb.SeaweedFiler.ReplicateLock:input_type -> filer_pb.ReplicateLockRequest
|
||||
91, // 106: filer_pb.SeaweedFiler.MountRegister:input_type -> filer_pb.MountRegisterRequest
|
||||
93, // 107: filer_pb.SeaweedFiler.MountList:input_type -> filer_pb.MountListRequest
|
||||
6, // 108: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
|
||||
98, // 109: filer_pb.SeaweedFiler.LookupDirectoryEntries:output_type -> filer_pb.LookupDirectoryEntriesResponse
|
||||
8, // 110: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
|
||||
28, // 111: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
|
||||
30, // 112: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
|
||||
32, // 113: filer_pb.SeaweedFiler.TouchAccessTime:output_type -> filer_pb.TouchAccessTimeResponse
|
||||
34, // 114: filer_pb.SeaweedFiler.AppendToEntry:output_type -> filer_pb.AppendToEntryResponse
|
||||
36, // 115: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
|
||||
22, // 116: filer_pb.SeaweedFiler.ObjectTransaction:output_type -> filer_pb.ObjectTransactionResponse
|
||||
27, // 117: filer_pb.SeaweedFiler.ObjectTransactionBatch:output_type -> filer_pb.ObjectTransactionBatchResponse
|
||||
25, // 118: filer_pb.SeaweedFiler.PosixLock:output_type -> filer_pb.PosixLockResponse
|
||||
38, // 119: filer_pb.SeaweedFiler.AtomicRenameEntry:output_type -> filer_pb.AtomicRenameEntryResponse
|
||||
40, // 120: filer_pb.SeaweedFiler.StreamRenameEntry:output_type -> filer_pb.StreamRenameEntryResponse
|
||||
90, // 121: filer_pb.SeaweedFiler.StreamMutateEntry:output_type -> filer_pb.StreamMutateEntryResponse
|
||||
42, // 122: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
|
||||
46, // 123: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
|
||||
49, // 124: filer_pb.SeaweedFiler.CollectionList:output_type -> filer_pb.CollectionListResponse
|
||||
51, // 125: filer_pb.SeaweedFiler.DeleteCollection:output_type -> filer_pb.DeleteCollectionResponse
|
||||
53, // 126: filer_pb.SeaweedFiler.Statistics:output_type -> filer_pb.StatisticsResponse
|
||||
55, // 127: filer_pb.SeaweedFiler.Ping:output_type -> filer_pb.PingResponse
|
||||
57, // 128: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
|
||||
65, // 129: filer_pb.SeaweedFiler.TraverseBfsMetadata:output_type -> filer_pb.TraverseBfsMetadataResponse
|
||||
59, // 130: filer_pb.SeaweedFiler.SubscribeMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
59, // 131: filer_pb.SeaweedFiler.SubscribeLocalMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
61, // 132: filer_pb.SeaweedFiler.ListMetadataSubscribers:output_type -> filer_pb.ListMetadataSubscribersResponse
|
||||
72, // 133: filer_pb.SeaweedFiler.KvGet:output_type -> filer_pb.KvGetResponse
|
||||
74, // 134: filer_pb.SeaweedFiler.KvPut:output_type -> filer_pb.KvPutResponse
|
||||
77, // 135: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:output_type -> filer_pb.CacheRemoteObjectToLocalClusterResponse
|
||||
79, // 136: filer_pb.SeaweedFiler.DistributedLock:output_type -> filer_pb.LockResponse
|
||||
81, // 137: filer_pb.SeaweedFiler.DistributedUnlock:output_type -> filer_pb.UnlockResponse
|
||||
83, // 138: filer_pb.SeaweedFiler.FindLockOwner:output_type -> filer_pb.FindLockOwnerResponse
|
||||
86, // 139: filer_pb.SeaweedFiler.TransferLocks:output_type -> filer_pb.TransferLocksResponse
|
||||
88, // 140: filer_pb.SeaweedFiler.ReplicateLock:output_type -> filer_pb.ReplicateLockResponse
|
||||
92, // 141: filer_pb.SeaweedFiler.MountRegister:output_type -> filer_pb.MountRegisterResponse
|
||||
94, // 142: filer_pb.SeaweedFiler.MountList:output_type -> filer_pb.MountListResponse
|
||||
108, // [108:143] is the sub-list for method output_type
|
||||
73, // [73:108] is the sub-list for method input_type
|
||||
73, // [73:73] is the sub-list for extension type_name
|
||||
73, // [73:73] is the sub-list for extension extendee
|
||||
0, // [0:73] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_filer_proto_init() }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v7.35.0
|
||||
// - protoc v3.21.12
|
||||
// source: filer.proto
|
||||
|
||||
package filer_pb
|
||||
|
||||
@@ -1135,6 +1135,16 @@ func (m *WriteCondition_Clause) MarshalToSizedBufferVT(dAtA []byte) (int, error)
|
||||
i -= len(m.unknownFields)
|
||||
copy(dAtA[i:], m.unknownFields)
|
||||
}
|
||||
if m.ExpectedEntry != nil {
|
||||
size, err := m.ExpectedEntry.MarshalToSizedBufferVT(dAtA[:i])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
i -= size
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(size))
|
||||
i--
|
||||
dAtA[i] = 0x52
|
||||
}
|
||||
if len(m.Fids) > 0 {
|
||||
for iNdEx := len(m.Fids) - 1; iNdEx >= 0; iNdEx-- {
|
||||
i -= len(m.Fids[iNdEx])
|
||||
@@ -2087,6 +2097,16 @@ func (m *UpdateEntryRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
|
||||
i -= len(m.unknownFields)
|
||||
copy(dAtA[i:], m.unknownFields)
|
||||
}
|
||||
if m.IsMoved {
|
||||
i--
|
||||
if m.IsMoved {
|
||||
dAtA[i] = 1
|
||||
} else {
|
||||
dAtA[i] = 0
|
||||
}
|
||||
i--
|
||||
dAtA[i] = 0x38
|
||||
}
|
||||
if m.Condition != nil {
|
||||
size, err := m.Condition.MarshalToSizedBufferVT(dAtA[:i])
|
||||
if err != nil {
|
||||
@@ -6958,6 +6978,10 @@ func (m *WriteCondition_Clause) SizeVT() (n int) {
|
||||
n += 1 + l + protohelpers.SizeOfVarint(uint64(l))
|
||||
}
|
||||
}
|
||||
if m.ExpectedEntry != nil {
|
||||
l = m.ExpectedEntry.SizeVT()
|
||||
n += 1 + l + protohelpers.SizeOfVarint(uint64(l))
|
||||
}
|
||||
n += len(m.unknownFields)
|
||||
return n
|
||||
}
|
||||
@@ -7332,6 +7356,9 @@ func (m *UpdateEntryRequest) SizeVT() (n int) {
|
||||
l = m.Condition.SizeVT()
|
||||
n += 1 + l + protohelpers.SizeOfVarint(uint64(l))
|
||||
}
|
||||
if m.IsMoved {
|
||||
n += 2
|
||||
}
|
||||
n += len(m.unknownFields)
|
||||
return n
|
||||
}
|
||||
@@ -12374,6 +12401,42 @@ func (m *WriteCondition_Clause) UnmarshalVT(dAtA []byte) error {
|
||||
}
|
||||
m.Fids = append(m.Fids, string(dAtA[iNdEx:postIndex]))
|
||||
iNdEx = postIndex
|
||||
case 10:
|
||||
if wireType != 2 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field ExpectedEntry", wireType)
|
||||
}
|
||||
var msglen int
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
msglen |= int(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if msglen < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
postIndex := iNdEx + msglen
|
||||
if postIndex < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
if postIndex > l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
if m.ExpectedEntry == nil {
|
||||
m.ExpectedEntry = &Entry{}
|
||||
}
|
||||
if err := m.ExpectedEntry.UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
|
||||
return err
|
||||
}
|
||||
iNdEx = postIndex
|
||||
default:
|
||||
iNdEx = preIndex
|
||||
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
|
||||
@@ -15067,6 +15130,26 @@ func (m *UpdateEntryRequest) UnmarshalVT(dAtA []byte) error {
|
||||
return err
|
||||
}
|
||||
iNdEx = postIndex
|
||||
case 7:
|
||||
if wireType != 0 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field IsMoved", wireType)
|
||||
}
|
||||
var v int
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
v |= int(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
m.IsMoved = bool(v != 0)
|
||||
default:
|
||||
iNdEx = preIndex
|
||||
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
|
||||
|
||||
@@ -259,6 +259,10 @@ 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 {
|
||||
}
|
||||
|
||||
@@ -1468,8 +1468,11 @@ 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"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
// when true, delete only if every needle is deleted: the volume held
|
||||
// data once but nothing is live anymore.
|
||||
OnlyGarbage bool `protobuf:"varint,4,opt,name=only_garbage,json=onlyGarbage,proto3" json:"only_garbage,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VolumeDeleteRequest) Reset() {
|
||||
@@ -1523,6 +1526,13 @@ 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
|
||||
@@ -7324,12 +7334,13 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\x15VolumeUnmountResponse\"<\n" +
|
||||
"\x1dVolumeConsolidateIndexRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\" \n" +
|
||||
"\x1eVolumeConsolidateIndexResponse\"{\n" +
|
||||
"\x1eVolumeConsolidateIndexResponse\"\x9e\x01\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\"\x16\n" +
|
||||
"\x10keep_remote_data\x18\x03 \x01(\bR\x0ekeepRemoteData\x12!\n" +
|
||||
"\fonly_garbage\x18\x04 \x01(\bR\vonlyGarbage\"\x16\n" +
|
||||
"\x14VolumeDeleteResponse\"q\n" +
|
||||
"\x19VolumeMarkReadonlyRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x18\n" +
|
||||
|
||||
@@ -14,15 +14,19 @@ 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 {
|
||||
syncKey := []byte(SyncKeyPrefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(SyncKeyPrefix):len(SyncKeyPrefix)+4], dirHash)
|
||||
|
||||
resp, err := client.KvGet(context.Background(), &filer_pb.KvGetRequest{Key: syncKey})
|
||||
resp, err := client.KvGet(context.Background(), &filer_pb.KvGetRequest{Key: SyncOffsetKey(dir)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -45,18 +49,13 @@ 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: syncKey,
|
||||
Key: SyncOffsetKey(dir),
|
||||
Value: valueBuf,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -1388,7 +1388,15 @@ func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListP
|
||||
StorageClass: aws.String("STANDARD"),
|
||||
}
|
||||
|
||||
entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d%s", *input.PartNumberMarker, multipartExt), false, uint32(*input.MaxParts))
|
||||
// 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))
|
||||
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.
|
||||
@@ -1411,6 +1419,10 @@ 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{
|
||||
@@ -1428,6 +1440,12 @@ 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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
+68
-10
@@ -3,6 +3,7 @@ package lance
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
@@ -23,6 +24,18 @@ 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
|
||||
@@ -40,12 +53,13 @@ type CredentialVendor interface {
|
||||
|
||||
// Server implements the Lance Namespace REST spec.
|
||||
type Server struct {
|
||||
filerClient FilerClient
|
||||
tablesManager *s3tables.Manager
|
||||
authenticator S3Authenticator
|
||||
credentialVendor CredentialVendor
|
||||
s3Endpoint string
|
||||
s3Region string
|
||||
filerClient FilerClient
|
||||
tablesManager *s3tables.Manager
|
||||
authenticator S3Authenticator
|
||||
credentialValidator CredentialValidator
|
||||
credentialVendor CredentialVendor
|
||||
s3Endpoint string
|
||||
s3Region string
|
||||
}
|
||||
|
||||
// NewServer creates a Lance namespace server over the given filer.
|
||||
@@ -63,6 +77,11 @@ 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) {
|
||||
@@ -87,6 +106,9 @@ 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)
|
||||
@@ -124,7 +146,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.RequestURI)
|
||||
glog.V(2).Infof("lance: no route for %s %s", r.Method, r.URL.EscapedPath())
|
||||
writeError(w, r, http.StatusNotFound, codeUnsupported, "no such operation")
|
||||
})
|
||||
|
||||
@@ -138,16 +160,52 @@ 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.RequestURI, r.RemoteAddr)
|
||||
glog.V(2).Infof("lance request: %s %s from %s", r.Method, r.URL.EscapedPath(), r.RemoteAddr)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Auth authenticates the caller and puts the identity in the request context.
|
||||
// The Lance spec maps identity onto the same headers the S3 authenticator
|
||||
// already understands, so SigV4 and bearer tokens both keep working.
|
||||
// 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.
|
||||
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,6 +33,20 @@ func ResolveS3Action(r *http.Request, baseAction string, bucket string, object s
|
||||
return baseAction
|
||||
}
|
||||
|
||||
// Object Lock actions are checked on top of another operation's request
|
||||
// shape (e.g. BypassGovernanceRetention on a versioned DELETE), so the
|
||||
// shape must not re-derive them.
|
||||
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
|
||||
|
||||
@@ -114,6 +114,89 @@ func TestResolveS3Action_AttributesBeforeVersionId(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveS3Action_ObjectLockActionsIgnoreRequestShape(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
method string
|
||||
baseAction string
|
||||
object string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "bypass on versioned delete",
|
||||
query: "versionId=abc123",
|
||||
method: http.MethodDelete,
|
||||
baseAction: s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_BYPASS_GOVERNANCE,
|
||||
},
|
||||
{
|
||||
name: "bypass on batch delete",
|
||||
query: "delete",
|
||||
method: http.MethodPost,
|
||||
baseAction: s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_BYPASS_GOVERNANCE,
|
||||
},
|
||||
{
|
||||
name: "get retention with versionId",
|
||||
query: "retention&versionId=abc123",
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_GET_OBJECT_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_RETENTION,
|
||||
},
|
||||
{
|
||||
name: "get legal hold with versionId",
|
||||
query: "legal-hold&versionId=abc123",
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD,
|
||||
},
|
||||
{
|
||||
name: "put retention with versionId",
|
||||
query: "retention&versionId=abc123",
|
||||
method: http.MethodPut,
|
||||
baseAction: s3_constants.ACTION_PUT_OBJECT_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_PUT_OBJECT_RETENTION,
|
||||
},
|
||||
{
|
||||
name: "put legal hold with versionId",
|
||||
query: "legal-hold&versionId=abc123",
|
||||
method: http.MethodPut,
|
||||
baseAction: s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD,
|
||||
},
|
||||
{
|
||||
name: "get bucket object lock config",
|
||||
query: "object-lock",
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG,
|
||||
want: s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK,
|
||||
},
|
||||
{
|
||||
name: "put bucket object lock config",
|
||||
query: "object-lock",
|
||||
method: http.MethodPut,
|
||||
baseAction: s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG,
|
||||
want: 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Bucket subresources registered with ACTION_ADMIN must resolve to their own
|
||||
// S3 actions so a policy granting one of them does not need s3:*, and so no
|
||||
// broader grant sweeps them in.
|
||||
|
||||
@@ -34,20 +34,12 @@ import (
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// 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
|
||||
)
|
||||
// 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
|
||||
|
||||
func (s3a *S3ApiServer) ListBucketsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -479,11 +471,8 @@ func (s3a *S3ApiServer) DeleteBucketHandler(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// The filer resolves and drops the bucket's collection inside the delete;
|
||||
// it keeps a shared one rather than risk another bucket's volumes.
|
||||
err := s3a.rm(r.Context(), s3a.option.BucketsPath, bucket, false, true)
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -496,36 +485,6 @@ 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)
|
||||
@@ -909,18 +868,24 @@ 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 ACLs or bucket policies
|
||||
// For anonymous requests, check if bucket allows public read via bucket policies or ACLs
|
||||
if isAnonymous {
|
||||
// First check ACL-based public access
|
||||
// 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.
|
||||
isPublic := s3a.isBucketPublicRead(bucket)
|
||||
glog.V(4).Infof("AuthWithPublicRead: bucket=%s, isPublicACL=%v", bucket, isPublic)
|
||||
if 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 != "" {
|
||||
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)
|
||||
@@ -944,7 +909,13 @@ func (s3a *S3ApiServer) AuthWithPublicRead(handler http.HandlerFunc, action Acti
|
||||
return
|
||||
}
|
||||
}
|
||||
// No matching policy statement - fall through to check ACLs and then IAM auth
|
||||
|
||||
// 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
|
||||
}
|
||||
glog.V(3).Infof("AuthWithPublicRead: no bucket policy match for %s, checking ACLs", bucket)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package s3api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -13,6 +14,7 @@ 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 {
|
||||
@@ -308,3 +310,56 @@ 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,6 +2,8 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
@@ -42,10 +44,26 @@ 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
|
||||
for _, entry := range f.parts {
|
||||
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
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -150,3 +168,113 @@ 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,6 +508,10 @@ 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
|
||||
|
||||
@@ -385,7 +385,11 @@ func (s3a *S3ApiServer) withObjectWriteLock(bucket, object string, preconditionF
|
||||
return fn()
|
||||
}
|
||||
|
||||
lock := s3a.newObjectWriteLock(bucket, object)
|
||||
lock, err := s3a.newObjectWriteLock(bucket, object)
|
||||
if err != nil {
|
||||
glog.Warningf("withObjectWriteLock: %v", err)
|
||||
return s3err.ErrServiceUnavailable
|
||||
}
|
||||
if lock == nil {
|
||||
if errCode := runPrecondition(); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
|
||||
@@ -2,6 +2,7 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
@@ -55,6 +56,38 @@ func TestGovernanceBypassUsesDedicatedAuthorization(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGovernanceBypassChecksBypassActionOnVersionedDelete(t *testing.T) {
|
||||
arn := "arn:aws:s3:::test-bucket/test-object"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
policyAction string
|
||||
allowed bool
|
||||
}{
|
||||
{"bypass permission", "s3:BypassGovernanceRetention", true},
|
||||
{"delete version only", "s3:DeleteObjectVersion", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
iam := newTestIAM()
|
||||
iam.identities[0].Actions = nil
|
||||
iam.identities[0].Account = &Account{Id: "test-account"}
|
||||
iam.policyEngine = NewBucketPolicyEngine()
|
||||
policy := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"%s","Resource":"%s"}]}`,
|
||||
tc.policyAction, arn)
|
||||
require.NoError(t, iam.policyEngine.engine.SetBucketPolicy("test-bucket", policy))
|
||||
s3a := &S3ApiServer{iam: iam}
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "http://localhost:8333/test-bucket/test-object?versionId=v1", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "test-bucket", "object": "test-object"})
|
||||
require.NoError(t, signRawHTTPRequest(context.Background(), req,
|
||||
"AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "us-east-1"))
|
||||
|
||||
if got := s3a.checkGovernanceBypassPermission(req, "test-bucket", "/test-object"); got != tc.allowed {
|
||||
t.Errorf("checkGovernanceBypassPermission() = %v, want %v", got, tc.allowed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGovernanceBypassUsesBodyObjectKey(t *testing.T) {
|
||||
iam := newTestIAM()
|
||||
iam.identities[0].Actions = []Action{
|
||||
|
||||
@@ -108,7 +108,7 @@ type S3ApiServer struct {
|
||||
icebergCredentialRole string
|
||||
icebergCredentialDuration int64
|
||||
cipher bool // encrypt data on volume servers
|
||||
newObjectWriteLock func(bucket, object string) objectWriteLock
|
||||
newObjectWriteLock func(bucket, object string) (objectWriteLock, error)
|
||||
// objectWriteLockClient resolves a key's owner filer for route-by-key.
|
||||
objectWriteLockClient *cluster.LockClient
|
||||
// unreachableOwners holds owners (pb.ServerAddress -> expiry time.Time) whose
|
||||
@@ -225,6 +225,9 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
}
|
||||
objectWriteLockClient.SetRing(servers, update.Version)
|
||||
})
|
||||
masterClient.SetOnMasterChangeFn(func(previous, current pb.ServerAddress) {
|
||||
objectWriteLockClient.ResetRing()
|
||||
})
|
||||
}
|
||||
// Start the master client connection loop - required for GetMaster() to work
|
||||
go masterClient.KeepConnectedToMaster(context.Background())
|
||||
@@ -345,16 +348,19 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
objectWriteLockClient = cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
}
|
||||
s3ApiServer.objectWriteLockClient = objectWriteLockClient
|
||||
s3ApiServer.newObjectWriteLock = func(bucket, object string) objectWriteLock {
|
||||
s3ApiServer.newObjectWriteLock = func(bucket, object string) (objectWriteLock, error) {
|
||||
lockKey := objectWriteRouteKeyPrefix + s3ApiServer.toFilerPath(bucket, object)
|
||||
owner := fmt.Sprintf("s3api-%d", s3ApiServer.randomClientId)
|
||||
lock := objectWriteLockClient.NewShortLivedLock(lockKey, owner)
|
||||
if lock == nil {
|
||||
return nil, fmt.Errorf("objectWriteLock: failed to acquire lock for %s", lockKey)
|
||||
}
|
||||
if err := lock.AttemptToLock(objectWriteLockTTL); err != nil {
|
||||
// The initial acquisition already succeeded with the default short TTL.
|
||||
// Renewal to a longer TTL is opportunistic to cover slower metadata paths.
|
||||
glog.Warningf("objectWriteLock: failed to extend lock TTL for %s: %v", lockKey, err)
|
||||
}
|
||||
return lock
|
||||
return lock, nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -161,7 +161,7 @@ func LoadClientTLSFromFile(configFile string, component string) (grpc.DialOption
|
||||
v.Set(key, filepath.Join(configDir, p))
|
||||
}
|
||||
}
|
||||
return LoadClientTLS(&util.ViperProxy{Viper: v}, component), nil
|
||||
return LoadClientTLS(util.NewViperProxy(v), component), nil
|
||||
}
|
||||
|
||||
func LoadClientTLS(config *util.ViperProxy, component string) grpc.DialOption {
|
||||
|
||||
@@ -134,7 +134,7 @@ func TestLoadClientTLSPrefersClientCert(t *testing.T) {
|
||||
serverCert, serverKey := ca.issue(t, dir, "server", []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth})
|
||||
clientCert, clientKey := ca.issue(t, dir, "client", []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth})
|
||||
|
||||
v := &util.ViperProxy{Viper: viper.New()}
|
||||
v := util.NewViperProxy(viper.New())
|
||||
v.Set("grpc.ca", ca.file)
|
||||
v.Set("grpc.master.cert", serverCert)
|
||||
v.Set("grpc.master.key", serverKey)
|
||||
@@ -153,7 +153,7 @@ func TestLoadClientTLSFallsBackToServingCert(t *testing.T) {
|
||||
ca := newTestCA(t, dir)
|
||||
dualCert, dualKey := ca.issue(t, dir, "dual", []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth})
|
||||
|
||||
v := &util.ViperProxy{Viper: viper.New()}
|
||||
v := util.NewViperProxy(viper.New())
|
||||
v.Set("grpc.ca", ca.file)
|
||||
v.Set("grpc.master.cert", dualCert)
|
||||
v.Set("grpc.master.key", dualKey)
|
||||
@@ -171,7 +171,7 @@ func TestLoadClientTLSServerOnlyEkuRejected(t *testing.T) {
|
||||
ca := newTestCA(t, dir)
|
||||
serverCert, serverKey := ca.issue(t, dir, "server", []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth})
|
||||
|
||||
v := &util.ViperProxy{Viper: viper.New()}
|
||||
v := util.NewViperProxy(viper.New())
|
||||
v.Set("grpc.ca", ca.file)
|
||||
v.Set("grpc.master.cert", serverCert)
|
||||
v.Set("grpc.master.key", serverKey)
|
||||
|
||||
+36
-6
@@ -288,12 +288,32 @@ func adjustHeaderContentDisposition(w http.ResponseWriter, r *http.Request, file
|
||||
}
|
||||
}
|
||||
|
||||
// responseBodyTracker records how many bytes have reached the ResponseWriter.
|
||||
// Bytes still sitting in the pooled bufio.Writer do not count: the status line
|
||||
// is not committed until the buffer flushes.
|
||||
type responseBodyTracker struct {
|
||||
http.ResponseWriter
|
||||
written int64
|
||||
}
|
||||
|
||||
func (t *responseBodyTracker) Write(p []byte) (int, error) {
|
||||
n, err := t.ResponseWriter.Write(p)
|
||||
t.written += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64, mimeType string, prepareWriteFn func(offset int64, size int64) (filer.DoStreamContent, error)) error {
|
||||
rangeReq := r.Header.Get("Range")
|
||||
sink := &responseBodyTracker{ResponseWriter: w}
|
||||
bufferedWriter := writePool.Get().(*bufio.Writer)
|
||||
bufferedWriter.Reset(w)
|
||||
bufferedWriter.Reset(sink)
|
||||
discardBuffered := false
|
||||
defer func() {
|
||||
bufferedWriter.Flush()
|
||||
if discardBuffered {
|
||||
bufferedWriter.Reset(io.Discard)
|
||||
} else {
|
||||
bufferedWriter.Flush()
|
||||
}
|
||||
writePool.Put(bufferedWriter)
|
||||
}()
|
||||
|
||||
@@ -306,6 +326,13 @@ func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64
|
||||
}
|
||||
if err = writeFn(bufferedWriter); err != nil {
|
||||
glog.Errorf("ProcessRangeRequest: %v", err)
|
||||
// Drop the unflushed tail: flushing it would finish a 200 whose
|
||||
// Content-Length is already set, delivering corrupt bytes as a
|
||||
// complete body.
|
||||
discardBuffered = true
|
||||
if sink.written > 0 {
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
w.Header().Del("Content-Length")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return fmt.Errorf("ProcessRangeRequest: %w", err)
|
||||
@@ -359,8 +386,10 @@ func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64
|
||||
err = writeFn(bufferedWriter)
|
||||
if err != nil {
|
||||
glog.Errorf("ProcessRangeRequest range[0]: %+v err: %v", w.Header(), err)
|
||||
// Cannot call http.Error() here because WriteHeader was already called
|
||||
return fmt.Errorf("ProcessRangeRequest range[0]: %w", err)
|
||||
// WriteHeader was already called: drop the unflushed tail and
|
||||
// abort so the client does not read corrupt bytes as a full body.
|
||||
discardBuffered = true
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -412,8 +441,9 @@ func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
if _, err := io.CopyN(bufferedWriter, sendContent, sendSize); err != nil {
|
||||
glog.Errorf("ProcessRangeRequest err: %v", err)
|
||||
// Cannot call http.Error() here because WriteHeader was already called
|
||||
return fmt.Errorf("ProcessRangeRequest err: %w", err)
|
||||
// WriteHeader was already called: drop the unflushed tail and abort.
|
||||
discardBuffered = true
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package weed_server
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
@@ -219,6 +220,85 @@ func (c *countingReadCloser) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// A write error after the body has flushed must not complete as 200 with the
|
||||
// full Content-Length: the unflushed tail is discarded and the connection
|
||||
// aborted mid-body.
|
||||
func TestProcessRangeRequestWriteErrorAfterBodyStarted(t *testing.T) {
|
||||
payload := bytes.Repeat([]byte("x"), 200*1024)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = ProcessRangeRequest(r, w, int64(len(payload)), "application/octet-stream", func(offset int64, size int64) (filer.DoStreamContent, error) {
|
||||
return func(writer io.Writer) error {
|
||||
// Page-sized writes, as readNeedleDataInto does. The tail sits
|
||||
// in the 128KiB buffer; flushing it would finish the 200.
|
||||
for off := 0; off < len(payload); off += 4096 {
|
||||
end := off + 4096
|
||||
if end > len(payload) {
|
||||
end = len(payload)
|
||||
}
|
||||
if _, werr := writer.Write(payload[off:end]); werr != nil {
|
||||
return werr
|
||||
}
|
||||
}
|
||||
return errors.New("ReadNeedleData checksum mismatch")
|
||||
}, nil
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := srv.Client().Get(srv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status %d, want the committed 200", resp.StatusCode)
|
||||
}
|
||||
body, readErr := io.ReadAll(resp.Body)
|
||||
if readErr == nil {
|
||||
t.Fatalf("body completed with %d bytes; the erroring tail must abort it", len(body))
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessRangeRequestWriteErrorBeforeBody(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodGet, "/test.bin", nil)
|
||||
w := httptest.NewRecorder()
|
||||
err := ProcessRangeRequest(r, w, 100, "application/octet-stream", func(offset int64, size int64) (filer.DoStreamContent, error) {
|
||||
return func(writer io.Writer) error {
|
||||
return errors.New("ReadNeedleData checksum mismatch")
|
||||
}, nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected write error")
|
||||
}
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status %d, want 500, body %q", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "checksum") {
|
||||
t.Fatalf("body %q, want the checksum error", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessRangeRequestLargeBody(t *testing.T) {
|
||||
payload := bytes.Repeat([]byte("y"), 200*1024)
|
||||
r := httptest.NewRequest(http.MethodGet, "/test.bin", nil)
|
||||
w := httptest.NewRecorder()
|
||||
err := ProcessRangeRequest(r, w, int64(len(payload)), "application/octet-stream", func(offset int64, size int64) (filer.DoStreamContent, error) {
|
||||
return func(writer io.Writer) error {
|
||||
_, werr := writer.Write(payload)
|
||||
return werr
|
||||
}, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status %d, want 200", w.Code)
|
||||
}
|
||||
if !bytes.Equal(w.Body.Bytes(), payload) {
|
||||
t.Fatalf("body len %d, want %d", w.Body.Len(), len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessRangeRequestRanges(t *testing.T) {
|
||||
data := []byte("0123456789")
|
||||
serve := func(rangeHeader string) (*httptest.ResponseRecorder, error) {
|
||||
|
||||
@@ -205,7 +205,8 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
// upsert. Route it to the entry's ring owner so one filer's lock arbitrates
|
||||
// every creator cluster-wide; is_moved bounds this to one hop. Plain creates
|
||||
// are upserts either way and stay local.
|
||||
if !req.IsMoved && (req.OExcl || conditionIsSet(req.Condition)) {
|
||||
routed := req.OExcl || conditionIsSet(req.Condition)
|
||||
if !req.IsMoved && routed {
|
||||
fullpath := util.NewFullPath(req.Directory, req.Entry.Name)
|
||||
// Held apart from the named resp, which the local path below writes into:
|
||||
// a failed forward must not leave it nil.
|
||||
@@ -228,6 +229,10 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
}
|
||||
return ownerResp, nil
|
||||
}
|
||||
} else if req.IsMoved && routed {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, fs.writeOwner(entryRouteKey(util.NewFullPath(req.Directory, req.Entry.Name)))); err != nil {
|
||||
return &filer_pb.CreateEntryResponse{}, err
|
||||
}
|
||||
}
|
||||
|
||||
chunks, garbage, err2 := fs.cleanupChunks(ctx, util.Join(req.Directory, req.Entry.Name), nil, req.Entry)
|
||||
@@ -321,6 +326,11 @@ func (fs *FilerServer) ObjectTransaction(ctx context.Context, req *filer_pb.Obje
|
||||
// serialization point — even when the caller's ring view was stale. is_moved
|
||||
// bounds this to one hop: a forwarded transaction is applied locally, so two
|
||||
// filers that disagree on the owner during a ring change cannot loop.
|
||||
if req.RouteKey != "" {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, fs.writeOwner(req.RouteKey)); err != nil {
|
||||
return &filer_pb.ObjectTransactionResponse{Error: err.Error()}, nil
|
||||
}
|
||||
}
|
||||
if req.RouteKey != "" && !req.IsMoved {
|
||||
// Rebuild rather than copy the request struct (it carries a mutex); the
|
||||
// pointer/slice fields are shared since the original is not mutated.
|
||||
@@ -662,6 +672,37 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr
|
||||
|
||||
fullpath := util.Join(req.Directory, req.Entry.Name)
|
||||
|
||||
// A conditional or preconditioned update is a read-then-write that the
|
||||
// per-path lock below only makes atomic on this filer. Route it to the
|
||||
// entry's ring owner so one filer's lock arbitrates every writer
|
||||
// cluster-wide; is_moved bounds this to one hop.
|
||||
routed := conditionIsSet(req.Condition) || len(req.ExpectedExtended) > 0
|
||||
if !req.IsMoved && routed {
|
||||
var ownerResp *filer_pb.UpdateEntryResponse
|
||||
handled, forwardErr := fs.forwardToWriteOwner(ctx, entryRouteKey(util.FullPath(fullpath)), func(owner pb.ServerAddress) error {
|
||||
glog.V(2).InfofCtx(ctx, "UpdateEntry %s: forwarding to owner %s", fullpath, owner)
|
||||
req.IsMoved = true
|
||||
return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
forwarded, e := client.UpdateEntry(ctx, req)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ownerResp = forwarded
|
||||
return nil
|
||||
})
|
||||
})
|
||||
if handled {
|
||||
if forwardErr != nil {
|
||||
return &filer_pb.UpdateEntryResponse{}, forwardErr
|
||||
}
|
||||
return ownerResp, nil
|
||||
}
|
||||
} else if req.IsMoved && routed {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, fs.writeOwner(entryRouteKey(util.FullPath(fullpath)))); err != nil {
|
||||
return &filer_pb.UpdateEntryResponse{}, err
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize concurrent mutations to the same path on this filer so the
|
||||
// read (preconditions, garbage diff) and the write are atomic. Callers
|
||||
// route a key's writes to this owner filer, making this local lock
|
||||
@@ -790,6 +831,9 @@ func (fs *FilerServer) AppendToEntry(ctx context.Context, req *filer_pb.AppendTo
|
||||
|
||||
lockClient := cluster.NewLockClient(fs.grpcDialOption, fs.option.Host)
|
||||
lock := lockClient.NewShortLivedLock(string(fullpath), string(fs.option.Host))
|
||||
if lock == nil {
|
||||
return nil, fmt.Errorf("failed to acquire lock for %s", fullpath)
|
||||
}
|
||||
defer lock.StopShortLivedLock()
|
||||
|
||||
// The cluster lock serializes appenders across filers; the path lock makes
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// conditionIsSet reports whether a condition asks for any check at all.
|
||||
@@ -82,6 +83,14 @@ func clauseSatisfied(c *filer_pb.WriteCondition_Clause, current *filer.Entry) bo
|
||||
return deadline <= time.Now().Unix()
|
||||
case filer_pb.WriteCondition_IF_CHUNKS_EQUAL:
|
||||
return chunkFidsEqual(current, c.Fids)
|
||||
case filer_pb.WriteCondition_IF_ENTRY_EQUAL:
|
||||
if !exists || c.ExpectedEntry == nil {
|
||||
return !exists && c.ExpectedEntry == nil
|
||||
}
|
||||
// Normalize the expected entry the way FindEntry normalizes the stored
|
||||
// one (e.g. FileSize grows to the chunk extent), or an unchanged entry
|
||||
// can compare unequal.
|
||||
return proto.Equal(current.ToProtoEntry(), filer.FromPbEntry("", c.ExpectedEntry).ToProtoEntry())
|
||||
default:
|
||||
// An unrecognized clause kind (e.g. from a newer client) must not be
|
||||
// treated as satisfied, which would silently bypass the guard. Fail
|
||||
|
||||
@@ -193,6 +193,34 @@ func TestWriteConditionUnknownKindFailsClosed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// IF_ENTRY_EQUAL compares the expected entry after the same normalization
|
||||
// FindEntry applied to the stored one: a raw event entry whose FileSize is
|
||||
// still zero must match a stored entry grown to its chunk extent.
|
||||
func TestIfEntryEqualNormalizesExpected(t *testing.T) {
|
||||
raw := &filer_pb.Entry{
|
||||
Name: "f",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 42},
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: 1, Cookie: 2}, Size: 100},
|
||||
},
|
||||
}
|
||||
stored := filer.FromPbEntry("/d", raw)
|
||||
if stored.FileSize != 100 {
|
||||
t.Fatalf("stored FileSize = %d, want chunk extent 100", stored.FileSize)
|
||||
}
|
||||
cond := one(&filer_pb.WriteCondition_Clause{
|
||||
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL,
|
||||
ExpectedEntry: raw,
|
||||
})
|
||||
if !writeConditionSatisfied(cond, stored) {
|
||||
t.Error("raw expected entry must equal its normalized stored form")
|
||||
}
|
||||
raw.Attributes.Mtime = 43
|
||||
if writeConditionSatisfied(cond, stored) {
|
||||
t.Error("changed expected entry must not equal the stored entry")
|
||||
}
|
||||
}
|
||||
|
||||
// storedEntryETag prefers the stored Seaweed ETag attribute and falls back to
|
||||
// the Md5-derived ETag, matching the S3 gateway.
|
||||
func TestStoredEntryETag(t *testing.T) {
|
||||
|
||||
@@ -3,10 +3,14 @@ package weed_server
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
@@ -89,6 +93,14 @@ func TestCreateEntryPlainStaysLocal(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ringPeerCtx simulates a request arriving over a connection from a ring
|
||||
// member, the provenance an is_moved marker needs before it is trusted.
|
||||
func ringPeerCtx() context.Context {
|
||||
return peer.NewContext(context.Background(), &peer.Peer{
|
||||
Addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 49999},
|
||||
})
|
||||
}
|
||||
|
||||
// is_moved bounds forwarding to one hop: the owner applies it even if its own
|
||||
// ring view says someone else owns the key.
|
||||
func TestCreateEntryMovedAppliesLocally(t *testing.T) {
|
||||
@@ -97,7 +109,7 @@ func TestCreateEntryMovedAppliesLocally(t *testing.T) {
|
||||
|
||||
req := createReq(name, true)
|
||||
req.IsMoved = true
|
||||
resp, err := fs.CreateEntry(context.Background(), req)
|
||||
resp, err := fs.CreateEntry(ringPeerCtx(), req)
|
||||
if err != nil || resp.Error != "" {
|
||||
t.Fatalf("forwarded create must be applied locally, got err=%v resp=%v", err, resp.Error)
|
||||
}
|
||||
@@ -106,6 +118,53 @@ func TestCreateEntryMovedAppliesLocally(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A caller can set is_moved, but without a ring member's connection it is not
|
||||
// trusted: on a non-owner the request is refused rather than evaluated under
|
||||
// the wrong lock or forwarded again, where it could cycle while rings disagree.
|
||||
func TestCreateEntryMovedFromClientIsNotTrusted(t *testing.T) {
|
||||
fs, store := createRouteServer(t)
|
||||
name := peerOwnedName(t, fs)
|
||||
|
||||
req := createReq(name, true)
|
||||
req.IsMoved = true
|
||||
_, err := fs.CreateEntry(context.Background(), req)
|
||||
if status.Code(err) != codes.PermissionDenied {
|
||||
t.Fatalf("a forged is_moved must be refused, got err=%v", err)
|
||||
}
|
||||
if _, found := store.entries[string(util.NewFullPath("/test", name))]; found {
|
||||
t.Fatal("a forged is_moved must not cause a local write")
|
||||
}
|
||||
}
|
||||
|
||||
// Forwarding an unlock to an unreachable owner must surface the RPC error, not
|
||||
// panic dereferencing the nil response of the failed call.
|
||||
func TestDistributedUnlockFailedForwardReturnsError(t *testing.T) {
|
||||
fs, _ := createRouteServer(t)
|
||||
|
||||
var name string
|
||||
for i := 0; i < 4000; i++ {
|
||||
candidate := fmt.Sprintf("lock-%d", i)
|
||||
if fs.filer.Dlm.LockRing.GetPrimary(candidate) != fs.option.Host {
|
||||
name = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
t.Skip("no lock owned by the peer")
|
||||
}
|
||||
|
||||
resp, err := fs.DistributedUnlock(context.Background(), &filer_pb.UnlockRequest{
|
||||
Name: name,
|
||||
RenewToken: "tok",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unlock forward should report via resp.Error, not err: %v", err)
|
||||
}
|
||||
if resp.Error == "" {
|
||||
t.Fatal("a failed forward must surface an error")
|
||||
}
|
||||
}
|
||||
|
||||
// An exclusive create this filer owns is applied locally, under its per-path lock.
|
||||
func TestCreateEntryExclusiveAppliedByOwner(t *testing.T) {
|
||||
fs, store := createRouteServer(t)
|
||||
|
||||
@@ -29,7 +29,9 @@ func (fs *FilerServer) DistributedLock(ctx context.Context, req *filer_pb.LockRe
|
||||
glog.V(4).Infof("FILER LOCK: LockWithTimeout result - name=%s lockOwner=%s renewToken=%s movedTo=%s err=%v",
|
||||
req.Name, resp.LockOwner, resp.RenewToken, movedTo, err)
|
||||
glog.V(4).Infof("lock %s %v %v %v, isMoved=%v %v", req.Name, req.SecondsToLock, req.RenewToken, req.Owner, req.IsMoved, movedTo)
|
||||
if movedTo != "" && movedTo != fs.option.Host && !req.IsMoved {
|
||||
if mErr := fs.checkMovedMarker(ctx, req.IsMoved, movedTo); mErr != nil {
|
||||
err = mErr
|
||||
} else if !req.IsMoved && movedTo != "" && movedTo != fs.option.Host {
|
||||
glog.V(0).Infof("FILER LOCK: Forwarding to correct filer - from=%s to=%s", fs.option.Host, movedTo)
|
||||
err = pb.WithFilerClient(false, 0, movedTo, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
secondResp, err := client.DistributedLock(ctx, &filer_pb.LockRequest{
|
||||
@@ -76,15 +78,20 @@ func (fs *FilerServer) DistributedUnlock(ctx context.Context, req *filer_pb.Unlo
|
||||
var movedTo pb.ServerAddress
|
||||
movedTo, err = fs.filer.Dlm.Unlock(req.Name, req.RenewToken)
|
||||
|
||||
if !req.IsMoved && movedTo != "" {
|
||||
if mErr := fs.checkMovedMarker(ctx, req.IsMoved, movedTo); mErr != nil {
|
||||
err = mErr
|
||||
} else if !req.IsMoved && movedTo != "" {
|
||||
err = pb.WithFilerClient(false, 0, movedTo, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
secondResp, err := client.DistributedUnlock(ctx, &filer_pb.UnlockRequest{
|
||||
Name: req.Name,
|
||||
RenewToken: req.RenewToken,
|
||||
IsMoved: true,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Error = secondResp.Error
|
||||
return err
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -101,6 +108,9 @@ func (fs *FilerServer) DistributedUnlock(ctx context.Context, req *filer_pb.Unlo
|
||||
|
||||
func (fs *FilerServer) FindLockOwner(ctx context.Context, req *filer_pb.FindLockOwnerRequest) (*filer_pb.FindLockOwnerResponse, error) {
|
||||
owner, movedTo, err := fs.filer.Dlm.FindLockOwner(req.Name)
|
||||
if mErr := fs.checkMovedMarker(ctx, req.IsMoved, movedTo); mErr != nil {
|
||||
return nil, mErr
|
||||
}
|
||||
if !req.IsMoved && movedTo != "" {
|
||||
err = pb.WithFilerClient(false, 0, movedTo, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
secondResp, err := client.FindLockOwner(ctx, &filer_pb.FindLockOwnerRequest{
|
||||
|
||||
@@ -769,10 +769,11 @@ func TestObjectTransactionRouteKeyOwnerAppliesLocally(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A forwarded transaction (is_moved) applies locally even when the ring names a
|
||||
// different owner: is_moved bounds forwarding to a single hop, so two filers that
|
||||
// disagree on the owner during a ring change cannot loop. If is_moved were
|
||||
// ignored, this would attempt to dial the bogus owner instead of applying.
|
||||
// A forwarded transaction (is_moved over a ring member's connection) applies
|
||||
// locally even when the ring names a different owner: is_moved bounds
|
||||
// forwarding to a single hop, so two filers that disagree on the owner during
|
||||
// a ring change cannot loop. Without the marker this would attempt to dial
|
||||
// the bogus owner instead of applying.
|
||||
func TestObjectTransactionIsMovedSkipsForward(t *testing.T) {
|
||||
self := pb.ServerAddress("localhost:1")
|
||||
other := pb.ServerAddress("localhost:2")
|
||||
@@ -781,7 +782,7 @@ func TestObjectTransactionIsMovedSkipsForward(t *testing.T) {
|
||||
})
|
||||
withRing(fs, self, other) // ring owner is "other", not self
|
||||
|
||||
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
|
||||
resp, err := fs.ObjectTransaction(ringPeerCtx(), &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: "/buckets/b/obj",
|
||||
RouteKey: "s3.object.write:/buckets/b/obj",
|
||||
IsMoved: true,
|
||||
|
||||
@@ -63,26 +63,31 @@ func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockReq
|
||||
return &filer_pb.PosixLockResponse{}, fmt.Errorf("lock is required")
|
||||
}
|
||||
|
||||
if !req.IsMoved && fs.filer.Dlm != nil {
|
||||
if fs.filer.Dlm != nil {
|
||||
if owner := fs.filer.Dlm.LockRing.GetPrimary(req.Key); owner != "" && owner != fs.option.Host {
|
||||
forwarded := &filer_pb.PosixLockRequest{
|
||||
Key: req.Key,
|
||||
IsMoved: true,
|
||||
Op: req.Op,
|
||||
Lock: req.Lock,
|
||||
Locks: req.Locks,
|
||||
}
|
||||
glog.V(4).InfofCtx(ctx, "PosixLock %s op=%v: forwarding to owner %s", req.Key, req.Op, owner)
|
||||
var resp *filer_pb.PosixLockResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.PosixLock(ctx, forwarded)
|
||||
return e
|
||||
})
|
||||
if err != nil {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, owner); err != nil {
|
||||
return &filer_pb.PosixLockResponse{}, err
|
||||
}
|
||||
return resp, nil
|
||||
if !req.IsMoved {
|
||||
forwarded := &filer_pb.PosixLockRequest{
|
||||
Key: req.Key,
|
||||
IsMoved: true,
|
||||
Op: req.Op,
|
||||
Lock: req.Lock,
|
||||
Locks: req.Locks,
|
||||
}
|
||||
glog.V(4).InfofCtx(ctx, "PosixLock %s op=%v: forwarding to owner %s", req.Key, req.Op, owner)
|
||||
var resp *filer_pb.PosixLockResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.PosixLock(ctx, forwarded)
|
||||
return e
|
||||
})
|
||||
if err != nil {
|
||||
return &filer_pb.PosixLockResponse{}, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,11 +2,18 @@ package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// writeOwner returns the filer that serializes writes to key, or "" when this
|
||||
@@ -55,3 +62,119 @@ func (fs *FilerServer) forwardToWriteOwner(ctx context.Context, key string, send
|
||||
func entryRouteKey(fullpath util.FullPath) string {
|
||||
return s3_constants.ObjectWriteRouteKeyPrefix + string(fullpath)
|
||||
}
|
||||
|
||||
// movedFromPeer reports whether an is_moved marker arrived on a connection
|
||||
// from a ring member, i.e. it marks a genuine forwarded hop.
|
||||
func (fs *FilerServer) movedFromPeer(ctx context.Context, isMoved bool) bool {
|
||||
if !isMoved || fs.filer.Dlm == nil {
|
||||
return false
|
||||
}
|
||||
p, ok := peer.FromContext(ctx)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
peerHost, _, err := net.SplitHostPort(p.Addr.String())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
peerIP := net.ParseIP(peerHost)
|
||||
if peerIP == nil {
|
||||
return false
|
||||
}
|
||||
for _, ip := range fs.ringMemberIPs(ctx) {
|
||||
if ip.Equal(peerIP) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ringPeerIPs caches resolved member addresses of one ring membership. A
|
||||
// member's hostname may re-resolve under the same ring address, so the cache
|
||||
// expires rather than trusting the resolution forever.
|
||||
type ringPeerIPs struct {
|
||||
members string
|
||||
ips []net.IP
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
const ringPeerIPTTL = 5 * time.Minute
|
||||
|
||||
// ringMemberIPs returns the ring members' addresses as IPs. Members can
|
||||
// advertise hostnames, so resolution is cached per membership to keep DNS off
|
||||
// each forwarded request; a failed lookup is not cached, so a DNS blip does
|
||||
// not keep rejecting genuine forwards until the next ring change.
|
||||
func (fs *FilerServer) ringMemberIPs(ctx context.Context) []net.IP {
|
||||
members := fs.filer.Dlm.LockRing.GetSnapshot()
|
||||
var sb strings.Builder
|
||||
for _, member := range members {
|
||||
sb.WriteString(string(member))
|
||||
sb.WriteByte(' ')
|
||||
}
|
||||
key := sb.String()
|
||||
if cached := fs.ringPeerIPs.Load(); cached != nil && cached.members == key && time.Now().Before(cached.expires) {
|
||||
return cached.ips
|
||||
}
|
||||
resolved, _, _ := fs.ringResolveGroup.Do(key, func() (any, error) {
|
||||
if cached := fs.ringPeerIPs.Load(); cached != nil && cached.members == key && time.Now().Before(cached.expires) {
|
||||
return cached.ips, nil
|
||||
}
|
||||
// Shared by every caller waiting on this key: the lookups outlive the
|
||||
// first request's cancellation, and run in parallel so one slow member
|
||||
// cannot starve the rest of the shared deadline.
|
||||
var ips []net.IP
|
||||
var hosts []string
|
||||
for _, member := range members {
|
||||
host, _, err := net.SplitHostPort(string(member))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
ips = append(ips, ip)
|
||||
continue
|
||||
}
|
||||
hosts = append(hosts, host)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
failed := false
|
||||
for _, host := range hosts {
|
||||
wg.Add(1)
|
||||
go func(host string) {
|
||||
defer wg.Done()
|
||||
lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
|
||||
defer cancel()
|
||||
found, err := net.DefaultResolver.LookupIP(lookupCtx, "ip", host)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err != nil {
|
||||
failed = true
|
||||
return
|
||||
}
|
||||
ips = append(ips, found...)
|
||||
}(host)
|
||||
}
|
||||
wg.Wait()
|
||||
if !failed {
|
||||
fs.ringPeerIPs.Store(&ringPeerIPs{members: key, ips: ips, expires: time.Now().Add(ringPeerIPTTL)})
|
||||
}
|
||||
return ips, nil
|
||||
})
|
||||
return resolved.([]net.IP)
|
||||
}
|
||||
|
||||
// checkMovedMarker refuses a request whose is_moved marker did not arrive from
|
||||
// a ring member while this filer is not the key's owner. The marker is
|
||||
// caller-controlled: applying it would evaluate a conditional mutation under a
|
||||
// non-owner's lock, and re-forwarding a claimed hop can cycle while rings
|
||||
// disagree — so an unverifiable marker on a non-owner is refused instead.
|
||||
// PermissionDenied keeps the refusal distinct from a write condition's
|
||||
// FailedPrecondition, which callers use to detect a stale stamp.
|
||||
// owner=="" means this filer is the serialization point and the request can
|
||||
// be applied locally.
|
||||
func (fs *FilerServer) checkMovedMarker(ctx context.Context, isMoved bool, owner pb.ServerAddress) error {
|
||||
if !isMoved || owner == "" || owner == fs.option.Host || fs.movedFromPeer(ctx, isMoved) {
|
||||
return nil
|
||||
}
|
||||
return status.Errorf(codes.PermissionDenied, "is_moved not sent by a ring member; the key's owner is %s", owner)
|
||||
}
|
||||
@@ -136,6 +136,11 @@ type FilerServer struct {
|
||||
// chunks behind the first request's back.
|
||||
tusActiveUploads sync.Map
|
||||
|
||||
// ringPeerIPs caches resolved ring member addresses per ring version so
|
||||
// verifying a forwarded request's peer does not pay a DNS lookup per hop.
|
||||
ringPeerIPs atomic.Pointer[ringPeerIPs]
|
||||
ringResolveGroup singleflight.Group
|
||||
|
||||
// entryLockTable serializes mutations to the same entry path on this filer.
|
||||
// CreateEntry takes it today; UpdateEntry and DeleteEntry are intended to take
|
||||
// it too as their callers route a key's writes to this node, making it the
|
||||
@@ -311,6 +316,8 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption)
|
||||
|
||||
fs.filer.LoadRemoteStorageConfAndMapping()
|
||||
|
||||
fs.filer.RebuildRemoteDeletionTombstones(context.Background())
|
||||
|
||||
grace.OnReload(fs.Reload)
|
||||
|
||||
fs.SetupDlmReplication()
|
||||
|
||||
@@ -51,6 +51,7 @@ type MasterOption struct {
|
||||
FileSizeLimitMB int
|
||||
VolumePreallocate bool
|
||||
MaxParallelVacuumPerServer int
|
||||
VacuumIntervalSeconds int
|
||||
// PulseSeconds int
|
||||
DefaultReplicaPlacement string
|
||||
GarbageThreshold float64
|
||||
@@ -202,6 +203,7 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
|
||||
ms.option.MaxParallelVacuumPerServer,
|
||||
topology.VolumeGrowStrategy.Threshold,
|
||||
ms.preallocateSize,
|
||||
time.Duration(ms.option.VacuumIntervalSeconds)*time.Second,
|
||||
)
|
||||
|
||||
ms.ProcessGrowRequest()
|
||||
|
||||
@@ -198,7 +198,7 @@ func (vs *VolumeServer) VolumeDelete(ctx context.Context, req *volume_server_pb.
|
||||
return resp, err
|
||||
}
|
||||
|
||||
err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), req.OnlyEmpty, req.KeepRemoteData)
|
||||
err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), req.OnlyEmpty, req.OnlyGarbage, req.KeepRemoteData)
|
||||
|
||||
if err != nil {
|
||||
glog.Errorf("volume delete %v: %v", req, err)
|
||||
|
||||
@@ -101,7 +101,7 @@ func (vs *VolumeServer) VolumeCopy(req *volume_server_pb.VolumeCopyRequest, stre
|
||||
glog.V(0).Infof("volume %d already exists. deleting before copying from %s...", req.VolumeId, req.SourceDataNode)
|
||||
// keep remote data: the inbound copy carries a .vif that may point at
|
||||
// the same cloud-tier object the existing volume references.
|
||||
if delErr := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), false, true); delErr != nil {
|
||||
if delErr := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), false, false, true); delErr != nil {
|
||||
return fmt.Errorf("failed to delete existing volume %d: %v", req.VolumeId, delErr)
|
||||
}
|
||||
glog.V(0).Infof("deleted existing volume %d before copying.", req.VolumeId)
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"io"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
@@ -16,6 +16,9 @@ func (vs *VolumeServer) VolumeIncrementalCopy(req *volume_server_pb.VolumeIncrem
|
||||
if v == nil {
|
||||
return fmt.Errorf("not found volume id %d", req.VolumeId)
|
||||
}
|
||||
if err := v.UnavailableError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stopOffset, _, _ := v.FileStat()
|
||||
foundOffset, isLastOne, err := v.BinarySearchByAppendAtNs(req.SinceNs)
|
||||
@@ -30,7 +33,7 @@ func (vs *VolumeServer) VolumeIncrementalCopy(req *volume_server_pb.VolumeIncrem
|
||||
startOffset := foundOffset.ToActualOffset()
|
||||
|
||||
buf := make([]byte, 1024*1024*2)
|
||||
return sendFileContent(v.DataBackend, buf, startOffset, int64(stopOffset), stream)
|
||||
return sendFileContent(v, buf, startOffset, int64(stopOffset), stream)
|
||||
|
||||
}
|
||||
|
||||
@@ -47,10 +50,13 @@ func (vs *VolumeServer) VolumeSyncStatus(ctx context.Context, req *volume_server
|
||||
|
||||
}
|
||||
|
||||
func sendFileContent(datBackend backend.BackendStorageFile, buf []byte, startOffset, stopOffset int64, stream volume_server_pb.VolumeServer_VolumeIncrementalCopyServer) error {
|
||||
func sendFileContent(v *storage.Volume, buf []byte, startOffset, stopOffset int64, stream volume_server_pb.VolumeServer_VolumeIncrementalCopyServer) error {
|
||||
var blockSizeLimit = int64(len(buf))
|
||||
for i := int64(0); i < stopOffset-startOffset; i += blockSizeLimit {
|
||||
n, readErr := datBackend.ReadAt(buf, startOffset+i)
|
||||
if err := v.UnavailableError(); err != nil {
|
||||
return err
|
||||
}
|
||||
n, readErr := v.DataBackend.ReadAt(buf, startOffset+i)
|
||||
if readErr == nil || readErr == io.EOF {
|
||||
resp := &volume_server_pb.VolumeIncrementalCopyResponse{}
|
||||
resp.FileContent = buf[:int64(n)]
|
||||
|
||||
@@ -29,6 +29,9 @@ func (vs *VolumeServer) streamReadOneVolume(vid needle.VolumeId, stream volume_s
|
||||
if v == nil {
|
||||
return fmt.Errorf("not found volume id %d", vid)
|
||||
}
|
||||
if err := v.UnavailableError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
scanner := &storage.VolumeFileScanner4ReadAll{
|
||||
Stream: stream,
|
||||
|
||||
@@ -20,6 +20,9 @@ func (vs *VolumeServer) VolumeTailSender(req *volume_server_pb.VolumeTailSenderR
|
||||
if v == nil {
|
||||
return fmt.Errorf("not found volume id %d", req.VolumeId)
|
||||
}
|
||||
if err := v.UnavailableError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer glog.V(1).Infof("tailing volume %d finished", v.Id)
|
||||
|
||||
@@ -27,6 +30,9 @@ func (vs *VolumeServer) VolumeTailSender(req *volume_server_pb.VolumeTailSenderR
|
||||
drainingSeconds := req.IdleTimeoutSeconds
|
||||
|
||||
for {
|
||||
if err := v.UnavailableError(); err != nil {
|
||||
return err
|
||||
}
|
||||
lastProcessedTimestampNs, err := sendNeedlesSince(stream, v, lastTimestampNs)
|
||||
if err != nil {
|
||||
glog.Infof("sendNeedlesSince: %v", err)
|
||||
@@ -64,6 +70,9 @@ func sendNeedlesSince(stream volume_server_pb.VolumeServer_VolumeTailSenderServe
|
||||
// log.Printf("reading ts %d offset %d isLast %v", lastTimestampNs, foundOffset, isLastOne)
|
||||
|
||||
if isLastOne {
|
||||
if err := v.UnavailableError(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// need to heart beat to the client to ensure the connection health
|
||||
sendErr := stream.Send(&volume_server_pb.VolumeTailSenderResponse{IsLastChunk: true, Version: uint32(v.Version())})
|
||||
return lastTimestampNs, sendErr
|
||||
@@ -72,6 +81,7 @@ func sendNeedlesSince(stream volume_server_pb.VolumeServer_VolumeTailSenderServe
|
||||
scanner := &VolumeFileScanner4Tailing{
|
||||
stream: stream,
|
||||
version: uint32(v.Version()),
|
||||
v: v,
|
||||
}
|
||||
|
||||
err = storage.ScanVolumeFileFrom(v.Version(), v.DataBackend, foundOffset.ToActualOffset(), scanner)
|
||||
@@ -112,6 +122,7 @@ type VolumeFileScanner4Tailing struct {
|
||||
stream volume_server_pb.VolumeServer_VolumeTailSenderServer
|
||||
lastProcessedTimestampNs uint64
|
||||
version uint32
|
||||
v *storage.Volume
|
||||
}
|
||||
|
||||
func (scanner *VolumeFileScanner4Tailing) VisitSuperBlock(superBlock super_block.SuperBlock) error {
|
||||
@@ -123,6 +134,9 @@ func (scanner *VolumeFileScanner4Tailing) ReadNeedleBody() bool {
|
||||
}
|
||||
|
||||
func (scanner *VolumeFileScanner4Tailing) VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error {
|
||||
if err := scanner.v.UnavailableError(); err != nil {
|
||||
return err
|
||||
}
|
||||
isLastChunk := false
|
||||
|
||||
// need to send body by chunks
|
||||
|
||||
@@ -2,6 +2,7 @@ package shell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -112,11 +113,16 @@ func (c *commandS3BucketCreate) Do(args []string, commandEnv *CommandEnv, writer
|
||||
entry.Extended[s3_constants.ExtObjectLockEnabledKey] = []byte(s3_constants.ObjectLockEnabled)
|
||||
}
|
||||
|
||||
if _, err := client.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
||||
createErr := filer_pb.CreateEntry(context.Background(), client, &filer_pb.CreateEntryRequest{
|
||||
Directory: filerBucketsPath,
|
||||
Entry: entry,
|
||||
}); err != nil {
|
||||
return err
|
||||
OExcl: true,
|
||||
})
|
||||
if errors.Is(createErr, filer_pb.ErrEntryAlreadyExists) {
|
||||
return fmt.Errorf("bucket %s already exists", *bucketName)
|
||||
}
|
||||
if createErr != nil {
|
||||
return createErr
|
||||
}
|
||||
|
||||
fmt.Fprintln(writer, "created bucket", *bucketName)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
type bucketCreateTestFilerServer struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
|
||||
mu sync.Mutex
|
||||
createReqs []*filer_pb.CreateEntryRequest
|
||||
}
|
||||
|
||||
func (s *bucketCreateTestFilerServer) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
|
||||
return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets"}, nil
|
||||
}
|
||||
|
||||
func (s *bucketCreateTestFilerServer) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.createReqs = append(s.createReqs, req)
|
||||
return &filer_pb.CreateEntryResponse{
|
||||
ErrorCode: filer_pb.FilerError_ENTRY_ALREADY_EXISTS,
|
||||
Error: "entry already exists",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *bucketCreateTestFilerServer) createRequests() []*filer_pb.CreateEntryRequest {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]*filer_pb.CreateEntryRequest(nil), s.createReqs...)
|
||||
}
|
||||
|
||||
func TestS3BucketCreateRequestsExclusiveCreate(t *testing.T) {
|
||||
filerServer := &bucketCreateTestFilerServer{}
|
||||
commandEnv, cleanup := newBucketCreateTestCommandEnv(t, filerServer)
|
||||
defer cleanup()
|
||||
|
||||
var output bytes.Buffer
|
||||
err := (&commandS3BucketCreate{}).Do([]string{"-name", "my-bucket"}, commandEnv, &output)
|
||||
require.EqualError(t, err, "bucket my-bucket already exists")
|
||||
|
||||
reqs := filerServer.createRequests()
|
||||
require.Len(t, reqs, 1)
|
||||
req := reqs[0]
|
||||
assert.True(t, req.OExcl, "bucket create must not replace an existing entry")
|
||||
assert.Equal(t, "/buckets", req.Directory)
|
||||
assert.Equal(t, "my-bucket", req.Entry.Name)
|
||||
}
|
||||
|
||||
func newBucketCreateTestCommandEnv(t *testing.T, filerServer filer_pb.SeaweedFilerServer) (*CommandEnv, func()) {
|
||||
t.Helper()
|
||||
|
||||
socketDir, err := os.MkdirTemp("", "swbucket-")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = os.RemoveAll(socketDir) })
|
||||
|
||||
socketPath := filepath.Join(socketDir, "filer.sock")
|
||||
listener, err := net.Listen("unix", socketPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, filerServer)
|
||||
go func() {
|
||||
_ = grpcServer.Serve(listener)
|
||||
}()
|
||||
|
||||
grpcPort := 48000 + os.Getpid()%1000
|
||||
pb.RegisterLocalGrpcSocket("127.0.0.1", grpcPort, socketPath)
|
||||
|
||||
cleanup := func() {
|
||||
grpcServer.Stop()
|
||||
_ = listener.Close()
|
||||
}
|
||||
|
||||
return &CommandEnv{
|
||||
option: &ShellOptions{
|
||||
FilerAddress: pb.ServerAddress(fmt.Sprintf("127.0.0.1:8888.%d", grpcPort)),
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
Directory: "/",
|
||||
},
|
||||
}, cleanup
|
||||
}
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user