mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6047e5b3c8 | ||
|
|
e6c1f3d7b2 | ||
|
|
dfd18ae231 | ||
|
|
dc5a81b1be | ||
|
|
2ef6046c5e | ||
|
|
662a6ac8ee | ||
|
|
a1eab5ff99 | ||
|
|
6fb3ec968d | ||
|
|
b0e0c5aaab | ||
|
|
e8b7347031 | ||
|
|
50efda9cc5 | ||
|
|
84b8a8e010 | ||
|
|
c6d6ee8297 | ||
|
|
de3ecaf0de | ||
|
|
df4f2f7020 | ||
|
|
1ee03b6411 | ||
|
|
dfac1315ca | ||
|
|
2d06ddab41 | ||
|
|
924d410dc8 | ||
|
|
2fa36549df | ||
|
|
e225940202 | ||
|
|
2188d1ccc5 | ||
|
|
4c36cd04d6 | ||
|
|
27a28faf49 | ||
|
|
c153420022 | ||
|
|
ae7333d28e | ||
|
|
0cd9f34177 | ||
|
|
1e1473ef4a | ||
|
|
4bc2b6d62b | ||
|
|
d970c15d71 | ||
|
|
1b13324fb7 |
No files matched your search
@@ -0,0 +1,92 @@
|
||||
name: "Metadata Subscribe Integration Tests"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/filer/**'
|
||||
- 'weed/pb/filer_pb/**'
|
||||
- 'weed/util/log_buffer/**'
|
||||
- 'weed/server/filer_grpc_server_sub_meta.go'
|
||||
- 'weed/command/filer_backup.go'
|
||||
- 'test/metadata_subscribe/**'
|
||||
- '.github/workflows/metadata-subscribe-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/filer/**'
|
||||
- 'weed/pb/filer_pb/**'
|
||||
- 'weed/util/log_buffer/**'
|
||||
- 'weed/server/filer_grpc_server_sub_meta.go'
|
||||
- 'weed/command/filer_backup.go'
|
||||
- 'test/metadata_subscribe/**'
|
||||
- '.github/workflows/metadata-subscribe-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/metadata-subscribe-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
GO_VERSION: '1.24'
|
||||
TEST_TIMEOUT: '10m'
|
||||
|
||||
jobs:
|
||||
metadata-subscribe-integration:
|
||||
name: Metadata Subscribe Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go ${{ env.GO_VERSION }}
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
- name: Build SeaweedFS
|
||||
run: |
|
||||
cd weed
|
||||
go build -o weed .
|
||||
chmod +x weed
|
||||
./weed version
|
||||
|
||||
- name: Run Metadata Subscribe Integration Tests
|
||||
run: |
|
||||
cd test/metadata_subscribe
|
||||
|
||||
echo "Running Metadata Subscribe integration tests..."
|
||||
echo "============================================"
|
||||
|
||||
# Run tests with verbose output
|
||||
go test -v -timeout=${{ env.TEST_TIMEOUT }} ./...
|
||||
|
||||
echo "============================================"
|
||||
echo "Metadata Subscribe integration tests completed"
|
||||
|
||||
- name: Archive logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: metadata-subscribe-test-logs
|
||||
path: |
|
||||
/tmp/seaweedfs_*
|
||||
retention-days: 7
|
||||
|
||||
- name: Test Summary
|
||||
if: always()
|
||||
run: |
|
||||
echo "## Metadata Subscribe Integration Test Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### Test Coverage" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Basic Subscription**: Subscribe to metadata changes and receive events" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Single-Filer No Stall**: Regression test for issue #4977" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Resume from Disk**: Verify subscription can resume from persisted logs" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### Related Issues" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- [#4977](https://github.com/seaweedfs/seaweedfs/issues/4977): filer.backup synchronisation stall" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -77,6 +77,7 @@ LABEL author="Chris Lu"
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
curl \
|
||||
fuse \
|
||||
wget && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
@@ -27,7 +27,7 @@ COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh
|
||||
# To disable: docker run -e GODEBUG=fips140=off ...
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk add --no-cache fuse su-exec && \
|
||||
RUN apk add --no-cache fuse curl su-exec && \
|
||||
addgroup -g 1000 seaweed && \
|
||||
adduser -D -u 1000 -G seaweed seaweed
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer_rocksdb.
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk add --no-cache fuse snappy gflags su-exec && \
|
||||
RUN apk add --no-cache fuse snappy gflags curl su-exec && \
|
||||
addgroup -g 1000 seaweed && \
|
||||
adduser -D -u 1000 -G seaweed seaweed
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer_rocksdb.
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk add --no-cache fuse snappy gflags tmux su-exec && \
|
||||
RUN apk add --no-cache fuse snappy gflags curl tmux su-exec && \
|
||||
addgroup -g 1000 seaweed && \
|
||||
adduser -D -u 1000 -G seaweed seaweed
|
||||
|
||||
|
||||
@@ -123,7 +123,7 @@ require (
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
github.com/ThreeDotsLabs/watermill v1.5.1
|
||||
github.com/a-h/templ v0.3.943
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20240515141816-262c6fe778ad
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
|
||||
github.com/arangodb/go-driver v1.6.9
|
||||
github.com/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.40.1
|
||||
@@ -203,8 +203,8 @@ require (
|
||||
github.com/openzipkin/zipkin-go v0.4.3 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
|
||||
github.com/pierrre/geohash v1.0.0 // indirect
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.54.1 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.57.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/ryanuber/go-glob v1.0.0 // indirect
|
||||
github.com/sasha-s/go-deadlock v0.3.1 // indirect
|
||||
@@ -218,7 +218,6 @@ require (
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/zipkin v1.36.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/mod v0.29.0 // indirect
|
||||
|
||||
@@ -651,8 +651,8 @@ github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmg
|
||||
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
|
||||
github.com/apache/arrow/go/v10 v10.0.1/go.mod h1:YvhnlEePVnBS4+0z3fhPfUy7W1Ikj0Ih0vcRo/gZ1M0=
|
||||
github.com/apache/thrift v0.16.0/go.mod h1:PHK3hniurgQaNMZYaCLEqXKsYK8upmhPbmdP2FXSqgU=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20240515141816-262c6fe778ad h1:fQBkhYv86zyW95PWhzBlkgz3NoY1ue0L+8oYBaoCMbg=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20240515141816-262c6fe778ad/go.mod h1:OMVSB21p9+xQUIqlGizHPZfjK+SHws1ht+ZytVDoz9U=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3 h1:WZaTKNHCfcw7fWSR6/RKnCldVzvYZC+Y20Su4lffEIg=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3/go.mod h1:OMVSB21p9+xQUIqlGizHPZfjK+SHws1ht+ZytVDoz9U=
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er+LKDHDUfU5tRvFwxH0LjPpZN8OoG8Ll+liGU=
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc/go.mod h1:w648aMHEgFYS6xb0KVMMtZ2uMeemhiKCuD2vj6gY52A=
|
||||
github.com/arangodb/go-driver v1.6.9 h1:zckB+xuA16NmHUuYOX7INCJTIyIkoBQjAGqNpiyf2HQ=
|
||||
@@ -1563,10 +1563,10 @@ github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4
|
||||
github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 h1:Y258uzXU/potCYnQd1r6wlAnoMB68BiCkCcCnKx1SH8=
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8/go.mod h1:bSJjRokAHHOhA+XFxplld8w2R/dXLH7Z3BZ532vhFwU=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||
github.com/quic-go/quic-go v0.54.1 h1:4ZAWm0AhCb6+hE+l5Q1NAL0iRn/ZrMwqHRGQiFwj2eg=
|
||||
github.com/quic-go/quic-go v0.54.1/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.57.0 h1:AsSSrrMs4qI/hLrKlTH/TGQeTMY0ib1pAOX7vA3AdqE=
|
||||
github.com/quic-go/quic-go v0.57.0/go.mod h1:ly4QBAjHA2VhdnxhojRsCUOeJwKYg+taDlos92xb1+s=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rclone/rclone v1.71.2 h1:3Jk5xNPFrZhVABRuN/OPvApuZQddpE2tkhYMuEn1Ud4=
|
||||
@@ -1872,8 +1872,8 @@ go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A
|
||||
go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
|
||||
go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
|
||||
@@ -132,9 +132,9 @@ spec:
|
||||
{{- end }}
|
||||
worker \
|
||||
{{- if .Values.worker.adminServer }}
|
||||
-adminServer={{ .Values.worker.adminServer }} \
|
||||
-admin={{ .Values.worker.adminServer }} \
|
||||
{{- else }}
|
||||
-adminServer={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.grpcPort }} \
|
||||
-admin={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.grpcPort }} \
|
||||
{{- end }}
|
||||
-capabilities={{ .Values.worker.capabilities }} \
|
||||
-maxConcurrent={{ .Values.worker.maxConcurrent }} \
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
.PHONY: test test-short build-weed clean
|
||||
|
||||
# Build weed binary first if needed
|
||||
build-weed:
|
||||
cd ../../weed && go build -o weed .
|
||||
|
||||
# Run all integration tests
|
||||
test: build-weed
|
||||
go test -v -timeout 5m .
|
||||
|
||||
# Run tests in short mode (skip integration tests)
|
||||
test-short:
|
||||
go test -v -short .
|
||||
|
||||
# Run specific test
|
||||
test-basic: build-weed
|
||||
go test -v -timeout 3m -run TestMetadataSubscribeBasic .
|
||||
|
||||
test-stall: build-weed
|
||||
go test -v -timeout 5m -run TestMetadataSubscribeSingleFilerNoStall .
|
||||
|
||||
test-resume: build-weed
|
||||
go test -v -timeout 3m -run TestMetadataSubscribeResumeFromDisk .
|
||||
|
||||
clean:
|
||||
rm -f ../../weed/weed
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Metadata Subscribe Integration Tests
|
||||
|
||||
This directory contains integration tests for the SeaweedFS metadata subscription functionality.
|
||||
|
||||
## Tests
|
||||
|
||||
### TestMetadataSubscribeBasic
|
||||
Tests basic metadata subscription functionality:
|
||||
- Start a SeaweedFS cluster (master, volume, filer)
|
||||
- Subscribe to metadata changes
|
||||
- Upload files and verify events are received
|
||||
|
||||
### TestMetadataSubscribeSingleFilerNoStall
|
||||
Regression test for [issue #4977](https://github.com/seaweedfs/seaweedfs/issues/4977):
|
||||
- Tests that metadata subscription doesn't stall in single-filer setups
|
||||
- Simulates high-load file uploads while a subscriber tries to keep up
|
||||
- Verifies that events are received without significant stalling
|
||||
|
||||
The bug was that in single-filer setups, `SubscribeMetadata` would block indefinitely
|
||||
on `MetaAggregator.MetaLogBuffer` which remains empty (no peers to aggregate from).
|
||||
The fix ensures that when the buffer is empty, the subscription returns to read from
|
||||
persisted logs on disk.
|
||||
|
||||
### TestMetadataSubscribeResumeFromDisk
|
||||
Tests that subscription can resume from disk:
|
||||
- Upload files before starting subscription
|
||||
- Wait for logs to be flushed to disk
|
||||
- Start subscription from the beginning
|
||||
- Verify pre-uploaded files are received from disk
|
||||
|
||||
## Running Tests
|
||||
|
||||
```bash
|
||||
# Run all tests (requires weed binary in PATH or built)
|
||||
go test -v ./test/metadata_subscribe/...
|
||||
|
||||
# Skip integration tests
|
||||
go test -short ./test/metadata_subscribe/...
|
||||
|
||||
# Run with increased timeout for slow systems
|
||||
go test -v -timeout 5m ./test/metadata_subscribe/...
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
- `weed` binary must be available in PATH or in the parent directories
|
||||
- Tests create temporary directories that are cleaned up after completion
|
||||
- Tests use ports 9333 (master), 8080 (volume), 8888 (filer)
|
||||
|
||||
@@ -0,0 +1,917 @@
|
||||
package metadata_subscribe
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// TestMetadataSubscribeBasic tests basic metadata subscription functionality
|
||||
func TestMetadataSubscribeBasic(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
testDir, err := os.MkdirTemp("", "seaweedfs_metadata_subscribe_test_")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(testDir)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startSeaweedFSCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
// Wait for servers to be ready
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:9333", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8080", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8888", 30*time.Second))
|
||||
|
||||
t.Logf("SeaweedFS cluster started successfully")
|
||||
|
||||
t.Run("subscribe_and_receive_events", func(t *testing.T) {
|
||||
// Create a channel to receive events
|
||||
eventsChan := make(chan *filer_pb.SubscribeMetadataResponse, 100)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
// Start subscribing in a goroutine
|
||||
subCtx, subCancel := context.WithCancel(ctx)
|
||||
defer subCancel()
|
||||
|
||||
go func() {
|
||||
err := subscribeToMetadata(subCtx, "127.0.0.1:8888", "/", eventsChan)
|
||||
if err != nil && !strings.Contains(err.Error(), "context canceled") {
|
||||
errChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for subscription to be established
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Create test files via HTTP
|
||||
testFiles := []string{
|
||||
"/test/file1.txt",
|
||||
"/test/file2.txt",
|
||||
"/test/subdir/file3.txt",
|
||||
}
|
||||
|
||||
for _, path := range testFiles {
|
||||
err := uploadFile("http://127.0.0.1:8888"+path, []byte("test content for "+path))
|
||||
require.NoError(t, err, "Failed to upload %s", path)
|
||||
t.Logf("Uploaded %s", path)
|
||||
}
|
||||
|
||||
// Collect events with timeout
|
||||
receivedPaths := make(map[string]bool)
|
||||
timeout := time.After(30 * time.Second)
|
||||
|
||||
eventLoop:
|
||||
for {
|
||||
select {
|
||||
case event := <-eventsChan:
|
||||
if event.EventNotification != nil && event.EventNotification.NewEntry != nil {
|
||||
path := filepath.Join(event.Directory, event.EventNotification.NewEntry.Name)
|
||||
t.Logf("Received event for: %s", path)
|
||||
receivedPaths[path] = true
|
||||
}
|
||||
// Check if we received all expected events
|
||||
allReceived := true
|
||||
for _, p := range testFiles {
|
||||
if !receivedPaths[p] {
|
||||
allReceived = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if allReceived {
|
||||
break eventLoop
|
||||
}
|
||||
case err := <-errChan:
|
||||
t.Fatalf("Subscription error: %v", err)
|
||||
case <-timeout:
|
||||
t.Logf("Timeout waiting for events. Received %d/%d events", len(receivedPaths), len(testFiles))
|
||||
break eventLoop
|
||||
}
|
||||
}
|
||||
|
||||
// Verify we received events for all test files
|
||||
for _, path := range testFiles {
|
||||
assert.True(t, receivedPaths[path], "Should have received event for %s", path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestMetadataSubscribeSingleFilerNoStall tests that subscription doesn't stall
|
||||
// in single-filer setups (regression test for issue #4977)
|
||||
func TestMetadataSubscribeSingleFilerNoStall(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
testDir, err := os.MkdirTemp("", "seaweedfs_single_filer_test_")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(testDir)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startSeaweedFSCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
// Wait for servers to be ready
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:9333", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8080", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8888", 30*time.Second))
|
||||
|
||||
t.Logf("Single-filer cluster started")
|
||||
|
||||
t.Run("high_load_subscription_no_stall", func(t *testing.T) {
|
||||
// This test simulates the scenario from issue #4977:
|
||||
// High-load writes while a subscriber tries to keep up
|
||||
|
||||
var receivedCount int64
|
||||
var uploadedCount int64
|
||||
|
||||
eventsChan := make(chan *filer_pb.SubscribeMetadataResponse, 1000)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
subCtx, subCancel := context.WithCancel(ctx)
|
||||
defer subCancel()
|
||||
|
||||
// Start subscriber
|
||||
go func() {
|
||||
err := subscribeToMetadata(subCtx, "127.0.0.1:8888", "/", eventsChan)
|
||||
if err != nil && !strings.Contains(err.Error(), "context canceled") {
|
||||
errChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for subscription to be established
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Start counting received events
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case event := <-eventsChan:
|
||||
if event.EventNotification != nil && event.EventNotification.NewEntry != nil {
|
||||
if !event.EventNotification.NewEntry.IsDirectory {
|
||||
atomic.AddInt64(&receivedCount, 1)
|
||||
}
|
||||
}
|
||||
case <-subCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Upload files concurrently (simulate high load)
|
||||
numFiles := 100
|
||||
numWorkers := 10
|
||||
|
||||
uploadWg := sync.WaitGroup{}
|
||||
for w := 0; w < numWorkers; w++ {
|
||||
uploadWg.Add(1)
|
||||
go func(workerId int) {
|
||||
defer uploadWg.Done()
|
||||
for i := 0; i < numFiles/numWorkers; i++ {
|
||||
path := fmt.Sprintf("/load_test/worker%d/file%d.txt", workerId, i)
|
||||
err := uploadFile("http://127.0.0.1:8888"+path, []byte(fmt.Sprintf("content %d-%d", workerId, i)))
|
||||
if err == nil {
|
||||
atomic.AddInt64(&uploadedCount, 1)
|
||||
}
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
|
||||
uploadWg.Wait()
|
||||
uploaded := atomic.LoadInt64(&uploadedCount)
|
||||
t.Logf("Uploaded %d files", uploaded)
|
||||
|
||||
// Wait for events to be received (with timeout to detect stall)
|
||||
stallTimeout := time.After(60 * time.Second)
|
||||
checkInterval := time.NewTicker(2 * time.Second)
|
||||
defer checkInterval.Stop()
|
||||
|
||||
lastReceived := atomic.LoadInt64(&receivedCount)
|
||||
staleCount := 0
|
||||
|
||||
waitLoop:
|
||||
for {
|
||||
select {
|
||||
case <-stallTimeout:
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
t.Logf("Timeout: received %d/%d events (%.1f%%)",
|
||||
received, uploaded, float64(received)/float64(uploaded)*100)
|
||||
break waitLoop
|
||||
case <-checkInterval.C:
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
if received >= uploaded {
|
||||
t.Logf("All %d events received", received)
|
||||
break waitLoop
|
||||
}
|
||||
if received == lastReceived {
|
||||
staleCount++
|
||||
if staleCount >= 5 {
|
||||
// If no progress for 10 seconds, subscription may be stalled
|
||||
t.Logf("WARNING: No progress for %d checks. Received %d/%d (%.1f%%)",
|
||||
staleCount, received, uploaded, float64(received)/float64(uploaded)*100)
|
||||
}
|
||||
} else {
|
||||
staleCount = 0
|
||||
t.Logf("Progress: received %d/%d events (%.1f%%)",
|
||||
received, uploaded, float64(received)/float64(uploaded)*100)
|
||||
}
|
||||
lastReceived = received
|
||||
case err := <-errChan:
|
||||
t.Fatalf("Subscription error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
subCancel()
|
||||
wg.Wait()
|
||||
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
|
||||
// With the fix for #4977, we should receive a high percentage of events
|
||||
// Before the fix, this would stall at ~20-40%
|
||||
percentage := float64(received) / float64(uploaded) * 100
|
||||
t.Logf("Final: received %d/%d events (%.1f%%)", received, uploaded, percentage)
|
||||
|
||||
// We should receive at least 80% of events (allowing for some timing issues)
|
||||
assert.GreaterOrEqual(t, percentage, 80.0,
|
||||
"Should receive at least 80%% of events (received %.1f%%)", percentage)
|
||||
})
|
||||
}
|
||||
|
||||
// TestMetadataSubscribeResumeFromDisk tests that subscription can resume from disk
|
||||
func TestMetadataSubscribeResumeFromDisk(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
testDir, err := os.MkdirTemp("", "seaweedfs_resume_test_")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(testDir)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startSeaweedFSCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:9333", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8080", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8888", 30*time.Second))
|
||||
|
||||
t.Run("upload_before_subscribe", func(t *testing.T) {
|
||||
// Upload files BEFORE starting subscription
|
||||
numFiles := 20
|
||||
for i := 0; i < numFiles; i++ {
|
||||
path := fmt.Sprintf("/pre_subscribe/file%d.txt", i)
|
||||
err := uploadFile("http://127.0.0.1:8888"+path, []byte(fmt.Sprintf("content %d", i)))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
t.Logf("Uploaded %d files before subscription", numFiles)
|
||||
|
||||
// Wait for logs to be flushed to disk
|
||||
time.Sleep(15 * time.Second)
|
||||
|
||||
// Now start subscription from the beginning
|
||||
eventsChan := make(chan *filer_pb.SubscribeMetadataResponse, 100)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
subCtx, subCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer subCancel()
|
||||
|
||||
go func() {
|
||||
err := subscribeToMetadataFromBeginning(subCtx, "127.0.0.1:8888", "/pre_subscribe/", eventsChan)
|
||||
if err != nil && !strings.Contains(err.Error(), "context") {
|
||||
errChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
// Count received events
|
||||
receivedCount := 0
|
||||
timeout := time.After(30 * time.Second)
|
||||
|
||||
countLoop:
|
||||
for {
|
||||
select {
|
||||
case event := <-eventsChan:
|
||||
if event.EventNotification != nil && event.EventNotification.NewEntry != nil {
|
||||
if !event.EventNotification.NewEntry.IsDirectory {
|
||||
receivedCount++
|
||||
t.Logf("Received event %d: %s/%s", receivedCount,
|
||||
event.Directory, event.EventNotification.NewEntry.Name)
|
||||
}
|
||||
}
|
||||
if receivedCount >= numFiles {
|
||||
break countLoop
|
||||
}
|
||||
case err := <-errChan:
|
||||
t.Fatalf("Subscription error: %v", err)
|
||||
case <-timeout:
|
||||
t.Logf("Timeout: received %d/%d events", receivedCount, numFiles)
|
||||
break countLoop
|
||||
}
|
||||
}
|
||||
|
||||
// Should receive all pre-uploaded files from disk
|
||||
assert.GreaterOrEqual(t, receivedCount, numFiles-2, // Allow small margin
|
||||
"Should receive most pre-uploaded files from disk (received %d/%d)", receivedCount, numFiles)
|
||||
})
|
||||
}
|
||||
|
||||
// TestMetadataSubscribeConcurrentWrites tests subscription with concurrent writes
|
||||
func TestMetadataSubscribeConcurrentWrites(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
testDir, err := os.MkdirTemp("", "seaweedfs_concurrent_writes_test_")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(testDir)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startSeaweedFSCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:9333", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8080", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8888", 30*time.Second))
|
||||
|
||||
t.Logf("Cluster started for concurrent writes test")
|
||||
|
||||
t.Run("concurrent_goroutine_writes", func(t *testing.T) {
|
||||
var receivedCount int64
|
||||
var uploadedCount int64
|
||||
|
||||
eventsChan := make(chan *filer_pb.SubscribeMetadataResponse, 10000)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
subCtx, subCancel := context.WithCancel(ctx)
|
||||
defer subCancel()
|
||||
|
||||
// Start subscriber
|
||||
go func() {
|
||||
err := subscribeToMetadata(subCtx, "127.0.0.1:8888", "/concurrent/", eventsChan)
|
||||
if err != nil && !strings.Contains(err.Error(), "context") {
|
||||
errChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Start counting received events
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case event := <-eventsChan:
|
||||
if event.EventNotification != nil && event.EventNotification.NewEntry != nil {
|
||||
if !event.EventNotification.NewEntry.IsDirectory {
|
||||
atomic.AddInt64(&receivedCount, 1)
|
||||
}
|
||||
}
|
||||
case <-subCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Launch many concurrent writers
|
||||
numWorkers := 50
|
||||
filesPerWorker := 20
|
||||
totalExpected := int64(numWorkers * filesPerWorker)
|
||||
|
||||
uploadWg := sync.WaitGroup{}
|
||||
for w := 0; w < numWorkers; w++ {
|
||||
uploadWg.Add(1)
|
||||
go func(workerId int) {
|
||||
defer uploadWg.Done()
|
||||
for i := 0; i < filesPerWorker; i++ {
|
||||
path := fmt.Sprintf("/concurrent/w%d/f%d.txt", workerId, i)
|
||||
content := []byte(fmt.Sprintf("worker%d-file%d", workerId, i))
|
||||
if err := uploadFile("http://127.0.0.1:8888"+path, content); err == nil {
|
||||
atomic.AddInt64(&uploadedCount, 1)
|
||||
}
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
|
||||
uploadWg.Wait()
|
||||
uploaded := atomic.LoadInt64(&uploadedCount)
|
||||
t.Logf("Uploaded %d/%d files from %d concurrent workers", uploaded, totalExpected, numWorkers)
|
||||
|
||||
// Wait for events with progress tracking
|
||||
stallTimeout := time.After(90 * time.Second)
|
||||
checkInterval := time.NewTicker(3 * time.Second)
|
||||
defer checkInterval.Stop()
|
||||
|
||||
lastReceived := int64(0)
|
||||
stableCount := 0
|
||||
|
||||
waitLoop:
|
||||
for {
|
||||
select {
|
||||
case <-stallTimeout:
|
||||
break waitLoop
|
||||
case <-checkInterval.C:
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
if received >= uploaded {
|
||||
t.Logf("All %d events received", received)
|
||||
break waitLoop
|
||||
}
|
||||
if received == lastReceived {
|
||||
stableCount++
|
||||
if stableCount >= 5 {
|
||||
t.Logf("No progress for %d checks, received %d/%d", stableCount, received, uploaded)
|
||||
break waitLoop
|
||||
}
|
||||
} else {
|
||||
stableCount = 0
|
||||
t.Logf("Progress: %d/%d (%.1f%%)", received, uploaded, float64(received)/float64(uploaded)*100)
|
||||
}
|
||||
lastReceived = received
|
||||
case err := <-errChan:
|
||||
t.Fatalf("Subscription error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
subCancel()
|
||||
wg.Wait()
|
||||
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
percentage := float64(received) / float64(uploaded) * 100
|
||||
t.Logf("Final: received %d/%d events (%.1f%%)", received, uploaded, percentage)
|
||||
|
||||
// Should receive at least 80% of events
|
||||
assert.GreaterOrEqual(t, percentage, 80.0,
|
||||
"Should receive at least 80%% of concurrent write events")
|
||||
})
|
||||
}
|
||||
|
||||
// TestMetadataSubscribeMillionUpdates tests subscription with 1 million metadata updates
|
||||
// This test creates metadata entries directly via gRPC without actual file content
|
||||
func TestMetadataSubscribeMillionUpdates(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
testDir, err := os.MkdirTemp("", "seaweedfs_million_updates_test_")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(testDir)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startSeaweedFSCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:9333", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8080", 30*time.Second))
|
||||
require.NoError(t, waitForHTTPServer("http://127.0.0.1:8888", 30*time.Second))
|
||||
|
||||
t.Logf("Cluster started for million updates test")
|
||||
|
||||
t.Run("million_metadata_updates", func(t *testing.T) {
|
||||
var receivedCount int64
|
||||
var createdCount int64
|
||||
totalEntries := int64(1_000_000)
|
||||
|
||||
eventsChan := make(chan *filer_pb.SubscribeMetadataResponse, 100000)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
subCtx, subCancel := context.WithCancel(ctx)
|
||||
defer subCancel()
|
||||
|
||||
// Start subscriber
|
||||
go func() {
|
||||
err := subscribeToMetadata(subCtx, "127.0.0.1:8888", "/million/", eventsChan)
|
||||
if err != nil && !strings.Contains(err.Error(), "context") {
|
||||
errChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Start counting received events
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case event := <-eventsChan:
|
||||
if event.EventNotification != nil && event.EventNotification.NewEntry != nil {
|
||||
if !event.EventNotification.NewEntry.IsDirectory {
|
||||
atomic.AddInt64(&receivedCount, 1)
|
||||
}
|
||||
}
|
||||
case <-subCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Create metadata entries directly via gRPC (no actual file content)
|
||||
numWorkers := 100
|
||||
entriesPerWorker := int(totalEntries) / numWorkers
|
||||
|
||||
startTime := time.Now()
|
||||
createWg := sync.WaitGroup{}
|
||||
|
||||
for w := 0; w < numWorkers; w++ {
|
||||
createWg.Add(1)
|
||||
go func(workerId int) {
|
||||
defer createWg.Done()
|
||||
grpcDialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
|
||||
err := pb.WithFilerClient(false, 0, pb.ServerAddress("127.0.0.1:8888"), grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
for i := 0; i < entriesPerWorker; i++ {
|
||||
dir := fmt.Sprintf("/million/bucket%d", workerId%100)
|
||||
name := fmt.Sprintf("entry_%d_%d", workerId, i)
|
||||
|
||||
_, err := client.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileSize: 100,
|
||||
Mtime: time.Now().Unix(),
|
||||
FileMode: 0644,
|
||||
Uid: 1000,
|
||||
Gid: 1000,
|
||||
},
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
atomic.AddInt64(&createdCount, 1)
|
||||
}
|
||||
|
||||
// Log progress every 10000 entries per worker
|
||||
if i > 0 && i%10000 == 0 {
|
||||
created := atomic.LoadInt64(&createdCount)
|
||||
elapsed := time.Since(startTime)
|
||||
rate := float64(created) / elapsed.Seconds()
|
||||
t.Logf("Worker %d: created %d entries, total %d (%.0f/sec)",
|
||||
workerId, i, created, rate)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Logf("Worker %d error: %v", workerId, err)
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
|
||||
// Progress reporter
|
||||
progressDone := make(chan struct{})
|
||||
go func() {
|
||||
ticker := time.NewTicker(10 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
created := atomic.LoadInt64(&createdCount)
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
elapsed := time.Since(startTime)
|
||||
createRate := float64(created) / elapsed.Seconds()
|
||||
receiveRate := float64(received) / elapsed.Seconds()
|
||||
t.Logf("Progress: created %d (%.0f/sec), received %d (%.0f/sec), lag %d",
|
||||
created, createRate, received, receiveRate, created-received)
|
||||
case <-progressDone:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
createWg.Wait()
|
||||
close(progressDone)
|
||||
|
||||
created := atomic.LoadInt64(&createdCount)
|
||||
elapsed := time.Since(startTime)
|
||||
t.Logf("Created %d entries in %v (%.0f/sec)", created, elapsed, float64(created)/elapsed.Seconds())
|
||||
|
||||
// Wait for subscription to catch up
|
||||
catchupTimeout := time.After(5 * time.Minute)
|
||||
checkInterval := time.NewTicker(5 * time.Second)
|
||||
defer checkInterval.Stop()
|
||||
|
||||
lastReceived := int64(0)
|
||||
stableCount := 0
|
||||
|
||||
waitLoop:
|
||||
for {
|
||||
select {
|
||||
case <-catchupTimeout:
|
||||
t.Logf("Catchup timeout reached")
|
||||
break waitLoop
|
||||
case <-checkInterval.C:
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
if received >= created {
|
||||
t.Logf("All %d events received", received)
|
||||
break waitLoop
|
||||
}
|
||||
if received == lastReceived {
|
||||
stableCount++
|
||||
if stableCount >= 10 {
|
||||
t.Logf("No progress for %d checks", stableCount)
|
||||
break waitLoop
|
||||
}
|
||||
} else {
|
||||
stableCount = 0
|
||||
rate := float64(received-lastReceived) / 5.0
|
||||
t.Logf("Catching up: %d/%d (%.1f%%) at %.0f/sec",
|
||||
received, created, float64(received)/float64(created)*100, rate)
|
||||
}
|
||||
lastReceived = received
|
||||
case err := <-errChan:
|
||||
t.Fatalf("Subscription error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
subCancel()
|
||||
wg.Wait()
|
||||
|
||||
received := atomic.LoadInt64(&receivedCount)
|
||||
percentage := float64(received) / float64(created) * 100
|
||||
totalTime := time.Since(startTime)
|
||||
t.Logf("Final: created %d, received %d (%.1f%%) in %v", created, received, percentage, totalTime)
|
||||
|
||||
// For million entries, we expect at least 90% to be received
|
||||
assert.GreaterOrEqual(t, percentage, 90.0,
|
||||
"Should receive at least 90%% of million metadata events (received %.1f%%)", percentage)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper types and functions
|
||||
|
||||
type TestCluster struct {
|
||||
masterCmd *exec.Cmd
|
||||
volumeCmd *exec.Cmd
|
||||
filerCmd *exec.Cmd
|
||||
testDir string
|
||||
}
|
||||
|
||||
func (c *TestCluster) Stop() {
|
||||
if c.filerCmd != nil && c.filerCmd.Process != nil {
|
||||
c.filerCmd.Process.Kill()
|
||||
c.filerCmd.Wait()
|
||||
}
|
||||
if c.volumeCmd != nil && c.volumeCmd.Process != nil {
|
||||
c.volumeCmd.Process.Kill()
|
||||
c.volumeCmd.Wait()
|
||||
}
|
||||
if c.masterCmd != nil && c.masterCmd.Process != nil {
|
||||
c.masterCmd.Process.Kill()
|
||||
c.masterCmd.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
func startSeaweedFSCluster(ctx context.Context, dataDir string) (*TestCluster, error) {
|
||||
weedBinary := findWeedBinary()
|
||||
if weedBinary == "" {
|
||||
return nil, fmt.Errorf("weed binary not found")
|
||||
}
|
||||
|
||||
cluster := &TestCluster{testDir: dataDir}
|
||||
|
||||
// Create directories
|
||||
masterDir := filepath.Join(dataDir, "master")
|
||||
volumeDir := filepath.Join(dataDir, "volume")
|
||||
filerDir := filepath.Join(dataDir, "filer")
|
||||
if err := os.MkdirAll(masterDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create master dir: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(volumeDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create volume dir: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(filerDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create filer dir: %v", err)
|
||||
}
|
||||
|
||||
// Start master server
|
||||
masterCmd := exec.CommandContext(ctx, weedBinary, "master",
|
||||
"-port", "9333",
|
||||
"-mdir", masterDir,
|
||||
"-volumeSizeLimitMB", "10",
|
||||
"-ip", "127.0.0.1",
|
||||
"-peers", "none",
|
||||
)
|
||||
masterLogFile, err := os.Create(filepath.Join(masterDir, "master.log"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create master log file: %v", err)
|
||||
}
|
||||
masterCmd.Stdout = masterLogFile
|
||||
masterCmd.Stderr = masterLogFile
|
||||
if err := masterCmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("failed to start master: %v", err)
|
||||
}
|
||||
cluster.masterCmd = masterCmd
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Start volume server
|
||||
volumeCmd := exec.CommandContext(ctx, weedBinary, "volume",
|
||||
"-port", "8080",
|
||||
"-dir", volumeDir,
|
||||
"-max", "10",
|
||||
"-master", "127.0.0.1:9333",
|
||||
"-ip", "127.0.0.1",
|
||||
)
|
||||
volumeLogFile, err := os.Create(filepath.Join(volumeDir, "volume.log"))
|
||||
if err != nil {
|
||||
cluster.Stop()
|
||||
return nil, fmt.Errorf("failed to create volume log file: %v", err)
|
||||
}
|
||||
volumeCmd.Stdout = volumeLogFile
|
||||
volumeCmd.Stderr = volumeLogFile
|
||||
if err := volumeCmd.Start(); err != nil {
|
||||
cluster.Stop()
|
||||
return nil, fmt.Errorf("failed to start volume: %v", err)
|
||||
}
|
||||
cluster.volumeCmd = volumeCmd
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Start filer server
|
||||
filerCmd := exec.CommandContext(ctx, weedBinary, "filer",
|
||||
"-port", "8888",
|
||||
"-master", "127.0.0.1:9333",
|
||||
"-ip", "127.0.0.1",
|
||||
)
|
||||
filerLogFile, err := os.Create(filepath.Join(filerDir, "filer.log"))
|
||||
if err != nil {
|
||||
cluster.Stop()
|
||||
return nil, fmt.Errorf("failed to create filer log file: %v", err)
|
||||
}
|
||||
filerCmd.Stdout = filerLogFile
|
||||
filerCmd.Stderr = filerLogFile
|
||||
if err := filerCmd.Start(); err != nil {
|
||||
cluster.Stop()
|
||||
return nil, fmt.Errorf("failed to start filer: %v", err)
|
||||
}
|
||||
cluster.filerCmd = filerCmd
|
||||
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
return cluster, nil
|
||||
}
|
||||
|
||||
func findWeedBinary() string {
|
||||
candidates := []string{
|
||||
"../../../weed/weed",
|
||||
"../../weed/weed",
|
||||
"./weed",
|
||||
"weed",
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if _, err := os.Stat(candidate); err == nil {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
if path, err := exec.LookPath("weed"); err == nil {
|
||||
return path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func waitForHTTPServer(url string, timeout time.Duration) error {
|
||||
start := time.Now()
|
||||
for time.Since(start) < timeout {
|
||||
resp, err := http.Get(url)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("timeout waiting for server %s", url)
|
||||
}
|
||||
|
||||
func uploadFile(url string, content []byte) error {
|
||||
// Create multipart form data
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
|
||||
// Extract filename from URL path
|
||||
parts := strings.Split(url, "/")
|
||||
filename := parts[len(parts)-1]
|
||||
if filename == "" {
|
||||
filename = "file.txt"
|
||||
}
|
||||
|
||||
// Create form file field
|
||||
part, err := writer.CreateFormFile("file", filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create form file: %v", err)
|
||||
}
|
||||
if _, err := part.Write(content); err != nil {
|
||||
return fmt.Errorf("write content: %v", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return fmt.Errorf("close writer: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", url, &buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("upload failed with status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func subscribeToMetadata(ctx context.Context, filerGrpcAddress, pathPrefix string, eventsChan chan<- *filer_pb.SubscribeMetadataResponse) error {
|
||||
return subscribeToMetadataWithOptions(ctx, filerGrpcAddress, pathPrefix, time.Now().UnixNano(), eventsChan)
|
||||
}
|
||||
|
||||
func subscribeToMetadataFromBeginning(ctx context.Context, filerGrpcAddress, pathPrefix string, eventsChan chan<- *filer_pb.SubscribeMetadataResponse) error {
|
||||
// Start from Unix epoch to get all events
|
||||
return subscribeToMetadataWithOptions(ctx, filerGrpcAddress, pathPrefix, 0, eventsChan)
|
||||
}
|
||||
|
||||
func subscribeToMetadataWithOptions(ctx context.Context, filerGrpcAddress, pathPrefix string, sinceNs int64, eventsChan chan<- *filer_pb.SubscribeMetadataResponse) error {
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
if grpcDialOption == nil {
|
||||
grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
}
|
||||
|
||||
return pb.WithFilerClient(false, 0, pb.ServerAddress(filerGrpcAddress), grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
stream, err := client.SubscribeMetadata(ctx, &filer_pb.SubscribeMetadataRequest{
|
||||
ClientName: "integration_test",
|
||||
PathPrefix: pathPrefix,
|
||||
SinceNs: sinceNs,
|
||||
ClientId: util.RandomInt32(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("subscribe: %v", err)
|
||||
}
|
||||
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if err != nil {
|
||||
if err == io.EOF || ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
select {
|
||||
case eventsChan <- resp:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
// Channel full after brief wait, log warning
|
||||
glog.Warningf("Event channel full, skipping event for %s", resp.Directory)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks"
|
||||
)
|
||||
|
||||
@@ -317,11 +318,12 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
quotaEnabled = false
|
||||
}
|
||||
|
||||
// Get versioning and object lock information from extended attributes
|
||||
// Get versioning, object lock, and owner information from extended attributes
|
||||
versioningEnabled := false
|
||||
objectLockEnabled := false
|
||||
objectLockMode := ""
|
||||
var objectLockDuration int32 = 0
|
||||
var owner string
|
||||
|
||||
if resp.Entry.Extended != nil {
|
||||
// Use shared utility to extract versioning information
|
||||
@@ -329,6 +331,11 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
|
||||
// Use shared utility to extract Object Lock information
|
||||
objectLockEnabled, objectLockMode, objectLockDuration = extractObjectLockInfoFromEntry(resp.Entry)
|
||||
|
||||
// Extract owner information
|
||||
if ownerBytes, ok := resp.Entry.Extended[s3_constants.AmzIdentityId]; ok {
|
||||
owner = string(ownerBytes)
|
||||
}
|
||||
}
|
||||
|
||||
bucket := S3Bucket{
|
||||
@@ -343,6 +350,7 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
ObjectLockEnabled: objectLockEnabled,
|
||||
ObjectLockMode: objectLockMode,
|
||||
ObjectLockDuration: objectLockDuration,
|
||||
Owner: owner,
|
||||
}
|
||||
buckets = append(buckets, bucket)
|
||||
}
|
||||
@@ -394,11 +402,12 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
details.Bucket.Quota = quota
|
||||
details.Bucket.QuotaEnabled = quotaEnabled
|
||||
|
||||
// Get versioning and object lock information from extended attributes
|
||||
// Get versioning, object lock, and owner information from extended attributes
|
||||
versioningEnabled := false
|
||||
objectLockEnabled := false
|
||||
objectLockMode := ""
|
||||
var objectLockDuration int32 = 0
|
||||
var owner string
|
||||
|
||||
if bucketResp.Entry.Extended != nil {
|
||||
// Use shared utility to extract versioning information
|
||||
@@ -406,12 +415,18 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
|
||||
// Use shared utility to extract Object Lock information
|
||||
objectLockEnabled, objectLockMode, objectLockDuration = extractObjectLockInfoFromEntry(bucketResp.Entry)
|
||||
|
||||
// Extract owner information
|
||||
if ownerBytes, ok := bucketResp.Entry.Extended[s3_constants.AmzIdentityId]; ok {
|
||||
owner = string(ownerBytes)
|
||||
}
|
||||
}
|
||||
|
||||
details.Bucket.VersioningEnabled = versioningEnabled
|
||||
details.Bucket.ObjectLockEnabled = objectLockEnabled
|
||||
details.Bucket.ObjectLockMode = objectLockMode
|
||||
details.Bucket.ObjectLockDuration = objectLockDuration
|
||||
details.Bucket.Owner = owner
|
||||
|
||||
// List objects in bucket (recursively)
|
||||
return s.listBucketObjects(client, bucketPath, "", details)
|
||||
|
||||
@@ -11,8 +11,14 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// MaxOwnerNameLength is the maximum allowed length for bucket owner identity names.
|
||||
// This is a reasonable limit to prevent abuse; AWS IAM user names are limited to 64 chars,
|
||||
// but we use 256 to allow for more complex identity formats (e.g., email addresses).
|
||||
const MaxOwnerNameLength = 256
|
||||
|
||||
// S3 Bucket management data structures for templates
|
||||
type S3BucketsData struct {
|
||||
Username string `json:"username"`
|
||||
@@ -33,6 +39,7 @@ type CreateBucketRequest struct {
|
||||
ObjectLockMode string `json:"object_lock_mode"` // Object lock mode: "GOVERNANCE" or "COMPLIANCE"
|
||||
SetDefaultRetention bool `json:"set_default_retention"` // Whether to set default retention
|
||||
ObjectLockDuration int32 `json:"object_lock_duration"` // Default retention duration in days
|
||||
Owner string `json:"owner"` // Bucket owner identity (for S3 IAM authentication)
|
||||
}
|
||||
|
||||
// S3 Bucket Management Handlers
|
||||
@@ -118,7 +125,14 @@ func (s *AdminServer) CreateBucket(c *gin.Context) {
|
||||
// Convert quota to bytes
|
||||
quotaBytes := convertQuotaToBytes(req.QuotaSize, req.QuotaUnit)
|
||||
|
||||
err := s.CreateS3BucketWithObjectLock(req.Name, quotaBytes, req.QuotaEnabled, req.VersioningEnabled, req.ObjectLockEnabled, req.ObjectLockMode, req.SetDefaultRetention, req.ObjectLockDuration)
|
||||
// Sanitize owner: trim whitespace and enforce max length
|
||||
owner := strings.TrimSpace(req.Owner)
|
||||
if len(owner) > MaxOwnerNameLength {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Owner name must be %d characters or less", MaxOwnerNameLength)})
|
||||
return
|
||||
}
|
||||
|
||||
err := s.CreateS3BucketWithObjectLock(req.Name, quotaBytes, req.QuotaEnabled, req.VersioningEnabled, req.ObjectLockEnabled, req.ObjectLockMode, req.SetDefaultRetention, req.ObjectLockDuration, owner)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create bucket: " + err.Error()})
|
||||
return
|
||||
@@ -134,6 +148,7 @@ func (s *AdminServer) CreateBucket(c *gin.Context) {
|
||||
"object_lock_enabled": req.ObjectLockEnabled,
|
||||
"object_lock_mode": req.ObjectLockMode,
|
||||
"object_lock_duration": req.ObjectLockDuration,
|
||||
"owner": owner,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -193,6 +208,88 @@ func (s *AdminServer) DeleteBucket(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateBucketOwner updates the owner of an S3 bucket
|
||||
func (s *AdminServer) UpdateBucketOwner(c *gin.Context) {
|
||||
bucketName := c.Param("bucket")
|
||||
if bucketName == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Bucket name is required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Use pointer to detect if owner field was explicitly provided
|
||||
var req struct {
|
||||
Owner *string `json:"owner"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Require owner field to be explicitly provided
|
||||
if req.Owner == nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Owner field is required (use empty string to clear owner)"})
|
||||
return
|
||||
}
|
||||
|
||||
// Trim and validate owner
|
||||
owner := strings.TrimSpace(*req.Owner)
|
||||
if len(owner) > MaxOwnerNameLength {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Owner name must be %d characters or less", MaxOwnerNameLength)})
|
||||
return
|
||||
}
|
||||
|
||||
err := s.SetBucketOwner(bucketName, owner)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update bucket owner: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Bucket owner updated successfully",
|
||||
"bucket": bucketName,
|
||||
"owner": owner,
|
||||
})
|
||||
}
|
||||
|
||||
// SetBucketOwner sets the owner of a bucket
|
||||
func (s *AdminServer) SetBucketOwner(bucketName string, owner string) error {
|
||||
return s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Get the current bucket entry
|
||||
lookupResp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: "/buckets",
|
||||
Name: bucketName,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup bucket %s: %w", bucketName, err)
|
||||
}
|
||||
|
||||
bucketEntry := lookupResp.Entry
|
||||
|
||||
// Initialize Extended map if nil
|
||||
if bucketEntry.Extended == nil {
|
||||
bucketEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
|
||||
// Set or remove the owner
|
||||
if owner == "" {
|
||||
delete(bucketEntry.Extended, s3_constants.AmzIdentityId)
|
||||
} else {
|
||||
bucketEntry.Extended[s3_constants.AmzIdentityId] = []byte(owner)
|
||||
}
|
||||
|
||||
// Update the entry
|
||||
_, err = client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: "/buckets",
|
||||
Entry: bucketEntry,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update bucket owner: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ListBucketsAPI returns the list of buckets as JSON
|
||||
func (s *AdminServer) ListBucketsAPI(c *gin.Context) {
|
||||
buckets, err := s.GetS3Buckets()
|
||||
@@ -288,11 +385,11 @@ func (s *AdminServer) SetBucketQuota(bucketName string, quotaBytes int64, quotaE
|
||||
|
||||
// CreateS3BucketWithQuota creates a new S3 bucket with quota settings
|
||||
func (s *AdminServer) CreateS3BucketWithQuota(bucketName string, quotaBytes int64, quotaEnabled bool) error {
|
||||
return s.CreateS3BucketWithObjectLock(bucketName, quotaBytes, quotaEnabled, false, false, "", false, 0)
|
||||
return s.CreateS3BucketWithObjectLock(bucketName, quotaBytes, quotaEnabled, false, false, "", false, 0, "")
|
||||
}
|
||||
|
||||
// CreateS3BucketWithObjectLock creates a new S3 bucket with quota, versioning, and object lock settings
|
||||
func (s *AdminServer) CreateS3BucketWithObjectLock(bucketName string, quotaBytes int64, quotaEnabled, versioningEnabled, objectLockEnabled bool, objectLockMode string, setDefaultRetention bool, objectLockDuration int32) error {
|
||||
// CreateS3BucketWithObjectLock creates a new S3 bucket with quota, versioning, object lock settings, and owner
|
||||
func (s *AdminServer) CreateS3BucketWithObjectLock(bucketName string, quotaBytes int64, quotaEnabled, versioningEnabled, objectLockEnabled bool, objectLockMode string, setDefaultRetention bool, objectLockDuration int32, owner string) error {
|
||||
return s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
// First ensure /buckets directory exists
|
||||
_, err := client.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
||||
@@ -344,9 +441,14 @@ func (s *AdminServer) CreateS3BucketWithObjectLock(bucketName string, quotaBytes
|
||||
TtlSec: 0,
|
||||
}
|
||||
|
||||
// Create extended attributes map for versioning
|
||||
// Create extended attributes map for versioning and owner
|
||||
extended := make(map[string][]byte)
|
||||
|
||||
// Set bucket owner if specified
|
||||
if owner != "" {
|
||||
extended[s3_constants.AmzIdentityId] = []byte(owner)
|
||||
}
|
||||
|
||||
// Create bucket entry
|
||||
bucketEntry := &filer_pb.Entry{
|
||||
Name: bucketName,
|
||||
|
||||
@@ -82,6 +82,7 @@ type S3Bucket struct {
|
||||
ObjectLockEnabled bool `json:"object_lock_enabled"` // Whether object lock is enabled
|
||||
ObjectLockMode string `json:"object_lock_mode"` // Object lock mode: "GOVERNANCE" or "COMPLIANCE"
|
||||
ObjectLockDuration int32 `json:"object_lock_duration"` // Default retention duration in days
|
||||
Owner string `json:"owner,omitempty"` // Bucket owner identity; empty means admin-only access
|
||||
}
|
||||
|
||||
type S3Object struct {
|
||||
|
||||
@@ -119,6 +119,7 @@ func (h *AdminHandlers) SetupRoutes(r *gin.Engine, authRequired bool, username,
|
||||
s3Api.DELETE("/buckets/:bucket", h.adminServer.DeleteBucket)
|
||||
s3Api.GET("/buckets/:bucket", h.adminServer.ShowBucketDetails)
|
||||
s3Api.PUT("/buckets/:bucket/quota", h.adminServer.UpdateBucketQuota)
|
||||
s3Api.PUT("/buckets/:bucket/owner", h.adminServer.UpdateBucketOwner)
|
||||
}
|
||||
|
||||
// User management API routes
|
||||
@@ -245,6 +246,7 @@ func (h *AdminHandlers) SetupRoutes(r *gin.Engine, authRequired bool, username,
|
||||
s3Api.DELETE("/buckets/:bucket", h.adminServer.DeleteBucket)
|
||||
s3Api.GET("/buckets/:bucket", h.adminServer.ShowBucketDetails)
|
||||
s3Api.PUT("/buckets/:bucket/quota", h.adminServer.UpdateBucketQuota)
|
||||
s3Api.PUT("/buckets/:bucket/owner", h.adminServer.UpdateBucketOwner)
|
||||
}
|
||||
|
||||
// User management API routes
|
||||
|
||||
@@ -113,6 +113,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Owner</th>
|
||||
<th>Created</th>
|
||||
<th>Objects</th>
|
||||
<th>Size</th>
|
||||
@@ -132,6 +133,15 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
{bucket.Name}
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
if bucket.Owner != "" {
|
||||
<span class="badge bg-info">
|
||||
<i class="fas fa-user me-1"></i>{bucket.Owner}
|
||||
</span>
|
||||
} else {
|
||||
<span class="text-muted small">No owner</span>
|
||||
}
|
||||
</td>
|
||||
<td>{bucket.CreatedAt.Format("2006-01-02 15:04")}</td>
|
||||
<td>{fmt.Sprintf("%d", bucket.ObjectCount)}</td>
|
||||
<td>{formatBytes(bucket.Size)}</td>
|
||||
@@ -193,6 +203,13 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
title="View Details">
|
||||
<i class="fas fa-eye"></i>
|
||||
</button>
|
||||
<button type="button"
|
||||
class="btn btn-outline-info btn-sm owner-btn"
|
||||
data-bucket-name={bucket.Name}
|
||||
data-current-owner={bucket.Owner}
|
||||
title="Manage Owner">
|
||||
<i class="fas fa-user-edit"></i>
|
||||
</button>
|
||||
<button type="button"
|
||||
class="btn btn-outline-warning btn-sm quota-btn"
|
||||
data-bucket-name={bucket.Name}
|
||||
@@ -213,7 +230,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
}
|
||||
if len(data.Buckets) == 0 {
|
||||
<tr>
|
||||
<td colspan="8" class="text-center text-muted py-4">
|
||||
<td colspan="9" class="text-center text-muted py-4">
|
||||
<i class="fas fa-cube fa-3x mb-3 text-muted"></i>
|
||||
<div>
|
||||
<h5>No Object Store buckets found</h5>
|
||||
@@ -268,6 +285,17 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="bucketOwner" class="form-label">Owner (Optional)</label>
|
||||
<select class="form-select" id="bucketOwner" name="owner">
|
||||
<option value="">No owner (admin-only access)</option>
|
||||
<!-- Options will be populated dynamically when modal opens -->
|
||||
</select>
|
||||
<div class="form-text">
|
||||
The S3 identity that owns this bucket. Non-admin users can only access buckets they own.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="form-check">
|
||||
@@ -481,9 +509,68 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Manage Owner Modal -->
|
||||
<div class="modal fade" id="manageOwnerModal" tabindex="-1" aria-labelledby="manageOwnerModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="manageOwnerModalLabel">
|
||||
<i class="fas fa-user-edit me-2"></i>Manage Bucket Owner
|
||||
</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form id="ownerForm">
|
||||
<div class="modal-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Bucket Name</label>
|
||||
<input type="text" class="form-control" id="ownerBucketName" readonly>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="bucketOwnerSelect" class="form-label">Owner</label>
|
||||
<select class="form-select" id="bucketOwnerSelect" name="owner">
|
||||
<option value="">No owner (admin-only access)</option>
|
||||
<!-- Options will be populated dynamically -->
|
||||
</select>
|
||||
<div class="form-text">
|
||||
Select the S3 identity that owns this bucket. Non-admin users can only access buckets they own.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="ownerLoadingSpinner" class="text-center py-2" style="display: none;">
|
||||
<div class="spinner-border spinner-border-sm text-primary" role="status">
|
||||
<span class="visually-hidden">Loading users...</span>
|
||||
</div>
|
||||
<span class="ms-2">Loading users...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="submit" class="btn btn-info">
|
||||
<i class="fas fa-save me-1"></i>Update Owner
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- JavaScript for bucket management -->
|
||||
<script>
|
||||
// Global state (shared between DOMContentLoaded handlers and global functions)
|
||||
let deleteModalInstance = null;
|
||||
let quotaModalInstance = null;
|
||||
let ownerModalInstance = null;
|
||||
let detailsModalInstance = null;
|
||||
let cachedUsers = null;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Initialize modal instances once (reuse with show/hide)
|
||||
deleteModalInstance = new bootstrap.Modal(document.getElementById('deleteBucketModal'));
|
||||
quotaModalInstance = new bootstrap.Modal(document.getElementById('manageQuotaModal'));
|
||||
ownerModalInstance = new bootstrap.Modal(document.getElementById('manageOwnerModal'));
|
||||
detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));
|
||||
|
||||
const quotaCheckbox = document.getElementById('enableQuota');
|
||||
const quotaSettings = document.getElementById('quotaSettings');
|
||||
const versioningCheckbox = document.getElementById('enableVersioning');
|
||||
@@ -517,6 +604,32 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
defaultRetentionSettings.style.display = this.checked ? 'block' : 'none';
|
||||
});
|
||||
|
||||
// Populate owner dropdown when create bucket modal opens
|
||||
document.getElementById('createBucketModal').addEventListener('show.bs.modal', async function() {
|
||||
const ownerSelect = document.getElementById('bucketOwner');
|
||||
|
||||
// Only fetch if not already populated
|
||||
if (ownerSelect.options.length <= 1) {
|
||||
try {
|
||||
const response = await fetch('/api/users');
|
||||
const data = await response.json();
|
||||
const users = data.users || [];
|
||||
|
||||
users.forEach(user => {
|
||||
const option = document.createElement('option');
|
||||
option.value = user.username;
|
||||
option.textContent = user.username;
|
||||
ownerSelect.appendChild(option);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching users for owner dropdown:', error);
|
||||
// Reset to default state on error - user can still create bucket without owner
|
||||
ownerSelect.innerHTML = '<option value="">No owner (admin-only access)</option>';
|
||||
ownerSelect.selectedIndex = 0;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Handle form submission
|
||||
createBucketForm.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
@@ -524,6 +637,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
const formData = new FormData(this);
|
||||
const data = {
|
||||
name: formData.get('name'),
|
||||
owner: formData.get('owner') || '',
|
||||
region: formData.get('region') || '',
|
||||
quota_size: quotaCheckbox.checked ? parseInt(formData.get('quota_size')) || 0 : 0,
|
||||
quota_unit: formData.get('quota_unit') || 'MB',
|
||||
@@ -569,41 +683,19 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
});
|
||||
|
||||
// Handle delete bucket
|
||||
let deleteModalInstance = null;
|
||||
const deleteForm = document.getElementById('deleteBucketModal');
|
||||
document.querySelectorAll('.delete-bucket-btn').forEach(button => {
|
||||
button.addEventListener('click', function() {
|
||||
const bucketName = this.dataset.bucketName;
|
||||
document.getElementById('deleteBucketName').textContent = bucketName;
|
||||
window.currentBucketToDelete = bucketName;
|
||||
|
||||
// Dispose of existing modal instance if it exists
|
||||
if (deleteModalInstance) {
|
||||
deleteModalInstance.dispose();
|
||||
}
|
||||
|
||||
// Create new modal instance
|
||||
deleteModalInstance = new bootstrap.Modal(document.getElementById('deleteBucketModal'));
|
||||
// Store bucket name on modal element instead of global window property
|
||||
deleteForm.dataset.bucketName = bucketName;
|
||||
deleteModalInstance.show();
|
||||
});
|
||||
});
|
||||
|
||||
// Add event listener to properly dispose of delete modal when hidden
|
||||
document.getElementById('deleteBucketModal').addEventListener('hidden.bs.modal', function() {
|
||||
if (deleteModalInstance) {
|
||||
deleteModalInstance.dispose();
|
||||
deleteModalInstance = null;
|
||||
}
|
||||
// Force remove any remaining backdrops
|
||||
document.querySelectorAll('.modal-backdrop').forEach(backdrop => {
|
||||
backdrop.remove();
|
||||
});
|
||||
// Ensure body classes are removed
|
||||
document.body.classList.remove('modal-open');
|
||||
document.body.style.removeProperty('padding-right');
|
||||
});
|
||||
|
||||
// Handle quota management
|
||||
let quotaModalInstance = null;
|
||||
const quotaForm = document.getElementById('quotaForm');
|
||||
document.querySelectorAll('.quota-btn').forEach(button => {
|
||||
button.addEventListener('click', function() {
|
||||
const bucketName = this.dataset.bucketName;
|
||||
@@ -617,15 +709,8 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
// Toggle quota size settings
|
||||
document.getElementById('quotaSizeSettings').style.display = quotaEnabled ? 'block' : 'none';
|
||||
|
||||
window.currentBucketToUpdate = bucketName;
|
||||
|
||||
// Dispose of existing modal instance if it exists
|
||||
if (quotaModalInstance) {
|
||||
quotaModalInstance.dispose();
|
||||
}
|
||||
|
||||
// Create new modal instance
|
||||
quotaModalInstance = new bootstrap.Modal(document.getElementById('manageQuotaModal'));
|
||||
// Store bucket name on form element instead of global window property
|
||||
quotaForm.dataset.bucketName = bucketName;
|
||||
quotaModalInstance.show();
|
||||
});
|
||||
});
|
||||
@@ -649,6 +734,9 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
document.getElementById('quotaForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const bucketName = this.dataset.bucketName;
|
||||
if (!bucketName) return;
|
||||
|
||||
const formData = new FormData(this);
|
||||
const enabled = document.getElementById('quotaEnabled').checked;
|
||||
const data = {
|
||||
@@ -657,7 +745,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
quota_enabled: enabled
|
||||
};
|
||||
|
||||
fetch(`/api/s3/buckets/${window.currentBucketToUpdate}/quota`, {
|
||||
fetch(`/api/s3/buckets/${bucketName}/quota`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -688,8 +776,97 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
document.getElementById('quotaSizeSettings').style.display = this.checked ? 'block' : 'none';
|
||||
});
|
||||
|
||||
// Handle owner management
|
||||
const ownerForm = document.getElementById('ownerForm');
|
||||
document.querySelectorAll('.owner-btn').forEach(button => {
|
||||
button.addEventListener('click', async function() {
|
||||
const bucketName = this.dataset.bucketName;
|
||||
const currentOwner = this.dataset.currentOwner || '';
|
||||
|
||||
document.getElementById('ownerBucketName').value = bucketName;
|
||||
// Store bucket name on form element instead of global window property
|
||||
ownerForm.dataset.bucketName = bucketName;
|
||||
|
||||
// Show loading spinner
|
||||
document.getElementById('ownerLoadingSpinner').style.display = 'block';
|
||||
document.getElementById('bucketOwnerSelect').disabled = true;
|
||||
|
||||
ownerModalInstance.show();
|
||||
|
||||
// Fetch users if not cached
|
||||
try {
|
||||
if (!cachedUsers) {
|
||||
const response = await fetch('/api/users');
|
||||
const data = await response.json();
|
||||
cachedUsers = data.users || [];
|
||||
}
|
||||
|
||||
// Populate the select dropdown
|
||||
const select = document.getElementById('bucketOwnerSelect');
|
||||
select.innerHTML = '<option value="">No owner (admin-only access)</option>';
|
||||
|
||||
cachedUsers.forEach(user => {
|
||||
const option = document.createElement('option');
|
||||
option.value = user.username;
|
||||
option.textContent = user.username;
|
||||
if (user.username === currentOwner) {
|
||||
option.selected = true;
|
||||
}
|
||||
select.appendChild(option);
|
||||
});
|
||||
|
||||
select.disabled = false;
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', error);
|
||||
alert('Error loading users: ' + error.message);
|
||||
// Re-enable select and reset to default on error
|
||||
const select = document.getElementById('bucketOwnerSelect');
|
||||
select.innerHTML = '<option value="">No owner (admin-only access)</option>';
|
||||
select.selectedIndex = 0;
|
||||
select.disabled = false;
|
||||
} finally {
|
||||
document.getElementById('ownerLoadingSpinner').style.display = 'none';
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Handle owner form submission
|
||||
document.getElementById('ownerForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const bucketName = this.dataset.bucketName;
|
||||
if (!bucketName) return;
|
||||
|
||||
const owner = document.getElementById('bucketOwnerSelect').value;
|
||||
const data = { owner: owner };
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}/owner`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.error) {
|
||||
alert('Error updating owner: ' + data.error);
|
||||
} else {
|
||||
alert('Bucket owner updated successfully!');
|
||||
// Properly close the modal before reloading
|
||||
if (ownerModalInstance) {
|
||||
ownerModalInstance.hide();
|
||||
}
|
||||
setTimeout(() => location.reload(), 500);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Error updating owner: ' + error.message);
|
||||
});
|
||||
});
|
||||
|
||||
// Handle view details button
|
||||
let detailsModalInstance = null;
|
||||
document.querySelectorAll('.view-details-btn').forEach(button => {
|
||||
button.addEventListener('click', function() {
|
||||
const bucketName = this.dataset.bucketName;
|
||||
@@ -707,13 +884,6 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
'<div class="mt-2">Loading bucket details...</div>' +
|
||||
'</div>';
|
||||
|
||||
// Dispose of existing modal instance if it exists
|
||||
if (detailsModalInstance) {
|
||||
detailsModalInstance.dispose();
|
||||
}
|
||||
|
||||
// Create new modal instance
|
||||
detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));
|
||||
detailsModalInstance.show();
|
||||
|
||||
// Fetch bucket details
|
||||
@@ -740,25 +910,10 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Add event listener to properly dispose of details modal when hidden
|
||||
document.getElementById('bucketDetailsModal').addEventListener('hidden.bs.modal', function() {
|
||||
if (detailsModalInstance) {
|
||||
detailsModalInstance.dispose();
|
||||
detailsModalInstance = null;
|
||||
}
|
||||
// Force remove any remaining backdrops
|
||||
document.querySelectorAll('.modal-backdrop').forEach(backdrop => {
|
||||
backdrop.remove();
|
||||
});
|
||||
// Ensure body classes are removed
|
||||
document.body.classList.remove('modal-open');
|
||||
document.body.style.removeProperty('padding-right');
|
||||
});
|
||||
});
|
||||
|
||||
function deleteBucket() {
|
||||
const bucketName = window.currentBucketToDelete;
|
||||
const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;
|
||||
if (!bucketName) return;
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}`, {
|
||||
@@ -786,6 +941,16 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
function displayBucketDetails(data) {
|
||||
const bucket = data.bucket;
|
||||
const objects = data.objects || [];
|
||||
|
||||
// Helper function to escape HTML to prevent XSS
|
||||
function escapeHtml(v) {
|
||||
return String(v ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// Helper function to format bytes
|
||||
function formatBytes(bytes) {
|
||||
@@ -818,10 +983,10 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
'<tbody>' +
|
||||
objects.map(obj =>
|
||||
'<tr>' +
|
||||
'<td><i class="fas fa-file me-1"></i>' + obj.key + '</td>' +
|
||||
'<td><i class="fas fa-file me-1"></i>' + escapeHtml(obj.key) + '</td>' +
|
||||
'<td>' + formatBytes(obj.size) + '</td>' +
|
||||
'<td>' + formatDate(obj.last_modified) + '</td>' +
|
||||
'<td><span class="badge bg-primary">' + obj.storage_class + '</span></td>' +
|
||||
'<td><span class="badge bg-primary">' + escapeHtml(obj.storage_class) + '</span></td>' +
|
||||
'</tr>'
|
||||
).join('') +
|
||||
'</tbody>' +
|
||||
@@ -840,7 +1005,11 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
'<table class="table table-sm">' +
|
||||
'<tr>' +
|
||||
'<td><strong>Name:</strong></td>' +
|
||||
'<td>' + bucket.name + '</td>' +
|
||||
'<td>' + escapeHtml(bucket.name) + '</td>' +
|
||||
'</tr>' +
|
||||
'<tr>' +
|
||||
'<td><strong>Owner:</strong></td>' +
|
||||
'<td>' + (bucket.owner ? '<span class="badge bg-info"><i class="fas fa-user me-1"></i>' + escapeHtml(bucket.owner) + '</span>' : '<span class="text-muted">No owner (admin-only)</span>') + '</td>' +
|
||||
'</tr>' +
|
||||
'<tr>' +
|
||||
'<td><strong>Created:</strong></td>' +
|
||||
@@ -886,7 +1055,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
'<td>' +
|
||||
(bucket.object_lock_enabled ?
|
||||
'<span class="badge bg-warning"><i class="fas fa-lock me-1"></i>Enabled</span>' +
|
||||
'<br><small class="text-muted">' + bucket.object_lock_mode + ' • ' + bucket.object_lock_duration + ' days</small>' :
|
||||
'<br><small class="text-muted">' + escapeHtml(bucket.object_lock_mode) + ' • ' + bucket.object_lock_duration + ' days</small>' :
|
||||
'<span class="badge bg-secondary"><i class="fas fa-unlock me-1"></i>Disabled</span>'
|
||||
) +
|
||||
'</td>' +
|
||||
@@ -906,26 +1075,45 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
}
|
||||
|
||||
function exportBucketList() {
|
||||
// Simple CSV export
|
||||
// RFC 4180 compliant CSV escaping: escape double quotes by doubling them
|
||||
function escapeCsvField(value) {
|
||||
const str = String(value ?? '');
|
||||
// If the field contains comma, double quote, or newline, wrap in quotes and escape internal quotes
|
||||
if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
|
||||
return '"' + str.replace(/"/g, '""') + '"';
|
||||
}
|
||||
return '"' + str + '"';
|
||||
}
|
||||
|
||||
const buckets = Array.from(document.querySelectorAll('#bucketsTable tbody tr')).map(row => {
|
||||
const cells = row.querySelectorAll('td');
|
||||
if (cells.length > 1) {
|
||||
return {
|
||||
name: cells[0].textContent.trim(),
|
||||
created: cells[1].textContent.trim(),
|
||||
objects: cells[2].textContent.trim(),
|
||||
size: cells[3].textContent.trim(),
|
||||
quota: cells[4].textContent.trim(),
|
||||
versioning: cells[5].textContent.trim(),
|
||||
objectLock: cells[6].textContent.trim()
|
||||
owner: cells[1].textContent.trim(),
|
||||
created: cells[2].textContent.trim(),
|
||||
objects: cells[3].textContent.trim(),
|
||||
size: cells[4].textContent.trim(),
|
||||
quota: cells[5].textContent.trim(),
|
||||
versioning: cells[6].textContent.trim(),
|
||||
objectLock: cells[7].textContent.trim()
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}).filter(bucket => bucket !== null);
|
||||
|
||||
const csvContent = "data:text/csv;charset=utf-8," +
|
||||
"Name,Created,Objects,Size,Quota,Versioning,Object Lock\n" +
|
||||
buckets.map(b => '"' + b.name + '","' + b.created + '","' + b.objects + '","' + b.size + '","' + b.quota + '","' + b.versioning + '","' + b.objectLock + '"').join("\n");
|
||||
"Name,Owner,Created,Objects,Size,Quota,Versioning,Object Lock\n" +
|
||||
buckets.map(b => [
|
||||
escapeCsvField(b.name),
|
||||
escapeCsvField(b.owner),
|
||||
escapeCsvField(b.created),
|
||||
escapeCsvField(b.objects),
|
||||
escapeCsvField(b.size),
|
||||
escapeCsvField(b.quota),
|
||||
escapeCsvField(b.versioning),
|
||||
escapeCsvField(b.objectLock)
|
||||
].join(',')).join("\n");
|
||||
|
||||
const encodedUri = encodeURI(csvContent);
|
||||
const link = document.createElement("a");
|
||||
|
||||
@@ -73,7 +73,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div><div class=\"col-auto\"><i class=\"fas fa-clock fa-2x text-gray-300\"></i></div></div></div></div></div></div><!-- Buckets Table --><div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-cube me-2\"></i>Object Store Buckets</h6><div class=\"dropdown no-arrow\"><a class=\"dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\"><i class=\"fas fa-ellipsis-v fa-sm fa-fw text-gray-400\"></i></a><div class=\"dropdown-menu dropdown-menu-right shadow animated--fade-in\"><div class=\"dropdown-header\">Actions:</div><a class=\"dropdown-item\" href=\"#\" onclick=\"exportBucketList()\"><i class=\"fas fa-download me-2\"></i>Export List</a></div></div></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\" id=\"bucketsTable\"><thead><tr><th>Name</th><th>Created</th><th>Objects</th><th>Size</th><th>Quota</th><th>Versioning</th><th>Object Lock</th><th>Actions</th></tr></thead> <tbody>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div><div class=\"col-auto\"><i class=\"fas fa-clock fa-2x text-gray-300\"></i></div></div></div></div></div></div><!-- Buckets Table --><div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-cube me-2\"></i>Object Store Buckets</h6><div class=\"dropdown no-arrow\"><a class=\"dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\"><i class=\"fas fa-ellipsis-v fa-sm fa-fw text-gray-400\"></i></a><div class=\"dropdown-menu dropdown-menu-right shadow animated--fade-in\"><div class=\"dropdown-header\">Actions:</div><a class=\"dropdown-item\" href=\"#\" onclick=\"exportBucketList()\"><i class=\"fas fa-download me-2\"></i>Export List</a></div></div></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\" id=\"bucketsTable\"><thead><tr><th>Name</th><th>Owner</th><th>Created</th><th>Objects</th><th>Size</th><th>Quota</th><th>Versioning</th><th>Object Lock</th><th>Actions</th></tr></thead> <tbody>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -85,7 +85,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var5 templ.SafeURL
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/s3/buckets/%s", bucket.Name)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 129, Col: 114}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 130, Col: 114}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -98,7 +98,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 132, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 133, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -108,278 +108,332 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 135, Col: 92}
|
||||
if bucket.Owner != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<span class=\"badge bg-info\"><i class=\"fas fa-user me-1\"></i>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 139, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "<span class=\"text-muted small\">No owner</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", bucket.ObjectCount))
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 136, Col: 86}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 145, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Size))
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", bucket.ObjectCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 137, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 146, Col: 86}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Size))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 147, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if bucket.Quota > 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "<div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "<div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 = []any{fmt.Sprintf("badge bg-%s", getQuotaStatusColor(bucket.Size, bucket.Quota, bucket.QuotaEnabled))}
|
||||
templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var10...)
|
||||
var templ_7745c5c3_Var11 = []any{fmt.Sprintf("badge bg-%s", getQuotaStatusColor(bucket.Size, bucket.Quota, bucket.QuotaEnabled))}
|
||||
templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var11...)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "<span class=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var10).String())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 1, Col: 0}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<span class=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Quota))
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var11).String())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 142, Col: 86}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 1, Col: 0}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</span> ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Quota))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 152, Col: 86}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</span> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if bucket.QuotaEnabled {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "<div class=\"small text-muted\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<div class=\"small text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%% used", float64(bucket.Size)/float64(bucket.Quota)*100))
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%% used", float64(bucket.Size)/float64(bucket.Quota)*100))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 146, Col: 139}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 156, Col: 139}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "<div class=\"small text-muted\">Disabled</div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "<div class=\"small text-muted\">Disabled</div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<span class=\"text-muted\">No quota</span>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<span class=\"text-muted\">No quota</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if bucket.VersioningEnabled {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Enabled</span>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Enabled</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "<span class=\"badge bg-secondary\"><i class=\"fas fa-times me-1\"></i>Disabled</span>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<span class=\"badge bg-secondary\"><i class=\"fas fa-times me-1\"></i>Disabled</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "</td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if bucket.ObjectLockEnabled {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "<div><span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span><div class=\"small text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 174, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, " • ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<div><span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span><div class=\"small text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 174, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 184, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</div></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, " • ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 184, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</div></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "<span class=\"badge bg-secondary\"><i class=\"fas fa-unlock me-1\"></i>Disabled</span>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "<span class=\"badge bg-secondary\"><i class=\"fas fa-unlock me-1\"></i>Disabled</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 templ.SafeURL
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
|
||||
var templ_7745c5c3_Var17 templ.SafeURL
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 185, Col: 127}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 192, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 195, Col: 127}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 198, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 202, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "\" data-current-quota=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm owner-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 199, Col: 125}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 208, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" data-quota-enabled=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" data-current-owner=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 200, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 209, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" title=\"Manage Owner\"><i class=\"fas fa-user-edit\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 206, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 215, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-current-quota=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 216, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-quota-enabled=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 217, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 223, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
if len(data.Buckets) == 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "<tr><td colspan=\"8\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<tr><td colspan=\"9\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</tbody></table></div></div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "</tbody></table></div></div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 243, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 260, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the bucket <strong id=\"deleteBucketName\"></strong>?</p><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Warning:</strong> This action cannot be undone. All objects Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
+35
-35
@@ -42,39 +42,39 @@ var (
|
||||
)
|
||||
|
||||
type FilerOptions struct {
|
||||
masters *pb.ServerDiscovery
|
||||
mastersString *string
|
||||
ip *string
|
||||
bindIp *string
|
||||
port *int
|
||||
portGrpc *int
|
||||
publicPort *int
|
||||
filerGroup *string
|
||||
collection *string
|
||||
defaultReplicaPlacement *string
|
||||
disableDirListing *bool
|
||||
maxMB *int
|
||||
dirListingLimit *int
|
||||
dataCenter *string
|
||||
rack *string
|
||||
enableNotification *bool
|
||||
disableHttp *bool
|
||||
cipher *bool
|
||||
metricsHttpPort *int
|
||||
metricsHttpIp *string
|
||||
saveToFilerLimit *int
|
||||
defaultLevelDbDirectory *string
|
||||
concurrentUploadLimitMB *int
|
||||
concurrentFileUploadLimit *int
|
||||
debug *bool
|
||||
debugPort *int
|
||||
localSocket *string
|
||||
showUIDirectoryDelete *bool
|
||||
downloadMaxMBps *int
|
||||
diskType *string
|
||||
allowedOrigins *string
|
||||
exposeDirectoryData *bool
|
||||
certProvider certprovider.Provider
|
||||
masters *pb.ServerDiscovery
|
||||
mastersString *string
|
||||
ip *string
|
||||
bindIp *string
|
||||
port *int
|
||||
portGrpc *int
|
||||
publicPort *int
|
||||
filerGroup *string
|
||||
collection *string
|
||||
defaultReplicaPlacement *string
|
||||
disableDirListing *bool
|
||||
maxMB *int
|
||||
dirListingLimit *int
|
||||
dataCenter *string
|
||||
rack *string
|
||||
enableNotification *bool
|
||||
disableHttp *bool
|
||||
cipher *bool
|
||||
metricsHttpPort *int
|
||||
metricsHttpIp *string
|
||||
saveToFilerLimit *int
|
||||
defaultLevelDbDirectory *string
|
||||
concurrentUploadLimitMB *int
|
||||
concurrentFileUploadLimit *int
|
||||
debug *bool
|
||||
debugPort *int
|
||||
localSocket *string
|
||||
showUIDirectoryDelete *bool
|
||||
downloadMaxMBps *int
|
||||
diskType *string
|
||||
allowedOrigins *string
|
||||
exposeDirectoryData *bool
|
||||
certProvider certprovider.Provider
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -99,7 +99,7 @@ func init() {
|
||||
f.metricsHttpIp = cmdFiler.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
|
||||
f.saveToFilerLimit = cmdFiler.Flag.Int("saveToFilerLimit", 0, "files smaller than this limit will be saved in filer store")
|
||||
f.defaultLevelDbDirectory = cmdFiler.Flag.String("defaultStoreDir", ".", "if filer.toml is empty, use an embedded filer store in the directory")
|
||||
f.concurrentUploadLimitMB = cmdFiler.Flag.Int("concurrentUploadLimitMB", 128, "limit total concurrent upload size")
|
||||
f.concurrentUploadLimitMB = cmdFiler.Flag.Int("concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
|
||||
f.concurrentFileUploadLimit = cmdFiler.Flag.Int("concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
|
||||
f.debug = cmdFiler.Flag.Bool("debug", false, "serves runtime profiling data, e.g., http://localhost:<debug.port>/debug/pprof/goroutine?debug=2")
|
||||
f.debugPort = cmdFiler.Flag.Int("debug.port", 6060, "http port for debugging")
|
||||
@@ -132,7 +132,7 @@ func init() {
|
||||
filerS3Options.tlsVerifyClientCert = cmdFiler.Flag.Bool("s3.tlsVerifyClientCert", false, "whether to verify the client's certificate")
|
||||
filerS3Options.bindIp = cmdFiler.Flag.String("s3.ip.bind", "", "ip address to bind to. If empty, default to same as -ip.bind option.")
|
||||
filerS3Options.idleTimeout = cmdFiler.Flag.Int("s3.idleTimeout", 120, "connection idle seconds")
|
||||
filerS3Options.concurrentUploadLimitMB = cmdFiler.Flag.Int("s3.concurrentUploadLimitMB", 128, "limit total concurrent upload size for S3")
|
||||
filerS3Options.concurrentUploadLimitMB = cmdFiler.Flag.Int("s3.concurrentUploadLimitMB", 0, "limit total concurrent upload size for S3, 0 means unlimited")
|
||||
filerS3Options.concurrentFileUploadLimit = cmdFiler.Flag.Int("s3.concurrentFileUploadLimit", 0, "limit number of concurrent file uploads for S3, 0 means unlimited")
|
||||
|
||||
// start webdav on filer
|
||||
|
||||
@@ -60,10 +60,22 @@ const (
|
||||
DefaultConcurrencyLimit = 32
|
||||
)
|
||||
|
||||
// syncState tracks the current sync state for graceful shutdown checkpoint saving
|
||||
type syncState struct {
|
||||
processor *MetadataProcessor
|
||||
grpcDialOption grpc.DialOption
|
||||
targetFiler pb.ServerAddress
|
||||
sourcePath string
|
||||
sourceFilerSignature int32
|
||||
}
|
||||
|
||||
var (
|
||||
syncOptions SyncOptions
|
||||
syncCpuProfile *string
|
||||
syncMemProfile *string
|
||||
// atomic pointers to current sync states for graceful shutdown
|
||||
syncStateA2B atomic.Pointer[syncState]
|
||||
syncStateB2A atomic.Pointer[syncState]
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -143,6 +155,27 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// register graceful shutdown hook to save checkpoints
|
||||
grace.OnInterrupt(func() {
|
||||
saveCheckpoint := func(name string, state *syncState) {
|
||||
if state == nil || state.processor == nil {
|
||||
return
|
||||
}
|
||||
offsetTsNs := state.processor.processedTsWatermark.Load()
|
||||
if offsetTsNs == 0 {
|
||||
return
|
||||
}
|
||||
if err := setOffset(state.grpcDialOption, state.targetFiler, getSignaturePrefixByPath(state.sourcePath), state.sourceFilerSignature, offsetTsNs); err != nil {
|
||||
glog.Errorf("failed to save checkpoint for %s on shutdown: %v", name, err)
|
||||
} else {
|
||||
glog.V(0).Infof("saved checkpoint for %s on shutdown: %v", name, time.Unix(0, offsetTsNs))
|
||||
}
|
||||
}
|
||||
|
||||
saveCheckpoint("A->B", syncStateA2B.Load())
|
||||
saveCheckpoint("B->A", syncStateB2A.Load())
|
||||
})
|
||||
|
||||
go func() {
|
||||
// a->b
|
||||
// set synchronization start timestamp to offset
|
||||
@@ -172,7 +205,8 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
*syncOptions.concurrency,
|
||||
*syncOptions.bDoDeleteFiles,
|
||||
aFilerSignature,
|
||||
bFilerSignature)
|
||||
bFilerSignature,
|
||||
&syncStateA2B)
|
||||
if err != nil {
|
||||
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
|
||||
time.Sleep(1747 * time.Millisecond)
|
||||
@@ -210,7 +244,8 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
*syncOptions.concurrency,
|
||||
*syncOptions.aDoDeleteFiles,
|
||||
bFilerSignature,
|
||||
aFilerSignature)
|
||||
aFilerSignature,
|
||||
&syncStateB2A)
|
||||
if err != nil {
|
||||
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
|
||||
time.Sleep(2147 * time.Millisecond)
|
||||
@@ -241,7 +276,7 @@ func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAdd
|
||||
}
|
||||
|
||||
func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceExcludePaths []string, sourceReadChunkFromFiler bool, targetFiler pb.ServerAddress, targetPath string,
|
||||
replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, doDeleteFiles bool, sourceFilerSignature int32, targetFilerSignature int32) error {
|
||||
replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, doDeleteFiles bool, sourceFilerSignature int32, targetFilerSignature int32, statePtr *atomic.Pointer[syncState]) error {
|
||||
|
||||
// if first time, start from now
|
||||
// if has previously synced, resume from that point of time
|
||||
@@ -278,6 +313,17 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, grpcDialOpti
|
||||
}
|
||||
processor := NewMetadataProcessor(processEventFn, concurrency, sourceFilerOffsetTsNs)
|
||||
|
||||
// update sync state for graceful shutdown checkpoint saving
|
||||
if statePtr != nil {
|
||||
statePtr.Store(&syncState{
|
||||
processor: processor,
|
||||
grpcDialOption: grpcDialOption,
|
||||
targetFiler: targetFiler,
|
||||
sourcePath: sourcePath,
|
||||
sourceFilerSignature: sourceFilerSignature,
|
||||
})
|
||||
}
|
||||
|
||||
var lastLogTsNs = time.Now().UnixNano()
|
||||
var clientName = fmt.Sprintf("syncFrom_%s_To_%s", string(sourceFiler), string(targetFiler))
|
||||
processEventFnWithOffset := pb.AddOffsetFunc(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
|
||||
@@ -37,6 +37,9 @@ type MountOptions struct {
|
||||
extraOptions []string
|
||||
fuseCommandPid int
|
||||
|
||||
// Periodic metadata flush to protect against orphan chunk cleanup
|
||||
metadataFlushSeconds *int
|
||||
|
||||
// RDMA acceleration options
|
||||
rdmaEnabled *bool
|
||||
rdmaSidecarAddr *string
|
||||
@@ -85,6 +88,9 @@ func init() {
|
||||
mountOptions.disableXAttr = cmdMount.Flag.Bool("disableXAttr", false, "disable xattr")
|
||||
mountOptions.fuseCommandPid = 0
|
||||
|
||||
// Periodic metadata flush to protect against orphan chunk cleanup
|
||||
mountOptions.metadataFlushSeconds = cmdMount.Flag.Int("metadataFlushSeconds", 120, "periodically flush file metadata to filer in seconds (0 to disable). This protects chunks from being purged by volume.fsck for long-running writes")
|
||||
|
||||
// RDMA acceleration flags
|
||||
mountOptions.rdmaEnabled = cmdMount.Flag.Bool("rdma.enabled", false, "enable RDMA acceleration for reads")
|
||||
mountOptions.rdmaSidecarAddr = cmdMount.Flag.String("rdma.sidecar", "", "RDMA sidecar address (e.g., localhost:8081)")
|
||||
|
||||
@@ -254,6 +254,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
UidGidMapper: uidGidMapper,
|
||||
DisableXAttr: *option.disableXAttr,
|
||||
IsMacOs: runtime.GOOS == "darwin",
|
||||
MetadataFlushSeconds: *option.metadataFlushSeconds,
|
||||
// RDMA acceleration options
|
||||
RdmaEnabled: *option.rdmaEnabled,
|
||||
RdmaSidecarAddr: *option.rdmaSidecarAddr,
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ func init() {
|
||||
s3StandaloneOptions.localFilerSocket = cmdS3.Flag.String("localFilerSocket", "", "local filer socket path")
|
||||
s3StandaloneOptions.localSocket = cmdS3.Flag.String("localSocket", "", "default to /tmp/seaweedfs-s3-<port>.sock")
|
||||
s3StandaloneOptions.idleTimeout = cmdS3.Flag.Int("idleTimeout", 120, "connection idle seconds")
|
||||
s3StandaloneOptions.concurrentUploadLimitMB = cmdS3.Flag.Int("concurrentUploadLimitMB", 128, "limit total concurrent upload size")
|
||||
s3StandaloneOptions.concurrentUploadLimitMB = cmdS3.Flag.Int("concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
|
||||
s3StandaloneOptions.concurrentFileUploadLimit = cmdS3.Flag.Int("concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
|
||||
}
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ func init() {
|
||||
filerOptions.dirListingLimit = cmdServer.Flag.Int("filer.dirListLimit", 1000, "limit sub dir listing size")
|
||||
filerOptions.cipher = cmdServer.Flag.Bool("filer.encryptVolumeData", false, "encrypt data on volume servers")
|
||||
filerOptions.saveToFilerLimit = cmdServer.Flag.Int("filer.saveToFilerLimit", 0, "Small files smaller than this limit can be cached in filer store.")
|
||||
filerOptions.concurrentUploadLimitMB = cmdServer.Flag.Int("filer.concurrentUploadLimitMB", 64, "limit total concurrent upload size")
|
||||
filerOptions.concurrentUploadLimitMB = cmdServer.Flag.Int("filer.concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
|
||||
filerOptions.concurrentFileUploadLimit = cmdServer.Flag.Int("filer.concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
|
||||
filerOptions.localSocket = cmdServer.Flag.String("filer.localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
|
||||
filerOptions.showUIDirectoryDelete = cmdServer.Flag.Bool("filer.ui.deleteDir", true, "enable filer UI show delete directory button")
|
||||
@@ -142,8 +142,8 @@ func init() {
|
||||
serverOptions.v.maintenanceMBPerSecond = cmdServer.Flag.Int("volume.maintenanceMBps", 0, "limit maintenance (replication / balance) IO rate in MB/s. Unset is 0, no limitation.")
|
||||
serverOptions.v.fileSizeLimitMB = cmdServer.Flag.Int("volume.fileSizeLimitMB", 256, "limit file size to avoid out of memory")
|
||||
serverOptions.v.ldbTimeout = cmdServer.Flag.Int64("volume.index.leveldbTimeout", 0, "alive time for leveldb (default to 0). If leveldb of volume is not accessed in ldbTimeout hours, it will be off loaded to reduce opened files and memory consumption.")
|
||||
serverOptions.v.concurrentUploadLimitMB = cmdServer.Flag.Int("volume.concurrentUploadLimitMB", 64, "limit total concurrent upload size")
|
||||
serverOptions.v.concurrentDownloadLimitMB = cmdServer.Flag.Int("volume.concurrentDownloadLimitMB", 64, "limit total concurrent download size")
|
||||
serverOptions.v.concurrentUploadLimitMB = cmdServer.Flag.Int("volume.concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
|
||||
serverOptions.v.concurrentDownloadLimitMB = cmdServer.Flag.Int("volume.concurrentDownloadLimitMB", 0, "limit total concurrent download size, 0 means unlimited")
|
||||
serverOptions.v.publicUrl = cmdServer.Flag.String("volume.publicUrl", "", "publicly accessible address")
|
||||
serverOptions.v.preStopSeconds = cmdServer.Flag.Int("volume.preStopSeconds", 10, "number of seconds between stop send heartbeats and stop volume server")
|
||||
serverOptions.v.pprof = cmdServer.Flag.Bool("volume.pprof", false, "enable pprof http handlers. precludes -memprofile and -cpuprofile")
|
||||
@@ -171,7 +171,7 @@ func init() {
|
||||
s3Options.localSocket = cmdServer.Flag.String("s3.localSocket", "", "default to /tmp/seaweedfs-s3-<port>.sock")
|
||||
s3Options.bindIp = cmdServer.Flag.String("s3.ip.bind", "", "ip address to bind to. If empty, default to same as -ip.bind option.")
|
||||
s3Options.idleTimeout = cmdServer.Flag.Int("s3.idleTimeout", 120, "connection idle seconds")
|
||||
s3Options.concurrentUploadLimitMB = cmdServer.Flag.Int("s3.concurrentUploadLimitMB", 128, "limit total concurrent upload size for S3")
|
||||
s3Options.concurrentUploadLimitMB = cmdServer.Flag.Int("s3.concurrentUploadLimitMB", 0, "limit total concurrent upload size for S3, 0 means unlimited")
|
||||
s3Options.concurrentFileUploadLimit = cmdServer.Flag.Int("s3.concurrentFileUploadLimit", 0, "limit number of concurrent file uploads for S3, 0 means unlimited")
|
||||
|
||||
sftpOptions.port = cmdServer.Flag.Int("sftp.port", 2022, "SFTP server listen port")
|
||||
|
||||
@@ -100,8 +100,8 @@ func init() {
|
||||
v.maintenanceMBPerSecond = cmdVolume.Flag.Int("maintenanceMBps", 0, "limit maintenance (replication / balance) IO rate in MB/s. Unset is 0, no limitation.")
|
||||
v.fileSizeLimitMB = cmdVolume.Flag.Int("fileSizeLimitMB", 256, "limit file size to avoid out of memory")
|
||||
v.ldbTimeout = cmdVolume.Flag.Int64("index.leveldbTimeout", 0, "alive time for leveldb (default to 0). If leveldb of volume is not accessed in ldbTimeout hours, it will be off loaded to reduce opened files and memory consumption.")
|
||||
v.concurrentUploadLimitMB = cmdVolume.Flag.Int("concurrentUploadLimitMB", 256, "limit total concurrent upload size")
|
||||
v.concurrentDownloadLimitMB = cmdVolume.Flag.Int("concurrentDownloadLimitMB", 256, "limit total concurrent download size")
|
||||
v.concurrentUploadLimitMB = cmdVolume.Flag.Int("concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
|
||||
v.concurrentDownloadLimitMB = cmdVolume.Flag.Int("concurrentDownloadLimitMB", 0, "limit total concurrent download size, 0 means unlimited")
|
||||
v.pprof = cmdVolume.Flag.Bool("pprof", false, "enable pprof http handlers. precludes -memprofile and -cpuprofile")
|
||||
v.metricsHttpPort = cmdVolume.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
|
||||
v.metricsHttpIp = cmdVolume.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
|
||||
|
||||
+6
-1
@@ -92,7 +92,12 @@ func (entry *Entry) ToExistingProtoEntry(message *filer_pb.Entry) {
|
||||
return
|
||||
}
|
||||
message.IsDirectory = entry.IsDirectory()
|
||||
message.Attributes = EntryAttributeToPb(entry)
|
||||
// Reuse pre-allocated attributes if available, otherwise allocate
|
||||
if message.Attributes != nil {
|
||||
EntryAttributeToExistingPb(entry, message.Attributes)
|
||||
} else {
|
||||
message.Attributes = EntryAttributeToPb(entry)
|
||||
}
|
||||
message.Chunks = entry.GetChunks()
|
||||
message.Extended = entry.Extended
|
||||
message.HardLinkId = entry.HardLinkId
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -11,15 +12,61 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// pbEntryPool reduces allocations in EncodeAttributesAndChunks and DecodeAttributesAndChunks
|
||||
// which are called on every filer store operation
|
||||
var pbEntryPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{}, // Pre-allocate attributes
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// resetPbEntry clears a protobuf Entry for reuse
|
||||
func resetPbEntry(e *filer_pb.Entry) {
|
||||
// Use struct assignment to clear all fields including protobuf internal fields
|
||||
// (unknownFields, sizeCache) that field-by-field reset would miss
|
||||
attrs := e.Attributes
|
||||
*e = filer_pb.Entry{}
|
||||
if attrs == nil {
|
||||
attrs = &filer_pb.FuseAttributes{}
|
||||
} else {
|
||||
resetFuseAttributes(attrs)
|
||||
}
|
||||
e.Attributes = attrs
|
||||
}
|
||||
|
||||
// resetFuseAttributes clears FuseAttributes for reuse
|
||||
func resetFuseAttributes(a *filer_pb.FuseAttributes) {
|
||||
// Use struct assignment to clear all fields including protobuf internal fields
|
||||
*a = filer_pb.FuseAttributes{}
|
||||
}
|
||||
|
||||
func (entry *Entry) EncodeAttributesAndChunks() ([]byte, error) {
|
||||
message := &filer_pb.Entry{}
|
||||
message := pbEntryPool.Get().(*filer_pb.Entry)
|
||||
defer func() {
|
||||
resetPbEntry(message)
|
||||
pbEntryPool.Put(message)
|
||||
}()
|
||||
|
||||
entry.ToExistingProtoEntry(message)
|
||||
return proto.Marshal(message)
|
||||
|
||||
data, err := proto.Marshal(message)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Copy the data to a new slice since proto.Marshal may return a slice
|
||||
// that shares memory with the message (not guaranteed to be a copy)
|
||||
return append([]byte(nil), data...), nil
|
||||
}
|
||||
|
||||
func (entry *Entry) DecodeAttributesAndChunks(blob []byte) error {
|
||||
|
||||
message := &filer_pb.Entry{}
|
||||
message := pbEntryPool.Get().(*filer_pb.Entry)
|
||||
defer func() {
|
||||
resetPbEntry(message)
|
||||
pbEntryPool.Put(message)
|
||||
}()
|
||||
|
||||
if err := proto.Unmarshal(blob, message); err != nil {
|
||||
return fmt.Errorf("decoding value blob for %s: %v", entry.FullPath, err)
|
||||
@@ -50,6 +97,28 @@ func EntryAttributeToPb(entry *Entry) *filer_pb.FuseAttributes {
|
||||
}
|
||||
}
|
||||
|
||||
// EntryAttributeToExistingPb fills an existing FuseAttributes to avoid allocation.
|
||||
// Safe to call with nil attr (will return early without populating).
|
||||
func EntryAttributeToExistingPb(entry *Entry, attr *filer_pb.FuseAttributes) {
|
||||
if attr == nil {
|
||||
return
|
||||
}
|
||||
attr.Crtime = entry.Attr.Crtime.Unix()
|
||||
attr.Mtime = entry.Attr.Mtime.Unix()
|
||||
attr.FileMode = uint32(entry.Attr.Mode)
|
||||
attr.Uid = entry.Uid
|
||||
attr.Gid = entry.Gid
|
||||
attr.Mime = entry.Mime
|
||||
attr.TtlSec = entry.Attr.TtlSec
|
||||
attr.UserName = entry.Attr.UserName
|
||||
attr.GroupName = entry.Attr.GroupNames
|
||||
attr.SymlinkTarget = entry.Attr.SymlinkTarget
|
||||
attr.Md5 = entry.Attr.Md5
|
||||
attr.FileSize = entry.Attr.FileSize
|
||||
attr.Rdev = entry.Attr.Rdev
|
||||
attr.Inode = entry.Attr.Inode
|
||||
}
|
||||
|
||||
func PbToEntryAttribute(attr *filer_pb.FuseAttributes) Attr {
|
||||
|
||||
t := Attr{}
|
||||
|
||||
@@ -160,18 +160,79 @@ func (fc *FilerConf) DeleteLocationConf(locationPrefix string) {
|
||||
return true
|
||||
})
|
||||
fc.rules = rules
|
||||
return
|
||||
}
|
||||
|
||||
// emptyPathConf is a singleton for paths with no matching rules
|
||||
// Callers must NOT mutate the returned value
|
||||
var emptyPathConf = &filer_pb.FilerConf_PathConf{}
|
||||
|
||||
func (fc *FilerConf) MatchStorageRule(path string) (pathConf *filer_pb.FilerConf_PathConf) {
|
||||
// Convert once to avoid allocation in multi-match case
|
||||
pathBytes := []byte(path)
|
||||
|
||||
// Fast path: check if any rules match before allocating
|
||||
// This avoids allocation for paths with no configured rules (common case)
|
||||
var firstMatch *filer_pb.FilerConf_PathConf
|
||||
matchCount := 0
|
||||
|
||||
fc.rules.MatchPrefix(pathBytes, func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
|
||||
matchCount++
|
||||
if matchCount == 1 {
|
||||
firstMatch = value
|
||||
return true // continue to check for more matches
|
||||
}
|
||||
// Stop after 2 matches - we only need to know if there are multiple
|
||||
return false
|
||||
})
|
||||
|
||||
// No rules match - return singleton (callers must NOT mutate)
|
||||
if matchCount == 0 {
|
||||
return emptyPathConf
|
||||
}
|
||||
|
||||
// Single rule matches - return directly (callers must NOT mutate)
|
||||
if matchCount == 1 {
|
||||
return firstMatch
|
||||
}
|
||||
|
||||
// Multiple rules match - need to merge (allocate new)
|
||||
pathConf = &filer_pb.FilerConf_PathConf{}
|
||||
fc.rules.MatchPrefix([]byte(path), func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
|
||||
fc.rules.MatchPrefix(pathBytes, func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
|
||||
mergePathConf(pathConf, value)
|
||||
return true
|
||||
})
|
||||
return pathConf
|
||||
}
|
||||
|
||||
// ClonePathConf creates a mutable copy of an existing PathConf.
|
||||
// Use this when you need to modify a config (e.g., before calling SetLocationConf).
|
||||
//
|
||||
// IMPORTANT: Keep in sync with filer_pb.FilerConf_PathConf fields.
|
||||
// When adding new fields to the protobuf, update this function accordingly.
|
||||
func ClonePathConf(src *filer_pb.FilerConf_PathConf) *filer_pb.FilerConf_PathConf {
|
||||
if src == nil {
|
||||
return &filer_pb.FilerConf_PathConf{}
|
||||
}
|
||||
return &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: src.LocationPrefix,
|
||||
Collection: src.Collection,
|
||||
Replication: src.Replication,
|
||||
Ttl: src.Ttl,
|
||||
DiskType: src.DiskType,
|
||||
Fsync: src.Fsync,
|
||||
VolumeGrowthCount: src.VolumeGrowthCount,
|
||||
ReadOnly: src.ReadOnly,
|
||||
MaxFileNameLength: src.MaxFileNameLength,
|
||||
DataCenter: src.DataCenter,
|
||||
Rack: src.Rack,
|
||||
DataNode: src.DataNode,
|
||||
DisableChunkDeletion: src.DisableChunkDeletion,
|
||||
Worm: src.Worm,
|
||||
WormGracePeriodSeconds: src.WormGracePeriodSeconds,
|
||||
WormRetentionTimeSeconds: src.WormRetentionTimeSeconds,
|
||||
}
|
||||
}
|
||||
|
||||
func (fc *FilerConf) GetCollectionTtls(collection string) (ttls map[string]string) {
|
||||
ttls = make(map[string]string)
|
||||
fc.rules.Walk(func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -47,3 +48,83 @@ func TestFilerConf(t *testing.T) {
|
||||
assert.Equal(t, false, fc.MatchStorageRule("/buckets/other").ReadOnly)
|
||||
|
||||
}
|
||||
|
||||
// TestClonePathConf verifies that ClonePathConf copies all exported fields.
|
||||
// Uses reflection to automatically detect new fields added to the protobuf,
|
||||
// ensuring the test fails if ClonePathConf is not updated for new fields.
|
||||
func TestClonePathConf(t *testing.T) {
|
||||
// Create a fully-populated PathConf with non-zero values for all fields
|
||||
src := &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/test/path",
|
||||
Collection: "test_collection",
|
||||
Replication: "001",
|
||||
Ttl: "7d",
|
||||
DiskType: "ssd",
|
||||
Fsync: true,
|
||||
VolumeGrowthCount: 5,
|
||||
ReadOnly: true,
|
||||
MaxFileNameLength: 255,
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack1",
|
||||
DataNode: "node1",
|
||||
DisableChunkDeletion: true,
|
||||
Worm: true,
|
||||
WormGracePeriodSeconds: 3600,
|
||||
WormRetentionTimeSeconds: 86400,
|
||||
}
|
||||
|
||||
clone := ClonePathConf(src)
|
||||
|
||||
// Verify it's a different object
|
||||
assert.NotSame(t, src, clone, "ClonePathConf should return a new object, not the same pointer")
|
||||
|
||||
// Use reflection to compare all exported fields
|
||||
// This will automatically catch any new fields added to the protobuf
|
||||
srcVal := reflect.ValueOf(src).Elem()
|
||||
cloneVal := reflect.ValueOf(clone).Elem()
|
||||
srcType := srcVal.Type()
|
||||
|
||||
for i := 0; i < srcType.NumField(); i++ {
|
||||
field := srcType.Field(i)
|
||||
|
||||
// Skip unexported fields (protobuf internal fields like sizeCache, unknownFields)
|
||||
if !field.IsExported() {
|
||||
continue
|
||||
}
|
||||
|
||||
srcField := srcVal.Field(i)
|
||||
cloneField := cloneVal.Field(i)
|
||||
|
||||
// Compare field values
|
||||
if !reflect.DeepEqual(srcField.Interface(), cloneField.Interface()) {
|
||||
t.Errorf("Field %s not copied correctly: src=%v, clone=%v",
|
||||
field.Name, srcField.Interface(), cloneField.Interface())
|
||||
}
|
||||
}
|
||||
|
||||
// Additionally verify that all exported fields in src are non-zero
|
||||
// This ensures we're testing with fully populated data
|
||||
for i := 0; i < srcType.NumField(); i++ {
|
||||
field := srcType.Field(i)
|
||||
if !field.IsExported() {
|
||||
continue
|
||||
}
|
||||
|
||||
srcField := srcVal.Field(i)
|
||||
if srcField.IsZero() {
|
||||
t.Errorf("Test setup error: field %s has zero value, update test to set a non-zero value", field.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify mutation of clone doesn't affect source
|
||||
clone.Collection = "modified"
|
||||
clone.ReadOnly = false
|
||||
assert.Equal(t, "test_collection", src.Collection, "Modifying clone should not affect source Collection")
|
||||
assert.Equal(t, true, src.ReadOnly, "Modifying clone should not affect source ReadOnly")
|
||||
}
|
||||
|
||||
func TestClonePathConfNil(t *testing.T) {
|
||||
clone := ClonePathConf(nil)
|
||||
assert.NotNil(t, clone, "ClonePathConf(nil) should return a non-nil empty PathConf")
|
||||
assert.Equal(t, "", clone.LocationPrefix, "ClonePathConf(nil) should return empty PathConf")
|
||||
}
|
||||
@@ -152,9 +152,21 @@ func (f *Filer) logFlushFunc(logBuffer *log_buffer.LogBuffer, startTime, stopTim
|
||||
}
|
||||
|
||||
var (
|
||||
VolumeNotFoundPattern = regexp.MustCompile(`volume \d+? not found`)
|
||||
volumeNotFoundPattern = regexp.MustCompile(`volume \d+? not found`)
|
||||
chunkNotFoundPattern = regexp.MustCompile(`(urls not found|File Not Found)`)
|
||||
)
|
||||
|
||||
// isChunkNotFoundError checks if the error indicates that a volume or chunk
|
||||
// has been deleted and is no longer available. These errors can be skipped
|
||||
// when reading persisted log files since the data is unrecoverable.
|
||||
func isChunkNotFoundError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
errMsg := err.Error()
|
||||
return volumeNotFoundPattern.MatchString(errMsg) || chunkNotFoundPattern.MatchString(errMsg)
|
||||
}
|
||||
|
||||
func (f *Filer) ReadPersistedLogBuffer(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastTsNs int64, isDone bool, err error) {
|
||||
|
||||
visitor, visitErr := f.collectPersistedLogBuffer(startPosition, stopTsNs)
|
||||
|
||||
@@ -265,11 +265,12 @@ func (c *LogFileEntryCollector) collectMore(v *OrderedLogVisitor) (err error) {
|
||||
// ----------
|
||||
|
||||
type LogFileQueueIterator struct {
|
||||
q *util.Queue[*LogFileEntry]
|
||||
masterClient *wdclient.MasterClient
|
||||
startTsNs int64
|
||||
stopTsNs int64
|
||||
currentFileIterator *LogFileIterator
|
||||
q *util.Queue[*LogFileEntry]
|
||||
masterClient *wdclient.MasterClient
|
||||
startTsNs int64
|
||||
stopTsNs int64
|
||||
pendingEntries []*filer_pb.LogEntry
|
||||
pendingIndex int
|
||||
}
|
||||
|
||||
func newLogFileQueueIterator(masterClient *wdclient.MasterClient, q *util.Queue[*LogFileEntry], startTsNs, stopTsNs int64) *LogFileQueueIterator {
|
||||
@@ -284,13 +285,17 @@ func newLogFileQueueIterator(masterClient *wdclient.MasterClient, q *util.Queue[
|
||||
// getNext will return io.EOF when done
|
||||
func (iter *LogFileQueueIterator) getNext(v *OrderedLogVisitor) (logEntry *filer_pb.LogEntry, err error) {
|
||||
for {
|
||||
if iter.currentFileIterator != nil {
|
||||
logEntry, err = iter.currentFileIterator.getNext()
|
||||
if err != io.EOF {
|
||||
return
|
||||
}
|
||||
// return pending entries first
|
||||
if iter.pendingIndex < len(iter.pendingEntries) {
|
||||
logEntry = iter.pendingEntries[iter.pendingIndex]
|
||||
iter.pendingIndex++
|
||||
return logEntry, nil
|
||||
}
|
||||
// now either iter.currentFileIterator is nil or err is io.EOF
|
||||
// reset for next file
|
||||
iter.pendingEntries = nil
|
||||
iter.pendingIndex = 0
|
||||
|
||||
// read entries from next file
|
||||
if iter.q.Len() == 0 {
|
||||
return nil, io.EOF
|
||||
}
|
||||
@@ -313,7 +318,38 @@ func (iter *LogFileQueueIterator) getNext(v *OrderedLogVisitor) (logEntry *filer
|
||||
if next != nil && next.TsNs <= iter.startTsNs {
|
||||
continue
|
||||
}
|
||||
iter.currentFileIterator = newLogFileIterator(iter.masterClient, t.FileEntry, iter.startTsNs, iter.stopTsNs)
|
||||
|
||||
// read all entries from this file
|
||||
iter.pendingEntries, err = iter.readFileEntries(t.FileEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readFileEntries reads all log entries from a single file
|
||||
func (iter *LogFileQueueIterator) readFileEntries(fileEntry *Entry) (entries []*filer_pb.LogEntry, err error) {
|
||||
fileIterator := newLogFileIterator(iter.masterClient, fileEntry, iter.startTsNs, iter.stopTsNs)
|
||||
defer func() {
|
||||
if closeErr := fileIterator.Close(); closeErr != nil && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
logEntry, err := fileIterator.getNext()
|
||||
if err == io.EOF {
|
||||
return entries, nil
|
||||
}
|
||||
if err != nil {
|
||||
if isChunkNotFoundError(err) {
|
||||
// Volume or chunk was deleted, skip the rest of this log file
|
||||
glog.Warningf("skipping rest of %s: %v", fileIterator.filePath, err)
|
||||
return entries, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
entries = append(entries, logEntry)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,6 +360,7 @@ type LogFileIterator struct {
|
||||
sizeBuf []byte
|
||||
startTsNs int64
|
||||
stopTsNs int64
|
||||
filePath string
|
||||
}
|
||||
|
||||
func newLogFileIterator(masterClient *wdclient.MasterClient, fileEntry *Entry, startTsNs, stopTsNs int64) *LogFileIterator {
|
||||
@@ -332,9 +369,17 @@ func newLogFileIterator(masterClient *wdclient.MasterClient, fileEntry *Entry, s
|
||||
sizeBuf: make([]byte, 4),
|
||||
startTsNs: startTsNs,
|
||||
stopTsNs: stopTsNs,
|
||||
filePath: string(fileEntry.FullPath),
|
||||
}
|
||||
}
|
||||
|
||||
func (iter *LogFileIterator) Close() error {
|
||||
if r, ok := iter.r.(io.Closer); ok {
|
||||
return r.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getNext will return io.EOF when done
|
||||
func (iter *LogFileIterator) getNext() (logEntry *filer_pb.LogEntry, err error) {
|
||||
var n int
|
||||
|
||||
@@ -32,9 +32,10 @@ type VirtualFilerStore interface {
|
||||
}
|
||||
|
||||
type FilerStoreWrapper struct {
|
||||
defaultStore FilerStore
|
||||
pathToStore ptrie.Trie[string]
|
||||
storeIdToStore map[string]FilerStore
|
||||
defaultStore FilerStore
|
||||
pathToStore ptrie.Trie[string]
|
||||
storeIdToStore map[string]FilerStore
|
||||
hasPathSpecificStore bool // fast check to skip MatchPrefix when no path-specific stores
|
||||
}
|
||||
|
||||
func NewFilerStoreWrapper(store FilerStore) *FilerStoreWrapper {
|
||||
@@ -82,10 +83,15 @@ func (fsw *FilerStoreWrapper) AddPathSpecificStore(path string, storeId string,
|
||||
if err != nil {
|
||||
glog.Fatalf("put path specific store: %v", err)
|
||||
}
|
||||
fsw.hasPathSpecificStore = true
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) getActualStore(path util.FullPath) (store FilerStore) {
|
||||
store = fsw.defaultStore
|
||||
// Fast path: skip MatchPrefix if no path-specific stores are configured (common case)
|
||||
if !fsw.hasPathSpecificStore {
|
||||
return
|
||||
}
|
||||
if path == "/" || path == "//" {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/apple/foundationdb/bindings/go/src/fdb"
|
||||
@@ -37,15 +38,146 @@ import (
|
||||
const (
|
||||
// FoundationDB transaction size limit is 10MB
|
||||
FDB_TRANSACTION_SIZE_LIMIT = 10 * 1024 * 1024
|
||||
// Safe limit for batch size (leave margin for FDB overhead)
|
||||
FDB_BATCH_SIZE_LIMIT = 8 * 1024 * 1024
|
||||
// Maximum number of entries to return in a single directory listing
|
||||
// Large batches can cause transaction timeouts and increase memory pressure
|
||||
MAX_DIRECTORY_LIST_LIMIT = 1000
|
||||
|
||||
// Write batching defaults
|
||||
DEFAULT_BATCH_SIZE = 100
|
||||
DEFAULT_BATCH_INTERVAL = 5 * time.Millisecond
|
||||
)
|
||||
|
||||
func init() {
|
||||
filer.Stores = append(filer.Stores, &FoundationDBStore{})
|
||||
}
|
||||
|
||||
// writeOp represents a pending write operation
|
||||
type writeOp struct {
|
||||
key fdb.Key
|
||||
value []byte // nil for delete
|
||||
done chan error
|
||||
}
|
||||
|
||||
// opSize returns the approximate size of an operation in bytes
|
||||
func (op *writeOp) size() int {
|
||||
return len(op.key) + len(op.value)
|
||||
}
|
||||
|
||||
// writeBatcher batches multiple writes into single transactions
|
||||
type writeBatcher struct {
|
||||
store *FoundationDBStore
|
||||
ops chan *writeOp
|
||||
stop chan struct{}
|
||||
wg sync.WaitGroup
|
||||
size int
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
func newWriteBatcher(store *FoundationDBStore, size int, interval time.Duration) *writeBatcher {
|
||||
b := &writeBatcher{
|
||||
store: store,
|
||||
ops: make(chan *writeOp, size*10),
|
||||
stop: make(chan struct{}),
|
||||
size: size,
|
||||
interval: interval,
|
||||
}
|
||||
b.wg.Add(1)
|
||||
go b.run()
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *writeBatcher) run() {
|
||||
defer b.wg.Done()
|
||||
batch := make([]*writeOp, 0, b.size)
|
||||
batchBytes := 0 // Track cumulative size of batch
|
||||
timer := time.NewTimer(b.interval)
|
||||
defer timer.Stop()
|
||||
|
||||
flush := func() {
|
||||
if len(batch) == 0 {
|
||||
return
|
||||
}
|
||||
_, err := b.store.database.Transact(func(tr fdb.Transaction) (interface{}, error) {
|
||||
for _, op := range batch {
|
||||
if op.value != nil {
|
||||
tr.Set(op.key, op.value)
|
||||
} else {
|
||||
tr.Clear(op.key)
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
for _, op := range batch {
|
||||
if op.done != nil {
|
||||
op.done <- err
|
||||
close(op.done)
|
||||
}
|
||||
}
|
||||
batch = batch[:0]
|
||||
batchBytes = 0
|
||||
}
|
||||
|
||||
resetTimer := func() {
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
timer.Reset(b.interval)
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case op := <-b.ops:
|
||||
batch = append(batch, op)
|
||||
batchBytes += op.size()
|
||||
// Flush when batch count or size limit is reached
|
||||
if len(batch) >= b.size || batchBytes >= FDB_BATCH_SIZE_LIMIT {
|
||||
flush()
|
||||
resetTimer()
|
||||
}
|
||||
case <-timer.C:
|
||||
flush()
|
||||
// Timer already fired, safe to reset directly
|
||||
timer.Reset(b.interval)
|
||||
case <-b.stop:
|
||||
for {
|
||||
select {
|
||||
case op := <-b.ops:
|
||||
batch = append(batch, op)
|
||||
default:
|
||||
flush()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *writeBatcher) submit(key fdb.Key, value []byte, wait bool) error {
|
||||
op := &writeOp{key: key, value: value}
|
||||
if wait {
|
||||
op.done = make(chan error, 1)
|
||||
}
|
||||
select {
|
||||
case b.ops <- op:
|
||||
if wait {
|
||||
return <-op.done
|
||||
}
|
||||
return nil
|
||||
case <-b.stop:
|
||||
return fmt.Errorf("batcher stopped")
|
||||
}
|
||||
}
|
||||
|
||||
func (b *writeBatcher) shutdown() {
|
||||
close(b.stop)
|
||||
b.wg.Wait()
|
||||
}
|
||||
|
||||
type FoundationDBStore struct {
|
||||
database fdb.Database
|
||||
seaweedfsDir directory.DirectorySubspace
|
||||
@@ -53,6 +185,10 @@ type FoundationDBStore struct {
|
||||
directoryPrefix string
|
||||
timeout time.Duration
|
||||
maxRetryDelay time.Duration
|
||||
// Write batching
|
||||
batcher *writeBatcher
|
||||
batchSize int
|
||||
batchInterval time.Duration
|
||||
}
|
||||
|
||||
// Context key type for storing transactions
|
||||
@@ -89,6 +225,8 @@ func (store *FoundationDBStore) Initialize(configuration util.Configuration, pre
|
||||
configuration.SetDefault(prefix+"timeout", "5s")
|
||||
configuration.SetDefault(prefix+"max_retry_delay", "1s")
|
||||
configuration.SetDefault(prefix+"directory_prefix", "seaweedfs")
|
||||
configuration.SetDefault(prefix+"batch_size", DEFAULT_BATCH_SIZE)
|
||||
configuration.SetDefault(prefix+"batch_interval", DEFAULT_BATCH_INTERVAL.String())
|
||||
|
||||
clusterFile := configuration.GetString(prefix + "cluster_file")
|
||||
apiVersion := configuration.GetInt(prefix + "api_version")
|
||||
@@ -108,6 +246,18 @@ func (store *FoundationDBStore) Initialize(configuration util.Configuration, pre
|
||||
return fmt.Errorf("invalid max_retry_delay duration %s: %w", maxRetryDelayStr, err)
|
||||
}
|
||||
|
||||
// Parse batch configuration
|
||||
store.batchSize = configuration.GetInt(prefix + "batch_size")
|
||||
if store.batchSize <= 0 {
|
||||
store.batchSize = DEFAULT_BATCH_SIZE
|
||||
}
|
||||
batchIntervalStr := configuration.GetString(prefix + "batch_interval")
|
||||
store.batchInterval, err = time.ParseDuration(batchIntervalStr)
|
||||
if err != nil {
|
||||
glog.Warningf("invalid %sbatch_interval duration %q, using default %v: %v", prefix, batchIntervalStr, DEFAULT_BATCH_INTERVAL, err)
|
||||
store.batchInterval = DEFAULT_BATCH_INTERVAL
|
||||
}
|
||||
|
||||
return store.initialize(clusterFile, apiVersion)
|
||||
}
|
||||
|
||||
@@ -138,6 +288,11 @@ func (store *FoundationDBStore) initialize(clusterFile string, apiVersion int) e
|
||||
return fmt.Errorf("failed to create/open kv directory: %w", err)
|
||||
}
|
||||
|
||||
// Start write batcher for improved throughput
|
||||
store.batcher = newWriteBatcher(store, store.batchSize, store.batchInterval)
|
||||
glog.V(0).Infof("FoundationDB: write batching enabled (batch_size=%d, batch_interval=%v)",
|
||||
store.batchSize, store.batchInterval)
|
||||
|
||||
glog.V(0).Infof("FoundationDB store initialized successfully with directory prefix: %s", store.directoryPrefix)
|
||||
return nil
|
||||
}
|
||||
@@ -215,7 +370,12 @@ func (store *FoundationDBStore) UpdateEntry(ctx context.Context, entry *filer.En
|
||||
return nil
|
||||
}
|
||||
|
||||
// Execute in a new transaction if not in an existing one
|
||||
// Use write batcher for better throughput
|
||||
if store.batcher != nil {
|
||||
return store.batcher.submit(key, value, true)
|
||||
}
|
||||
|
||||
// Fallback: execute in a new transaction
|
||||
_, err = store.database.Transact(func(tr fdb.Transaction) (interface{}, error) {
|
||||
tr.Set(key, value)
|
||||
return nil, nil
|
||||
@@ -276,7 +436,12 @@ func (store *FoundationDBStore) DeleteEntry(ctx context.Context, fullpath util.F
|
||||
return nil
|
||||
}
|
||||
|
||||
// Execute in a new transaction if not in an existing one
|
||||
// Use write batcher for better throughput (nil value = delete)
|
||||
if store.batcher != nil {
|
||||
return store.batcher.submit(key, nil, true)
|
||||
}
|
||||
|
||||
// Fallback: execute in a new transaction
|
||||
_, err := store.database.Transact(func(tr fdb.Transaction) (interface{}, error) {
|
||||
tr.Clear(key)
|
||||
return nil, nil
|
||||
@@ -556,13 +721,37 @@ func (store *FoundationDBStore) KvDelete(ctx context.Context, key []byte) error
|
||||
}
|
||||
|
||||
func (store *FoundationDBStore) Shutdown() {
|
||||
// Stop write batcher
|
||||
if store.batcher != nil {
|
||||
store.batcher.shutdown()
|
||||
store.batcher = nil
|
||||
}
|
||||
// FoundationDB doesn't have an explicit close method for Database
|
||||
glog.V(0).Infof("FoundationDB store shutdown")
|
||||
}
|
||||
|
||||
// tuplePool reduces allocations in genKey which is called on every FDB operation
|
||||
var tuplePool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
// Pre-allocate slice with capacity 2 for (dirPath, fileName)
|
||||
t := make(tuple.Tuple, 2)
|
||||
return &t
|
||||
},
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
func (store *FoundationDBStore) genKey(dirPath, fileName string) fdb.Key {
|
||||
return store.seaweedfsDir.Pack(tuple.Tuple{dirPath, fileName})
|
||||
// Get a tuple from pool to avoid slice allocation
|
||||
tp := tuplePool.Get().(*tuple.Tuple)
|
||||
defer func() {
|
||||
// Clear references before returning to pool to avoid memory leaks
|
||||
(*tp)[0] = nil
|
||||
(*tp)[1] = nil
|
||||
tuplePool.Put(tp)
|
||||
}()
|
||||
(*tp)[0] = dirPath
|
||||
(*tp)[1] = fileName
|
||||
return store.seaweedfsDir.Pack(*tp)
|
||||
}
|
||||
|
||||
func (store *FoundationDBStore) extractFileName(key fdb.Key) (string, error) {
|
||||
|
||||
@@ -107,6 +107,39 @@ func (store *LevelDBStore) UpdateEntry(ctx context.Context, entry *filer.Entry)
|
||||
return store.InsertEntry(ctx, entry)
|
||||
}
|
||||
|
||||
// BatchInsertEntries inserts multiple entries in a single LevelDB batch write.
|
||||
// This is more efficient than inserting entries one by one as it reduces
|
||||
// the number of write operations and syncs to disk.
|
||||
func (store *LevelDBStore) BatchInsertEntries(ctx context.Context, entries []*filer.Entry) error {
|
||||
if len(entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
batch := new(leveldb.Batch)
|
||||
|
||||
for _, entry := range entries {
|
||||
key := genKey(entry.DirAndName())
|
||||
|
||||
value, err := entry.EncodeAttributesAndChunks()
|
||||
if err != nil {
|
||||
return fmt.Errorf("encoding %s %+v: %w", entry.FullPath, entry.Attr, err)
|
||||
}
|
||||
|
||||
if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
|
||||
value = weed_util.MaybeGzipData(value)
|
||||
}
|
||||
|
||||
batch.Put(key, value)
|
||||
}
|
||||
|
||||
err := store.db.Write(batch, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("batch write: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *LevelDBStore) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
|
||||
key := genKey(fullpath.DirAndName())
|
||||
|
||||
|
||||
+8
-20
@@ -245,6 +245,7 @@ type ChunkStreamReader struct {
|
||||
|
||||
var _ = io.ReadSeeker(&ChunkStreamReader{})
|
||||
var _ = io.ReaderAt(&ChunkStreamReader{})
|
||||
var _ = io.Closer(&ChunkStreamReader{})
|
||||
|
||||
func doNewChunkStreamReader(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
|
||||
|
||||
@@ -374,24 +375,6 @@ func (c *ChunkStreamReader) fetchChunkToBuffer(chunkView *ChunkView) error {
|
||||
glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Fast path: for full, plain chunks, read directly into a single buffer to avoid
|
||||
// the streaming loop (which stages 64KB at a time and adds an extra copy).
|
||||
if chunkView.CipherKey == nil && !chunkView.IsGzipped && chunkView.IsFullChunk() {
|
||||
buf := make([]byte, chunkView.ViewSize)
|
||||
n, fetchErr := util_http.RetriedFetchChunkData(context.Background(), buf, urlStrings, nil, false, true, chunkView.OffsetInChunk, chunkView.FileId)
|
||||
if fetchErr == nil && n == len(buf) {
|
||||
c.buffer = buf
|
||||
c.bufferOffset = chunkView.ViewOffset
|
||||
c.chunk = chunkView.FileId
|
||||
return nil
|
||||
}
|
||||
// Fall back to the streaming path on partial fill or error
|
||||
if fetchErr != nil {
|
||||
glog.V(1).Infof("read %s direct failed, err: %v, falling back to stream", chunkView.FileId, fetchErr)
|
||||
}
|
||||
}
|
||||
|
||||
var buffer bytes.Buffer
|
||||
var shouldRetry bool
|
||||
jwt := JwtForVolumeServer(chunkView.FileId)
|
||||
@@ -421,8 +404,13 @@ func (c *ChunkStreamReader) fetchChunkToBuffer(chunkView *ChunkView) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ChunkStreamReader) Close() {
|
||||
// TODO try to release and reuse buffer
|
||||
func (c *ChunkStreamReader) Close() error {
|
||||
c.bufferLock.Lock()
|
||||
defer c.bufferLock.Unlock()
|
||||
c.buffer = nil
|
||||
c.head = nil
|
||||
c.chunkView = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func VolumeId(fileId string) string {
|
||||
|
||||
@@ -160,6 +160,10 @@ func (i *InodeToPath) MarkChildrenCached(fullpath util.FullPath) {
|
||||
return
|
||||
}
|
||||
path, found := i.inode2path[inode]
|
||||
if !found {
|
||||
glog.Warningf("MarkChildrenCached inode %d not found in inode2path for %v", inode, fullpath)
|
||||
return
|
||||
}
|
||||
path.isChildrenCached = true
|
||||
if i.cacheMetaTtlSec > 0 {
|
||||
path.cachedExpiresTime = time.Now().Add(i.cacheMetaTtlSec)
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer/leveldb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -17,20 +19,24 @@ import (
|
||||
// e.g. fill fileId field for chunks
|
||||
|
||||
type MetaCache struct {
|
||||
root util.FullPath
|
||||
localStore filer.VirtualFilerStore
|
||||
root util.FullPath
|
||||
localStore filer.VirtualFilerStore
|
||||
leveldbStore *leveldb.LevelDBStore // direct reference for batch operations
|
||||
sync.RWMutex
|
||||
uidGidMapper *UidGidMapper
|
||||
markCachedFn func(fullpath util.FullPath)
|
||||
isCachedFn func(fullpath util.FullPath) bool
|
||||
invalidateFunc func(fullpath util.FullPath, entry *filer_pb.Entry)
|
||||
visitGroup singleflight.Group // deduplicates concurrent EnsureVisited calls for the same path
|
||||
}
|
||||
|
||||
func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPath,
|
||||
markCachedFn func(path util.FullPath), isCachedFn func(path util.FullPath) bool, invalidateFunc func(util.FullPath, *filer_pb.Entry)) *MetaCache {
|
||||
leveldbStore, virtualStore := openMetaStore(dbFolder)
|
||||
return &MetaCache{
|
||||
root: root,
|
||||
localStore: openMetaStore(dbFolder),
|
||||
localStore: virtualStore,
|
||||
leveldbStore: leveldbStore,
|
||||
markCachedFn: markCachedFn,
|
||||
isCachedFn: isCachedFn,
|
||||
uidGidMapper: uidGidMapper,
|
||||
@@ -40,7 +46,7 @@ func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPat
|
||||
}
|
||||
}
|
||||
|
||||
func openMetaStore(dbFolder string) filer.VirtualFilerStore {
|
||||
func openMetaStore(dbFolder string) (*leveldb.LevelDBStore, filer.VirtualFilerStore) {
|
||||
|
||||
os.RemoveAll(dbFolder)
|
||||
os.MkdirAll(dbFolder, 0755)
|
||||
@@ -54,7 +60,7 @@ func openMetaStore(dbFolder string) filer.VirtualFilerStore {
|
||||
glog.Fatalf("Failed to initialize metadata cache store for %s: %+v", store.GetName(), err)
|
||||
}
|
||||
|
||||
return filer.NewFilerStoreWrapper(store)
|
||||
return store, filer.NewFilerStoreWrapper(store)
|
||||
|
||||
}
|
||||
|
||||
@@ -68,6 +74,12 @@ func (mc *MetaCache) doInsertEntry(ctx context.Context, entry *filer.Entry) erro
|
||||
return mc.localStore.InsertEntry(ctx, entry)
|
||||
}
|
||||
|
||||
// doBatchInsertEntries inserts multiple entries using LevelDB's batch write.
|
||||
// This is more efficient than inserting entries one by one.
|
||||
func (mc *MetaCache) doBatchInsertEntries(ctx context.Context, entries []*filer.Entry) error {
|
||||
return mc.leveldbStore.BatchInsertEntries(ctx, entries)
|
||||
}
|
||||
|
||||
func (mc *MetaCache) AtomicUpdateEntryFromFiler(ctx context.Context, oldPath util.FullPath, newEntry *filer.Entry) error {
|
||||
mc.Lock()
|
||||
defer mc.Unlock()
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -11,22 +13,18 @@ import (
|
||||
)
|
||||
|
||||
func EnsureVisited(mc *MetaCache, client filer_pb.FilerClient, dirPath util.FullPath) error {
|
||||
|
||||
// Collect all uncached paths from target directory up to root
|
||||
var uncachedPaths []util.FullPath
|
||||
currentPath := dirPath
|
||||
|
||||
for {
|
||||
|
||||
// the directory children are already cached
|
||||
// so no need for this and upper directories
|
||||
// If this path is cached, all ancestors are also cached
|
||||
if mc.isCachedFn(currentPath) {
|
||||
return nil
|
||||
break
|
||||
}
|
||||
uncachedPaths = append(uncachedPaths, currentPath)
|
||||
|
||||
if err := doEnsureVisited(mc, client, currentPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// continue to parent directory
|
||||
// Continue to parent directory
|
||||
if currentPath != mc.root {
|
||||
parent, _ := currentPath.DirAndName()
|
||||
currentPath = util.FullPath(parent)
|
||||
@@ -35,33 +33,82 @@ func EnsureVisited(mc *MetaCache, client filer_pb.FilerClient, dirPath util.Full
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
if len(uncachedPaths) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fetch all uncached directories in parallel with context for cancellation
|
||||
// If one fetch fails, cancel the others to avoid unnecessary work
|
||||
g, ctx := errgroup.WithContext(context.Background())
|
||||
for _, p := range uncachedPaths {
|
||||
path := p // capture for closure
|
||||
g.Go(func() error {
|
||||
return doEnsureVisited(ctx, mc, client, path)
|
||||
})
|
||||
}
|
||||
return g.Wait()
|
||||
}
|
||||
|
||||
func doEnsureVisited(mc *MetaCache, client filer_pb.FilerClient, path util.FullPath) error {
|
||||
// batchInsertSize is the number of entries to accumulate before flushing to LevelDB.
|
||||
// 100 provides a balance between memory usage (~100 Entry pointers) and write efficiency
|
||||
// (fewer disk syncs). Larger values reduce I/O overhead but increase memory and latency.
|
||||
const batchInsertSize = 100
|
||||
|
||||
glog.V(4).Infof("ReadDirAllEntries %s ...", path)
|
||||
func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClient, path util.FullPath) error {
|
||||
// Use singleflight to deduplicate concurrent requests for the same path
|
||||
_, err, _ := mc.visitGroup.Do(string(path), func() (interface{}, error) {
|
||||
// Check for cancellation before starting
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
err := util.Retry("ReadDirAllEntries", func() error {
|
||||
return filer_pb.ReadDirAllEntries(context.Background(), client, path, "", func(pbEntry *filer_pb.Entry, isLast bool) error {
|
||||
entry := filer.FromPbEntry(string(path), pbEntry)
|
||||
if IsHiddenSystemEntry(string(path), entry.Name()) {
|
||||
// Double-check if already cached (another goroutine may have completed)
|
||||
if mc.isCachedFn(path) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
glog.V(4).Infof("ReadDirAllEntries %s ...", path)
|
||||
|
||||
// Collect entries in batches for efficient LevelDB writes
|
||||
var batch []*filer.Entry
|
||||
|
||||
fetchErr := util.Retry("ReadDirAllEntries", func() error {
|
||||
batch = nil // Reset batch on retry, allow GC of previous entries
|
||||
return filer_pb.ReadDirAllEntries(ctx, client, path, "", func(pbEntry *filer_pb.Entry, isLast bool) error {
|
||||
entry := filer.FromPbEntry(string(path), pbEntry)
|
||||
if IsHiddenSystemEntry(string(path), entry.Name()) {
|
||||
return nil
|
||||
}
|
||||
|
||||
batch = append(batch, entry)
|
||||
|
||||
// Flush batch when it reaches the threshold
|
||||
// Don't rely on isLast here - hidden entries may cause early return
|
||||
if len(batch) >= batchInsertSize {
|
||||
// No lock needed - LevelDB Write() is thread-safe
|
||||
if err := mc.doBatchInsertEntries(ctx, batch); err != nil {
|
||||
return fmt.Errorf("batch insert for %s: %w", path, err)
|
||||
}
|
||||
// Create new slice to allow GC of flushed entries
|
||||
batch = make([]*filer.Entry, 0, batchInsertSize)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := mc.doInsertEntry(context.Background(), entry); err != nil {
|
||||
glog.V(0).Infof("read %s: %v", entry.FullPath, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
err = fmt.Errorf("list %s: %v", path, err)
|
||||
} else {
|
||||
if fetchErr != nil {
|
||||
return nil, fmt.Errorf("list %s: %w", path, fetchErr)
|
||||
}
|
||||
|
||||
// Flush any remaining entries in the batch
|
||||
if len(batch) > 0 {
|
||||
if err := mc.doBatchInsertEntries(ctx, batch); err != nil {
|
||||
return nil, fmt.Errorf("batch insert remaining for %s: %w", path, err)
|
||||
}
|
||||
}
|
||||
mc.markCachedFn(path)
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,10 @@ type Option struct {
|
||||
Cipher bool // whether encrypt data on volume server
|
||||
UidGidMapper *meta_cache.UidGidMapper
|
||||
|
||||
// Periodic metadata flush interval in seconds (0 to disable)
|
||||
// This protects chunks from being purged by volume.fsck for long-running writes
|
||||
MetadataFlushSeconds int
|
||||
|
||||
// RDMA acceleration options
|
||||
RdmaEnabled bool
|
||||
RdmaSidecarAddr string
|
||||
@@ -214,6 +218,7 @@ func (wfs *WFS) StartBackgroundTasks() error {
|
||||
startTime := time.Now()
|
||||
go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.option.FilerMountRootPath, startTime.UnixNano(), follower)
|
||||
go wfs.loopCheckQuota()
|
||||
go wfs.loopFlushDirtyMetadata()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"sync"
|
||||
|
||||
"github.com/hanwen/go-fuse/v2/fuse"
|
||||
@@ -16,6 +15,7 @@ type DirectoryHandleId uint64
|
||||
|
||||
const (
|
||||
directoryStreamBaseOffset = 2 // . & ..
|
||||
batchSize = 1000
|
||||
)
|
||||
|
||||
// DirectoryHandle represents an open directory handle.
|
||||
@@ -159,27 +159,30 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out *fuse.DirEntryList, isPl
|
||||
}
|
||||
}
|
||||
|
||||
isEarlyTerminated := false
|
||||
dirPath, code := wfs.inodeToPath.GetPath(input.NodeId)
|
||||
if code != fuse.OK {
|
||||
return code
|
||||
}
|
||||
|
||||
var dirEntry fuse.DirEntry
|
||||
processEachEntryFn := func(entry *filer.Entry) bool {
|
||||
|
||||
// index is the position in entryStream, used to calculate the offset for next readdir
|
||||
processEachEntryFn := func(entry *filer.Entry, index int64) bool {
|
||||
dirEntry.Name = entry.Name()
|
||||
dirEntry.Mode = toSyscallMode(entry.Mode)
|
||||
inode := wfs.inodeToPath.Lookup(dirPath.Child(dirEntry.Name), entry.Crtime.Unix(), entry.IsDirectory(), len(entry.HardLinkId) > 0, entry.Inode, false)
|
||||
dirEntry.Ino = inode
|
||||
|
||||
// Set Off to the next offset so client can resume from correct position
|
||||
dirEntry.Off = dh.entryStreamOffset + uint64(index) + 1
|
||||
|
||||
if !isPlusMode {
|
||||
if !out.AddDirEntry(dirEntry) {
|
||||
isEarlyTerminated = true
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
entryOut := out.AddDirLookupEntry(dirEntry)
|
||||
if entryOut == nil {
|
||||
isEarlyTerminated = true
|
||||
return false
|
||||
}
|
||||
if fh, found := wfs.fhMap.FindFileHandle(inode); found {
|
||||
@@ -195,59 +198,90 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out *fuse.DirEntryList, isPl
|
||||
if input.Offset < directoryStreamBaseOffset {
|
||||
if !isPlusMode {
|
||||
if input.Offset == 0 {
|
||||
out.AddDirEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: "."})
|
||||
out.AddDirEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: ".", Off: 1})
|
||||
}
|
||||
out.AddDirEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: ".."})
|
||||
out.AddDirEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: "..", Off: 2})
|
||||
} else {
|
||||
if input.Offset == 0 {
|
||||
out.AddDirLookupEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: "."})
|
||||
out.AddDirLookupEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: ".", Off: 1})
|
||||
}
|
||||
out.AddDirLookupEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: ".."})
|
||||
out.AddDirLookupEntry(fuse.DirEntry{Mode: fuse.S_IFDIR, Name: "..", Off: 2})
|
||||
}
|
||||
input.Offset = directoryStreamBaseOffset
|
||||
}
|
||||
|
||||
var lastEntryName string
|
||||
|
||||
// Read from cache first, then load next batch if needed
|
||||
if input.Offset >= dh.entryStreamOffset {
|
||||
// Handle case: new handle with non-zero offset but empty cache
|
||||
// This happens when NFS-Ganesha opens multiple directory handles
|
||||
if len(dh.entryStream) == 0 && input.Offset > dh.entryStreamOffset {
|
||||
skipCount := int64(input.Offset - dh.entryStreamOffset)
|
||||
|
||||
if err := meta_cache.EnsureVisited(wfs.metaCache, wfs, dirPath); err != nil {
|
||||
glog.Errorf("dir ReadDirAll %s: %v", dirPath, err)
|
||||
return fuse.EIO
|
||||
}
|
||||
|
||||
// Load entries from beginning to fill cache up to the requested offset
|
||||
loadErr := wfs.metaCache.ListDirectoryEntries(context.Background(), dirPath, "", false, skipCount+int64(batchSize), func(entry *filer.Entry) (bool, error) {
|
||||
dh.entryStream = append(dh.entryStream, entry)
|
||||
return true, nil
|
||||
})
|
||||
if loadErr != nil {
|
||||
glog.Errorf("list meta cache: %v", loadErr)
|
||||
return fuse.EIO
|
||||
}
|
||||
}
|
||||
|
||||
if input.Offset > dh.entryStreamOffset {
|
||||
entryPreviousIndex := (input.Offset - dh.entryStreamOffset) - 1
|
||||
if uint64(len(dh.entryStream)) > entryPreviousIndex {
|
||||
lastEntryName = dh.entryStream[entryPreviousIndex].Name()
|
||||
dh.entryStream = dh.entryStream[entryPreviousIndex:]
|
||||
dh.entryStreamOffset = input.Offset - 1
|
||||
}
|
||||
}
|
||||
entryCurrentIndex := input.Offset - dh.entryStreamOffset
|
||||
for uint64(len(dh.entryStream)) > entryCurrentIndex {
|
||||
|
||||
entryCurrentIndex := int64(input.Offset - dh.entryStreamOffset)
|
||||
for int64(len(dh.entryStream)) > entryCurrentIndex {
|
||||
entry := dh.entryStream[entryCurrentIndex]
|
||||
if processEachEntryFn(entry) {
|
||||
if processEachEntryFn(entry, entryCurrentIndex) {
|
||||
lastEntryName = entry.Name()
|
||||
entryCurrentIndex++
|
||||
} else {
|
||||
// early terminated
|
||||
return fuse.OK
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := meta_cache.EnsureVisited(wfs.metaCache, wfs, dirPath); err != nil {
|
||||
glog.Errorf("dir ReadDirAll %s: %v", dirPath, err)
|
||||
return fuse.EIO
|
||||
}
|
||||
listErr := wfs.metaCache.ListDirectoryEntries(context.Background(), dirPath, lastEntryName, false, int64(math.MaxInt32), func(entry *filer.Entry) (bool, error) {
|
||||
dh.entryStream = append(dh.entryStream, entry)
|
||||
if !processEachEntryFn(entry) {
|
||||
return false, nil
|
||||
// Cache exhausted, load next batch
|
||||
if err := meta_cache.EnsureVisited(wfs.metaCache, wfs, dirPath); err != nil {
|
||||
glog.Errorf("dir ReadDirAll %s: %v", dirPath, err)
|
||||
return fuse.EIO
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
if listErr != nil {
|
||||
glog.Errorf("list meta cache: %v", listErr)
|
||||
return fuse.EIO
|
||||
}
|
||||
|
||||
if !isEarlyTerminated {
|
||||
dh.isFinished = true
|
||||
// Batch loading: fetch batchSize entries starting from lastEntryName
|
||||
loadedCount := 0
|
||||
bufferFull := false
|
||||
loadErr := wfs.metaCache.ListDirectoryEntries(context.Background(), dirPath, lastEntryName, false, int64(batchSize), func(entry *filer.Entry) (bool, error) {
|
||||
currentIndex := int64(len(dh.entryStream))
|
||||
dh.entryStream = append(dh.entryStream, entry)
|
||||
loadedCount++
|
||||
if !processEachEntryFn(entry, currentIndex) {
|
||||
bufferFull = true
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
if loadErr != nil {
|
||||
glog.Errorf("list meta cache: %v", loadErr)
|
||||
return fuse.EIO
|
||||
}
|
||||
|
||||
// Mark finished only when loading completed normally (not buffer full)
|
||||
// and we got fewer entries than requested
|
||||
if !bufferFull && loadedCount < batchSize {
|
||||
dh.isFinished = true
|
||||
}
|
||||
}
|
||||
|
||||
return fuse.OK
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// loopFlushDirtyMetadata periodically flushes dirty file metadata to the filer.
|
||||
// This protects newly uploaded chunks from being purged by volume.fsck orphan cleanup
|
||||
// for files that remain open for extended periods without being closed.
|
||||
//
|
||||
// The problem: When a file is opened and written to continuously, chunks are uploaded
|
||||
// to volume servers but the file metadata (containing chunk references) is only saved
|
||||
// to the filer on file close or fsync. If volume.fsck runs during this window, it may
|
||||
// identify these chunks as orphans (since they're not referenced in filer metadata)
|
||||
// and purge them.
|
||||
//
|
||||
// This background task periodically flushes metadata for open files, ensuring chunk
|
||||
// references are visible to volume.fsck even before files are closed.
|
||||
func (wfs *WFS) loopFlushDirtyMetadata() {
|
||||
if wfs.option.MetadataFlushSeconds <= 0 {
|
||||
glog.V(0).Infof("periodic metadata flush disabled")
|
||||
return
|
||||
}
|
||||
|
||||
flushInterval := time.Duration(wfs.option.MetadataFlushSeconds) * time.Second
|
||||
glog.V(0).Infof("periodic metadata flush enabled, interval: %v", flushInterval)
|
||||
|
||||
ticker := time.NewTicker(flushInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
wfs.flushAllDirtyMetadata()
|
||||
}
|
||||
}
|
||||
|
||||
// flushAllDirtyMetadata iterates through all open file handles and flushes
|
||||
// metadata for files that have dirty metadata (chunks uploaded but not yet persisted).
|
||||
func (wfs *WFS) flushAllDirtyMetadata() {
|
||||
// Collect file handles with dirty metadata under a read lock
|
||||
var dirtyHandles []*FileHandle
|
||||
wfs.fhMap.RLock()
|
||||
for _, fh := range wfs.fhMap.inode2fh {
|
||||
if fh.dirtyMetadata {
|
||||
dirtyHandles = append(dirtyHandles, fh)
|
||||
}
|
||||
}
|
||||
wfs.fhMap.RUnlock()
|
||||
|
||||
if len(dirtyHandles) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
glog.V(3).Infof("flushing metadata for %d open files", len(dirtyHandles))
|
||||
|
||||
// Process dirty handles in parallel with limited concurrency
|
||||
var wg sync.WaitGroup
|
||||
concurrency := wfs.option.ConcurrentWriters
|
||||
if concurrency <= 0 {
|
||||
concurrency = 16
|
||||
}
|
||||
sem := make(chan struct{}, concurrency)
|
||||
|
||||
for _, fh := range dirtyHandles {
|
||||
wg.Add(1)
|
||||
sem <- struct{}{}
|
||||
go func(handle *FileHandle) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
if err := wfs.flushFileMetadata(handle); err != nil {
|
||||
glog.Warningf("failed to flush metadata for %s: %v", handle.FullPath(), err)
|
||||
}
|
||||
}(fh)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// flushFileMetadata flushes the current file metadata to the filer without
|
||||
// flushing dirty pages from memory. This updates chunk references in the filer
|
||||
// so volume.fsck can see them, while keeping data in the write buffer.
|
||||
func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
|
||||
// Acquire exclusive lock on the file handle
|
||||
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("flushMetadata", fh.fh, util.ExclusiveLock)
|
||||
defer fh.wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
|
||||
|
||||
// Double-check dirty flag under lock
|
||||
if !fh.dirtyMetadata {
|
||||
return nil
|
||||
}
|
||||
|
||||
fileFullPath := fh.FullPath()
|
||||
dir, name := fileFullPath.DirAndName()
|
||||
|
||||
glog.V(4).Infof("flushFileMetadata %s fh %d", fileFullPath, fh.fh)
|
||||
|
||||
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
entry := fh.GetEntry()
|
||||
if entry == nil {
|
||||
return nil
|
||||
}
|
||||
entry.Name = name
|
||||
|
||||
if entry.Attributes != nil {
|
||||
entry.Attributes.Mtime = time.Now().Unix()
|
||||
}
|
||||
|
||||
// Get current chunks - these include chunks that have been uploaded
|
||||
// but not yet persisted to filer metadata
|
||||
chunks := entry.GetChunks()
|
||||
if len(chunks) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Separate manifest and non-manifest chunks
|
||||
manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(chunks)
|
||||
|
||||
// Compact chunks to remove fully overlapped ones
|
||||
compactedChunks, _ := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
|
||||
|
||||
// Try to create manifest chunks for large files
|
||||
compactedChunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), compactedChunks)
|
||||
if manifestErr != nil {
|
||||
glog.V(0).Infof("flushFileMetadata MaybeManifestize: %v", manifestErr)
|
||||
}
|
||||
|
||||
entry.Chunks = append(compactedChunks, manifestChunks...)
|
||||
|
||||
request := &filer_pb.CreateEntryRequest{
|
||||
Directory: string(dir),
|
||||
Entry: entry.GetEntry(),
|
||||
Signatures: []int32{wfs.signature},
|
||||
SkipCheckParentDirectory: true,
|
||||
}
|
||||
|
||||
wfs.mapPbIdFromLocalToFiler(request.Entry)
|
||||
defer wfs.mapPbIdFromFilerToLocal(request.Entry)
|
||||
|
||||
if err := filer_pb.CreateEntry(context.Background(), client, request); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Update meta cache
|
||||
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
|
||||
return fmt.Errorf("update meta cache for %s: %w", fileFullPath, err)
|
||||
}
|
||||
|
||||
glog.V(3).Infof("flushed metadata for %s with %d chunks", fileFullPath, len(entry.GetChunks()))
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Note: We do NOT clear dirtyMetadata here because:
|
||||
// 1. There may still be dirty pages in the write buffer
|
||||
// 2. The file may receive more writes before close
|
||||
// 3. dirtyMetadata will be cleared on the final flush when the file is closed
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -4,12 +4,13 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"google.golang.org/grpc"
|
||||
"math/rand/v2"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
@@ -101,7 +102,7 @@ func LookupVolumeIds(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vids
|
||||
GrpcPort: int(loc.GrpcPort),
|
||||
})
|
||||
}
|
||||
if vidLocations.Error != "" {
|
||||
if vidLocations.Error == "" {
|
||||
vc.Set(vidLocations.VolumeOrFileId, locations, 10*time.Minute)
|
||||
}
|
||||
ret[vidLocations.VolumeOrFileId] = &LookupResult{
|
||||
|
||||
@@ -110,7 +110,7 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
|
||||
func AddOffsetFunc(processEventFn ProcessMetadataFunc, offsetInterval time.Duration, offsetFunc func(counter int64, offset int64) error) ProcessMetadataFunc {
|
||||
var counter int64
|
||||
var lastWriteTime time.Time
|
||||
var lastWriteTime = time.Now()
|
||||
return func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if err := processEventFn(resp); err != nil {
|
||||
return err
|
||||
|
||||
@@ -138,23 +138,25 @@ func requestIDUnaryInterceptor() grpc.UnaryServerInterceptor {
|
||||
info *grpc.UnaryServerInfo,
|
||||
handler grpc.UnaryHandler,
|
||||
) (interface{}, error) {
|
||||
incomingMd, _ := metadata.FromIncomingContext(ctx)
|
||||
idList := incomingMd.Get(request_id.AmzRequestIDHeader)
|
||||
// Get request ID from incoming metadata
|
||||
var reqID string
|
||||
if len(idList) > 0 {
|
||||
reqID = idList[0]
|
||||
if incomingMd, ok := metadata.FromIncomingContext(ctx); ok {
|
||||
if idList := incomingMd.Get(request_id.AmzRequestIDHeader); len(idList) > 0 {
|
||||
reqID = idList[0]
|
||||
}
|
||||
}
|
||||
if reqID == "" {
|
||||
reqID = uuid.New().String()
|
||||
}
|
||||
|
||||
ctx = metadata.NewOutgoingContext(ctx,
|
||||
metadata.New(map[string]string{
|
||||
request_id.AmzRequestIDHeader: reqID,
|
||||
}))
|
||||
|
||||
// Store request ID in context for handlers to access
|
||||
ctx = request_id.Set(ctx, reqID)
|
||||
|
||||
// Also set outgoing context so handlers making downstream gRPC calls
|
||||
// will automatically propagate the request ID
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, request_id.AmzRequestIDHeader, reqID)
|
||||
|
||||
// Set trailer with request ID for response
|
||||
grpc.SetTrailer(ctx, metadata.Pairs(request_id.AmzRequestIDHeader, reqID))
|
||||
|
||||
return handler(ctx, req)
|
||||
@@ -187,8 +189,8 @@ func WithGrpcClient(streamingMode bool, signature int32, fn func(*grpc.ClientCon
|
||||
} else {
|
||||
ctx := context.Background()
|
||||
if signature != 0 {
|
||||
md := metadata.New(map[string]string{"sw-client-id": fmt.Sprintf("%d", signature)})
|
||||
ctx = metadata.NewOutgoingContext(ctx, md)
|
||||
// Optimize: Use AppendToOutgoingContext instead of creating new map
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, "sw-client-id", fmt.Sprintf("%d", signature))
|
||||
}
|
||||
grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
|
||||
if err != nil {
|
||||
|
||||
@@ -610,19 +610,19 @@ func (iam *IdentityAccessManagement) authRequest(r *http.Request, action Action)
|
||||
}
|
||||
|
||||
// Only check IAM if bucket policy didn't explicitly allow
|
||||
// This ensures bucket policies can independently grant access (AWS semantics)
|
||||
if !policyAllows {
|
||||
// Use enhanced IAM authorization if available, otherwise fall back to legacy authorization
|
||||
if iam.iamIntegration != nil {
|
||||
// Always use IAM when available for unified authorization
|
||||
// Traditional identities (with Actions from -s3.config) use legacy auth,
|
||||
// JWT/STS identities (no Actions) use IAM authorization
|
||||
if len(identity.Actions) > 0 {
|
||||
if !identity.canDo(action, bucket, object) {
|
||||
return identity, s3err.ErrAccessDenied
|
||||
}
|
||||
} else if iam.iamIntegration != nil {
|
||||
if errCode := iam.authorizeWithIAM(r, identity, action, bucket, object); errCode != s3err.ErrNone {
|
||||
return identity, errCode
|
||||
}
|
||||
} else {
|
||||
// Fall back to existing authorization when IAM is not configured
|
||||
if !identity.canDo(action, bucket, object) {
|
||||
return identity, s3err.ErrAccessDenied
|
||||
}
|
||||
return identity, s3err.ErrAccessDenied
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -771,6 +771,11 @@ func (iam *IdentityAccessManagement) SetIAMIntegration(integration *S3IAMIntegra
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
iam.iamIntegration = integration
|
||||
// When IAM integration is configured, authentication must be enabled
|
||||
// to ensure requests go through proper auth checks
|
||||
if integration != nil {
|
||||
iam.isAuthEnabled = true
|
||||
}
|
||||
}
|
||||
|
||||
// authenticateJWTWithIAM authenticates JWT tokens using the IAM integration
|
||||
|
||||
@@ -140,17 +140,44 @@ const (
|
||||
func GetBucketAndObject(r *http.Request) (bucket, object string) {
|
||||
vars := mux.Vars(r)
|
||||
bucket = vars["bucket"]
|
||||
object = vars["object"]
|
||||
object = NormalizeObjectKey(vars["object"])
|
||||
return
|
||||
}
|
||||
|
||||
// NormalizeObjectKey ensures the object key has a leading slash and no duplicate slashes.
|
||||
// This normalizes keys from various sources (URL path, form values, etc.) to a consistent format.
|
||||
func NormalizeObjectKey(object string) string {
|
||||
object = removeDuplicateSlashes(object)
|
||||
if !strings.HasPrefix(object, "/") {
|
||||
object = "/" + object
|
||||
}
|
||||
return object
|
||||
}
|
||||
|
||||
return
|
||||
// removeDuplicateSlashes removes consecutive slashes from a path
|
||||
func removeDuplicateSlashes(s string) string {
|
||||
var result strings.Builder
|
||||
result.Grow(len(s))
|
||||
|
||||
lastWasSlash := false
|
||||
for _, r := range s {
|
||||
if r == '/' {
|
||||
if !lastWasSlash {
|
||||
result.WriteRune(r)
|
||||
}
|
||||
lastWasSlash = true
|
||||
} else {
|
||||
result.WriteRune(r)
|
||||
lastWasSlash = false
|
||||
}
|
||||
}
|
||||
return result.String()
|
||||
}
|
||||
|
||||
func GetPrefix(r *http.Request) string {
|
||||
query := r.URL.Query()
|
||||
prefix := query.Get("prefix")
|
||||
prefix = removeDuplicateSlashes(prefix)
|
||||
if !strings.HasPrefix(prefix, "/") {
|
||||
prefix = "/" + prefix
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -654,3 +655,155 @@ func executeS3OperationWithJWT(t *testing.T, s3Server http.Handler, operation S3
|
||||
|
||||
return allowed
|
||||
}
|
||||
|
||||
// TestS3AuthenticationDenied tests that unauthenticated and invalid requests are properly rejected
|
||||
func TestS3AuthenticationDenied(t *testing.T) {
|
||||
s3Server, _ := setupCompleteS3IAMSystem(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupRequest func() *http.Request
|
||||
expectedStatus int
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "no_authorization_header",
|
||||
setupRequest: func() *http.Request {
|
||||
req := httptest.NewRequest("GET", "/test-auth", nil)
|
||||
// No Authorization header
|
||||
return req
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
description: "Request without Authorization header should be rejected",
|
||||
},
|
||||
{
|
||||
name: "empty_bearer_token",
|
||||
setupRequest: func() *http.Request {
|
||||
req := httptest.NewRequest("GET", "/test-auth", nil)
|
||||
req.Header.Set("Authorization", "Bearer ")
|
||||
return req
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
description: "Request with empty Bearer token should be rejected",
|
||||
},
|
||||
{
|
||||
name: "invalid_jwt_token",
|
||||
setupRequest: func() *http.Request {
|
||||
req := httptest.NewRequest("GET", "/test-auth", nil)
|
||||
req.Header.Set("Authorization", "Bearer invalid.jwt.token")
|
||||
return req
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
description: "Request with invalid JWT token should be rejected",
|
||||
},
|
||||
{
|
||||
name: "malformed_authorization_header",
|
||||
setupRequest: func() *http.Request {
|
||||
req := httptest.NewRequest("GET", "/test-auth", nil)
|
||||
req.Header.Set("Authorization", "NotBearer sometoken")
|
||||
return req
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
description: "Request with malformed Authorization header should be rejected",
|
||||
},
|
||||
{
|
||||
name: "expired_jwt_token",
|
||||
setupRequest: func() *http.Request {
|
||||
// Create an expired JWT token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"iss": "https://test-issuer.com",
|
||||
"sub": "test-user",
|
||||
"exp": time.Now().Add(-time.Hour).Unix(), // Expired 1 hour ago
|
||||
"iat": time.Now().Add(-2 * time.Hour).Unix(),
|
||||
})
|
||||
tokenString, _ := token.SignedString([]byte("test-signing-key"))
|
||||
|
||||
req := httptest.NewRequest("GET", "/test-auth", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenString)
|
||||
return req
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
description: "Request with expired JWT token should be rejected",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := tt.setupRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
s3Server.ServeHTTP(recorder, req)
|
||||
|
||||
// Verify the request was rejected with the expected status
|
||||
assert.Equal(t, tt.expectedStatus, recorder.Code,
|
||||
"%s: expected status %d but got %d. Response: %s",
|
||||
tt.description, tt.expectedStatus, recorder.Code, recorder.Body.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestS3IAMOnlyModeRejectsAnonymous tests that when only IAM is configured
|
||||
// (no traditional identities), anonymous requests are properly denied
|
||||
func TestS3IAMOnlyModeRejectsAnonymous(t *testing.T) {
|
||||
// Create IAM with NO traditional identities (simulating IAM-only setup)
|
||||
iam := &IdentityAccessManagement{
|
||||
identities: []*Identity{},
|
||||
accessKeyIdent: make(map[string]*Identity),
|
||||
nameToIdentity: make(map[string]*Identity),
|
||||
accounts: make(map[string]*Account),
|
||||
emailAccount: make(map[string]*Account),
|
||||
hashes: make(map[string]*sync.Pool),
|
||||
hashCounters: make(map[string]*int32),
|
||||
}
|
||||
|
||||
// Set up IAM integration
|
||||
iamManager := integration.NewIAMManager()
|
||||
config := &integration.IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: time.Hour * 12},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
DefaultEffect: "Deny",
|
||||
StoreType: "memory",
|
||||
},
|
||||
Roles: &integration.RoleStoreConfig{
|
||||
StoreType: "memory",
|
||||
},
|
||||
}
|
||||
|
||||
err := iamManager.Initialize(config, func() string {
|
||||
return "localhost:8888"
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
s3IAMIntegration := NewS3IAMIntegration(iamManager, "localhost:8888")
|
||||
require.NotNil(t, s3IAMIntegration)
|
||||
|
||||
// Set IAM integration - this should enable auth
|
||||
iam.SetIAMIntegration(s3IAMIntegration)
|
||||
|
||||
// Verify auth is enabled
|
||||
require.True(t, iam.isEnabled(), "Auth must be enabled when IAM integration is configured")
|
||||
|
||||
// Test that the Auth middleware blocks unauthenticated requests
|
||||
handlerCalled := false
|
||||
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
handlerCalled = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
// Wrap with auth middleware
|
||||
wrappedHandler := iam.Auth(testHandler, "Write")
|
||||
|
||||
// Create an unauthenticated request
|
||||
req := httptest.NewRequest("PUT", "/mybucket/test.txt", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
wrappedHandler.ServeHTTP(rr, req)
|
||||
|
||||
// Handler should NOT have been called
|
||||
assert.False(t, handlerCalled, "Handler should not be called for unauthenticated request")
|
||||
assert.NotEqual(t, http.StatusOK, rr.Code, "Unauthenticated request should not return 200 OK")
|
||||
}
|
||||
@@ -201,6 +201,7 @@ func removeDuplicateSlashes(object string) string {
|
||||
return result.String()
|
||||
}
|
||||
|
||||
|
||||
// hasChildren checks if a path has any child objects (is a directory with contents)
|
||||
//
|
||||
// This helper function is used to distinguish implicit directories from regular files or empty directories.
|
||||
|
||||
@@ -573,6 +573,10 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
|
||||
break
|
||||
}
|
||||
|
||||
// Update nextMarker to ensure pagination advances past this .versions directory
|
||||
// This is critical to prevent infinite loops when results are truncated
|
||||
nextMarker = versionsDir
|
||||
|
||||
// Extract object name from .versions directory name (remove .versions suffix)
|
||||
baseObjectName := strings.TrimSuffix(versionsDir, s3_constants.VersionsFolder)
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
if fileName != "" && strings.Contains(formValues.Get("Key"), "${filename}") {
|
||||
formValues.Set("Key", strings.Replace(formValues.Get("Key"), "${filename}", fileName, -1))
|
||||
}
|
||||
object := formValues.Get("Key")
|
||||
object := s3_constants.NormalizeObjectKey(formValues.Get("Key"))
|
||||
|
||||
successRedirect := formValues.Get("success_action_redirect")
|
||||
successStatus := formValues.Get("success_action_status")
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestPostPolicyKeyNormalization tests that object keys from presigned POST
|
||||
// are properly normalized with a leading slash and duplicate slashes removed.
|
||||
// This addresses issue #7713 where keys without leading slashes caused
|
||||
// bucket and key to be concatenated without a separator.
|
||||
func TestPostPolicyKeyNormalization(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
expectedPrefix string // Expected path prefix after bucket
|
||||
}{
|
||||
{
|
||||
name: "key without leading slash",
|
||||
key: "test_image.png",
|
||||
expectedPrefix: "/test_image.png",
|
||||
},
|
||||
{
|
||||
name: "key with leading slash",
|
||||
key: "/test_image.png",
|
||||
expectedPrefix: "/test_image.png",
|
||||
},
|
||||
{
|
||||
name: "key with path without leading slash",
|
||||
key: "folder/subfolder/test_image.png",
|
||||
expectedPrefix: "/folder/subfolder/test_image.png",
|
||||
},
|
||||
{
|
||||
name: "key with path with leading slash",
|
||||
key: "/folder/subfolder/test_image.png",
|
||||
expectedPrefix: "/folder/subfolder/test_image.png",
|
||||
},
|
||||
{
|
||||
name: "simple filename",
|
||||
key: "file.txt",
|
||||
expectedPrefix: "/file.txt",
|
||||
},
|
||||
{
|
||||
name: "key with duplicate slashes",
|
||||
key: "folder//subfolder///file.txt",
|
||||
expectedPrefix: "/folder/subfolder/file.txt",
|
||||
},
|
||||
{
|
||||
name: "key with leading duplicate slashes",
|
||||
key: "//folder/file.txt",
|
||||
expectedPrefix: "/folder/file.txt",
|
||||
},
|
||||
{
|
||||
name: "key with trailing slash",
|
||||
key: "folder/",
|
||||
expectedPrefix: "/folder/",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Use the actual NormalizeObjectKey function
|
||||
object := s3_constants.NormalizeObjectKey(tt.key)
|
||||
|
||||
// Verify the normalized object has the expected prefix
|
||||
assert.Equal(t, tt.expectedPrefix, object,
|
||||
"Key should be normalized correctly")
|
||||
|
||||
// Verify path construction would be correct
|
||||
bucket := "my-bucket"
|
||||
bucketsPath := "/buckets"
|
||||
expectedPath := bucketsPath + "/" + bucket + tt.expectedPrefix
|
||||
actualPath := bucketsPath + "/" + bucket + object
|
||||
|
||||
assert.Equal(t, expectedPath, actualPath,
|
||||
"File path should be correctly constructed with slash between bucket and key")
|
||||
|
||||
// Verify we don't have double slashes (except at the start which is fine)
|
||||
assert.NotContains(t, actualPath[1:], "//",
|
||||
"Path should not contain double slashes")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeObjectKey tests the NormalizeObjectKey function directly
|
||||
func TestNormalizeObjectKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{"empty string", "", "/"},
|
||||
{"simple file", "file.txt", "/file.txt"},
|
||||
{"with leading slash", "/file.txt", "/file.txt"},
|
||||
{"path without slash", "a/b/c.txt", "/a/b/c.txt"},
|
||||
{"path with slash", "/a/b/c.txt", "/a/b/c.txt"},
|
||||
{"duplicate slashes", "a//b///c.txt", "/a/b/c.txt"},
|
||||
{"leading duplicates", "///a/b.txt", "/a/b.txt"},
|
||||
{"all duplicates", "//a//b//", "/a/b/"},
|
||||
{"just slashes", "///", "/"},
|
||||
{"trailing slash", "folder/", "/folder/"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := s3_constants.NormalizeObjectKey(tt.input)
|
||||
assert.Equal(t, tt.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostPolicyFilenameSubstitution tests the ${filename} substitution in keys
|
||||
func TestPostPolicyFilenameSubstitution(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
keyTemplate string
|
||||
uploadedFilename string
|
||||
expectedKey string
|
||||
}{
|
||||
{
|
||||
name: "filename at end",
|
||||
keyTemplate: "uploads/${filename}",
|
||||
uploadedFilename: "photo.jpg",
|
||||
expectedKey: "/uploads/photo.jpg",
|
||||
},
|
||||
{
|
||||
name: "filename in middle",
|
||||
keyTemplate: "user/files/${filename}/original",
|
||||
uploadedFilename: "document.pdf",
|
||||
expectedKey: "/user/files/document.pdf/original",
|
||||
},
|
||||
{
|
||||
name: "no substitution needed",
|
||||
keyTemplate: "static/file.txt",
|
||||
uploadedFilename: "ignored.txt",
|
||||
expectedKey: "/static/file.txt",
|
||||
},
|
||||
{
|
||||
name: "filename only",
|
||||
keyTemplate: "${filename}",
|
||||
uploadedFilename: "myfile.png",
|
||||
expectedKey: "/myfile.png",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Simulate the substitution logic from PostPolicyBucketHandler
|
||||
key := tt.keyTemplate
|
||||
if tt.uploadedFilename != "" && strings.Contains(key, "${filename}") {
|
||||
key = strings.Replace(key, "${filename}", tt.uploadedFilename, -1)
|
||||
}
|
||||
|
||||
// Normalize using the actual function
|
||||
object := s3_constants.NormalizeObjectKey(key)
|
||||
|
||||
assert.Equal(t, tt.expectedKey, object,
|
||||
"Key should be correctly substituted and normalized")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractPostPolicyFormValues tests the form value extraction
|
||||
func TestExtractPostPolicyFormValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
contentType string
|
||||
fileContent string
|
||||
fileName string
|
||||
expectSuccess bool
|
||||
}{
|
||||
{
|
||||
name: "basic upload",
|
||||
key: "test.txt",
|
||||
contentType: "text/plain",
|
||||
fileContent: "hello world",
|
||||
fileName: "upload.txt",
|
||||
expectSuccess: true,
|
||||
},
|
||||
{
|
||||
name: "upload with path key",
|
||||
key: "folder/subfolder/test.txt",
|
||||
contentType: "application/octet-stream",
|
||||
fileContent: "binary data",
|
||||
fileName: "data.bin",
|
||||
expectSuccess: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create multipart form
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
|
||||
// Add form fields
|
||||
writer.WriteField("key", tt.key)
|
||||
writer.WriteField("Content-Type", tt.contentType)
|
||||
|
||||
// Add file
|
||||
part, err := writer.CreateFormFile("file", tt.fileName)
|
||||
assert.NoError(t, err)
|
||||
_, err = io.WriteString(part, tt.fileContent)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = writer.Close()
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Parse the form
|
||||
reader := multipart.NewReader(&buf, writer.Boundary())
|
||||
form, err := reader.ReadForm(5 * 1024 * 1024)
|
||||
assert.NoError(t, err)
|
||||
defer form.RemoveAll()
|
||||
|
||||
// Extract values using the actual function
|
||||
filePart, fileName, fileContentType, fileSize, formValues, err := extractPostPolicyFormValues(form)
|
||||
|
||||
if tt.expectSuccess {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, filePart)
|
||||
assert.Equal(t, tt.fileName, fileName)
|
||||
assert.NotEmpty(t, fileContentType)
|
||||
assert.Greater(t, fileSize, int64(0))
|
||||
assert.Equal(t, tt.key, formValues.Get("Key"))
|
||||
|
||||
filePart.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostPolicyPathConstruction is an integration-style test that verifies
|
||||
// the complete path construction logic
|
||||
func TestPostPolicyPathConstruction(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
bucket string
|
||||
formKey string // Key as it would come from form (may not have leading slash)
|
||||
expectedPath string
|
||||
}{
|
||||
{
|
||||
name: "simple key without slash - the bug case",
|
||||
bucket: "my-bucket",
|
||||
formKey: "test_image.png",
|
||||
expectedPath: "/buckets/my-bucket/test_image.png",
|
||||
},
|
||||
{
|
||||
name: "simple key with slash",
|
||||
bucket: "my-bucket",
|
||||
formKey: "/test_image.png",
|
||||
expectedPath: "/buckets/my-bucket/test_image.png",
|
||||
},
|
||||
{
|
||||
name: "nested path without leading slash",
|
||||
bucket: "uploads",
|
||||
formKey: "2024/01/photo.jpg",
|
||||
expectedPath: "/buckets/uploads/2024/01/photo.jpg",
|
||||
},
|
||||
{
|
||||
name: "nested path with leading slash",
|
||||
bucket: "uploads",
|
||||
formKey: "/2024/01/photo.jpg",
|
||||
expectedPath: "/buckets/uploads/2024/01/photo.jpg",
|
||||
},
|
||||
{
|
||||
name: "key with duplicate slashes",
|
||||
bucket: "my-bucket",
|
||||
formKey: "folder//file.txt",
|
||||
expectedPath: "/buckets/my-bucket/folder/file.txt",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Use the actual NormalizeObjectKey function
|
||||
object := s3_constants.NormalizeObjectKey(tt.formKey)
|
||||
|
||||
// Construct path as done in PostPolicyBucketHandler
|
||||
filePath := s3a.option.BucketsPath + "/" + tt.bucket + object
|
||||
|
||||
assert.Equal(t, tt.expectedPath, filePath,
|
||||
"File path should be correctly constructed")
|
||||
|
||||
// Verify bucket and key are properly separated
|
||||
assert.Contains(t, filePath, tt.bucket+"/",
|
||||
"Bucket should be followed by a slash")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostPolicyBucketHandlerKeyExtraction tests that the handler correctly
|
||||
// extracts and normalizes the key from a POST request
|
||||
func TestPostPolicyBucketHandlerKeyExtraction(t *testing.T) {
|
||||
// Create a minimal S3ApiServer for testing
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
bucket string
|
||||
key string
|
||||
wantPathHas string // substring that must be in the constructed path
|
||||
}{
|
||||
{
|
||||
name: "key without leading slash",
|
||||
bucket: "test-bucket",
|
||||
key: "simple-file.txt",
|
||||
wantPathHas: "/test-bucket/simple-file.txt",
|
||||
},
|
||||
{
|
||||
name: "key with leading slash",
|
||||
bucket: "test-bucket",
|
||||
key: "/prefixed-file.txt",
|
||||
wantPathHas: "/test-bucket/prefixed-file.txt",
|
||||
},
|
||||
{
|
||||
name: "key with duplicate slashes",
|
||||
bucket: "test-bucket",
|
||||
key: "folder//nested///file.txt",
|
||||
wantPathHas: "/test-bucket/folder/nested/file.txt",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create multipart form body
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
|
||||
// Add required fields
|
||||
writer.WriteField("key", tt.key)
|
||||
writer.WriteField("Policy", "") // Empty policy for this test
|
||||
|
||||
// Add file
|
||||
part, _ := writer.CreateFormFile("file", "test.txt")
|
||||
part.Write([]byte("test content"))
|
||||
writer.Close()
|
||||
|
||||
// Create request
|
||||
req := httptest.NewRequest(http.MethodPost, "/"+tt.bucket, &buf)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
// Set up mux vars (simulating router)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": tt.bucket})
|
||||
|
||||
// Parse form to extract key
|
||||
reader, _ := req.MultipartReader()
|
||||
form, _ := reader.ReadForm(5 * 1024 * 1024)
|
||||
defer form.RemoveAll()
|
||||
|
||||
_, _, _, _, formValues, _ := extractPostPolicyFormValues(form)
|
||||
|
||||
// Apply the same normalization as PostPolicyBucketHandler
|
||||
object := s3_constants.NormalizeObjectKey(formValues.Get("Key"))
|
||||
|
||||
// Construct path
|
||||
filePath := s3a.option.BucketsPath + "/" + tt.bucket + object
|
||||
|
||||
assert.Contains(t, filePath, tt.wantPathHas,
|
||||
"Path should contain properly separated bucket and key")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -264,225 +264,237 @@ func (s3a *S3ApiServer) listObjectVersions(bucket, prefix, keyMarker, versionIdM
|
||||
|
||||
// findVersionsRecursively searches for all .versions directories and regular files recursively
|
||||
func (s3a *S3ApiServer) findVersionsRecursively(currentPath, relativePath string, allVersions *[]interface{}, processedObjects map[string]bool, seenVersionIds map[string]bool, bucket, prefix string) error {
|
||||
// List entries in current directory
|
||||
entries, _, err := s3a.list(currentPath, "", "", false, 1000)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
entryPath := path.Join(relativePath, entry.Name)
|
||||
|
||||
// Skip if this doesn't match the prefix filter
|
||||
if normalizedPrefix := strings.TrimPrefix(prefix, "/"); normalizedPrefix != "" {
|
||||
// An entry is a candidate if:
|
||||
// 1. Its path is a match for the prefix.
|
||||
// 2. It is a directory that is an ancestor of the prefix path, so we must descend into it.
|
||||
|
||||
// Condition 1: The entry's path starts with the prefix.
|
||||
isMatch := strings.HasPrefix(entryPath, normalizedPrefix)
|
||||
if !isMatch && entry.IsDirectory {
|
||||
// Also check if a directory entry matches a directory-style prefix (e.g., prefix "a/", entry "a").
|
||||
isMatch = strings.HasPrefix(entryPath+"/", normalizedPrefix)
|
||||
}
|
||||
|
||||
// Condition 2: The prefix path starts with the entry's path (and it's a directory).
|
||||
canDescend := entry.IsDirectory && strings.HasPrefix(normalizedPrefix, entryPath)
|
||||
|
||||
if !isMatch && !canDescend {
|
||||
continue
|
||||
}
|
||||
// List entries in current directory with pagination
|
||||
startFrom := ""
|
||||
for {
|
||||
entries, isLast, err := s3a.list(currentPath, "", startFrom, false, filer.PaginationSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if entry.IsDirectory {
|
||||
// Skip .uploads directory (multipart upload temporary files)
|
||||
if strings.HasPrefix(entry.Name, ".uploads") {
|
||||
continue
|
||||
for _, entry := range entries {
|
||||
// Track last entry name for pagination
|
||||
startFrom = entry.Name
|
||||
|
||||
entryPath := path.Join(relativePath, entry.Name)
|
||||
|
||||
// Skip if this doesn't match the prefix filter
|
||||
if normalizedPrefix := strings.TrimPrefix(prefix, "/"); normalizedPrefix != "" {
|
||||
// An entry is a candidate if:
|
||||
// 1. Its path is a match for the prefix.
|
||||
// 2. It is a directory that is an ancestor of the prefix path, so we must descend into it.
|
||||
|
||||
// Condition 1: The entry's path starts with the prefix.
|
||||
isMatch := strings.HasPrefix(entryPath, normalizedPrefix)
|
||||
if !isMatch && entry.IsDirectory {
|
||||
// Also check if a directory entry matches a directory-style prefix (e.g., prefix "a/", entry "a").
|
||||
isMatch = strings.HasPrefix(entryPath+"/", normalizedPrefix)
|
||||
}
|
||||
|
||||
// Condition 2: The prefix path starts with the entry's path (and it's a directory).
|
||||
canDescend := entry.IsDirectory && strings.HasPrefix(normalizedPrefix, entryPath)
|
||||
|
||||
if !isMatch && !canDescend {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this is a .versions directory
|
||||
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
|
||||
// Extract object name from .versions directory name
|
||||
objectKey := strings.TrimSuffix(entryPath, s3_constants.VersionsFolder)
|
||||
normalizedObjectKey := removeDuplicateSlashes(objectKey)
|
||||
// Mark both keys as processed for backward compatibility
|
||||
processedObjects[objectKey] = true
|
||||
processedObjects[normalizedObjectKey] = true
|
||||
|
||||
glog.V(2).Infof("Found .versions directory for object %s (normalized: %s)", objectKey, normalizedObjectKey)
|
||||
|
||||
versions, err := s3a.getObjectVersionList(bucket, normalizedObjectKey)
|
||||
if err != nil {
|
||||
glog.Warningf("Failed to get versions for object %s (normalized: %s): %v", objectKey, normalizedObjectKey, err)
|
||||
if entry.IsDirectory {
|
||||
// Skip .uploads directory (multipart upload temporary files)
|
||||
if strings.HasPrefix(entry.Name, ".uploads") {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, version := range versions {
|
||||
// Check for duplicate version IDs and skip if already seen
|
||||
// Use normalized key for deduplication
|
||||
versionKey := normalizedObjectKey + ":" + version.VersionId
|
||||
if seenVersionIds[versionKey] {
|
||||
glog.Warningf("findVersionsRecursively: duplicate version %s for object %s detected, skipping", version.VersionId, normalizedObjectKey)
|
||||
// Check if this is a .versions directory
|
||||
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
|
||||
// Extract object name from .versions directory name
|
||||
objectKey := strings.TrimSuffix(entryPath, s3_constants.VersionsFolder)
|
||||
normalizedObjectKey := removeDuplicateSlashes(objectKey)
|
||||
// Mark both keys as processed for backward compatibility
|
||||
processedObjects[objectKey] = true
|
||||
processedObjects[normalizedObjectKey] = true
|
||||
|
||||
glog.V(2).Infof("Found .versions directory for object %s (normalized: %s)", objectKey, normalizedObjectKey)
|
||||
|
||||
versions, err := s3a.getObjectVersionList(bucket, normalizedObjectKey)
|
||||
if err != nil {
|
||||
glog.Warningf("Failed to get versions for object %s (normalized: %s): %v", objectKey, normalizedObjectKey, err)
|
||||
continue
|
||||
}
|
||||
seenVersionIds[versionKey] = true
|
||||
|
||||
if version.IsDeleteMarker {
|
||||
glog.V(4).Infof("Adding delete marker from .versions: objectKey=%s, versionId=%s, isLatest=%v, versionKey=%s",
|
||||
normalizedObjectKey, version.VersionId, version.IsLatest, versionKey)
|
||||
deleteMarker := &DeleteMarkerEntry{
|
||||
Key: normalizedObjectKey, // Use normalized key for consistency
|
||||
VersionId: version.VersionId,
|
||||
IsLatest: version.IsLatest,
|
||||
LastModified: version.LastModified,
|
||||
Owner: s3a.getObjectOwnerFromVersion(version, bucket, normalizedObjectKey),
|
||||
for _, version := range versions {
|
||||
// Check for duplicate version IDs and skip if already seen
|
||||
// Use normalized key for deduplication
|
||||
versionKey := normalizedObjectKey + ":" + version.VersionId
|
||||
if seenVersionIds[versionKey] {
|
||||
glog.Warningf("findVersionsRecursively: duplicate version %s for object %s detected, skipping", version.VersionId, normalizedObjectKey)
|
||||
continue
|
||||
}
|
||||
*allVersions = append(*allVersions, deleteMarker)
|
||||
} else {
|
||||
glog.V(4).Infof("Adding version from .versions: objectKey=%s, versionId=%s, isLatest=%v, versionKey=%s",
|
||||
normalizedObjectKey, version.VersionId, version.IsLatest, versionKey)
|
||||
seenVersionIds[versionKey] = true
|
||||
|
||||
if version.IsDeleteMarker {
|
||||
glog.V(4).Infof("Adding delete marker from .versions: objectKey=%s, versionId=%s, isLatest=%v, versionKey=%s",
|
||||
normalizedObjectKey, version.VersionId, version.IsLatest, versionKey)
|
||||
deleteMarker := &DeleteMarkerEntry{
|
||||
Key: normalizedObjectKey, // Use normalized key for consistency
|
||||
VersionId: version.VersionId,
|
||||
IsLatest: version.IsLatest,
|
||||
LastModified: version.LastModified,
|
||||
Owner: s3a.getObjectOwnerFromVersion(version, bucket, normalizedObjectKey),
|
||||
}
|
||||
*allVersions = append(*allVersions, deleteMarker)
|
||||
} else {
|
||||
glog.V(4).Infof("Adding version from .versions: objectKey=%s, versionId=%s, isLatest=%v, versionKey=%s",
|
||||
normalizedObjectKey, version.VersionId, version.IsLatest, versionKey)
|
||||
versionEntry := &VersionEntry{
|
||||
Key: normalizedObjectKey, // Use normalized key for consistency
|
||||
VersionId: version.VersionId,
|
||||
IsLatest: version.IsLatest,
|
||||
LastModified: version.LastModified,
|
||||
ETag: version.ETag,
|
||||
Size: version.Size,
|
||||
Owner: s3a.getObjectOwnerFromVersion(version, bucket, normalizedObjectKey),
|
||||
StorageClass: "STANDARD",
|
||||
}
|
||||
*allVersions = append(*allVersions, versionEntry)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This is a regular directory - check if it's an explicit S3 directory object
|
||||
// Only include directories that were explicitly created via S3 API (have FolderMimeType)
|
||||
// This excludes implicit directories created when uploading files like "test1/a"
|
||||
if entry.Attributes.Mime == s3_constants.FolderMimeType {
|
||||
directoryKey := entryPath
|
||||
if !strings.HasSuffix(directoryKey, "/") {
|
||||
directoryKey += "/"
|
||||
}
|
||||
|
||||
// Add directory as a version entry with VersionId "null" (following S3/Minio behavior)
|
||||
glog.V(2).Infof("findVersionsRecursively: found explicit S3 directory %s", directoryKey)
|
||||
|
||||
// Calculate ETag for empty directory
|
||||
directoryETag := "\"d41d8cd98f00b204e9800998ecf8427e\""
|
||||
|
||||
versionEntry := &VersionEntry{
|
||||
Key: normalizedObjectKey, // Use normalized key for consistency
|
||||
VersionId: version.VersionId,
|
||||
IsLatest: version.IsLatest,
|
||||
LastModified: version.LastModified,
|
||||
ETag: version.ETag,
|
||||
Size: version.Size,
|
||||
Owner: s3a.getObjectOwnerFromVersion(version, bucket, normalizedObjectKey),
|
||||
Key: directoryKey,
|
||||
VersionId: "null",
|
||||
IsLatest: true,
|
||||
LastModified: time.Unix(entry.Attributes.Mtime, 0),
|
||||
ETag: directoryETag,
|
||||
Size: 0, // Directories have size 0
|
||||
Owner: s3a.getObjectOwnerFromEntry(entry),
|
||||
StorageClass: "STANDARD",
|
||||
}
|
||||
*allVersions = append(*allVersions, versionEntry)
|
||||
}
|
||||
|
||||
// Recursively search subdirectories (regardless of whether they're explicit or implicit)
|
||||
fullPath := path.Join(currentPath, entry.Name)
|
||||
err := s3a.findVersionsRecursively(fullPath, entryPath, allVersions, processedObjects, seenVersionIds, bucket, prefix)
|
||||
if err != nil {
|
||||
glog.Warningf("Error searching subdirectory %s: %v", entryPath, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This is a regular directory - check if it's an explicit S3 directory object
|
||||
// Only include directories that were explicitly created via S3 API (have FolderMimeType)
|
||||
// This excludes implicit directories created when uploading files like "test1/a"
|
||||
if entry.Attributes.Mime == s3_constants.FolderMimeType {
|
||||
directoryKey := entryPath
|
||||
if !strings.HasSuffix(directoryKey, "/") {
|
||||
directoryKey += "/"
|
||||
}
|
||||
// This is a regular file - check if it's a pre-versioning object
|
||||
objectKey := entryPath
|
||||
|
||||
// Add directory as a version entry with VersionId "null" (following S3/Minio behavior)
|
||||
glog.V(2).Infof("findVersionsRecursively: found explicit S3 directory %s", directoryKey)
|
||||
// Normalize object key to ensure consistency with other version operations
|
||||
normalizedObjectKey := removeDuplicateSlashes(objectKey)
|
||||
|
||||
// Calculate ETag for empty directory
|
||||
directoryETag := "\"d41d8cd98f00b204e9800998ecf8427e\""
|
||||
|
||||
versionEntry := &VersionEntry{
|
||||
Key: directoryKey,
|
||||
VersionId: "null",
|
||||
IsLatest: true,
|
||||
LastModified: time.Unix(entry.Attributes.Mtime, 0),
|
||||
ETag: directoryETag,
|
||||
Size: 0, // Directories have size 0
|
||||
Owner: s3a.getObjectOwnerFromEntry(entry),
|
||||
StorageClass: "STANDARD",
|
||||
}
|
||||
*allVersions = append(*allVersions, versionEntry)
|
||||
}
|
||||
|
||||
// Recursively search subdirectories (regardless of whether they're explicit or implicit)
|
||||
fullPath := path.Join(currentPath, entry.Name)
|
||||
err := s3a.findVersionsRecursively(fullPath, entryPath, allVersions, processedObjects, seenVersionIds, bucket, prefix)
|
||||
if err != nil {
|
||||
glog.Warningf("Error searching subdirectory %s: %v", entryPath, err)
|
||||
// Skip if this object already has a .versions directory (already processed)
|
||||
// Check both normalized and original keys for backward compatibility
|
||||
if processedObjects[objectKey] || processedObjects[normalizedObjectKey] {
|
||||
glog.V(4).Infof("Skipping already processed object: objectKey=%s, normalizedObjectKey=%s, processedObjects[objectKey]=%v, processedObjects[normalizedObjectKey]=%v",
|
||||
objectKey, normalizedObjectKey, processedObjects[objectKey], processedObjects[normalizedObjectKey])
|
||||
continue
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This is a regular file - check if it's a pre-versioning object
|
||||
objectKey := entryPath
|
||||
|
||||
// Normalize object key to ensure consistency with other version operations
|
||||
normalizedObjectKey := removeDuplicateSlashes(objectKey)
|
||||
glog.V(4).Infof("Processing regular file: objectKey=%s, normalizedObjectKey=%s, NOT in processedObjects", objectKey, normalizedObjectKey)
|
||||
|
||||
// Skip if this object already has a .versions directory (already processed)
|
||||
// Check both normalized and original keys for backward compatibility
|
||||
if processedObjects[objectKey] || processedObjects[normalizedObjectKey] {
|
||||
glog.V(4).Infof("Skipping already processed object: objectKey=%s, normalizedObjectKey=%s, processedObjects[objectKey]=%v, processedObjects[normalizedObjectKey]=%v",
|
||||
objectKey, normalizedObjectKey, processedObjects[objectKey], processedObjects[normalizedObjectKey])
|
||||
continue
|
||||
}
|
||||
|
||||
glog.V(4).Infof("Processing regular file: objectKey=%s, normalizedObjectKey=%s, NOT in processedObjects", objectKey, normalizedObjectKey)
|
||||
|
||||
// This is a pre-versioning or suspended-versioning object
|
||||
// Check if this file has version metadata (ExtVersionIdKey)
|
||||
hasVersionMeta := false
|
||||
if entry.Extended != nil {
|
||||
if versionIdBytes, ok := entry.Extended[s3_constants.ExtVersionIdKey]; ok {
|
||||
hasVersionMeta = true
|
||||
glog.V(4).Infof("Regular file %s has version metadata: %s", normalizedObjectKey, string(versionIdBytes))
|
||||
// This is a pre-versioning or suspended-versioning object
|
||||
// Check if this file has version metadata (ExtVersionIdKey)
|
||||
hasVersionMeta := false
|
||||
if entry.Extended != nil {
|
||||
if versionIdBytes, ok := entry.Extended[s3_constants.ExtVersionIdKey]; ok {
|
||||
hasVersionMeta = true
|
||||
glog.V(4).Infof("Regular file %s has version metadata: %s", normalizedObjectKey, string(versionIdBytes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if a .versions directory exists for this object
|
||||
versionsObjectPath := normalizedObjectKey + s3_constants.VersionsFolder
|
||||
_, versionsErr := s3a.getEntry(currentPath, versionsObjectPath)
|
||||
if versionsErr == nil {
|
||||
// .versions directory exists
|
||||
glog.V(4).Infof("Found .versions directory for regular file %s, hasVersionMeta=%v", normalizedObjectKey, hasVersionMeta)
|
||||
// Check if a .versions directory exists for this object
|
||||
// Use entry.Name (relative to currentPath) to avoid duplicating subdirectory segments
|
||||
versionsEntryName := entry.Name + s3_constants.VersionsFolder
|
||||
_, versionsErr := s3a.getEntry(currentPath, versionsEntryName)
|
||||
if versionsErr == nil {
|
||||
// .versions directory exists
|
||||
glog.V(4).Infof("Found .versions directory for regular file %s, hasVersionMeta=%v", normalizedObjectKey, hasVersionMeta)
|
||||
|
||||
// If this file has version metadata, it's a suspended versioning null version
|
||||
// Include it and it will be the latest
|
||||
if hasVersionMeta {
|
||||
glog.V(4).Infof("Including suspended versioning file %s (has version metadata)", normalizedObjectKey)
|
||||
// Continue to add it below
|
||||
} else {
|
||||
// No version metadata - this is a pre-versioning file
|
||||
// Skip it if there's already a null version in .versions
|
||||
versions, err := s3a.getObjectVersionList(bucket, normalizedObjectKey)
|
||||
if err == nil {
|
||||
hasNullVersion := false
|
||||
for _, v := range versions {
|
||||
if v.VersionId == "null" {
|
||||
hasNullVersion = true
|
||||
break
|
||||
// If this file has version metadata, it's a suspended versioning null version
|
||||
// Include it and it will be the latest
|
||||
if hasVersionMeta {
|
||||
glog.V(4).Infof("Including suspended versioning file %s (has version metadata)", normalizedObjectKey)
|
||||
// Continue to add it below
|
||||
} else {
|
||||
// No version metadata - this is a pre-versioning file
|
||||
// Skip it if there's already a null version in .versions
|
||||
versions, err := s3a.getObjectVersionList(bucket, normalizedObjectKey)
|
||||
if err == nil {
|
||||
hasNullVersion := false
|
||||
for _, v := range versions {
|
||||
if v.VersionId == "null" {
|
||||
hasNullVersion = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasNullVersion {
|
||||
glog.V(4).Infof("Skipping pre-versioning file %s, null version exists in .versions", normalizedObjectKey)
|
||||
processedObjects[objectKey] = true
|
||||
processedObjects[normalizedObjectKey] = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
if hasNullVersion {
|
||||
glog.V(4).Infof("Skipping pre-versioning file %s, null version exists in .versions", normalizedObjectKey)
|
||||
processedObjects[objectKey] = true
|
||||
processedObjects[normalizedObjectKey] = true
|
||||
continue
|
||||
}
|
||||
glog.V(4).Infof("Including pre-versioning file %s (no null version in .versions)", normalizedObjectKey)
|
||||
}
|
||||
glog.V(4).Infof("Including pre-versioning file %s (no null version in .versions)", normalizedObjectKey)
|
||||
} else {
|
||||
glog.V(4).Infof("No .versions directory for regular file %s, hasVersionMeta=%v", normalizedObjectKey, hasVersionMeta)
|
||||
}
|
||||
} else {
|
||||
glog.V(4).Infof("No .versions directory for regular file %s, hasVersionMeta=%v", normalizedObjectKey, hasVersionMeta)
|
||||
|
||||
// Add this file as a null version with IsLatest=true
|
||||
isLatest := true
|
||||
|
||||
// Check for duplicate version IDs and skip if already seen
|
||||
// Use normalized key for deduplication to match how other version operations work
|
||||
versionKey := normalizedObjectKey + ":null"
|
||||
if seenVersionIds[versionKey] {
|
||||
glog.Warningf("findVersionsRecursively: duplicate null version for object %s detected (versionKey=%s), skipping", normalizedObjectKey, versionKey)
|
||||
continue
|
||||
}
|
||||
seenVersionIds[versionKey] = true
|
||||
|
||||
etag := s3a.calculateETagFromChunks(entry.Chunks)
|
||||
|
||||
glog.V(4).Infof("Adding null version from regular file: objectKey=%s, normalizedObjectKey=%s, versionKey=%s, isLatest=%v, hasVersionMeta=%v",
|
||||
objectKey, normalizedObjectKey, versionKey, isLatest, hasVersionMeta)
|
||||
|
||||
versionEntry := &VersionEntry{
|
||||
Key: normalizedObjectKey, // Use normalized key for consistency
|
||||
VersionId: "null",
|
||||
IsLatest: isLatest,
|
||||
LastModified: time.Unix(entry.Attributes.Mtime, 0),
|
||||
ETag: etag,
|
||||
Size: int64(entry.Attributes.FileSize),
|
||||
Owner: s3a.getObjectOwnerFromEntry(entry),
|
||||
StorageClass: "STANDARD",
|
||||
}
|
||||
*allVersions = append(*allVersions, versionEntry)
|
||||
}
|
||||
}
|
||||
|
||||
// Add this file as a null version with IsLatest=true
|
||||
isLatest := true
|
||||
|
||||
// Check for duplicate version IDs and skip if already seen
|
||||
// Use normalized key for deduplication to match how other version operations work
|
||||
versionKey := normalizedObjectKey + ":null"
|
||||
if seenVersionIds[versionKey] {
|
||||
glog.Warningf("findVersionsRecursively: duplicate null version for object %s detected (versionKey=%s), skipping", normalizedObjectKey, versionKey)
|
||||
continue
|
||||
}
|
||||
seenVersionIds[versionKey] = true
|
||||
|
||||
etag := s3a.calculateETagFromChunks(entry.Chunks)
|
||||
|
||||
glog.V(4).Infof("Adding null version from regular file: objectKey=%s, normalizedObjectKey=%s, versionKey=%s, isLatest=%v, hasVersionMeta=%v",
|
||||
objectKey, normalizedObjectKey, versionKey, isLatest, hasVersionMeta)
|
||||
|
||||
versionEntry := &VersionEntry{
|
||||
Key: normalizedObjectKey, // Use normalized key for consistency
|
||||
VersionId: "null",
|
||||
IsLatest: isLatest,
|
||||
LastModified: time.Unix(entry.Attributes.Mtime, 0),
|
||||
ETag: etag,
|
||||
Size: int64(entry.Attributes.FileSize),
|
||||
Owner: s3a.getObjectOwnerFromEntry(entry),
|
||||
StorageClass: "STANDARD",
|
||||
}
|
||||
*allVersions = append(*allVersions, versionEntry)
|
||||
// If we've reached the last page, stop pagination
|
||||
if isLast {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestVersionedObjectListingPathConstruction tests that versioned objects are listed with correct paths.
|
||||
// This is an integration test that validates the fix for GitHub discussion #7573.
|
||||
//
|
||||
// Issue: When using Velero with Kopia and S3 bucket versioning enabled, list operations were
|
||||
// returning doubled paths like "kopia/logpaste/kopia/logpaste/file" instead of "kopia/logpaste/file".
|
||||
// This caused Kopia to fail with "unable to load pack indexes despite 10 retries".
|
||||
//
|
||||
// Root cause: getLatestVersionEntryForListOperation was setting entry.Name to the full object path
|
||||
// instead of just the base filename. When eachEntryFn combined dir + entry.Name, paths got doubled.
|
||||
//
|
||||
// Fix: Use path.Base(object) to extract only the filename portion.
|
||||
func TestVersionedObjectListingPathConstruction(t *testing.T) {
|
||||
// Test that getLatestVersionEntryForListOperation creates entries with correct Name field
|
||||
t.Run("entry name should be base filename for versioned objects", func(t *testing.T) {
|
||||
// Simulate the fix: when creating logical entries for versioned object listing,
|
||||
// we use path.Base(object) instead of the full path
|
||||
testCases := []struct {
|
||||
name string
|
||||
objectPath string
|
||||
expectedName string
|
||||
dir string
|
||||
bucketPrefix string
|
||||
expectedKey string
|
||||
}{
|
||||
{
|
||||
name: "kopia file in nested directory",
|
||||
objectPath: "kopia/logpaste/kopia.blobcfg",
|
||||
expectedName: "kopia.blobcfg",
|
||||
dir: "/buckets/velero/kopia/logpaste",
|
||||
bucketPrefix: "/buckets/velero/",
|
||||
expectedKey: "kopia/logpaste/kopia.blobcfg",
|
||||
},
|
||||
{
|
||||
name: "kopia repository file",
|
||||
objectPath: "kopia/logpaste/kopia.repository",
|
||||
expectedName: "kopia.repository",
|
||||
dir: "/buckets/velero/kopia/logpaste",
|
||||
bucketPrefix: "/buckets/velero/",
|
||||
expectedKey: "kopia/logpaste/kopia.repository",
|
||||
},
|
||||
{
|
||||
name: "backup file in nested directory",
|
||||
objectPath: "backups/test1/velero-backup.json",
|
||||
expectedName: "velero-backup.json",
|
||||
dir: "/buckets/velero/backups/test1",
|
||||
bucketPrefix: "/buckets/velero/",
|
||||
expectedKey: "backups/test1/velero-backup.json",
|
||||
},
|
||||
{
|
||||
name: "file at bucket root",
|
||||
objectPath: "file.txt",
|
||||
expectedName: "file.txt",
|
||||
dir: "/buckets/velero",
|
||||
bucketPrefix: "/buckets/velero/",
|
||||
expectedKey: "file.txt",
|
||||
},
|
||||
{
|
||||
name: "deeply nested file",
|
||||
objectPath: "a/b/c/d/e/file.json",
|
||||
expectedName: "file.json",
|
||||
dir: "/buckets/velero/a/b/c/d/e",
|
||||
bucketPrefix: "/buckets/velero/",
|
||||
expectedKey: "a/b/c/d/e/file.json",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Simulate what the fix does: use path.Base to get just the filename
|
||||
entryName := path.Base(tc.objectPath)
|
||||
assert.Equal(t, tc.expectedName, entryName, "entry.Name should be base filename only")
|
||||
|
||||
// Verify that combining dir + entry.Name produces correct key
|
||||
// This is what eachEntryFn does in the list operation
|
||||
key := (tc.dir + "/" + entryName)[len(tc.bucketPrefix):]
|
||||
assert.Equal(t, tc.expectedKey, key, "final key should not have doubled paths")
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("verify path doubling bug is fixed", func(t *testing.T) {
|
||||
// This test demonstrates the exact bug that was fixed
|
||||
objectPath := "kopia/logpaste/kopia.blobcfg"
|
||||
dir := "/buckets/velero/kopia/logpaste"
|
||||
bucketPrefix := "/buckets/velero/"
|
||||
|
||||
// WRONG behavior (before fix): entry.Name = full path
|
||||
wrongEntryName := objectPath
|
||||
wrongKey := (dir + "/" + wrongEntryName)[len(bucketPrefix):]
|
||||
assert.Equal(t, "kopia/logpaste/kopia/logpaste/kopia.blobcfg", wrongKey,
|
||||
"bug: using full path as entry.Name causes path doubling")
|
||||
|
||||
// CORRECT behavior (after fix): entry.Name = base filename only
|
||||
correctEntryName := path.Base(objectPath)
|
||||
correctKey := (dir + "/" + correctEntryName)[len(bucketPrefix):]
|
||||
assert.Equal(t, "kopia/logpaste/kopia.blobcfg", correctKey,
|
||||
"fix: using path.Base for entry.Name produces correct path")
|
||||
})
|
||||
}
|
||||
|
||||
// TestVersionedEntryCreation tests that versioned entries are created correctly
|
||||
// with all necessary metadata for list operations.
|
||||
func TestVersionedEntryCreation(t *testing.T) {
|
||||
t.Run("logical entry should have correct attributes", func(t *testing.T) {
|
||||
// Simulate creating a logical entry for a versioned object
|
||||
objectPath := "kopia/logpaste/kopia.repository"
|
||||
|
||||
// Create a mock versioned entry (as would be returned from .versions directory)
|
||||
mockVersionedEntry := &filer_pb.Entry{
|
||||
Name: "v_1880a8e61c70fd480b47df7f530b796b", // Version file name
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: 1234567890,
|
||||
FileSize: 1024,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte("1880a8e61c70fd480b47df7f530b796b"),
|
||||
s3_constants.ExtETagKey: []byte("\"abc123\""),
|
||||
},
|
||||
}
|
||||
|
||||
// Simulate what getLatestVersionEntryForListOperation does with the fix
|
||||
logicalEntry := &filer_pb.Entry{
|
||||
Name: path.Base(objectPath), // This is the fix!
|
||||
IsDirectory: false,
|
||||
Attributes: mockVersionedEntry.Attributes,
|
||||
Extended: mockVersionedEntry.Extended,
|
||||
Chunks: mockVersionedEntry.Chunks,
|
||||
}
|
||||
|
||||
// Verify the logical entry has the correct name
|
||||
assert.Equal(t, "kopia.repository", logicalEntry.Name,
|
||||
"logical entry should have base filename as Name")
|
||||
assert.False(t, logicalEntry.IsDirectory,
|
||||
"logical entry should not be a directory")
|
||||
assert.NotNil(t, logicalEntry.Extended,
|
||||
"logical entry should preserve extended attributes")
|
||||
})
|
||||
}
|
||||
|
||||
// TestVersionsFolderPathHandling tests that .versions folder paths are handled correctly
|
||||
func TestVersionsFolderPathHandling(t *testing.T) {
|
||||
t.Run("versions folder suffix handling", func(t *testing.T) {
|
||||
testCases := []struct {
|
||||
versionsDir string
|
||||
expectedObject string
|
||||
}{
|
||||
{
|
||||
versionsDir: "kopia.blobcfg.versions",
|
||||
expectedObject: "kopia.blobcfg",
|
||||
},
|
||||
{
|
||||
versionsDir: "kopia.repository.versions",
|
||||
expectedObject: "kopia.repository",
|
||||
},
|
||||
{
|
||||
versionsDir: "file.txt.versions",
|
||||
expectedObject: "file.txt",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.versionsDir, func(t *testing.T) {
|
||||
// This is what the list handler does to extract object name
|
||||
baseObjectName := tc.versionsDir[:len(tc.versionsDir)-len(s3_constants.VersionsFolder)]
|
||||
assert.Equal(t, tc.expectedObject, baseObjectName,
|
||||
"object name should be correctly extracted from versions directory")
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,8 +173,11 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption)
|
||||
}
|
||||
})
|
||||
fs.filer.Cipher = option.Cipher
|
||||
whiteList := util.StringSplit(v.GetString("guard.white_list"), ",")
|
||||
fs.filerGuard = security.NewGuard(whiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
|
||||
// we do not support IP whitelist right now https://github.com/seaweedfs/seaweedfs/issues/7094
|
||||
if v.GetString("guard.white_list") != "" {
|
||||
glog.Warningf("filer: guard.white_list is configured but the IP whitelist feature is currently disabled. See https://github.com/seaweedfs/seaweedfs/issues/7094")
|
||||
}
|
||||
fs.filerGuard = security.NewGuard([]string{}, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
|
||||
fs.volumeGuard = security.NewGuard([]string{}, volumeSigningKey, volumeExpiresAfterSec, volumeReadSigningKey, volumeReadExpiresAfterSec)
|
||||
|
||||
fs.checkWithMaster()
|
||||
@@ -254,6 +257,4 @@ func (fs *FilerServer) Reload() {
|
||||
glog.V(0).Infoln("Reload filer server...")
|
||||
|
||||
util.LoadConfiguration("security", false)
|
||||
v := util.GetViper()
|
||||
fs.filerGuard.UpdateWhiteList(util.StringSplit(v.GetString("guard.white_list"), ","))
|
||||
}
|
||||
@@ -254,8 +254,10 @@ func (fs *FilerServer) detectStorageOption(ctx context.Context, requestURI, qCol
|
||||
return nil, ErrReadOnly
|
||||
}
|
||||
|
||||
if rule.MaxFileNameLength == 0 {
|
||||
rule.MaxFileNameLength = fs.filer.MaxFilenameLength
|
||||
// Use local variable instead of mutating shared rule
|
||||
maxFileNameLength := rule.MaxFileNameLength
|
||||
if maxFileNameLength == 0 {
|
||||
maxFileNameLength = fs.filer.MaxFilenameLength
|
||||
}
|
||||
|
||||
// required by buckets folder
|
||||
@@ -282,7 +284,7 @@ func (fs *FilerServer) detectStorageOption(ctx context.Context, requestURI, qCol
|
||||
DiskType: util.Nvl(diskType, rule.DiskType),
|
||||
Fsync: rule.Fsync,
|
||||
VolumeGrowthCount: rule.VolumeGrowthCount,
|
||||
MaxFileNameLength: rule.MaxFileNameLength,
|
||||
MaxFileNameLength: maxFileNameLength,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -284,15 +284,30 @@ func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServ
|
||||
}
|
||||
ms.deleteClient(clientName)
|
||||
}()
|
||||
for i, message := range ms.Topo.ToVolumeLocations() {
|
||||
if i == 0 {
|
||||
if leader, err := ms.Topo.Leader(); err == nil {
|
||||
message.Leader = string(leader)
|
||||
}
|
||||
}
|
||||
if sendErr := stream.Send(&master_pb.KeepConnectedResponse{VolumeLocation: message}); sendErr != nil {
|
||||
|
||||
// Send volume locations to the client
|
||||
volumeLocations := ms.Topo.ToVolumeLocations()
|
||||
if len(volumeLocations) == 0 {
|
||||
// Always send at least one message with leader info so the client can unblock
|
||||
leader, _ := ms.Topo.Leader()
|
||||
if sendErr := stream.Send(&master_pb.KeepConnectedResponse{
|
||||
VolumeLocation: &master_pb.VolumeLocation{
|
||||
Leader: string(leader),
|
||||
},
|
||||
}); sendErr != nil {
|
||||
return sendErr
|
||||
}
|
||||
} else {
|
||||
for i, message := range volumeLocations {
|
||||
if i == 0 {
|
||||
if leader, err := ms.Topo.Leader(); err == nil {
|
||||
message.Leader = string(leader)
|
||||
}
|
||||
}
|
||||
if sendErr := stream.Send(&master_pb.KeepConnectedResponse{VolumeLocation: message}); sendErr != nil {
|
||||
return sendErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
|
||||
"io"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Commands = append(Commands, &commandClusterStatus{})
|
||||
}
|
||||
|
||||
type commandClusterStatus struct{}
|
||||
type ClusterStatusPrinter struct {
|
||||
writer io.Writer
|
||||
|
||||
locked bool
|
||||
collections []string
|
||||
topology *master_pb.TopologyInfo
|
||||
volumeSizeLimitMb uint64
|
||||
}
|
||||
|
||||
func (c *commandClusterStatus) Name() string {
|
||||
return "cluster.status"
|
||||
}
|
||||
|
||||
func (c *commandClusterStatus) Help() string {
|
||||
return `outputs a quick overview of the cluster status`
|
||||
}
|
||||
|
||||
func (c *commandClusterStatus) HasTag(CommandTag) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *commandClusterStatus) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
|
||||
flags := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
|
||||
if err = flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collections, err := ListCollectionNames(commandEnv, true, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
topology, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sp := &ClusterStatusPrinter{
|
||||
writer: writer,
|
||||
|
||||
locked: commandEnv.isLocked(),
|
||||
collections: collections,
|
||||
topology: topology,
|
||||
volumeSizeLimitMb: volumeSizeLimitMb,
|
||||
}
|
||||
sp.Print()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO: humanize figures in output
|
||||
// TODO: add option to collect detailed file stats
|
||||
func (sp *ClusterStatusPrinter) Print() {
|
||||
sp.write("")
|
||||
sp.printClusterInfo()
|
||||
sp.printVolumeInfo()
|
||||
sp.printStorageInfo()
|
||||
}
|
||||
|
||||
func (sp *ClusterStatusPrinter) write(format string, a ...any) {
|
||||
fmt.Fprintf(sp.writer, strings.TrimRight(format, "\r\n "), a...)
|
||||
fmt.Fprint(sp.writer, "\n")
|
||||
}
|
||||
|
||||
func (sp *ClusterStatusPrinter) printClusterInfo() {
|
||||
dcs := len(sp.topology.DataCenterInfos)
|
||||
|
||||
racks := 0
|
||||
nodes := 0
|
||||
disks := 0
|
||||
for _, dci := range sp.topology.DataCenterInfos {
|
||||
racks += len(dci.RackInfos)
|
||||
for _, ri := range dci.RackInfos {
|
||||
for _, dni := range ri.DataNodeInfos {
|
||||
nodes++
|
||||
disks += len(dni.DiskInfos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
status := "unlocked"
|
||||
if sp.locked {
|
||||
status = "LOCKED"
|
||||
}
|
||||
|
||||
sp.write("cluster:")
|
||||
sp.write("\tid: %s", sp.topology.Id)
|
||||
sp.write("\tstatus: %s", status)
|
||||
sp.write("\tnodes: %d", nodes)
|
||||
sp.write("\ttopology: %d DC(s), %d disk(s) on %d rack(s)", dcs, disks, racks)
|
||||
sp.write("")
|
||||
}
|
||||
|
||||
func (sp *ClusterStatusPrinter) printVolumeInfo() {
|
||||
collections := len(sp.collections)
|
||||
var maxVolumes uint64
|
||||
volumes := map[needle.VolumeId]bool{}
|
||||
ecVolumes := map[needle.VolumeId]bool{}
|
||||
|
||||
var replicas, roReplicas, rwReplicas, ecShards uint64
|
||||
|
||||
for _, dci := range sp.topology.DataCenterInfos {
|
||||
for _, ri := range dci.RackInfos {
|
||||
for _, dni := range ri.DataNodeInfos {
|
||||
for _, di := range dni.DiskInfos {
|
||||
maxVolumes += uint64(di.MaxVolumeCount)
|
||||
for _, vi := range di.VolumeInfos {
|
||||
vid := needle.VolumeId(vi.Id)
|
||||
volumes[vid] = true
|
||||
replicas++
|
||||
if vi.ReadOnly {
|
||||
roReplicas++
|
||||
} else {
|
||||
rwReplicas++
|
||||
}
|
||||
}
|
||||
for _, eci := range di.EcShardInfos {
|
||||
vid := needle.VolumeId(eci.Id)
|
||||
ecVolumes[vid] = true
|
||||
ecShards += uint64(erasure_coding.ShardBits(eci.EcIndexBits).ShardIdCount())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var roReplicasRatio, rwReplicasRatio, ecShardsPerVolume float64
|
||||
if replicas != 0 {
|
||||
roReplicasRatio = float64(roReplicas) / float64(replicas)
|
||||
rwReplicasRatio = float64(rwReplicas) / float64(replicas)
|
||||
}
|
||||
if len(ecVolumes) != 0 {
|
||||
ecShardsPerVolume = float64(ecShards) / float64(len(ecVolumes))
|
||||
}
|
||||
|
||||
totalVolumes := len(volumes) + len(ecVolumes)
|
||||
|
||||
sp.write("volumes:")
|
||||
sp.write("\ttotal: %d volumes on %d collections", totalVolumes, collections)
|
||||
sp.write("\tmax size: %d bytes", sp.volumeSizeLimitMb*1024*1024)
|
||||
sp.write("\tregular: %d/%d volumes on %d replicas, %d writable (%.02f%%), %d read-only (%.02f%%)", len(volumes), maxVolumes, replicas, rwReplicas, 100*rwReplicasRatio, roReplicas, 100*roReplicasRatio)
|
||||
sp.write("\tEC: %d EC volumes on %d shards (%.02f shards/volume)", len(ecVolumes), ecShards, ecShardsPerVolume)
|
||||
sp.write("")
|
||||
}
|
||||
|
||||
func (sp *ClusterStatusPrinter) printStorageInfo() {
|
||||
perVolumeSize := map[needle.VolumeId]uint64{}
|
||||
perEcVolumeSize := map[needle.VolumeId]uint64{}
|
||||
var rawVolumeSize, rawEcVolumeSize uint64
|
||||
|
||||
for _, dci := range sp.topology.DataCenterInfos {
|
||||
for _, ri := range dci.RackInfos {
|
||||
for _, dni := range ri.DataNodeInfos {
|
||||
for _, di := range dni.DiskInfos {
|
||||
for _, vi := range di.VolumeInfos {
|
||||
vid := needle.VolumeId(vi.Id)
|
||||
perVolumeSize[vid] = vi.Size
|
||||
rawVolumeSize += vi.Size
|
||||
}
|
||||
for _, eci := range di.EcShardInfos {
|
||||
vid := needle.VolumeId(eci.Id)
|
||||
var size uint64
|
||||
for _, ss := range eci.ShardSizes {
|
||||
size += uint64(ss)
|
||||
}
|
||||
perEcVolumeSize[vid] += size
|
||||
rawEcVolumeSize += size
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// normalize EC logical volume sizes given shard settings
|
||||
for vid := range perEcVolumeSize {
|
||||
perEcVolumeSize[vid] = perEcVolumeSize[vid] * erasure_coding.DataShardsCount / erasure_coding.TotalShardsCount
|
||||
}
|
||||
|
||||
var volumeSize, ecVolumeSize uint64
|
||||
for _, s := range perVolumeSize {
|
||||
volumeSize += s
|
||||
}
|
||||
for _, s := range perEcVolumeSize {
|
||||
ecVolumeSize += s
|
||||
}
|
||||
|
||||
totalSize := volumeSize + ecVolumeSize
|
||||
|
||||
sp.write("storage:")
|
||||
sp.write("\ttotal: %d bytes", totalSize)
|
||||
sp.write("\tregular volumes: %d bytes", volumeSize)
|
||||
sp.write("\tEC volumes: %d bytes", ecVolumeSize)
|
||||
sp.write("\traw: %d bytes on volume replicas, %d bytes on EC shard files", rawVolumeSize, rawEcVolumeSize)
|
||||
sp.write("")
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -20,7 +22,10 @@ func (c *commandEcBalance) Name() string {
|
||||
func (c *commandEcBalance) Help() string {
|
||||
return `balance all ec shards among all racks and volume servers
|
||||
|
||||
ec.balance [-c EACH_COLLECTION|<collection_name>] [-apply] [-dataCenter <data_center>] [-shardReplicaPlacement <replica_placement>]
|
||||
ec.balance [-c EACH_COLLECTION|<collection_name>] [-apply] [-dataCenter <data_center>] [-shardReplicaPlacement <replica_placement>] [-diskType <disk_type>]
|
||||
|
||||
Options:
|
||||
-diskType: the disk type for EC shards (hdd, ssd, or empty for default hdd)
|
||||
|
||||
Algorithm:
|
||||
` + ecBalanceAlgorithmDescription
|
||||
@@ -35,6 +40,7 @@ func (c *commandEcBalance) Do(args []string, commandEnv *CommandEnv, writer io.W
|
||||
collection := balanceCommand.String("collection", "EACH_COLLECTION", "collection name, or \"EACH_COLLECTION\" for each collection")
|
||||
dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
|
||||
shardReplicaPlacement := balanceCommand.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty")
|
||||
diskTypeStr := balanceCommand.String("diskType", "", "the disk type for EC shards (hdd, ssd, or empty for default hdd)")
|
||||
maxParallelization := balanceCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
|
||||
applyBalancing := balanceCommand.Bool("apply", false, "apply the balancing plan")
|
||||
// TODO: remove this alias
|
||||
@@ -67,5 +73,7 @@ func (c *commandEcBalance) Do(args []string, commandEnv *CommandEnv, writer io.W
|
||||
return err
|
||||
}
|
||||
|
||||
return EcBalance(commandEnv, collections, *dc, rp, *maxParallelization, *applyBalancing)
|
||||
diskType := types.ToDiskType(*diskTypeStr)
|
||||
|
||||
return EcBalance(commandEnv, collections, *dc, rp, diskType, *maxParallelization, *applyBalancing)
|
||||
}
|
||||
@@ -182,7 +182,7 @@ func collectTopologyInfo(commandEnv *CommandEnv, delayBeforeCollecting time.Dura
|
||||
|
||||
}
|
||||
|
||||
func collectEcNodesForDC(commandEnv *CommandEnv, selectedDataCenter string) (ecNodes []*EcNode, totalFreeEcSlots int, err error) {
|
||||
func collectEcNodesForDC(commandEnv *CommandEnv, selectedDataCenter string, diskType types.DiskType) (ecNodes []*EcNode, totalFreeEcSlots int, err error) {
|
||||
// list all possible locations
|
||||
// collect topology information
|
||||
topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
|
||||
@@ -191,15 +191,15 @@ func collectEcNodesForDC(commandEnv *CommandEnv, selectedDataCenter string) (ecN
|
||||
}
|
||||
|
||||
// find out all volume servers with one slot left.
|
||||
ecNodes, totalFreeEcSlots = collectEcVolumeServersByDc(topologyInfo, selectedDataCenter)
|
||||
ecNodes, totalFreeEcSlots = collectEcVolumeServersByDc(topologyInfo, selectedDataCenter, diskType)
|
||||
|
||||
sortEcNodesByFreeslotsDescending(ecNodes)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func collectEcNodes(commandEnv *CommandEnv) (ecNodes []*EcNode, totalFreeEcSlots int, err error) {
|
||||
return collectEcNodesForDC(commandEnv, "")
|
||||
func collectEcNodes(commandEnv *CommandEnv, diskType types.DiskType) (ecNodes []*EcNode, totalFreeEcSlots int, err error) {
|
||||
return collectEcNodesForDC(commandEnv, "", diskType)
|
||||
}
|
||||
|
||||
func collectCollectionsForVolumeIds(t *master_pb.TopologyInfo, vids []needle.VolumeId) []string {
|
||||
@@ -242,7 +242,7 @@ func collectCollectionsForVolumeIds(t *master_pb.TopologyInfo, vids []needle.Vol
|
||||
return collections
|
||||
}
|
||||
|
||||
func moveMountedShardToEcNode(commandEnv *CommandEnv, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, destinationEcNode *EcNode, destDiskId uint32, applyBalancing bool) (err error) {
|
||||
func moveMountedShardToEcNode(commandEnv *CommandEnv, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, destinationEcNode *EcNode, destDiskId uint32, applyBalancing bool, diskType types.DiskType) (err error) {
|
||||
|
||||
if !commandEnv.isLocked() {
|
||||
return fmt.Errorf("lock is lost")
|
||||
@@ -280,8 +280,8 @@ func moveMountedShardToEcNode(commandEnv *CommandEnv, existingLocation *EcNode,
|
||||
|
||||
}
|
||||
|
||||
destinationEcNode.addEcVolumeShards(vid, collection, copiedShardIds)
|
||||
existingLocation.deleteEcVolumeShards(vid, copiedShardIds)
|
||||
destinationEcNode.addEcVolumeShards(vid, collection, copiedShardIds, diskType)
|
||||
existingLocation.deleteEcVolumeShards(vid, copiedShardIds, diskType)
|
||||
|
||||
return nil
|
||||
|
||||
@@ -421,13 +421,13 @@ func (ecNode *EcNode) localShardIdCount(vid uint32) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func collectEcVolumeServersByDc(topo *master_pb.TopologyInfo, selectedDataCenter string) (ecNodes []*EcNode, totalFreeEcSlots int) {
|
||||
func collectEcVolumeServersByDc(topo *master_pb.TopologyInfo, selectedDataCenter string, diskType types.DiskType) (ecNodes []*EcNode, totalFreeEcSlots int) {
|
||||
eachDataNode(topo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
if selectedDataCenter != "" && selectedDataCenter != string(dc) {
|
||||
return
|
||||
}
|
||||
|
||||
freeEcSlots := countFreeShardSlots(dn, types.HardDriveType)
|
||||
freeEcSlots := countFreeShardSlots(dn, diskType)
|
||||
ecNode := &EcNode{
|
||||
info: dn,
|
||||
dc: dc,
|
||||
@@ -439,17 +439,17 @@ func collectEcVolumeServersByDc(topo *master_pb.TopologyInfo, selectedDataCenter
|
||||
// Build disk-level information from volumes and EC shards
|
||||
// First, discover all unique disk IDs from VolumeInfos (includes empty disks)
|
||||
allDiskIds := make(map[uint32]string) // diskId -> diskType
|
||||
for diskType, diskInfo := range dn.DiskInfos {
|
||||
for diskTypeKey, diskInfo := range dn.DiskInfos {
|
||||
if diskInfo == nil {
|
||||
continue
|
||||
}
|
||||
// Get all disk IDs from volumes
|
||||
for _, vi := range diskInfo.VolumeInfos {
|
||||
allDiskIds[vi.DiskId] = diskType
|
||||
allDiskIds[vi.DiskId] = diskTypeKey
|
||||
}
|
||||
// Also get disk IDs from EC shards
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
allDiskIds[ecShardInfo.DiskId] = diskType
|
||||
allDiskIds[ecShardInfo.DiskId] = diskTypeKey
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,7 +476,7 @@ func collectEcVolumeServersByDc(topo *master_pb.TopologyInfo, selectedDataCenter
|
||||
}
|
||||
freePerDisk := int(freeEcSlots) / diskCount
|
||||
|
||||
for diskId, diskType := range allDiskIds {
|
||||
for diskId, diskTypeStr := range allDiskIds {
|
||||
shards := diskShards[diskId]
|
||||
if shards == nil {
|
||||
shards = make(map[needle.VolumeId]erasure_coding.ShardBits)
|
||||
@@ -488,7 +488,7 @@ func collectEcVolumeServersByDc(topo *master_pb.TopologyInfo, selectedDataCenter
|
||||
|
||||
ecNode.disks[diskId] = &EcDisk{
|
||||
diskId: diskId,
|
||||
diskType: diskType,
|
||||
diskType: diskTypeStr,
|
||||
freeEcSlots: freePerDisk,
|
||||
ecShardCount: totalShardCount,
|
||||
ecShards: shards,
|
||||
@@ -551,9 +551,9 @@ func ceilDivide(a, b int) int {
|
||||
return (a / b) + r
|
||||
}
|
||||
|
||||
func findEcVolumeShards(ecNode *EcNode, vid needle.VolumeId) erasure_coding.ShardBits {
|
||||
func findEcVolumeShards(ecNode *EcNode, vid needle.VolumeId, diskType types.DiskType) erasure_coding.ShardBits {
|
||||
|
||||
if diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]; found {
|
||||
if diskInfo, found := ecNode.info.DiskInfos[string(diskType)]; found {
|
||||
for _, shardInfo := range diskInfo.EcShardInfos {
|
||||
if needle.VolumeId(shardInfo.Id) == vid {
|
||||
return erasure_coding.ShardBits(shardInfo.EcIndexBits)
|
||||
@@ -564,10 +564,10 @@ func findEcVolumeShards(ecNode *EcNode, vid needle.VolumeId) erasure_coding.Shar
|
||||
return 0
|
||||
}
|
||||
|
||||
func (ecNode *EcNode) addEcVolumeShards(vid needle.VolumeId, collection string, shardIds []uint32) *EcNode {
|
||||
func (ecNode *EcNode) addEcVolumeShards(vid needle.VolumeId, collection string, shardIds []uint32, diskType types.DiskType) *EcNode {
|
||||
|
||||
foundVolume := false
|
||||
diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
|
||||
diskInfo, found := ecNode.info.DiskInfos[string(diskType)]
|
||||
if found {
|
||||
for _, shardInfo := range diskInfo.EcShardInfos {
|
||||
if needle.VolumeId(shardInfo.Id) == vid {
|
||||
@@ -584,9 +584,9 @@ func (ecNode *EcNode) addEcVolumeShards(vid needle.VolumeId, collection string,
|
||||
}
|
||||
} else {
|
||||
diskInfo = &master_pb.DiskInfo{
|
||||
Type: string(types.HardDriveType),
|
||||
Type: string(diskType),
|
||||
}
|
||||
ecNode.info.DiskInfos[string(types.HardDriveType)] = diskInfo
|
||||
ecNode.info.DiskInfos[string(diskType)] = diskInfo
|
||||
}
|
||||
|
||||
if !foundVolume {
|
||||
@@ -598,7 +598,7 @@ func (ecNode *EcNode) addEcVolumeShards(vid needle.VolumeId, collection string,
|
||||
Id: uint32(vid),
|
||||
Collection: collection,
|
||||
EcIndexBits: uint32(newShardBits),
|
||||
DiskType: string(types.HardDriveType),
|
||||
DiskType: string(diskType),
|
||||
})
|
||||
ecNode.freeEcSlot -= len(shardIds)
|
||||
}
|
||||
@@ -606,9 +606,9 @@ func (ecNode *EcNode) addEcVolumeShards(vid needle.VolumeId, collection string,
|
||||
return ecNode
|
||||
}
|
||||
|
||||
func (ecNode *EcNode) deleteEcVolumeShards(vid needle.VolumeId, shardIds []uint32) *EcNode {
|
||||
func (ecNode *EcNode) deleteEcVolumeShards(vid needle.VolumeId, shardIds []uint32, diskType types.DiskType) *EcNode {
|
||||
|
||||
if diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]; found {
|
||||
if diskInfo, found := ecNode.info.DiskInfos[string(diskType)]; found {
|
||||
for _, shardInfo := range diskInfo.EcShardInfos {
|
||||
if needle.VolumeId(shardInfo.Id) == vid {
|
||||
oldShardBits := erasure_coding.ShardBits(shardInfo.EcIndexBits)
|
||||
@@ -649,6 +649,7 @@ type ecBalancer struct {
|
||||
replicaPlacement *super_block.ReplicaPlacement
|
||||
applyBalancing bool
|
||||
maxParallelization int
|
||||
diskType types.DiskType // target disk type for EC shards (default: HardDriveType)
|
||||
}
|
||||
|
||||
func (ecb *ecBalancer) errorWaitGroup() *ErrorWaitGroup {
|
||||
@@ -705,7 +706,7 @@ func (ecb *ecBalancer) doDeduplicateEcShards(collection string, vid needle.Volum
|
||||
// Use MaxShardCount (32) to support custom EC ratios
|
||||
shardToLocations := make([][]*EcNode, erasure_coding.MaxShardCount)
|
||||
for _, ecNode := range locations {
|
||||
shardBits := findEcVolumeShards(ecNode, vid)
|
||||
shardBits := findEcVolumeShards(ecNode, vid, ecb.diskType)
|
||||
for _, shardId := range shardBits.ShardIds() {
|
||||
shardToLocations[shardId] = append(shardToLocations[shardId], ecNode)
|
||||
}
|
||||
@@ -728,7 +729,7 @@ func (ecb *ecBalancer) doDeduplicateEcShards(collection string, vid needle.Volum
|
||||
if err := sourceServerDeleteEcShards(ecb.commandEnv.option.GrpcDialOption, collection, vid, pb.NewServerAddressFromDataNode(ecNode.info), duplicatedShardIds); err != nil {
|
||||
return err
|
||||
}
|
||||
ecNode.deleteEcVolumeShards(vid, duplicatedShardIds)
|
||||
ecNode.deleteEcVolumeShards(vid, duplicatedShardIds, ecb.diskType)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -748,9 +749,9 @@ func (ecb *ecBalancer) balanceEcShardsAcrossRacks(collection string) error {
|
||||
return ewg.Wait()
|
||||
}
|
||||
|
||||
func countShardsByRack(vid needle.VolumeId, locations []*EcNode) map[string]int {
|
||||
func countShardsByRack(vid needle.VolumeId, locations []*EcNode, diskType types.DiskType) map[string]int {
|
||||
return groupByCount(locations, func(ecNode *EcNode) (id string, count int) {
|
||||
shardBits := findEcVolumeShards(ecNode, vid)
|
||||
shardBits := findEcVolumeShards(ecNode, vid, diskType)
|
||||
return string(ecNode.rack), shardBits.ShardIdCount()
|
||||
})
|
||||
}
|
||||
@@ -759,7 +760,7 @@ func (ecb *ecBalancer) doBalanceEcShardsAcrossRacks(collection string, vid needl
|
||||
racks := ecb.racks()
|
||||
|
||||
// see the volume's shards are in how many racks, and how many in each rack
|
||||
rackToShardCount := countShardsByRack(vid, locations)
|
||||
rackToShardCount := countShardsByRack(vid, locations, ecb.diskType)
|
||||
|
||||
// Calculate actual total shards for this volume (not hardcoded default)
|
||||
var totalShardsForVolume int
|
||||
@@ -779,7 +780,7 @@ func (ecb *ecBalancer) doBalanceEcShardsAcrossRacks(collection string, vid needl
|
||||
continue
|
||||
}
|
||||
possibleEcNodes := rackEcNodesWithVid[rackId]
|
||||
for shardId, ecNode := range pickNEcShardsToMoveFrom(possibleEcNodes, vid, count-averageShardsPerEcRack) {
|
||||
for shardId, ecNode := range pickNEcShardsToMoveFrom(possibleEcNodes, vid, count-averageShardsPerEcRack, ecb.diskType) {
|
||||
ecShardsToMove[shardId] = ecNode
|
||||
}
|
||||
}
|
||||
@@ -856,7 +857,7 @@ func (ecb *ecBalancer) balanceEcShardsWithinRacks(collection string) error {
|
||||
for vid, locations := range vidLocations {
|
||||
|
||||
// see the volume's shards are in how many racks, and how many in each rack
|
||||
rackToShardCount := countShardsByRack(vid, locations)
|
||||
rackToShardCount := countShardsByRack(vid, locations, ecb.diskType)
|
||||
rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
|
||||
return string(ecNode.rack)
|
||||
})
|
||||
@@ -865,7 +866,7 @@ func (ecb *ecBalancer) balanceEcShardsWithinRacks(collection string) error {
|
||||
|
||||
var possibleDestinationEcNodes []*EcNode
|
||||
for _, n := range racks[RackId(rackId)].ecNodes {
|
||||
if _, found := n.info.DiskInfos[string(types.HardDriveType)]; found {
|
||||
if _, found := n.info.DiskInfos[string(ecb.diskType)]; found {
|
||||
possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
|
||||
}
|
||||
}
|
||||
@@ -882,7 +883,7 @@ func (ecb *ecBalancer) balanceEcShardsWithinRacks(collection string) error {
|
||||
func (ecb *ecBalancer) doBalanceEcShardsWithinOneRack(averageShardsPerEcNode int, collection string, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode) error {
|
||||
for _, ecNode := range existingLocations {
|
||||
|
||||
shardBits := findEcVolumeShards(ecNode, vid)
|
||||
shardBits := findEcVolumeShards(ecNode, vid, ecb.diskType)
|
||||
overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
|
||||
|
||||
for _, shardId := range shardBits.ShardIds() {
|
||||
@@ -927,7 +928,7 @@ func (ecb *ecBalancer) doBalanceEcRack(ecRack *EcRack) error {
|
||||
}
|
||||
|
||||
ecNodeIdToShardCount := groupByCount(rackEcNodes, func(ecNode *EcNode) (id string, count int) {
|
||||
diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
|
||||
diskInfo, found := ecNode.info.DiskInfos[string(ecb.diskType)]
|
||||
if !found {
|
||||
return
|
||||
}
|
||||
@@ -955,17 +956,18 @@ func (ecb *ecBalancer) doBalanceEcRack(ecRack *EcRack) error {
|
||||
if fullNodeShardCount > averageShardCount && emptyNodeShardCount+1 <= averageShardCount {
|
||||
|
||||
emptyNodeIds := make(map[uint32]bool)
|
||||
if emptyDiskInfo, found := emptyNode.info.DiskInfos[string(types.HardDriveType)]; found {
|
||||
if emptyDiskInfo, found := emptyNode.info.DiskInfos[string(ecb.diskType)]; found {
|
||||
for _, shards := range emptyDiskInfo.EcShardInfos {
|
||||
emptyNodeIds[shards.Id] = true
|
||||
}
|
||||
}
|
||||
if fullDiskInfo, found := fullNode.info.DiskInfos[string(types.HardDriveType)]; found {
|
||||
if fullDiskInfo, found := fullNode.info.DiskInfos[string(ecb.diskType)]; found {
|
||||
for _, shards := range fullDiskInfo.EcShardInfos {
|
||||
if _, found := emptyNodeIds[shards.Id]; !found {
|
||||
for _, shardId := range erasure_coding.ShardBits(shards.EcIndexBits).ShardIds() {
|
||||
vid := needle.VolumeId(shards.Id)
|
||||
destDiskId := pickBestDiskOnNode(emptyNode, vid)
|
||||
// For balancing, strictly require matching disk type
|
||||
destDiskId := pickBestDiskOnNode(emptyNode, vid, ecb.diskType, true)
|
||||
|
||||
if destDiskId > 0 {
|
||||
fmt.Printf("%s moves ec shards %d.%d to %s (disk %d)\n", fullNode.info.Id, shards.Id, shardId, emptyNode.info.Id, destDiskId)
|
||||
@@ -973,7 +975,7 @@ func (ecb *ecBalancer) doBalanceEcRack(ecRack *EcRack) error {
|
||||
fmt.Printf("%s moves ec shards %d.%d to %s\n", fullNode.info.Id, shards.Id, shardId, emptyNode.info.Id)
|
||||
}
|
||||
|
||||
err := moveMountedShardToEcNode(ecb.commandEnv, fullNode, shards.Collection, vid, shardId, emptyNode, destDiskId, ecb.applyBalancing)
|
||||
err := moveMountedShardToEcNode(ecb.commandEnv, fullNode, shards.Collection, vid, shardId, emptyNode, destDiskId, ecb.applyBalancing, ecb.diskType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1003,7 +1005,7 @@ func (ecb *ecBalancer) pickEcNodeToBalanceShardsInto(vid needle.VolumeId, existi
|
||||
|
||||
nodeShards := map[*EcNode]int{}
|
||||
for _, node := range possibleDestinations {
|
||||
nodeShards[node] = findEcVolumeShards(node, vid).ShardIdCount()
|
||||
nodeShards[node] = findEcVolumeShards(node, vid, ecb.diskType).ShardIdCount()
|
||||
}
|
||||
|
||||
targets := []*EcNode{}
|
||||
@@ -1078,14 +1080,17 @@ func diskDistributionScore(ecNode *EcNode, vid needle.VolumeId) int {
|
||||
}
|
||||
|
||||
// pickBestDiskOnNode selects the best disk on a node for placing a new EC shard
|
||||
// It prefers disks with fewer shards and more free slots
|
||||
func pickBestDiskOnNode(ecNode *EcNode, vid needle.VolumeId) uint32 {
|
||||
// It prefers disks of the specified type with fewer shards and more free slots
|
||||
// If strictDiskType is false, it will fall back to other disk types if no matching disk is found
|
||||
func pickBestDiskOnNode(ecNode *EcNode, vid needle.VolumeId, diskType types.DiskType, strictDiskType bool) uint32 {
|
||||
if len(ecNode.disks) == 0 {
|
||||
return 0 // No disk info available, let the server decide
|
||||
}
|
||||
|
||||
var bestDiskId uint32
|
||||
bestScore := -1
|
||||
var fallbackDiskId uint32
|
||||
fallbackScore := -1
|
||||
|
||||
for diskId, disk := range ecNode.disks {
|
||||
if disk.freeEcSlots <= 0 {
|
||||
@@ -1102,13 +1107,26 @@ func pickBestDiskOnNode(ecNode *EcNode, vid needle.VolumeId) uint32 {
|
||||
// Lower score is better
|
||||
score := disk.ecShardCount*10 + existingShards*100
|
||||
|
||||
if bestScore == -1 || score < bestScore {
|
||||
bestScore = score
|
||||
bestDiskId = diskId
|
||||
if disk.diskType == string(diskType) {
|
||||
// Matching disk type - this is preferred
|
||||
if bestScore == -1 || score < bestScore {
|
||||
bestScore = score
|
||||
bestDiskId = diskId
|
||||
}
|
||||
} else if !strictDiskType {
|
||||
// Non-matching disk type - use as fallback if allowed
|
||||
if fallbackScore == -1 || score < fallbackScore {
|
||||
fallbackScore = score
|
||||
fallbackDiskId = diskId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestDiskId
|
||||
// Return matching disk type if found, otherwise fallback
|
||||
if bestDiskId != 0 {
|
||||
return bestDiskId
|
||||
}
|
||||
return fallbackDiskId
|
||||
}
|
||||
|
||||
// pickEcNodeAndDiskToBalanceShardsInto picks both a destination node and specific disk
|
||||
@@ -1118,7 +1136,8 @@ func (ecb *ecBalancer) pickEcNodeAndDiskToBalanceShardsInto(vid needle.VolumeId,
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
diskId := pickBestDiskOnNode(node, vid)
|
||||
// For balancing, strictly require matching disk type
|
||||
diskId := pickBestDiskOnNode(node, vid, ecb.diskType, true)
|
||||
return node, diskId, nil
|
||||
}
|
||||
|
||||
@@ -1134,14 +1153,14 @@ func (ecb *ecBalancer) pickOneEcNodeAndMoveOneShard(existingLocation *EcNode, co
|
||||
} else {
|
||||
fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destNode.info.Id)
|
||||
}
|
||||
return moveMountedShardToEcNode(ecb.commandEnv, existingLocation, collection, vid, shardId, destNode, destDiskId, ecb.applyBalancing)
|
||||
return moveMountedShardToEcNode(ecb.commandEnv, existingLocation, collection, vid, shardId, destNode, destDiskId, ecb.applyBalancing, ecb.diskType)
|
||||
}
|
||||
|
||||
func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[erasure_coding.ShardId]*EcNode {
|
||||
func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int, diskType types.DiskType) map[erasure_coding.ShardId]*EcNode {
|
||||
picked := make(map[erasure_coding.ShardId]*EcNode)
|
||||
var candidateEcNodes []*CandidateEcNode
|
||||
for _, ecNode := range ecNodes {
|
||||
shardBits := findEcVolumeShards(ecNode, vid)
|
||||
shardBits := findEcVolumeShards(ecNode, vid, diskType)
|
||||
if shardBits.ShardIdCount() > 0 {
|
||||
candidateEcNodes = append(candidateEcNodes, &CandidateEcNode{
|
||||
ecNode: ecNode,
|
||||
@@ -1155,13 +1174,13 @@ func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[
|
||||
for i := 0; i < n; i++ {
|
||||
selectedEcNodeIndex := -1
|
||||
for i, candidateEcNode := range candidateEcNodes {
|
||||
shardBits := findEcVolumeShards(candidateEcNode.ecNode, vid)
|
||||
shardBits := findEcVolumeShards(candidateEcNode.ecNode, vid, diskType)
|
||||
if shardBits > 0 {
|
||||
selectedEcNodeIndex = i
|
||||
for _, shardId := range shardBits.ShardIds() {
|
||||
candidateEcNode.shardCount--
|
||||
picked[shardId] = candidateEcNode.ecNode
|
||||
candidateEcNode.ecNode.deleteEcVolumeShards(vid, []uint32{uint32(shardId)})
|
||||
candidateEcNode.ecNode.deleteEcVolumeShards(vid, []uint32{uint32(shardId)}, diskType)
|
||||
break
|
||||
}
|
||||
break
|
||||
@@ -1180,7 +1199,7 @@ func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[
|
||||
func (ecb *ecBalancer) collectVolumeIdToEcNodes(collection string) map[needle.VolumeId][]*EcNode {
|
||||
vidLocations := make(map[needle.VolumeId][]*EcNode)
|
||||
for _, ecNode := range ecb.ecNodes {
|
||||
diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
|
||||
diskInfo, found := ecNode.info.DiskInfos[string(ecb.diskType)]
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
@@ -1194,9 +1213,9 @@ func (ecb *ecBalancer) collectVolumeIdToEcNodes(collection string) map[needle.Vo
|
||||
return vidLocations
|
||||
}
|
||||
|
||||
func EcBalance(commandEnv *CommandEnv, collections []string, dc string, ecReplicaPlacement *super_block.ReplicaPlacement, maxParallelization int, applyBalancing bool) (err error) {
|
||||
func EcBalance(commandEnv *CommandEnv, collections []string, dc string, ecReplicaPlacement *super_block.ReplicaPlacement, diskType types.DiskType, maxParallelization int, applyBalancing bool) (err error) {
|
||||
// collect all ec nodes
|
||||
allEcNodes, totalFreeEcSlots, err := collectEcNodesForDC(commandEnv, dc)
|
||||
allEcNodes, totalFreeEcSlots, err := collectEcNodesForDC(commandEnv, dc, diskType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1210,6 +1229,7 @@ func EcBalance(commandEnv *CommandEnv, collections []string, dc string, ecReplic
|
||||
replicaPlacement: ecReplicaPlacement,
|
||||
applyBalancing: applyBalancing,
|
||||
maxParallelization: maxParallelization,
|
||||
diskType: diskType,
|
||||
}
|
||||
|
||||
if len(collections) == 0 {
|
||||
|
||||
@@ -106,7 +106,7 @@ func TestParseReplicaPlacementArg(t *testing.T) {
|
||||
func TestEcDistribution(t *testing.T) {
|
||||
|
||||
// find out all volume servers with one slot left.
|
||||
ecNodes, totalFreeEcSlots := collectEcVolumeServersByDc(topology1, "")
|
||||
ecNodes, totalFreeEcSlots := collectEcVolumeServersByDc(topology1, "", types.HardDriveType)
|
||||
|
||||
sortEcNodesByFreeslotsDescending(ecNodes)
|
||||
|
||||
@@ -149,16 +149,17 @@ func TestPickRackToBalanceShardsInto(t *testing.T) {
|
||||
|
||||
for _, tc := range testCases {
|
||||
vid, _ := needle.NewVolumeId(tc.vid)
|
||||
ecNodes, _ := collectEcVolumeServersByDc(tc.topology, "")
|
||||
ecNodes, _ := collectEcVolumeServersByDc(tc.topology, "", types.HardDriveType)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString(tc.replicaPlacement)
|
||||
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
replicaPlacement: rp,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
racks := ecb.racks()
|
||||
rackToShardCount := countShardsByRack(vid, ecNodes)
|
||||
rackToShardCount := countShardsByRack(vid, ecNodes, types.HardDriveType)
|
||||
|
||||
got, gotErr := ecb.pickRackToBalanceShardsInto(racks, rackToShardCount)
|
||||
if err := errorCheck(gotErr, tc.wantErr); err != nil {
|
||||
@@ -225,10 +226,11 @@ func TestPickEcNodeToBalanceShardsInto(t *testing.T) {
|
||||
|
||||
for _, tc := range testCases {
|
||||
vid, _ := needle.NewVolumeId(tc.vid)
|
||||
allEcNodes, _ := collectEcVolumeServersByDc(tc.topology, "")
|
||||
allEcNodes, _ := collectEcVolumeServersByDc(tc.topology, "", types.HardDriveType)
|
||||
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: allEcNodes,
|
||||
ecNodes: allEcNodes,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
// Resolve target node by name
|
||||
|
||||
@@ -32,13 +32,23 @@ func (c *commandEcDecode) Name() string {
|
||||
func (c *commandEcDecode) Help() string {
|
||||
return `decode a erasure coded volume into a normal volume
|
||||
|
||||
ec.decode [-collection=""] [-volumeId=<volume_id>]
|
||||
ec.decode [-collection=""] [-volumeId=<volume_id>] [-diskType=<disk_type>]
|
||||
|
||||
The -collection parameter supports regular expressions for pattern matching:
|
||||
- Use exact match: ec.decode -collection="^mybucket$"
|
||||
- Match multiple buckets: ec.decode -collection="bucket.*"
|
||||
- Match all collections: ec.decode -collection=".*"
|
||||
|
||||
Options:
|
||||
-diskType: source disk type where EC shards are stored (hdd, ssd, or empty for default hdd)
|
||||
|
||||
Examples:
|
||||
# Decode EC shards from HDD (default)
|
||||
ec.decode -collection=mybucket
|
||||
|
||||
# Decode EC shards from SSD
|
||||
ec.decode -collection=mybucket -diskType=ssd
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
@@ -50,6 +60,7 @@ func (c *commandEcDecode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
decodeCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
volumeId := decodeCommand.Int("volumeId", 0, "the volume id")
|
||||
collection := decodeCommand.String("collection", "", "the collection name")
|
||||
diskTypeStr := decodeCommand.String("diskType", "", "source disk type where EC shards are stored (hdd, ssd, or empty for default hdd)")
|
||||
if err = decodeCommand.Parse(args); err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -59,6 +70,7 @@ func (c *commandEcDecode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
}
|
||||
|
||||
vid := needle.VolumeId(*volumeId)
|
||||
diskType := types.ToDiskType(*diskTypeStr)
|
||||
|
||||
// collect topology information
|
||||
topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
|
||||
@@ -68,17 +80,17 @@ func (c *commandEcDecode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
|
||||
// volumeId is provided
|
||||
if vid != 0 {
|
||||
return doEcDecode(commandEnv, topologyInfo, *collection, vid)
|
||||
return doEcDecode(commandEnv, topologyInfo, *collection, vid, diskType)
|
||||
}
|
||||
|
||||
// apply to all volumes in the collection
|
||||
volumeIds, err := collectEcShardIds(topologyInfo, *collection)
|
||||
volumeIds, err := collectEcShardIds(topologyInfo, *collection, diskType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("ec decode volumes: %v\n", volumeIds)
|
||||
for _, vid := range volumeIds {
|
||||
if err = doEcDecode(commandEnv, topologyInfo, *collection, vid); err != nil {
|
||||
if err = doEcDecode(commandEnv, topologyInfo, *collection, vid, diskType); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -86,14 +98,14 @@ func (c *commandEcDecode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
return nil
|
||||
}
|
||||
|
||||
func doEcDecode(commandEnv *CommandEnv, topoInfo *master_pb.TopologyInfo, collection string, vid needle.VolumeId) (err error) {
|
||||
func doEcDecode(commandEnv *CommandEnv, topoInfo *master_pb.TopologyInfo, collection string, vid needle.VolumeId, diskType types.DiskType) (err error) {
|
||||
|
||||
if !commandEnv.isLocked() {
|
||||
return fmt.Errorf("lock is lost")
|
||||
}
|
||||
|
||||
// find volume location
|
||||
nodeToEcIndexBits := collectEcNodeShardBits(topoInfo, vid)
|
||||
nodeToEcIndexBits := collectEcNodeShardBits(topoInfo, vid, diskType)
|
||||
|
||||
fmt.Printf("ec volume %d shard locations: %+v\n", vid, nodeToEcIndexBits)
|
||||
|
||||
@@ -248,7 +260,7 @@ func lookupVolumeIds(commandEnv *CommandEnv, volumeIds []string) (volumeIdLocati
|
||||
return resp.VolumeIdLocations, nil
|
||||
}
|
||||
|
||||
func collectEcShardIds(topoInfo *master_pb.TopologyInfo, collectionPattern string) (vids []needle.VolumeId, err error) {
|
||||
func collectEcShardIds(topoInfo *master_pb.TopologyInfo, collectionPattern string, diskType types.DiskType) (vids []needle.VolumeId, err error) {
|
||||
// compile regex pattern for collection matching
|
||||
collectionRegex, err := compileCollectionPattern(collectionPattern)
|
||||
if err != nil {
|
||||
@@ -257,7 +269,7 @@ func collectEcShardIds(topoInfo *master_pb.TopologyInfo, collectionPattern strin
|
||||
|
||||
vidMap := make(map[uint32]bool)
|
||||
eachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
if diskInfo, found := dn.DiskInfos[string(types.HardDriveType)]; found {
|
||||
if diskInfo, found := dn.DiskInfos[string(diskType)]; found {
|
||||
for _, v := range diskInfo.EcShardInfos {
|
||||
if collectionRegex.MatchString(v.Collection) {
|
||||
vidMap[v.Id] = true
|
||||
@@ -273,11 +285,11 @@ func collectEcShardIds(topoInfo *master_pb.TopologyInfo, collectionPattern strin
|
||||
return
|
||||
}
|
||||
|
||||
func collectEcNodeShardBits(topoInfo *master_pb.TopologyInfo, vid needle.VolumeId) map[pb.ServerAddress]erasure_coding.ShardBits {
|
||||
func collectEcNodeShardBits(topoInfo *master_pb.TopologyInfo, vid needle.VolumeId, diskType types.DiskType) map[pb.ServerAddress]erasure_coding.ShardBits {
|
||||
|
||||
nodeToEcIndexBits := make(map[pb.ServerAddress]erasure_coding.ShardBits)
|
||||
eachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
if diskInfo, found := dn.DiskInfos[string(types.HardDriveType)]; found {
|
||||
if diskInfo, found := dn.DiskInfos[string(diskType)]; found {
|
||||
for _, v := range diskInfo.EcShardInfos {
|
||||
if v.Id == uint32(vid) {
|
||||
nodeToEcIndexBits[pb.NewServerAddressFromDataNode(dn)] = erasure_coding.ShardBits(v.EcIndexBits)
|
||||
|
||||
@@ -37,8 +37,8 @@ func (c *commandEcEncode) Name() string {
|
||||
func (c *commandEcEncode) Help() string {
|
||||
return `apply erasure coding to a volume
|
||||
|
||||
ec.encode [-collection=""] [-fullPercent=95 -quietFor=1h] [-verbose]
|
||||
ec.encode [-collection=""] [-volumeId=<volume_id>] [-verbose]
|
||||
ec.encode [-collection=""] [-fullPercent=95 -quietFor=1h] [-verbose] [-sourceDiskType=<disk_type>] [-diskType=<disk_type>]
|
||||
ec.encode [-collection=""] [-volumeId=<volume_id>] [-verbose] [-diskType=<disk_type>]
|
||||
|
||||
This command will:
|
||||
1. freeze one volume
|
||||
@@ -61,6 +61,18 @@ func (c *commandEcEncode) Help() string {
|
||||
|
||||
Options:
|
||||
-verbose: show detailed reasons why volumes are not selected for encoding
|
||||
-sourceDiskType: filter source volumes by disk type (hdd, ssd, or empty for all)
|
||||
-diskType: target disk type for EC shards (hdd, ssd, or empty for default hdd)
|
||||
|
||||
Examples:
|
||||
# Encode SSD volumes to SSD EC shards (same tier)
|
||||
ec.encode -collection=mybucket -sourceDiskType=ssd -diskType=ssd
|
||||
|
||||
# Encode SSD volumes to HDD EC shards (tier migration to cheaper storage)
|
||||
ec.encode -collection=mybucket -sourceDiskType=ssd -diskType=hdd
|
||||
|
||||
# Encode all volumes to SSD EC shards
|
||||
ec.encode -collection=mybucket -diskType=ssd
|
||||
|
||||
Re-balancing algorithm:
|
||||
` + ecBalanceAlgorithmDescription
|
||||
@@ -80,6 +92,8 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
maxParallelization := encodeCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
|
||||
forceChanges := encodeCommand.Bool("force", false, "force the encoding even if the cluster has less than recommended 4 nodes")
|
||||
shardReplicaPlacement := encodeCommand.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty")
|
||||
sourceDiskTypeStr := encodeCommand.String("sourceDiskType", "", "filter source volumes by disk type (hdd, ssd, or empty for all)")
|
||||
diskTypeStr := encodeCommand.String("diskType", "", "target disk type for EC shards (hdd, ssd, or empty for default hdd)")
|
||||
applyBalancing := encodeCommand.Bool("rebalance", false, "re-balance EC shards after creation")
|
||||
verbose := encodeCommand.Bool("verbose", false, "show detailed reasons why volumes are not selected for encoding")
|
||||
|
||||
@@ -94,6 +108,16 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
return err
|
||||
}
|
||||
|
||||
// Parse source disk type filter (optional)
|
||||
var sourceDiskType *types.DiskType
|
||||
if *sourceDiskTypeStr != "" {
|
||||
sdt := types.ToDiskType(*sourceDiskTypeStr)
|
||||
sourceDiskType = &sdt
|
||||
}
|
||||
|
||||
// Parse target disk type for EC shards
|
||||
diskType := types.ToDiskType(*diskTypeStr)
|
||||
|
||||
// collect topology information
|
||||
topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
|
||||
if err != nil {
|
||||
@@ -119,7 +143,7 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
balanceCollections = collectCollectionsForVolumeIds(topologyInfo, volumeIds)
|
||||
} else {
|
||||
// apply to all volumes for the given collection pattern (regex)
|
||||
volumeIds, balanceCollections, err = collectVolumeIdsForEcEncode(commandEnv, *collection, nil, *fullPercentage, *quietPeriod, *verbose)
|
||||
volumeIds, balanceCollections, err = collectVolumeIdsForEcEncode(commandEnv, *collection, sourceDiskType, *fullPercentage, *quietPeriod, *verbose)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -142,7 +166,7 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
return fmt.Errorf("ec encode for volumes %v: %w", volumeIds, err)
|
||||
}
|
||||
// ...re-balance ec shards...
|
||||
if err := EcBalance(commandEnv, balanceCollections, "", rp, *maxParallelization, *applyBalancing); err != nil {
|
||||
if err := EcBalance(commandEnv, balanceCollections, "", rp, diskType, *maxParallelization, *applyBalancing); err != nil {
|
||||
return fmt.Errorf("re-balance ec shards for collection(s) %v: %w", balanceCollections, err)
|
||||
}
|
||||
// ...then delete original volumes using pre-collected locations.
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -24,6 +25,7 @@ type ecRebuilder struct {
|
||||
writer io.Writer
|
||||
applyChanges bool
|
||||
collections []string
|
||||
diskType types.DiskType
|
||||
|
||||
ewg *ErrorWaitGroup
|
||||
ecNodesMu sync.Mutex
|
||||
@@ -39,7 +41,7 @@ func (c *commandEcRebuild) Name() string {
|
||||
func (c *commandEcRebuild) Help() string {
|
||||
return `find and rebuild missing ec shards among volume servers
|
||||
|
||||
ec.rebuild [-c EACH_COLLECTION|<collection_name>] [-apply] [-maxParallelization N]
|
||||
ec.rebuild [-c EACH_COLLECTION|<collection_name>] [-apply] [-maxParallelization N] [-diskType=<disk_type>]
|
||||
|
||||
Options:
|
||||
-collection: specify a collection name, or "EACH_COLLECTION" to process all collections
|
||||
@@ -47,6 +49,7 @@ func (c *commandEcRebuild) Help() string {
|
||||
-maxParallelization: number of volumes to rebuild concurrently (default: 10)
|
||||
Increase for faster rebuilds with more system resources.
|
||||
Decrease if experiencing resource contention or instability.
|
||||
-diskType: disk type for EC shards (hdd, ssd, or empty for default hdd)
|
||||
|
||||
Algorithm:
|
||||
|
||||
@@ -83,6 +86,7 @@ func (c *commandEcRebuild) Do(args []string, commandEnv *CommandEnv, writer io.W
|
||||
collection := fixCommand.String("collection", "EACH_COLLECTION", "collection name, or \"EACH_COLLECTION\" for each collection")
|
||||
maxParallelization := fixCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
|
||||
applyChanges := fixCommand.Bool("apply", false, "apply the changes")
|
||||
diskTypeStr := fixCommand.String("diskType", "", "disk type for EC shards (hdd, ssd, or empty for default hdd)")
|
||||
// TODO: remove this alias
|
||||
applyChangesAlias := fixCommand.Bool("force", false, "apply the changes (alias for -apply)")
|
||||
if err = fixCommand.Parse(args); err != nil {
|
||||
@@ -95,8 +99,10 @@ func (c *commandEcRebuild) Do(args []string, commandEnv *CommandEnv, writer io.W
|
||||
return
|
||||
}
|
||||
|
||||
diskType := types.ToDiskType(*diskTypeStr)
|
||||
|
||||
// collect all ec nodes
|
||||
allEcNodes, _, err := collectEcNodes(commandEnv)
|
||||
allEcNodes, _, err := collectEcNodes(commandEnv, diskType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -117,6 +123,7 @@ func (c *commandEcRebuild) Do(args []string, commandEnv *CommandEnv, writer io.W
|
||||
writer: writer,
|
||||
applyChanges: *applyChanges,
|
||||
collections: collections,
|
||||
diskType: diskType,
|
||||
|
||||
ewg: NewErrorWaitGroup(*maxParallelization),
|
||||
}
|
||||
@@ -294,7 +301,7 @@ func (erb *ecRebuilder) rebuildOneEcVolume(collection string, volumeId needle.Vo
|
||||
// ensure ECNode updates are atomic
|
||||
erb.ecNodesMu.Lock()
|
||||
defer erb.ecNodesMu.Unlock()
|
||||
rebuilder.addEcVolumeShards(volumeId, collection, generatedShardIds)
|
||||
rebuilder.addEcVolumeShards(volumeId, collection, generatedShardIds, erb.diskType)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func TestCommandEcBalanceSmall(t *testing.T) {
|
||||
@@ -14,6 +15,7 @@ func TestCommandEcBalanceSmall(t *testing.T) {
|
||||
newEcNode("dc1", "rack2", "dn2", 100).addEcVolumeAndShardsForTest(2, "c1", []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}),
|
||||
},
|
||||
applyBalancing: false,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
@@ -30,6 +32,7 @@ func TestCommandEcBalanceNothingToMove(t *testing.T) {
|
||||
addEcVolumeAndShardsForTest(2, "c1", []uint32{0, 1, 2, 3, 4, 5, 6}),
|
||||
},
|
||||
applyBalancing: false,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
@@ -48,6 +51,7 @@ func TestCommandEcBalanceAddNewServers(t *testing.T) {
|
||||
newEcNode("dc1", "rack1", "dn4", 100),
|
||||
},
|
||||
applyBalancing: false,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
@@ -66,6 +70,7 @@ func TestCommandEcBalanceAddNewRacks(t *testing.T) {
|
||||
newEcNode("dc1", "rack2", "dn4", 100),
|
||||
},
|
||||
applyBalancing: false,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
@@ -109,6 +114,7 @@ func TestCommandEcBalanceVolumeEvenButRackUneven(t *testing.T) {
|
||||
newEcNode("dc1", "rack1", "dn3", 100),
|
||||
},
|
||||
applyBalancing: false,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
@@ -128,5 +134,5 @@ func newEcNode(dc string, rack string, dataNodeId string, freeEcSlot int) *EcNod
|
||||
}
|
||||
|
||||
func (ecNode *EcNode) addEcVolumeAndShardsForTest(vid uint32, collection string, shardIds []uint32) *EcNode {
|
||||
return ecNode.addEcVolumeShards(needle.VolumeId(vid), collection, shardIds)
|
||||
return ecNode.addEcVolumeShards(needle.VolumeId(vid), collection, shardIds, types.HardDriveType)
|
||||
}
|
||||
@@ -4,11 +4,14 @@ import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -27,6 +30,15 @@ func (c *commandS3BucketCreate) Help() string {
|
||||
|
||||
Example:
|
||||
s3.bucket.create -name <bucket_name>
|
||||
s3.bucket.create -name <bucket_name> -owner <identity_name>
|
||||
|
||||
The -owner flag sets the bucket owner identity. This is important when using
|
||||
S3 IAM authentication, as non-admin users can only access buckets they own.
|
||||
If not specified, the bucket will have no owner and will only be accessible
|
||||
by admin users.
|
||||
|
||||
The -owner value should match the identity name configured in your S3 IAM
|
||||
system (the "name" field in s3.json identities configuration).
|
||||
`
|
||||
}
|
||||
|
||||
@@ -38,6 +50,7 @@ func (c *commandS3BucketCreate) Do(args []string, commandEnv *CommandEnv, writer
|
||||
|
||||
bucketCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
bucketName := bucketCommand.String("name", "", "bucket name")
|
||||
bucketOwner := bucketCommand.String("owner", "", "bucket owner identity name (for S3 IAM authentication)")
|
||||
if err = bucketCommand.Parse(args); err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -51,6 +64,9 @@ func (c *commandS3BucketCreate) Do(args []string, commandEnv *CommandEnv, writer
|
||||
return err
|
||||
}
|
||||
|
||||
// Trim whitespace from owner and treat whitespace-only as empty
|
||||
owner := strings.TrimSpace(*bucketOwner)
|
||||
|
||||
err = commandEnv.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
@@ -59,7 +75,7 @@ func (c *commandS3BucketCreate) Do(args []string, commandEnv *CommandEnv, writer
|
||||
}
|
||||
filerBucketsPath := resp.DirBuckets
|
||||
|
||||
println("create bucket under", filerBucketsPath)
|
||||
fmt.Fprintln(writer, "create bucket under", filerBucketsPath)
|
||||
|
||||
entry := &filer_pb.Entry{
|
||||
Name: *bucketName,
|
||||
@@ -71,14 +87,25 @@ func (c *commandS3BucketCreate) Do(args []string, commandEnv *CommandEnv, writer
|
||||
},
|
||||
}
|
||||
|
||||
if err := filer_pb.CreateEntry(context.Background(), client, &filer_pb.CreateEntryRequest{
|
||||
// Set bucket owner if specified
|
||||
if owner != "" {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
entry.Extended[s3_constants.AmzIdentityId] = []byte(owner)
|
||||
}
|
||||
|
||||
if _, err := client.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
||||
Directory: filerBucketsPath,
|
||||
Entry: entry,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
println("created bucket", *bucketName)
|
||||
fmt.Fprintln(writer, "created bucket", *bucketName)
|
||||
if owner != "" {
|
||||
fmt.Fprintln(writer, "bucket owner:", owner)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"math"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -71,6 +72,12 @@ func (c *commandS3BucketList) Do(args []string, commandEnv *CommandEnv, writer i
|
||||
if entry.Quota > 0 {
|
||||
fmt.Fprintf(writer, "\tquota:%d\tusage:%.2f%%", entry.Quota, float64(collectionSize)*100/float64(entry.Quota))
|
||||
}
|
||||
// Show bucket owner (use %q to escape special characters)
|
||||
if entry.Extended != nil {
|
||||
if owner, ok := entry.Extended[s3_constants.AmzIdentityId]; ok && len(owner) > 0 {
|
||||
fmt.Fprintf(writer, "\towner:%q", string(owner))
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(writer)
|
||||
return nil
|
||||
}, "", false, math.MaxUint32)
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Commands = append(Commands, &commandS3BucketOwner{})
|
||||
}
|
||||
|
||||
type commandS3BucketOwner struct {
|
||||
}
|
||||
|
||||
func (c *commandS3BucketOwner) Name() string {
|
||||
return "s3.bucket.owner"
|
||||
}
|
||||
|
||||
func (c *commandS3BucketOwner) Help() string {
|
||||
return `view or change the owner of an S3 bucket
|
||||
|
||||
Example:
|
||||
# View the current owner of a bucket
|
||||
s3.bucket.owner -name <bucket_name>
|
||||
|
||||
# Set or change the owner of a bucket
|
||||
s3.bucket.owner -name <bucket_name> -owner <identity_name>
|
||||
|
||||
# Remove the owner (make bucket admin-only)
|
||||
s3.bucket.owner -name <bucket_name> -delete
|
||||
|
||||
The owner identity determines which S3 user can access the bucket.
|
||||
Non-admin users can only access buckets they own. Admin users can
|
||||
access all buckets regardless of ownership.
|
||||
|
||||
The -owner value should match the identity name configured in your
|
||||
S3 IAM system (the "name" field in s3.json identities configuration).
|
||||
`
|
||||
}
|
||||
|
||||
func (c *commandS3BucketOwner) HasTag(CommandTag) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *commandS3BucketOwner) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
|
||||
|
||||
bucketCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
bucketName := bucketCommand.String("name", "", "bucket name")
|
||||
bucketOwner := bucketCommand.String("owner", "", "new bucket owner identity name")
|
||||
deleteOwner := bucketCommand.Bool("delete", false, "remove the bucket owner (make admin-only)")
|
||||
if err = bucketCommand.Parse(args); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if *bucketName == "" {
|
||||
return fmt.Errorf("empty bucket name")
|
||||
}
|
||||
|
||||
// Trim whitespace from owner
|
||||
owner := strings.TrimSpace(*bucketOwner)
|
||||
|
||||
// Validate flags: can't use both -owner and -delete
|
||||
if owner != "" && *deleteOwner {
|
||||
return fmt.Errorf("cannot use both -owner and -delete flags together")
|
||||
}
|
||||
|
||||
err = commandEnv.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("get filer configuration: %w", err)
|
||||
}
|
||||
filerBucketsPath := resp.DirBuckets
|
||||
|
||||
// Look up the bucket entry
|
||||
lookupResp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: filerBucketsPath,
|
||||
Name: *bucketName,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup bucket %s: %w", *bucketName, err)
|
||||
}
|
||||
|
||||
entry := lookupResp.Entry
|
||||
|
||||
// If -owner is provided, set the owner
|
||||
if owner != "" {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
entry.Extended[s3_constants.AmzIdentityId] = []byte(owner)
|
||||
fmt.Fprintf(writer, "Setting owner of bucket %s to: %s\n", *bucketName, owner)
|
||||
|
||||
// Update the entry
|
||||
if _, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: filerBucketsPath,
|
||||
Entry: entry,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("failed to update bucket: %w", err)
|
||||
}
|
||||
|
||||
fmt.Fprintf(writer, "Bucket owner updated successfully.\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// If -delete is provided, remove the owner
|
||||
if *deleteOwner {
|
||||
if entry.Extended != nil {
|
||||
delete(entry.Extended, s3_constants.AmzIdentityId)
|
||||
}
|
||||
fmt.Fprintf(writer, "Removing owner from bucket %s\n", *bucketName)
|
||||
|
||||
// Update the entry
|
||||
if _, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: filerBucketsPath,
|
||||
Entry: entry,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("failed to update bucket: %w", err)
|
||||
}
|
||||
|
||||
fmt.Fprintf(writer, "Bucket owner removed. Bucket is now admin-only.\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Display current owner (no flags provided)
|
||||
fmt.Fprintf(writer, "Bucket: %s\n", *bucketName)
|
||||
fmt.Fprintf(writer, "Path: %s\n", util.NewFullPath(filerBucketsPath, *bucketName))
|
||||
|
||||
if entry.Extended != nil {
|
||||
if ownerBytes, ok := entry.Extended[s3_constants.AmzIdentityId]; ok && len(ownerBytes) > 0 {
|
||||
fmt.Fprintf(writer, "Owner: %s\n", string(ownerBytes))
|
||||
} else {
|
||||
fmt.Fprintf(writer, "Owner: (none - admin access only)\n")
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(writer, "Owner: (none - admin access only)\n")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -5,10 +5,11 @@ import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"io"
|
||||
"math"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -104,7 +105,10 @@ func (c *commandS3BucketQuotaEnforce) Do(args []string, commandEnv *CommandEnv,
|
||||
func (c *commandS3BucketQuotaEnforce) processEachBucket(fc *filer.FilerConf, filerBucketsPath string, entry *filer_pb.Entry, writer io.Writer, collectionSize float64) (hasConfChanges bool) {
|
||||
|
||||
locPrefix := filerBucketsPath + "/" + entry.Name + "/"
|
||||
locConf := fc.MatchStorageRule(locPrefix)
|
||||
existingConf := fc.MatchStorageRule(locPrefix)
|
||||
|
||||
// Create a mutable copy for modification
|
||||
locConf := filer.ClonePathConf(existingConf)
|
||||
locConf.LocationPrefix = locPrefix
|
||||
|
||||
if entry.Quota > 0 {
|
||||
|
||||
@@ -76,6 +76,12 @@ func (c *commandVolumeFsck) Help() string {
|
||||
2. collect all file ids from the filer, as set B
|
||||
3. find out the set B subtract A
|
||||
|
||||
-cutoffTimeAgo is used to only check chunks older than the cutoff time.
|
||||
This is important because:
|
||||
Chunks are uploaded to volume servers before metadata is committed to filer.
|
||||
A newly uploaded chunk may appear as orphan if metadata commit is still pending.
|
||||
The default 5h cutoff provides sufficient buffer for metadata commits.
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
@@ -94,7 +100,7 @@ func (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.
|
||||
c.forcePurging = fsckCommand.Bool("forcePurging", false, "delete missing data from volumes in one replica used together with applyPurging")
|
||||
purgeAbsent := fsckCommand.Bool("reallyDeleteFilerEntries", false, "<expert only!> delete missing file entries from filer if the corresponding volume is missing for any reason, please ensure all still existing/expected volumes are connected! used together with findMissingChunksInFiler")
|
||||
tempPath := fsckCommand.String("tempPath", path.Join(os.TempDir()), "path for temporary idx files")
|
||||
cutoffTimeAgo := fsckCommand.Duration("cutoffTimeAgo", 5*time.Minute, "only include entries on volume servers before this cutoff time to check orphan chunks")
|
||||
cutoffTimeAgo := fsckCommand.Duration("cutoffTimeAgo", 5*time.Hour, "only include entries on volume servers before this cutoff time to check orphan chunks")
|
||||
modifyTimeAgo := fsckCommand.Duration("modifyTimeAgo", 0, "only include entries after this modify time to check orphan chunks")
|
||||
c.verifyNeedle = fsckCommand.Bool("verifyNeedles", false, "check needles status from volume server")
|
||||
|
||||
|
||||
@@ -156,21 +156,30 @@ func (c *commandVolumeServerEvacuate) evacuateNormalVolumes(commandEnv *CommandE
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerEvacuate) evacuateEcVolumes(commandEnv *CommandEnv, volumeServer string, skipNonMoveable, applyChange bool, writer io.Writer) error {
|
||||
// find this ec volume server
|
||||
// Evacuate EC volumes for all disk types discovered from topology
|
||||
// Disk types are free-form tags (e.g., "", "hdd", "ssd", "nvme", etc.)
|
||||
// We need to handle each disk type separately because shards should be moved to nodes with the same disk type
|
||||
// We collect topology once at the start and track capacity changes ourselves
|
||||
// (via freeEcSlot decrement after each move) rather than repeatedly refreshing,
|
||||
// which would give a false sense of correctness since topology could be stale.
|
||||
ecNodes, _ := collectEcVolumeServersByDc(c.topologyInfo, "")
|
||||
thisNodes, otherNodes := c.ecNodesOtherThan(ecNodes, volumeServer)
|
||||
if len(thisNodes) == 0 {
|
||||
return fmt.Errorf("%s is not found in this cluster\n", volumeServer)
|
||||
}
|
||||
diskTypes := collectVolumeDiskTypes(c.topologyInfo)
|
||||
|
||||
// move away ec volumes
|
||||
for _, thisNode := range thisNodes {
|
||||
for _, diskInfo := range thisNode.info.DiskInfos {
|
||||
for _, diskType := range diskTypes {
|
||||
ecNodes, _ := collectEcVolumeServersByDc(c.topologyInfo, "", diskType)
|
||||
thisNodes, otherNodes := c.ecNodesOtherThan(ecNodes, volumeServer)
|
||||
if len(thisNodes) == 0 {
|
||||
// This server doesn't have EC shards for this disk type, skip
|
||||
continue
|
||||
}
|
||||
|
||||
// move away ec volumes for this disk type
|
||||
for _, thisNode := range thisNodes {
|
||||
diskInfo, found := thisNode.info.DiskInfos[string(diskType)]
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
hasMoved, err := c.moveAwayOneEcVolume(commandEnv, ecShardInfo, thisNode, otherNodes, applyChange, writer)
|
||||
hasMoved, err := c.moveAwayOneEcVolume(commandEnv, ecShardInfo, thisNode, otherNodes, applyChange, diskType, writer)
|
||||
if err != nil {
|
||||
fmt.Fprintf(writer, "move away volume %d from %s: %v\n", ecShardInfo.Id, volumeServer, err)
|
||||
}
|
||||
@@ -187,7 +196,7 @@ func (c *commandVolumeServerEvacuate) evacuateEcVolumes(commandEnv *CommandEnv,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerEvacuate) moveAwayOneEcVolume(commandEnv *CommandEnv, ecShardInfo *master_pb.VolumeEcShardInformationMessage, thisNode *EcNode, otherNodes []*EcNode, applyChange bool, writer io.Writer) (hasMoved bool, err error) {
|
||||
func (c *commandVolumeServerEvacuate) moveAwayOneEcVolume(commandEnv *CommandEnv, ecShardInfo *master_pb.VolumeEcShardInformationMessage, thisNode *EcNode, otherNodes []*EcNode, applyChange bool, diskType types.DiskType, writer io.Writer) (hasMoved bool, err error) {
|
||||
|
||||
for _, shardId := range erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIds() {
|
||||
// Sort by: 1) fewest shards of this volume, 2) most free EC slots
|
||||
@@ -217,13 +226,14 @@ func (c *commandVolumeServerEvacuate) moveAwayOneEcVolume(commandEnv *CommandEnv
|
||||
collectionPrefix = ecShardInfo.Collection + "_"
|
||||
}
|
||||
vid := needle.VolumeId(ecShardInfo.Id)
|
||||
destDiskId := pickBestDiskOnNode(emptyNode, vid)
|
||||
// For evacuation, prefer same disk type but allow fallback to other types
|
||||
destDiskId := pickBestDiskOnNode(emptyNode, vid, diskType, false)
|
||||
if destDiskId > 0 {
|
||||
fmt.Fprintf(writer, "moving ec volume %s%d.%d %s => %s (disk %d)\n", collectionPrefix, ecShardInfo.Id, shardId, thisNode.info.Id, emptyNode.info.Id, destDiskId)
|
||||
} else {
|
||||
fmt.Fprintf(writer, "moving ec volume %s%d.%d %s => %s\n", collectionPrefix, ecShardInfo.Id, shardId, thisNode.info.Id, emptyNode.info.Id)
|
||||
}
|
||||
err = moveMountedShardToEcNode(commandEnv, thisNode, ecShardInfo.Collection, vid, shardId, emptyNode, destDiskId, applyChange)
|
||||
err = moveMountedShardToEcNode(commandEnv, thisNode, ecShardInfo.Collection, vid, shardId, emptyNode, destDiskId, applyChange, diskType)
|
||||
if err != nil {
|
||||
hasMoved = false
|
||||
return
|
||||
|
||||
@@ -130,10 +130,7 @@ func NewHttpClient(clientName ClientName, opts ...HttpClientOpt) (*HTTPClient, e
|
||||
httpClient.Transport = &http.Transport{
|
||||
MaxIdleConns: 1024,
|
||||
MaxIdleConnsPerHost: 1024,
|
||||
// Allow truly parallel per-host connections and avoid HTTP/2 multiplexing
|
||||
MaxConnsPerHost: 0, // unlimited
|
||||
ForceAttemptHTTP2: false, // disable HTTP/2 to avoid implicit single-connection multiplexing
|
||||
TLSClientConfig: tlsConfig,
|
||||
TLSClientConfig: tlsConfig,
|
||||
}
|
||||
httpClient.Client = &http.Client{
|
||||
Transport: httpClient.Transport,
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
)
|
||||
|
||||
const BufferSize = 8 * 1024 * 1024
|
||||
const PreviousBufferCount = 32
|
||||
const PreviousBufferCount = 4
|
||||
|
||||
// Errors that can be returned by log buffer operations
|
||||
var (
|
||||
@@ -723,7 +723,10 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
|
||||
}
|
||||
}
|
||||
if tsMemory.IsZero() { // case 2.2
|
||||
return nil, -2, nil
|
||||
// Buffer is empty - return ResumeFromDiskError so caller can read from disk
|
||||
// This fixes issue #4977 where SubscribeMetadata stalls because
|
||||
// MetaAggregator.MetaLogBuffer is empty in single-filer setups
|
||||
return nil, -2, ResumeFromDiskError
|
||||
} else if lastReadPosition.Time.Before(tsMemory) { // case 2.3
|
||||
// For time-based reads, only check timestamp for disk reads
|
||||
// Don't use offset comparisons as they're not meaningful for time-based subscriptions
|
||||
@@ -859,6 +862,18 @@ var bufferPool = sync.Pool{
|
||||
},
|
||||
}
|
||||
|
||||
// logEntryPool reduces allocations in readTs which is called frequently during binary search
|
||||
var logEntryPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return &filer_pb.LogEntry{}
|
||||
},
|
||||
}
|
||||
|
||||
// resetLogEntry clears a LogEntry for pool reuse
|
||||
func resetLogEntry(e *filer_pb.LogEntry) {
|
||||
proto.Reset(e)
|
||||
}
|
||||
|
||||
func copiedBytes(buf []byte) (copied *bytes.Buffer) {
|
||||
copied = bufferPool.Get().(*bytes.Buffer)
|
||||
copied.Reset()
|
||||
@@ -880,7 +895,13 @@ func readTs(buf []byte, pos int) (size int, ts int64, err error) {
|
||||
}
|
||||
|
||||
entryData := buf[pos+4 : pos+4+size]
|
||||
logEntry := &filer_pb.LogEntry{}
|
||||
|
||||
// Use pooled LogEntry to avoid allocation on every call
|
||||
logEntry := logEntryPool.Get().(*filer_pb.LogEntry)
|
||||
defer func() {
|
||||
resetLogEntry(logEntry)
|
||||
logEntryPool.Put(logEntry)
|
||||
}()
|
||||
|
||||
err = proto.Unmarshal(entryData, logEntry)
|
||||
if err != nil {
|
||||
@@ -888,6 +909,6 @@ func readTs(buf []byte, pos int) (size int, ts int64, err error) {
|
||||
// This allows caller to handle corruption gracefully
|
||||
return 0, 0, fmt.Errorf("corrupted log buffer: failed to unmarshal LogEntry at pos %d, size %d: %w", pos, size, err)
|
||||
}
|
||||
return size, logEntry.TsNs, nil
|
||||
|
||||
return size, logEntry.TsNs, nil
|
||||
}
|
||||
Reference in new issue
Block a user