mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
263b7bbf53 |
No files matched your search
@@ -261,7 +261,7 @@ jobs:
|
||||
helm-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [copy-to-dockerhub]
|
||||
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
|
||||
if: github.event_name == 'push'
|
||||
permissions:
|
||||
contents: write
|
||||
pages: write
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
name: "helm: manual release"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pages: write
|
||||
|
||||
jobs:
|
||||
helm-release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Publish Helm charts
|
||||
uses: stefanprodan/helm-gh-pages@v1.7.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
charts_dir: k8s/charts
|
||||
target_dir: helm
|
||||
branch: gh-pages
|
||||
helm_version: "3.18.4"
|
||||
@@ -260,140 +260,6 @@ jobs:
|
||||
path: test/s3tables/catalog_spark/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
risingwave-catalog-tests:
|
||||
name: RisingWave Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
id: go
|
||||
|
||||
- name: Set up Docker
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Pre-pull RisingWave image
|
||||
run: |
|
||||
docker pull risingwavelabs/risingwave:v2.5.0
|
||||
docker pull postgres:16-alpine
|
||||
|
||||
- name: Run go mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
go install -buildvcs=false ./weed
|
||||
|
||||
- name: Run RisingWave Catalog Integration Tests
|
||||
timeout-minutes: 25
|
||||
working-directory: test/s3tables/catalog_risingwave
|
||||
run: |
|
||||
set -x
|
||||
set -o pipefail
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
echo "=== Starting RisingWave Catalog Tests ==="
|
||||
|
||||
# Run RisingWave catalog integration tests
|
||||
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
|
||||
echo "RisingWave catalog integration tests failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Show test output on failure
|
||||
if: failure()
|
||||
working-directory: test/s3tables/catalog_risingwave
|
||||
run: |
|
||||
echo "=== Test Output ==="
|
||||
if [ -f test-output.log ]; then
|
||||
tail -200 test-output.log
|
||||
fi
|
||||
|
||||
echo "=== Process information ==="
|
||||
ps aux | grep -E "(weed|test|docker)" || true
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: risingwave-catalog-test-logs
|
||||
path: test/s3tables/catalog_risingwave/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
sts-integration-tests:
|
||||
name: STS Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
id: go
|
||||
|
||||
- name: Set up Docker
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Pre-pull Python image
|
||||
run: docker pull python:3
|
||||
|
||||
- name: Run go mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
go install -buildvcs=false ./weed
|
||||
|
||||
- name: Run STS Integration Tests
|
||||
timeout-minutes: 25
|
||||
working-directory: test/s3tables/sts_integration
|
||||
run: |
|
||||
set -x
|
||||
set -o pipefail
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
echo "=== Starting STS Integration Tests ==="
|
||||
|
||||
# Run STS integration tests
|
||||
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
|
||||
echo "STS integration tests failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Show test output on failure
|
||||
if: failure()
|
||||
working-directory: test/s3tables/sts_integration
|
||||
run: |
|
||||
echo "=== Test Output ==="
|
||||
if [ -f test-output.log ]; then
|
||||
tail -200 test-output.log
|
||||
fi
|
||||
|
||||
echo "=== Process information ==="
|
||||
ps aux | grep -E "(weed|test|docker)" || true
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: sts-integration-test-logs
|
||||
path: test/s3tables/sts_integration/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
s3-tables-build-verification:
|
||||
name: S3 Tables Build Verification
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "seaweedfs.componentName" (list . "admin") }}
|
||||
name: {{ printf "%s-admin" (include "seaweedfs.fullname" .) | trunc 63 | trimSuffix "-" }}
|
||||
namespace: {{ .Release.Namespace }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
|
||||
|
||||
@@ -134,7 +134,7 @@ spec:
|
||||
{{- if .Values.worker.adminServer }}
|
||||
-admin={{ .Values.worker.adminServer }} \
|
||||
{{- else }}
|
||||
-admin={{ include "seaweedfs.componentName" (list . "admin") }}.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
|
||||
-admin={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
|
||||
{{- end }}
|
||||
-capabilities={{ .Values.worker.capabilities }} \
|
||||
-maxConcurrent={{ .Values.worker.maxConcurrent }} \
|
||||
|
||||
@@ -14,7 +14,7 @@ func setupSparkIssue8234Env(t *testing.T) *TestEnvironment {
|
||||
}
|
||||
|
||||
env.StartSeaweedFS(t)
|
||||
t.Cleanup(func() { env.Cleanup(t) })
|
||||
t.Cleanup(func() { env.Cleanup() })
|
||||
|
||||
createObjectBucket(t, env, "test")
|
||||
env.startSparkContainer(t)
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
package spark
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
)
|
||||
|
||||
func TestSparkS3TemporaryDirectoryCleanupIssue8285Regression(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping Spark integration test in short mode")
|
||||
}
|
||||
|
||||
env := setupSparkIssue8234Env(t)
|
||||
|
||||
script := `
|
||||
import pyspark.sql.functions as F
|
||||
|
||||
target = "s3a://test/issue-8285/output"
|
||||
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.name", "directory")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.magic.enabled", "false")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.staging.abort.pending.uploads", "true")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.staging.conflict-mode", "append")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.staging.tmp.path", "/tmp")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.directory.marker.retention", "keep")
|
||||
|
||||
df = spark.range(0, 200).repartition(12).withColumn("value", F.col("id") * 2)
|
||||
df.write.format("parquet").mode("overwrite").save(target)
|
||||
count = spark.read.parquet(target).count()
|
||||
print("WRITE_COUNT=" + str(count))
|
||||
`
|
||||
|
||||
code, output := runSparkPyScript(t, env.sparkContainer, script, env.s3Port)
|
||||
if code != 0 {
|
||||
t.Fatalf("Spark script exited with code %d; output:\n%s", code, output)
|
||||
}
|
||||
if !strings.Contains(output, "WRITE_COUNT=200") {
|
||||
t.Fatalf("expected write/read success marker in output, got:\n%s", output)
|
||||
}
|
||||
|
||||
keys := listObjectKeysByPrefix(t, env, "test", "issue-8285/")
|
||||
var temporaryKeys []string
|
||||
for _, key := range keys {
|
||||
if hasTemporaryPathSegment(key) {
|
||||
temporaryKeys = append(temporaryKeys, key)
|
||||
}
|
||||
}
|
||||
|
||||
if len(temporaryKeys) > 0 {
|
||||
t.Fatalf("issue #8285 regression detected: found lingering _temporary artifacts: %v\nall keys: %v", temporaryKeys, keys)
|
||||
}
|
||||
|
||||
temporaryCandidates := []string{
|
||||
"issue-8285/output/_temporary/",
|
||||
"issue-8285/output/_temporary/0/",
|
||||
"issue-8285/output/_temporary/0/_temporary/",
|
||||
}
|
||||
lingering := waitForObjectsToDisappear(t, env, "test", temporaryCandidates, 35*time.Second)
|
||||
if len(lingering) > 0 {
|
||||
t.Fatalf("issue #8285 regression detected: lingering temporary directories: %v", lingering)
|
||||
}
|
||||
}
|
||||
|
||||
func listObjectKeysByPrefix(t *testing.T, env *TestEnvironment, bucketName, prefix string) []string {
|
||||
t.Helper()
|
||||
client := newS3Client(env)
|
||||
|
||||
pager := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName),
|
||||
Prefix: aws.String(prefix),
|
||||
})
|
||||
|
||||
var keys []string
|
||||
for pager.HasMorePages() {
|
||||
page, err := pager.NextPage(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("failed listing objects for prefix %q: %v", prefix, err)
|
||||
}
|
||||
for _, object := range page.Contents {
|
||||
keys = append(keys, aws.ToString(object.Key))
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func headObjectInfo(t *testing.T, env *TestEnvironment, bucketName, key string) (bool, string, error) {
|
||||
t.Helper()
|
||||
|
||||
client := newS3Client(env)
|
||||
output, err := client.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err == nil {
|
||||
return true, aws.ToString(output.ContentType), nil
|
||||
}
|
||||
|
||||
var notFound *s3types.NotFound
|
||||
if strings.Contains(err.Error(), "NotFound") || strings.Contains(err.Error(), "NoSuchKey") || errors.As(err, ¬Found) {
|
||||
return false, "", nil
|
||||
}
|
||||
return false, "", err
|
||||
}
|
||||
|
||||
func waitForObjectsToDisappear(t *testing.T, env *TestEnvironment, bucketName string, keys []string, timeout time.Duration) []string {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(timeout)
|
||||
pending := make(map[string]struct{}, len(keys))
|
||||
details := make(map[string]string, len(keys))
|
||||
for _, key := range keys {
|
||||
pending[key] = struct{}{}
|
||||
}
|
||||
|
||||
for len(pending) > 0 && time.Now().Before(deadline) {
|
||||
for key := range pending {
|
||||
exists, contentType, err := headObjectInfo(t, env, bucketName, key)
|
||||
if err != nil {
|
||||
details[key] = fmt.Sprintf("%s (head_error=%v)", key, err)
|
||||
continue
|
||||
}
|
||||
if !exists {
|
||||
delete(pending, key)
|
||||
delete(details, key)
|
||||
continue
|
||||
}
|
||||
details[key] = fmt.Sprintf("%s (exists=true, contentType=%q)", key, contentType)
|
||||
}
|
||||
if len(pending) > 0 {
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
if len(pending) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var lingering []string
|
||||
for _, key := range keys {
|
||||
if _, ok := pending[key]; !ok {
|
||||
continue
|
||||
}
|
||||
if detail, hasDetail := details[key]; hasDetail {
|
||||
lingering = append(lingering, detail)
|
||||
} else {
|
||||
lingering = append(lingering, key)
|
||||
}
|
||||
}
|
||||
return lingering
|
||||
}
|
||||
|
||||
func newS3Client(env *TestEnvironment) *s3.Client {
|
||||
cfg := aws.Config{
|
||||
Region: "us-east-1",
|
||||
Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(env.accessKey, env.secretKey, "")),
|
||||
BaseEndpoint: aws.String(fmt.Sprintf("http://localhost:%d", env.s3Port)),
|
||||
}
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
func hasTemporaryPathSegment(key string) bool {
|
||||
for _, segment := range strings.Split(strings.TrimSuffix(key, "/"), "/") {
|
||||
if segment == "_temporary" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -54,8 +53,6 @@ type TestEnvironment struct {
|
||||
dockerAvailable bool
|
||||
weedBinary string
|
||||
seaweedfsDataDir string
|
||||
weedLogPath string
|
||||
weedLogFile *os.File
|
||||
masterPort int
|
||||
filerPort int
|
||||
s3Port int
|
||||
@@ -116,15 +113,6 @@ func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
"-s3.config", iamConfigPath,
|
||||
"-dir", env.seaweedfsDataDir,
|
||||
)
|
||||
weedLogPath := filepath.Join(env.seaweedfsDataDir, "weed-mini.log")
|
||||
weedLogFile, err := os.Create(weedLogPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create weed log file: %v", err)
|
||||
}
|
||||
env.weedLogPath = weedLogPath
|
||||
env.weedLogFile = weedLogFile
|
||||
env.masterProcess.Stdout = weedLogFile
|
||||
env.masterProcess.Stderr = weedLogFile
|
||||
env.masterProcess.Env = append(os.Environ(),
|
||||
"AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
@@ -172,30 +160,12 @@ func (env *TestEnvironment) startSparkContainer(t *testing.T) {
|
||||
env.sparkContainer = container
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
func (env *TestEnvironment) Cleanup() {
|
||||
if env.masterProcess != nil && env.masterProcess.Process != nil {
|
||||
_ = env.masterProcess.Process.Kill()
|
||||
_ = env.masterProcess.Wait()
|
||||
}
|
||||
clearMiniProcess(env.masterProcess)
|
||||
if env.weedLogFile != nil {
|
||||
_ = env.weedLogFile.Close()
|
||||
}
|
||||
|
||||
if t.Failed() && os.Getenv("CI") != "" && env.weedLogPath != "" {
|
||||
logData, err := os.ReadFile(env.weedLogPath)
|
||||
if err != nil {
|
||||
t.Logf("failed to read weed mini log file %s: %v", env.weedLogPath, err)
|
||||
} else {
|
||||
// Print the tail to keep CI output manageable while preserving failure context.
|
||||
const maxTailBytes = 64 * 1024
|
||||
start := 0
|
||||
if len(logData) > maxTailBytes {
|
||||
start = len(logData) - maxTailBytes
|
||||
}
|
||||
t.Logf("weed mini logs (tail, %d bytes):\n%s", len(logData)-start, string(logData[start:]))
|
||||
}
|
||||
}
|
||||
|
||||
if env.sparkContainer != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
@@ -43,15 +43,16 @@ func hasDocker() bool {
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
// getFreePort returns an available ephemeral port and its listener
|
||||
func getFreePort() (int, net.Listener, error) {
|
||||
// getFreePort returns an available ephemeral port
|
||||
func getFreePort() (int, error) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
return 0, err
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
addr := listener.Addr().(*net.TCPAddr)
|
||||
return addr.Port, listener, nil
|
||||
return addr.Port, nil
|
||||
}
|
||||
|
||||
// NewTestEnvironment creates a new test environment
|
||||
@@ -90,67 +91,43 @@ func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
}
|
||||
|
||||
// Allocate free ephemeral ports for each service
|
||||
var listeners []net.Listener
|
||||
defer func() {
|
||||
for _, l := range listeners {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
var l net.Listener
|
||||
s3Port, l, err := getFreePort()
|
||||
s3Port, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for S3: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
icebergPort, l, err := getFreePort()
|
||||
icebergPort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Iceberg: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
s3GrpcPort, l, err := getFreePort()
|
||||
s3GrpcPort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for S3 gRPC: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
masterPort, l, err := getFreePort()
|
||||
masterPort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Master: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
masterGrpcPort, l, err := getFreePort()
|
||||
masterGrpcPort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Master gRPC: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
filerPort, l, err := getFreePort()
|
||||
filerPort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Filer: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
filerGrpcPort, l, err := getFreePort()
|
||||
filerGrpcPort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Filer gRPC: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
volumePort, l, err := getFreePort()
|
||||
volumePort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Volume: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
volumeGrpcPort, l, err := getFreePort()
|
||||
volumeGrpcPort, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Volume gRPC: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
return &TestEnvironment{
|
||||
seaweedDir: seaweedDir,
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
package catalog_risingwave
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRisingWaveIcebergCatalog(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
if !env.dockerAvailable {
|
||||
t.Skip("Docker not available, skipping RisingWave integration test")
|
||||
}
|
||||
|
||||
t.Log(">>> Starting SeaweedFS...")
|
||||
env.StartSeaweedFS(t)
|
||||
t.Log(">>> SeaweedFS started.")
|
||||
|
||||
tableBucket := "iceberg-tables"
|
||||
t.Logf(">>> Creating table bucket: %s", tableBucket)
|
||||
createTableBucket(t, env, tableBucket)
|
||||
|
||||
t.Log(">>> Starting RisingWave...")
|
||||
env.StartRisingWave(t)
|
||||
t.Log(">>> RisingWave started.")
|
||||
|
||||
// Create Iceberg namespace
|
||||
createIcebergNamespace(t, env, "default")
|
||||
|
||||
// Create a catalog in RisingWave that points to SeaweedFS Iceberg REST API
|
||||
icebergUri := env.dockerIcebergEndpoint()
|
||||
s3Endpoint := env.dockerS3Endpoint()
|
||||
|
||||
tableName := "test_table_" + randomString(6)
|
||||
createIcebergTable(t, env, tableBucket, "default", tableName)
|
||||
|
||||
sourceName := "test_source_" + randomString(6)
|
||||
createSourceSql := fmt.Sprintf(`
|
||||
CREATE SOURCE %s WITH (
|
||||
connector = 'iceberg',
|
||||
catalog.type = 'rest',
|
||||
catalog.uri = '%s',
|
||||
catalog.name = 'default',
|
||||
database.name = 'default',
|
||||
table.name = '%s',
|
||||
warehouse.path = 's3://%s',
|
||||
s3.endpoint = '%s',
|
||||
s3.region = 'us-east-1',
|
||||
s3.access.key = '%s',
|
||||
s3.secret.key = '%s',
|
||||
s3.path.style.access = 'true',
|
||||
catalog.rest.sigv4_enabled = 'true',
|
||||
catalog.rest.signing_region = 'us-east-1',
|
||||
catalog.rest.signing_name = 's3'
|
||||
);`, sourceName, icebergUri, tableName, tableBucket, s3Endpoint, env.accessKey, env.secretKey)
|
||||
|
||||
t.Logf(">>> Creating source %s...", sourceName)
|
||||
runRisingWaveSQL(t, env.postgresSidecar, createSourceSql)
|
||||
|
||||
showSourcesOutput := runRisingWaveSQL(t, env.postgresSidecar, "SHOW SOURCES;")
|
||||
if !strings.Contains(showSourcesOutput, sourceName) {
|
||||
t.Fatalf("Expected source %s in SHOW SOURCES output:\n%s", sourceName, showSourcesOutput)
|
||||
}
|
||||
|
||||
describeOutput := runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("DESCRIBE %s;", sourceName))
|
||||
if !strings.Contains(describeOutput, "id") || !strings.Contains(describeOutput, "name") {
|
||||
t.Fatalf("Expected id/name columns in DESCRIBE output:\n%s", describeOutput)
|
||||
}
|
||||
|
||||
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("SELECT * FROM %s LIMIT 0;", sourceName))
|
||||
|
||||
t.Log(">>> RisingWave Iceberg Catalog test passed!")
|
||||
}
|
||||
@@ -1,481 +0,0 @@
|
||||
package catalog_risingwave
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/seaweedfs/seaweedfs/test/s3tables/testutil"
|
||||
)
|
||||
|
||||
var (
|
||||
miniProcessMu sync.Mutex
|
||||
lastMiniProcess *exec.Cmd
|
||||
)
|
||||
|
||||
func stopPreviousMini() {
|
||||
miniProcessMu.Lock()
|
||||
defer miniProcessMu.Unlock()
|
||||
|
||||
if lastMiniProcess != nil && lastMiniProcess.Process != nil {
|
||||
_ = lastMiniProcess.Process.Kill()
|
||||
_ = lastMiniProcess.Wait()
|
||||
}
|
||||
lastMiniProcess = nil
|
||||
}
|
||||
|
||||
func registerMiniProcess(cmd *exec.Cmd) {
|
||||
miniProcessMu.Lock()
|
||||
lastMiniProcess = cmd
|
||||
miniProcessMu.Unlock()
|
||||
}
|
||||
|
||||
func clearMiniProcess(cmd *exec.Cmd) {
|
||||
miniProcessMu.Lock()
|
||||
if lastMiniProcess == cmd {
|
||||
lastMiniProcess = nil
|
||||
}
|
||||
miniProcessMu.Unlock()
|
||||
}
|
||||
|
||||
type TestEnvironment struct {
|
||||
t *testing.T
|
||||
dockerAvailable bool
|
||||
seaweedfsDataDir string
|
||||
masterPort int
|
||||
filerPort int
|
||||
s3Port int
|
||||
icebergRestPort int
|
||||
risingwavePort int
|
||||
bindIP string
|
||||
accessKey string
|
||||
secretKey string
|
||||
risingwaveContainer string
|
||||
postgresSidecar string
|
||||
masterProcess *exec.Cmd
|
||||
logFile *os.File
|
||||
}
|
||||
|
||||
func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
env := &TestEnvironment{
|
||||
t: t,
|
||||
accessKey: "AKIAIOSFODNN7EXAMPLE",
|
||||
secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
|
||||
}
|
||||
|
||||
// Check if Docker is available
|
||||
cmd := exec.Command("docker", "version")
|
||||
env.dockerAvailable = cmd.Run() == nil
|
||||
|
||||
return env
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) hostMasterAddress() string {
|
||||
return fmt.Sprintf("127.0.0.1:%d", env.masterPort)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) hostS3Endpoint() string {
|
||||
return fmt.Sprintf("http://127.0.0.1:%d", env.s3Port)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) hostIcebergEndpoint() string {
|
||||
return fmt.Sprintf("http://127.0.0.1:%d", env.icebergRestPort)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) dockerS3Endpoint() string {
|
||||
return fmt.Sprintf("http://host.docker.internal:%d", env.s3Port)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) dockerIcebergEndpoint() string {
|
||||
return fmt.Sprintf("http://host.docker.internal:%d", env.icebergRestPort)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
stopPreviousMini()
|
||||
|
||||
var err error
|
||||
env.seaweedfsDataDir, err = os.MkdirTemp("", "seaweed-risingwave-test-")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp directory: %v", err)
|
||||
}
|
||||
|
||||
env.masterPort = mustFreePort(t, "Master")
|
||||
env.filerPort = mustFreePort(t, "Filer")
|
||||
env.s3Port = mustFreePort(t, "S3")
|
||||
env.icebergRestPort = mustFreePort(t, "Iceberg")
|
||||
env.risingwavePort = mustFreePort(t, "RisingWave")
|
||||
|
||||
env.bindIP = testutil.FindBindIP()
|
||||
|
||||
iamConfigPath, err := testutil.WriteIAMConfig(env.seaweedfsDataDir, env.accessKey, env.secretKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create IAM config: %v", err)
|
||||
}
|
||||
|
||||
// Create log file for SeaweedFS
|
||||
logFile, err := os.Create(filepath.Join(env.seaweedfsDataDir, "seaweedfs.log"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create log file: %v", err)
|
||||
}
|
||||
env.logFile = logFile
|
||||
|
||||
// Start SeaweedFS using weed mini (all-in-one including Iceberg REST)
|
||||
env.masterProcess = exec.Command(
|
||||
"weed", "mini",
|
||||
"-ip", env.bindIP,
|
||||
"-ip.bind", "0.0.0.0",
|
||||
"-master.port", fmt.Sprintf("%d", env.masterPort),
|
||||
"-filer.port", fmt.Sprintf("%d", env.filerPort),
|
||||
"-s3.port", fmt.Sprintf("%d", env.s3Port),
|
||||
"-s3.port.iceberg", fmt.Sprintf("%d", env.icebergRestPort),
|
||||
"-s3.config", iamConfigPath,
|
||||
"-dir", env.seaweedfsDataDir,
|
||||
)
|
||||
env.masterProcess.Stdout = logFile
|
||||
env.masterProcess.Stderr = logFile
|
||||
env.masterProcess.Env = append(os.Environ(),
|
||||
"AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
"ICEBERG_WAREHOUSE=s3://iceberg-tables",
|
||||
"S3TABLES_DEFAULT_BUCKET=iceberg-tables",
|
||||
)
|
||||
if err := env.masterProcess.Start(); err != nil {
|
||||
t.Fatalf("failed to start weed mini: %v", err)
|
||||
}
|
||||
registerMiniProcess(env.masterProcess)
|
||||
|
||||
// Wait for all services to be ready
|
||||
if !waitForPort(env.masterPort, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - master port %d not listening", env.masterPort)
|
||||
}
|
||||
if !waitForPort(env.filerPort, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - filer port %d not listening", env.filerPort)
|
||||
}
|
||||
if !waitForPort(env.s3Port, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - s3 port %d not listening", env.s3Port)
|
||||
}
|
||||
if !waitForPort(env.icebergRestPort, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - iceberg rest port %d not listening", env.icebergRestPort)
|
||||
}
|
||||
}
|
||||
|
||||
func mustFreePort(t *testing.T, name string) int {
|
||||
t.Helper()
|
||||
minPort := 10000
|
||||
maxPort := 55000 // Ensure port+10000 < 65535
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
for i := 0; i < 1000; i++ {
|
||||
port := minPort + r.Intn(maxPort-minPort)
|
||||
|
||||
// Check http port
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ln.Close()
|
||||
|
||||
// Check grpc port (weed mini uses port+10000)
|
||||
ln2, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port+10000))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ln2.Close()
|
||||
|
||||
return port
|
||||
}
|
||||
t.Fatalf("failed to find a free port < %d for %s after 1000 attempts", maxPort, name)
|
||||
return 0
|
||||
}
|
||||
|
||||
func waitForPort(port int, timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
conn, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), 500*time.Millisecond)
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
return true
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) StartRisingWave(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
containerName := "seaweed-risingwave-" + randomString(8)
|
||||
env.risingwaveContainer = containerName
|
||||
|
||||
cmd := exec.Command("docker", "run", "-d",
|
||||
"--name", containerName,
|
||||
"-p", fmt.Sprintf("%d:4566", env.risingwavePort),
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-e", "AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"-e", "AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
"-e", "AWS_REGION=us-east-1",
|
||||
"-e", "AWS_S3_PATH_STYLE_ACCESS=true",
|
||||
"-e", "AWS_S3_FORCE_PATH_STYLE=true",
|
||||
"risingwavelabs/risingwave:v2.5.0",
|
||||
"playground",
|
||||
)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to start RisingWave container: %v\n%s", err, string(output))
|
||||
}
|
||||
|
||||
// Start a sidecar postgres container for running psql commands
|
||||
sidecarName := "seaweed-risingwave-sidecar-" + randomString(8)
|
||||
env.postgresSidecar = sidecarName
|
||||
sidecarCmd := exec.Command("docker", "run", "-d", "--rm",
|
||||
"--name", sidecarName,
|
||||
"--network", fmt.Sprintf("container:%s", containerName),
|
||||
"postgres:16-alpine",
|
||||
"sleep", "infinity",
|
||||
)
|
||||
if output, err := sidecarCmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to start postgres sidecar: %v\n%s", err, string(output))
|
||||
}
|
||||
|
||||
// Wait for RisingWave port to be open on host
|
||||
if !waitForPort(env.risingwavePort, 120*time.Second) {
|
||||
t.Fatalf("timed out waiting for RisingWave port %d to be open", env.risingwavePort)
|
||||
}
|
||||
|
||||
// Wait for RisingWave to be truly ready via psql in the sidecar.
|
||||
if !env.waitForRisingWave(120 * time.Second) {
|
||||
t.Fatalf("timed out waiting for RisingWave to be ready via psql")
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) waitForRisingWave(timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
env.t.Logf(">>> Waiting for RisingWave to be ready (timeout %v)...\n", timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if output, err := runPostgresClientSQL(env.postgresSidecar, "SELECT 1;"); err == nil {
|
||||
env.t.Logf(">>> RisingWave is ready.\n")
|
||||
return true
|
||||
} else {
|
||||
env.t.Logf(">>> RisingWave not ready yet: %v (Output: %s)\n", err, string(output))
|
||||
}
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func runPostgresClientSQL(containerName, sql string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, "docker", "exec",
|
||||
containerName,
|
||||
"psql",
|
||||
"-h", "127.0.0.1",
|
||||
"-p", "4566",
|
||||
"-U", "root",
|
||||
"-d", "dev",
|
||||
"-v", "ON_ERROR_STOP=1",
|
||||
"-c", sql,
|
||||
)
|
||||
return cmd.CombinedOutput()
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if env.risingwaveContainer != "" {
|
||||
if t.Failed() {
|
||||
logs, err := exec.Command("docker", "logs", env.risingwaveContainer).CombinedOutput()
|
||||
if err == nil {
|
||||
env.t.Logf(">>> RisingWave Logs:\n%s\n", string(logs))
|
||||
} else {
|
||||
env.t.Logf(">>> Failed to get RisingWave logs: %v\n", err)
|
||||
}
|
||||
}
|
||||
_ = exec.Command("docker", "rm", "-f", env.risingwaveContainer).Run()
|
||||
}
|
||||
|
||||
if env.postgresSidecar != "" {
|
||||
_ = exec.Command("docker", "rm", "-f", env.postgresSidecar).Run()
|
||||
}
|
||||
|
||||
if env.seaweedfsDataDir != "" && t.Failed() {
|
||||
logPath := filepath.Join(env.seaweedfsDataDir, "seaweedfs.log")
|
||||
if content, err := os.ReadFile(logPath); err == nil {
|
||||
env.t.Logf(">>> SeaweedFS Logs:\n%s\n", string(content))
|
||||
}
|
||||
env.t.Logf(">>> Filer Contents:\n")
|
||||
listFilerContents(t, env, "/")
|
||||
}
|
||||
|
||||
if env.masterProcess != nil && env.masterProcess.Process != nil {
|
||||
_ = env.masterProcess.Process.Kill()
|
||||
_ = env.masterProcess.Wait()
|
||||
}
|
||||
clearMiniProcess(env.masterProcess)
|
||||
|
||||
if env.seaweedfsDataDir != "" {
|
||||
if env.logFile != nil {
|
||||
env.logFile.Close()
|
||||
}
|
||||
_ = os.RemoveAll(env.seaweedfsDataDir)
|
||||
}
|
||||
}
|
||||
|
||||
func runRisingWaveSQL(t *testing.T, containerName, sql string) string {
|
||||
t.Helper()
|
||||
|
||||
output, err := runPostgresClientSQL(containerName, sql)
|
||||
if err != nil {
|
||||
t.Fatalf("RisingWave command failed: %v\nSQL: %s\nOutput:\n%s", err, sql, string(output))
|
||||
}
|
||||
return string(output)
|
||||
}
|
||||
|
||||
func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Helper()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, "weed", "shell",
|
||||
fmt.Sprintf("-master=%s", env.hostMasterAddress()),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("s3tables.bucket -create -name %s -account 000000000000\nexit\n", bucketName))
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create table bucket %s via weed shell: %v\nOutput: %s", bucketName, err, string(output))
|
||||
}
|
||||
}
|
||||
|
||||
func doIcebergSignedJSONRequest(env *TestEnvironment, method, path string, payload any) (int, string, error) {
|
||||
url := env.hostIcebergEndpoint() + path
|
||||
|
||||
var body io.Reader
|
||||
var payloadHash string
|
||||
|
||||
if payload != nil {
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
body = bytes.NewReader(data)
|
||||
// hash := sha256.Sum256(data)
|
||||
// payloadHash = hex.EncodeToString(hash[:])
|
||||
payloadHash = "UNSIGNED-PAYLOAD"
|
||||
} else {
|
||||
payloadHash = "UNSIGNED-PAYLOAD"
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, url, body)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("X-Amz-Content-Sha256", payloadHash)
|
||||
|
||||
// Sign the request
|
||||
credsProvider := credentials.NewStaticCredentialsProvider(env.accessKey, env.secretKey, "")
|
||||
creds, err := credsProvider.Retrieve(context.Background())
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("failed to retrieve credentials: %w", err)
|
||||
}
|
||||
signer := v4.NewSigner()
|
||||
|
||||
if err := signer.SignHTTP(context.Background(), creds, req, payloadHash, "s3", "us-east-1", time.Now()); err != nil {
|
||||
return 0, "", fmt.Errorf("failed to sign request: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
return resp.StatusCode, string(respBody), nil
|
||||
}
|
||||
|
||||
func createIcebergNamespace(t *testing.T, env *TestEnvironment, namespace string) {
|
||||
t.Helper()
|
||||
|
||||
status, raw, err := doIcebergSignedJSONRequest(env, "POST", "/v1/namespaces", map[string]any{
|
||||
"namespace": []string{namespace},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Iceberg namespace %s: %v", namespace, err)
|
||||
}
|
||||
if status != 200 && status != 409 {
|
||||
t.Fatalf("failed to create Iceberg namespace %s: status %d body: %s", namespace, status, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func createIcebergTable(t *testing.T, env *TestEnvironment, bucketName, namespace, tableName string) {
|
||||
t.Helper()
|
||||
|
||||
createPath := fmt.Sprintf("/v1/namespaces/%s/tables", namespace)
|
||||
status, raw, err := doIcebergSignedJSONRequest(env, "POST", createPath, map[string]any{
|
||||
"name": tableName,
|
||||
"location": fmt.Sprintf("s3://%s/%s/%s", bucketName, namespace, tableName),
|
||||
"schema": map[string]any{
|
||||
"type": "struct",
|
||||
"fields": []map[string]any{
|
||||
{"id": 1, "name": "id", "required": false, "type": "int"},
|
||||
{"id": 2, "name": "name", "required": false, "type": "string"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Iceberg table %s.%s in bucket %s: %v", namespace, tableName, bucketName, err)
|
||||
}
|
||||
if status != 200 && status != 409 {
|
||||
t.Fatalf("failed to create Iceberg table %s.%s in bucket %s: status %d body: %s", namespace, tableName, bucketName, status, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func listFilerContents(t *testing.T, env *TestEnvironment, path string) {
|
||||
t.Helper()
|
||||
|
||||
cmd := exec.Command("weed", "shell",
|
||||
fmt.Sprintf("-master=%s", env.hostMasterAddress()),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("fs.ls -R %s\nexit\n", path))
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
env.t.Logf(">>> Warning: failed to list filer contents: %v\nOutput: %s\n", err, string(output))
|
||||
} else {
|
||||
env.t.Logf("%s\n", string(output))
|
||||
}
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = letters[rand.Intn(len(letters))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
package sts_integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/s3tables/testutil"
|
||||
)
|
||||
|
||||
// TestEnvironment mirrors the one in trino_catalog_test.go but simplified
|
||||
type TestEnvironment struct {
|
||||
seaweedDir string
|
||||
weedBinary string
|
||||
dataDir string
|
||||
bindIP string
|
||||
s3Port int
|
||||
s3GrpcPort int
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
filerPort int
|
||||
filerGrpcPort int
|
||||
volumePort int
|
||||
volumeGrpcPort int
|
||||
weedProcess *exec.Cmd
|
||||
weedCancel context.CancelFunc
|
||||
dockerAvailable bool
|
||||
accessKey string
|
||||
secretKey string
|
||||
}
|
||||
|
||||
func TestSTSIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
if !env.dockerAvailable {
|
||||
t.Skip("Docker not available, skipping STS integration test")
|
||||
}
|
||||
|
||||
fmt.Printf(">>> Starting SeaweedFS...\n")
|
||||
env.StartSeaweedFS(t)
|
||||
fmt.Printf(">>> SeaweedFS started.\n")
|
||||
|
||||
// Run python script in docker to test STS
|
||||
runPythonSTSClient(t, env)
|
||||
}
|
||||
|
||||
func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
t.Helper()
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get working directory: %v", err)
|
||||
}
|
||||
|
||||
seaweedDir := wd
|
||||
for i := 0; i < 6; i++ {
|
||||
if _, err := os.Stat(filepath.Join(seaweedDir, "go.mod")); err == nil {
|
||||
break
|
||||
}
|
||||
seaweedDir = filepath.Dir(seaweedDir)
|
||||
}
|
||||
|
||||
weedBinary := filepath.Join(seaweedDir, "weed", "weed")
|
||||
info, err := os.Stat(weedBinary)
|
||||
if err != nil || info.IsDir() {
|
||||
weedBinary = "weed"
|
||||
if _, err := exec.LookPath(weedBinary); err != nil {
|
||||
t.Skip("weed binary not found, skipping integration test")
|
||||
}
|
||||
}
|
||||
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("Docker not available, skipping integration test")
|
||||
}
|
||||
|
||||
// Create a unique temporary directory for this test run
|
||||
dataDir, err := os.MkdirTemp("", "seaweed-sts-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
// The Cleanup method will remove this directory, so no need for defer here.
|
||||
|
||||
bindIP := testutil.FindBindIP()
|
||||
|
||||
masterPort, masterGrpcPort := testutil.MustFreePortPair(t, "Master")
|
||||
volumePort, volumeGrpcPort := testutil.MustFreePortPair(t, "Volume")
|
||||
filerPort, filerGrpcPort := testutil.MustFreePortPair(t, "Filer")
|
||||
s3Port, s3GrpcPort := testutil.MustFreePortPair(t, "S3") // Changed to use testutil.MustFreePortPair
|
||||
|
||||
return &TestEnvironment{
|
||||
seaweedDir: seaweedDir,
|
||||
weedBinary: weedBinary,
|
||||
dataDir: dataDir,
|
||||
bindIP: bindIP,
|
||||
s3Port: s3Port,
|
||||
s3GrpcPort: s3GrpcPort,
|
||||
masterPort: masterPort,
|
||||
masterGrpcPort: masterGrpcPort,
|
||||
filerPort: filerPort,
|
||||
filerGrpcPort: filerGrpcPort,
|
||||
volumePort: volumePort,
|
||||
volumeGrpcPort: volumeGrpcPort,
|
||||
dockerAvailable: testutil.HasDocker(),
|
||||
accessKey: "admin", // Matching default in testutil.WriteIAMConfig
|
||||
secretKey: "admin",
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
// Create IAM config file
|
||||
iamConfigPath, err := testutil.WriteIAMConfig(env.dataDir, env.accessKey, env.secretKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create IAM config: %v", err)
|
||||
}
|
||||
|
||||
// Create empty security.toml
|
||||
securityToml := filepath.Join(env.dataDir, "security.toml")
|
||||
if err := os.WriteFile(securityToml, []byte("# Empty security config for testing\n"), 0644); err != nil {
|
||||
t.Fatalf("Failed to create security.toml: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
env.weedCancel = cancel
|
||||
|
||||
cmd := exec.CommandContext(ctx, env.weedBinary, "mini",
|
||||
"-master.port", fmt.Sprintf("%d", env.masterPort),
|
||||
"-master.port.grpc", fmt.Sprintf("%d", env.masterGrpcPort),
|
||||
"-volume.port", fmt.Sprintf("%d", env.volumePort),
|
||||
"-volume.port.grpc", fmt.Sprintf("%d", env.volumeGrpcPort),
|
||||
"-filer.port", fmt.Sprintf("%d", env.filerPort),
|
||||
"-filer.port.grpc", fmt.Sprintf("%d", env.filerGrpcPort),
|
||||
"-s3.port", fmt.Sprintf("%d", env.s3Port),
|
||||
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
|
||||
"-s3.config", iamConfigPath,
|
||||
"-ip", env.bindIP,
|
||||
"-ip.bind", "0.0.0.0",
|
||||
"-dir", env.dataDir,
|
||||
)
|
||||
cmd.Dir = env.dataDir
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("Failed to start SeaweedFS: %v", err)
|
||||
}
|
||||
env.weedProcess = cmd
|
||||
|
||||
// Wait for S3 API to be ready
|
||||
if !testutil.WaitForService(fmt.Sprintf("http://localhost:%d/status", env.s3Port), 30*time.Second) {
|
||||
t.Fatalf("S3 API failed to become ready")
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Start(t *testing.T) {
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("Docker not available")
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
t.Helper()
|
||||
if env.weedCancel != nil {
|
||||
env.weedCancel()
|
||||
}
|
||||
if env.weedProcess != nil {
|
||||
time.Sleep(1 * time.Second)
|
||||
_ = env.weedProcess.Wait()
|
||||
}
|
||||
if env.dataDir != "" {
|
||||
_ = os.RemoveAll(env.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
func runPythonSTSClient(t *testing.T, env *TestEnvironment) {
|
||||
t.Helper()
|
||||
|
||||
// Write python script to temp dir
|
||||
scriptContent := fmt.Sprintf(`
|
||||
import boto3
|
||||
import botocore.config
|
||||
from botocore.exceptions import ClientError
|
||||
import os
|
||||
import sys
|
||||
|
||||
print("Starting STS test...")
|
||||
|
||||
endpoint_url = "http://host.docker.internal:%d"
|
||||
access_key = "%s"
|
||||
secret_key = "%s"
|
||||
region = "us-east-1"
|
||||
|
||||
print(f"Connecting to {endpoint_url} with key {access_key}")
|
||||
|
||||
try:
|
||||
config = botocore.config.Config(
|
||||
retries={'max_attempts': 0}
|
||||
)
|
||||
sts = boto3.client(
|
||||
'sts',
|
||||
endpoint_url=endpoint_url,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
region_name=region,
|
||||
config=config
|
||||
)
|
||||
|
||||
role_arn = "arn:aws:iam::000000000000:role/test-role"
|
||||
session_name = "test-session"
|
||||
|
||||
print(f"Calling AssumeRole on {role_arn}")
|
||||
|
||||
# This call typically sends parameters in POST body by default in boto3
|
||||
response = sts.assume_role(
|
||||
RoleArn=role_arn,
|
||||
RoleSessionName=session_name
|
||||
)
|
||||
|
||||
print("Success! Got credentials:")
|
||||
print(response['Credentials'])
|
||||
|
||||
except ClientError as e:
|
||||
# Print available keys for debugging if needed
|
||||
# print(e.response.keys())
|
||||
|
||||
response_meta = e.response.get('ResponseMetadata', {})
|
||||
http_code = response_meta.get('HTTPStatusCode')
|
||||
|
||||
error_data = e.response.get('Error', {})
|
||||
error_code = error_data.get('Code', 'Unknown')
|
||||
|
||||
print(f"Got error: {http_code} {error_code}")
|
||||
|
||||
# We expect 503 ServiceUnavailable because stsHandlers is nil in weed mini
|
||||
# This confirms the request was routed to STS handler logic (UnifiedPostHandler)
|
||||
# instead of IAM handler (which would return 403 AccessDenied or 501 NotImplemented)
|
||||
if http_code == 503:
|
||||
print("SUCCESS: Got expected 503 Service Unavailable (STS not configured)")
|
||||
sys.exit(0)
|
||||
|
||||
print(f"FAILED: Unexpected error {e}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"FAILED: {e}")
|
||||
sys.exit(1)
|
||||
`, env.s3Port, env.accessKey, env.secretKey)
|
||||
|
||||
scriptPath := filepath.Join(env.dataDir, "sts_test.py")
|
||||
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0644); err != nil {
|
||||
t.Fatalf("Failed to write python script: %v", err)
|
||||
}
|
||||
|
||||
containerName := "seaweed-sts-client-" + fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
|
||||
cmd := exec.Command("docker", "run", "--rm",
|
||||
"--name", containerName,
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-v", fmt.Sprintf("%s:/work", env.dataDir),
|
||||
"python:3",
|
||||
"/bin/bash", "-c", "pip install boto3 && python /work/sts_test.py",
|
||||
)
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("Python STS client failed: %v\nOutput:\n%s", err, string(output))
|
||||
}
|
||||
t.Logf("Python STS client output:\n%s", string(output))
|
||||
}
|
||||
|
||||
// Helpers copied from trino_catalog_test.go
|
||||
@@ -1,66 +0,0 @@
|
||||
package testutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func HasDocker() bool {
|
||||
cmd := exec.Command("docker", "version")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
func MustFreePortPair(t *testing.T, name string) (int, int) {
|
||||
httpPort, grpcPort, err := findAvailablePortPair()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port pair for %s: %v", name, err)
|
||||
}
|
||||
return httpPort, grpcPort
|
||||
}
|
||||
|
||||
func findAvailablePortPair() (int, int, error) {
|
||||
httpPort, err := GetFreePort()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
grpcPort, err := GetFreePort()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return httpPort, grpcPort, nil
|
||||
}
|
||||
|
||||
func GetFreePort() (int, error) {
|
||||
listener, err := net.Listen("tcp", "0.0.0.0:0")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer listener.Close()
|
||||
return listener.Addr().(*net.TCPAddr).Port, nil
|
||||
}
|
||||
|
||||
func WaitForService(url string, timeout time.Duration) bool {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
ticker := time.NewTicker(500 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-ticker.C:
|
||||
resp, err := client.Get(url)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -579,6 +579,9 @@ func (s *AdminServer) ListS3TablesBucketsAPI(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (s *AdminServer) CreateS3TablesBucket(c *gin.Context) {
|
||||
if !requireSessionCSRFToken(c) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Tags map[string]string `json:"tags"`
|
||||
@@ -664,6 +667,9 @@ func (s *AdminServer) SetTableBucketOwner(ctx context.Context, bucketName, owner
|
||||
}
|
||||
|
||||
func (s *AdminServer) DeleteS3TablesBucket(c *gin.Context) {
|
||||
if !requireSessionCSRFToken(c) {
|
||||
return
|
||||
}
|
||||
bucketArn := c.Query("bucket")
|
||||
if bucketArn == "" {
|
||||
c.JSON(400, gin.H{"error": "Bucket ARN is required"})
|
||||
|
||||
@@ -390,10 +390,11 @@ func (option *RemoteGatewayOptions) detectBucketInfo(actualDir string) (bucket u
|
||||
}
|
||||
|
||||
func extractBucketPath(bucketsDir, dir string) (util.FullPath, bool) {
|
||||
if bucketPath, ok := util.ExtractBucketPath(bucketsDir, dir, false); ok {
|
||||
return util.FullPath(bucketPath), true
|
||||
if !strings.HasPrefix(dir, bucketsDir+"/") {
|
||||
return "", false
|
||||
}
|
||||
return "", false
|
||||
parts := strings.SplitN(dir[len(bucketsDir)+1:], "/", 2)
|
||||
return util.FullPath(bucketsDir).Child(parts[0]), true
|
||||
}
|
||||
|
||||
func (option *RemoteGatewayOptions) collectRemoteStorageConf() (err error) {
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/user"
|
||||
"path"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -27,7 +26,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"google.golang.org/grpc/reflection"
|
||||
@@ -61,63 +59,6 @@ func runMount(cmd *Command, args []string) bool {
|
||||
return RunMount(&mountOptions, os.FileMode(umask))
|
||||
}
|
||||
|
||||
func ensureBucketAllowEmptyFolders(ctx context.Context, filerClient filer_pb.FilerClient, mountRoot, bucketRootPath string) error {
|
||||
bucketPath, isBucketRootMount := bucketPathForMountRoot(mountRoot, bucketRootPath)
|
||||
if !isBucketRootMount {
|
||||
return nil
|
||||
}
|
||||
|
||||
entry, err := filer_pb.GetEntry(ctx, filerClient, util.FullPath(bucketPath))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry == nil {
|
||||
return fmt.Errorf("bucket %s not found", bucketPath)
|
||||
}
|
||||
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(string(entry.Extended[s3_constants.ExtAllowEmptyFolders])), "true") {
|
||||
return nil
|
||||
}
|
||||
|
||||
entry.Extended[s3_constants.ExtAllowEmptyFolders] = []byte("true")
|
||||
|
||||
bucketFullPath := util.FullPath(bucketPath)
|
||||
parent, _ := bucketFullPath.DirAndName()
|
||||
if err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
|
||||
Directory: parent,
|
||||
Entry: entry,
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glog.V(3).Infof("RunMount: set bucket %s %s=true", bucketPath, s3_constants.ExtAllowEmptyFolders)
|
||||
return nil
|
||||
}
|
||||
|
||||
func bucketPathForMountRoot(mountRoot, bucketRootPath string) (string, bool) {
|
||||
cleanPath := path.Clean("/" + strings.TrimPrefix(mountRoot, "/"))
|
||||
cleanBucketRoot := path.Clean("/" + strings.TrimPrefix(bucketRootPath, "/"))
|
||||
if cleanBucketRoot == "/" {
|
||||
return "", false
|
||||
}
|
||||
prefix := cleanBucketRoot + "/"
|
||||
if !strings.HasPrefix(cleanPath, prefix) {
|
||||
return "", false
|
||||
}
|
||||
rest := strings.TrimPrefix(cleanPath, prefix)
|
||||
|
||||
bucketParts := strings.Split(rest, "/")
|
||||
if len(bucketParts) != 1 || bucketParts[0] == "" {
|
||||
return "", false
|
||||
}
|
||||
return cleanBucketRoot + "/" + bucketParts[0], true
|
||||
}
|
||||
|
||||
func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
|
||||
// basic checks
|
||||
@@ -132,7 +73,6 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
var cipher bool
|
||||
var bucketRootPath string
|
||||
var err error
|
||||
for i := 0; i < 10; i++ {
|
||||
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
@@ -141,7 +81,6 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err)
|
||||
}
|
||||
cipher = resp.Cipher
|
||||
bucketRootPath = resp.DirBuckets
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -154,9 +93,6 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
glog.Errorf("failed to talk to filer %v: %v", filerAddresses, err)
|
||||
return true
|
||||
}
|
||||
if bucketRootPath == "" {
|
||||
bucketRootPath = "/buckets"
|
||||
}
|
||||
|
||||
filerMountRootPath := *option.filerMountRootPath
|
||||
|
||||
@@ -351,10 +287,6 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
fmt.Printf("failed to create dir %s on filer %s: %v\n", mountRoot, filerAddresses, err)
|
||||
return false
|
||||
}
|
||||
if err := ensureBucketAllowEmptyFolders(context.Background(), seaweedFileSystem, mountRoot, bucketRootPath); err != nil {
|
||||
fmt.Printf("failed to set bucket auto-remove-empty-folders policy for %s: %v\n", mountRoot, err)
|
||||
return false
|
||||
}
|
||||
|
||||
server, err := fuse.NewServer(seaweedFileSystem, dir, fuseMountOptions)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
//go:build linux || darwin || freebsd
|
||||
// +build linux darwin freebsd
|
||||
|
||||
package command
|
||||
|
||||
import "testing"
|
||||
|
||||
func Test_bucketPathForMountRoot(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mountRoot string
|
||||
expected string
|
||||
ok bool
|
||||
}{
|
||||
{
|
||||
name: "bucket root mount",
|
||||
mountRoot: "/buckets/test",
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "bucket root with trailing slash",
|
||||
mountRoot: "/buckets/test/",
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "subdirectory mount",
|
||||
mountRoot: "/buckets/test/data",
|
||||
expected: "",
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "non-bucket mount",
|
||||
mountRoot: "/data/test",
|
||||
expected: "",
|
||||
ok: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotPath, gotOK := bucketPathForMountRoot(tt.mountRoot, "/buckets")
|
||||
if gotOK != tt.ok {
|
||||
t.Fatalf("expected ok=%v, got %v", tt.ok, gotOK)
|
||||
}
|
||||
if gotPath != tt.expected {
|
||||
t.Fatalf("expected path %q, got %q", tt.expected, gotPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -21,9 +21,8 @@ type CleanupQueue struct {
|
||||
|
||||
// queueItem represents an item in the cleanup queue
|
||||
type queueItem struct {
|
||||
folder string
|
||||
triggeredBy string
|
||||
queueTime time.Time
|
||||
folder string
|
||||
queueTime time.Time
|
||||
}
|
||||
|
||||
// NewCleanupQueue creates a new CleanupQueue with the specified limits
|
||||
@@ -40,7 +39,7 @@ func NewCleanupQueue(maxSize int, maxAge time.Duration) *CleanupQueue {
|
||||
// The item is inserted in time-sorted order (oldest at front) to handle out-of-order events.
|
||||
// If folder already exists with an older time, the time is updated and position adjusted.
|
||||
// Returns true if the folder was newly added, false if it was updated.
|
||||
func (q *CleanupQueue) Add(folder string, triggeredBy string, eventTime time.Time) bool {
|
||||
func (q *CleanupQueue) Add(folder string, eventTime time.Time) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
|
||||
@@ -52,24 +51,23 @@ func (q *CleanupQueue) Add(folder string, triggeredBy string, eventTime time.Tim
|
||||
// Remove from current position
|
||||
q.items.Remove(elem)
|
||||
// Re-insert with new time in sorted position
|
||||
newElem := q.insertSorted(folder, triggeredBy, eventTime)
|
||||
newElem := q.insertSorted(folder, eventTime)
|
||||
q.itemsMap[folder] = newElem
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Insert new folder in sorted position
|
||||
elem := q.insertSorted(folder, triggeredBy, eventTime)
|
||||
elem := q.insertSorted(folder, eventTime)
|
||||
q.itemsMap[folder] = elem
|
||||
return true
|
||||
}
|
||||
|
||||
// insertSorted inserts an item in the correct position to maintain time ordering (oldest at front)
|
||||
func (q *CleanupQueue) insertSorted(folder string, triggeredBy string, eventTime time.Time) *list.Element {
|
||||
func (q *CleanupQueue) insertSorted(folder string, eventTime time.Time) *list.Element {
|
||||
item := &queueItem{
|
||||
folder: folder,
|
||||
triggeredBy: triggeredBy,
|
||||
queueTime: eventTime,
|
||||
folder: folder,
|
||||
queueTime: eventTime,
|
||||
}
|
||||
|
||||
// Find the correct position (insert before the first item with a later time)
|
||||
@@ -137,35 +135,35 @@ func (q *CleanupQueue) shouldProcessLocked() bool {
|
||||
|
||||
// Pop removes and returns the oldest folder from the queue.
|
||||
// Returns the folder and true if an item was available, or empty string and false if queue is empty.
|
||||
func (q *CleanupQueue) Pop() (string, string, bool) {
|
||||
func (q *CleanupQueue) Pop() (string, bool) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
|
||||
front := q.items.Front()
|
||||
if front == nil {
|
||||
return "", "", false
|
||||
return "", false
|
||||
}
|
||||
|
||||
item := front.Value.(*queueItem)
|
||||
q.items.Remove(front)
|
||||
delete(q.itemsMap, item.folder)
|
||||
|
||||
return item.folder, item.triggeredBy, true
|
||||
return item.folder, true
|
||||
}
|
||||
|
||||
// Peek returns the oldest folder without removing it.
|
||||
// Returns the folder and queue time if available, or empty values if queue is empty.
|
||||
func (q *CleanupQueue) Peek() (folder string, triggeredBy string, queueTime time.Time, ok bool) {
|
||||
func (q *CleanupQueue) Peek() (folder string, queueTime time.Time, ok bool) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
|
||||
front := q.items.Front()
|
||||
if front == nil {
|
||||
return "", "", time.Time{}, false
|
||||
return "", time.Time{}, false
|
||||
}
|
||||
|
||||
item := front.Value.(*queueItem)
|
||||
return item.folder, item.triggeredBy, item.queueTime, true
|
||||
return item.folder, item.queueTime, true
|
||||
}
|
||||
|
||||
// Len returns the current queue size.
|
||||
|
||||
@@ -10,7 +10,7 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
// Add first item
|
||||
if !q.Add("/buckets/b1/folder1", "item1", now) {
|
||||
if !q.Add("/buckets/b1/folder1", now) {
|
||||
t.Error("expected Add to return true for new item")
|
||||
}
|
||||
if q.Len() != 1 {
|
||||
@@ -18,7 +18,7 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
}
|
||||
|
||||
// Add second item with later time
|
||||
if !q.Add("/buckets/b1/folder2", "item2", now.Add(1*time.Second)) {
|
||||
if !q.Add("/buckets/b1/folder2", now.Add(1*time.Second)) {
|
||||
t.Error("expected Add to return true for new item")
|
||||
}
|
||||
if q.Len() != 2 {
|
||||
@@ -26,7 +26,7 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
}
|
||||
|
||||
// Add duplicate with newer time - should update and reposition
|
||||
if q.Add("/buckets/b1/folder1", "item1-updated", now.Add(2*time.Second)) {
|
||||
if q.Add("/buckets/b1/folder1", now.Add(2*time.Second)) {
|
||||
t.Error("expected Add to return false for existing item")
|
||||
}
|
||||
if q.Len() != 2 {
|
||||
@@ -34,14 +34,11 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
}
|
||||
|
||||
// folder1 should now be at the back (newer time) - verify by popping
|
||||
folder1, triggered1, _ := q.Pop()
|
||||
folder2, triggered2, _ := q.Pop()
|
||||
folder1, _ := q.Pop()
|
||||
folder2, _ := q.Pop()
|
||||
if folder1 != "/buckets/b1/folder2" || folder2 != "/buckets/b1/folder1" {
|
||||
t.Errorf("expected folder1 to be moved to back, got %s, %s", folder1, folder2)
|
||||
}
|
||||
if triggered1 != "item2" || triggered2 != "item1-updated" {
|
||||
t.Errorf("triggeredBy mismatch: got %s, %s", triggered1, triggered2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupQueue_Add_OutOfOrder(t *testing.T) {
|
||||
@@ -49,23 +46,16 @@ func TestCleanupQueue_Add_OutOfOrder(t *testing.T) {
|
||||
baseTime := time.Now()
|
||||
|
||||
// Add items out of order
|
||||
q.Add("/buckets/b1/folder3", "f3", baseTime.Add(3*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "f1", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder2", "f2", baseTime.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder3", baseTime.Add(3*time.Second))
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder2", baseTime.Add(2*time.Second))
|
||||
|
||||
// Items should be in time order (oldest first) - verify by popping
|
||||
expected := []struct {
|
||||
folder string
|
||||
item string
|
||||
}{
|
||||
{"/buckets/b1/folder1", "f1"},
|
||||
{"/buckets/b1/folder2", "f2"},
|
||||
{"/buckets/b1/folder3", "f3"},
|
||||
}
|
||||
expected := []string{"/buckets/b1/folder1", "/buckets/b1/folder2", "/buckets/b1/folder3"}
|
||||
for i, exp := range expected {
|
||||
folder, item, ok := q.Pop()
|
||||
if !ok || folder != exp.folder || item != exp.item {
|
||||
t.Errorf("at index %d: expected %s by %s, got %s by %s", i, exp.folder, exp.item, folder, item)
|
||||
folder, ok := q.Pop()
|
||||
if !ok || folder != exp {
|
||||
t.Errorf("at index %d: expected %s, got %s", i, exp, folder)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,15 +65,15 @@ func TestCleanupQueue_Add_DuplicateWithOlderTime(t *testing.T) {
|
||||
baseTime := time.Now()
|
||||
|
||||
// Add folder at t=5
|
||||
q.Add("/buckets/b1/folder1", "t5", baseTime.Add(5*time.Second))
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(5*time.Second))
|
||||
|
||||
// Try to add same folder with older time - should NOT update
|
||||
q.Add("/buckets/b1/folder1", "t2", baseTime.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(2*time.Second))
|
||||
|
||||
// Time and triggeredBy should remain at t=5
|
||||
_, triggered, queueTime, _ := q.Peek()
|
||||
if queueTime != baseTime.Add(5*time.Second) || triggered != "t5" {
|
||||
t.Errorf("expected time to remain unchanged, got %v and %s", queueTime, triggered)
|
||||
// Time should remain at t=5
|
||||
_, queueTime, _ := q.Peek()
|
||||
if queueTime != baseTime.Add(5*time.Second) {
|
||||
t.Errorf("expected time to remain unchanged, got %v", queueTime)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,9 +81,9 @@ func TestCleanupQueue_Remove(t *testing.T) {
|
||||
q := NewCleanupQueue(100, 10*time.Minute)
|
||||
now := time.Now()
|
||||
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
|
||||
// Remove middle item
|
||||
if !q.Remove("/buckets/b1/folder2") {
|
||||
@@ -112,8 +102,8 @@ func TestCleanupQueue_Remove(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify order is preserved by popping
|
||||
folder1, _, _ := q.Pop()
|
||||
folder3, _, _ := q.Pop()
|
||||
folder1, _ := q.Pop()
|
||||
folder3, _ := q.Pop()
|
||||
if folder1 != "/buckets/b1/folder1" || folder3 != "/buckets/b1/folder3" {
|
||||
t.Errorf("unexpected order: %s, %s", folder1, folder3)
|
||||
}
|
||||
@@ -124,30 +114,30 @@ func TestCleanupQueue_Pop(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
// Pop from empty queue
|
||||
folder, item, ok := q.Pop()
|
||||
folder, ok := q.Pop()
|
||||
if ok {
|
||||
t.Error("expected Pop to return false for empty queue")
|
||||
}
|
||||
if folder != "" || item != "" {
|
||||
t.Errorf("expected empty results, got %s by %s", folder, item)
|
||||
if folder != "" {
|
||||
t.Errorf("expected empty folder, got %s", folder)
|
||||
}
|
||||
|
||||
// Add items and pop in order
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
|
||||
folder, _, ok = q.Pop()
|
||||
folder, ok = q.Pop()
|
||||
if !ok || folder != "/buckets/b1/folder1" {
|
||||
t.Errorf("expected folder1, got %s (ok=%v)", folder, ok)
|
||||
}
|
||||
|
||||
folder, _, ok = q.Pop()
|
||||
folder, ok = q.Pop()
|
||||
if !ok || folder != "/buckets/b1/folder2" {
|
||||
t.Errorf("expected folder2, got %s (ok=%v)", folder, ok)
|
||||
}
|
||||
|
||||
folder, _, ok = q.Pop()
|
||||
folder, ok = q.Pop()
|
||||
if !ok || folder != "/buckets/b1/folder3" {
|
||||
t.Errorf("expected folder3, got %s (ok=%v)", folder, ok)
|
||||
}
|
||||
@@ -163,16 +153,16 @@ func TestCleanupQueue_Peek(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
// Peek empty queue
|
||||
folder, item, _, ok := q.Peek()
|
||||
folder, _, ok := q.Peek()
|
||||
if ok {
|
||||
t.Error("expected Peek to return false for empty queue")
|
||||
}
|
||||
|
||||
// Add item and peek
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
folder, item, queueTime, ok := q.Peek()
|
||||
if !ok || folder != "/buckets/b1/folder1" || item != "i1" {
|
||||
t.Errorf("expected folder1 by i1, got %s by %s (ok=%v)", folder, item, ok)
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
folder, queueTime, ok := q.Peek()
|
||||
if !ok || folder != "/buckets/b1/folder1" {
|
||||
t.Errorf("expected folder1, got %s (ok=%v)", folder, ok)
|
||||
}
|
||||
if queueTime != now {
|
||||
t.Errorf("expected queue time %v, got %v", now, queueTime)
|
||||
@@ -188,7 +178,7 @@ func TestCleanupQueue_Contains(t *testing.T) {
|
||||
q := NewCleanupQueue(100, 10*time.Minute)
|
||||
now := time.Now()
|
||||
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
|
||||
if !q.Contains("/buckets/b1/folder1") {
|
||||
t.Error("expected Contains to return true")
|
||||
@@ -208,14 +198,14 @@ func TestCleanupQueue_ShouldProcess_MaxSize(t *testing.T) {
|
||||
}
|
||||
|
||||
// Add items below max
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
if q.ShouldProcess() {
|
||||
t.Error("queue below max should not need processing")
|
||||
}
|
||||
|
||||
// Add item to reach max
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
if !q.ShouldProcess() {
|
||||
t.Error("queue at max should need processing")
|
||||
}
|
||||
@@ -226,7 +216,7 @@ func TestCleanupQueue_ShouldProcess_MaxAge(t *testing.T) {
|
||||
|
||||
// Add item with old event time
|
||||
oldTime := time.Now().Add(-1 * time.Second) // 1 second ago
|
||||
q.Add("/buckets/b1/folder1", "i1", oldTime)
|
||||
q.Add("/buckets/b1/folder1", oldTime)
|
||||
|
||||
// Item is older than maxAge, should need processing
|
||||
if !q.ShouldProcess() {
|
||||
@@ -235,7 +225,7 @@ func TestCleanupQueue_ShouldProcess_MaxAge(t *testing.T) {
|
||||
|
||||
// Clear and add fresh item
|
||||
q.Clear()
|
||||
q.Add("/buckets/b1/folder2", "i2", time.Now())
|
||||
q.Add("/buckets/b1/folder2", time.Now())
|
||||
|
||||
// Fresh item should not trigger processing
|
||||
if q.ShouldProcess() {
|
||||
@@ -247,9 +237,9 @@ func TestCleanupQueue_Clear(t *testing.T) {
|
||||
q := NewCleanupQueue(100, 10*time.Minute)
|
||||
now := time.Now()
|
||||
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
|
||||
q.Clear()
|
||||
|
||||
@@ -271,7 +261,7 @@ func TestCleanupQueue_OldestAge(t *testing.T) {
|
||||
|
||||
// Add item with time in the past
|
||||
oldTime := time.Now().Add(-5 * time.Minute)
|
||||
q.Add("/buckets/b1/folder1", "i1", oldTime)
|
||||
q.Add("/buckets/b1/folder1", oldTime)
|
||||
|
||||
// Age should be approximately 5 minutes
|
||||
age := q.OldestAge()
|
||||
@@ -293,12 +283,12 @@ func TestCleanupQueue_TimeOrder(t *testing.T) {
|
||||
"/buckets/b1/e",
|
||||
}
|
||||
for i, item := range items {
|
||||
q.Add(item, "i", baseTime.Add(time.Duration(i)*time.Second))
|
||||
q.Add(item, baseTime.Add(time.Duration(i)*time.Second))
|
||||
}
|
||||
|
||||
// Pop should return in time order
|
||||
for i, expected := range items {
|
||||
got, _, ok := q.Pop()
|
||||
got, ok := q.Pop()
|
||||
if !ok {
|
||||
t.Errorf("Pop %d: expected item, got empty", i)
|
||||
}
|
||||
@@ -313,17 +303,17 @@ func TestCleanupQueue_DuplicateWithNewerTime(t *testing.T) {
|
||||
baseTime := time.Now()
|
||||
|
||||
// Add items
|
||||
q.Add("/buckets/b1/folder1", "i1", baseTime)
|
||||
q.Add("/buckets/b1/folder2", "i2", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", baseTime.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", baseTime)
|
||||
q.Add("/buckets/b1/folder2", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", baseTime.Add(2*time.Second))
|
||||
|
||||
// Add duplicate with newer time - should update and reposition
|
||||
q.Add("/buckets/b1/folder1", "i1-new", baseTime.Add(3*time.Second))
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(3*time.Second))
|
||||
|
||||
// folder1 should now be at the back (newest time) - verify by popping
|
||||
expected := []string{"/buckets/b1/folder2", "/buckets/b1/folder3", "/buckets/b1/folder1"}
|
||||
for i, exp := range expected {
|
||||
folder, _, ok := q.Pop()
|
||||
folder, ok := q.Pop()
|
||||
if !ok || folder != exp {
|
||||
t.Errorf("at index %d: expected %s, got %s", i, exp, folder)
|
||||
}
|
||||
@@ -338,7 +328,7 @@ func TestCleanupQueue_Concurrent(t *testing.T) {
|
||||
// Concurrent adds
|
||||
go func() {
|
||||
for i := 0; i < 100; i++ {
|
||||
q.Add("/buckets/b1/folder"+string(rune('A'+i%26)), "item", now.Add(time.Duration(i)*time.Millisecond))
|
||||
q.Add("/buckets/b1/folder"+string(rune('A'+i%26)), now.Add(time.Duration(i)*time.Millisecond))
|
||||
}
|
||||
done <- true
|
||||
}()
|
||||
|
||||
@@ -18,7 +18,7 @@ const (
|
||||
DefaultMaxCountCheck = 1000
|
||||
DefaultCacheExpiry = 5 * time.Minute
|
||||
DefaultQueueMaxSize = 1000
|
||||
DefaultQueueMaxAge = 5 * time.Second
|
||||
DefaultQueueMaxAge = 10 * time.Minute
|
||||
DefaultProcessorSleep = 10 * time.Second // How often to check queue
|
||||
)
|
||||
|
||||
@@ -32,17 +32,12 @@ type FilerOperations interface {
|
||||
// folderState tracks the state of a folder for empty folder cleanup
|
||||
type folderState struct {
|
||||
roughCount int // Cached rough count (up to maxCountCheck)
|
||||
isImplicit *bool // Tri-state boolean: nil (unknown), true (implicit), false (explicit)
|
||||
lastAddTime time.Time // Last time an item was added
|
||||
lastDelTime time.Time // Last time an item was deleted
|
||||
lastCheck time.Time // Last time we checked the actual count
|
||||
}
|
||||
|
||||
type bucketCleanupPolicyState struct {
|
||||
autoRemove bool
|
||||
attrValue string
|
||||
lastCheck time.Time
|
||||
}
|
||||
|
||||
// EmptyFolderCleaner handles asynchronous cleanup of empty folders
|
||||
// Each filer owns specific folders via consistent hashing based on the peer filer list
|
||||
type EmptyFolderCleaner struct {
|
||||
@@ -51,9 +46,8 @@ type EmptyFolderCleaner struct {
|
||||
host pb.ServerAddress
|
||||
|
||||
// Folder state tracking
|
||||
mu sync.RWMutex
|
||||
folderCounts map[string]*folderState // Rough count cache
|
||||
bucketCleanupPolicies map[string]*bucketCleanupPolicyState // bucket path -> cleanup policy cache
|
||||
mu sync.RWMutex
|
||||
folderCounts map[string]*folderState // Rough count cache
|
||||
|
||||
// Cleanup queue (thread-safe, has its own lock)
|
||||
cleanupQueue *CleanupQueue
|
||||
@@ -72,18 +66,17 @@ type EmptyFolderCleaner struct {
|
||||
// NewEmptyFolderCleaner creates a new EmptyFolderCleaner
|
||||
func NewEmptyFolderCleaner(filer FilerOperations, lockRing *lock_manager.LockRing, host pb.ServerAddress, bucketPath string) *EmptyFolderCleaner {
|
||||
efc := &EmptyFolderCleaner{
|
||||
filer: filer,
|
||||
lockRing: lockRing,
|
||||
host: host,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
bucketCleanupPolicies: make(map[string]*bucketCleanupPolicyState),
|
||||
cleanupQueue: NewCleanupQueue(DefaultQueueMaxSize, DefaultQueueMaxAge),
|
||||
maxCountCheck: DefaultMaxCountCheck,
|
||||
cacheExpiry: DefaultCacheExpiry,
|
||||
processorSleep: DefaultProcessorSleep,
|
||||
bucketPath: bucketPath,
|
||||
enabled: true,
|
||||
stopCh: make(chan struct{}),
|
||||
filer: filer,
|
||||
lockRing: lockRing,
|
||||
host: host,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
cleanupQueue: NewCleanupQueue(DefaultQueueMaxSize, DefaultQueueMaxAge),
|
||||
maxCountCheck: DefaultMaxCountCheck,
|
||||
cacheExpiry: DefaultCacheExpiry,
|
||||
processorSleep: DefaultProcessorSleep,
|
||||
bucketPath: bucketPath,
|
||||
enabled: true,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
go efc.cacheEvictionLoop()
|
||||
go efc.cleanupProcessor()
|
||||
@@ -169,8 +162,8 @@ func (efc *EmptyFolderCleaner) OnDeleteEvent(directory string, entryName string,
|
||||
}
|
||||
|
||||
// Add to cleanup queue with event time (handles out-of-order events)
|
||||
if efc.cleanupQueue.Add(directory, entryName, eventTime) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: queued %s for cleanup (triggered by %s)", directory, entryName)
|
||||
if efc.cleanupQueue.Add(directory, eventTime) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: queued %s for cleanup", directory)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,10 +214,6 @@ func (efc *EmptyFolderCleaner) cleanupProcessor() {
|
||||
func (efc *EmptyFolderCleaner) processCleanupQueue() {
|
||||
// Check if we should process
|
||||
if !efc.cleanupQueue.ShouldProcess() {
|
||||
if efc.cleanupQueue.Len() > 0 {
|
||||
glog.Infof("EmptyFolderCleaner: pending queue not processed yet (len=%d, oldest_age=%v, max_size=%d, max_age=%v)",
|
||||
efc.cleanupQueue.Len(), efc.cleanupQueue.OldestAge(), efc.cleanupQueue.maxSize, efc.cleanupQueue.maxAge)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -239,30 +228,35 @@ func (efc *EmptyFolderCleaner) processCleanupQueue() {
|
||||
}
|
||||
|
||||
// Pop the oldest item
|
||||
folder, triggeredBy, ok := efc.cleanupQueue.Pop()
|
||||
folder, ok := efc.cleanupQueue.Pop()
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
|
||||
// Execute cleanup for this folder
|
||||
efc.executeCleanup(folder, triggeredBy)
|
||||
efc.executeCleanup(folder)
|
||||
|
||||
// If queue is no longer full and oldest item is not old enough, stop processing
|
||||
if !efc.cleanupQueue.ShouldProcess() {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// executeCleanup performs the actual cleanup of an empty folder
|
||||
func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string) {
|
||||
func (efc *EmptyFolderCleaner) executeCleanup(folder string) {
|
||||
efc.mu.Lock()
|
||||
|
||||
// Quick check: if we have cached count and it's > 0, skip
|
||||
if state, exists := efc.folderCounts[folder]; exists {
|
||||
if state.roughCount > 0 {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s (triggered by %s), cached count=%d", folder, triggeredBy, state.roughCount)
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s, cached count=%d", folder, state.roughCount)
|
||||
efc.mu.Unlock()
|
||||
return
|
||||
}
|
||||
// If there was an add after our delete, skip
|
||||
if !state.lastAddTime.IsZero() && state.lastAddTime.After(state.lastDelTime) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s (triggered by %s), add happened after delete", folder, triggeredBy)
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s, add happened after delete", folder)
|
||||
efc.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -271,23 +265,47 @@ func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string)
|
||||
|
||||
// Re-check ownership (topology might have changed)
|
||||
if !efc.ownsFolder(folder) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: no longer owner of %s (triggered by %s), skipping", folder, triggeredBy)
|
||||
glog.V(3).Infof("EmptyFolderCleaner: no longer owner of %s, skipping", folder)
|
||||
return
|
||||
}
|
||||
|
||||
// Check for explicit implicit_dir attribute
|
||||
// First check cache
|
||||
ctx := context.Background()
|
||||
bucketPath, autoRemove, source, attrValue, err := efc.getBucketCleanupPolicy(ctx, folder)
|
||||
if err != nil {
|
||||
if err == filer_pb.ErrNotFound {
|
||||
efc.mu.RLock()
|
||||
var cachedImplicit *bool
|
||||
if state, exists := efc.folderCounts[folder]; exists {
|
||||
cachedImplicit = state.isImplicit
|
||||
}
|
||||
efc.mu.RUnlock()
|
||||
|
||||
var isImplicit bool
|
||||
if cachedImplicit != nil {
|
||||
isImplicit = *cachedImplicit
|
||||
} else {
|
||||
// Not cached, check filer
|
||||
attrs, err := efc.filer.GetEntryAttributes(ctx, util.FullPath(folder))
|
||||
if err != nil {
|
||||
if err == filer_pb.ErrNotFound {
|
||||
return
|
||||
}
|
||||
glog.V(2).Infof("EmptyFolderCleaner: error getting attributes for %s: %v", folder, err)
|
||||
return
|
||||
}
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to load bucket cleanup policy for folder %s (triggered by %s): %v", folder, triggeredBy, err)
|
||||
return
|
||||
|
||||
isImplicit = attrs != nil && string(attrs[s3_constants.ExtS3ImplicitDir]) == "true"
|
||||
|
||||
// Update cache
|
||||
efc.mu.Lock()
|
||||
if _, exists := efc.folderCounts[folder]; !exists {
|
||||
efc.folderCounts[folder] = &folderState{}
|
||||
}
|
||||
efc.folderCounts[folder].isImplicit = &isImplicit
|
||||
efc.mu.Unlock()
|
||||
}
|
||||
|
||||
if !autoRemove {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping folder %s (triggered by %s), bucket %s auto-remove-empty-folders disabled (source=%s attr=%s)",
|
||||
folder, triggeredBy, bucketPath, source, attrValue)
|
||||
if !isImplicit {
|
||||
glog.V(4).Infof("EmptyFolderCleaner: folder %s is not marked as implicit, skipping", folder)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -308,14 +326,14 @@ func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string)
|
||||
efc.mu.Unlock()
|
||||
|
||||
if count > 0 {
|
||||
glog.Infof("EmptyFolderCleaner: folder %s (triggered by %s) has %d items, not empty", folder, triggeredBy, count)
|
||||
glog.V(3).Infof("EmptyFolderCleaner: folder %s has %d items, not empty", folder, count)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the empty folder
|
||||
glog.Infof("EmptyFolderCleaner: deleting empty folder %s (triggered by %s)", folder, triggeredBy)
|
||||
glog.V(2).Infof("EmptyFolderCleaner: deleting empty folder %s", folder)
|
||||
if err := efc.deleteFolder(ctx, folder); err != nil {
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to delete empty folder %s (triggered by %s): %v", folder, triggeredBy, err)
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to delete empty folder %s: %v", folder, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -339,60 +357,6 @@ func (efc *EmptyFolderCleaner) deleteFolder(ctx context.Context, folder string)
|
||||
return efc.filer.DeleteEntryMetaAndData(ctx, util.FullPath(folder), false, false, false, false, nil, 0)
|
||||
}
|
||||
|
||||
func (efc *EmptyFolderCleaner) getBucketCleanupPolicy(ctx context.Context, folder string) (bucketPath string, autoRemove bool, source string, attrValue string, err error) {
|
||||
bucketPath, ok := util.ExtractBucketPath(efc.bucketPath, folder, true)
|
||||
if !ok {
|
||||
return "", true, "default", "<not_bucket_path>", nil
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
efc.mu.RLock()
|
||||
if state, found := efc.bucketCleanupPolicies[bucketPath]; found && now.Sub(state.lastCheck) <= efc.cacheExpiry {
|
||||
efc.mu.RUnlock()
|
||||
return bucketPath, state.autoRemove, "cache", state.attrValue, nil
|
||||
}
|
||||
efc.mu.RUnlock()
|
||||
|
||||
attrs, err := efc.filer.GetEntryAttributes(ctx, util.FullPath(bucketPath))
|
||||
if err != nil {
|
||||
return "", true, "", "", err
|
||||
}
|
||||
|
||||
autoRemove, attrValue = autoRemoveEmptyFoldersEnabled(attrs)
|
||||
|
||||
efc.mu.Lock()
|
||||
if efc.bucketCleanupPolicies == nil {
|
||||
efc.bucketCleanupPolicies = make(map[string]*bucketCleanupPolicyState)
|
||||
}
|
||||
efc.bucketCleanupPolicies[bucketPath] = &bucketCleanupPolicyState{
|
||||
autoRemove: autoRemove,
|
||||
attrValue: attrValue,
|
||||
lastCheck: now,
|
||||
}
|
||||
efc.mu.Unlock()
|
||||
|
||||
return bucketPath, autoRemove, "filer", attrValue, nil
|
||||
}
|
||||
|
||||
func autoRemoveEmptyFoldersEnabled(attrs map[string][]byte) (bool, string) {
|
||||
if attrs == nil {
|
||||
return true, "<no_attrs>"
|
||||
}
|
||||
|
||||
value, found := attrs[s3_constants.ExtAllowEmptyFolders]
|
||||
if !found {
|
||||
return true, "<missing>"
|
||||
}
|
||||
|
||||
text := strings.TrimSpace(string(value))
|
||||
if text == "" {
|
||||
return true, "<empty>"
|
||||
}
|
||||
|
||||
return !strings.EqualFold(text, "true"), text
|
||||
}
|
||||
|
||||
// isUnderPath checks if child is under parent path
|
||||
func isUnderPath(child, parent string) bool {
|
||||
if parent == "" || parent == "/" {
|
||||
@@ -481,12 +445,6 @@ func (efc *EmptyFolderCleaner) evictStaleCacheEntries() {
|
||||
}
|
||||
}
|
||||
|
||||
for bucketPath, state := range efc.bucketCleanupPolicies {
|
||||
if now.Sub(state.lastCheck) > efc.cacheExpiry {
|
||||
delete(efc.bucketCleanupPolicies, bucketPath)
|
||||
}
|
||||
}
|
||||
|
||||
if expiredCount > 0 {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: evicted %d stale cache entries", expiredCount)
|
||||
}
|
||||
@@ -502,7 +460,6 @@ func (efc *EmptyFolderCleaner) Stop() {
|
||||
efc.enabled = false
|
||||
efc.cleanupQueue.Clear()
|
||||
efc.folderCounts = make(map[string]*folderState) // Clear cache on stop
|
||||
efc.bucketCleanupPolicies = make(map[string]*bucketCleanupPolicyState)
|
||||
}
|
||||
|
||||
// GetPendingCleanupCount returns the number of pending cleanup tasks (for testing)
|
||||
|
||||
@@ -1,43 +1,13 @@
|
||||
package empty_folder_cleanup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
type mockFilerOps struct {
|
||||
countFn func(path util.FullPath) (int, error)
|
||||
deleteFn func(path util.FullPath) error
|
||||
attrsFn func(path util.FullPath) (map[string][]byte, error)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) CountDirectoryEntries(_ context.Context, dirPath util.FullPath, _ int) (int, error) {
|
||||
if m.countFn == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return m.countFn(dirPath)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) DeleteEntryMetaAndData(_ context.Context, p util.FullPath, _, _, _, _ bool, _ []int32, _ int64) error {
|
||||
if m.deleteFn == nil {
|
||||
return nil
|
||||
}
|
||||
return m.deleteFn(p)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) GetEntryAttributes(_ context.Context, p util.FullPath) (map[string][]byte, error) {
|
||||
if m.attrsFn == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return m.attrsFn(p)
|
||||
}
|
||||
|
||||
func Test_isUnderPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -96,56 +66,6 @@ func Test_isUnderBucketPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test_autoRemoveEmptyFoldersEnabled(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
attrs map[string][]byte
|
||||
enabled bool
|
||||
attrValue string
|
||||
}{
|
||||
{
|
||||
name: "no attrs defaults enabled",
|
||||
attrs: nil,
|
||||
enabled: true,
|
||||
attrValue: "<no_attrs>",
|
||||
},
|
||||
{
|
||||
name: "missing key defaults enabled",
|
||||
attrs: map[string][]byte{},
|
||||
enabled: true,
|
||||
attrValue: "<missing>",
|
||||
},
|
||||
{
|
||||
name: "allow-empty disables cleanup",
|
||||
attrs: map[string][]byte{
|
||||
s3_constants.ExtAllowEmptyFolders: []byte("true"),
|
||||
},
|
||||
enabled: false,
|
||||
attrValue: "true",
|
||||
},
|
||||
{
|
||||
name: "explicit false keeps cleanup enabled",
|
||||
attrs: map[string][]byte{
|
||||
s3_constants.ExtAllowEmptyFolders: []byte("false"),
|
||||
},
|
||||
enabled: true,
|
||||
attrValue: "false",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
enabled, attrValue := autoRemoveEmptyFoldersEnabled(tt.attrs)
|
||||
if enabled != tt.enabled {
|
||||
t.Fatalf("expected enabled=%v, got %v", tt.enabled, enabled)
|
||||
}
|
||||
if attrValue != tt.attrValue {
|
||||
t.Fatalf("expected attrValue=%q, got %q", tt.attrValue, attrValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_ownsFolder(t *testing.T) {
|
||||
// Create a LockRing with multiple servers
|
||||
lockRing := lock_manager.NewLockRing(5 * time.Second)
|
||||
@@ -592,7 +512,7 @@ func TestEmptyFolderCleaner_cacheEviction_skipsEntriesInQueue(t *testing.T) {
|
||||
// Add a stale cache entry
|
||||
cleaner.folderCounts[folder] = &folderState{roughCount: 0, lastCheck: oldTime}
|
||||
// Also add to cleanup queue
|
||||
cleaner.cleanupQueue.Add(folder, "item", time.Now())
|
||||
cleaner.cleanupQueue.Add(folder, time.Now())
|
||||
|
||||
// Run eviction
|
||||
cleaner.evictStaleCacheEntries()
|
||||
@@ -638,7 +558,7 @@ func TestEmptyFolderCleaner_queueFIFOOrder(t *testing.T) {
|
||||
|
||||
// Verify time-sorted order by popping
|
||||
for i, expected := range folders {
|
||||
folder, _, ok := cleaner.cleanupQueue.Pop()
|
||||
folder, ok := cleaner.cleanupQueue.Pop()
|
||||
if !ok || folder != expected {
|
||||
t.Errorf("expected folder %s at index %d, got %s", expected, i, folder)
|
||||
}
|
||||
@@ -646,90 +566,3 @@ func TestEmptyFolderCleaner_queueFIFOOrder(t *testing.T) {
|
||||
|
||||
cleaner.Stop()
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_processCleanupQueue_drainsAllOnceTriggered(t *testing.T) {
|
||||
lockRing := lock_manager.NewLockRing(5 * time.Second)
|
||||
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"})
|
||||
|
||||
var deleted []string
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(_ util.FullPath) (int, error) {
|
||||
return 0, nil
|
||||
},
|
||||
deleteFn: func(path util.FullPath) error {
|
||||
deleted = append(deleted, string(path))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cleaner := &EmptyFolderCleaner{
|
||||
filer: mock,
|
||||
lockRing: lockRing,
|
||||
host: "filer1:8888",
|
||||
bucketPath: "/buckets",
|
||||
enabled: true,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
cleanupQueue: NewCleanupQueue(2, time.Hour),
|
||||
maxCountCheck: 1000,
|
||||
cacheExpiry: time.Minute,
|
||||
processorSleep: time.Second,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
cleaner.cleanupQueue.Add("/buckets/test/folder1", "i1", now)
|
||||
cleaner.cleanupQueue.Add("/buckets/test/folder2", "i2", now.Add(time.Millisecond))
|
||||
cleaner.cleanupQueue.Add("/buckets/test/folder3", "i3", now.Add(2*time.Millisecond))
|
||||
|
||||
cleaner.processCleanupQueue()
|
||||
|
||||
if got := cleaner.cleanupQueue.Len(); got != 0 {
|
||||
t.Fatalf("expected queue to be drained, got len=%d", got)
|
||||
}
|
||||
if len(deleted) != 3 {
|
||||
t.Fatalf("expected 3 deleted folders, got %d", len(deleted))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_executeCleanup_bucketPolicyDisabledSkips(t *testing.T) {
|
||||
lockRing := lock_manager.NewLockRing(5 * time.Second)
|
||||
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"})
|
||||
|
||||
var deleted []string
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(_ util.FullPath) (int, error) {
|
||||
return 0, nil
|
||||
},
|
||||
deleteFn: func(path util.FullPath) error {
|
||||
deleted = append(deleted, string(path))
|
||||
return nil
|
||||
},
|
||||
attrsFn: func(path util.FullPath) (map[string][]byte, error) {
|
||||
if string(path) == "/buckets/test" {
|
||||
return map[string][]byte{s3_constants.ExtAllowEmptyFolders: []byte("true")}, nil
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
cleaner := &EmptyFolderCleaner{
|
||||
filer: mock,
|
||||
lockRing: lockRing,
|
||||
host: "filer1:8888",
|
||||
bucketPath: "/buckets",
|
||||
enabled: true,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
cleanupQueue: NewCleanupQueue(1000, time.Minute),
|
||||
maxCountCheck: 1000,
|
||||
cacheExpiry: time.Minute,
|
||||
processorSleep: time.Second,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
folder := "/buckets/test/folder"
|
||||
cleaner.executeCleanup(folder, "triggered_item")
|
||||
|
||||
if len(deleted) != 0 {
|
||||
t.Fatalf("expected folder %s to be skipped, got deletions %v", folder, deleted)
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
@@ -302,8 +303,12 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di
|
||||
GroupNames: entry.GroupNames,
|
||||
},
|
||||
}
|
||||
// level > 3 corresponds to a path depth greater than "/buckets/<bucket_name>",
|
||||
// ensuring we only mark subdirectories within a bucket as implicit.
|
||||
if isUnderBuckets && level > 3 {
|
||||
// Parent directories under buckets are created automatically; no additional logging.
|
||||
dirEntry.Extended = map[string][]byte{
|
||||
s3_constants.ExtS3ImplicitDir: []byte("true"),
|
||||
}
|
||||
}
|
||||
|
||||
glog.V(2).InfofCtx(ctx, "create directory: %s %v", dirPath, dirEntry.Mode)
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
@@ -104,15 +103,7 @@ func (m *IAMManager) Initialize(config *IAMConfig, filerAddressProvider func() s
|
||||
|
||||
// Initialize STS service
|
||||
m.stsService = sts.NewSTSService()
|
||||
|
||||
// Use default config if none provided
|
||||
stsConfig := config.STS
|
||||
if stsConfig == nil {
|
||||
glog.V(1).Infof("No STS configuration provided, using defaults")
|
||||
stsConfig = sts.DefaultSTSConfig()
|
||||
}
|
||||
|
||||
if err := m.stsService.Initialize(stsConfig); err != nil {
|
||||
if err := m.stsService.Initialize(config.STS); err != nil {
|
||||
return fmt.Errorf("failed to initialize STS service: %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
)
|
||||
|
||||
// TestIAMManagerInitializeWithoutSTSConfig tests that IAM manager can initialize
|
||||
// without an explicit STS configuration by using defaults
|
||||
func TestIAMManagerInitializeWithoutSTSConfig(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
|
||||
// Create config without STS section (nil)
|
||||
// But with minimal policy and role configs to satisfy other components
|
||||
config := &IAMConfig{
|
||||
STS: nil, // No STS config provided - will use defaults
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
DefaultEffect: "Deny",
|
||||
StoreType: "memory",
|
||||
},
|
||||
Roles: &RoleStoreConfig{
|
||||
StoreType: "memory",
|
||||
},
|
||||
}
|
||||
|
||||
// Initialize should succeed with default STS config
|
||||
err := manager.Initialize(config, func() string { return "localhost:8888" })
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize IAM manager without STS config: %v", err)
|
||||
}
|
||||
|
||||
// Verify STS service is initialized
|
||||
stsService := manager.GetSTSService()
|
||||
if stsService == nil {
|
||||
t.Fatal("STS service is nil after initialization")
|
||||
}
|
||||
|
||||
if !stsService.IsInitialized() {
|
||||
t.Fatal("STS service is not initialized")
|
||||
}
|
||||
|
||||
// Verify the default config was applied
|
||||
if stsService.Config.Issuer != "seaweedfs-sts" {
|
||||
t.Errorf("Expected default issuer 'seaweedfs-sts', got '%s'", stsService.Config.Issuer)
|
||||
}
|
||||
|
||||
if stsService.Config.TokenDuration.Duration != 1*time.Hour {
|
||||
t.Errorf("Expected default token duration 1h, got %v", stsService.Config.TokenDuration.Duration)
|
||||
}
|
||||
|
||||
if stsService.Config.MaxSessionLength.Duration != 12*time.Hour {
|
||||
t.Errorf("Expected default max session length 12h, got %v", stsService.Config.MaxSessionLength.Duration)
|
||||
}
|
||||
|
||||
t.Logf("Successfully initialized STS service with default configuration")
|
||||
}
|
||||
|
||||
// TestIAMManagerInitializeWithExplicitSTSConfig tests that explicit STS config still works
|
||||
func TestIAMManagerInitializeWithExplicitSTSConfig(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
|
||||
// Create config with explicit STS section
|
||||
config := &IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: 30 * time.Minute},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 2 * time.Hour},
|
||||
Issuer: "custom-issuer",
|
||||
SigningKey: []byte("custom-signing-key-for-testing-purposes-only"),
|
||||
AccountId: "999888777666",
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
DefaultEffect: "Deny",
|
||||
StoreType: "memory",
|
||||
},
|
||||
Roles: &RoleStoreConfig{
|
||||
StoreType: "memory",
|
||||
},
|
||||
}
|
||||
|
||||
// Initialize should succeed with explicit config
|
||||
err := manager.Initialize(config, func() string { return "localhost:8888" })
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize IAM manager with explicit STS config: %v", err)
|
||||
}
|
||||
|
||||
// Verify STS service uses the custom config
|
||||
stsService := manager.GetSTSService()
|
||||
if stsService == nil {
|
||||
t.Fatal("STS service is nil after initialization")
|
||||
}
|
||||
|
||||
if !stsService.IsInitialized() {
|
||||
t.Fatal("STS service is not initialized")
|
||||
}
|
||||
|
||||
if stsService.Config.Issuer != "custom-issuer" {
|
||||
t.Errorf("Expected issuer 'custom-issuer', got '%s'", stsService.Config.Issuer)
|
||||
}
|
||||
|
||||
if stsService.Config.AccountId != "999888777666" {
|
||||
t.Errorf("Expected account ID '999888777666', got '%s'", stsService.Config.AccountId)
|
||||
}
|
||||
|
||||
t.Logf("Successfully initialized STS service with explicit configuration")
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package sts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -259,28 +258,6 @@ func NewSTSService() *STSService {
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultSTSConfig returns a default STS configuration with sensible defaults
|
||||
// This ensures the STS service can be initialized even when no explicit configuration is provided
|
||||
func DefaultSTSConfig() *STSConfig {
|
||||
// Generate a secure random signing key
|
||||
signingKey := make([]byte, 32) // 256 bits
|
||||
if _, err := rand.Read(signingKey); err != nil {
|
||||
// Fallback to a warning message if random generation fails
|
||||
// This should never happen in practice, but we handle it defensively
|
||||
glog.Warningf("Failed to generate random signing key, using deterministic fallback: %v", err)
|
||||
signingKey = []byte("default-signing-key-change-in-production-environments")
|
||||
}
|
||||
|
||||
return &STSConfig{
|
||||
TokenDuration: FlexibleDuration{Duration: 1 * time.Hour}, // 1 hour default
|
||||
MaxSessionLength: FlexibleDuration{Duration: 12 * time.Hour}, // 12 hours max
|
||||
Issuer: "seaweedfs-sts",
|
||||
SigningKey: signingKey,
|
||||
AccountId: "111122223333", // Default AWS account ID
|
||||
Providers: nil, // No providers by default
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize initializes the STS service with configuration
|
||||
func (s *STSService) Initialize(config *STSConfig) error {
|
||||
if config == nil {
|
||||
|
||||
@@ -129,17 +129,6 @@ func newUploader(httpClient HTTPClient) *Uploader {
|
||||
// UploadWithRetry will retry both assigning volume request and uploading content
|
||||
// The option parameter does not need to specify UploadUrl and Jwt, which will come from assigning volume.
|
||||
func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assignRequest *filer_pb.AssignVolumeRequest, uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
|
||||
bytesReader, ok := reader.(*util.BytesReader)
|
||||
if ok {
|
||||
data = bytesReader.Bytes
|
||||
} else {
|
||||
data, err = io.ReadAll(reader)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read input: %w", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
doUploadFunc := func() error {
|
||||
|
||||
var host string
|
||||
@@ -169,7 +158,7 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
|
||||
uploadOption.Jwt = auth
|
||||
|
||||
var uploadErr error
|
||||
uploadResult, uploadErr = uploader.retriedUploadData(context.Background(), data, uploadOption)
|
||||
uploadResult, uploadErr, data = uploader.doUpload(context.Background(), reader, uploadOption)
|
||||
return uploadErr
|
||||
}
|
||||
if uploadOption.RetryForever {
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
package filersink
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
@@ -24,13 +18,10 @@ import (
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
func (fs *FilerSink) replicateChunks(ctx context.Context, sourceChunks []*filer_pb.FileChunk, path string, sourceMtime int64) (replicatedChunks []*filer_pb.FileChunk, err error) {
|
||||
func (fs *FilerSink) replicateChunks(sourceChunks []*filer_pb.FileChunk, path string) (replicatedChunks []*filer_pb.FileChunk, err error) {
|
||||
if len(sourceChunks) == 0 {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
// a simple progress bar. Not ideal. Fix me.
|
||||
var bar *progressbar.ProgressBar
|
||||
@@ -47,64 +38,26 @@ func (fs *FilerSink) replicateChunks(ctx context.Context, sourceChunks []*filer_
|
||||
}
|
||||
|
||||
replicatedChunks = make([]*filer_pb.FileChunk, len(sourceChunks))
|
||||
var errLock sync.Mutex
|
||||
setError := func(e error) {
|
||||
if e == nil {
|
||||
return
|
||||
}
|
||||
errLock.Lock()
|
||||
if err == nil {
|
||||
err = e
|
||||
}
|
||||
errLock.Unlock()
|
||||
}
|
||||
hasError := func() bool {
|
||||
errLock.Lock()
|
||||
defer errLock.Unlock()
|
||||
return err != nil
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for chunkIndex, sourceChunk := range sourceChunks {
|
||||
if hasError() {
|
||||
break
|
||||
}
|
||||
|
||||
if sourceChunk.IsChunkManifest {
|
||||
replicatedChunk, replicateErr := fs.replicateOneManifestChunk(ctx, sourceChunk, path, sourceMtime)
|
||||
if replicateErr != nil {
|
||||
setError(replicateErr)
|
||||
break
|
||||
}
|
||||
replicatedChunks[chunkIndex] = replicatedChunk
|
||||
if bar != nil {
|
||||
bar.Add(1)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
index, source := chunkIndex, sourceChunk
|
||||
fs.executor.Execute(func() {
|
||||
defer wg.Done()
|
||||
var replicatedChunk *filer_pb.FileChunk
|
||||
retryErr := util.Retry("replicate chunks", func() error {
|
||||
chunk, e := fs.replicateOneChunk(source, path, sourceMtime)
|
||||
util.Retry("replicate chunks", func() error {
|
||||
replicatedChunk, e := fs.replicateOneChunk(source, path)
|
||||
if e != nil {
|
||||
err = e
|
||||
return e
|
||||
}
|
||||
replicatedChunk = chunk
|
||||
replicatedChunks[index] = replicatedChunk
|
||||
if bar != nil {
|
||||
bar.Add(1)
|
||||
}
|
||||
err = nil
|
||||
return nil
|
||||
})
|
||||
if retryErr != nil {
|
||||
setError(retryErr)
|
||||
return
|
||||
}
|
||||
|
||||
replicatedChunks[index] = replicatedChunk
|
||||
if bar != nil {
|
||||
bar.Add(1)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
@@ -112,9 +65,9 @@ func (fs *FilerSink) replicateChunks(ctx context.Context, sourceChunks []*filer_
|
||||
return
|
||||
}
|
||||
|
||||
func (fs *FilerSink) replicateOneChunk(sourceChunk *filer_pb.FileChunk, path string, sourceMtime int64) (*filer_pb.FileChunk, error) {
|
||||
func (fs *FilerSink) replicateOneChunk(sourceChunk *filer_pb.FileChunk, path string) (*filer_pb.FileChunk, error) {
|
||||
|
||||
fileId, err := fs.fetchAndWrite(sourceChunk, path, sourceMtime)
|
||||
fileId, err := fs.fetchAndWrite(sourceChunk, path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("copy %s: %v", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
@@ -128,236 +81,63 @@ func (fs *FilerSink) replicateOneChunk(sourceChunk *filer_pb.FileChunk, path str
|
||||
SourceFileId: sourceChunk.GetFileIdString(),
|
||||
CipherKey: sourceChunk.CipherKey,
|
||||
IsCompressed: sourceChunk.IsCompressed,
|
||||
SseType: sourceChunk.SseType,
|
||||
SseMetadata: sourceChunk.SseMetadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) replicateOneManifestChunk(ctx context.Context, sourceChunk *filer_pb.FileChunk, path string, sourceMtime int64) (*filer_pb.FileChunk, error) {
|
||||
resolvedChunks, err := filer.ResolveOneChunkManifest(ctx, fs.filerSource.LookupFileId, sourceChunk)
|
||||
func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string) (fileId string, err error) {
|
||||
|
||||
filename, header, resp, err := fs.filerSource.ReadPart(sourceChunk.GetFileIdString())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve manifest %s: %w", sourceChunk.GetFileIdString(), err)
|
||||
return "", fmt.Errorf("read part %s: %v", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
defer util_http.CloseResponse(resp)
|
||||
|
||||
replicatedResolvedChunks, err := fs.replicateChunks(ctx, resolvedChunks, path, sourceMtime)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("replicate manifest data chunks %s: %w", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
manifestDataChunks := make([]*filer_pb.FileChunk, len(replicatedResolvedChunks))
|
||||
for i, chunk := range replicatedResolvedChunks {
|
||||
copied := *chunk
|
||||
manifestDataChunks[i] = &copied
|
||||
}
|
||||
filer_pb.BeforeEntrySerialization(manifestDataChunks)
|
||||
manifestData, err := proto.Marshal(&filer_pb.FileChunkManifest{
|
||||
Chunks: manifestDataChunks,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal manifest %s: %w", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
manifestFileId, err := fs.uploadManifestChunk(path, sourceMtime, sourceChunk.GetFileIdString(), manifestData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &filer_pb.FileChunk{
|
||||
FileId: manifestFileId,
|
||||
Offset: sourceChunk.Offset,
|
||||
Size: sourceChunk.Size,
|
||||
ModifiedTsNs: sourceChunk.ModifiedTsNs,
|
||||
ETag: sourceChunk.ETag,
|
||||
SourceFileId: sourceChunk.GetFileIdString(),
|
||||
IsChunkManifest: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) uploadManifestChunk(path string, sourceMtime int64, sourceFileId string, manifestData []byte) (fileId string, err error) {
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
glog.V(0).Infof("upload manifest data %v: %v", sourceFileId, err)
|
||||
return "", fmt.Errorf("upload manifest data: %w", err)
|
||||
}
|
||||
|
||||
retryName := fmt.Sprintf("replicate manifest chunk %s", sourceFileId)
|
||||
err = util.RetryUntil(retryName, func() error {
|
||||
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: fs.replication,
|
||||
Collection: fs.collection,
|
||||
TtlSec: fs.ttlSec,
|
||||
DataCenter: fs.dataCenter,
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: "",
|
||||
Cipher: false,
|
||||
IsInputCompressed: false,
|
||||
MimeType: "application/octet-stream",
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
return fs.buildUploadUrl(host, fileId)
|
||||
},
|
||||
bytes.NewReader(manifestData),
|
||||
)
|
||||
if uploadErr != nil {
|
||||
return fmt.Errorf("upload manifest data: %w", uploadErr)
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
return fmt.Errorf("upload manifest result: %v", uploadResult.Error)
|
||||
}
|
||||
|
||||
fileId = currentFileId
|
||||
return nil
|
||||
}, func(uploadErr error) (shouldContinue bool) {
|
||||
if fs.hasSourceNewerVersion(path, sourceMtime) {
|
||||
glog.V(1).Infof("skip retrying stale source manifest %s for %s: %v", sourceFileId, path, uploadErr)
|
||||
return false
|
||||
}
|
||||
glog.V(0).Infof("upload source manifest %v: %v", sourceFileId, uploadErr)
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return fileId, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string, sourceMtime int64) (fileId string, err error) {
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
glog.V(0).Infof("upload source data %v: %v", sourceChunk.GetFileIdString(), err)
|
||||
return "", fmt.Errorf("upload data: %w", err)
|
||||
}
|
||||
|
||||
retryName := fmt.Sprintf("replicate chunk %s", sourceChunk.GetFileIdString())
|
||||
err = util.RetryUntil(retryName, func() error {
|
||||
filename, header, resp, readErr := fs.filerSource.ReadPart(sourceChunk.GetFileIdString())
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("read part %s: %w", sourceChunk.GetFileIdString(), readErr)
|
||||
}
|
||||
defer util_http.CloseResponse(resp)
|
||||
fileId, uploadResult, err, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: fs.replication,
|
||||
Collection: fs.collection,
|
||||
TtlSec: fs.ttlSec,
|
||||
DataCenter: fs.dataCenter,
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: filename,
|
||||
Cipher: false,
|
||||
IsInputCompressed: "gzip" == header.Get("Content-Encoding"),
|
||||
MimeType: header.Get("Content-Type"),
|
||||
PairMap: nil,
|
||||
RetryForever: true,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
if fs.writeChunkByFiler {
|
||||
fileUrl = fmt.Sprintf("http://%s/?proxyChunkId=%s", fs.address, fileId)
|
||||
}
|
||||
glog.V(4).Infof("replicating %s to %s header:%+v", filename, fileUrl, header)
|
||||
return fileUrl
|
||||
},
|
||||
resp.Body,
|
||||
)
|
||||
|
||||
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: fs.replication,
|
||||
Collection: fs.collection,
|
||||
TtlSec: fs.ttlSec,
|
||||
DataCenter: fs.dataCenter,
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: filename,
|
||||
Cipher: false,
|
||||
IsInputCompressed: "gzip" == header.Get("Content-Encoding"),
|
||||
MimeType: header.Get("Content-Type"),
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
fileUrl := fs.buildUploadUrl(host, fileId)
|
||||
glog.V(4).Infof("replicating %s to %s header:%+v", filename, fileUrl, header)
|
||||
return fileUrl
|
||||
},
|
||||
resp.Body,
|
||||
)
|
||||
if uploadErr != nil {
|
||||
return fmt.Errorf("upload data: %w", uploadErr)
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
return fmt.Errorf("upload result: %v", uploadResult.Error)
|
||||
}
|
||||
|
||||
fileId = currentFileId
|
||||
return nil
|
||||
}, func(uploadErr error) (shouldContinue bool) {
|
||||
if fs.hasSourceNewerVersion(path, sourceMtime) {
|
||||
glog.V(1).Infof("skip retrying stale source %s for %s: %v", sourceChunk.GetFileIdString(), path, uploadErr)
|
||||
return false
|
||||
}
|
||||
glog.V(0).Infof("upload source data %v: %v", sourceChunk.GetFileIdString(), uploadErr)
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
glog.V(0).Infof("upload source data %v: %v", sourceChunk.GetFileIdString(), err)
|
||||
return "", fmt.Errorf("upload data: %w", err)
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
glog.V(0).Infof("upload failure %v: %v", filename, err)
|
||||
return "", fmt.Errorf("upload result: %v", uploadResult.Error)
|
||||
}
|
||||
|
||||
return fileId, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) buildUploadUrl(host, fileId string) string {
|
||||
if fs.writeChunkByFiler {
|
||||
return fmt.Sprintf("http://%s/?proxyChunkId=%s", fs.address, fileId)
|
||||
}
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
}
|
||||
|
||||
func (fs *FilerSink) hasSourceNewerVersion(targetPath string, sourceMtime int64) bool {
|
||||
if sourceMtime <= 0 || fs.filerSource == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
sourcePath, ok := fs.targetPathToSourcePath(targetPath)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
sourceEntry, err := filer_pb.GetEntry(context.Background(), fs.filerSource, sourcePath)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("lookup source entry %s: %v", sourcePath, err)
|
||||
return false
|
||||
}
|
||||
if sourceEntry == nil {
|
||||
glog.V(1).Infof("source entry %s no longer exists", sourcePath)
|
||||
return true
|
||||
}
|
||||
|
||||
return sourceEntry.Attributes != nil && sourceEntry.Attributes.Mtime > sourceMtime
|
||||
}
|
||||
|
||||
func (fs *FilerSink) targetPathToSourcePath(targetPath string) (util.FullPath, bool) {
|
||||
if fs.filerSource == nil {
|
||||
return "", false
|
||||
}
|
||||
|
||||
normalizePath := func(p string) string {
|
||||
p = strings.TrimSuffix(p, "/")
|
||||
if p == "" {
|
||||
return "/"
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
sourceRoot := normalizePath(fs.filerSource.Dir)
|
||||
targetRoot := normalizePath(fs.dir)
|
||||
targetPath = normalizePath(targetPath)
|
||||
|
||||
var relative string
|
||||
switch {
|
||||
case targetRoot == "/":
|
||||
relative = strings.TrimPrefix(targetPath, "/")
|
||||
case targetPath == targetRoot:
|
||||
relative = ""
|
||||
case strings.HasPrefix(targetPath, targetRoot+"/"):
|
||||
relative = targetPath[len(targetRoot)+1:]
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
|
||||
if relative == "" {
|
||||
return util.FullPath(sourceRoot), true
|
||||
}
|
||||
return util.FullPath(sourceRoot).Child(relative), true
|
||||
return
|
||||
}
|
||||
|
||||
var _ = filer_pb.FilerClient(&FilerSink{})
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
package filersink
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestTargetPathToSourcePath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
targetRoot string
|
||||
sourceRoot string
|
||||
targetPath string
|
||||
wantPath util.FullPath
|
||||
wantOK bool
|
||||
}{
|
||||
{
|
||||
name: "basic mapping",
|
||||
targetRoot: "/target",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/target/path/file.txt",
|
||||
wantPath: "/source/path/file.txt",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "trailing slash roots",
|
||||
targetRoot: "/target/",
|
||||
sourceRoot: "/source/",
|
||||
targetPath: "/target/path/file.txt",
|
||||
wantPath: "/source/path/file.txt",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "root target mapping",
|
||||
targetRoot: "/",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/path/file.txt",
|
||||
wantPath: "/source/path/file.txt",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "target root itself",
|
||||
targetRoot: "/target",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/target",
|
||||
wantPath: "/source",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "outside target root",
|
||||
targetRoot: "/target",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/other/path/file.txt",
|
||||
wantPath: "",
|
||||
wantOK: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fs := &FilerSink{
|
||||
dir: tc.targetRoot,
|
||||
filerSource: &source.FilerSource{
|
||||
Dir: tc.sourceRoot,
|
||||
},
|
||||
}
|
||||
|
||||
gotPath, ok := fs.targetPathToSourcePath(tc.targetPath)
|
||||
if ok != tc.wantOK {
|
||||
t.Fatalf("ok mismatch: got %v, want %v", ok, tc.wantOK)
|
||||
}
|
||||
if gotPath != tc.wantPath {
|
||||
t.Fatalf("path mismatch: got %q, want %q", gotPath, tc.wantPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,7 @@ func (fs *FilerSink) CreateEntry(key string, entry *filer_pb.Entry, signatures [
|
||||
}
|
||||
}
|
||||
|
||||
replicatedChunks, err := fs.replicateChunks(context.Background(), entry.GetChunks(), key, getEntryMtime(entry))
|
||||
replicatedChunks, err := fs.replicateChunks(entry.GetChunks(), key)
|
||||
|
||||
if err != nil {
|
||||
// only warning here since the source chunk may have been deleted already
|
||||
@@ -211,7 +211,7 @@ func (fs *FilerSink) UpdateEntry(key string, oldEntry *filer_pb.Entry, newParent
|
||||
}
|
||||
|
||||
// replicate the chunks that are new in the source
|
||||
replicatedChunks, err := fs.replicateChunks(context.Background(), newChunks, key, getEntryMtime(newEntry))
|
||||
replicatedChunks, err := fs.replicateChunks(newChunks, key)
|
||||
if err != nil {
|
||||
glog.Warningf("replicate entry chunks %s: %v", key, err)
|
||||
return true, nil
|
||||
@@ -261,10 +261,3 @@ func compareChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunc
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func getEntryMtime(entry *filer_pb.Entry) int64 {
|
||||
if entry == nil || entry.Attributes == nil {
|
||||
return 0
|
||||
}
|
||||
return entry.Attributes.Mtime
|
||||
}
|
||||
@@ -381,7 +381,15 @@ func ExtractConditionValuesFromRequest(r *http.Request) map[string][]string {
|
||||
values := make(map[string][]string)
|
||||
|
||||
// AWS condition keys
|
||||
values["aws:SourceIp"] = []string{extractSourceIP(r)}
|
||||
// Extract IP address without port for proper IP matching
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
// Log a warning if splitting fails
|
||||
glog.Warningf("Failed to parse IP address from RemoteAddr %q: %v", r.RemoteAddr, err)
|
||||
// If splitting fails, use the original RemoteAddr (might be just IP without port)
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
values["aws:SourceIp"] = []string{host}
|
||||
values["aws:SecureTransport"] = []string{fmt.Sprintf("%t", r.TLS != nil)}
|
||||
// Use AWS standard condition key for current time
|
||||
values["aws:CurrentTime"] = []string{time.Now().Format(time.RFC3339)}
|
||||
@@ -437,101 +445,6 @@ func ExtractConditionValuesFromRequest(r *http.Request) map[string][]string {
|
||||
return values
|
||||
}
|
||||
|
||||
// extractSourceIP returns the best-effort client IP address for condition evaluation.
|
||||
// Preference order: X-Forwarded-For (first valid IP), X-Real-Ip, then RemoteAddr.
|
||||
// IMPORTANT: X-Forwarded-For and X-Real-Ip are trusted without validation.
|
||||
// When the service is exposed directly, clients can spoof aws:SourceIp unless a
|
||||
// reverse proxy overwrites these headers.
|
||||
|
||||
// isPrivateIP returns true if the given IP is considered a "trusted proxy"
|
||||
// address, such as loopback, link-local, or RFC1918 private ranges.
|
||||
// isPrivateIP returns true if the given IP is considered a "trusted proxy"
|
||||
// address, such as loopback, link-local, or private ranges.
|
||||
func isPrivateIP(ip net.IP) bool {
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
return ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate()
|
||||
}
|
||||
|
||||
func extractSourceIP(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
remoteAddr := strings.TrimSpace(r.RemoteAddr)
|
||||
if remoteAddr == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Fall back to unix socket markers or other non-IP placeholders.
|
||||
if remoteAddr == "@" {
|
||||
return remoteAddr
|
||||
}
|
||||
|
||||
host := remoteAddr
|
||||
if h, _, err := net.SplitHostPort(remoteAddr); err == nil {
|
||||
host = h
|
||||
}
|
||||
|
||||
remoteIP := net.ParseIP(host)
|
||||
if remoteIP == nil {
|
||||
// Do not return DNS names or unparseable values.
|
||||
return ""
|
||||
}
|
||||
|
||||
// Only trust forwarding headers when the connection appears to come from
|
||||
// a trusted proxy (e.g., private/loopback address).
|
||||
if isPrivateIP(remoteIP) {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
// Iterate right-to-left to find the first non-trusted (public) IP
|
||||
entries := strings.Split(xff, ",")
|
||||
for i := len(entries) - 1; i >= 0; i-- {
|
||||
candidate := strings.TrimSpace(entries[i])
|
||||
if candidate == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
ip := net.ParseIP(candidate)
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// If the IP is trusted/private, we treat it as another proxy in the chain and continue
|
||||
if isPrivateIP(ip) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Found a public/non-trusted IP, return it as the client IP
|
||||
return ip.String()
|
||||
}
|
||||
|
||||
// If we exhausted the list (all were private/trusted) or found no valid IPs,
|
||||
// fallback related logic could go here.
|
||||
// For now, if all are private, we continue to check X-Real-Ip or return RemoteIP?
|
||||
// The prompt implies we should prefer the extracted IP.
|
||||
// If all in XFF are private, likely the original client IS private (internal network).
|
||||
// The best guess for "original client" in a fully trusted chain is the left-most valid IP.
|
||||
for _, candidate := range entries {
|
||||
candidate = strings.TrimSpace(candidate)
|
||||
if ip := net.ParseIP(candidate); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if xRealIP := strings.TrimSpace(r.Header.Get("X-Real-Ip")); xRealIP != "" {
|
||||
if ip := net.ParseIP(xRealIP); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Default to the actual peer IP when no trusted proxy is detected or the
|
||||
// forwarding headers are absent/invalid.
|
||||
return remoteIP.String()
|
||||
}
|
||||
|
||||
// BuildResourceArn builds an ARN for the given bucket and object
|
||||
func BuildResourceArn(bucketName, objectName string) string {
|
||||
if objectName == "" {
|
||||
|
||||
@@ -458,89 +458,6 @@ func TestExtractConditionValuesFromRequest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractConditionValuesFromRequestSourceIPPrecedence(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
header map[string][]string
|
||||
remoteAddr string
|
||||
expectedIP string
|
||||
}{
|
||||
{
|
||||
name: "uses right-most public X-Forwarded-For entry",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"bad-ip, 203.0.113.10, 198.51.100.5"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "198.51.100.5",
|
||||
},
|
||||
{
|
||||
name: "falls back to X-Real-Ip when X-Forwarded-For has no valid ip",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"bad-ip"},
|
||||
"X-Real-Ip": {"198.51.100.7"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "198.51.100.7",
|
||||
},
|
||||
{
|
||||
name: "uses RemoteAddr ip when no forwarding headers",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "192.168.1.100",
|
||||
},
|
||||
{
|
||||
name: "keeps unix socket marker when RemoteAddr is not an ip",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "@",
|
||||
expectedIP: "@",
|
||||
},
|
||||
{
|
||||
name: "uses IPv6 X-Forwarded-For entry",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"2001:db8::8, 198.51.100.7"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "198.51.100.7",
|
||||
},
|
||||
{
|
||||
name: "ignores spoofed IP when real client is public",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"8.8.8.8, 203.0.113.10, 10.0.0.1"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "203.0.113.10",
|
||||
},
|
||||
{
|
||||
name: "handles bracketed IPv6 remote address",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "[2001:db8::1]:12345",
|
||||
expectedIP: "2001:db8::1",
|
||||
},
|
||||
{
|
||||
name: "avoids returning DNS host names",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "example.com:9000",
|
||||
expectedIP: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := &http.Request{
|
||||
Method: "GET",
|
||||
URL: &url.URL{Path: "/"},
|
||||
Header: tt.header,
|
||||
RemoteAddr: tt.remoteAddr,
|
||||
}
|
||||
|
||||
values := ExtractConditionValuesFromRequest(req)
|
||||
if len(values["aws:SourceIp"]) != 1 || values["aws:SourceIp"][0] != tt.expectedIP {
|
||||
t.Errorf("Expected SourceIp %q, got %v", tt.expectedIP, values["aws:SourceIp"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyEvaluationWithConditions(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ const (
|
||||
ExtETagKey = "Seaweed-X-Amz-ETag"
|
||||
ExtLatestVersionIdKey = "Seaweed-X-Amz-Latest-Version-Id"
|
||||
ExtLatestVersionFileNameKey = "Seaweed-X-Amz-Latest-Version-File-Name"
|
||||
ExtAllowEmptyFolders = "Seaweed-X-Amz-Allow-Empty-Folders"
|
||||
ExtS3ImplicitDir = "Seaweed-X-Amz-Implicit-Dir"
|
||||
// Cached list metadata in .versions directory for single-scan efficiency
|
||||
ExtLatestVersionSizeKey = "Seaweed-X-Amz-Latest-Version-Size"
|
||||
ExtLatestVersionETagKey = "Seaweed-X-Amz-Latest-Version-ETag"
|
||||
|
||||
@@ -2,6 +2,7 @@ package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -22,7 +23,7 @@ const (
|
||||
func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
glog.Infof("DeleteObjectHandler %s %s", bucket, object)
|
||||
glog.V(3).Infof("DeleteObjectHandler %s %s", bucket, object)
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
@@ -124,9 +125,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
// Normalize trailing-slash object keys (e.g. "path/") to the
|
||||
// underlying directory entry path so DeleteEntry gets a valid name.
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object)
|
||||
target := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object))
|
||||
dir, name := target.DirAndName()
|
||||
|
||||
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
@@ -341,9 +340,13 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
} else {
|
||||
// Handle non-versioned delete (original logic)
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object.Key)
|
||||
parentDirectoryPath, entryName := target.DirAndName()
|
||||
isDeleteData, isRecursive := true, false
|
||||
lastSeparator := strings.LastIndex(object.Key, "/")
|
||||
parentDirectoryPath, entryName, isDeleteData, isRecursive := "", object.Key, true, false
|
||||
if lastSeparator > 0 && lastSeparator+1 < len(object.Key) {
|
||||
entryName = object.Key[lastSeparator+1:]
|
||||
parentDirectoryPath = object.Key[:lastSeparator]
|
||||
}
|
||||
parentDirectoryPath = fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), parentDirectoryPath)
|
||||
|
||||
err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
|
||||
if err == nil {
|
||||
|
||||
@@ -139,8 +139,6 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
fullDirPath = fullDirPath + "/" + dirName
|
||||
}
|
||||
|
||||
glog.Infof("PutObjectHandler: explicit directory marker %s/%s (contentType=%q, len=%d)",
|
||||
bucket, object, objectContentType, r.ContentLength)
|
||||
if err := s3a.mkdir(
|
||||
fullDirPath, entryName,
|
||||
func(entry *filer_pb.Entry) {
|
||||
|
||||
+16
-98
@@ -1,11 +1,9 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -426,93 +424,6 @@ func (s3a *S3ApiServer) handleCORSOriginValidation(w http.ResponseWriter, r *htt
|
||||
return true
|
||||
}
|
||||
|
||||
// UnifiedPostHandler handles authenticated POST requests to the root path
|
||||
// It inspects the Action parameter to dispatch to either STS or IAM handlers
|
||||
func (s3a *S3ApiServer) UnifiedPostHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// 1. Authenticate (preserves body)
|
||||
identity, errCode := s3a.iam.AuthSignatureOnly(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Parse Form to get Action
|
||||
// Save the body first so we can restore it for STS handler signature verification
|
||||
var bodyBytes []byte
|
||||
if r.Body != nil {
|
||||
// Limit body size to prevent DoS attacks
|
||||
r.Body = http.MaxBytesReader(w, r.Body, iamRequestBodyLimit)
|
||||
var err error
|
||||
bodyBytes, err = io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
glog.Errorf("failed to read request body: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
r.Body.Close()
|
||||
// Restore body for ParseForm
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
||||
}
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Restore body again for downstream handlers (STS needs it for signature verification)
|
||||
if bodyBytes != nil {
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
||||
}
|
||||
|
||||
// 3. Dispatch
|
||||
action := r.Form.Get("Action")
|
||||
if strings.HasPrefix(action, "AssumeRole") {
|
||||
// STS
|
||||
if s3a.stsHandlers == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrServiceUnavailable)
|
||||
return
|
||||
}
|
||||
s3a.stsHandlers.HandleSTSRequest(w, r)
|
||||
} else {
|
||||
// IAM
|
||||
// IAM API requests must be authenticated - reject nil identity
|
||||
if identity == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
|
||||
// Store identity in context
|
||||
// Always set identity in context when non-nil to ensure downstream handlers have access
|
||||
ctx := r.Context()
|
||||
if identity.Name != "" {
|
||||
ctx = SetIdentityNameInContext(ctx, identity.Name)
|
||||
}
|
||||
ctx = SetIdentityInContext(ctx, identity)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
targetUserName := r.Form.Get("UserName")
|
||||
|
||||
// Check permissions based on action type
|
||||
isSelfServiceAction := iamRequiresAdminForOthers(action)
|
||||
isActingOnSelf := targetUserName == "" || targetUserName == identity.Name
|
||||
|
||||
// Permission check is required for all actions except for self-service actions
|
||||
// performed on the user's own identity.
|
||||
if !(isSelfServiceAction && isActingOnSelf) {
|
||||
if !identity.isAdmin() {
|
||||
if s3a.iam.VerifyActionPermission(r, identity, Action("iam:"+action), "arn:aws:iam:::*", "") != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Call Limit middleware + DoActions
|
||||
handler, _ := s3a.cb.Limit(s3a.embeddedIam.DoActions, ACTION_WRITE)
|
||||
handler.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
|
||||
// API Router
|
||||
apiRouter := router.PathPrefix("/").Subrouter()
|
||||
@@ -774,31 +685,38 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
|
||||
// POST / (without specific query parameters)
|
||||
// Uses AuthIam for granular permission checking
|
||||
if s3a.embeddedIam != nil {
|
||||
|
||||
// 2. Authenticated IAM/STS Post requests
|
||||
// 2. Authenticated IAM requests
|
||||
// Only match if the request appears to be authenticated (AWS Signature)
|
||||
// We use a UnifiedPostHandler to dispatch based on Action (STS vs IAM)
|
||||
// AND is not an STS request (which should be handled by STS handlers)
|
||||
iamMatcher := func(r *http.Request, rm *mux.RouteMatch) bool {
|
||||
if getRequestAuthType(r) == authTypeAnonymous {
|
||||
return false
|
||||
}
|
||||
|
||||
// IMPORTANT: We do NOT parse the body here.
|
||||
// UnifiedPostHandler will handle authentication and body parsing.
|
||||
// We only filter out requests that are explicitly targeted at STS via Query params
|
||||
// to avoid double-handling, although UnifiedPostHandler would handle them correctly anyway.
|
||||
// IMPORTANT: Do NOT call r.ParseForm() here!
|
||||
// ParseForm() consumes the request body, which breaks AWS Signature V4 verification
|
||||
// for IAM requests. The signature must be calculated on the original body.
|
||||
// Instead, check only the query string for the Action parameter.
|
||||
|
||||
// Action in Query String is handled by explicit STS routes above
|
||||
// For IAM requests, the Action is typically in the POST body, not query string
|
||||
// So we match all authenticated POST / requests and let AuthIam validate them
|
||||
// This is safe because:
|
||||
// 1. STS actions are excluded (handled by separate STS routes)
|
||||
// 2. S3 operations don't POST to / (they use /<bucket> or /<bucket>/<key>)
|
||||
// 3. IAM operations all POST to /
|
||||
|
||||
// Only exclude STS actions which might be in query string
|
||||
action := r.URL.Query().Get("Action")
|
||||
if action == "AssumeRole" || action == "AssumeRoleWithWebIdentity" || action == "AssumeRoleWithLDAPIdentity" {
|
||||
return false
|
||||
}
|
||||
|
||||
// Match all other authenticated POST / requests (IAM operations)
|
||||
return true
|
||||
}
|
||||
|
||||
apiRouter.Methods(http.MethodPost).Path("/").MatcherFunc(iamMatcher).
|
||||
HandlerFunc(track(s3a.UnifiedPostHandler, "IAM-Unified"))
|
||||
HandlerFunc(track(s3a.embeddedIam.AuthIam(s3a.cb.Limit(s3a.embeddedIam.DoActions, ACTION_WRITE)), "IAM"))
|
||||
|
||||
glog.V(1).Infof("Embedded IAM API enabled on S3 port")
|
||||
}
|
||||
|
||||
@@ -116,7 +116,6 @@ const (
|
||||
|
||||
ErrTooManyRequest
|
||||
ErrRequestBytesExceed
|
||||
ErrServiceUnavailable
|
||||
|
||||
OwnershipControlsNotFoundError
|
||||
ErrNoSuchTagSet
|
||||
@@ -513,11 +512,6 @@ var errorCodeResponse = map[ErrorCode]APIError{
|
||||
Description: "Simultaneous request bytes exceed limitations",
|
||||
HTTPStatusCode: http.StatusServiceUnavailable,
|
||||
},
|
||||
ErrServiceUnavailable: {
|
||||
Code: "ServiceUnavailable",
|
||||
Description: "Service Unavailable",
|
||||
HTTPStatusCode: http.StatusServiceUnavailable,
|
||||
},
|
||||
|
||||
OwnershipControlsNotFoundError: {
|
||||
Code: "OwnershipControlsNotFoundError",
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Minimal mock implementation of AuthenticateJWT needed for testing
|
||||
type mockIAMIntegration struct{}
|
||||
|
||||
func (m *mockIAMIntegration) AuthenticateJWT(ctx context.Context, r *http.Request) (*IAMIdentity, s3err.ErrorCode) {
|
||||
return &IAMIdentity{
|
||||
Name: "test-user",
|
||||
Account: &Account{
|
||||
Id: "test-account",
|
||||
DisplayName: "test-account",
|
||||
EmailAddress: "test@example.com",
|
||||
},
|
||||
Principal: "arn:aws:iam::test-account:user/test-user",
|
||||
SessionToken: "mock-session-token",
|
||||
}, s3err.ErrNone
|
||||
}
|
||||
func (m *mockIAMIntegration) AuthorizeAction(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
func (m *mockIAMIntegration) ValidateTrustPolicyForPrincipal(ctx context.Context, roleArn, principalArn string) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockIAMIntegration) ValidateSessionToken(ctx context.Context, token string) (*sts.SessionInfo, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestSTSAssumeRolePostBody(t *testing.T) {
|
||||
// Setup S3ApiServer with IAM enabled
|
||||
option := &S3ApiServerOption{
|
||||
DomainName: "localhost",
|
||||
EnableIam: true,
|
||||
Filers: []pb.ServerAddress{"localhost:8888"},
|
||||
}
|
||||
|
||||
// Create IAM instance that we can control
|
||||
// We need to bypass the file/store loading logic in NewIdentityAccessManagement
|
||||
// So we construct it manually similarly to how it's done for tests
|
||||
iam := &IdentityAccessManagement{
|
||||
identities: []*Identity{{Name: "test-user"}},
|
||||
isAuthEnabled: true,
|
||||
accessKeyIdent: make(map[string]*Identity),
|
||||
nameToIdentity: make(map[string]*Identity),
|
||||
iamIntegration: &mockIAMIntegration{},
|
||||
}
|
||||
|
||||
// Pre-populate an identity for testing
|
||||
ident := &Identity{
|
||||
Name: "test-user",
|
||||
Credentials: []*Credential{
|
||||
{AccessKey: "test", SecretKey: "test", Status: "Active"},
|
||||
},
|
||||
Actions: nil, // Admin
|
||||
IsStatic: true,
|
||||
}
|
||||
iam.identities[0] = ident
|
||||
iam.accessKeyIdent["test"] = ident
|
||||
iam.nameToIdentity["test-user"] = ident
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: option,
|
||||
iam: iam,
|
||||
embeddedIam: &EmbeddedIamApi{iam: iam, getS3ApiConfigurationFunc: func(cfg *iam_pb.S3ApiConfiguration) error { return nil }},
|
||||
stsHandlers: NewSTSHandlers(nil, iam), // STS service nil -> will return STSErrSTSNotReady (503)
|
||||
credentialManager: nil, // Not needed for this test as we pre-populated IAM
|
||||
cb: &CircuitBreaker{
|
||||
counters: make(map[string]*int64),
|
||||
limitations: make(map[string]int64),
|
||||
},
|
||||
}
|
||||
s3a.cb.s3a = s3a
|
||||
s3a.inFlightDataLimitCond = sync.NewCond(&sync.Mutex{})
|
||||
|
||||
// Create router and register routes
|
||||
router := mux.NewRouter()
|
||||
s3a.registerRouter(router)
|
||||
|
||||
// Test Case 1: STS Action in Query String (Should work - routed to STS)
|
||||
t.Run("ActionInQuery", func(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "/?Action=AssumeRole", nil)
|
||||
// We aren't signing requests, so we expect STSErrAccessDenied (403) from STS handler
|
||||
// due to invalid signature, OR STSErrSTSNotReady (503) if it gets past auth.
|
||||
// The key is it should NOT be 501 Not Implemented (which comes from IAM handler)
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
// If routed to STS, we expect 400 (Bad Request) - MissingParameter
|
||||
// because we didn't provide RoleArn/RoleSessionName etc.
|
||||
// Or 503 if it checks STS service readiness first.
|
||||
|
||||
// Let's see what we get. The STS handler checks parameters first.
|
||||
// "RoleArn is required" -> 400 Bad Request
|
||||
|
||||
assert.NotEqual(t, http.StatusNotImplemented, rr.Code, "Should not return 501 (IAM handler)")
|
||||
assert.Equal(t, http.StatusBadRequest, rr.Code, "Should return 400 (STS handler) for missing params")
|
||||
})
|
||||
|
||||
// Test Case 2: STS Action in Body (Should FAIL current implementation - routed to IAM)
|
||||
t.Run("ActionInBody", func(t *testing.T) {
|
||||
form := url.Values{}
|
||||
form.Add("Action", "AssumeRole")
|
||||
form.Add("RoleArn", "arn:aws:iam::123:role/test")
|
||||
form.Add("RoleSessionName", "session")
|
||||
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
// We need an Authorization header to trigger the IAM matcher
|
||||
// The matcher checks: getRequestAuthType(r) != authTypeAnonymous
|
||||
// So we provide a dummy auth header
|
||||
|
||||
req.Header.Set("Authorization", "Bearer test-token")
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
// CURRENT BEHAVIOR:
|
||||
// The Router does not match "/" for STS because Action is not in query.
|
||||
// The Router matches "/" for IAM because it has Authorization header.
|
||||
// IAM handler (AuthIam) calls DoActions.
|
||||
// DoActions switches on "AssumeRole" -> default -> Not Implemented (501).
|
||||
|
||||
// DESIRED BEHAVIOR (after fix):
|
||||
// Should be routed to UnifiedPostHandler (or similar), detected as STS action,
|
||||
// and routed to STS handler.
|
||||
// STS handler should return 403 Forbidden (Access Denied) or 400 Bad Request
|
||||
// because of signature mismatch (since we provided dummy auth).
|
||||
// It should NOT be 501.
|
||||
|
||||
// For verification of fix, we assert it IS 503 (STS Service Not Initialized).
|
||||
// This confirms it was routed to STS handler.
|
||||
if rr.Code != http.StatusServiceUnavailable {
|
||||
t.Logf("Unexpected status code: %d", rr.Code)
|
||||
t.Logf("Response body: %s", rr.Body.String())
|
||||
}
|
||||
// Confirm it routed to STS
|
||||
assert.Equal(t, http.StatusServiceUnavailable, rr.Code, "Fixed behavior: Should return 503 from STS handler (service not ready)")
|
||||
})
|
||||
|
||||
// Test Case 3: STS Action in Body with SigV4-style Authorization (Real-world scenario)
|
||||
// This test validates that requests with AWS SigV4 Authorization headers and POST body
|
||||
// parameters are correctly routed to the STS handler.
|
||||
t.Run("ActionInBodyWithSigV4Style", func(t *testing.T) {
|
||||
form := url.Values{}
|
||||
form.Add("Action", "AssumeRole")
|
||||
form.Add("RoleArn", "arn:aws:iam::123:role/test")
|
||||
form.Add("RoleSessionName", "session")
|
||||
|
||||
bodyContent := form.Encode()
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(bodyContent))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// Set AWS SigV4-style Authorization header
|
||||
// This simulates a real SigV4-signed request without needing perfect signature
|
||||
// The key is to validate that UnifiedPostHandler correctly routes based on Action
|
||||
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260212/us-east-1/sts/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=dummy")
|
||||
req.Header.Set("x-amz-date", "20260212T000000Z")
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
// With SigV4-style Authorization header, the request should:
|
||||
// 1. Be recognized as authenticated (not anonymous)
|
||||
// 2. Be routed to UnifiedPostHandler
|
||||
// 3. UnifiedPostHandler should parse Action=AssumeRole from body
|
||||
// 4. Route to STS handler (which returns 503 because stsService is nil)
|
||||
// OR return 403 if signature validation fails (which is acceptable)
|
||||
|
||||
// The key validation is that it should NOT return 501 (IAM handler's "Not Implemented")
|
||||
// This confirms the routing fix works for SigV4-signed requests with POST body params
|
||||
|
||||
if rr.Code != http.StatusServiceUnavailable && rr.Code != http.StatusForbidden {
|
||||
t.Logf("Unexpected status code: %d", rr.Code)
|
||||
t.Logf("Response body: %s", rr.Body.String())
|
||||
}
|
||||
|
||||
// Accept either 503 (routed to STS, service unavailable) or 403 (signature failed)
|
||||
// Both indicate correct routing to STS handler, not IAM handler
|
||||
assert.NotEqual(t, http.StatusNotImplemented, rr.Code, "Should not return 501 (IAM handler)")
|
||||
assert.Contains(t, []int{http.StatusServiceUnavailable, http.StatusForbidden}, rr.Code,
|
||||
"Should return 503 (STS unavailable) or 403 (auth failed), confirming STS routing")
|
||||
})
|
||||
}
|
||||
@@ -99,9 +99,9 @@ func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb
|
||||
switch m := req.GetMode(); m {
|
||||
case volume_server_pb.VolumeScrubMode_INDEX:
|
||||
// index scrubs do not verify individual EC shards
|
||||
files, serrs = v.ScrubIndex()
|
||||
files, serrs = v.CheckIndex()
|
||||
case volume_server_pb.VolumeScrubMode_LOCAL:
|
||||
files, shardInfos, serrs = v.ScrubLocal()
|
||||
files, shardInfos, serrs = scrubEcVolumeLocal(ctx, v)
|
||||
case volume_server_pb.VolumeScrubMode_FULL:
|
||||
files, shardInfos, serrs = scrubEcVolumeFull(ctx, v)
|
||||
default:
|
||||
@@ -129,6 +129,10 @@ func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func scrubEcVolumeLocal(ctx context.Context, v *erasure_coding.EcVolume) (int64, []*volume_server_pb.EcShardInfo, []error) {
|
||||
return 0, nil, []error{fmt.Errorf("scrubEcVolumeLocal(): not implemented, see https://github.com/seaweedfs/seaweedfs/issues/8018")}
|
||||
}
|
||||
|
||||
func scrubEcVolumeFull(ctx context.Context, v *erasure_coding.EcVolume) (int64, []*volume_server_pb.EcShardInfo, []error) {
|
||||
return 0, nil, []error{fmt.Errorf("scrubEcVolumeFull(): not implemented, see https://github.com/seaweedfs/seaweedfs/issues/8018")}
|
||||
}
|
||||
@@ -214,13 +214,13 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
sp.regularVolumesStats = RegularVolumesStats{}
|
||||
sp.ecVolumesStats = EcVolumesStats{}
|
||||
|
||||
var statsMu, writerMu sync.Mutex
|
||||
var mu sync.Mutex
|
||||
var progressTotal, progressDone uint64
|
||||
ewg := NewErrorWaitGroup(sp.maxParallelization)
|
||||
|
||||
updateProgress := func() {
|
||||
writerMu.Lock()
|
||||
defer writerMu.Unlock()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
progressDone++
|
||||
sp.write("collecting file stats: %s \r", sp.uint64Pct(progressDone, progressTotal))
|
||||
@@ -230,15 +230,13 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
for _, ri := range dci.RackInfos {
|
||||
for _, dni := range ri.DataNodeInfos {
|
||||
for _, d := range dni.DiskInfos {
|
||||
statsMu.Lock()
|
||||
mu.Lock()
|
||||
progressTotal += uint64(len(d.VolumeInfos))
|
||||
progressTotal += uint64(len(d.EcShardInfos))
|
||||
statsMu.Unlock()
|
||||
mu.Unlock()
|
||||
|
||||
for _, v := range d.VolumeInfos {
|
||||
ewg.Add(func() error {
|
||||
defer updateProgress()
|
||||
|
||||
// Collect regular volume stats
|
||||
err := operation.WithVolumeServerClient(false, pb.NewServerAddressWithGrpcPort(dni.Id, int(dni.GrpcPort)), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
resp, reqErr := volumeServerClient.VolumeStatus(context.Background(), &volume_server_pb.VolumeStatusRequest{
|
||||
@@ -248,8 +246,8 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return reqErr
|
||||
}
|
||||
|
||||
statsMu.Lock()
|
||||
defer statsMu.Unlock()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if resp != nil {
|
||||
if _, ok := sp.regularVolumesStats[v.Id]; !ok {
|
||||
sp.regularVolumesStats[v.Id] = []*VolumeReplicaStats{}
|
||||
@@ -265,24 +263,26 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
updateProgress()
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
for _, eci := range d.EcShardInfos {
|
||||
ewg.Add(func() error {
|
||||
defer updateProgress()
|
||||
|
||||
// Collect EC shard stats
|
||||
statsMu.Lock()
|
||||
|
||||
var err error
|
||||
|
||||
mu.Lock()
|
||||
_, ok := sp.ecVolumesStats[eci.Id]
|
||||
statsMu.Unlock()
|
||||
mu.Unlock()
|
||||
if ok {
|
||||
// this EC volume has been already processed, likely on a different node
|
||||
return nil
|
||||
}
|
||||
|
||||
err := operation.WithVolumeServerClient(false, pb.NewServerAddressWithGrpcPort(dni.Id, int(dni.GrpcPort)), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
err = operation.WithVolumeServerClient(false, pb.NewServerAddressWithGrpcPort(dni.Id, int(dni.GrpcPort)), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
resp, reqErr := volumeServerClient.VolumeEcShardsInfo(context.Background(), &volume_server_pb.VolumeEcShardsInfoRequest{
|
||||
VolumeId: uint32(eci.Id),
|
||||
})
|
||||
@@ -290,8 +290,8 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return reqErr
|
||||
}
|
||||
|
||||
statsMu.Lock()
|
||||
defer statsMu.Unlock()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if resp != nil {
|
||||
sp.ecVolumesStats[eci.Id] = &EcVolumeStats{
|
||||
VolumeId: eci.Id,
|
||||
@@ -303,6 +303,7 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
updateProgress()
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
@@ -49,7 +49,8 @@ func (c *commandEcVolumeScrub) Do(args []string, commandEnv *CommandEnv, writer
|
||||
volScrubCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
nodesStr := volScrubCommand.String("node", "", "comma-separated list of volume server <host>:<port> (optional)")
|
||||
volumeIDsStr := volScrubCommand.String("volumeId", "", "comma-separated EC volume IDs to process (optional)")
|
||||
mode := volScrubCommand.String("mode", "local", "scrubbing mode (index/local/full)")
|
||||
// TODO: switch default mode to LOCAL, once implemented.
|
||||
mode := volScrubCommand.String("mode", "index", "scrubbing mode (index/local/full)")
|
||||
maxParallelization := volScrubCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
|
||||
|
||||
if err = volScrubCommand.Parse(args); err != nil {
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
@@ -40,8 +39,7 @@ func init() {
|
||||
}
|
||||
|
||||
const (
|
||||
readbufferSize = 16
|
||||
jwtFilerTokenExpirationSeconds = 300
|
||||
readbufferSize = 16
|
||||
)
|
||||
|
||||
type commandVolumeFsck struct {
|
||||
@@ -55,7 +53,6 @@ type commandVolumeFsck struct {
|
||||
forcePurging *bool
|
||||
findMissingChunksInFiler *bool
|
||||
verifyNeedle *bool
|
||||
filerSigningKey string
|
||||
}
|
||||
|
||||
func (c *commandVolumeFsck) Name() string {
|
||||
@@ -142,8 +139,6 @@ func (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.
|
||||
}
|
||||
defer os.RemoveAll(c.tempFolder)
|
||||
|
||||
c.filerSigningKey = util.GetViper().GetString("jwt.filer_signing.key")
|
||||
|
||||
// collect all volume id locations
|
||||
dataNodeVolumeIdToVInfo, err := c.collectVolumeIds()
|
||||
if err != nil {
|
||||
@@ -561,12 +556,6 @@ func (c *commandVolumeFsck) httpDelete(path util.FullPath) {
|
||||
Host: c.env.option.FilerAddress.ToHttpAddress(),
|
||||
Path: string(path),
|
||||
}
|
||||
|
||||
if c.filerSigningKey != "" {
|
||||
encodedJwt := security.GenJwtForFilerServer(security.SigningKey(c.filerSigningKey), jwtFilerTokenExpirationSeconds)
|
||||
req.Header.Set("Authorization", "BEARER "+string(encodedJwt))
|
||||
}
|
||||
|
||||
if *c.verbose {
|
||||
fmt.Fprintf(c.writer, "full HTTP delete request to be sent: %v\n", req)
|
||||
}
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Commands = append(Commands, &commandVolumeServerState{})
|
||||
}
|
||||
|
||||
type commandVolumeServerState struct {
|
||||
env *CommandEnv
|
||||
writer io.Writer
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) Name() string {
|
||||
return "volumeServer.state"
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) Help() string {
|
||||
return `query/update volume server state settings
|
||||
|
||||
volumeServer.state [-nodes <host:port>] [..state flags...]
|
||||
|
||||
This command display volume server state flags for the provided
|
||||
list of nodes; if empty, all nodes in the topology are queried.
|
||||
For example:
|
||||
|
||||
volumeServer.state --nodes 192.168.10.111:9000,192.168.10.112:9000
|
||||
|
||||
Additionally, if any flags are provided, these are applied
|
||||
to the selected node(s). The command will display the resulting
|
||||
state for each node *after* the state is updated. For exmaple...
|
||||
|
||||
volumeServer.state --nodes 192.168.10.111:9000 --maintenanceOn
|
||||
|
||||
...will set the specified volume server to maintenance mode.
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) HasTag(CommandTag) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) write(format string, a ...any) {
|
||||
format = strings.TrimRight(format, " ")
|
||||
if len(format) == 0 {
|
||||
format = "\n"
|
||||
}
|
||||
fmt.Fprintf(c.writer, format, a...)
|
||||
|
||||
last := format[len(format)-1:]
|
||||
if last != "\n" && last != "\r" {
|
||||
fmt.Fprint(c.writer, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) bool2Str(b bool) string {
|
||||
if b {
|
||||
return "yes"
|
||||
}
|
||||
return "no"
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
|
||||
vsStateCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
nodesStr := vsStateCommand.String("nodes", "", "comma-separated list of volume servers <host>:<port> (optional)")
|
||||
maintenanceOn := vsStateCommand.Bool("maintenanceOn", false, "enables maintenance mode on the server")
|
||||
maintenanceOff := vsStateCommand.Bool("maintenanceOff", false, "disables maintenance mode on the server")
|
||||
if err = vsStateCommand.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if *maintenanceOn && *maintenanceOff {
|
||||
return fmt.Errorf("--maintenanceOn and --maintenanceOff are mutually exclusive")
|
||||
}
|
||||
|
||||
volumeServerAddrs := []pb.ServerAddress{}
|
||||
if *nodesStr != "" {
|
||||
for _, addr := range strings.Split(*nodesStr, ",") {
|
||||
volumeServerAddrs = append(volumeServerAddrs, pb.ServerAddress(addr))
|
||||
}
|
||||
} else {
|
||||
dns, err := collectDataNodes(commandEnv, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dn := range dns {
|
||||
volumeServerAddrs = append(volumeServerAddrs, pb.ServerAddress(dn.Address))
|
||||
}
|
||||
}
|
||||
slices.Sort(volumeServerAddrs)
|
||||
if len(volumeServerAddrs) == 0 {
|
||||
return fmt.Errorf("no volume servers specified")
|
||||
}
|
||||
|
||||
c.env = commandEnv
|
||||
c.writer = writer
|
||||
|
||||
for _, addr := range volumeServerAddrs {
|
||||
state, err := c.getVolumeServerState(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load state from %v: %v", addr, err)
|
||||
}
|
||||
|
||||
stateOrig := &volume_server_pb.VolumeServerState{}
|
||||
proto.Merge(stateOrig, state)
|
||||
|
||||
// apply updates, if any
|
||||
switch {
|
||||
case *maintenanceOn:
|
||||
state.Maintenance = true
|
||||
case *maintenanceOff:
|
||||
state.Maintenance = false
|
||||
}
|
||||
|
||||
// update volume server state if settings changed
|
||||
if !proto.Equal(state, stateOrig) {
|
||||
state, err = c.setVolumeServerState(addr, state)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update state for %v: %v", addr, err)
|
||||
}
|
||||
}
|
||||
|
||||
c.write("%v\t -> Maintenance mode: %s\n", addr.String(), c.bool2Str(state.GetMaintenance()))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) getVolumeServerState(volumeServerAddress pb.ServerAddress) (*volume_server_pb.VolumeServerState, error) {
|
||||
var state *volume_server_pb.VolumeServerState
|
||||
|
||||
err := operation.WithVolumeServerClient(false, volumeServerAddress, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
res, err := volumeServerClient.GetState(context.Background(), &volume_server_pb.GetStateRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
state = res.GetState()
|
||||
return nil
|
||||
})
|
||||
|
||||
return state, err
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) setVolumeServerState(volumeServerAddress pb.ServerAddress, state *volume_server_pb.VolumeServerState) (*volume_server_pb.VolumeServerState, error) {
|
||||
var stateAfter *volume_server_pb.VolumeServerState
|
||||
|
||||
err := operation.WithVolumeServerClient(false, volumeServerAddress, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
res, err := volumeServerClient.SetState(context.Background(), &volume_server_pb.SetStateRequest{
|
||||
State: state,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stateAfter = res.GetState()
|
||||
return nil
|
||||
})
|
||||
|
||||
return stateAfter, err
|
||||
}
|
||||
@@ -339,3 +339,14 @@ func (ev *EcVolume) WalkIndex(processNeedleFn func(key types.NeedleId, offset ty
|
||||
}
|
||||
return idx.WalkIndexFile(ev.ecxFile, 0, processNeedleFn)
|
||||
}
|
||||
|
||||
func (ev *EcVolume) CheckIndex() (int64, []error) {
|
||||
if ev.ecxFile == nil {
|
||||
return 0, []error{fmt.Errorf("no ECX file associated with EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
if ev.ecxFileSize == 0 {
|
||||
return 0, []error{fmt.Errorf("zero-size ECX file for EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
|
||||
return idx.CheckIndexFile(ev.ecxFile, ev.ecxFileSize, ev.Version)
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// ScrubIndex verifies index integrity of an EC volume.
|
||||
func (ev *EcVolume) ScrubIndex() (int64, []error) {
|
||||
if ev.ecxFile == nil {
|
||||
return 0, []error{fmt.Errorf("no ECX file associated with EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
if ev.ecxFileSize == 0 {
|
||||
return 0, []error{fmt.Errorf("zero-size ECX file for EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
|
||||
return idx.CheckIndexFile(ev.ecxFile, ev.ecxFileSize, ev.Version)
|
||||
}
|
||||
|
||||
// ScrubLocal checks the integrity of local shards for a EC volume. Notably, it cannot verify CRC on needles.
|
||||
// Returns a count of processed file entries, slice of found broken shards, and slice of found errors.
|
||||
func (ecv *EcVolume) ScrubLocal() (int64, []*volume_server_pb.EcShardInfo, []error) {
|
||||
// local scan means verifying indexes as well
|
||||
_, errs := ecv.ScrubIndex()
|
||||
|
||||
brokenShardsMap := map[ShardId]*EcVolumeShard{}
|
||||
var count int64
|
||||
|
||||
flagShardBroken := func(ecs *EcVolumeShard, errFmt string, a ...any) {
|
||||
// reads for EC chunks can hit the same shard multiple times, so dedupe upon read errors
|
||||
brokenShardsMap[ecs.ShardId] = ecs
|
||||
errs = append(errs, fmt.Errorf(errFmt, a...))
|
||||
}
|
||||
|
||||
err := idx.WalkIndexFile(ecv.ecxFile, 0, func(id types.NeedleId, offset types.Offset, size types.Size) error {
|
||||
count++
|
||||
if size.IsTombstone() {
|
||||
// nothing to do for tombstones...
|
||||
return nil
|
||||
}
|
||||
|
||||
var read int64
|
||||
locations := ecv.LocateEcShardNeedleInterval(ecv.Version, offset.ToActualOffset(), size)
|
||||
|
||||
for i, iv := range locations {
|
||||
sid, soffset := iv.ToShardIdAndOffset(ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize)
|
||||
ssize := int64(iv.Size.Raw())
|
||||
shard, found := ecv.FindEcVolumeShard(sid)
|
||||
if !found {
|
||||
// shard is not local :( skip it
|
||||
read += ssize
|
||||
continue
|
||||
}
|
||||
if soffset+int64(ssize) > shard.Size() {
|
||||
flagShardBroken(shard, "local shard %d for needle %d is too short (%d), cannot read chunk %d/%d", sid, id, shard.Size(), i+1, len(locations))
|
||||
continue
|
||||
}
|
||||
|
||||
buf := make([]byte, ssize)
|
||||
got, err := shard.ReadAt(buf, soffset)
|
||||
if err != nil {
|
||||
flagShardBroken(shard, "failed to read chunk %d/%d for needle %d from local shard %d at offset %d: %v", i+1, len(locations), id, sid, soffset, err)
|
||||
continue
|
||||
}
|
||||
if int64(got) != ssize {
|
||||
flagShardBroken(shard, "expected %d bytes for chunk %d/%d for needle %d from local shard %d, got %d", ssize, i+1, len(locations), id, sid, got)
|
||||
continue
|
||||
}
|
||||
read += int64(got)
|
||||
}
|
||||
|
||||
if got, want := read, needle.GetActualSize(size, ecv.Version); got != want {
|
||||
return fmt.Errorf("expected %d bytes for needle %d, got %d", want, id, got)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
// collect broken shard infos for reporting
|
||||
brokenShards := make([]*volume_server_pb.EcShardInfo, 0, len(brokenShardsMap))
|
||||
for _, s := range brokenShardsMap {
|
||||
brokenShards = append(brokenShards, s.ToEcShardInfo())
|
||||
}
|
||||
slices.SortFunc(brokenShards, func(a, b *volume_server_pb.EcShardInfo) int {
|
||||
if a.ShardId < b.ShardId {
|
||||
return -1
|
||||
}
|
||||
if a.ShardId > b.ShardId {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
return count, brokenShards, errs
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
func TestPositioning(t *testing.T) {
|
||||
|
||||
ecxFile, err := os.OpenFile("./test_files/389.ecx", os.O_RDONLY, 0)
|
||||
ecxFile, err := os.OpenFile("../idx/test_files/389.ecx", os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
t.Errorf("failed to open ecx file: %v", err)
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@ func TestCheckIndexFile(t *testing.T) {
|
||||
fmt.Errorf("expected an index file of size 2540, got 2528"),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "healthy EC index",
|
||||
indexPath: "./test_files/389.ecx",
|
||||
version: needle.Version3,
|
||||
want: 485098,
|
||||
wantErrs: []error{},
|
||||
},
|
||||
{
|
||||
name: "healthy EC index with deleted files",
|
||||
indexPath: "./test_files/deleted_files.ecx",
|
||||
|
||||
File renamed without changes.
@@ -132,17 +132,15 @@ func generateLevelDbFile(dbFileName string, indexFile *os.File) error {
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) Get(key NeedleId) (element *needle_map.NeedleValue, ok bool) {
|
||||
bytes := make([]byte, NeedleIdSize)
|
||||
if m.ldbTimeout > 0 {
|
||||
if err := m.ensureLdbLoaded(); err != nil {
|
||||
m.ldbAccessLock.RLock()
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
loadErr := reloadLdb(m)
|
||||
if loadErr != nil {
|
||||
return nil, false
|
||||
}
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
}
|
||||
return m.getFromDb(key)
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) getFromDb(key NeedleId) (element *needle_map.NeedleValue, ok bool) {
|
||||
bytes := make([]byte, NeedleIdSize)
|
||||
NeedleIdToBytes(bytes[0:NeedleIdSize], key)
|
||||
data, err := m.db.Get(bytes, nil)
|
||||
if err != nil || len(data) != OffsetSize+SizeSize {
|
||||
@@ -157,12 +155,14 @@ func (m *LevelDbNeedleMap) Put(key NeedleId, offset Offset, size Size) error {
|
||||
var oldSize Size
|
||||
var watermark uint64
|
||||
if m.ldbTimeout > 0 {
|
||||
if err := m.ensureLdbLoaded(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.ldbAccessLock.RLock()
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
loadErr := reloadLdb(m)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
}
|
||||
}
|
||||
if oldNeedle, ok := m.getFromDb(key); ok {
|
||||
if oldNeedle, ok := m.Get(key); ok {
|
||||
oldSize = oldNeedle.Size
|
||||
}
|
||||
m.logPut(key, oldSize, size)
|
||||
@@ -222,12 +222,14 @@ func levelDbDelete(db *leveldb.DB, key NeedleId) error {
|
||||
func (m *LevelDbNeedleMap) Delete(key NeedleId, offset Offset) error {
|
||||
var watermark uint64
|
||||
if m.ldbTimeout > 0 {
|
||||
if err := m.ensureLdbLoaded(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.ldbAccessLock.RLock()
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
loadErr := reloadLdb(m)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
}
|
||||
}
|
||||
oldNeedle, found := m.getFromDb(key)
|
||||
oldNeedle, found := m.Get(key)
|
||||
if !found || oldNeedle.Size.IsDeleted() {
|
||||
return nil
|
||||
}
|
||||
@@ -398,24 +400,6 @@ func (m *LevelDbNeedleMap) DoOffsetLoading(v *Volume, indexFile *os.File, startF
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) ensureLdbLoaded() error {
|
||||
for {
|
||||
m.ldbAccessLock.RLock()
|
||||
if m.db != nil {
|
||||
return nil
|
||||
}
|
||||
m.ldbAccessLock.RUnlock()
|
||||
m.ldbAccessLock.Lock()
|
||||
if m.db == nil {
|
||||
if err := reloadLdb(m); err != nil {
|
||||
m.ldbAccessLock.Unlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
m.ldbAccessLock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func reloadLdb(m *LevelDbNeedleMap) (err error) {
|
||||
if m.db != nil {
|
||||
return nil
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func TestLevelDbNeedleMap_Concurrency(t *testing.T) {
|
||||
dir, err := os.MkdirTemp("", "test_leveldb_concurrency")
|
||||
if err != nil {
|
||||
t.Fatalf("temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
prefix := "test"
|
||||
indexFile, err := os.Create(filepath.Join(dir, prefix+".idx"))
|
||||
if err != nil {
|
||||
t.Fatalf("create index file: %v", err)
|
||||
}
|
||||
dbFileName := filepath.Join(dir, prefix+".ldb")
|
||||
|
||||
// Create and initialize map
|
||||
m, err := NewLevelDbNeedleMap(dbFileName, indexFile, nil, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLevelDbNeedleMap: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
// Pre-populate some data
|
||||
key := types.NeedleId(1)
|
||||
if err := m.Put(key, types.ToOffset(100), types.Size(200)); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
// Force unload to start from nil state
|
||||
if err := unloadLdb(m); err != nil {
|
||||
t.Fatalf("unloadLdb: %v", err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
startCh := make(chan struct{})
|
||||
errCh := make(chan error, 100)
|
||||
|
||||
// Spawn multiple goroutines to trigger the race
|
||||
// Multiple readers will see m.db == nil and try to reload concurrently
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
<-startCh
|
||||
|
||||
// Try multiple times to increase chance of collision
|
||||
for j := 0; j < 2; j++ {
|
||||
_, ok := m.Get(key)
|
||||
if !ok {
|
||||
// Get failed, possibly due to race in reload.
|
||||
// But we also put data concurrently, so maybe it's missing if deleted?
|
||||
// In this test, we only Put, never Delete. So Key 1 should be there.
|
||||
// However, if DB reload fails, Get returns false!
|
||||
errCh <- fmt.Errorf("routine %d iter %d: Get returned false", id, j)
|
||||
}
|
||||
|
||||
// Also try Put concurrently
|
||||
err := m.Put(types.NeedleId(2+id), types.ToOffset(100), types.Size(200))
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("routine %d iter %d: Put failed: %v", id, j, err)
|
||||
}
|
||||
|
||||
// Manually unload occasionally to reset the state
|
||||
if j%2 == 0 {
|
||||
// This might fail if locked, but that's fine
|
||||
unloadLdb(m)
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
close(startCh)
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
|
||||
for e := range errCh {
|
||||
t.Errorf("Error encountered: %v", e)
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,6 @@ type Offset struct {
|
||||
|
||||
type Size int32
|
||||
|
||||
func (s Size) IsTombstone() bool {
|
||||
return s == TombstoneFileSize
|
||||
}
|
||||
|
||||
// IsDeleted checks if the needle entry has been marked as deleted (tombstoned).
|
||||
// Use this when checking if an entry should exist in the needle map.
|
||||
// Returns true for negative sizes or TombstoneFileSize.
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package util
|
||||
|
||||
import "strings"
|
||||
|
||||
// ExtractBucketPath returns the bucket path under basePath that contains target.
|
||||
// If requireChild is true, the target must include additional segments beyond the bucket itself.
|
||||
func ExtractBucketPath(basePath, target string, requireChild bool) (string, bool) {
|
||||
cleanBase := strings.TrimSuffix(basePath, "/")
|
||||
if cleanBase == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
prefix := cleanBase + "/"
|
||||
if !strings.HasPrefix(target, prefix) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
rest := strings.TrimPrefix(target, prefix)
|
||||
if rest == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
bucketName, _, found := strings.Cut(rest, "/")
|
||||
if bucketName == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
if requireChild && !found {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return prefix + bucketName, true
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package util
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestExtractBucketPath(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
base string
|
||||
target string
|
||||
requireChild bool
|
||||
expected string
|
||||
ok bool
|
||||
}{
|
||||
{
|
||||
name: "child paths return bucket",
|
||||
base: "/buckets",
|
||||
target: "/buckets/test/folder/file",
|
||||
requireChild: true,
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "bucket root without child fails when required",
|
||||
base: "/buckets",
|
||||
target: "/buckets/test",
|
||||
requireChild: true,
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "bucket root allowed when not required",
|
||||
base: "/buckets",
|
||||
target: "/buckets/test",
|
||||
requireChild: false,
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "path outside buckets fails",
|
||||
base: "/buckets",
|
||||
target: "/data/test/folder",
|
||||
requireChild: true,
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "trailing slash on base is normalized",
|
||||
base: "/buckets/",
|
||||
target: "/buckets/test/sub",
|
||||
requireChild: true,
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, ok := ExtractBucketPath(tt.base, tt.target, tt.requireChild)
|
||||
if ok != tt.ok {
|
||||
t.Fatalf("expected ok=%v, got %v", tt.ok, ok)
|
||||
}
|
||||
if got != tt.expected {
|
||||
t.Fatalf("expected path %q, got %q", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user