Compare commits

..
Author SHA1 Message Date
Chris Lu 5fc2fefb4a Fix STS credential validation by providing default configuration
When no STS configuration is provided in the IAM config file, the STS
service was not being initialized, causing temporary credentials from
AssumeRole to be rejected with "InvalidAccessKeyId" errors.

This commit adds a DefaultSTSConfig() function that provides sensible
defaults (1h token duration, 12h max session, secure random signing key)
and updates the IAM manager to use these defaults when no explicit STS
configuration is provided.

Changes:
- Add DefaultSTSConfig() with secure random signing key generation
- Update IAM manager to use default config when config.STS is nil
- Add tests verifying initialization with and without explicit config

Fixes #8312
2026-02-12 13:36:33 -08:00
Chris Lu 6e393f3326 Improve error handling in UnifiedPostHandler
- Add http.MaxBytesReader to limit body size to 10 MiB (iamRequestBodyLimit)
- Add proper error handling for io.ReadAll failures
- Log errors when body reading fails
- Prevents DoS attacks from oversized request bodies
- Addresses code review feedback
2026-02-12 12:58:22 -08:00
Chris Lu 7939e5808e Fix: preserve request body for STS signature verification
- Save and restore request body in UnifiedPostHandler after ParseForm()
- This allows STS handler to verify signatures correctly
- Fixes 'invalid AWS signature: 53' error (ErrContentSHA256Mismatch)
- ParseForm() consumes the body, so we need to restore it for downstream handlers
2026-02-12 12:35:52 -08:00
147 changed files with 971 additions and 27160 deletions

No files matched your search

+6 -24
View File
@@ -15,20 +15,24 @@ permissions:
jobs:
vet:
name: Go Vet
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.x
uses: actions/setup-go@a5f9b05d2d216f63e13859e0d847461041025775 # v2
with:
go-version: ^1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v2
- name: Get dependencies
run: |
cd weed; go get -v -t -d ./...
- name: Go Vet (excluding protobuf lock copying)
run: |
cd weed
@@ -38,30 +42,8 @@ jobs:
# Fail only if there are actual vet errors (not counting the filtered lock warnings)
if grep -q "vet:" vet-output.txt; then exit 1; fi
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.x
uses: actions/setup-go@a5f9b05d2d216f63e13859e0d847461041025775 # v2
with:
go-version: ^1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v2
- name: Build
run: cd weed; go build -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v .
test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.x
uses: actions/setup-go@a5f9b05d2d216f63e13859e0d847461041025775 # v2
with:
go-version: ^1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v2
- name: Test
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
-69
View File
@@ -394,75 +394,6 @@ jobs:
path: test/s3tables/sts_integration/test-output.log
retention-days: 3
lakekeeper-integration-tests:
name: Lakekeeper 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: Pre-pull LocalStack image (if needed)
run: docker pull localstack/localstack:latest || true
- name: Run go mod tidy
run: go mod tidy
- name: Install SeaweedFS
run: |
go install -buildvcs=false ./weed
- name: Run Lakekeeper Integration Tests
timeout-minutes: 25
working-directory: test/s3tables/lakekeeper
run: |
set -x
set -o pipefail
echo "=== System Information ==="
uname -a
free -h
df -h
echo "=== Starting Lakekeeper Integration Tests ==="
# Run Lakekeeper integration tests
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
echo "Lakekeeper integration tests failed"
exit 1
}
- name: Show test output on failure
if: failure()
working-directory: test/s3tables/lakekeeper
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: lakekeeper-integration-test-logs
path: test/s3tables/lakekeeper/test-output.log
retention-days: 3
s3-tables-build-verification:
name: S3 Tables Build Verification
runs-on: ubuntu-22.04
@@ -1,170 +0,0 @@
name: "Volume Server Integration Tests"
on:
pull_request:
branches: [ master ]
paths:
- 'test/volume_server/**'
- 'weed/server/**'
- 'weed/storage/**'
- 'weed/pb/volume_server.proto'
- 'weed/pb/volume_server_pb/**'
- 'rust/volume_server/**'
- '.github/workflows/volume-server-integration-tests.yml'
push:
branches: [ master, main ]
paths:
- 'test/volume_server/**'
- 'weed/server/**'
- 'weed/storage/**'
- 'weed/pb/volume_server.proto'
- 'weed/pb/volume_server_pb/**'
- 'rust/volume_server/**'
- '.github/workflows/volume-server-integration-tests.yml'
concurrency:
group: ${{ github.head_ref || github.ref }}/volume-server-integration-tests
cancel-in-progress: true
permissions:
contents: read
env:
GO_VERSION: '1.24'
TEST_TIMEOUT: '30m'
jobs:
volume-server-integration-tests:
name: Volume Server Integration Tests (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
runs-on: ubuntu-22.04
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
test-type: [grpc, http]
shard: [1, 2, 3]
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Set up Go ${{ env.GO_VERSION }}
uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
- name: Build SeaweedFS binary
run: |
cd weed
go build -o weed .
chmod +x weed
./weed version
- name: Run volume server integration tests
env:
WEED_BINARY: ${{ github.workspace }}/weed/weed
run: |
if [ "${{ matrix.test-type }}" == "grpc" ]; then
if [ "${{ matrix.shard }}" == "1" ]; then
TEST_PATTERN="^Test[A-H]"
elif [ "${{ matrix.shard }}" == "2" ]; then
TEST_PATTERN="^Test[I-S]"
else
TEST_PATTERN="^Test[T-Z]"
fi
else
if [ "${{ matrix.shard }}" == "1" ]; then
TEST_PATTERN="^Test[A-G]"
elif [ "${{ matrix.shard }}" == "2" ]; then
TEST_PATTERN="^Test[H-R]"
else
TEST_PATTERN="^Test[S-Z]"
fi
fi
echo "Running volume server integration tests for ${{ matrix.test-type }} (Shard ${{ matrix.shard }}, pattern: ${TEST_PATTERN})..."
go test -v -count=1 -timeout=${{ env.TEST_TIMEOUT }} ./test/volume_server/${{ matrix.test-type }}/... -run "${TEST_PATTERN}"
- name: Collect logs on failure
if: failure()
run: |
mkdir -p /tmp/volume-server-it-logs
find /tmp -maxdepth 1 -type d -name "seaweedfs_volume_server_it_*" -print -exec cp -r {} /tmp/volume-server-it-logs/ \; || true
- name: Archive logs on failure
if: failure()
uses: actions/upload-artifact@v6
with:
name: volume-server-integration-test-logs
path: /tmp/volume-server-it-logs/
if-no-files-found: warn
retention-days: 7
- name: Test summary
if: always()
run: |
if [ "${{ matrix.test-type }}" == "grpc" ]; then
if [ "${{ matrix.shard }}" == "1" ]; then
TEST_PATTERN="^Test[A-H]"
elif [ "${{ matrix.shard }}" == "2" ]; then
TEST_PATTERN="^Test[I-S]"
else
TEST_PATTERN="^Test[T-Z]"
fi
else
if [ "${{ matrix.shard }}" == "1" ]; then
TEST_PATTERN="^Test[A-G]"
elif [ "${{ matrix.shard }}" == "2" ]; then
TEST_PATTERN="^Test[H-R]"
else
TEST_PATTERN="^Test[S-Z]"
fi
fi
echo "## Volume Server Integration Test Summary (${{ matrix.test-type }} - Shard ${{ matrix.shard }})" >> "$GITHUB_STEP_SUMMARY"
echo "- Suite: test/volume_server/${{ matrix.test-type }} (Pattern: ${TEST_PATTERN})" >> "$GITHUB_STEP_SUMMARY"
echo "- Command: go test -v -count=1 -timeout=${{ env.TEST_TIMEOUT }} ./test/volume_server/${{ matrix.test-type }}/... -run \"${TEST_PATTERN}\"" >> "$GITHUB_STEP_SUMMARY"
volume-server-rust-smoke:
name: Volume Server Rust Smoke
runs-on: ubuntu-22.04
timeout-minutes: 40
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Set up Go ${{ env.GO_VERSION }}
uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
- name: Set up Rust toolchain
uses: dtolnay/rust-toolchain@stable
- name: Build SeaweedFS binary
run: |
cd weed
go build -o weed .
chmod +x weed
./weed version
- name: Run Rust-mode HTTP smoke tests
env:
WEED_BINARY: ${{ github.workspace }}/weed/weed
VOLUME_SERVER_IMPL: rust
run: |
go test -v -count=1 -timeout=25m ./test/volume_server/http/... -run "TestAdminStatusAndHealthz|TestUploadReadRangeHeadDeleteRoundTrip"
- name: Run Rust-mode gRPC smoke tests
env:
WEED_BINARY: ${{ github.workspace }}/weed/weed
VOLUME_SERVER_IMPL: rust
run: |
go test -v -count=1 -timeout=25m ./test/volume_server/grpc/... -run "TestStateAndStatusRPCs|TestVolumeSyncStatusAndReadVolumeFileStatus"
- name: Rust smoke summary
if: always()
run: |
echo "## Volume Server Rust Smoke Summary" >> "$GITHUB_STEP_SUMMARY"
echo "- Mode: Go master + Rust volume server launcher (VOLUME_SERVER_IMPL=rust)" >> "$GITHUB_STEP_SUMMARY"
echo "- HTTP Command: go test -v -count=1 -timeout=25m ./test/volume_server/http/... -run \"TestAdminStatusAndHealthz|TestUploadReadRangeHeadDeleteRoundTrip\"" >> "$GITHUB_STEP_SUMMARY"
echo "- gRPC Command: go test -v -count=1 -timeout=25m ./test/volume_server/grpc/... -run \"TestStateAndStatusRPCs|TestVolumeSyncStatusAndReadVolumeFileStatus\"" >> "$GITHUB_STEP_SUMMARY"
@@ -134,7 +134,7 @@ spec:
{{- if .Values.worker.adminServer }}
-admin={{ .Values.worker.adminServer }} \
{{- else }}
-admin={{ template "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
-admin={{ include "seaweedfs.componentName" (list . "admin") }}.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
{{- end }}
-capabilities={{ .Values.worker.capabilities }} \
-maxConcurrent={{ .Values.worker.maxConcurrent }} \
-7
View File
@@ -1,7 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "weed-volume-rs"
version = "0.1.0"
-6
View File
@@ -1,6 +0,0 @@
[package]
name = "weed-volume-rs"
version = "0.1.0"
edition = "2021"
[dependencies]
-61
View File
@@ -1,61 +0,0 @@
# Rust Volume Server Rewrite Dev Plan
## Goal
Build a Rust implementation of SeaweedFS volume server that is behavior-compatible with the current Go implementation and can pass the existing integration suites under `/Users/chris/dev/seaweedfs2/test/volume_server/http` and `/Users/chris/dev/seaweedfs2/test/volume_server/grpc`.
## Compatibility Target
- CLI compatibility for volume-server startup flags used by integration harness.
- HTTP and gRPC behavioral parity for tested paths.
- Drop-in process integration with current Go master in transition phases.
## Phases
### Phase 0: Bootstrap and Harness Integration
- [x] Add Rust volume-server crate.
- [x] Implement Rust launcher that can run as a volume-server process entrypoint.
- [x] Add integration harness switches so tests can run with:
- Go master + Go volume (default)
- Go master + Rust volume (`VOLUME_SERVER_IMPL=rust` or `VOLUME_SERVER_BINARY=...`)
- [ ] Add CI smoke coverage for Rust volume-server mode.
### Phase 1: Native Rust Control Plane Skeleton
- [ ] Native Rust HTTP server with admin endpoints:
- [ ] `GET /status`
- [ ] `GET /healthz`
- [ ] static/UI endpoints used by tests
- [ ] Native Rust gRPC server with basic lifecycle/state RPCs:
- [ ] `GetState`, `SetState`, `VolumeServerStatus`, `Ping`, `VolumeServerLeave`
- [ ] Flag/config parser parity for currently exercised startup options.
### Phase 2: Native Data Path (HTTP + core gRPC)
- [ ] HTTP read/write/delete parity:
- [ ] path variants, conditional headers, ranges, auth, throttling
- [ ] chunk manifest read/delete behavior
- [ ] image and compression transform branches
- [ ] gRPC data RPC parity:
- [ ] `ReadNeedleBlob`, `ReadNeedleMeta`, `WriteNeedleBlob`
- [ ] `BatchDelete`, `ReadAllNeedles`
- [ ] copy/receive/sync baseline
### Phase 3: Advanced gRPC Surface
- [ ] Vacuum RPC family.
- [ ] Tail sender/receiver.
- [ ] Erasure coding family.
- [ ] Tiering/remote fetch family.
- [ ] Query/Scrub family.
### Phase 4: Hardening and Cutover
- [ ] Determinism/flake hardening in integration runtime.
- [ ] Performance and resource-baseline checks versus Go.
- [ ] Optional dual-run diff tooling for payload/header parity.
- [ ] Default harness/CI mode switch to Rust volume server once parity threshold is met.
## Integration Test Mapping
- HTTP suite: `/Users/chris/dev/seaweedfs2/test/volume_server/http`
- gRPC suite: `/Users/chris/dev/seaweedfs2/test/volume_server/grpc`
- Harness: `/Users/chris/dev/seaweedfs2/test/volume_server/framework`
## Progress Log
- Date: 2026-02-15
- Change: Created Rust volume-server crate (`weed-volume-rs`) as compatibility launcher and wired harness binary selection (`VOLUME_SERVER_IMPL`/`VOLUME_SERVER_BINARY`).
- Validation: Rust-mode conformance smoke execution pending CI and local subset runs.
-177
View File
@@ -1,177 +0,0 @@
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::{Command, ExitCode};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("weed-volume-rs: {err}");
ExitCode::from(1)
}
}
}
fn run() -> Result<(), String> {
let args: Vec<String> = env::args().skip(1).collect();
if args.iter().any(|a| a == "-h" || a == "--help") {
print_help();
return Ok(());
}
if args.iter().any(|a| a == "--version") {
println!("weed-volume-rs 0.1.0");
return Ok(());
}
let mut forwarded = Vec::<String>::new();
let has_volume_subcommand = args.iter().any(|a| a == "volume");
if has_volume_subcommand {
forwarded.extend(args);
} else {
forwarded.push("volume".to_string());
forwarded.extend(args);
}
let weed_binary = resolve_weed_binary()?;
#[cfg(unix)]
{
let exec_err = Command::new(&weed_binary).args(&forwarded).exec();
return Err(format!(
"exec {} failed: {}",
weed_binary.display(),
exec_err
));
}
#[cfg(not(unix))]
{
let status = Command::new(&weed_binary)
.args(&forwarded)
.status()
.map_err(|e| format!("spawn {} failed: {}", weed_binary.display(), e))?;
if status.success() {
return Ok(());
}
return Err(format!(
"delegated process {} exited with status {}",
weed_binary.display(),
status
));
}
}
fn print_help() {
println!("weed-volume-rs");
println!();
println!("Rust compatibility launcher for SeaweedFS volume server.");
println!("It forwards all volume-server flags to the Go weed binary.");
println!();
println!("Examples:");
println!(" weed-volume-rs -ip=127.0.0.1 -port=8080 -master=127.0.0.1:9333 ...");
println!(" weed-volume-rs volume -ip=127.0.0.1 -port=8080 -master=127.0.0.1:9333 ...");
}
fn resolve_weed_binary() -> Result<PathBuf, String> {
if let Some(from_env) = env::var_os("WEED_BINARY") {
let path = PathBuf::from(from_env);
if is_executable_file(&path) {
return Ok(path);
}
return Err(format!(
"WEED_BINARY is set but not executable: {}",
path.display()
));
}
let repo_root = resolve_repo_root()?;
let local_weed = repo_root.join("weed").join("weed");
if is_executable_file(&local_weed) {
return Ok(local_weed);
}
let bin_dir = env::temp_dir().join("seaweedfs_volume_server_it_bin");
std::fs::create_dir_all(&bin_dir)
.map_err(|e| format!("create binary directory {}: {}", bin_dir.display(), e))?;
let bin_path = bin_dir.join("weed");
if is_executable_file(&bin_path) {
return Ok(bin_path);
}
build_weed_binary(&repo_root, &bin_path)?;
if !is_executable_file(&bin_path) {
return Err(format!(
"built weed binary is not executable: {}",
bin_path.display()
));
}
Ok(bin_path)
}
fn resolve_repo_root() -> Result<PathBuf, String> {
if let Some(from_env) = env::var_os("SEAWEEDFS_REPO_ROOT") {
return Ok(PathBuf::from(from_env));
}
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let repo_root = manifest_dir
.parent()
.and_then(|p| p.parent())
.ok_or_else(|| "unable to detect repository root from CARGO_MANIFEST_DIR".to_string())?;
Ok(repo_root.to_path_buf())
}
fn build_weed_binary(repo_root: &PathBuf, output_path: &PathBuf) -> Result<(), String> {
let mut cmd = Command::new("go");
cmd.arg("build").arg("-o").arg(output_path).arg(".");
cmd.current_dir(repo_root.join("weed"));
let output = cmd
.output()
.map_err(|e| format!("failed to execute go build: {}", e))?;
if output.status.success() {
return Ok(());
}
let mut msg = String::new();
msg.push_str("go build failed");
if !output.stdout.is_empty() {
msg.push_str("\nstdout:\n");
msg.push_str(&String::from_utf8_lossy(&output.stdout));
}
if !output.stderr.is_empty() {
msg.push_str("\nstderr:\n");
msg.push_str(&String::from_utf8_lossy(&output.stderr));
}
Err(msg)
}
fn is_executable_file(path: &PathBuf) -> bool {
let metadata = match std::fs::metadata(path) {
Ok(v) => v,
Err(_) => return false,
};
if !metadata.is_file() {
return false;
}
#[cfg(unix)]
{
metadata.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
{
true
}
}
#[allow(dead_code)]
fn _collect_os_args() -> Vec<OsString> {
env::args_os().collect()
}
@@ -41,7 +41,7 @@
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.11.5</version>
<version>1.11.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@@ -1,82 +0,0 @@
package iam
import (
"encoding/xml"
"io"
"net/http"
"net/url"
"os"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestSTSTemporaryCredentialPrefix verifies that STS temporary credentials use ASIA prefix
// This test ensures AWS compatibility - temporary credentials should use ASIA, not AKIA
func TestSTSTemporaryCredentialPrefix(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !isSTSEndpointRunning(t) {
t.Skip("SeaweedFS STS endpoint is not running at", TestSTSEndpoint)
}
// Use test credentials from environment or fall back to defaults
accessKey := os.Getenv("STS_TEST_ACCESS_KEY")
if accessKey == "" {
accessKey = "admin"
}
secretKey := os.Getenv("STS_TEST_SECRET_KEY")
if secretKey == "" {
secretKey = "admin"
}
t.Run("assume_role_returns_asia_prefix", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/admin"},
"RoleSessionName": {"asia-prefix-test"},
}, accessKey, secretKey)
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if resp.StatusCode != http.StatusOK {
t.Logf("Response status: %d, body: %s", resp.StatusCode, string(body))
t.Skip("AssumeRole not fully implemented yet")
}
var stsResp AssumeRoleTestResponse
err = xml.Unmarshal(body, &stsResp)
require.NoError(t, err, "Failed to parse response: %s", string(body))
creds := stsResp.Result.Credentials
require.NotEmpty(t, creds.AccessKeyId, "AccessKeyId should not be empty")
// Verify ASIA prefix for temporary credentials
assert.True(t, strings.HasPrefix(creds.AccessKeyId, "ASIA"),
"Temporary credentials must use ASIA prefix (not AKIA for permanent keys), got: %s", creds.AccessKeyId)
// Verify it's NOT using AKIA (permanent credentials)
assert.False(t, strings.HasPrefix(creds.AccessKeyId, "AKIA"),
"Temporary credentials must NOT use AKIA prefix (that's for permanent IAM keys), got: %s", creds.AccessKeyId)
// Verify format: ASIA + 16 hex characters = 20 chars total
assert.Equal(t, 20, len(creds.AccessKeyId),
"Access key ID should be 20 characters (ASIA + 16 hex chars), got: %s", creds.AccessKeyId)
t.Logf("✓ Temporary credentials correctly use ASIA prefix: %s", creds.AccessKeyId)
})
t.Run("assume_role_with_web_identity_returns_asia_prefix", func(t *testing.T) {
// This test would require OIDC setup, so we'll skip it for now
// but the same ASIA prefix validation should apply
t.Skip("AssumeRoleWithWebIdentity requires OIDC provider setup")
})
}
@@ -1,219 +0,0 @@
package catalog_risingwave
import (
"fmt"
"strings"
"testing"
"time"
)
func TestRisingWaveIcebergDML(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")
icebergUri := env.dockerIcebergEndpoint()
s3Endpoint := env.dockerS3Endpoint()
// 1. Test INSERT (Append-only)
t.Run("TestInsert", func(t *testing.T) {
tableName := "test_insert_" + randomString(6)
createIcebergTable(t, env, tableBucket, "default", tableName)
rwTableName := "rw_insert_" + randomString(6)
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("CREATE TABLE %s (id int, name varchar);", rwTableName))
sinkName := "test_sink_insert_" + randomString(6)
createSinkSql := fmt.Sprintf(`
CREATE SINK %s FROM %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',
type = 'append-only',
force_append_only = 'true'
);`, sinkName, rwTableName, icebergUri, tableName, tableBucket, s3Endpoint, env.accessKey, env.secretKey)
t.Logf(">>> Creating sink %s...", sinkName)
runRisingWaveSQL(t, env.postgresSidecar, createSinkSql)
t.Log(">>> Inserting into RisingWave table...")
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("INSERT INTO %s VALUES (1, 'Alice'), (2, 'Bob');", rwTableName))
runRisingWaveSQL(t, env.postgresSidecar, "FLUSH;")
// Verify with Source
sourceName := "test_source_insert_" + 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)
runRisingWaveSQL(t, env.postgresSidecar, createSourceSql)
t.Log(">>> Selecting from source to verify INSERT...")
verifyQuery(t, env, sourceName, "1 | Alice", "2 | Bob")
})
// 2. Test UPSERT (Update/Delete)
t.Run("TestUpsert", func(t *testing.T) {
tableName := "test_upsert_" + randomString(6)
// We need a table with PK for upsert to work effectively in RW logic,
// effectively maps to Iceberg v2 table.
createIcebergTable(t, env, tableBucket, "default", tableName)
rwTableName := "rw_upsert_" + randomString(6)
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("CREATE TABLE %s (id int PRIMARY KEY, name varchar);", rwTableName))
sinkName := "test_sink_upsert_" + randomString(6)
createSinkSql := fmt.Sprintf(`
CREATE SINK %s FROM %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',
type = 'upsert', -- Upsert mode
primary_key = 'id'
);`, sinkName, rwTableName, icebergUri, tableName, tableBucket, s3Endpoint, env.accessKey, env.secretKey)
t.Logf(">>> Creating upsert sink %s...", sinkName)
runRisingWaveSQL(t, env.postgresSidecar, createSinkSql)
t.Log(">>> Inserting initial data...")
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("INSERT INTO %s VALUES (1, 'Charlie'), (2, 'Dave');", rwTableName))
runRisingWaveSQL(t, env.postgresSidecar, "FLUSH;")
// Update 1, Delete 2
t.Log(">>> Updating and Deleting data...")
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("UPDATE %s SET name = 'Charles' WHERE id = 1;", rwTableName))
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("DELETE FROM %s WHERE id = 2;", rwTableName))
runRisingWaveSQL(t, env.postgresSidecar, "FLUSH;")
// Verify with Source
sourceName := "test_source_upsert_" + 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)
runRisingWaveSQL(t, env.postgresSidecar, createSourceSql)
t.Log(">>> Selecting from source to verify UPSERT...")
// Should see (1, 'Charles') and NOT (2, 'Dave')
verifyQuery(t, env, sourceName, "1 | Charles")
verifyQueryAbsence(t, env, sourceName, "2 | Dave")
})
}
func verifyQuery(t *testing.T, env *TestEnvironment, sourceName string, expectedSubstrings ...string) {
t.Helper()
var output string
for i := 0; i < 15; i++ {
output = runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("SELECT * FROM %s ORDER BY id;", sourceName))
allFound := true
for _, s := range expectedSubstrings {
if !strings.Contains(output, s) {
allFound = false
break
}
}
if allFound {
return
}
time.Sleep(2 * time.Second)
}
t.Fatalf("Failed to find expected data %v in output:\n%s", expectedSubstrings, output)
}
func verifyQueryAbsence(t *testing.T, env *TestEnvironment, sourceName string, unexpectedSubstrings ...string) {
t.Helper()
var output string
for i := 0; i < 15; i++ {
output = runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("SELECT * FROM %s ORDER BY id;", sourceName))
noneFound := true
for _, s := range unexpectedSubstrings {
if strings.Contains(output, s) {
noneFound = false
break
}
}
if noneFound {
return
}
time.Sleep(2 * time.Second)
}
t.Fatalf("Found unexpected data %v in output:\n%s", unexpectedSubstrings, output)
}
-341
View File
@@ -1,341 +0,0 @@
package lakekeeper
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/s3tables/testutil"
)
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
accessKey string
secretKey string
}
func TestLakekeeperIntegration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !testutil.HasDocker() {
t.Skip("Docker not available, skipping Lakekeeper integration test")
}
env := NewTestEnvironment(t)
defer env.Cleanup(t)
fmt.Printf(">>> Starting SeaweedFS with Lakekeeper configuration...\n")
env.StartSeaweedFS(t)
fmt.Printf(">>> SeaweedFS started.\n")
// Run python script in docker to test STS and S3 operations
runLakekeeperRepro(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")
if _, err := os.Stat(weedBinary); err != nil {
weedBinary = "weed"
if _, err := exec.LookPath(weedBinary); err != nil {
t.Skip("weed binary not found, skipping integration test")
}
}
dataDir, err := os.MkdirTemp("", "seaweed-lakekeeper-test-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
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")
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,
accessKey: "admin",
secretKey: "admin",
}
}
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
t.Helper()
iamConfigPath := filepath.Join(env.dataDir, "iam.json")
// Note: signingKey must be base64 encoded for []byte JSON unmarshaling
iamConfig := fmt.Sprintf(`{
"identities": [
{
"name": "admin",
"credentials": [
{
"accessKey": "%s",
"secretKey": "%s"
}
],
"actions": ["Admin", "Read", "List", "Tagging", "Write"]
}
],
"sts": {
"tokenDuration": "12h",
"maxSessionLength": "24h",
"issuer": "seaweedfs-sts",
"signingKey": "dGVzdC1zaWduaW5nLWtleS1mb3Itc3RzLWludGVncmF0aW9uLXRlc3Rz"
},
"roles": [
{
"roleName": "LakekeeperVendedRole",
"roleArn": "arn:aws:iam::000000000000:role/LakekeeperVendedRole",
"trustPolicy": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "sts:AssumeRole"
}
]
},
"attachedPolicies": ["FullAccess"]
}
],
"policies": [
{
"name": "FullAccess",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
]
}
}
]
}`, env.accessKey, env.secretKey)
if err := os.WriteFile(iamConfigPath, []byte(iamConfig), 0644); err != nil {
t.Fatalf("Failed to create IAM config: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
env.weedCancel = cancel
// Start weed mini with both S3 config (standard IAM) and IAM config (advanced IAM/STS)
cmd := exec.CommandContext(ctx, env.weedBinary, "-v", "4", "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,
"-s3.iam.config", iamConfigPath,
"-s3.iam.readOnly=false",
"-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
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) 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 runLakekeeperRepro(t *testing.T, env *TestEnvironment) {
t.Helper()
scriptContent := fmt.Sprintf(`
import boto3
import botocore.config
import botocore
from botocore.exceptions import ClientError
import os
import sys
import time
import logging
# Enable botocore debug logging to see signature calculation
logging.basicConfig(level=logging.DEBUG)
botocore.session.get_session().set_debug_logger()
print("Starting Lakekeeper repro test...")
endpoint_url = "http://host.docker.internal:%d"
access_key = "%s"
secret_key = "%s"
region = "us-east-1"
print(f"Connecting to {endpoint_url}")
try:
config = botocore.config.Config(
retries={'max_attempts': 3}
)
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/LakekeeperVendedRole"
session_name = "lakekeeper-session"
print(f"Calling AssumeRole on {role_arn} with POST body...")
# Standard boto3 call sends parameters in POST body
response = sts.assume_role(
RoleArn=role_arn,
RoleSessionName=session_name
)
creds = response['Credentials']
access_key_id = creds['AccessKeyId']
secret_access_key = creds['SecretAccessKey']
session_token = creds['SessionToken']
print(f"Success! Got credentials with prefix: {access_key_id[:4]}")
if not access_key_id.startswith("ASIA"):
print(f"FAILED: Expected ASIA prefix, got {access_key_id}")
sys.exit(1)
print("Verifying S3 operations with vended credentials...")
s3 = boto3.client(
's3',
endpoint_url=endpoint_url,
aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key,
aws_session_token=session_token,
region_name=region,
config=config
)
bucket = "lakekeeper-vended-bucket"
print(f"Creating bucket {bucket}...")
s3.create_bucket(Bucket=bucket)
print("Listing buckets...")
response = s3.list_buckets()
buckets = [b['Name'] for b in response['Buckets']]
print(f"Found buckets: {buckets}")
if bucket not in buckets:
print(f"FAILED: Bucket {bucket} not found in list")
sys.exit(1)
print("SUCCESS: Lakekeeper flow verified!")
sys.exit(0)
except Exception as e:
print(f"FAILED: {e}")
# Print more details if it is a ClientError
if hasattr(e, 'response'):
print(f"Response: {e.response}")
sys.exit(1)
`, env.s3Port, env.accessKey, env.secretKey)
scriptPath := filepath.Join(env.dataDir, "lakekeeper_repro.py")
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0644); err != nil {
t.Fatalf("Failed to write python script: %v", err)
}
containerName := "seaweed-lakekeeper-client-" + fmt.Sprintf("%d", time.Now().UnixNano())
// Create a context with timeout for the docker run command
dockerCtx, dockerCancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer dockerCancel()
cmd := exec.CommandContext(dockerCtx, "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/lakekeeper_repro.py",
)
output, err := cmd.CombinedOutput()
if err != nil {
if dockerCtx.Err() == context.DeadlineExceeded {
t.Fatalf("Lakekeeper repro client timed out after 5 minutes\nOutput:\n%s", string(output))
}
t.Fatalf("Lakekeeper repro client failed: %v\nOutput:\n%s", err, string(output))
}
t.Logf("Lakekeeper repro client output:\n%s", string(output))
}
@@ -33,8 +33,6 @@ type TestEnvironment struct {
secretKey string
}
const testSTSIntegrationSigningKey = "dGVzdC1zaWduaW5nLWtleS1mb3Itc3RzLWludGVncmF0aW9uLXRlc3Rz" // gitleaks:allow - test-signing-key-for-sts-integration-tests
func TestSTSIntegration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
@@ -112,70 +110,17 @@ func NewTestEnvironment(t *testing.T) *TestEnvironment {
volumePort: volumePort,
volumeGrpcPort: volumeGrpcPort,
dockerAvailable: testutil.HasDocker(),
accessKey: "admin",
secretKey: "adminadmin",
accessKey: "admin", // Matching default in testutil.WriteIAMConfig
secretKey: "admin",
}
}
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
t.Helper()
iamConfigPath := filepath.Join(env.dataDir, "iam.json")
// Note: signingKey must be base64 encoded for []byte JSON unmarshaling
iamConfig := fmt.Sprintf(`{
"identities": [
{
"name": "admin",
"credentials": [
{ "accessKey": "%s", "secretKey": "%s" }
],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
}
],
"sts": {
"tokenDuration": "1h",
"maxSessionLength": "12h",
"issuer": "seaweedfs-sts",
"signingKey": "%s"
},
"policy": {
"defaultEffect": "Deny",
"storeType": "memory"
},
"policies": [
{
"name": "S3FullAccessPolicy",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:*"],
"Resource": ["*"]
}
]
}
}
],
"roles": [
{
"roleName": "TestRole",
"roleArn": "arn:aws:iam::role/TestRole",
"attachedPolicies": ["S3FullAccessPolicy"],
"trustPolicy": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": ["sts:AssumeRole"]
}
]
}
}
]
}`, env.accessKey, env.secretKey, testSTSIntegrationSigningKey)
if err := os.WriteFile(iamConfigPath, []byte(iamConfig), 0644); err != nil {
// 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)
}
@@ -198,8 +143,6 @@ func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
"-s3.port", fmt.Sprintf("%d", env.s3Port),
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
"-s3.config", iamConfigPath,
"-s3.iam.config", iamConfigPath,
"-s3.iam.readOnly", "false",
"-ip", env.bindIP,
"-ip.bind", "0.0.0.0",
"-dir", env.dataDir,
@@ -247,62 +190,22 @@ func runPythonSTSClient(t *testing.T, env *TestEnvironment) {
import boto3
import botocore.config
from botocore.exceptions import ClientError
import json
import os
import sys
import time
import urllib.error
import urllib.request
print("Starting STS inline session policy test...")
print("Starting STS test...")
primary_endpoint = "http://host.docker.internal:%d"
fallback_endpoint = "http://%s:%d"
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:
def wait_for_endpoint(url, timeout=30):
deadline = time.time() + timeout
while time.time() < deadline:
try:
with urllib.request.urlopen(url, timeout=2):
return True
except urllib.error.HTTPError:
return True
except Exception:
time.sleep(1)
return False
def select_endpoint(urls):
for url in urls:
if wait_for_endpoint(url):
return url
raise Exception("No reachable S3 endpoint from container")
endpoint_url = select_endpoint([primary_endpoint, fallback_endpoint])
print(f"Using endpoint {endpoint_url}")
config = botocore.config.Config(
retries={'max_attempts': 0},
s3={'addressing_style': 'path'}
retries={'max_attempts': 0}
)
admin_s3 = boto3.client(
's3',
endpoint_url=endpoint_url,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name=region,
config=config
)
bucket = f"sts-inline-policy-{int(time.time() * 1000)}"
key = "allowed.txt"
print(f"Creating bucket {bucket} with admin credentials")
admin_s3.create_bucket(Bucket=bucket)
admin_s3.put_object(Bucket=bucket, Key=key, Body=b"ok")
sts = boto3.client(
'sts',
endpoint_url=endpoint_url,
@@ -312,77 +215,45 @@ try:
config=config
)
role_arn = "arn:aws:iam::role/TestRole"
role_arn = "arn:aws:iam::000000000000:role/test-role"
session_name = "test-session"
session_policy = json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": [f"arn:aws:s3:::{bucket}"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{bucket}/*"]
}
]
})
print(f"Calling AssumeRole on {role_arn} with inline session policy")
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,
Policy=session_policy
RoleSessionName=session_name
)
creds = response['Credentials']
vended_s3 = boto3.client(
's3',
endpoint_url=endpoint_url,
aws_access_key_id=creds['AccessKeyId'],
aws_secret_access_key=creds['SecretAccessKey'],
aws_session_token=creds['SessionToken'],
region_name=region,
config=config
)
print("Listing objects (allowed)")
list_resp = vended_s3.list_objects_v2(Bucket=bucket)
keys = [obj.get('Key') for obj in list_resp.get('Contents', [])]
if key not in keys:
print(f"FAILED: Expected to see {key} in list_objects_v2 results")
sys.exit(1)
print("Getting object (allowed)")
body = vended_s3.get_object(Bucket=bucket, Key=key)['Body'].read()
if body != b"ok":
print("FAILED: Unexpected object content")
sys.exit(1)
print("Putting object (expected to be denied)")
try:
vended_s3.put_object(Bucket=bucket, Key="denied.txt", Body=b"no")
print("FAILED: PutObject unexpectedly succeeded")
sys.exit(1)
except ClientError as e:
error_code = e.response.get('Error', {}).get('Code', '')
if error_code != 'AccessDenied':
print(f"FAILED: Expected AccessDenied, got {error_code}")
sys.exit(1)
print("PutObject correctly denied by inline session policy")
print("SUCCESS: Inline session policy downscoping verified")
sys.exit(0)
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}")
if hasattr(e, 'response'):
print(f"Response: {e.response}")
import traceback
traceback.print_exc()
sys.exit(1)
`, env.s3Port, env.bindIP, env.s3Port, env.accessKey, env.secretKey)
`, env.s3Port, env.accessKey, env.secretKey)
scriptPath := filepath.Join(env.dataDir, "sts_test.py")
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0644); err != nil {
File diff suppressed because it is too large. Load diff
-10
View File
@@ -1,10 +0,0 @@
.PHONY: test-volume-server test-volume-server-short test-volume-server-rust-smoke
test-volume-server:
go test ./test/volume_server/... -v
test-volume-server-short:
go test ./test/volume_server/... -short -v
test-volume-server-rust-smoke:
VOLUME_SERVER_IMPL=rust go test ./test/volume_server/http ./test/volume_server/grpc -run 'TestAdminStatusAndHealthz|TestUploadReadRangeHeadDeleteRoundTrip|TestStateAndStatusRPCs|TestVolumeSyncStatusAndReadVolumeFileStatus' -v
-30
View File
@@ -1,30 +0,0 @@
# Volume Server Integration Tests
This package contains integration tests for SeaweedFS volume server HTTP and gRPC APIs.
## Run Tests
Run tests from repo root:
```bash
go test ./test/volume_server/... -v
```
If a `weed` binary is not found, the harness will build one automatically.
## Optional environment variables
- `WEED_BINARY`: explicit path to the `weed` executable (disables auto-build).
- `VOLUME_SERVER_IMPL`: select volume-server implementation (`go` default, `rust` for Rust launcher mode).
- `VOLUME_SERVER_BINARY`: explicit path to the volume-server executable (overrides `VOLUME_SERVER_IMPL`).
- `VOLUME_SERVER_RUST_REBUILD=1`: force rebuild of Rust volume-server binary in Rust mode.
- `VOLUME_SERVER_IT_KEEP_LOGS=1`: keep temporary test directories and process logs.
## Current scope (Phase 0)
- Shared cluster/framework utilities
- Matrix profile definitions
- Initial HTTP admin endpoint checks
- Initial gRPC state/status checks
More API coverage is tracked in `/Users/chris/dev/seaweedfs2/test/volume_server/DEV_PLAN.md`.
-515
View File
@@ -1,515 +0,0 @@
package framework
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
const (
defaultWaitTimeout = 30 * time.Second
defaultWaitTick = 200 * time.Millisecond
testVolumeSizeLimitMB = 32
)
// Cluster is a lightweight SeaweedFS master + one volume server test harness.
type Cluster struct {
testingTB testing.TB
profile matrix.Profile
weedBinary string
volumeBinary string
baseDir string
configDir string
logsDir string
keepLogs bool
masterPort int
masterGrpcPort int
volumePort int
volumeGrpcPort int
volumePubPort int
masterCmd *exec.Cmd
volumeCmd *exec.Cmd
cleanupOnce sync.Once
}
// StartSingleVolumeCluster boots one master and one volume server.
func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
t.Helper()
weedBinary, volumeBinary, err := FindOrBuildServerBinaries()
if err != nil {
t.Fatalf("resolve server binaries: %v", err)
}
baseDir, keepLogs, err := newWorkDir()
if err != nil {
t.Fatalf("create temp test directory: %v", err)
}
configDir := filepath.Join(baseDir, "config")
logsDir := filepath.Join(baseDir, "logs")
masterDataDir := filepath.Join(baseDir, "master")
volumeDataDir := filepath.Join(baseDir, "volume")
for _, dir := range []string{configDir, logsDir, masterDataDir, volumeDataDir} {
if mkErr := os.MkdirAll(dir, 0o755); mkErr != nil {
t.Fatalf("create %s: %v", dir, mkErr)
}
}
if err = writeSecurityConfig(configDir, profile); err != nil {
t.Fatalf("write security config: %v", err)
}
masterPort, masterGrpcPort, err := allocateMasterPortPair()
if err != nil {
t.Fatalf("allocate master port pair: %v", err)
}
ports, err := allocatePorts(3)
if err != nil {
t.Fatalf("allocate ports: %v", err)
}
c := &Cluster{
testingTB: t,
profile: profile,
weedBinary: weedBinary,
volumeBinary: volumeBinary,
baseDir: baseDir,
configDir: configDir,
logsDir: logsDir,
keepLogs: keepLogs,
masterPort: masterPort,
masterGrpcPort: masterGrpcPort,
volumePort: ports[0],
volumeGrpcPort: ports[1],
volumePubPort: ports[0],
}
if profile.SplitPublicPort {
c.volumePubPort = ports[2]
}
if err = c.startMaster(masterDataDir); err != nil {
c.Stop()
t.Fatalf("start master: %v", err)
}
if err = c.waitForHTTP(c.MasterURL() + "/dir/status"); err != nil {
masterLog := c.tailLog("master.log")
c.Stop()
t.Fatalf("wait for master readiness: %v\nmaster log tail:\n%s", err, masterLog)
}
if err = c.startVolume(volumeDataDir); err != nil {
masterLog := c.tailLog("master.log")
c.Stop()
t.Fatalf("start volume: %v\nmaster log tail:\n%s", err, masterLog)
}
if err = c.waitForHTTP(c.VolumeAdminURL() + "/status"); err != nil {
volumeLog := c.tailLog("volume.log")
c.Stop()
t.Fatalf("wait for volume readiness: %v\nvolume log tail:\n%s", err, volumeLog)
}
if err = c.waitForTCP(c.VolumeGRPCAddress()); err != nil {
volumeLog := c.tailLog("volume.log")
c.Stop()
t.Fatalf("wait for volume grpc readiness: %v\nvolume log tail:\n%s", err, volumeLog)
}
t.Cleanup(func() {
c.Stop()
})
return c
}
// Stop terminates all processes and cleans temporary files.
func (c *Cluster) Stop() {
if c == nil {
return
}
c.cleanupOnce.Do(func() {
stopProcess(c.volumeCmd)
stopProcess(c.masterCmd)
if !c.keepLogs && !c.testingTB.Failed() {
_ = os.RemoveAll(c.baseDir)
} else if c.baseDir != "" {
c.testingTB.Logf("volume server integration logs kept at %s", c.baseDir)
}
})
}
func (c *Cluster) startMaster(dataDir string) error {
logFile, err := os.Create(filepath.Join(c.logsDir, "master.log"))
if err != nil {
return err
}
args := []string{
"-config_dir=" + c.configDir,
"master",
"-ip=127.0.0.1",
"-port=" + strconv.Itoa(c.masterPort),
"-port.grpc=" + strconv.Itoa(c.masterGrpcPort),
"-mdir=" + dataDir,
"-peers=none",
"-volumeSizeLimitMB=" + strconv.Itoa(testVolumeSizeLimitMB),
"-defaultReplication=000",
}
c.masterCmd = exec.Command(c.weedBinary, args...)
c.masterCmd.Dir = c.baseDir
c.masterCmd.Stdout = logFile
c.masterCmd.Stderr = logFile
return c.masterCmd.Start()
}
func (c *Cluster) startVolume(dataDir string) error {
logFile, err := os.Create(filepath.Join(c.logsDir, "volume.log"))
if err != nil {
return err
}
args := []string{
"-config_dir=" + c.configDir,
"volume",
"-ip=127.0.0.1",
"-port=" + strconv.Itoa(c.volumePort),
"-port.grpc=" + strconv.Itoa(c.volumeGrpcPort),
"-port.public=" + strconv.Itoa(c.volumePubPort),
"-dir=" + dataDir,
"-max=16",
"-master=127.0.0.1:" + strconv.Itoa(c.masterPort),
"-readMode=" + c.profile.ReadMode,
"-concurrentUploadLimitMB=" + strconv.Itoa(c.profile.ConcurrentUploadLimitMB),
"-concurrentDownloadLimitMB=" + strconv.Itoa(c.profile.ConcurrentDownloadLimitMB),
}
if c.profile.InflightUploadTimeout > 0 {
args = append(args, "-inflightUploadDataTimeout="+c.profile.InflightUploadTimeout.String())
}
if c.profile.InflightDownloadTimeout > 0 {
args = append(args, "-inflightDownloadDataTimeout="+c.profile.InflightDownloadTimeout.String())
}
c.volumeCmd = exec.Command(c.volumeBinary, args...)
c.volumeCmd.Dir = c.baseDir
c.volumeCmd.Stdout = logFile
c.volumeCmd.Stderr = logFile
return c.volumeCmd.Start()
}
func (c *Cluster) waitForHTTP(url string) error {
client := &http.Client{Timeout: 1 * time.Second}
deadline := time.Now().Add(defaultWaitTimeout)
for time.Now().Before(deadline) {
resp, err := client.Get(url)
if err == nil {
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
if resp.StatusCode < 500 {
return nil
}
}
time.Sleep(defaultWaitTick)
}
return fmt.Errorf("timed out waiting for %s", url)
}
func (c *Cluster) waitForTCP(addr string) error {
deadline := time.Now().Add(defaultWaitTimeout)
for time.Now().Before(deadline) {
conn, err := net.DialTimeout("tcp", addr, time.Second)
if err == nil {
_ = conn.Close()
return nil
}
time.Sleep(defaultWaitTick)
}
return fmt.Errorf("timed out waiting for tcp %s", addr)
}
func stopProcess(cmd *exec.Cmd) {
if cmd == nil || cmd.Process == nil {
return
}
_ = cmd.Process.Signal(os.Interrupt)
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(10 * time.Second):
_ = cmd.Process.Kill()
<-done
case <-done:
}
}
func allocatePorts(count int) ([]int, error) {
listeners := make([]net.Listener, 0, count)
ports := make([]int, 0, count)
for i := 0; i < count; i++ {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
for _, ll := range listeners {
_ = ll.Close()
}
return nil, err
}
listeners = append(listeners, l)
ports = append(ports, l.Addr().(*net.TCPAddr).Port)
}
for _, l := range listeners {
_ = l.Close()
}
return ports, nil
}
func allocateMasterPortPair() (int, int, error) {
for masterPort := 10000; masterPort <= 55535; masterPort++ {
masterGrpcPort := masterPort + 10000
l1, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(masterPort)))
if err != nil {
continue
}
l2, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(masterGrpcPort)))
if err != nil {
_ = l1.Close()
continue
}
_ = l2.Close()
_ = l1.Close()
return masterPort, masterGrpcPort, nil
}
return 0, 0, errors.New("unable to find available master port pair")
}
func newWorkDir() (dir string, keepLogs bool, err error) {
keepLogs = os.Getenv("VOLUME_SERVER_IT_KEEP_LOGS") == "1"
dir, err = os.MkdirTemp("", "seaweedfs_volume_server_it_")
return dir, keepLogs, err
}
func writeSecurityConfig(configDir string, profile matrix.Profile) error {
var b strings.Builder
if profile.EnableJWT {
if profile.JWTSigningKey == "" || profile.JWTReadKey == "" {
return errors.New("jwt profile requires both write and read keys")
}
b.WriteString("[jwt.signing]\n")
b.WriteString("key = \"")
b.WriteString(profile.JWTSigningKey)
b.WriteString("\"\n")
b.WriteString("expires_after_seconds = 60\n\n")
b.WriteString("[jwt.signing.read]\n")
b.WriteString("key = \"")
b.WriteString(profile.JWTReadKey)
b.WriteString("\"\n")
b.WriteString("expires_after_seconds = 60\n")
}
if b.Len() == 0 {
b.WriteString("# optional security config generated for integration tests\n")
}
return os.WriteFile(filepath.Join(configDir, "security.toml"), []byte(b.String()), 0o644)
}
// FindOrBuildWeedBinary returns an executable weed binary, building one when needed.
func FindOrBuildWeedBinary() (string, error) {
if fromEnv := os.Getenv("WEED_BINARY"); fromEnv != "" {
if isExecutableFile(fromEnv) {
return fromEnv, nil
}
return "", fmt.Errorf("WEED_BINARY is set but not executable: %s", fromEnv)
}
repoRoot, err := detectRepoRoot()
if err != nil {
return "", err
}
if candidate := filepath.Join(repoRoot, "weed", "weed"); isExecutableFile(candidate) {
return candidate, nil
}
binDir := filepath.Join(os.TempDir(), "seaweedfs_volume_server_it_bin")
if err := os.MkdirAll(binDir, 0o755); err != nil {
return "", fmt.Errorf("create binary directory %s: %w", binDir, err)
}
binPath := filepath.Join(binDir, "weed")
if isExecutableFile(binPath) {
return binPath, nil
}
cmd := exec.Command("go", "build", "-o", binPath, ".")
cmd.Dir = filepath.Join(repoRoot, "weed")
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("build weed binary: %w\n%s", err, out.String())
}
if !isExecutableFile(binPath) {
return "", fmt.Errorf("built weed binary is not executable: %s", binPath)
}
return binPath, nil
}
// FindOrBuildServerBinaries returns master and volume executables.
// Master always runs from the Go weed binary; volume can be switched via env.
func FindOrBuildServerBinaries() (masterBinary string, volumeBinary string, err error) {
masterBinary, err = FindOrBuildWeedBinary()
if err != nil {
return "", "", err
}
volumeBinary, err = FindOrBuildVolumeServerBinary(masterBinary)
if err != nil {
return "", "", err
}
return masterBinary, volumeBinary, nil
}
// FindOrBuildVolumeServerBinary resolves the executable used for volume-server processes.
//
// Behavior:
// - `VOLUME_SERVER_BINARY=/path/to/bin`: use explicit executable path.
// - `VOLUME_SERVER_IMPL=rust`: build/use Rust volume server launcher.
// - default: use the same Go `weed` binary.
func FindOrBuildVolumeServerBinary(defaultBinary string) (string, error) {
if fromEnv := os.Getenv("VOLUME_SERVER_BINARY"); fromEnv != "" {
if isExecutableFile(fromEnv) {
return fromEnv, nil
}
return "", fmt.Errorf("VOLUME_SERVER_BINARY is set but not executable: %s", fromEnv)
}
impl := strings.ToLower(strings.TrimSpace(os.Getenv("VOLUME_SERVER_IMPL")))
if impl == "" || impl == "go" {
return defaultBinary, nil
}
if impl != "rust" {
return "", fmt.Errorf("unsupported VOLUME_SERVER_IMPL %q (supported: go, rust)", impl)
}
repoRoot, err := detectRepoRoot()
if err != nil {
return "", err
}
return FindOrBuildRustVolumeServerBinary(repoRoot)
}
// FindOrBuildRustVolumeServerBinary builds the Rust volume server launcher when needed.
func FindOrBuildRustVolumeServerBinary(repoRoot string) (string, error) {
manifestPath := filepath.Join(repoRoot, "rust", "volume_server", "Cargo.toml")
if _, err := os.Stat(manifestPath); err != nil {
return "", fmt.Errorf("rust volume server manifest not found at %s: %w", manifestPath, err)
}
targetDir := filepath.Join(os.TempDir(), "seaweedfs_volume_server_it_rust_target")
binPath := filepath.Join(targetDir, "release", "weed-volume-rs")
if isExecutableFile(binPath) && os.Getenv("VOLUME_SERVER_RUST_REBUILD") != "1" {
return binPath, nil
}
cmd := exec.Command("cargo", "build", "--release", "--manifest-path", manifestPath, "--target-dir", targetDir)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("build rust volume server binary: %w\n%s", err, out.String())
}
if !isExecutableFile(binPath) {
return "", fmt.Errorf("built rust volume server binary is not executable: %s", binPath)
}
return binPath, nil
}
func detectRepoRoot() (string, error) {
if _, file, _, ok := runtime.Caller(0); ok {
return filepath.Clean(filepath.Join(filepath.Dir(file), "..", "..", "..")), nil
}
return "", errors.New("unable to detect repository root")
}
func isExecutableFile(path string) bool {
info, err := os.Stat(path)
if err != nil || info.IsDir() {
return false
}
mode := info.Mode().Perm()
return mode&0o111 != 0
}
func (c *Cluster) tailLog(logName string) string {
f, err := os.Open(filepath.Join(c.logsDir, logName))
if err != nil {
return ""
}
defer f.Close()
scanner := bufio.NewScanner(f)
lines := make([]string, 0, 40)
for scanner.Scan() {
lines = append(lines, scanner.Text())
if len(lines) > 40 {
lines = lines[1:]
}
}
return strings.Join(lines, "\n")
}
func (c *Cluster) MasterAddress() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.masterPort))
}
func (c *Cluster) VolumeAdminAddress() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumePort))
}
func (c *Cluster) VolumePublicAddress() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumePubPort))
}
func (c *Cluster) VolumeGRPCAddress() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumeGrpcPort))
}
// VolumeServerAddress returns SeaweedFS server address format: ip:httpPort.grpcPort
func (c *Cluster) VolumeServerAddress() string {
return fmt.Sprintf("%s.%d", c.VolumeAdminAddress(), c.volumeGrpcPort)
}
func (c *Cluster) MasterURL() string {
return "http://" + c.MasterAddress()
}
func (c *Cluster) VolumeAdminURL() string {
return "http://" + c.VolumeAdminAddress()
}
func (c *Cluster) VolumePublicURL() string {
return "http://" + c.VolumePublicAddress()
}
func (c *Cluster) BaseDir() string {
return c.baseDir
}
@@ -1,295 +0,0 @@
package framework
import (
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
type DualVolumeCluster struct {
testingTB testing.TB
profile matrix.Profile
weedBinary string
volumeBinary string
baseDir string
configDir string
logsDir string
keepLogs bool
masterPort int
masterGrpcPort int
volumePort0 int
volumeGrpcPort0 int
volumePubPort0 int
volumePort1 int
volumeGrpcPort1 int
volumePubPort1 int
masterCmd *exec.Cmd
volumeCmd0 *exec.Cmd
volumeCmd1 *exec.Cmd
cleanupOnce sync.Once
}
func StartDualVolumeCluster(t testing.TB, profile matrix.Profile) *DualVolumeCluster {
t.Helper()
weedBinary, volumeBinary, err := FindOrBuildServerBinaries()
if err != nil {
t.Fatalf("resolve server binaries: %v", err)
}
baseDir, keepLogs, err := newWorkDir()
if err != nil {
t.Fatalf("create temp test directory: %v", err)
}
configDir := filepath.Join(baseDir, "config")
logsDir := filepath.Join(baseDir, "logs")
masterDataDir := filepath.Join(baseDir, "master")
volumeDataDir0 := filepath.Join(baseDir, "volume0")
volumeDataDir1 := filepath.Join(baseDir, "volume1")
for _, dir := range []string{configDir, logsDir, masterDataDir, volumeDataDir0, volumeDataDir1} {
if mkErr := os.MkdirAll(dir, 0o755); mkErr != nil {
t.Fatalf("create %s: %v", dir, mkErr)
}
}
if err = writeSecurityConfig(configDir, profile); err != nil {
t.Fatalf("write security config: %v", err)
}
masterPort, masterGrpcPort, err := allocateMasterPortPair()
if err != nil {
t.Fatalf("allocate master port pair: %v", err)
}
ports, err := allocatePorts(6)
if err != nil {
t.Fatalf("allocate volume ports: %v", err)
}
c := &DualVolumeCluster{
testingTB: t,
profile: profile,
weedBinary: weedBinary,
volumeBinary: volumeBinary,
baseDir: baseDir,
configDir: configDir,
logsDir: logsDir,
keepLogs: keepLogs,
masterPort: masterPort,
masterGrpcPort: masterGrpcPort,
volumePort0: ports[0],
volumeGrpcPort0: ports[1],
volumePubPort0: ports[0],
volumePort1: ports[2],
volumeGrpcPort1: ports[3],
volumePubPort1: ports[2],
}
if profile.SplitPublicPort {
c.volumePubPort0 = ports[4]
c.volumePubPort1 = ports[5]
}
if err = c.startMaster(masterDataDir); err != nil {
c.Stop()
t.Fatalf("start master: %v", err)
}
if err = c.waitForHTTP(c.MasterURL() + "/dir/status"); err != nil {
masterLog := c.tailLog("master.log")
c.Stop()
t.Fatalf("wait for master readiness: %v\nmaster log tail:\n%s", err, masterLog)
}
if err = c.startVolume(0, volumeDataDir0); err != nil {
masterLog := c.tailLog("master.log")
c.Stop()
t.Fatalf("start first volume server: %v\nmaster log tail:\n%s", err, masterLog)
}
if err = c.waitForHTTP(c.VolumeAdminURL(0) + "/status"); err != nil {
volumeLog := c.tailLog("volume0.log")
c.Stop()
t.Fatalf("wait for first volume readiness: %v\nvolume log tail:\n%s", err, volumeLog)
}
if err = c.waitForTCP(c.VolumeGRPCAddress(0)); err != nil {
volumeLog := c.tailLog("volume0.log")
c.Stop()
t.Fatalf("wait for first volume grpc readiness: %v\nvolume log tail:\n%s", err, volumeLog)
}
if err = c.startVolume(1, volumeDataDir1); err != nil {
volumeLog := c.tailLog("volume0.log")
c.Stop()
t.Fatalf("start second volume server: %v\nfirst volume log tail:\n%s", err, volumeLog)
}
if err = c.waitForHTTP(c.VolumeAdminURL(1) + "/status"); err != nil {
volumeLog := c.tailLog("volume1.log")
c.Stop()
t.Fatalf("wait for second volume readiness: %v\nvolume log tail:\n%s", err, volumeLog)
}
if err = c.waitForTCP(c.VolumeGRPCAddress(1)); err != nil {
volumeLog := c.tailLog("volume1.log")
c.Stop()
t.Fatalf("wait for second volume grpc readiness: %v\nvolume log tail:\n%s", err, volumeLog)
}
t.Cleanup(func() {
c.Stop()
})
return c
}
func (c *DualVolumeCluster) Stop() {
if c == nil {
return
}
c.cleanupOnce.Do(func() {
stopProcess(c.volumeCmd1)
stopProcess(c.volumeCmd0)
stopProcess(c.masterCmd)
if !c.keepLogs && !c.testingTB.Failed() {
_ = os.RemoveAll(c.baseDir)
} else if c.baseDir != "" {
c.testingTB.Logf("volume server integration logs kept at %s", c.baseDir)
}
})
}
func (c *DualVolumeCluster) startMaster(dataDir string) error {
logFile, err := os.Create(filepath.Join(c.logsDir, "master.log"))
if err != nil {
return err
}
args := []string{
"-config_dir=" + c.configDir,
"master",
"-ip=127.0.0.1",
"-port=" + strconv.Itoa(c.masterPort),
"-port.grpc=" + strconv.Itoa(c.masterGrpcPort),
"-mdir=" + dataDir,
"-peers=none",
"-volumeSizeLimitMB=" + strconv.Itoa(testVolumeSizeLimitMB),
"-defaultReplication=000",
}
c.masterCmd = exec.Command(c.weedBinary, args...)
c.masterCmd.Dir = c.baseDir
c.masterCmd.Stdout = logFile
c.masterCmd.Stderr = logFile
return c.masterCmd.Start()
}
func (c *DualVolumeCluster) startVolume(index int, dataDir string) error {
logName := fmt.Sprintf("volume%d.log", index)
logFile, err := os.Create(filepath.Join(c.logsDir, logName))
if err != nil {
return err
}
volumePort := c.volumePort0
volumeGrpcPort := c.volumeGrpcPort0
volumePubPort := c.volumePubPort0
if index == 1 {
volumePort = c.volumePort1
volumeGrpcPort = c.volumeGrpcPort1
volumePubPort = c.volumePubPort1
}
args := []string{
"-config_dir=" + c.configDir,
"volume",
"-ip=127.0.0.1",
"-port=" + strconv.Itoa(volumePort),
"-port.grpc=" + strconv.Itoa(volumeGrpcPort),
"-port.public=" + strconv.Itoa(volumePubPort),
"-dir=" + dataDir,
"-max=16",
"-master=127.0.0.1:" + strconv.Itoa(c.masterPort),
"-readMode=" + c.profile.ReadMode,
"-concurrentUploadLimitMB=" + strconv.Itoa(c.profile.ConcurrentUploadLimitMB),
"-concurrentDownloadLimitMB=" + strconv.Itoa(c.profile.ConcurrentDownloadLimitMB),
}
if c.profile.InflightUploadTimeout > 0 {
args = append(args, "-inflightUploadDataTimeout="+c.profile.InflightUploadTimeout.String())
}
if c.profile.InflightDownloadTimeout > 0 {
args = append(args, "-inflightDownloadDataTimeout="+c.profile.InflightDownloadTimeout.String())
}
cmd := exec.Command(c.volumeBinary, args...)
cmd.Dir = c.baseDir
cmd.Stdout = logFile
cmd.Stderr = logFile
if err = cmd.Start(); err != nil {
return err
}
if index == 1 {
c.volumeCmd1 = cmd
} else {
c.volumeCmd0 = cmd
}
return nil
}
func (c *DualVolumeCluster) waitForHTTP(url string) error {
return (&Cluster{}).waitForHTTP(url)
}
func (c *DualVolumeCluster) waitForTCP(addr string) error {
return (&Cluster{}).waitForTCP(addr)
}
func (c *DualVolumeCluster) tailLog(logName string) string {
return (&Cluster{logsDir: c.logsDir}).tailLog(logName)
}
func (c *DualVolumeCluster) MasterAddress() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.masterPort))
}
func (c *DualVolumeCluster) MasterURL() string {
return "http://" + c.MasterAddress()
}
func (c *DualVolumeCluster) VolumeAdminAddress(index int) string {
if index == 1 {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumePort1))
}
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumePort0))
}
func (c *DualVolumeCluster) VolumePublicAddress(index int) string {
if index == 1 {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumePubPort1))
}
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumePubPort0))
}
func (c *DualVolumeCluster) VolumeGRPCAddress(index int) string {
if index == 1 {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumeGrpcPort1))
}
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumeGrpcPort0))
}
func (c *DualVolumeCluster) VolumeAdminURL(index int) string {
return "http://" + c.VolumeAdminAddress(index)
}
func (c *DualVolumeCluster) VolumePublicURL(index int) string {
return "http://" + c.VolumePublicAddress(index)
}
@@ -1,91 +0,0 @@
package framework
import (
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
type ClusterWithFiler struct {
*Cluster
filerCmd *exec.Cmd
filerPort int
filerGrpcPort int
}
func StartSingleVolumeClusterWithFiler(t testing.TB, profile matrix.Profile) *ClusterWithFiler {
t.Helper()
baseCluster := StartSingleVolumeCluster(t, profile)
ports, err := allocatePorts(2)
if err != nil {
t.Fatalf("allocate filer ports: %v", err)
}
filerDataDir := filepath.Join(baseCluster.baseDir, "filer")
if mkErr := os.MkdirAll(filerDataDir, 0o755); mkErr != nil {
t.Fatalf("create filer data dir: %v", mkErr)
}
logFile, err := os.Create(filepath.Join(baseCluster.logsDir, "filer.log"))
if err != nil {
t.Fatalf("create filer log file: %v", err)
}
filerPort := ports[0]
filerGrpcPort := ports[1]
args := []string{
"-config_dir=" + baseCluster.configDir,
"filer",
"-master=127.0.0.1:" + strconv.Itoa(baseCluster.masterPort),
"-ip=127.0.0.1",
"-port=" + strconv.Itoa(filerPort),
"-port.grpc=" + strconv.Itoa(filerGrpcPort),
"-defaultStoreDir=" + filerDataDir,
}
filerCmd := exec.Command(baseCluster.weedBinary, args...)
filerCmd.Dir = baseCluster.baseDir
filerCmd.Stdout = logFile
filerCmd.Stderr = logFile
if err = filerCmd.Start(); err != nil {
t.Fatalf("start filer: %v", err)
}
if err = baseCluster.waitForTCP(net.JoinHostPort("127.0.0.1", strconv.Itoa(filerGrpcPort))); err != nil {
filerLogTail := baseCluster.tailLog("filer.log")
stopProcess(filerCmd)
t.Fatalf("wait for filer grpc readiness: %v\nfiler log tail:\n%s", err, filerLogTail)
}
t.Cleanup(func() {
stopProcess(filerCmd)
})
return &ClusterWithFiler{
Cluster: baseCluster,
filerCmd: filerCmd,
filerPort: filerPort,
filerGrpcPort: filerGrpcPort,
}
}
func (c *ClusterWithFiler) FilerAddress() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.filerPort))
}
func (c *ClusterWithFiler) FilerGRPCAddress() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.filerGrpcPort))
}
func (c *ClusterWithFiler) FilerServerAddress() string {
return fmt.Sprintf("%s.%d", c.FilerAddress(), c.filerGrpcPort)
}
@@ -1,8 +0,0 @@
package framework
// Phase 0 placeholder for future fault injection utilities.
//
// Planned extensions:
// - restart/kill selected processes
// - temporary network isolation hooks
// - master or peer outage helpers for proxy/replication branch coverage
@@ -1,28 +0,0 @@
package framework
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func DialVolumeServer(t testing.TB, address string) (*grpc.ClientConn, volume_server_pb.VolumeServerClient) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, address,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
)
if err != nil {
t.Fatalf("dial volume grpc %s: %v", address, err)
}
return conn, volume_server_pb.NewVolumeServerClient(conn)
}
@@ -1,34 +0,0 @@
package framework
import (
"io"
"net/http"
"testing"
"time"
)
func NewHTTPClient() *http.Client {
return &http.Client{Timeout: 10 * time.Second}
}
func DoRequest(t testing.TB, client *http.Client, req *http.Request) *http.Response {
t.Helper()
resp, err := client.Do(req)
if err != nil {
t.Fatalf("http request %s %s: %v", req.Method, req.URL.String(), err)
}
return resp
}
func ReadAllAndClose(t testing.TB, resp *http.Response) []byte {
t.Helper()
if resp == nil {
return nil
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read response body: %v", err)
}
return body
}
@@ -1,56 +0,0 @@
package framework
import (
"bytes"
"context"
"fmt"
"net/http"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
func AllocateVolume(t testing.TB, client volume_server_pb.VolumeServerClient, volumeID uint32, collection string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := client.AllocateVolume(ctx, &volume_server_pb.AllocateVolumeRequest{
VolumeId: volumeID,
Collection: collection,
Replication: "000",
Version: uint32(needle.GetCurrentVersion()),
})
if err != nil {
t.Fatalf("allocate volume %d: %v", volumeID, err)
}
}
func NewFileID(volumeID uint32, key uint64, cookie uint32) string {
return needle.NewFileId(needle.VolumeId(volumeID), key, cookie).String()
}
func UploadBytes(t testing.TB, client *http.Client, volumeURL, fid string, data []byte) *http.Response {
t.Helper()
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/%s", volumeURL, fid), bytes.NewReader(data))
if err != nil {
t.Fatalf("build upload request: %v", err)
}
req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set("Content-Length", fmt.Sprintf("%d", len(data)))
return DoRequest(t, client, req)
}
func ReadBytes(t testing.TB, client *http.Client, volumeURL, fid string) *http.Response {
t.Helper()
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s", volumeURL, fid), nil)
if err != nil {
t.Fatalf("build read request: %v", err)
}
return DoRequest(t, client, req)
}
-445
View File
@@ -1,445 +0,0 @@
package volume_server_grpc_test
import (
"context"
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestVolumeNeedleStatusForUploadedFile(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(21)
const needleID = uint64(778899)
const cookie = uint32(0xA1B2C3D4)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
client := framework.NewHTTPClient()
payload := []byte("needle-status-payload")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload status: expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
statusResp, err := grpcClient.VolumeNeedleStatus(ctx, &volume_server_pb.VolumeNeedleStatusRequest{
VolumeId: volumeID,
NeedleId: needleID,
})
if err != nil {
t.Fatalf("VolumeNeedleStatus failed: %v", err)
}
if statusResp.GetNeedleId() != needleID {
t.Fatalf("needle id mismatch: got %d want %d", statusResp.GetNeedleId(), needleID)
}
if statusResp.GetCookie() != cookie {
t.Fatalf("cookie mismatch: got %d want %d", statusResp.GetCookie(), cookie)
}
if statusResp.GetSize() == 0 {
t.Fatalf("expected non-zero needle size")
}
}
func TestVolumeNeedleStatusViaEcShardsWhenNormalVolumeUnmounted(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(26)
const needleID = uint64(778900)
const cookie = uint32(0xA1B2C3D5)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, needleID, cookie)
payload := []byte("needle-status-ec-path-payload")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload status: expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
})
if err != nil {
t.Fatalf("VolumeEcShardsMount data shards failed: %v", err)
}
_, err = grpcClient.VolumeUnmount(ctx, &volume_server_pb.VolumeUnmountRequest{
VolumeId: volumeID,
})
if err != nil {
t.Fatalf("VolumeUnmount failed: %v", err)
}
statusResp, err := grpcClient.VolumeNeedleStatus(ctx, &volume_server_pb.VolumeNeedleStatusRequest{
VolumeId: volumeID,
NeedleId: needleID,
})
if err != nil {
t.Fatalf("VolumeNeedleStatus via EC shards failed: %v", err)
}
if statusResp.GetNeedleId() != needleID {
t.Fatalf("needle id mismatch: got %d want %d", statusResp.GetNeedleId(), needleID)
}
if statusResp.GetCookie() != cookie {
t.Fatalf("cookie mismatch: got %d want %d", statusResp.GetCookie(), cookie)
}
if statusResp.GetSize() == 0 {
t.Fatalf("expected non-zero needle size from EC-backed needle status")
}
_, err = grpcClient.VolumeNeedleStatus(ctx, &volume_server_pb.VolumeNeedleStatusRequest{
VolumeId: volumeID,
NeedleId: needleID + 999999,
})
if err == nil || !strings.Contains(strings.ToLower(err.Error()), "not found") {
t.Fatalf("VolumeNeedleStatus via EC shards missing-needle error mismatch: %v", err)
}
}
func TestVolumeNeedleStatusMissingVolumeAndNeedle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(25)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeNeedleStatus(ctx, &volume_server_pb.VolumeNeedleStatusRequest{
VolumeId: 99925,
NeedleId: 1,
})
if err == nil {
t.Fatalf("VolumeNeedleStatus should fail for missing volume")
}
if !strings.Contains(strings.ToLower(err.Error()), "volume not found") {
t.Fatalf("VolumeNeedleStatus missing-volume error mismatch: %v", err)
}
_, err = grpcClient.VolumeNeedleStatus(ctx, &volume_server_pb.VolumeNeedleStatusRequest{
VolumeId: volumeID,
NeedleId: 123456789,
})
if err == nil {
t.Fatalf("VolumeNeedleStatus should fail for missing needle")
}
if !strings.Contains(strings.ToLower(err.Error()), "not found") {
t.Fatalf("VolumeNeedleStatus missing-needle error mismatch: %v", err)
}
}
func mustNewRequest(t testing.TB, method, url string) *http.Request {
t.Helper()
req, err := http.NewRequest(method, url, nil)
if err != nil {
t.Fatalf("create request %s %s: %v", method, url, err)
}
return req
}
func TestVolumeConfigureInvalidReplication(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(22)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := grpcClient.VolumeConfigure(ctx, &volume_server_pb.VolumeConfigureRequest{
VolumeId: volumeID,
Replication: "bad-replication",
})
if err != nil {
t.Fatalf("VolumeConfigure returned grpc error: %v", err)
}
if resp.GetError() == "" {
t.Fatalf("VolumeConfigure expected response error for invalid replication")
}
if !strings.Contains(strings.ToLower(resp.GetError()), "replication") {
t.Fatalf("VolumeConfigure error should mention replication, got: %q", resp.GetError())
}
}
func TestVolumeConfigureSuccessAndMissingRollbackPath(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(24)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
successResp, err := grpcClient.VolumeConfigure(ctx, &volume_server_pb.VolumeConfigureRequest{
VolumeId: volumeID,
Replication: "000",
})
if err != nil {
t.Fatalf("VolumeConfigure success path returned grpc error: %v", err)
}
if successResp.GetError() != "" {
t.Fatalf("VolumeConfigure success path expected empty response error, got: %q", successResp.GetError())
}
statusResp, err := grpcClient.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeStatus after successful configure failed: %v", err)
}
if statusResp.GetIsReadOnly() {
t.Fatalf("VolumeStatus after configure expected writable volume")
}
missingResp, err := grpcClient.VolumeConfigure(ctx, &volume_server_pb.VolumeConfigureRequest{
VolumeId: 99024,
Replication: "000",
})
if err != nil {
t.Fatalf("VolumeConfigure missing-volume branch should return response error, got grpc error: %v", err)
}
if missingResp.GetError() == "" {
t.Fatalf("VolumeConfigure missing-volume expected non-empty response error")
}
lower := strings.ToLower(missingResp.GetError())
if !strings.Contains(lower, "not found on disk") {
t.Fatalf("VolumeConfigure missing-volume error should mention not found on disk, got: %q", missingResp.GetError())
}
if !strings.Contains(lower, "failed to restore mount") {
t.Fatalf("VolumeConfigure missing-volume error should include remount rollback failure, got: %q", missingResp.GetError())
}
}
func TestPingVolumeTargetAndLeaveAffectsHealthz(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pingResp, err := grpcClient.Ping(ctx, &volume_server_pb.PingRequest{
TargetType: cluster.VolumeServerType,
Target: clusterHarness.VolumeServerAddress(),
})
if err != nil {
t.Fatalf("Ping target volume server failed: %v", err)
}
if pingResp.GetRemoteTimeNs() == 0 {
t.Fatalf("expected remote timestamp from ping target volume server")
}
if _, err = grpcClient.VolumeServerLeave(ctx, &volume_server_pb.VolumeServerLeaveRequest{}); err != nil {
t.Fatalf("VolumeServerLeave failed: %v", err)
}
client := framework.NewHTTPClient()
healthURL := clusterHarness.VolumeAdminURL() + "/healthz"
deadline := time.Now().Add(5 * time.Second)
for {
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, healthURL))
_ = framework.ReadAllAndClose(t, resp)
if resp.StatusCode == http.StatusServiceUnavailable {
return
}
if time.Now().After(deadline) {
t.Fatalf("expected healthz to return 503 after leave, got %d", resp.StatusCode)
}
time.Sleep(100 * time.Millisecond)
}
}
func TestVolumeServerLeaveIsIdempotent(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := grpcClient.VolumeServerLeave(ctx, &volume_server_pb.VolumeServerLeaveRequest{}); err != nil {
t.Fatalf("first VolumeServerLeave failed: %v", err)
}
if _, err := grpcClient.VolumeServerLeave(ctx, &volume_server_pb.VolumeServerLeaveRequest{}); err != nil {
t.Fatalf("second VolumeServerLeave should be idempotent success, got: %v", err)
}
client := framework.NewHTTPClient()
healthURL := clusterHarness.VolumeAdminURL() + "/healthz"
deadline := time.Now().Add(5 * time.Second)
for {
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, healthURL))
_ = framework.ReadAllAndClose(t, resp)
if resp.StatusCode == http.StatusServiceUnavailable {
return
}
if time.Now().After(deadline) {
t.Fatalf("expected healthz to stay 503 after repeated leave, got %d", resp.StatusCode)
}
time.Sleep(100 * time.Millisecond)
}
}
func TestPingUnknownAndUnreachableTargetPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
unknownResp, err := grpcClient.Ping(ctx, &volume_server_pb.PingRequest{
TargetType: "unknown-type",
Target: "127.0.0.1:12345",
})
if err != nil {
t.Fatalf("Ping unknown target type should not return grpc error, got: %v", err)
}
if unknownResp.GetRemoteTimeNs() != 0 {
t.Fatalf("Ping unknown target type expected remote_time_ns=0, got %d", unknownResp.GetRemoteTimeNs())
}
if unknownResp.GetStopTimeNs() < unknownResp.GetStartTimeNs() {
t.Fatalf("Ping unknown target type expected stop_time_ns >= start_time_ns")
}
_, err = grpcClient.Ping(ctx, &volume_server_pb.PingRequest{
TargetType: cluster.MasterType,
Target: "127.0.0.1:1",
})
if err == nil {
t.Fatalf("Ping master target should fail when target is unreachable")
}
if !strings.Contains(err.Error(), "ping master") {
t.Fatalf("Ping master unreachable error mismatch: %v", err)
}
_, err = grpcClient.Ping(ctx, &volume_server_pb.PingRequest{
TargetType: cluster.FilerType,
Target: "127.0.0.1:1",
})
if err == nil {
t.Fatalf("Ping filer target should fail when target is unreachable")
}
if !strings.Contains(err.Error(), "ping filer") {
t.Fatalf("Ping filer unreachable error mismatch: %v", err)
}
}
func TestPingMasterTargetSuccess(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := grpcClient.Ping(ctx, &volume_server_pb.PingRequest{
TargetType: cluster.MasterType,
Target: clusterHarness.MasterAddress(),
})
if err != nil {
t.Fatalf("Ping master target success path failed: %v", err)
}
if resp.GetRemoteTimeNs() == 0 {
t.Fatalf("Ping master target expected non-zero remote time")
}
if resp.GetStopTimeNs() < resp.GetStartTimeNs() {
t.Fatalf("Ping master target expected stop >= start, got start=%d stop=%d", resp.GetStartTimeNs(), resp.GetStopTimeNs())
}
}
func TestPingFilerTargetSuccess(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeClusterWithFiler(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := grpcClient.Ping(ctx, &volume_server_pb.PingRequest{
TargetType: cluster.FilerType,
Target: clusterHarness.FilerServerAddress(),
})
if err != nil {
t.Fatalf("Ping filer target success path failed: %v", err)
}
if resp.GetRemoteTimeNs() == 0 {
t.Fatalf("Ping filer target expected non-zero remote time")
}
if resp.GetStopTimeNs() < resp.GetStartTimeNs() {
t.Fatalf("Ping filer target expected stop >= start, got start=%d stop=%d", resp.GetStartTimeNs(), resp.GetStopTimeNs())
}
}
@@ -1,215 +0,0 @@
package volume_server_grpc_test
import (
"context"
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestVolumeAdminLifecycleRPCs(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
const volumeID = uint32(11)
framework.AllocateVolume(t, client, volumeID, "")
statusResp, err := client.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeStatus failed: %v", err)
}
if statusResp.GetFileCount() != 0 {
t.Fatalf("new volume should be empty, got file_count=%d", statusResp.GetFileCount())
}
if _, err = client.VolumeUnmount(ctx, &volume_server_pb.VolumeUnmountRequest{VolumeId: volumeID}); err != nil {
t.Fatalf("VolumeUnmount failed: %v", err)
}
if _, err = client.VolumeMount(ctx, &volume_server_pb.VolumeMountRequest{VolumeId: volumeID}); err != nil {
t.Fatalf("VolumeMount failed: %v", err)
}
if _, err = client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{VolumeId: volumeID, OnlyEmpty: true}); err != nil {
t.Fatalf("VolumeDelete failed: %v", err)
}
_, err = client.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err == nil {
t.Fatalf("VolumeStatus should fail after delete")
}
if st, ok := status.FromError(err); !ok || st.Code() == codes.OK {
t.Fatalf("VolumeStatus error should be a non-OK grpc status, got: %v", err)
}
}
func TestVolumeDeleteOnlyEmptyVariants(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(13)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 66001, 0x11223344)
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("volume-delete-only-empty"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{VolumeId: volumeID, OnlyEmpty: true})
if err == nil || !strings.Contains(err.Error(), "volume not empty") {
t.Fatalf("VolumeDelete only_empty=true expected volume-not-empty error, got: %v", err)
}
_, err = grpcClient.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{VolumeId: volumeID, OnlyEmpty: false})
if err != nil {
t.Fatalf("VolumeDelete only_empty=false failed: %v", err)
}
_, err = grpcClient.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err == nil {
t.Fatalf("VolumeStatus should fail after non-empty delete with only_empty=false")
}
}
func TestMaintenanceModeRejectsAllocateVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stateResp, err := client.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = client.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{Maintenance: true, Version: stateResp.GetState().GetVersion()},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
_, err = client.AllocateVolume(ctx, &volume_server_pb.AllocateVolumeRequest{VolumeId: 12, Replication: "000"})
if err == nil {
t.Fatalf("AllocateVolume should fail when maintenance mode is enabled")
}
if !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("expected maintenance mode error, got: %v", err)
}
}
func TestAllocateDuplicateAndMountUnmountMissingVariants(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
const missingVolumeID = uint32(99331)
const volumeID = uint32(14)
if _, err := client.VolumeUnmount(ctx, &volume_server_pb.VolumeUnmountRequest{VolumeId: missingVolumeID}); err != nil {
t.Fatalf("VolumeUnmount missing volume should be idempotent success, got: %v", err)
}
_, err := client.VolumeMount(ctx, &volume_server_pb.VolumeMountRequest{VolumeId: missingVolumeID})
if err == nil {
t.Fatalf("VolumeMount missing volume should fail")
}
if !strings.Contains(err.Error(), "not found on disk") {
t.Fatalf("VolumeMount missing volume error mismatch: %v", err)
}
framework.AllocateVolume(t, client, volumeID, "")
_, err = client.AllocateVolume(ctx, &volume_server_pb.AllocateVolumeRequest{
VolumeId: volumeID,
Replication: "000",
})
if err == nil {
t.Fatalf("AllocateVolume duplicate should fail")
}
if !strings.Contains(strings.ToLower(err.Error()), "already exists") {
t.Fatalf("AllocateVolume duplicate error mismatch: %v", err)
}
if _, err = client.VolumeUnmount(ctx, &volume_server_pb.VolumeUnmountRequest{VolumeId: volumeID}); err != nil {
t.Fatalf("VolumeUnmount existing volume failed: %v", err)
}
if _, err = client.VolumeUnmount(ctx, &volume_server_pb.VolumeUnmountRequest{VolumeId: volumeID}); err != nil {
t.Fatalf("VolumeUnmount already-unmounted volume should be idempotent success, got: %v", err)
}
if _, err = client.VolumeMount(ctx, &volume_server_pb.VolumeMountRequest{VolumeId: volumeID}); err != nil {
t.Fatalf("VolumeMount remount failed: %v", err)
}
}
func TestMaintenanceModeRejectsVolumeDelete(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(15)
framework.AllocateVolume(t, client, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stateResp, err := client.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = client.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{Maintenance: true, Version: stateResp.GetState().GetVersion()},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
_, err = client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{VolumeId: volumeID, OnlyEmpty: true})
if err == nil {
t.Fatalf("VolumeDelete should fail when maintenance mode is enabled")
}
if !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("expected maintenance mode error, got: %v", err)
}
}
@@ -1,177 +0,0 @@
package volume_server_grpc_test
import (
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestVolumeMarkReadonlyAndWritableLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(72)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{
VolumeId: volumeID,
Persist: false,
})
if err != nil {
t.Fatalf("VolumeMarkReadonly failed: %v", err)
}
readOnlyStatus, err := grpcClient.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeStatus after readonly failed: %v", err)
}
if !readOnlyStatus.GetIsReadOnly() {
t.Fatalf("VolumeStatus expected readonly=true after VolumeMarkReadonly")
}
_, err = grpcClient.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeMarkWritable failed: %v", err)
}
writableStatus, err := grpcClient.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeStatus after writable failed: %v", err)
}
if writableStatus.GetIsReadOnly() {
t.Fatalf("VolumeStatus expected readonly=false after VolumeMarkWritable")
}
}
func TestVolumeMarkReadonlyPersistTrue(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(74)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{
VolumeId: volumeID,
Persist: true,
})
if err != nil {
t.Fatalf("VolumeMarkReadonly persist=true failed: %v", err)
}
statusResp, err := grpcClient.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeStatus after persist readonly failed: %v", err)
}
if !statusResp.GetIsReadOnly() {
t.Fatalf("VolumeStatus expected readonly=true after persist readonly")
}
}
func TestVolumeMarkReadonlyWritableErrorPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{VolumeId: 98771, Persist: true})
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeMarkReadonly missing-volume error mismatch: %v", err)
}
_, err = grpcClient.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{VolumeId: 98772})
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeMarkWritable missing-volume error mismatch: %v", err)
}
stateResp, err := grpcClient.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = grpcClient.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{
Maintenance: true,
Version: stateResp.GetState().GetVersion(),
},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
_, err = grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{VolumeId: 1, Persist: true})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeMarkReadonly maintenance error mismatch: %v", err)
}
_, err = grpcClient.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{VolumeId: 1})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeMarkWritable maintenance error mismatch: %v", err)
}
}
func TestDeleteCollectionRemovesVolumeAndIsIdempotent(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(73)
const collection = "it-delete-collection"
framework.AllocateVolume(t, grpcClient, volumeID, collection)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeStatus before DeleteCollection failed: %v", err)
}
_, err = grpcClient.DeleteCollection(ctx, &volume_server_pb.DeleteCollectionRequest{Collection: collection})
if err != nil {
t.Fatalf("DeleteCollection existing collection failed: %v", err)
}
_, err = grpcClient.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{VolumeId: volumeID})
if err == nil {
t.Fatalf("VolumeStatus should fail after collection delete")
}
if !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("VolumeStatus after DeleteCollection error mismatch: %v", err)
}
_, err = grpcClient.DeleteCollection(ctx, &volume_server_pb.DeleteCollectionRequest{Collection: collection})
if err != nil {
t.Fatalf("DeleteCollection idempotent retry failed: %v", err)
}
}
@@ -1,264 +0,0 @@
package volume_server_grpc_test
import (
"bytes"
"context"
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestBatchDeleteInvalidFidAndMaintenanceMode(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{FileIds: []string{"bad-fid"}})
if err != nil {
t.Fatalf("BatchDelete invalid fid should return response, got error: %v", err)
}
if len(resp.GetResults()) != 1 {
t.Fatalf("expected one batch delete result, got %d", len(resp.GetResults()))
}
if got := resp.GetResults()[0].GetStatus(); got != 400 {
t.Fatalf("invalid fid expected status 400, got %d", got)
}
stateResp, err := client.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = client.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{Maintenance: true, Version: stateResp.GetState().GetVersion()},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
_, err = client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{FileIds: []string{"1,1234567890ab"}})
if err == nil {
t.Fatalf("BatchDelete should fail when maintenance mode is enabled")
}
if !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("expected maintenance mode error, got: %v", err)
}
}
func TestBatchDeleteCookieMismatchAndSkipCheck(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(31)
const needleID = uint64(900001)
const correctCookie = uint32(0x1122AABB)
const wrongCookie = uint32(0x1122AABC)
framework.AllocateVolume(t, client, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, needleID, correctCookie)
uploadResp := framework.UploadBytes(t, httpClient, cluster.VolumeAdminURL(), fid, []byte("batch-delete-cookie-check"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
wrongCookieFid := framework.NewFileID(volumeID, needleID, wrongCookie)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
mismatchResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
FileIds: []string{wrongCookieFid},
SkipCookieCheck: false,
})
if err != nil {
t.Fatalf("BatchDelete with cookie check failed: %v", err)
}
if len(mismatchResp.GetResults()) != 1 {
t.Fatalf("BatchDelete cookie mismatch expected 1 result, got %d", len(mismatchResp.GetResults()))
}
if mismatchResp.GetResults()[0].GetStatus() != http.StatusBadRequest {
t.Fatalf("BatchDelete cookie mismatch expected status 400, got %d", mismatchResp.GetResults()[0].GetStatus())
}
skipCheckResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
FileIds: []string{wrongCookieFid},
SkipCookieCheck: true,
})
if err != nil {
t.Fatalf("BatchDelete skip cookie check failed: %v", err)
}
if len(skipCheckResp.GetResults()) != 1 {
t.Fatalf("BatchDelete skip check expected 1 result, got %d", len(skipCheckResp.GetResults()))
}
if skipCheckResp.GetResults()[0].GetStatus() != http.StatusAccepted {
t.Fatalf("BatchDelete skip check expected status 202, got %d", skipCheckResp.GetResults()[0].GetStatus())
}
readAfterDelete := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fid)
_ = framework.ReadAllAndClose(t, readAfterDelete)
if readAfterDelete.StatusCode != http.StatusNotFound {
t.Fatalf("read after skip-check batch delete expected 404, got %d", readAfterDelete.StatusCode)
}
}
func TestBatchDeleteMixedStatusesAndMismatchStopsProcessing(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(32)
framework.AllocateVolume(t, client, volumeID, "")
const needleA = uint64(910001)
const needleB = uint64(910002)
const needleC = uint64(910003)
const cookieA = uint32(0x11111111)
const cookieB = uint32(0x22222222)
const cookieC = uint32(0x33333333)
httpClient := framework.NewHTTPClient()
fidA := framework.NewFileID(volumeID, needleA, cookieA)
fidB := framework.NewFileID(volumeID, needleB, cookieB)
fidC := framework.NewFileID(volumeID, needleC, cookieC)
for _, tc := range []struct {
fid string
body string
}{
{fid: fidA, body: "batch-delete-mixed-a"},
{fid: fidB, body: "batch-delete-mixed-b"},
{fid: fidC, body: "batch-delete-mixed-c"},
} {
uploadResp := framework.UploadBytes(t, httpClient, cluster.VolumeAdminURL(), tc.fid, []byte(tc.body))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload %s expected 201, got %d", tc.fid, uploadResp.StatusCode)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
missingFid := framework.NewFileID(volumeID, 919999, 0x44444444)
mixedResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
FileIds: []string{"bad-fid", fidA, missingFid},
})
if err != nil {
t.Fatalf("BatchDelete mixed status request failed: %v", err)
}
if len(mixedResp.GetResults()) != 3 {
t.Fatalf("BatchDelete mixed status expected 3 results, got %d", len(mixedResp.GetResults()))
}
if mixedResp.GetResults()[0].GetStatus() != http.StatusBadRequest {
t.Fatalf("BatchDelete mixed result[0] expected 400, got %d", mixedResp.GetResults()[0].GetStatus())
}
if mixedResp.GetResults()[1].GetStatus() != http.StatusAccepted {
t.Fatalf("BatchDelete mixed result[1] expected 202, got %d", mixedResp.GetResults()[1].GetStatus())
}
if mixedResp.GetResults()[2].GetStatus() != http.StatusNotFound {
t.Fatalf("BatchDelete mixed result[2] expected 404, got %d", mixedResp.GetResults()[2].GetStatus())
}
readDeletedA := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fidA)
_ = framework.ReadAllAndClose(t, readDeletedA)
if readDeletedA.StatusCode != http.StatusNotFound {
t.Fatalf("fidA should be deleted after batch delete, got status %d", readDeletedA.StatusCode)
}
wrongCookieB := framework.NewFileID(volumeID, needleB, cookieB+1)
stopResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
FileIds: []string{wrongCookieB, fidC},
})
if err != nil {
t.Fatalf("BatchDelete mismatch-stop request failed: %v", err)
}
if len(stopResp.GetResults()) != 1 {
t.Fatalf("BatchDelete mismatch-stop expected 1 result due early break, got %d", len(stopResp.GetResults()))
}
if stopResp.GetResults()[0].GetStatus() != http.StatusBadRequest {
t.Fatalf("BatchDelete mismatch-stop expected 400, got %d", stopResp.GetResults()[0].GetStatus())
}
readB := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fidB)
_ = framework.ReadAllAndClose(t, readB)
if readB.StatusCode != http.StatusOK {
t.Fatalf("fidB should remain after cookie mismatch path, got %d", readB.StatusCode)
}
readC := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fidC)
_ = framework.ReadAllAndClose(t, readC)
if readC.StatusCode != http.StatusOK {
t.Fatalf("fidC should remain when batch processing stops on mismatch, got %d", readC.StatusCode)
}
}
func TestBatchDeleteRejectsChunkManifestNeedles(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(33)
framework.AllocateVolume(t, client, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 920001, 0x5555AAAA)
req, err := http.NewRequest(http.MethodPost, cluster.VolumeAdminURL()+"/"+fid+"?cm=true", bytes.NewReader([]byte("manifest-placeholder-payload")))
if err != nil {
t.Fatalf("create chunk manifest upload request: %v", err)
}
req.Header.Set("Content-Type", "application/octet-stream")
uploadResp := framework.DoRequest(t, httpClient, req)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("chunk manifest upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{FileIds: []string{fid}})
if err != nil {
t.Fatalf("BatchDelete chunk manifest should return response, got grpc error: %v", err)
}
if len(resp.GetResults()) != 1 {
t.Fatalf("BatchDelete chunk manifest expected one result, got %d", len(resp.GetResults()))
}
if resp.GetResults()[0].GetStatus() != http.StatusNotAcceptable {
t.Fatalf("BatchDelete chunk manifest expected status 406, got %d", resp.GetResults()[0].GetStatus())
}
if !strings.Contains(resp.GetResults()[0].GetError(), "ChunkManifest") {
t.Fatalf("BatchDelete chunk manifest expected error mentioning ChunkManifest, got %q", resp.GetResults()[0].GetError())
}
readResp := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fid)
_ = framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusOK {
t.Fatalf("chunk manifest should not be deleted by BatchDelete reject path, got %d", readResp.StatusCode)
}
}
@@ -1,431 +0,0 @@
package volume_server_grpc_test
import (
"context"
"io"
"math"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestVolumeIncrementalCopyDataAndNoDataPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(91)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 770001, 0x1122AABB)
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("incremental-copy-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != 201 {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
dataStream, err := grpcClient.VolumeIncrementalCopy(ctx, &volume_server_pb.VolumeIncrementalCopyRequest{
VolumeId: volumeID,
SinceNs: 0,
})
if err != nil {
t.Fatalf("VolumeIncrementalCopy start failed: %v", err)
}
totalBytes := 0
for {
msg, recvErr := dataStream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
t.Fatalf("VolumeIncrementalCopy recv failed: %v", recvErr)
}
totalBytes += len(msg.GetFileContent())
}
if totalBytes == 0 {
t.Fatalf("VolumeIncrementalCopy expected streamed bytes for since_ns=0")
}
noDataStream, err := grpcClient.VolumeIncrementalCopy(ctx, &volume_server_pb.VolumeIncrementalCopyRequest{
VolumeId: volumeID,
SinceNs: math.MaxUint64,
})
if err != nil {
t.Fatalf("VolumeIncrementalCopy no-data start failed: %v", err)
}
_, err = noDataStream.Recv()
if err != io.EOF {
t.Fatalf("VolumeIncrementalCopy no-data expected EOF, got: %v", err)
}
}
func TestCopyFileIgnoreNotFoundAndStopOffsetZeroPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(92)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
missingNoIgnore, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Ext: ".definitely-missing",
CompactionRevision: math.MaxUint32,
StopOffset: 1,
IgnoreSourceFileNotFound: false,
})
if err == nil {
_, err = missingNoIgnore.Recv()
}
if err == nil {
t.Fatalf("CopyFile should fail for missing source file when ignore_source_file_not_found=false")
}
missingIgnored, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Ext: ".definitely-missing",
CompactionRevision: math.MaxUint32,
StopOffset: 1,
IgnoreSourceFileNotFound: true,
})
if err != nil {
t.Fatalf("CopyFile ignore-not-found start failed: %v", err)
}
_, err = missingIgnored.Recv()
if err != io.EOF {
t.Fatalf("CopyFile ignore-not-found expected EOF, got: %v", err)
}
stopZeroStream, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Ext: ".definitely-missing",
CompactionRevision: math.MaxUint32,
StopOffset: 0,
IgnoreSourceFileNotFound: false,
})
if err != nil {
t.Fatalf("CopyFile stop_offset=0 start failed: %v", err)
}
_, err = stopZeroStream.Recv()
if err != io.EOF {
t.Fatalf("CopyFile stop_offset=0 expected EOF, got: %v", err)
}
}
func TestCopyFileCompactionRevisionMismatch(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(94)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Ext: ".idx",
CompactionRevision: 1, // fresh volume starts at revision 0
StopOffset: 1,
})
if err == nil {
_, err = stream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "is compacted") {
t.Fatalf("CopyFile compaction mismatch error mismatch: %v", err)
}
}
func TestReceiveFileProtocolViolationResponses(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
contentFirstStream, err := grpcClient.ReceiveFile(ctx)
if err != nil {
t.Fatalf("ReceiveFile stream create failed: %v", err)
}
if err = contentFirstStream.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_FileContent{
FileContent: []byte("content-before-info"),
},
}); err != nil {
t.Fatalf("ReceiveFile send content-first failed: %v", err)
}
contentFirstResp, err := contentFirstStream.CloseAndRecv()
if err != nil {
t.Fatalf("ReceiveFile content-first close failed: %v", err)
}
if !strings.Contains(contentFirstResp.GetError(), "file info must be sent first") {
t.Fatalf("ReceiveFile content-first response mismatch: %+v", contentFirstResp)
}
unknownTypeStream, err := grpcClient.ReceiveFile(ctx)
if err != nil {
t.Fatalf("ReceiveFile stream create for unknown-type failed: %v", err)
}
if err = unknownTypeStream.Send(&volume_server_pb.ReceiveFileRequest{}); err != nil {
t.Fatalf("ReceiveFile send unknown-type request failed: %v", err)
}
unknownTypeResp, err := unknownTypeStream.CloseAndRecv()
if err != nil {
t.Fatalf("ReceiveFile unknown-type close failed: %v", err)
}
if !strings.Contains(unknownTypeResp.GetError(), "unknown message type") {
t.Fatalf("ReceiveFile unknown-type response mismatch: %+v", unknownTypeResp)
}
}
func TestReceiveFileSuccessForRegularVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(95)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
payloadA := []byte("receive-file-chunk-a:")
payloadB := []byte("receive-file-chunk-b")
expected := append(append([]byte{}, payloadA...), payloadB...)
receiveStream, err := grpcClient.ReceiveFile(ctx)
if err != nil {
t.Fatalf("ReceiveFile stream create failed: %v", err)
}
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_Info{
Info: &volume_server_pb.ReceiveFileInfo{
VolumeId: volumeID,
Ext: ".tmprecv",
Collection: "",
IsEcVolume: false,
FileSize: uint64(len(expected)),
},
},
}); err != nil {
t.Fatalf("ReceiveFile send info failed: %v", err)
}
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payloadA},
}); err != nil {
t.Fatalf("ReceiveFile send payloadA failed: %v", err)
}
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payloadB},
}); err != nil {
t.Fatalf("ReceiveFile send payloadB failed: %v", err)
}
resp, err := receiveStream.CloseAndRecv()
if err != nil {
t.Fatalf("ReceiveFile close failed: %v", err)
}
if resp.GetError() != "" {
t.Fatalf("ReceiveFile unexpected error response: %+v", resp)
}
if resp.GetBytesWritten() != uint64(len(expected)) {
t.Fatalf("ReceiveFile bytes_written mismatch: got %d want %d", resp.GetBytesWritten(), len(expected))
}
copyStream, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Ext: ".tmprecv",
CompactionRevision: math.MaxUint32,
StopOffset: uint64(len(expected)),
})
if err != nil {
t.Fatalf("CopyFile for received data start failed: %v", err)
}
var copied []byte
for {
msg, recvErr := copyStream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
t.Fatalf("CopyFile for received data recv failed: %v", recvErr)
}
copied = append(copied, msg.GetFileContent()...)
}
if string(copied) != string(expected) {
t.Fatalf("received file data mismatch: got %q want %q", string(copied), string(expected))
}
}
func TestReceiveFileSuccessForEcVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
const volumeID = uint32(96)
const collection = "ec-receive-success"
const ext = ".ec00"
payloadA := []byte("receive-ec-file-chunk-a:")
payloadB := []byte("receive-ec-file-chunk-b")
expected := append(append([]byte{}, payloadA...), payloadB...)
receiveStream, err := grpcClient.ReceiveFile(ctx)
if err != nil {
t.Fatalf("ReceiveFile stream create failed: %v", err)
}
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_Info{
Info: &volume_server_pb.ReceiveFileInfo{
VolumeId: volumeID,
Ext: ext,
Collection: collection,
IsEcVolume: true,
ShardId: 0,
FileSize: uint64(len(expected)),
},
},
}); err != nil {
t.Fatalf("ReceiveFile send EC info failed: %v", err)
}
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payloadA},
}); err != nil {
t.Fatalf("ReceiveFile send EC payloadA failed: %v", err)
}
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payloadB},
}); err != nil {
t.Fatalf("ReceiveFile send EC payloadB failed: %v", err)
}
resp, err := receiveStream.CloseAndRecv()
if err != nil {
t.Fatalf("ReceiveFile EC close failed: %v", err)
}
if resp.GetError() != "" {
t.Fatalf("ReceiveFile EC unexpected error response: %+v", resp)
}
if resp.GetBytesWritten() != uint64(len(expected)) {
t.Fatalf("ReceiveFile EC bytes_written mismatch: got %d want %d", resp.GetBytesWritten(), len(expected))
}
copyStream, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Collection: collection,
IsEcVolume: true,
Ext: ext,
CompactionRevision: math.MaxUint32,
StopOffset: uint64(len(expected)),
})
if err != nil {
t.Fatalf("CopyFile for received EC data start failed: %v", err)
}
var copied []byte
for {
msg, recvErr := copyStream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
t.Fatalf("CopyFile for received EC data recv failed: %v", recvErr)
}
copied = append(copied, msg.GetFileContent()...)
}
if string(copied) != string(expected) {
t.Fatalf("received EC file data mismatch: got %q want %q", string(copied), string(expected))
}
}
func TestCopyFileEcVolumeIgnoreMissingSourcePaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
streamNoIgnore, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: 99601,
Collection: "ec-copy-missing",
IsEcVolume: true,
Ext: ".ec00",
CompactionRevision: math.MaxUint32,
StopOffset: 1,
IgnoreSourceFileNotFound: false,
})
if err == nil {
_, err = streamNoIgnore.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found ec volume id") {
t.Fatalf("CopyFile EC missing source error mismatch: %v", err)
}
streamIgnore, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: 99602,
Collection: "ec-copy-missing",
IsEcVolume: true,
Ext: ".ec00",
CompactionRevision: math.MaxUint32,
StopOffset: 1,
IgnoreSourceFileNotFound: true,
})
if err != nil {
t.Fatalf("CopyFile EC ignore-missing start failed: %v", err)
}
_, err = streamIgnore.Recv()
if err != io.EOF {
t.Fatalf("CopyFile EC ignore-missing expected EOF, got: %v", err)
}
}
-284
View File
@@ -1,284 +0,0 @@
package volume_server_grpc_test
import (
"context"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestVolumeSyncStatusAndReadVolumeFileStatus(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(41)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
syncResp, err := grpcClient.VolumeSyncStatus(ctx, &volume_server_pb.VolumeSyncStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeSyncStatus failed: %v", err)
}
if syncResp.GetVolumeId() != volumeID {
t.Fatalf("VolumeSyncStatus volume id mismatch: got %d want %d", syncResp.GetVolumeId(), volumeID)
}
statusResp, err := grpcClient.ReadVolumeFileStatus(ctx, &volume_server_pb.ReadVolumeFileStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("ReadVolumeFileStatus failed: %v", err)
}
if statusResp.GetVolumeId() != volumeID {
t.Fatalf("ReadVolumeFileStatus volume id mismatch: got %d want %d", statusResp.GetVolumeId(), volumeID)
}
if statusResp.GetVersion() == 0 {
t.Fatalf("ReadVolumeFileStatus expected non-zero version")
}
}
func TestCopyAndStreamMethodsMissingVolumePaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeSyncStatus(ctx, &volume_server_pb.VolumeSyncStatusRequest{VolumeId: 98761})
if err == nil {
t.Fatalf("VolumeSyncStatus should fail for missing volume")
}
incrementalStream, err := grpcClient.VolumeIncrementalCopy(ctx, &volume_server_pb.VolumeIncrementalCopyRequest{VolumeId: 98762, SinceNs: 0})
if err == nil {
_, err = incrementalStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("VolumeIncrementalCopy missing-volume error mismatch: %v", err)
}
readAllStream, err := grpcClient.ReadAllNeedles(ctx, &volume_server_pb.ReadAllNeedlesRequest{VolumeIds: []uint32{98763}})
if err == nil {
_, err = readAllStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("ReadAllNeedles missing-volume error mismatch: %v", err)
}
copyFileStream, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{VolumeId: 98764, Ext: ".dat", StopOffset: 1})
if err == nil {
_, err = copyFileStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("CopyFile missing-volume error mismatch: %v", err)
}
_, err = grpcClient.ReadVolumeFileStatus(ctx, &volume_server_pb.ReadVolumeFileStatusRequest{VolumeId: 98765})
if err == nil || !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("ReadVolumeFileStatus missing-volume error mismatch: %v", err)
}
}
func TestVolumeCopyAndReceiveFileMaintenanceRejection(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stateResp, err := grpcClient.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = grpcClient.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{Maintenance: true, Version: stateResp.GetState().GetVersion()},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
copyStream, err := grpcClient.VolumeCopy(ctx, &volume_server_pb.VolumeCopyRequest{VolumeId: 1, SourceDataNode: "127.0.0.1:1234"})
if err == nil {
_, err = copyStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeCopy maintenance error mismatch: %v", err)
}
receiveClient, err := grpcClient.ReceiveFile(ctx)
if err != nil {
t.Fatalf("ReceiveFile client creation failed: %v", err)
}
_ = receiveClient.Send(&volume_server_pb.ReceiveFileRequest{
Data: &volume_server_pb.ReceiveFileRequest_Info{
Info: &volume_server_pb.ReceiveFileInfo{VolumeId: 1, Ext: ".dat"},
},
})
_, err = receiveClient.CloseAndRecv()
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("ReceiveFile maintenance error mismatch: %v", err)
}
}
func TestVolumeCopySuccessFromPeerAndMountsDestination(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartDualVolumeCluster(t, matrix.P1())
sourceConn, sourceClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer sourceConn.Close()
destConn, destClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(1))
defer destConn.Close()
const volumeID = uint32(42)
framework.AllocateVolume(t, sourceClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 880001, 0x12345678)
payload := []byte("volume-copy-success-payload")
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(0), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload to source expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
copyStream, err := destClient.VolumeCopy(ctx, &volume_server_pb.VolumeCopyRequest{
VolumeId: volumeID,
Collection: "",
SourceDataNode: clusterHarness.VolumeAdminAddress(0) + "." + strings.Split(clusterHarness.VolumeGRPCAddress(0), ":")[1],
})
if err != nil {
t.Fatalf("VolumeCopy start failed: %v", err)
}
sawFinalAppendTimestamp := false
for {
msg, recvErr := copyStream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
t.Fatalf("VolumeCopy recv failed: %v", recvErr)
}
if msg.GetLastAppendAtNs() > 0 {
sawFinalAppendTimestamp = true
}
}
if !sawFinalAppendTimestamp {
t.Fatalf("VolumeCopy expected final response with last_append_at_ns")
}
destReadResp := framework.ReadBytes(t, httpClient, clusterHarness.VolumeAdminURL(1), fid)
destReadBody := framework.ReadAllAndClose(t, destReadResp)
if destReadResp.StatusCode != http.StatusOK {
t.Fatalf("read from copied destination expected 200, got %d", destReadResp.StatusCode)
}
if string(destReadBody) != string(payload) {
t.Fatalf("destination copied payload mismatch: got %q want %q", string(destReadBody), string(payload))
}
}
func TestVolumeCopyOverwritesExistingDestinationVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartDualVolumeCluster(t, matrix.P1())
sourceConn, sourceClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer sourceConn.Close()
destConn, destClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(1))
defer destConn.Close()
const volumeID = uint32(43)
framework.AllocateVolume(t, sourceClient, volumeID, "")
framework.AllocateVolume(t, destClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 880002, 0x23456789)
sourcePayload := []byte("volume-copy-overwrite-source")
destPayload := []byte("volume-copy-overwrite-destination-old")
sourceUploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(0), fid, sourcePayload)
_ = framework.ReadAllAndClose(t, sourceUploadResp)
if sourceUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload to source expected 201, got %d", sourceUploadResp.StatusCode)
}
destUploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(1), fid, destPayload)
_ = framework.ReadAllAndClose(t, destUploadResp)
if destUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload to destination expected 201, got %d", destUploadResp.StatusCode)
}
destReadBeforeResp := framework.ReadBytes(t, httpClient, clusterHarness.VolumeAdminURL(1), fid)
destReadBeforeBody := framework.ReadAllAndClose(t, destReadBeforeResp)
if destReadBeforeResp.StatusCode != http.StatusOK {
t.Fatalf("destination pre-copy read expected 200, got %d", destReadBeforeResp.StatusCode)
}
if string(destReadBeforeBody) != string(destPayload) {
t.Fatalf("destination pre-copy payload mismatch: got %q want %q", string(destReadBeforeBody), string(destPayload))
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
copyStream, err := destClient.VolumeCopy(ctx, &volume_server_pb.VolumeCopyRequest{
VolumeId: volumeID,
Collection: "",
SourceDataNode: clusterHarness.VolumeAdminAddress(0) + "." + strings.Split(clusterHarness.VolumeGRPCAddress(0), ":")[1],
})
if err != nil {
t.Fatalf("VolumeCopy overwrite start failed: %v", err)
}
sawFinalAppendTimestamp := false
for {
msg, recvErr := copyStream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
t.Fatalf("VolumeCopy overwrite recv failed: %v", recvErr)
}
if msg.GetLastAppendAtNs() > 0 {
sawFinalAppendTimestamp = true
}
}
if !sawFinalAppendTimestamp {
t.Fatalf("VolumeCopy overwrite expected final response with last_append_at_ns")
}
destReadAfterResp := framework.ReadBytes(t, httpClient, clusterHarness.VolumeAdminURL(1), fid)
destReadAfterBody := framework.ReadAllAndClose(t, destReadAfterResp)
if destReadAfterResp.StatusCode != http.StatusOK {
t.Fatalf("destination post-copy read expected 200, got %d", destReadAfterResp.StatusCode)
}
if string(destReadAfterBody) != string(sourcePayload) {
t.Fatalf("destination post-copy payload mismatch: got %q want %q", string(destReadAfterBody), string(sourcePayload))
}
}
-146
View File
@@ -1,146 +0,0 @@
package volume_server_grpc_test
import (
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestReadNeedleBlobAndMetaMissingVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.ReadNeedleBlob(ctx, &volume_server_pb.ReadNeedleBlobRequest{
VolumeId: 99111,
Offset: 0,
Size: 16,
})
if err == nil {
t.Fatalf("ReadNeedleBlob should fail for missing volume")
}
if !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("ReadNeedleBlob missing volume error mismatch: %v", err)
}
_, err = grpcClient.ReadNeedleMeta(ctx, &volume_server_pb.ReadNeedleMetaRequest{
VolumeId: 99112,
NeedleId: 1,
Offset: 0,
Size: 16,
})
if err == nil {
t.Fatalf("ReadNeedleMeta should fail for missing volume")
}
if !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("ReadNeedleMeta missing volume error mismatch: %v", err)
}
}
func TestWriteNeedleBlobMaintenanceAndMissingVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.WriteNeedleBlob(ctx, &volume_server_pb.WriteNeedleBlobRequest{
VolumeId: 99113,
NeedleId: 1,
NeedleBlob: []byte("abc"),
Size: 3,
})
if err == nil {
t.Fatalf("WriteNeedleBlob should fail for missing volume")
}
if !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("WriteNeedleBlob missing volume error mismatch: %v", err)
}
stateResp, err := grpcClient.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = grpcClient.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{Maintenance: true, Version: stateResp.GetState().GetVersion()},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
_, err = grpcClient.WriteNeedleBlob(ctx, &volume_server_pb.WriteNeedleBlobRequest{
VolumeId: 1,
NeedleId: 2,
NeedleBlob: []byte("def"),
Size: 3,
})
if err == nil {
t.Fatalf("WriteNeedleBlob should fail in maintenance mode")
}
if !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("WriteNeedleBlob maintenance mode error mismatch: %v", err)
}
}
func TestReadNeedleBlobAndMetaInvalidOffsets(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(92)
framework.AllocateVolume(t, grpcClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 880001, 0xCCDD1122)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, []byte("invalid-offset-check"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != 201 {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.ReadNeedleBlob(ctx, &volume_server_pb.ReadNeedleBlobRequest{
VolumeId: volumeID,
Offset: 1 << 40,
Size: 64,
})
if err == nil {
t.Fatalf("ReadNeedleBlob should fail for invalid offset")
}
if !strings.Contains(strings.ToLower(err.Error()), "read needle blob") {
t.Fatalf("ReadNeedleBlob invalid offset error mismatch: %v", err)
}
_, err = grpcClient.ReadNeedleMeta(ctx, &volume_server_pb.ReadNeedleMetaRequest{
VolumeId: volumeID,
NeedleId: 880001,
Offset: 1 << 40,
Size: 64,
})
if err == nil {
t.Fatalf("ReadNeedleMeta should fail for invalid offset")
}
}
@@ -1,273 +0,0 @@
package volume_server_grpc_test
import (
"context"
"io"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
func TestReadWriteNeedleBlobAndMetaRoundTrip(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(83)
const sourceNeedleID = uint64(333333)
const sourceCookie = uint32(0xABCD0102)
const clonedNeedleID = uint64(333334)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
payload := []byte("blob-roundtrip-content")
fid := framework.NewFileID(volumeID, sourceNeedleID, sourceCookie)
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != 201 {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
fileStatus, err := grpcClient.ReadVolumeFileStatus(ctx, &volume_server_pb.ReadVolumeFileStatusRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("ReadVolumeFileStatus failed: %v", err)
}
if fileStatus.GetIdxFileSize() == 0 {
t.Fatalf("expected non-zero idx file size after upload")
}
idxBytes := copyFileBytes(t, grpcClient, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Ext: ".idx",
CompactionRevision: fileStatus.GetCompactionRevision(),
StopOffset: fileStatus.GetIdxFileSize(),
})
offset, size := findNeedleOffsetAndSize(t, idxBytes, sourceNeedleID)
blobResp, err := grpcClient.ReadNeedleBlob(ctx, &volume_server_pb.ReadNeedleBlobRequest{
VolumeId: volumeID,
Offset: offset,
Size: size,
})
if err != nil {
t.Fatalf("ReadNeedleBlob failed: %v", err)
}
if len(blobResp.GetNeedleBlob()) == 0 {
t.Fatalf("ReadNeedleBlob returned empty blob")
}
metaResp, err := grpcClient.ReadNeedleMeta(ctx, &volume_server_pb.ReadNeedleMetaRequest{
VolumeId: volumeID,
NeedleId: sourceNeedleID,
Offset: offset,
Size: size,
})
if err != nil {
t.Fatalf("ReadNeedleMeta failed: %v", err)
}
if metaResp.GetCookie() != sourceCookie {
t.Fatalf("ReadNeedleMeta cookie mismatch: got %d want %d", metaResp.GetCookie(), sourceCookie)
}
_, err = grpcClient.WriteNeedleBlob(ctx, &volume_server_pb.WriteNeedleBlobRequest{
VolumeId: volumeID,
NeedleId: clonedNeedleID,
Size: size,
NeedleBlob: blobResp.GetNeedleBlob(),
})
if err != nil {
t.Fatalf("WriteNeedleBlob failed: %v", err)
}
clonedStatus, err := grpcClient.VolumeNeedleStatus(ctx, &volume_server_pb.VolumeNeedleStatusRequest{
VolumeId: volumeID,
NeedleId: clonedNeedleID,
})
if err != nil {
t.Fatalf("VolumeNeedleStatus for cloned needle failed: %v", err)
}
if clonedStatus.GetNeedleId() != sourceNeedleID {
t.Fatalf("cloned needle status id mismatch: got %d want %d", clonedStatus.GetNeedleId(), sourceNeedleID)
}
if clonedStatus.GetCookie() != sourceCookie {
t.Fatalf("cloned needle cookie mismatch: got %d want %d", clonedStatus.GetCookie(), sourceCookie)
}
clonedReadResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), framework.NewFileID(volumeID, clonedNeedleID, sourceCookie))
clonedReadBody := framework.ReadAllAndClose(t, clonedReadResp)
if clonedReadResp.StatusCode != 200 {
t.Fatalf("cloned needle GET expected 200, got %d", clonedReadResp.StatusCode)
}
if string(clonedReadBody) != string(payload) {
t.Fatalf("cloned needle body mismatch: got %q want %q", string(clonedReadBody), string(payload))
}
}
func TestReadAllNeedlesStreamsUploadedRecords(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(84)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
expected := map[uint64]string{
444441: "read-all-needle-one",
444442: "read-all-needle-two",
}
for key, body := range expected {
resp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), framework.NewFileID(volumeID, key, 0xA0B0C0D0), []byte(body))
_ = framework.ReadAllAndClose(t, resp)
if resp.StatusCode != 201 {
t.Fatalf("upload for key %d expected 201, got %d", key, resp.StatusCode)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.ReadAllNeedles(ctx, &volume_server_pb.ReadAllNeedlesRequest{VolumeIds: []uint32{volumeID}})
if err != nil {
t.Fatalf("ReadAllNeedles start failed: %v", err)
}
seen := map[uint64]string{}
for {
msg, recvErr := stream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
t.Fatalf("ReadAllNeedles recv failed: %v", recvErr)
}
if _, wanted := expected[msg.GetNeedleId()]; wanted {
seen[msg.GetNeedleId()] = string(msg.GetNeedleBlob())
}
}
for key, body := range expected {
got, found := seen[key]
if !found {
t.Fatalf("ReadAllNeedles missing key %d in stream", key)
}
if got != body {
t.Fatalf("ReadAllNeedles body mismatch for key %d: got %q want %q", key, got, body)
}
}
}
func TestReadAllNeedlesExistingThenMissingVolumeAbortsStream(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const existingVolumeID = uint32(85)
const missingVolumeID = uint32(98585)
const needleID = uint64(445551)
framework.AllocateVolume(t, grpcClient, existingVolumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(existingVolumeID, needleID, 0xAA11BB22)
payload := "read-all-existing-then-missing"
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte(payload))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != 201 {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.ReadAllNeedles(ctx, &volume_server_pb.ReadAllNeedlesRequest{
VolumeIds: []uint32{existingVolumeID, missingVolumeID},
})
if err != nil {
t.Fatalf("ReadAllNeedles start failed: %v", err)
}
seenUploadedNeedle := false
for {
msg, recvErr := stream.Recv()
if recvErr == io.EOF {
t.Fatalf("ReadAllNeedles expected stream error for missing volume, got EOF")
}
if recvErr != nil {
if !strings.Contains(recvErr.Error(), "not found volume id") {
t.Fatalf("ReadAllNeedles missing-volume error mismatch: %v", recvErr)
}
break
}
if msg.GetNeedleId() == needleID && string(msg.GetNeedleBlob()) == payload {
seenUploadedNeedle = true
}
}
if !seenUploadedNeedle {
t.Fatalf("ReadAllNeedles should stream entries from existing volume before missing-volume abort")
}
}
func copyFileBytes(t testing.TB, grpcClient volume_server_pb.VolumeServerClient, req *volume_server_pb.CopyFileRequest) []byte {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.CopyFile(ctx, req)
if err != nil {
t.Fatalf("CopyFile start failed: %v", err)
}
var out []byte
for {
msg, recvErr := stream.Recv()
if recvErr == io.EOF {
return out
}
if recvErr != nil {
t.Fatalf("CopyFile recv failed: %v", recvErr)
}
out = append(out, msg.GetFileContent()...)
}
}
func findNeedleOffsetAndSize(t testing.TB, idxBytes []byte, needleID uint64) (offset int64, size int32) {
t.Helper()
for i := 0; i+types.NeedleMapEntrySize <= len(idxBytes); i += types.NeedleMapEntrySize {
key, entryOffset, entrySize := idx.IdxFileEntry(idxBytes[i : i+types.NeedleMapEntrySize])
if uint64(key) != needleID {
continue
}
if entryOffset.IsZero() || entrySize <= 0 {
continue
}
return entryOffset.ToActualOffset(), int32(entrySize)
}
t.Fatalf("needle id %d not found in idx entries", needleID)
return 0, 0
}
@@ -1,777 +0,0 @@
package volume_server_grpc_test
import (
"context"
"io"
"math"
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestEcMaintenanceModeRejections(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stateResp, err := grpcClient.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = grpcClient.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{
Maintenance: true,
Version: stateResp.GetState().GetVersion(),
},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{VolumeId: 1, Collection: ""})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeEcShardsGenerate maintenance error mismatch: %v", err)
}
_, err = grpcClient.VolumeEcShardsCopy(ctx, &volume_server_pb.VolumeEcShardsCopyRequest{
VolumeId: 1,
Collection: "",
SourceDataNode: "127.0.0.1:1",
ShardIds: []uint32{0},
})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeEcShardsCopy maintenance error mismatch: %v", err)
}
_, err = grpcClient.VolumeEcShardsDelete(ctx, &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: 1,
Collection: "",
ShardIds: []uint32{0},
})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeEcShardsDelete maintenance error mismatch: %v", err)
}
_, err = grpcClient.VolumeEcBlobDelete(ctx, &volume_server_pb.VolumeEcBlobDeleteRequest{
VolumeId: 1,
Collection: "",
FileKey: 1,
Version: 3,
})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeEcBlobDelete maintenance error mismatch: %v", err)
}
_, err = grpcClient.VolumeEcShardsToVolume(ctx, &volume_server_pb.VolumeEcShardsToVolumeRequest{
VolumeId: 1,
Collection: "",
})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeEcShardsToVolume maintenance error mismatch: %v", err)
}
}
func TestEcMissingInvalidAndNoopPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: 98791,
Collection: "",
})
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeEcShardsGenerate missing-volume error mismatch: %v", err)
}
rebuildResp, err := grpcClient.VolumeEcShardsRebuild(ctx, &volume_server_pb.VolumeEcShardsRebuildRequest{
VolumeId: 98792,
Collection: "ec-rebuild",
})
if err != nil {
t.Fatalf("VolumeEcShardsRebuild missing-volume should return empty success, got: %v", err)
}
if len(rebuildResp.GetRebuiltShardIds()) != 0 {
t.Fatalf("VolumeEcShardsRebuild expected no rebuilt shards for missing volume, got %v", rebuildResp.GetRebuiltShardIds())
}
_, err = grpcClient.VolumeEcShardsCopy(ctx, &volume_server_pb.VolumeEcShardsCopyRequest{
VolumeId: 98793,
Collection: "ec-copy",
SourceDataNode: "127.0.0.1:1",
ShardIds: []uint32{0},
DiskId: 99,
})
if err == nil || !strings.Contains(err.Error(), "invalid disk_id") {
t.Fatalf("VolumeEcShardsCopy invalid-disk error mismatch: %v", err)
}
_, err = grpcClient.VolumeEcShardsDelete(ctx, &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: 98794,
Collection: "ec-delete",
ShardIds: []uint32{0, 1},
})
if err != nil {
t.Fatalf("VolumeEcShardsDelete missing-volume should be no-op success, got: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: 98795,
Collection: "ec-mount",
ShardIds: []uint32{0},
})
if err == nil {
t.Fatalf("VolumeEcShardsMount should fail for missing EC shards")
}
_, err = grpcClient.VolumeEcShardsUnmount(ctx, &volume_server_pb.VolumeEcShardsUnmountRequest{
VolumeId: 98796,
ShardIds: []uint32{0},
})
if err != nil {
t.Fatalf("VolumeEcShardsUnmount missing shards should be no-op success, got: %v", err)
}
readStream, err := grpcClient.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
VolumeId: 98797,
ShardId: 0,
Offset: 0,
Size: 1,
})
if err == nil {
_, err = readStream.Recv()
}
if err == nil || err == io.EOF {
t.Fatalf("VolumeEcShardRead should fail for missing EC volume")
}
_, err = grpcClient.VolumeEcBlobDelete(ctx, &volume_server_pb.VolumeEcBlobDeleteRequest{
VolumeId: 98798,
Collection: "ec-blob",
FileKey: 1,
Version: 3,
})
if err != nil {
t.Fatalf("VolumeEcBlobDelete missing local EC volume should be no-op success, got: %v", err)
}
_, err = grpcClient.VolumeEcShardsToVolume(ctx, &volume_server_pb.VolumeEcShardsToVolumeRequest{
VolumeId: 98799,
Collection: "ec-to-volume",
})
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeEcShardsToVolume missing-volume error mismatch: %v", err)
}
_, err = grpcClient.VolumeEcShardsInfo(ctx, &volume_server_pb.VolumeEcShardsInfoRequest{
VolumeId: 98800,
})
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeEcShardsInfo missing-volume error mismatch: %v", err)
}
}
func TestEcGenerateMountInfoUnmountLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(115)
framework.AllocateVolume(t, grpcClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 990001, 0x1234ABCD)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, []byte("ec-generate-lifecycle-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate success path failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0},
})
if err != nil {
t.Fatalf("VolumeEcShardsMount success path failed: %v", err)
}
infoResp, err := grpcClient.VolumeEcShardsInfo(ctx, &volume_server_pb.VolumeEcShardsInfoRequest{
VolumeId: volumeID,
})
if err != nil {
t.Fatalf("VolumeEcShardsInfo after mount failed: %v", err)
}
if len(infoResp.GetEcShardInfos()) == 0 {
t.Fatalf("VolumeEcShardsInfo expected non-empty shard infos after mount")
}
if infoResp.GetVolumeSize() == 0 {
t.Fatalf("VolumeEcShardsInfo expected non-zero volume size after mount")
}
_, err = grpcClient.VolumeEcShardsUnmount(ctx, &volume_server_pb.VolumeEcShardsUnmountRequest{
VolumeId: volumeID,
ShardIds: []uint32{0},
})
if err != nil {
t.Fatalf("VolumeEcShardsUnmount success path failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsInfo(ctx, &volume_server_pb.VolumeEcShardsInfoRequest{
VolumeId: volumeID,
})
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeEcShardsInfo after unmount expected not-found error, got: %v", err)
}
}
func TestEcShardReadAndBlobDeleteLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(116)
const fileKey = uint64(990002)
framework.AllocateVolume(t, grpcClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, fileKey, 0x2233CCDD)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, []byte("ec-shard-read-delete-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0},
})
if err != nil {
t.Fatalf("VolumeEcShardsMount failed: %v", err)
}
readStream, err := grpcClient.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
VolumeId: volumeID,
ShardId: 0,
Offset: 0,
Size: 1,
})
if err != nil {
t.Fatalf("VolumeEcShardRead start failed: %v", err)
}
firstChunk, err := readStream.Recv()
if err != nil {
t.Fatalf("VolumeEcShardRead recv failed: %v", err)
}
if len(firstChunk.GetData()) == 0 {
t.Fatalf("VolumeEcShardRead expected non-empty data chunk before deletion")
}
_, err = grpcClient.VolumeEcBlobDelete(ctx, &volume_server_pb.VolumeEcBlobDeleteRequest{
VolumeId: volumeID,
Collection: "",
FileKey: fileKey,
Version: uint32(needle.GetCurrentVersion()),
})
if err != nil {
t.Fatalf("VolumeEcBlobDelete first delete failed: %v", err)
}
_, err = grpcClient.VolumeEcBlobDelete(ctx, &volume_server_pb.VolumeEcBlobDeleteRequest{
VolumeId: volumeID,
Collection: "",
FileKey: fileKey,
Version: uint32(needle.GetCurrentVersion()),
})
if err != nil {
t.Fatalf("VolumeEcBlobDelete second delete should be idempotent success, got: %v", err)
}
deletedStream, err := grpcClient.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
VolumeId: volumeID,
ShardId: 0,
FileKey: fileKey,
Offset: 0,
Size: 1,
})
if err != nil {
t.Fatalf("VolumeEcShardRead deleted-check start failed: %v", err)
}
deletedMsg, err := deletedStream.Recv()
if err != nil {
t.Fatalf("VolumeEcShardRead deleted-check recv failed: %v", err)
}
if !deletedMsg.GetIsDeleted() {
t.Fatalf("VolumeEcShardRead expected IsDeleted=true after blob delete")
}
_, err = deletedStream.Recv()
if err != io.EOF {
t.Fatalf("VolumeEcShardRead deleted-check expected EOF after deleted marker, got: %v", err)
}
}
func TestEcRebuildMissingShardLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(117)
framework.AllocateVolume(t, grpcClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 990003, 0x3344DDEE)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, []byte("ec-rebuild-shard-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsDelete(ctx, &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0},
})
if err != nil {
t.Fatalf("VolumeEcShardsDelete shard 0 failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0},
})
if err == nil {
t.Fatalf("VolumeEcShardsMount should fail when shard 0 has been deleted")
}
rebuildResp, err := grpcClient.VolumeEcShardsRebuild(ctx, &volume_server_pb.VolumeEcShardsRebuildRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsRebuild failed: %v", err)
}
if len(rebuildResp.GetRebuiltShardIds()) == 0 {
t.Fatalf("VolumeEcShardsRebuild expected rebuilt shard ids")
}
foundShard0 := false
for _, shardID := range rebuildResp.GetRebuiltShardIds() {
if shardID == 0 {
foundShard0 = true
break
}
}
if !foundShard0 {
t.Fatalf("VolumeEcShardsRebuild expected shard 0 to be rebuilt, got %v", rebuildResp.GetRebuiltShardIds())
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0},
})
if err != nil {
t.Fatalf("VolumeEcShardsMount shard 0 after rebuild failed: %v", err)
}
}
func TestEcShardsToVolumeMissingShardAndNoLiveEntries(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
httpClient := framework.NewHTTPClient()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
t.Run("missing shard returns error", func(t *testing.T) {
const volumeID = uint32(118)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 990004, 0x4455EEFF)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, []byte("ec-to-volume-missing-shard-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsDelete(ctx, &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0},
})
if err != nil {
t.Fatalf("VolumeEcShardsDelete shard 0 failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{1},
})
if err != nil {
t.Fatalf("VolumeEcShardsMount shard 1 failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsToVolume(ctx, &volume_server_pb.VolumeEcShardsToVolumeRequest{
VolumeId: volumeID,
Collection: "",
})
if err == nil || !strings.Contains(err.Error(), "missing shard 0") {
t.Fatalf("VolumeEcShardsToVolume missing-shard error mismatch: %v", err)
}
})
t.Run("no live entries returns failed precondition", func(t *testing.T) {
const volumeID = uint32(119)
const needleID = uint64(990005)
const cookie = uint32(0x5566FF11)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, []byte("ec-no-live-entries-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
deleteResp := framework.DoRequest(t, httpClient, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL()+"/"+fid))
_ = framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusAccepted {
t.Fatalf("delete expected 202, got %d", deleteResp.StatusCode)
}
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
})
if err != nil {
t.Fatalf("VolumeEcShardsMount data shards failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsToVolume(ctx, &volume_server_pb.VolumeEcShardsToVolumeRequest{
VolumeId: volumeID,
Collection: "",
})
if err == nil {
t.Fatalf("VolumeEcShardsToVolume expected failed-precondition error when no live entries")
}
if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("VolumeEcShardsToVolume no-live-entries expected FailedPrecondition, got %v (%v)", status.Code(err), err)
}
if !strings.Contains(err.Error(), erasure_coding.EcNoLiveEntriesSubstring) {
t.Fatalf("VolumeEcShardsToVolume no-live-entries error should mention %q, got %v", erasure_coding.EcNoLiveEntriesSubstring, err)
}
})
}
func TestEcShardsToVolumeSuccessRoundTrip(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(120)
const needleID = uint64(990006)
const cookie = uint32(0x66771122)
framework.AllocateVolume(t, grpcClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, needleID, cookie)
payload := []byte("ec-shards-to-volume-success-roundtrip-content")
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
})
if err != nil {
t.Fatalf("VolumeEcShardsMount data shards failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsToVolume(ctx, &volume_server_pb.VolumeEcShardsToVolumeRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsToVolume success path failed: %v", err)
}
readResp := framework.ReadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid)
readBody := framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusOK {
t.Fatalf("post-conversion read expected 200, got %d", readResp.StatusCode)
}
if string(readBody) != string(payload) {
t.Fatalf("post-conversion payload mismatch: got %q want %q", string(readBody), string(payload))
}
}
func TestEcShardsDeleteLastShardRemovesEcx(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(121)
framework.AllocateVolume(t, grpcClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 990007, 0x77882233)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, []byte("ec-delete-all-shards-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("VolumeEcShardsGenerate failed: %v", err)
}
// Verify .ecx is present before deleting all shards.
ecxBeforeDelete, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Collection: "",
IsEcVolume: true,
Ext: ".ecx",
CompactionRevision: math.MaxUint32,
StopOffset: 1,
})
if err != nil {
t.Fatalf("CopyFile .ecx before shard deletion start failed: %v", err)
}
if _, err = ecxBeforeDelete.Recv(); err != nil {
t.Fatalf("CopyFile .ecx before shard deletion recv failed: %v", err)
}
_, err = grpcClient.VolumeEcShardsDelete(ctx, &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: volumeID,
Collection: "",
ShardIds: []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
})
if err != nil {
t.Fatalf("VolumeEcShardsDelete all shards failed: %v", err)
}
ecxAfterDelete, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Collection: "",
IsEcVolume: true,
Ext: ".ecx",
CompactionRevision: math.MaxUint32,
StopOffset: 1,
})
if err == nil {
_, err = ecxAfterDelete.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found ec volume id") {
t.Fatalf("CopyFile .ecx after deleting all shards should fail not-found, got: %v", err)
}
}
func TestEcShardsCopyFromPeerSuccess(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartDualVolumeCluster(t, matrix.P1())
sourceConn, sourceClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer sourceConn.Close()
destConn, destClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(1))
defer destConn.Close()
const volumeID = uint32(122)
framework.AllocateVolume(t, sourceClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 990008, 0x88993344)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(0), fid, []byte("ec-copy-from-peer-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("source upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := sourceClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
VolumeId: volumeID,
Collection: "",
})
if err != nil {
t.Fatalf("source VolumeEcShardsGenerate failed: %v", err)
}
sourceDataNode := clusterHarness.VolumeAdminAddress(0) + "." + strings.Split(clusterHarness.VolumeGRPCAddress(0), ":")[1]
_, err = destClient.VolumeEcShardsCopy(ctx, &volume_server_pb.VolumeEcShardsCopyRequest{
VolumeId: volumeID,
Collection: "",
SourceDataNode: sourceDataNode,
ShardIds: []uint32{0},
CopyEcxFile: true,
CopyVifFile: true,
})
if err != nil {
t.Fatalf("destination VolumeEcShardsCopy success path failed: %v", err)
}
for _, ext := range []string{".ec00", ".ecx", ".vif"} {
copyStream, copyErr := destClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Collection: "",
IsEcVolume: true,
Ext: ext,
CompactionRevision: math.MaxUint32,
StopOffset: 1,
})
if copyErr != nil {
t.Fatalf("destination CopyFile %s start failed: %v", ext, copyErr)
}
if _, copyErr = copyStream.Recv(); copyErr != nil {
t.Fatalf("destination CopyFile %s recv failed: %v", ext, copyErr)
}
}
}
func TestEcShardsCopyFailsWhenSourceUnavailable(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeEcShardsCopy(ctx, &volume_server_pb.VolumeEcShardsCopyRequest{
VolumeId: 12345,
Collection: "",
SourceDataNode: "127.0.0.1:1.1",
ShardIds: []uint32{0},
CopyEcxFile: true,
})
if err == nil || !strings.Contains(err.Error(), "VolumeEcShardsCopy volume") {
t.Fatalf("VolumeEcShardsCopy source-unavailable error mismatch: %v", err)
}
}
@@ -1,139 +0,0 @@
package volume_server_grpc_test
import (
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestStateAndStatusRPCs(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
initialState, err := client.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
if initialState.GetState() == nil {
t.Fatalf("GetState returned nil state")
}
setResp, err := client.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{
Maintenance: true,
Version: initialState.GetState().GetVersion(),
},
})
if err != nil {
t.Fatalf("SetState(maintenance=true) failed: %v", err)
}
if !setResp.GetState().GetMaintenance() {
t.Fatalf("expected maintenance=true after SetState")
}
setResp, err = client.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{
Maintenance: false,
Version: setResp.GetState().GetVersion(),
},
})
if err != nil {
t.Fatalf("SetState(maintenance=false) failed: %v", err)
}
if setResp.GetState().GetMaintenance() {
t.Fatalf("expected maintenance=false after SetState")
}
statusResp, err := client.VolumeServerStatus(ctx, &volume_server_pb.VolumeServerStatusRequest{})
if err != nil {
t.Fatalf("VolumeServerStatus failed: %v", err)
}
if statusResp.GetVersion() == "" {
t.Fatalf("VolumeServerStatus returned empty version")
}
if len(statusResp.GetDiskStatuses()) == 0 {
t.Fatalf("VolumeServerStatus returned no disk statuses")
}
if statusResp.GetState() == nil {
t.Fatalf("VolumeServerStatus returned nil state")
}
if statusResp.GetMemoryStatus() == nil {
t.Fatalf("VolumeServerStatus returned nil memory status")
}
if statusResp.GetMemoryStatus().GetGoroutines() <= 0 {
t.Fatalf("VolumeServerStatus memory status should report goroutines, got %d", statusResp.GetMemoryStatus().GetGoroutines())
}
pingResp, err := client.Ping(ctx, &volume_server_pb.PingRequest{})
if err != nil {
t.Fatalf("Ping failed: %v", err)
}
if pingResp.GetStartTimeNs() == 0 || pingResp.GetStopTimeNs() == 0 {
t.Fatalf("Ping timestamps should be non-zero: %+v", pingResp)
}
if pingResp.GetStopTimeNs() < pingResp.GetStartTimeNs() {
t.Fatalf("Ping stop time should be >= start time: %+v", pingResp)
}
}
func TestSetStateVersionMismatchAndNilStateNoop(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, client := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
initialState, err := client.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
initialVersion := initialState.GetState().GetVersion()
staleResp, err := client.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{
Maintenance: true,
Version: initialVersion + 1,
},
})
if err == nil {
t.Fatalf("SetState with stale version should fail")
}
if !strings.Contains(err.Error(), "version mismatch") {
t.Fatalf("SetState stale version error mismatch: %v", err)
}
if staleResp.GetState().GetVersion() != initialVersion {
t.Fatalf("SetState stale version should not mutate server version: got %d want %d", staleResp.GetState().GetVersion(), initialVersion)
}
if staleResp.GetState().GetMaintenance() != initialState.GetState().GetMaintenance() {
t.Fatalf("SetState stale version should not mutate maintenance flag")
}
nilResp, err := client.SetState(ctx, &volume_server_pb.SetStateRequest{})
if err != nil {
t.Fatalf("SetState nil-state request should be no-op success: %v", err)
}
if nilResp.GetState().GetVersion() != initialVersion {
t.Fatalf("SetState nil-state should keep version unchanged: got %d want %d", nilResp.GetState().GetVersion(), initialVersion)
}
if nilResp.GetState().GetMaintenance() != initialState.GetState().GetMaintenance() {
t.Fatalf("SetState nil-state should keep maintenance unchanged")
}
}
-387
View File
@@ -1,387 +0,0 @@
package volume_server_grpc_test
import (
"context"
"io"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestScrubVolumeIndexAndUnsupportedMode(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(61)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
indexResp, err := grpcClient.ScrubVolume(ctx, &volume_server_pb.ScrubVolumeRequest{
VolumeIds: []uint32{volumeID},
Mode: volume_server_pb.VolumeScrubMode_INDEX,
})
if err != nil {
t.Fatalf("ScrubVolume index mode failed: %v", err)
}
if indexResp.GetTotalVolumes() != 1 {
t.Fatalf("ScrubVolume expected total_volumes=1, got %d", indexResp.GetTotalVolumes())
}
_, err = grpcClient.ScrubVolume(ctx, &volume_server_pb.ScrubVolumeRequest{
VolumeIds: []uint32{volumeID},
Mode: volume_server_pb.VolumeScrubMode(99),
})
if err == nil {
t.Fatalf("ScrubVolume should fail for unsupported mode")
}
if !strings.Contains(err.Error(), "unsupported volume scrub mode") {
t.Fatalf("ScrubVolume unsupported mode error mismatch: %v", err)
}
}
func TestScrubEcVolumeMissingVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.ScrubEcVolume(ctx, &volume_server_pb.ScrubEcVolumeRequest{
VolumeIds: []uint32{98765},
Mode: volume_server_pb.VolumeScrubMode_INDEX,
})
if err == nil {
t.Fatalf("ScrubEcVolume should fail for missing EC volume")
}
if !strings.Contains(err.Error(), "EC volume id") {
t.Fatalf("ScrubEcVolume missing-volume error mismatch: %v", err)
}
}
func TestScrubEcVolumeAutoSelectNoEcVolumes(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := grpcClient.ScrubEcVolume(ctx, &volume_server_pb.ScrubEcVolumeRequest{
Mode: volume_server_pb.VolumeScrubMode_INDEX,
})
if err != nil {
t.Fatalf("ScrubEcVolume auto-select failed: %v", err)
}
if resp.GetTotalVolumes() != 0 {
t.Fatalf("ScrubEcVolume auto-select expected total_volumes=0 without EC data, got %d", resp.GetTotalVolumes())
}
if len(resp.GetBrokenVolumeIds()) != 0 {
t.Fatalf("ScrubEcVolume auto-select expected no broken volumes, got %v", resp.GetBrokenVolumeIds())
}
}
func TestQueryInvalidAndMissingFileIDPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
invalidStream, err := grpcClient.Query(ctx, &volume_server_pb.QueryRequest{
FromFileIds: []string{"bad-fid"},
Selections: []string{"name"},
Filter: &volume_server_pb.QueryRequest_Filter{},
InputSerialization: &volume_server_pb.QueryRequest_InputSerialization{
JsonInput: &volume_server_pb.QueryRequest_InputSerialization_JSONInput{},
},
})
if err == nil {
_, err = invalidStream.Recv()
}
if err == nil {
t.Fatalf("Query should fail for invalid file id")
}
missingFid := framework.NewFileID(98766, 1, 1)
missingStream, err := grpcClient.Query(ctx, &volume_server_pb.QueryRequest{
FromFileIds: []string{missingFid},
Selections: []string{"name"},
Filter: &volume_server_pb.QueryRequest_Filter{},
InputSerialization: &volume_server_pb.QueryRequest_InputSerialization{
JsonInput: &volume_server_pb.QueryRequest_InputSerialization_JSONInput{},
},
})
if err == nil {
_, err = missingStream.Recv()
}
if err == nil {
t.Fatalf("Query should fail for missing file id volume")
}
}
func TestScrubVolumeAutoSelectAndAllModes(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeIDA = uint32(62)
const volumeIDB = uint32(63)
framework.AllocateVolume(t, grpcClient, volumeIDA, "")
framework.AllocateVolume(t, grpcClient, volumeIDB, "")
// upload some data so index files are not zero-sized
httpClient := framework.NewHTTPClient()
framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), framework.NewFileID(volumeIDA, 1, 1), []byte("test data A"))
framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), framework.NewFileID(volumeIDB, 2, 2), []byte("test data B"))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
autoResp, err := grpcClient.ScrubVolume(ctx, &volume_server_pb.ScrubVolumeRequest{
Mode: volume_server_pb.VolumeScrubMode_INDEX,
})
if err != nil {
t.Fatalf("ScrubVolume auto-select failed: %v", err)
}
if autoResp.GetTotalVolumes() < 2 {
t.Fatalf("ScrubVolume auto-select expected at least 2 volumes, got %d", autoResp.GetTotalVolumes())
}
localResp, err := grpcClient.ScrubVolume(ctx, &volume_server_pb.ScrubVolumeRequest{
VolumeIds: []uint32{volumeIDA},
Mode: volume_server_pb.VolumeScrubMode_LOCAL,
})
if err != nil {
t.Fatalf("ScrubVolume local mode failed: %v", err)
}
if localResp.GetTotalVolumes() != 1 {
t.Fatalf("ScrubVolume local mode expected total_volumes=1, got %d", localResp.GetTotalVolumes())
}
if len(localResp.GetBrokenVolumeIds()) != 0 {
t.Fatalf("ScrubVolume local mode expected no broken volumes, got %v: %v", localResp.GetBrokenVolumeIds(), localResp.GetDetails())
}
fullResp, err := grpcClient.ScrubVolume(ctx, &volume_server_pb.ScrubVolumeRequest{
VolumeIds: []uint32{volumeIDA},
Mode: volume_server_pb.VolumeScrubMode_FULL,
})
if err != nil {
t.Fatalf("ScrubVolume full mode failed: %v", err)
}
if fullResp.GetTotalVolumes() != 1 {
t.Fatalf("ScrubVolume full mode expected total_volumes=1, got %d", fullResp.GetTotalVolumes())
}
if len(fullResp.GetBrokenVolumeIds()) != 0 {
t.Fatalf("ScrubVolume full mode expected no broken volumes, got %v: %v", fullResp.GetBrokenVolumeIds(), fullResp.GetDetails())
}
}
func TestQueryJsonSuccessAndCsvNoOutput(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(64)
const needleID = uint64(777001)
const cookie = uint32(0xAABBCCDD)
framework.AllocateVolume(t, grpcClient, volumeID, "")
jsonLines := []byte("{\"score\":3}\n{\"score\":12}\n{\"score\":18}\n")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, needleID, cookie)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, jsonLines)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != 201 {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
queryStream, err := grpcClient.Query(ctx, &volume_server_pb.QueryRequest{
FromFileIds: []string{fid},
Selections: []string{"score"},
Filter: &volume_server_pb.QueryRequest_Filter{
Field: "score",
Operand: ">",
Value: "10",
},
InputSerialization: &volume_server_pb.QueryRequest_InputSerialization{
JsonInput: &volume_server_pb.QueryRequest_InputSerialization_JSONInput{Type: "LINES"},
},
})
if err != nil {
t.Fatalf("Query json start failed: %v", err)
}
firstStripe, err := queryStream.Recv()
if err != nil {
t.Fatalf("Query json recv failed: %v", err)
}
records := string(firstStripe.GetRecords())
if !strings.Contains(records, "score:12") || !strings.Contains(records, "score:18") {
t.Fatalf("Query json records missing expected filtered scores: %q", records)
}
if strings.Contains(records, "score:3") {
t.Fatalf("Query json records should not include filtered-out score: %q", records)
}
_, err = queryStream.Recv()
if err != io.EOF {
t.Fatalf("Query json expected EOF after first stripe, got: %v", err)
}
csvStream, err := grpcClient.Query(ctx, &volume_server_pb.QueryRequest{
FromFileIds: []string{fid},
Selections: []string{"score"},
Filter: &volume_server_pb.QueryRequest_Filter{},
InputSerialization: &volume_server_pb.QueryRequest_InputSerialization{
CsvInput: &volume_server_pb.QueryRequest_InputSerialization_CSVInput{},
},
})
if err != nil {
t.Fatalf("Query csv start failed: %v", err)
}
_, err = csvStream.Recv()
if err != io.EOF {
t.Fatalf("Query csv expected EOF with no rows, got: %v", err)
}
}
func TestQueryJsonNoMatchReturnsEmptyStripe(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(65)
const needleID = uint64(777002)
const cookie = uint32(0xABABCDCD)
framework.AllocateVolume(t, grpcClient, volumeID, "")
jsonLines := []byte("{\"score\":1}\n{\"score\":2}\n")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, needleID, cookie)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, jsonLines)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != 201 {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
queryStream, err := grpcClient.Query(ctx, &volume_server_pb.QueryRequest{
FromFileIds: []string{fid},
Selections: []string{"score"},
Filter: &volume_server_pb.QueryRequest_Filter{
Field: "score",
Operand: ">",
Value: "100",
},
InputSerialization: &volume_server_pb.QueryRequest_InputSerialization{
JsonInput: &volume_server_pb.QueryRequest_InputSerialization_JSONInput{Type: "LINES"},
},
})
if err != nil {
t.Fatalf("Query json no-match start failed: %v", err)
}
firstStripe, err := queryStream.Recv()
if err != nil {
t.Fatalf("Query json no-match recv failed: %v", err)
}
if len(firstStripe.GetRecords()) != 0 {
t.Fatalf("Query json no-match expected empty records stripe, got: %q", string(firstStripe.GetRecords()))
}
_, err = queryStream.Recv()
if err != io.EOF {
t.Fatalf("Query json no-match expected EOF after first empty stripe, got: %v", err)
}
}
func TestQueryCookieMismatchReturnsEOFNoResults(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(66)
const needleID = uint64(777003)
const cookie = uint32(0xCDCDABAB)
framework.AllocateVolume(t, grpcClient, volumeID, "")
jsonLines := []byte("{\"score\":7}\n{\"score\":8}\n")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, needleID, cookie)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, jsonLines)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != 201 {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
wrongCookieFid := framework.NewFileID(volumeID, needleID, cookie+1)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.Query(ctx, &volume_server_pb.QueryRequest{
FromFileIds: []string{wrongCookieFid},
Selections: []string{"score"},
Filter: &volume_server_pb.QueryRequest_Filter{
Field: "score",
Operand: ">",
Value: "0",
},
InputSerialization: &volume_server_pb.QueryRequest_InputSerialization{
JsonInput: &volume_server_pb.QueryRequest_InputSerialization_JSONInput{Type: "LINES"},
},
})
if err != nil {
t.Fatalf("Query start for cookie mismatch should not fail immediately, got: %v", err)
}
_, err = stream.Recv()
if err != io.EOF {
t.Fatalf("Query cookie mismatch expected EOF with no streamed records, got: %v", err)
}
}
-206
View File
@@ -1,206 +0,0 @@
package volume_server_grpc_test
import (
"bytes"
"context"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestVolumeTailSenderMissingVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.VolumeTailSender(ctx, &volume_server_pb.VolumeTailSenderRequest{VolumeId: 77777, SinceNs: 0, IdleTimeoutSeconds: 1})
if err == nil {
_, err = stream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found volume") {
t.Fatalf("VolumeTailSender missing-volume error mismatch: %v", err)
}
}
func TestVolumeTailSenderHeartbeatThenEOF(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(71)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.VolumeTailSender(ctx, &volume_server_pb.VolumeTailSenderRequest{
VolumeId: volumeID,
SinceNs: 0,
IdleTimeoutSeconds: 1,
})
if err != nil {
t.Fatalf("VolumeTailSender start failed: %v", err)
}
msg, err := stream.Recv()
if err != nil {
t.Fatalf("VolumeTailSender first recv failed: %v", err)
}
if !msg.GetIsLastChunk() {
t.Fatalf("expected first tail message to be heartbeat IsLastChunk=true")
}
_, err = stream.Recv()
if err != io.EOF {
t.Fatalf("expected EOF after idle timeout drain, got: %v", err)
}
}
func TestVolumeTailReceiverMissingVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.VolumeTailReceiver(ctx, &volume_server_pb.VolumeTailReceiverRequest{VolumeId: 88888, SourceVolumeServer: clusterHarness.VolumeServerAddress(), SinceNs: 0, IdleTimeoutSeconds: 1})
if err == nil || !strings.Contains(err.Error(), "receiver not found volume") {
t.Fatalf("VolumeTailReceiver missing-volume error mismatch: %v", err)
}
}
func TestVolumeTailReceiverReplicatesSourceUpdates(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartDualVolumeCluster(t, matrix.P1())
sourceConn, sourceClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer sourceConn.Close()
destConn, destClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(1))
defer destConn.Close()
const volumeID = uint32(72)
framework.AllocateVolume(t, sourceClient, volumeID, "")
framework.AllocateVolume(t, destClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 880003, 0x3456789A)
payload := []byte("tail-receiver-replicates-source-updates")
sourceUploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(0), fid, payload)
_ = framework.ReadAllAndClose(t, sourceUploadResp)
if sourceUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("source upload expected 201, got %d", sourceUploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := destClient.VolumeTailReceiver(ctx, &volume_server_pb.VolumeTailReceiverRequest{
VolumeId: volumeID,
SourceVolumeServer: clusterHarness.VolumeAdminAddress(0) + "." + strings.Split(clusterHarness.VolumeGRPCAddress(0), ":")[1],
SinceNs: 0,
IdleTimeoutSeconds: 1,
})
if err != nil {
t.Fatalf("VolumeTailReceiver success path failed: %v", err)
}
destReadResp := framework.ReadBytes(t, httpClient, clusterHarness.VolumeAdminURL(1), fid)
destReadBody := framework.ReadAllAndClose(t, destReadResp)
if destReadResp.StatusCode != http.StatusOK {
t.Fatalf("destination read after tail receive expected 200, got %d", destReadResp.StatusCode)
}
if string(destReadBody) != string(payload) {
t.Fatalf("destination tail-received payload mismatch: got %q want %q", string(destReadBody), string(payload))
}
}
func TestVolumeTailSenderLargeNeedleChunking(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(73)
framework.AllocateVolume(t, grpcClient, volumeID, "")
httpClient := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 880004, 0x456789AB)
largePayload := bytes.Repeat([]byte("L"), 2*1024*1024+128*1024)
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("large upload expected 201, got %d", uploadResp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
stream, err := grpcClient.VolumeTailSender(ctx, &volume_server_pb.VolumeTailSenderRequest{
VolumeId: volumeID,
SinceNs: 0,
IdleTimeoutSeconds: 1,
})
if err != nil {
t.Fatalf("VolumeTailSender start failed: %v", err)
}
dataChunkCount := 0
sawNonLastDataChunk := false
sawLastDataChunk := false
for {
msg, recvErr := stream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
t.Fatalf("VolumeTailSender recv failed: %v", recvErr)
}
if len(msg.GetNeedleBody()) == 0 {
continue
}
dataChunkCount++
if msg.GetIsLastChunk() {
sawLastDataChunk = true
} else {
sawNonLastDataChunk = true
}
}
if dataChunkCount < 2 {
t.Fatalf("VolumeTailSender expected multiple chunks for large needle, got %d", dataChunkCount)
}
if !sawNonLastDataChunk {
t.Fatalf("VolumeTailSender expected at least one non-last data chunk")
}
if !sawLastDataChunk {
t.Fatalf("VolumeTailSender expected a final data chunk marked IsLastChunk=true")
}
}
@@ -1,236 +0,0 @@
package volume_server_grpc_test
import (
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestFetchAndWriteNeedleMaintenanceAndMissingVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.FetchAndWriteNeedle(ctx, &volume_server_pb.FetchAndWriteNeedleRequest{
VolumeId: 98781,
NeedleId: 1,
})
if err == nil || !strings.Contains(err.Error(), "not found volume id") {
t.Fatalf("FetchAndWriteNeedle missing-volume error mismatch: %v", err)
}
stateResp, err := grpcClient.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = grpcClient.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{
Maintenance: true,
Version: stateResp.GetState().GetVersion(),
},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
_, err = grpcClient.FetchAndWriteNeedle(ctx, &volume_server_pb.FetchAndWriteNeedleRequest{
VolumeId: 1,
NeedleId: 1,
})
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("FetchAndWriteNeedle maintenance error mismatch: %v", err)
}
}
func TestFetchAndWriteNeedleInvalidRemoteConfig(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(88)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := grpcClient.FetchAndWriteNeedle(ctx, &volume_server_pb.FetchAndWriteNeedleRequest{
VolumeId: volumeID,
NeedleId: 1,
Cookie: 1,
Size: 1,
RemoteConf: &remote_pb.RemoteConf{
Name: "it-invalid-remote",
Type: "does-not-exist",
},
RemoteLocation: &remote_pb.RemoteStorageLocation{
Name: "it-invalid-remote",
Path: "/test",
},
})
if err == nil || !strings.Contains(err.Error(), "get remote client") {
t.Fatalf("FetchAndWriteNeedle invalid-remote error mismatch: %v", err)
}
}
func TestVolumeTierMoveDatToRemoteErrorPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(85)
const collection = "tier-collection"
framework.AllocateVolume(t, grpcClient, volumeID, collection)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
missingStream, err := grpcClient.VolumeTierMoveDatToRemote(ctx, &volume_server_pb.VolumeTierMoveDatToRemoteRequest{
VolumeId: 98782,
Collection: collection,
DestinationBackendName: "dummy",
})
if err == nil {
_, err = missingStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeTierMoveDatToRemote missing-volume error mismatch: %v", err)
}
mismatchStream, err := grpcClient.VolumeTierMoveDatToRemote(ctx, &volume_server_pb.VolumeTierMoveDatToRemoteRequest{
VolumeId: volumeID,
Collection: "wrong-collection",
DestinationBackendName: "dummy",
})
if err == nil {
_, err = mismatchStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "unexpected input") {
t.Fatalf("VolumeTierMoveDatToRemote collection mismatch error mismatch: %v", err)
}
stateResp, err := grpcClient.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = grpcClient.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{
Maintenance: true,
Version: stateResp.GetState().GetVersion(),
},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
maintenanceStream, err := grpcClient.VolumeTierMoveDatToRemote(ctx, &volume_server_pb.VolumeTierMoveDatToRemoteRequest{
VolumeId: volumeID,
Collection: collection,
DestinationBackendName: "dummy",
})
if err == nil {
_, err = maintenanceStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("VolumeTierMoveDatToRemote maintenance error mismatch: %v", err)
}
}
func TestVolumeTierMoveDatToRemoteMissingBackend(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(89)
const collection = "tier-missing-backend"
framework.AllocateVolume(t, grpcClient, volumeID, collection)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := grpcClient.VolumeTierMoveDatToRemote(ctx, &volume_server_pb.VolumeTierMoveDatToRemoteRequest{
VolumeId: volumeID,
Collection: collection,
DestinationBackendName: "definitely-missing-backend",
})
if err == nil {
_, err = stream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "destination definitely-missing-backend not found") {
t.Fatalf("VolumeTierMoveDatToRemote missing-backend error mismatch: %v", err)
}
}
func TestVolumeTierMoveDatFromRemoteErrorPaths(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(86)
const collection = "tier-download-collection"
framework.AllocateVolume(t, grpcClient, volumeID, collection)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
missingStream, err := grpcClient.VolumeTierMoveDatFromRemote(ctx, &volume_server_pb.VolumeTierMoveDatFromRemoteRequest{
VolumeId: 98783,
Collection: collection,
})
if err == nil {
_, err = missingStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("VolumeTierMoveDatFromRemote missing-volume error mismatch: %v", err)
}
mismatchStream, err := grpcClient.VolumeTierMoveDatFromRemote(ctx, &volume_server_pb.VolumeTierMoveDatFromRemoteRequest{
VolumeId: volumeID,
Collection: "wrong-collection",
})
if err == nil {
_, err = mismatchStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "unexpected input") {
t.Fatalf("VolumeTierMoveDatFromRemote collection mismatch error mismatch: %v", err)
}
localDiskStream, err := grpcClient.VolumeTierMoveDatFromRemote(ctx, &volume_server_pb.VolumeTierMoveDatFromRemoteRequest{
VolumeId: volumeID,
Collection: collection,
})
if err == nil {
_, err = localDiskStream.Recv()
}
if err == nil || !strings.Contains(err.Error(), "already on local disk") {
t.Fatalf("VolumeTierMoveDatFromRemote local-disk error mismatch: %v", err)
}
}
-87
View File
@@ -1,87 +0,0 @@
package volume_server_grpc_test
import (
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
func TestVacuumVolumeCheckSuccessAndMissingVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(31)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := grpcClient.VacuumVolumeCheck(ctx, &volume_server_pb.VacuumVolumeCheckRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VacuumVolumeCheck existing volume failed: %v", err)
}
if resp.GetGarbageRatio() < 0 || resp.GetGarbageRatio() > 1 {
t.Fatalf("unexpected garbage ratio: %f", resp.GetGarbageRatio())
}
_, err = grpcClient.VacuumVolumeCheck(ctx, &volume_server_pb.VacuumVolumeCheckRequest{VolumeId: 99999})
if err == nil {
t.Fatalf("VacuumVolumeCheck should fail for missing volume")
}
}
func TestVacuumMaintenanceModeRejections(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stateResp, err := grpcClient.GetState(ctx, &volume_server_pb.GetStateRequest{})
if err != nil {
t.Fatalf("GetState failed: %v", err)
}
_, err = grpcClient.SetState(ctx, &volume_server_pb.SetStateRequest{
State: &volume_server_pb.VolumeServerState{Maintenance: true, Version: stateResp.GetState().GetVersion()},
})
if err != nil {
t.Fatalf("SetState maintenance=true failed: %v", err)
}
assertMaintenanceErr := func(name string, err error) {
t.Helper()
if err == nil {
t.Fatalf("%s should fail in maintenance mode", name)
}
if !strings.Contains(err.Error(), "maintenance mode") {
t.Fatalf("%s expected maintenance mode error, got: %v", name, err)
}
}
compactStream, err := grpcClient.VacuumVolumeCompact(ctx, &volume_server_pb.VacuumVolumeCompactRequest{VolumeId: 31})
if err == nil {
_, err = compactStream.Recv()
}
assertMaintenanceErr("VacuumVolumeCompact", err)
_, err = grpcClient.VacuumVolumeCommit(ctx, &volume_server_pb.VacuumVolumeCommitRequest{VolumeId: 31})
assertMaintenanceErr("VacuumVolumeCommit", err)
_, err = grpcClient.VacuumVolumeCleanup(ctx, &volume_server_pb.VacuumVolumeCleanupRequest{VolumeId: 31})
assertMaintenanceErr("VacuumVolumeCleanup", err)
}
-174
View File
@@ -1,174 +0,0 @@
package volume_server_http_test
import (
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
)
func TestAdminStatusAndHealthz(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
client := framework.NewHTTPClient()
statusReq, err := http.NewRequest(http.MethodGet, cluster.VolumeAdminURL()+"/status", nil)
if err != nil {
t.Fatalf("create status request: %v", err)
}
statusReq.Header.Set(request_id.AmzRequestIDHeader, "test-request-id-1")
statusResp := framework.DoRequest(t, client, statusReq)
statusBody := framework.ReadAllAndClose(t, statusResp)
if statusResp.StatusCode != http.StatusOK {
t.Fatalf("expected /status code 200, got %d, body: %s", statusResp.StatusCode, string(statusBody))
}
if got := statusResp.Header.Get("Server"); !strings.Contains(got, "SeaweedFS Volume") {
t.Fatalf("expected /status Server header to contain SeaweedFS Volume, got %q", got)
}
if got := statusResp.Header.Get(request_id.AmzRequestIDHeader); got != "test-request-id-1" {
t.Fatalf("expected echoed request id, got %q", got)
}
var payload map[string]interface{}
if err := json.Unmarshal(statusBody, &payload); err != nil {
t.Fatalf("decode status response: %v", err)
}
for _, field := range []string{"Version", "DiskStatuses", "Volumes"} {
if _, found := payload[field]; !found {
t.Fatalf("status payload missing field %q", field)
}
}
healthReq := mustNewRequest(t, http.MethodGet, cluster.VolumeAdminURL()+"/healthz")
healthReq.Header.Set(request_id.AmzRequestIDHeader, "test-request-id-2")
healthResp := framework.DoRequest(t, client, healthReq)
_ = framework.ReadAllAndClose(t, healthResp)
if healthResp.StatusCode != http.StatusOK {
t.Fatalf("expected /healthz code 200, got %d", healthResp.StatusCode)
}
if got := healthResp.Header.Get("Server"); !strings.Contains(got, "SeaweedFS Volume") {
t.Fatalf("expected /healthz Server header to contain SeaweedFS Volume, got %q", got)
}
if got := healthResp.Header.Get(request_id.AmzRequestIDHeader); got != "test-request-id-2" {
t.Fatalf("expected /healthz echoed request id, got %q", got)
}
uiResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, cluster.VolumeAdminURL()+"/ui/index.html"))
uiBody := framework.ReadAllAndClose(t, uiResp)
if uiResp.StatusCode != http.StatusOK {
t.Fatalf("expected /ui/index.html code 200, got %d, body: %s", uiResp.StatusCode, string(uiBody))
}
if !strings.Contains(strings.ToLower(string(uiBody)), "volume") {
t.Fatalf("ui page does not look like volume status page")
}
}
func TestOptionsMethodsByPort(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P2())
client := framework.NewHTTPClient()
adminResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodOptions, cluster.VolumeAdminURL()+"/"))
_ = framework.ReadAllAndClose(t, adminResp)
if adminResp.StatusCode != http.StatusOK {
t.Fatalf("admin OPTIONS expected 200, got %d", adminResp.StatusCode)
}
adminAllowed := adminResp.Header.Get("Access-Control-Allow-Methods")
for _, expected := range []string{"PUT", "POST", "GET", "DELETE", "OPTIONS"} {
if !strings.Contains(adminAllowed, expected) {
t.Fatalf("admin allow methods missing %q, got %q", expected, adminAllowed)
}
}
if adminResp.Header.Get("Access-Control-Allow-Headers") != "*" {
t.Fatalf("admin allow headers expected '*', got %q", adminResp.Header.Get("Access-Control-Allow-Headers"))
}
publicResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodOptions, cluster.VolumePublicURL()+"/"))
_ = framework.ReadAllAndClose(t, publicResp)
if publicResp.StatusCode != http.StatusOK {
t.Fatalf("public OPTIONS expected 200, got %d", publicResp.StatusCode)
}
publicAllowed := publicResp.Header.Get("Access-Control-Allow-Methods")
if !strings.Contains(publicAllowed, "GET") || !strings.Contains(publicAllowed, "OPTIONS") {
t.Fatalf("public allow methods expected GET and OPTIONS, got %q", publicAllowed)
}
if strings.Contains(publicAllowed, "POST") {
t.Fatalf("public allow methods should not include POST, got %q", publicAllowed)
}
if publicResp.Header.Get("Access-Control-Allow-Headers") != "*" {
t.Fatalf("public allow headers expected '*', got %q", publicResp.Header.Get("Access-Control-Allow-Headers"))
}
}
func TestOptionsWithOriginIncludesCorsHeaders(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P2())
client := framework.NewHTTPClient()
adminReq := mustNewRequest(t, http.MethodOptions, cluster.VolumeAdminURL()+"/")
adminReq.Header.Set("Origin", "https://example.com")
adminResp := framework.DoRequest(t, client, adminReq)
_ = framework.ReadAllAndClose(t, adminResp)
if adminResp.StatusCode != http.StatusOK {
t.Fatalf("admin OPTIONS expected 200, got %d", adminResp.StatusCode)
}
if adminResp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatalf("admin OPTIONS expected Access-Control-Allow-Origin=*, got %q", adminResp.Header.Get("Access-Control-Allow-Origin"))
}
if adminResp.Header.Get("Access-Control-Allow-Credentials") != "true" {
t.Fatalf("admin OPTIONS expected Access-Control-Allow-Credentials=true, got %q", adminResp.Header.Get("Access-Control-Allow-Credentials"))
}
publicReq := mustNewRequest(t, http.MethodOptions, cluster.VolumePublicURL()+"/")
publicReq.Header.Set("Origin", "https://example.com")
publicResp := framework.DoRequest(t, client, publicReq)
_ = framework.ReadAllAndClose(t, publicResp)
if publicResp.StatusCode != http.StatusOK {
t.Fatalf("public OPTIONS expected 200, got %d", publicResp.StatusCode)
}
if publicResp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatalf("public OPTIONS expected Access-Control-Allow-Origin=*, got %q", publicResp.Header.Get("Access-Control-Allow-Origin"))
}
if publicResp.Header.Get("Access-Control-Allow-Credentials") != "true" {
t.Fatalf("public OPTIONS expected Access-Control-Allow-Credentials=true, got %q", publicResp.Header.Get("Access-Control-Allow-Credentials"))
}
}
func TestUiIndexNotExposedWhenJwtSigningEnabled(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P3())
client := framework.NewHTTPClient()
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, cluster.VolumeAdminURL()+"/ui/index.html"))
body := framework.ReadAllAndClose(t, resp)
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("expected /ui/index.html to be gated by auth under JWT profile (401), got %d body=%s", resp.StatusCode, string(body))
}
}
func mustNewRequest(t testing.TB, method, url string) *http.Request {
t.Helper()
req, err := http.NewRequest(method, url, nil)
if err != nil {
t.Fatalf("create request %s %s: %v", method, url, err)
}
return req
}
-419
View File
@@ -1,419 +0,0 @@
package volume_server_http_test
import (
"bytes"
"net/http"
"testing"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/security"
)
func TestJWTAuthForWriteAndRead(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P3()
clusterHarness := framework.StartSingleVolumeCluster(t, profile)
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(51)
const needleID = uint64(123456)
const cookie = uint32(0xABCDEF12)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
payload := []byte("jwt-protected-content")
client := framework.NewHTTPClient()
unauthWrite := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
unauthWriteResp := framework.DoRequest(t, client, unauthWrite)
_ = framework.ReadAllAndClose(t, unauthWriteResp)
if unauthWriteResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("unauthorized write expected 401, got %d", unauthWriteResp.StatusCode)
}
invalidWrite := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
invalidWrite.Header.Set("Authorization", "Bearer invalid")
invalidWriteResp := framework.DoRequest(t, client, invalidWrite)
_ = framework.ReadAllAndClose(t, invalidWriteResp)
if invalidWriteResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("invalid write token expected 401, got %d", invalidWriteResp.StatusCode)
}
writeToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, fid)
authWrite := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
authWrite.Header.Set("Authorization", "Bearer "+string(writeToken))
authWriteResp := framework.DoRequest(t, client, authWrite)
_ = framework.ReadAllAndClose(t, authWriteResp)
if authWriteResp.StatusCode != http.StatusCreated {
t.Fatalf("authorized write expected 201, got %d", authWriteResp.StatusCode)
}
unauthReadReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
unauthReadResp := framework.DoRequest(t, client, unauthReadReq)
_ = framework.ReadAllAndClose(t, unauthReadResp)
if unauthReadResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("unauthorized read expected 401, got %d", unauthReadResp.StatusCode)
}
readToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, fid)
authReadReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
authReadReq.Header.Set("Authorization", "Bearer "+string(readToken))
authReadResp := framework.DoRequest(t, client, authReadReq)
authReadBody := framework.ReadAllAndClose(t, authReadResp)
if authReadResp.StatusCode != http.StatusOK {
t.Fatalf("authorized read expected 200, got %d", authReadResp.StatusCode)
}
if string(authReadBody) != string(payload) {
t.Fatalf("authorized read content mismatch: got %q want %q", string(authReadBody), string(payload))
}
}
func TestJWTAuthRejectsFidMismatch(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P3()
clusterHarness := framework.StartSingleVolumeCluster(t, profile)
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(52)
const needleID = uint64(223344)
const cookie = uint32(0x10203040)
const otherNeedleID = uint64(223345)
const otherCookie = uint32(0x50607080)
const wrongCookie = uint32(0x10203041)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
otherFid := framework.NewFileID(volumeID, otherNeedleID, otherCookie)
payload := []byte("jwt-fid-mismatch-content")
client := framework.NewHTTPClient()
writeTokenForOtherFid := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, otherFid)
mismatchedWrite := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
mismatchedWrite.Header.Set("Authorization", "Bearer "+string(writeTokenForOtherFid))
mismatchedWriteResp := framework.DoRequest(t, client, mismatchedWrite)
_ = framework.ReadAllAndClose(t, mismatchedWriteResp)
if mismatchedWriteResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("write with mismatched fid token expected 401, got %d", mismatchedWriteResp.StatusCode)
}
wrongCookieFid := framework.NewFileID(volumeID, needleID, wrongCookie)
writeTokenWrongCookie := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, wrongCookieFid)
wrongCookieWrite := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
wrongCookieWrite.Header.Set("Authorization", "Bearer "+string(writeTokenWrongCookie))
wrongCookieWriteResp := framework.DoRequest(t, client, wrongCookieWrite)
_ = framework.ReadAllAndClose(t, wrongCookieWriteResp)
if wrongCookieWriteResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("write with wrong-cookie fid token expected 401, got %d", wrongCookieWriteResp.StatusCode)
}
writeTokenForFid := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, fid)
validWrite := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
validWrite.Header.Set("Authorization", "Bearer "+string(writeTokenForFid))
validWriteResp := framework.DoRequest(t, client, validWrite)
_ = framework.ReadAllAndClose(t, validWriteResp)
if validWriteResp.StatusCode != http.StatusCreated {
t.Fatalf("authorized write expected 201, got %d", validWriteResp.StatusCode)
}
readTokenForOtherFid := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, otherFid)
mismatchedReadReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
mismatchedReadReq.Header.Set("Authorization", "Bearer "+string(readTokenForOtherFid))
mismatchedReadResp := framework.DoRequest(t, client, mismatchedReadReq)
_ = framework.ReadAllAndClose(t, mismatchedReadResp)
if mismatchedReadResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("read with mismatched fid token expected 401, got %d", mismatchedReadResp.StatusCode)
}
readTokenWrongCookie := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, wrongCookieFid)
wrongCookieReadReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
wrongCookieReadReq.Header.Set("Authorization", "Bearer "+string(readTokenWrongCookie))
wrongCookieReadResp := framework.DoRequest(t, client, wrongCookieReadReq)
_ = framework.ReadAllAndClose(t, wrongCookieReadResp)
if wrongCookieReadResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("read with wrong-cookie fid token expected 401, got %d", wrongCookieReadResp.StatusCode)
}
}
func newUploadRequest(t testing.TB, url string, payload []byte) *http.Request {
t.Helper()
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
t.Fatalf("create upload request %s: %v", url, err)
}
req.Header.Set("Content-Type", "application/octet-stream")
return req
}
func TestJWTAuthRejectsExpiredTokens(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P3()
clusterHarness := framework.StartSingleVolumeCluster(t, profile)
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(53)
const needleID = uint64(334455)
const cookie = uint32(0x22334455)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
payload := []byte("expired-token-content")
client := framework.NewHTTPClient()
expiredWriteToken := mustGenExpiredToken(t, []byte(profile.JWTSigningKey), fid)
writeReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
writeReq.Header.Set("Authorization", "Bearer "+expiredWriteToken)
writeResp := framework.DoRequest(t, client, writeReq)
_ = framework.ReadAllAndClose(t, writeResp)
if writeResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("expired write token expected 401, got %d", writeResp.StatusCode)
}
// Seed data with a valid token so read auth path can be exercised against existing content.
validWriteToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, fid)
validWriteReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
validWriteReq.Header.Set("Authorization", "Bearer "+string(validWriteToken))
validWriteResp := framework.DoRequest(t, client, validWriteReq)
_ = framework.ReadAllAndClose(t, validWriteResp)
if validWriteResp.StatusCode != http.StatusCreated {
t.Fatalf("valid write expected 201, got %d", validWriteResp.StatusCode)
}
expiredReadToken := mustGenExpiredToken(t, []byte(profile.JWTReadKey), fid)
readReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
readReq.Header.Set("Authorization", "Bearer "+expiredReadToken)
readResp := framework.DoRequest(t, client, readReq)
_ = framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("expired read token expected 401, got %d", readResp.StatusCode)
}
}
func TestJWTAuthViaQueryParamAndCookie(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P3()
clusterHarness := framework.StartSingleVolumeCluster(t, profile)
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(54)
const needleID = uint64(445566)
const cookie = uint32(0x31415926)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
payload := []byte("jwt-query-cookie-content")
client := framework.NewHTTPClient()
writeToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, fid)
writeReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid+"?jwt="+string(writeToken), payload)
writeResp := framework.DoRequest(t, client, writeReq)
_ = framework.ReadAllAndClose(t, writeResp)
if writeResp.StatusCode != http.StatusCreated {
t.Fatalf("query-jwt write expected 201, got %d", writeResp.StatusCode)
}
readToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, fid)
readReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
readReq.AddCookie(&http.Cookie{Name: "AT", Value: string(readToken)})
readResp := framework.DoRequest(t, client, readReq)
readBody := framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusOK {
t.Fatalf("cookie-jwt read expected 200, got %d", readResp.StatusCode)
}
if string(readBody) != string(payload) {
t.Fatalf("cookie-jwt read body mismatch: got %q want %q", string(readBody), string(payload))
}
}
func TestJWTTokenSourcePrecedenceQueryOverHeader(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P3()
clusterHarness := framework.StartSingleVolumeCluster(t, profile)
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(55)
const needleID = uint64(556677)
const cookie = uint32(0x99887766)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
otherFID := framework.NewFileID(volumeID, needleID+1, cookie+1)
payload := []byte("jwt-precedence-content")
client := framework.NewHTTPClient()
validWriteToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, fid)
invalidWriteQueryToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, otherFID)
writeReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid+"?jwt="+string(invalidWriteQueryToken), payload)
writeReq.Header.Set("Authorization", "Bearer "+string(validWriteToken))
writeResp := framework.DoRequest(t, client, writeReq)
_ = framework.ReadAllAndClose(t, writeResp)
if writeResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("query token should take precedence over header token for write, expected 401 got %d", writeResp.StatusCode)
}
// Seed data with valid write token, then exercise read precedence.
seedWriteReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
seedWriteReq.Header.Set("Authorization", "Bearer "+string(validWriteToken))
seedWriteResp := framework.DoRequest(t, client, seedWriteReq)
_ = framework.ReadAllAndClose(t, seedWriteResp)
if seedWriteResp.StatusCode != http.StatusCreated {
t.Fatalf("seed write expected 201, got %d", seedWriteResp.StatusCode)
}
validReadToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, fid)
invalidReadQueryToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, otherFID)
readReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid+"?jwt="+string(invalidReadQueryToken))
readReq.Header.Set("Authorization", "Bearer "+string(validReadToken))
readResp := framework.DoRequest(t, client, readReq)
_ = framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("query token should take precedence over header token for read, expected 401 got %d", readResp.StatusCode)
}
}
func TestJWTTokenSourcePrecedenceHeaderOverCookie(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P3()
clusterHarness := framework.StartSingleVolumeCluster(t, profile)
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(56)
const needleID = uint64(667788)
const cookie = uint32(0x11229988)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
otherFID := framework.NewFileID(volumeID, needleID+1, cookie+1)
payload := []byte("jwt-precedence-header-cookie")
client := framework.NewHTTPClient()
validWriteToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, fid)
invalidCookieWriteToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, otherFID)
writeReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
writeReq.Header.Set("Authorization", "Bearer "+string(validWriteToken))
writeReq.AddCookie(&http.Cookie{Name: "AT", Value: string(invalidCookieWriteToken)})
writeResp := framework.DoRequest(t, client, writeReq)
_ = framework.ReadAllAndClose(t, writeResp)
if writeResp.StatusCode != http.StatusCreated {
t.Fatalf("header token should take precedence over cookie token for write, expected 201 got %d", writeResp.StatusCode)
}
validReadToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, fid)
invalidCookieReadToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, otherFID)
readReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
readReq.Header.Set("Authorization", "Bearer "+string(validReadToken))
readReq.AddCookie(&http.Cookie{Name: "AT", Value: string(invalidCookieReadToken)})
readResp := framework.DoRequest(t, client, readReq)
readBody := framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusOK {
t.Fatalf("header token should take precedence over cookie token for read, expected 200 got %d", readResp.StatusCode)
}
if string(readBody) != string(payload) {
t.Fatalf("header-over-cookie read body mismatch: got %q want %q", string(readBody), string(payload))
}
}
func TestJWTTokenSourcePrecedenceQueryOverCookie(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P3()
clusterHarness := framework.StartSingleVolumeCluster(t, profile)
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(57)
const needleID = uint64(778899)
const cookie = uint32(0x88776655)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, needleID, cookie)
otherFID := framework.NewFileID(volumeID, needleID+1, cookie+1)
payload := []byte("jwt-precedence-query-cookie")
client := framework.NewHTTPClient()
validWriteToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, fid)
invalidQueryWriteToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTSigningKey)), 60, otherFID)
writeReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid+"?jwt="+string(invalidQueryWriteToken), payload)
writeReq.AddCookie(&http.Cookie{Name: "AT", Value: string(validWriteToken)})
writeResp := framework.DoRequest(t, client, writeReq)
_ = framework.ReadAllAndClose(t, writeResp)
if writeResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("query token should take precedence over cookie token for write, expected 401 got %d", writeResp.StatusCode)
}
// Seed data with valid write token so read precedence can be exercised.
seedWriteReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
seedWriteReq.Header.Set("Authorization", "Bearer "+string(validWriteToken))
seedWriteResp := framework.DoRequest(t, client, seedWriteReq)
_ = framework.ReadAllAndClose(t, seedWriteResp)
if seedWriteResp.StatusCode != http.StatusCreated {
t.Fatalf("seed write expected 201, got %d", seedWriteResp.StatusCode)
}
validReadToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, fid)
invalidQueryReadToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, otherFID)
readReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid+"?jwt="+string(invalidQueryReadToken))
readReq.AddCookie(&http.Cookie{Name: "AT", Value: string(validReadToken)})
readResp := framework.DoRequest(t, client, readReq)
_ = framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusUnauthorized {
t.Fatalf("query token should take precedence over cookie token for read, expected 401 got %d", readResp.StatusCode)
}
// Validate positive path: valid query token should succeed even if cookie token is invalid.
validQueryReadReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid+"?jwt="+string(validReadToken))
invalidCookieReadToken := security.GenJwtForVolumeServer(security.SigningKey([]byte(profile.JWTReadKey)), 60, otherFID)
validQueryReadReq.AddCookie(&http.Cookie{Name: "AT", Value: string(invalidCookieReadToken)})
validQueryReadResp := framework.DoRequest(t, client, validQueryReadReq)
validQueryReadBody := framework.ReadAllAndClose(t, validQueryReadResp)
if validQueryReadResp.StatusCode != http.StatusOK {
t.Fatalf("valid query token should succeed over invalid cookie token, expected 200 got %d", validQueryReadResp.StatusCode)
}
if string(validQueryReadBody) != string(payload) {
t.Fatalf("query-over-cookie read body mismatch: got %q want %q", string(validQueryReadBody), string(payload))
}
}
func mustGenExpiredToken(t testing.TB, key []byte, fid string) string {
t.Helper()
claims := security.SeaweedFileIdClaims{
Fid: fid,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString(key)
if err != nil {
t.Fatalf("sign expired token: %v", err)
}
return signed
}
@@ -1,232 +0,0 @@
package volume_server_http_test
import (
"bytes"
"encoding/json"
"net/http"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/operation"
)
func TestChunkManifestExpansionAndBypass(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(102)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
chunkFID := framework.NewFileID(volumeID, 772005, 0x5E6F7081)
chunkPayload := []byte("chunk-manifest-expanded-content")
chunkUploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), chunkFID, chunkPayload)
_ = framework.ReadAllAndClose(t, chunkUploadResp)
if chunkUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("chunk upload expected 201, got %d", chunkUploadResp.StatusCode)
}
manifest := &operation.ChunkManifest{
Name: "manifest.bin",
Mime: "application/octet-stream",
Size: int64(len(chunkPayload)),
Chunks: []*operation.ChunkInfo{
{
Fid: chunkFID,
Offset: 0,
Size: int64(len(chunkPayload)),
},
},
}
manifestBytes, err := json.Marshal(manifest)
if err != nil {
t.Fatalf("marshal chunk manifest: %v", err)
}
manifestFID := framework.NewFileID(volumeID, 772006, 0x6F708192)
manifestUploadReq, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+manifestFID+"?cm=true", bytes.NewReader(manifestBytes))
if err != nil {
t.Fatalf("create manifest upload request: %v", err)
}
manifestUploadReq.Header.Set("Content-Type", "application/json")
manifestUploadResp := framework.DoRequest(t, client, manifestUploadReq)
_ = framework.ReadAllAndClose(t, manifestUploadResp)
if manifestUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("manifest upload expected 201, got %d", manifestUploadResp.StatusCode)
}
expandedReadResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), manifestFID)
expandedReadBody := framework.ReadAllAndClose(t, expandedReadResp)
if expandedReadResp.StatusCode != http.StatusOK {
t.Fatalf("manifest expanded read expected 200, got %d", expandedReadResp.StatusCode)
}
if string(expandedReadBody) != string(chunkPayload) {
t.Fatalf("manifest expanded read mismatch: got %q want %q", string(expandedReadBody), string(chunkPayload))
}
if expandedReadResp.Header.Get("X-File-Store") != "chunked" {
t.Fatalf("manifest expanded read expected X-File-Store=chunked, got %q", expandedReadResp.Header.Get("X-File-Store"))
}
bypassReadResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+manifestFID+"?cm=false"))
bypassReadBody := framework.ReadAllAndClose(t, bypassReadResp)
if bypassReadResp.StatusCode != http.StatusOK {
t.Fatalf("manifest bypass read expected 200, got %d", bypassReadResp.StatusCode)
}
if bypassReadResp.Header.Get("X-File-Store") != "" {
t.Fatalf("manifest bypass read expected empty X-File-Store header, got %q", bypassReadResp.Header.Get("X-File-Store"))
}
var gotManifest operation.ChunkManifest
if err = json.Unmarshal(bypassReadBody, &gotManifest); err != nil {
t.Fatalf("manifest bypass read expected JSON payload, got decode error: %v body=%q", err, string(bypassReadBody))
}
if len(gotManifest.Chunks) != 1 || gotManifest.Chunks[0].Fid != chunkFID {
t.Fatalf("manifest bypass read payload mismatch: %+v", gotManifest)
}
}
func TestChunkManifestDeleteRemovesChildChunks(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(104)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
chunkFID := framework.NewFileID(volumeID, 772008, 0x8192A3B4)
chunkPayload := []byte("chunk-manifest-delete-content")
chunkUploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), chunkFID, chunkPayload)
_ = framework.ReadAllAndClose(t, chunkUploadResp)
if chunkUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("chunk upload expected 201, got %d", chunkUploadResp.StatusCode)
}
manifest := &operation.ChunkManifest{
Name: "manifest-delete.bin",
Mime: "application/octet-stream",
Size: int64(len(chunkPayload)),
Chunks: []*operation.ChunkInfo{
{
Fid: chunkFID,
Offset: 0,
Size: int64(len(chunkPayload)),
},
},
}
manifestBytes, err := json.Marshal(manifest)
if err != nil {
t.Fatalf("marshal chunk manifest: %v", err)
}
manifestFID := framework.NewFileID(volumeID, 772009, 0x92A3B4C5)
manifestUploadReq, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+manifestFID+"?cm=true", bytes.NewReader(manifestBytes))
if err != nil {
t.Fatalf("create manifest upload request: %v", err)
}
manifestUploadReq.Header.Set("Content-Type", "application/json")
manifestUploadResp := framework.DoRequest(t, client, manifestUploadReq)
_ = framework.ReadAllAndClose(t, manifestUploadResp)
if manifestUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("manifest upload expected 201, got %d", manifestUploadResp.StatusCode)
}
deleteResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL()+"/"+manifestFID))
deleteBody := framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusAccepted {
t.Fatalf("manifest delete expected 202, got %d", deleteResp.StatusCode)
}
var deleteResult map[string]int64
if err = json.Unmarshal(deleteBody, &deleteResult); err != nil {
t.Fatalf("decode manifest delete response: %v body=%q", err, string(deleteBody))
}
if deleteResult["size"] != int64(len(chunkPayload)) {
t.Fatalf("manifest delete expected size=%d, got %d", len(chunkPayload), deleteResult["size"])
}
manifestReadAfterDelete := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), manifestFID)
_ = framework.ReadAllAndClose(t, manifestReadAfterDelete)
if manifestReadAfterDelete.StatusCode != http.StatusNotFound {
t.Fatalf("manifest read after delete expected 404, got %d", manifestReadAfterDelete.StatusCode)
}
chunkReadAfterDelete := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), chunkFID)
_ = framework.ReadAllAndClose(t, chunkReadAfterDelete)
if chunkReadAfterDelete.StatusCode != http.StatusNotFound {
t.Fatalf("chunk read after manifest delete expected 404, got %d", chunkReadAfterDelete.StatusCode)
}
}
func TestChunkManifestDeleteFailsWhenChildDeletionFails(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(105)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
manifest := &operation.ChunkManifest{
Name: "manifest-delete-failure.bin",
Mime: "application/octet-stream",
Size: 1,
Chunks: []*operation.ChunkInfo{
{
Fid: "not-a-valid-fid",
Offset: 0,
Size: 1,
},
},
}
manifestBytes, err := json.Marshal(manifest)
if err != nil {
t.Fatalf("marshal chunk manifest: %v", err)
}
manifestFID := framework.NewFileID(volumeID, 772010, 0xA3B4C5D6)
manifestUploadReq, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+manifestFID+"?cm=true", bytes.NewReader(manifestBytes))
if err != nil {
t.Fatalf("create manifest upload request: %v", err)
}
manifestUploadReq.Header.Set("Content-Type", "application/json")
manifestUploadResp := framework.DoRequest(t, client, manifestUploadReq)
_ = framework.ReadAllAndClose(t, manifestUploadResp)
if manifestUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("manifest upload expected 201, got %d", manifestUploadResp.StatusCode)
}
deleteResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL()+"/"+manifestFID))
deleteBody := framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusInternalServerError {
t.Fatalf("manifest delete with invalid child fid expected 500, got %d body=%q", deleteResp.StatusCode, string(deleteBody))
}
manifestBypassRead := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+manifestFID+"?cm=false"))
manifestBypassBody := framework.ReadAllAndClose(t, manifestBypassRead)
if manifestBypassRead.StatusCode != http.StatusOK {
t.Fatalf("manifest bypass read after failed delete expected 200, got %d", manifestBypassRead.StatusCode)
}
var gotManifest operation.ChunkManifest
if err = json.Unmarshal(manifestBypassBody, &gotManifest); err != nil {
t.Fatalf("manifest bypass read expected JSON payload, got decode error: %v body=%q", err, string(manifestBypassBody))
}
if len(gotManifest.Chunks) != 1 || gotManifest.Chunks[0].Fid != "not-a-valid-fid" {
t.Fatalf("manifest payload mismatch after failed delete: %+v", gotManifest)
}
}
@@ -1,97 +0,0 @@
package volume_server_http_test
import (
"bytes"
"compress/gzip"
"io"
"net/http"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func gzipData(t testing.TB, data []byte) []byte {
t.Helper()
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
if _, err := zw.Write(data); err != nil {
t.Fatalf("gzip write: %v", err)
}
if err := zw.Close(); err != nil {
t.Fatalf("gzip close: %v", err)
}
return buf.Bytes()
}
func gunzipData(t testing.TB, data []byte) []byte {
t.Helper()
zr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
t.Fatalf("gunzip new reader: %v", err)
}
defer zr.Close()
out, err := io.ReadAll(zr)
if err != nil {
t.Fatalf("gunzip read: %v", err)
}
return out
}
func TestCompressedReadAcceptEncodingMatrix(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(103)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 772007, 0x708192A3)
plainPayload := []byte("compressed-read-accept-encoding-matrix-content-compressed-read-accept-encoding-matrix-content")
compressedPayload := gzipData(t, plainPayload)
uploadReq, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+fid, bytes.NewReader(compressedPayload))
if err != nil {
t.Fatalf("create compressed upload request: %v", err)
}
uploadReq.Header.Set("Content-Type", "text/plain")
uploadReq.Header.Set("Content-Encoding", "gzip")
uploadResp := framework.DoRequest(t, client, uploadReq)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("compressed upload expected 201, got %d", uploadResp.StatusCode)
}
gzipReadReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
gzipReadReq.Header.Set("Accept-Encoding", "gzip")
gzipReadResp := framework.DoRequest(t, client, gzipReadReq)
gzipReadBody := framework.ReadAllAndClose(t, gzipReadResp)
if gzipReadResp.StatusCode != http.StatusOK {
t.Fatalf("gzip-accepted read expected 200, got %d", gzipReadResp.StatusCode)
}
if gzipReadResp.Header.Get("Content-Encoding") != "gzip" {
t.Fatalf("gzip-accepted read expected Content-Encoding=gzip, got %q", gzipReadResp.Header.Get("Content-Encoding"))
}
if string(gunzipData(t, gzipReadBody)) != string(plainPayload) {
t.Fatalf("gzip-accepted read body mismatch after gunzip")
}
identityReadReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
identityReadReq.Header.Set("Accept-Encoding", "identity")
identityReadResp := framework.DoRequest(t, client, identityReadReq)
identityReadBody := framework.ReadAllAndClose(t, identityReadResp)
if identityReadResp.StatusCode != http.StatusOK {
t.Fatalf("identity read expected 200, got %d", identityReadResp.StatusCode)
}
if identityReadResp.Header.Get("Content-Encoding") != "" {
t.Fatalf("identity read expected no Content-Encoding header, got %q", identityReadResp.Header.Get("Content-Encoding"))
}
if string(identityReadBody) != string(plainPayload) {
t.Fatalf("identity read body mismatch: got %q want %q", string(identityReadBody), string(plainPayload))
}
}
@@ -1,102 +0,0 @@
package volume_server_http_test
import (
"fmt"
"net/http"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestReadPassthroughHeadersAndDownloadDisposition(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(96)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fullFileID := framework.NewFileID(volumeID, 661122, 0x55667788)
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fullFileID, []byte("passthrough-header-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
parts := strings.SplitN(fullFileID, ",", 2)
if len(parts) != 2 {
t.Fatalf("unexpected file id format: %q", fullFileID)
}
fidOnly := parts[1]
url := fmt.Sprintf("%s/%d/%s/%s?response-content-type=text/plain&response-cache-control=no-store&dl=true",
clusterHarness.VolumeAdminURL(),
volumeID,
fidOnly,
"report.txt",
)
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, url))
_ = framework.ReadAllAndClose(t, resp)
if resp.StatusCode != http.StatusOK {
t.Fatalf("passthrough read expected 200, got %d", resp.StatusCode)
}
if resp.Header.Get("Content-Type") != "text/plain" {
t.Fatalf("response-content-type override mismatch: %q", resp.Header.Get("Content-Type"))
}
if resp.Header.Get("Cache-Control") != "no-store" {
t.Fatalf("response-cache-control override mismatch: %q", resp.Header.Get("Cache-Control"))
}
contentDisposition := resp.Header.Get("Content-Disposition")
if !strings.Contains(contentDisposition, "attachment") || !strings.Contains(contentDisposition, "report.txt") {
t.Fatalf("download disposition header mismatch: %q", contentDisposition)
}
}
func TestStaticAssetEndpoints(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
client := framework.NewHTTPClient()
faviconResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/favicon.ico"))
_ = framework.ReadAllAndClose(t, faviconResp)
if faviconResp.StatusCode != http.StatusOK {
t.Fatalf("/favicon.ico expected 200, got %d", faviconResp.StatusCode)
}
staticResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/seaweedfsstatic/seaweed50x50.png"))
_ = framework.ReadAllAndClose(t, staticResp)
if staticResp.StatusCode != http.StatusOK {
t.Fatalf("/seaweedfsstatic/seaweed50x50.png expected 200, got %d", staticResp.StatusCode)
}
}
func TestStaticAssetEndpointsOnPublicPort(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P2())
client := framework.NewHTTPClient()
faviconResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumePublicURL()+"/favicon.ico"))
_ = framework.ReadAllAndClose(t, faviconResp)
if faviconResp.StatusCode != http.StatusOK {
t.Fatalf("public /favicon.ico expected 200, got %d", faviconResp.StatusCode)
}
staticResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumePublicURL()+"/seaweedfsstatic/seaweed50x50.png"))
_ = framework.ReadAllAndClose(t, staticResp)
if staticResp.StatusCode != http.StatusOK {
t.Fatalf("public /seaweedfsstatic/seaweed50x50.png expected 200, got %d", staticResp.StatusCode)
}
}
@@ -1,92 +0,0 @@
package volume_server_http_test
import (
"bytes"
"fmt"
"image"
"image/color"
"image/png"
"net/http"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func makePNGFixture(t testing.TB, width, height int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
img.Set(x, y, color.RGBA{R: uint8(x * 20), G: uint8(y * 20), B: 200, A: 255})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("encode png fixture: %v", err)
}
return buf.Bytes()
}
func decodeImageConfig(t testing.TB, data []byte) image.Config {
t.Helper()
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
t.Fatalf("decode image config: %v", err)
}
return cfg
}
func TestImageResizeAndCropReadVariants(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(101)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fullFileID := framework.NewFileID(volumeID, 772004, 0x4D5E6F70)
uploadReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fullFileID, makePNGFixture(t, 6, 4))
uploadReq.Header.Set("Content-Type", "image/png")
uploadResp := framework.DoRequest(t, client, uploadReq)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("image upload expected 201, got %d", uploadResp.StatusCode)
}
parts := strings.SplitN(fullFileID, ",", 2)
if len(parts) != 2 {
t.Fatalf("unexpected file id format: %q", fullFileID)
}
fidOnly := parts[1]
resizeURL := fmt.Sprintf("%s/%d/%s/%s?width=2&height=1", clusterHarness.VolumeAdminURL(), volumeID, fidOnly, "fixture.png")
resizeResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, resizeURL))
resizeBody := framework.ReadAllAndClose(t, resizeResp)
if resizeResp.StatusCode != http.StatusOK {
t.Fatalf("image resize read expected 200, got %d", resizeResp.StatusCode)
}
resizeCfg := decodeImageConfig(t, resizeBody)
if resizeCfg.Width > 2 || resizeCfg.Height > 1 {
t.Fatalf("image resize expected dimensions <= 2x1, got %dx%d", resizeCfg.Width, resizeCfg.Height)
}
cropURL := fmt.Sprintf("%s/%d/%s/%s?crop_x1=1&crop_y1=1&crop_x2=4&crop_y2=3", clusterHarness.VolumeAdminURL(), volumeID, fidOnly, "fixture.png")
cropResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, cropURL))
cropBody := framework.ReadAllAndClose(t, cropResp)
if cropResp.StatusCode != http.StatusOK {
t.Fatalf("image crop read expected 200, got %d", cropResp.StatusCode)
}
cropCfg := decodeImageConfig(t, cropBody)
if cropCfg.Width != 3 || cropCfg.Height != 2 {
t.Fatalf("image crop expected 3x2, got %dx%d", cropCfg.Width, cropCfg.Height)
}
}
@@ -1,287 +0,0 @@
package volume_server_http_test
import (
"bytes"
"net/http"
"strconv"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestPublicPortReadOnlyMethodBehavior(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P2())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(81)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 123321, 0x01020304)
originalData := []byte("public-port-original")
replacementData := []byte("public-port-replacement")
client := framework.NewHTTPClient()
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, originalData)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("admin upload expected 201, got %d", uploadResp.StatusCode)
}
publicReadResp := framework.ReadBytes(t, client, clusterHarness.VolumePublicURL(), fid)
publicReadBody := framework.ReadAllAndClose(t, publicReadResp)
if publicReadResp.StatusCode != http.StatusOK {
t.Fatalf("public GET expected 200, got %d", publicReadResp.StatusCode)
}
if string(publicReadBody) != string(originalData) {
t.Fatalf("public GET body mismatch: got %q want %q", string(publicReadBody), string(originalData))
}
publicPostReq := newUploadRequest(t, clusterHarness.VolumePublicURL()+"/"+fid, replacementData)
publicPostResp := framework.DoRequest(t, client, publicPostReq)
_ = framework.ReadAllAndClose(t, publicPostResp)
if publicPostResp.StatusCode != http.StatusOK {
t.Fatalf("public POST expected passthrough 200, got %d", publicPostResp.StatusCode)
}
publicDeleteResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumePublicURL()+"/"+fid))
_ = framework.ReadAllAndClose(t, publicDeleteResp)
if publicDeleteResp.StatusCode != http.StatusOK {
t.Fatalf("public DELETE expected passthrough 200, got %d", publicDeleteResp.StatusCode)
}
adminReadResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), fid)
adminReadBody := framework.ReadAllAndClose(t, adminReadResp)
if adminReadResp.StatusCode != http.StatusOK {
t.Fatalf("admin GET after public POST/DELETE expected 200, got %d", adminReadResp.StatusCode)
}
if string(adminReadBody) != string(originalData) {
t.Fatalf("public port should not mutate data: got %q want %q", string(adminReadBody), string(originalData))
}
}
func TestCorsAndUnsupportedMethodBehavior(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P2())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(82)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 789789, 0x0A0B0C0D)
client := framework.NewHTTPClient()
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("cors-check"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("admin upload expected 201, got %d", uploadResp.StatusCode)
}
adminOriginReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
adminOriginReq.Header.Set("Origin", "https://example.com")
adminOriginResp := framework.DoRequest(t, client, adminOriginReq)
_ = framework.ReadAllAndClose(t, adminOriginResp)
if adminOriginResp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatalf("admin GET origin header mismatch: %q", adminOriginResp.Header.Get("Access-Control-Allow-Origin"))
}
if adminOriginResp.Header.Get("Access-Control-Allow-Credentials") != "true" {
t.Fatalf("admin GET credentials header mismatch: %q", adminOriginResp.Header.Get("Access-Control-Allow-Credentials"))
}
publicOriginReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumePublicURL()+"/"+fid)
publicOriginReq.Header.Set("Origin", "https://example.com")
publicOriginResp := framework.DoRequest(t, client, publicOriginReq)
_ = framework.ReadAllAndClose(t, publicOriginResp)
if publicOriginResp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatalf("public GET origin header mismatch: %q", publicOriginResp.Header.Get("Access-Control-Allow-Origin"))
}
if publicOriginResp.Header.Get("Access-Control-Allow-Credentials") != "true" {
t.Fatalf("public GET credentials header mismatch: %q", publicOriginResp.Header.Get("Access-Control-Allow-Credentials"))
}
adminPatchReq, err := http.NewRequest(http.MethodPatch, clusterHarness.VolumeAdminURL()+"/"+fid, bytes.NewReader([]byte("patch")))
if err != nil {
t.Fatalf("create admin PATCH request: %v", err)
}
adminPatchResp := framework.DoRequest(t, client, adminPatchReq)
_ = framework.ReadAllAndClose(t, adminPatchResp)
if adminPatchResp.StatusCode != http.StatusBadRequest {
t.Fatalf("admin PATCH expected 400, got %d", adminPatchResp.StatusCode)
}
publicPatchReq, err := http.NewRequest(http.MethodPatch, clusterHarness.VolumePublicURL()+"/"+fid, bytes.NewReader([]byte("patch")))
if err != nil {
t.Fatalf("create public PATCH request: %v", err)
}
publicPatchResp := framework.DoRequest(t, client, publicPatchReq)
_ = framework.ReadAllAndClose(t, publicPatchResp)
if publicPatchResp.StatusCode != http.StatusOK {
t.Fatalf("public PATCH expected passthrough 200, got %d", publicPatchResp.StatusCode)
}
}
func TestUnsupportedMethodTraceParity(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P2())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(83)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 123999, 0x01010101)
client := framework.NewHTTPClient()
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("trace-method-check"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
adminTraceReq := mustNewRequest(t, http.MethodTrace, clusterHarness.VolumeAdminURL()+"/"+fid)
adminTraceResp := framework.DoRequest(t, client, adminTraceReq)
_ = framework.ReadAllAndClose(t, adminTraceResp)
if adminTraceResp.StatusCode != http.StatusBadRequest {
t.Fatalf("admin TRACE expected 400, got %d", adminTraceResp.StatusCode)
}
publicTraceReq := mustNewRequest(t, http.MethodTrace, clusterHarness.VolumePublicURL()+"/"+fid)
publicTraceResp := framework.DoRequest(t, client, publicTraceReq)
_ = framework.ReadAllAndClose(t, publicTraceResp)
if publicTraceResp.StatusCode != http.StatusOK {
t.Fatalf("public TRACE expected passthrough 200, got %d", publicTraceResp.StatusCode)
}
}
func TestUnsupportedMethodPropfindParity(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P2())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(84)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 124000, 0x02020202)
client := framework.NewHTTPClient()
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("propfind-method-check"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
adminReq := mustNewRequest(t, "PROPFIND", clusterHarness.VolumeAdminURL()+"/"+fid)
adminResp := framework.DoRequest(t, client, adminReq)
_ = framework.ReadAllAndClose(t, adminResp)
if adminResp.StatusCode != http.StatusBadRequest {
t.Fatalf("admin PROPFIND expected 400, got %d", adminResp.StatusCode)
}
publicReq := mustNewRequest(t, "PROPFIND", clusterHarness.VolumePublicURL()+"/"+fid)
publicResp := framework.DoRequest(t, client, publicReq)
_ = framework.ReadAllAndClose(t, publicResp)
if publicResp.StatusCode != http.StatusOK {
t.Fatalf("public PROPFIND expected passthrough 200, got %d", publicResp.StatusCode)
}
verifyResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), fid)
verifyBody := framework.ReadAllAndClose(t, verifyResp)
if verifyResp.StatusCode != http.StatusOK {
t.Fatalf("verify GET expected 200, got %d", verifyResp.StatusCode)
}
if string(verifyBody) != "propfind-method-check" {
t.Fatalf("PROPFIND should not mutate data, got %q", string(verifyBody))
}
}
func TestUnsupportedMethodConnectParity(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P2())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(85)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 124001, 0x03030303)
client := framework.NewHTTPClient()
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("connect-method-check"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
adminReq := mustNewRequest(t, "CONNECT", clusterHarness.VolumeAdminURL()+"/"+fid)
adminResp := framework.DoRequest(t, client, adminReq)
_ = framework.ReadAllAndClose(t, adminResp)
if adminResp.StatusCode != http.StatusBadRequest {
t.Fatalf("admin CONNECT expected 400, got %d", adminResp.StatusCode)
}
publicReq := mustNewRequest(t, "CONNECT", clusterHarness.VolumePublicURL()+"/"+fid)
publicResp := framework.DoRequest(t, client, publicReq)
_ = framework.ReadAllAndClose(t, publicResp)
if publicResp.StatusCode != http.StatusOK {
t.Fatalf("public CONNECT expected passthrough 200, got %d", publicResp.StatusCode)
}
verifyResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), fid)
verifyBody := framework.ReadAllAndClose(t, verifyResp)
if verifyResp.StatusCode != http.StatusOK {
t.Fatalf("verify GET expected 200, got %d", verifyResp.StatusCode)
}
if string(verifyBody) != "connect-method-check" {
t.Fatalf("CONNECT should not mutate data, got %q", string(verifyBody))
}
}
func TestPublicPortHeadReadParity(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P2())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(86)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 124002, 0x04040404)
payload := []byte("public-head-parity-content")
client := framework.NewHTTPClient()
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
headResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodHead, clusterHarness.VolumePublicURL()+"/"+fid))
headBody := framework.ReadAllAndClose(t, headResp)
if headResp.StatusCode != http.StatusOK {
t.Fatalf("public HEAD expected 200, got %d", headResp.StatusCode)
}
if got := headResp.Header.Get("Content-Length"); got != strconv.Itoa(len(payload)) {
t.Fatalf("public HEAD content-length mismatch: got %q want %d", got, len(payload))
}
if len(headBody) != 0 {
t.Fatalf("public HEAD body should be empty, got %d bytes", len(headBody))
}
}
@@ -1,82 +0,0 @@
package volume_server_http_test
import (
"net/http"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestMultiRangeReadReturnsMultipartPayload(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(97)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 771999, 0x0A1B2C3D)
payload := []byte("0123456789abcdef")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
multiRangeReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
multiRangeReq.Header.Set("Range", "bytes=0-1,4-5")
multiRangeResp := framework.DoRequest(t, client, multiRangeReq)
multiRangeBody := framework.ReadAllAndClose(t, multiRangeResp)
if multiRangeResp.StatusCode != http.StatusPartialContent {
t.Fatalf("multi-range expected 206, got %d", multiRangeResp.StatusCode)
}
if !strings.Contains(multiRangeResp.Header.Get("Content-Type"), "multipart/byteranges") {
t.Fatalf("multi-range content-type mismatch: %q", multiRangeResp.Header.Get("Content-Type"))
}
bodyText := string(multiRangeBody)
if !strings.Contains(bodyText, "01") || !strings.Contains(bodyText, "45") {
t.Fatalf("multi-range body missing expected segments: %q", bodyText)
}
}
func TestOversizedCombinedRangesAreIgnored(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(100)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 772003, 0x3C4D5E6F)
payload := []byte("0123456789abcdef")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
// Range bytes sum is 22 (> payload size 16), which exercises the oversized-range guard path.
oversizedRangeReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
oversizedRangeReq.Header.Set("Range", "bytes=0-10,5-15")
oversizedRangeResp := framework.DoRequest(t, client, oversizedRangeReq)
oversizedRangeBody := framework.ReadAllAndClose(t, oversizedRangeResp)
if oversizedRangeResp.StatusCode != http.StatusOK {
t.Fatalf("oversized combined range expected 200, got %d", oversizedRangeResp.StatusCode)
}
if len(oversizedRangeBody) != 0 {
t.Fatalf("oversized combined range expected empty body, got %d bytes", len(oversizedRangeBody))
}
}
@@ -1,54 +0,0 @@
package volume_server_http_test
import (
"net/http"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestReadDeletedQueryReturnsDeletedNeedleData(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(94)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 551234, 0xCAFE1234)
payload := []byte("read-deleted-needle-payload")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
deleteResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL()+"/"+fid))
_ = framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusAccepted {
t.Fatalf("delete expected 202, got %d", deleteResp.StatusCode)
}
normalRead := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), fid)
_ = framework.ReadAllAndClose(t, normalRead)
if normalRead.StatusCode != http.StatusNotFound {
t.Fatalf("normal read after delete expected 404, got %d", normalRead.StatusCode)
}
readDeletedReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid+"?readDeleted=true")
readDeletedResp := framework.DoRequest(t, client, readDeletedReq)
readDeletedBody := framework.ReadAllAndClose(t, readDeletedResp)
if readDeletedResp.StatusCode != http.StatusOK {
t.Fatalf("read with readDeleted=true expected 200, got %d", readDeletedResp.StatusCode)
}
if string(readDeletedBody) != string(payload) {
t.Fatalf("readDeleted body mismatch: got %q want %q", string(readDeletedBody), string(payload))
}
}
@@ -1,319 +0,0 @@
package volume_server_http_test
import (
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestReadModeProxyMissingLocalVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P1()
profile.ReadMode = "proxy"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
const volumeID = uint32(101)
framework.AllocateVolume(t, grpc0, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 120001, 0x0102ABCD)
payload := []byte("proxy-read-mode-forwarded-content")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
readURL := clusterHarness.VolumeAdminURL(1) + "/" + fid
var finalBody []byte
if !waitForHTTPStatus(t, client, readURL, http.StatusOK, 10*time.Second, func(resp *http.Response) {
finalBody = framework.ReadAllAndClose(t, resp)
}) {
t.Fatalf("proxy read mode did not return 200 from non-owning volume server within deadline")
}
if string(finalBody) != string(payload) {
t.Fatalf("proxy read mode body mismatch: got %q want %q", string(finalBody), string(payload))
}
}
func TestReadModeRedirectMissingLocalVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P1()
profile.ReadMode = "redirect"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
const volumeID = uint32(102)
framework.AllocateVolume(t, grpc0, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 120002, 0x0102DCBA)
payload := []byte("redirect-read-mode-content")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
noRedirectClient := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
readURL := clusterHarness.VolumeAdminURL(1) + "/" + fid
var redirectLocation string
if !waitForHTTPStatus(t, noRedirectClient, readURL, http.StatusMovedPermanently, 10*time.Second, func(resp *http.Response) {
redirectLocation = resp.Header.Get("Location")
_ = framework.ReadAllAndClose(t, resp)
}) {
t.Fatalf("redirect read mode did not return 301 from non-owning volume server within deadline")
}
if redirectLocation == "" {
t.Fatalf("redirect response missing Location header")
}
if !strings.Contains(redirectLocation, "proxied=true") {
t.Fatalf("redirect Location should include proxied=true, got %q", redirectLocation)
}
followResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, redirectLocation))
followBody := framework.ReadAllAndClose(t, followResp)
if followResp.StatusCode != http.StatusOK {
t.Fatalf("following redirect expected 200, got %d", followResp.StatusCode)
}
if string(followBody) != string(payload) {
t.Fatalf("redirect-follow body mismatch: got %q want %q", string(followBody), string(payload))
}
}
func TestReadModeLocalMissingLocalVolumeReturnsNotFound(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P1()
profile.ReadMode = "local"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
const volumeID = uint32(103)
framework.AllocateVolume(t, grpc0, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 120003, 0x0102BEEF)
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, []byte("local-read-mode-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
readResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(1), fid)
_ = framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusNotFound {
t.Fatalf("local read mode expected 404 on non-owning server, got %d", readResp.StatusCode)
}
}
func TestReadDeletedProxyModeOnMissingLocalVolume(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P1()
profile.ReadMode = "proxy"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
const volumeID = uint32(104)
framework.AllocateVolume(t, grpc0, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 120004, 0x0102CAFE)
payload := []byte("proxy-readDeleted-missing-local-content")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
deleteResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL(0)+"/"+fid))
_ = framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusAccepted {
t.Fatalf("delete expected 202, got %d", deleteResp.StatusCode)
}
readURL := clusterHarness.VolumeAdminURL(1) + "/" + fid + "?readDeleted=true"
var proxiedBody []byte
if !waitForHTTPStatus(t, client, readURL, http.StatusOK, 10*time.Second, func(resp *http.Response) {
proxiedBody = framework.ReadAllAndClose(t, resp)
}) {
t.Fatalf("proxy readDeleted path did not return 200 from non-owning volume server within deadline")
}
if string(proxiedBody) != string(payload) {
t.Fatalf("proxy readDeleted body mismatch: got %q want %q", string(proxiedBody), string(payload))
}
}
func TestReadDeletedRedirectModeDropsQueryParameterParity(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P1()
profile.ReadMode = "redirect"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
const volumeID = uint32(105)
framework.AllocateVolume(t, grpc0, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 120005, 0x0102FACE)
payload := []byte("redirect-readDeleted-query-drop-parity")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
deleteResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL(0)+"/"+fid))
_ = framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusAccepted {
t.Fatalf("delete expected 202, got %d", deleteResp.StatusCode)
}
noRedirectClient := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
redirectURL := clusterHarness.VolumeAdminURL(1) + "/" + fid + "?readDeleted=true"
var location string
if !waitForHTTPStatus(t, noRedirectClient, redirectURL, http.StatusMovedPermanently, 10*time.Second, func(resp *http.Response) {
location = resp.Header.Get("Location")
_ = framework.ReadAllAndClose(t, resp)
}) {
t.Fatalf("redirect readDeleted path did not return 301 from non-owning volume server within deadline")
}
if location == "" {
t.Fatalf("redirect readDeleted response missing Location header")
}
if !strings.Contains(location, "proxied=true") {
t.Fatalf("redirect readDeleted Location should include proxied=true, got %q", location)
}
if strings.Contains(location, "readDeleted=true") {
t.Fatalf("redirect readDeleted Location should reflect current query-drop behavior, got %q", location)
}
followResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, location))
_ = framework.ReadAllAndClose(t, followResp)
if followResp.StatusCode != http.StatusNotFound {
t.Fatalf("redirect-follow without readDeleted query expected 404 for deleted needle, got %d", followResp.StatusCode)
}
}
func TestReadModeRedirectPreservesCollectionQuery(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P1()
profile.ReadMode = "redirect"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
const volumeID = uint32(109)
const collection = "redirect-collection"
framework.AllocateVolume(t, grpc0, volumeID, collection)
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 120006, 0x0102F00D)
payload := []byte("redirect-collection-preserve-content")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
noRedirectClient := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
redirectURL := clusterHarness.VolumeAdminURL(1) + "/" + fid + "?collection=" + collection
var location string
if !waitForHTTPStatus(t, noRedirectClient, redirectURL, http.StatusMovedPermanently, 10*time.Second, func(resp *http.Response) {
location = resp.Header.Get("Location")
_ = framework.ReadAllAndClose(t, resp)
}) {
t.Fatalf("redirect collection path did not return 301 from non-owning volume server within deadline")
}
if location == "" {
t.Fatalf("redirect collection response missing Location header")
}
if !strings.Contains(location, "proxied=true") {
t.Fatalf("redirect collection Location should include proxied=true, got %q", location)
}
if !strings.Contains(location, "collection="+collection) {
t.Fatalf("redirect collection Location should preserve collection query, got %q", location)
}
followResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, location))
followBody := framework.ReadAllAndClose(t, followResp)
if followResp.StatusCode != http.StatusOK {
t.Fatalf("redirect-follow expected 200, got %d", followResp.StatusCode)
}
if string(followBody) != string(payload) {
t.Fatalf("redirect-follow body mismatch: got %q want %q", string(followBody), string(payload))
}
}
func waitForHTTPStatus(t testing.TB, client *http.Client, url string, expectedStatus int, timeout time.Duration, onMatch func(resp *http.Response)) bool {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, url))
if resp.StatusCode == expectedStatus {
onMatch(resp)
return true
}
_ = framework.ReadAllAndClose(t, resp)
time.Sleep(200 * time.Millisecond)
}
return false
}
@@ -1,191 +0,0 @@
package volume_server_http_test
import (
"fmt"
"net/http"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestReadPathShapesAndIfModifiedSince(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(93)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fullFileID := framework.NewFileID(volumeID, 771234, 0xBEEFCACE)
uploadPayload := []byte("read-path-shape-content")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fullFileID, uploadPayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
parts := strings.SplitN(fullFileID, ",", 2)
if len(parts) != 2 {
t.Fatalf("unexpected file id format: %q", fullFileID)
}
fidOnly := parts[1]
readByVidFid := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, fmt.Sprintf("%s/%d/%s", clusterHarness.VolumeAdminURL(), volumeID, fidOnly)))
readByVidFidBody := framework.ReadAllAndClose(t, readByVidFid)
if readByVidFid.StatusCode != http.StatusOK {
t.Fatalf("GET /{vid}/{fid} expected 200, got %d", readByVidFid.StatusCode)
}
if string(readByVidFidBody) != string(uploadPayload) {
t.Fatalf("GET /{vid}/{fid} body mismatch: got %q want %q", string(readByVidFidBody), string(uploadPayload))
}
readWithFilename := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, fmt.Sprintf("%s/%d/%s/%s", clusterHarness.VolumeAdminURL(), volumeID, fidOnly, "named.bin")))
readWithFilenameBody := framework.ReadAllAndClose(t, readWithFilename)
if readWithFilename.StatusCode != http.StatusOK {
t.Fatalf("GET /{vid}/{fid}/{filename} expected 200, got %d", readWithFilename.StatusCode)
}
if string(readWithFilenameBody) != string(uploadPayload) {
t.Fatalf("GET /{vid}/{fid}/{filename} body mismatch: got %q want %q", string(readWithFilenameBody), string(uploadPayload))
}
lastModified := readWithFilename.Header.Get("Last-Modified")
if lastModified == "" {
t.Fatalf("expected Last-Modified header on read response")
}
ifModifiedSinceReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fullFileID)
ifModifiedSinceReq.Header.Set("If-Modified-Since", lastModified)
ifModifiedSinceResp := framework.DoRequest(t, client, ifModifiedSinceReq)
_ = framework.ReadAllAndClose(t, ifModifiedSinceResp)
if ifModifiedSinceResp.StatusCode != http.StatusNotModified {
t.Fatalf("If-Modified-Since expected 304, got %d", ifModifiedSinceResp.StatusCode)
}
headIfModifiedSinceReq := mustNewRequest(t, http.MethodHead, clusterHarness.VolumeAdminURL()+"/"+fullFileID)
headIfModifiedSinceReq.Header.Set("If-Modified-Since", lastModified)
headIfModifiedSinceResp := framework.DoRequest(t, client, headIfModifiedSinceReq)
headIfModifiedSinceBody := framework.ReadAllAndClose(t, headIfModifiedSinceResp)
if headIfModifiedSinceResp.StatusCode != http.StatusNotModified {
t.Fatalf("HEAD If-Modified-Since expected 304, got %d", headIfModifiedSinceResp.StatusCode)
}
if len(headIfModifiedSinceBody) != 0 {
t.Fatalf("HEAD If-Modified-Since expected empty body, got %d bytes", len(headIfModifiedSinceBody))
}
}
func TestMalformedVidFidPathReturnsBadRequest(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
client := framework.NewHTTPClient()
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/not-a-vid/not-a-fid"))
_ = framework.ReadAllAndClose(t, resp)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("malformed /{vid}/{fid} expected 400, got %d", resp.StatusCode)
}
}
func TestReadWrongCookieReturnsNotFound(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(95)
const needleID = uint64(771235)
const cookie = uint32(0xBEEFCACF)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, needleID, cookie)
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("read-cookie-mismatch-content"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
wrongCookieFid := framework.NewFileID(volumeID, needleID, cookie+1)
getResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), wrongCookieFid)
_ = framework.ReadAllAndClose(t, getResp)
if getResp.StatusCode != http.StatusNotFound {
t.Fatalf("GET with wrong cookie expected 404, got %d", getResp.StatusCode)
}
headResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodHead, clusterHarness.VolumeAdminURL()+"/"+wrongCookieFid))
headBody := framework.ReadAllAndClose(t, headResp)
if headResp.StatusCode != http.StatusNotFound {
t.Fatalf("HEAD with wrong cookie expected 404, got %d", headResp.StatusCode)
}
if len(headBody) != 0 {
t.Fatalf("HEAD wrong-cookie response body should be empty, got %d bytes", len(headBody))
}
}
func TestConditionalHeaderPrecedenceAndInvalidIfModifiedSince(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(99)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 772002, 0x2B3C4D5E)
payload := []byte("conditional-precedence-content")
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, payload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
baselineResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), fid)
_ = framework.ReadAllAndClose(t, baselineResp)
if baselineResp.StatusCode != http.StatusOK {
t.Fatalf("baseline read expected 200, got %d", baselineResp.StatusCode)
}
lastModified := baselineResp.Header.Get("Last-Modified")
if lastModified == "" {
t.Fatalf("baseline read expected Last-Modified header")
}
precedenceReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
precedenceReq.Header.Set("If-Modified-Since", lastModified)
precedenceReq.Header.Set("If-None-Match", "\"definitely-different-etag\"")
precedenceResp := framework.DoRequest(t, client, precedenceReq)
precedenceBody := framework.ReadAllAndClose(t, precedenceResp)
if precedenceResp.StatusCode != http.StatusNotModified {
t.Fatalf("conditional precedence expected 304, got %d", precedenceResp.StatusCode)
}
if len(precedenceBody) != 0 {
t.Fatalf("conditional precedence expected empty body, got %d bytes", len(precedenceBody))
}
invalidIMSReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
invalidIMSReq.Header.Set("If-Modified-Since", "not-a-valid-http-date")
invalidIMSReq.Header.Set("If-None-Match", "\"definitely-different-etag\"")
invalidIMSResp := framework.DoRequest(t, client, invalidIMSReq)
invalidIMSBody := framework.ReadAllAndClose(t, invalidIMSResp)
if invalidIMSResp.StatusCode != http.StatusOK {
t.Fatalf("invalid If-Modified-Since with mismatched etag expected 200, got %d", invalidIMSResp.StatusCode)
}
if string(invalidIMSBody) != string(payload) {
t.Fatalf("invalid If-Modified-Since fallback body mismatch: got %q want %q", string(invalidIMSBody), string(payload))
}
}
@@ -1,123 +0,0 @@
package volume_server_http_test
import (
"net/http"
"strconv"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestUploadReadRangeHeadDeleteRoundTrip(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, cluster.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(7)
framework.AllocateVolume(t, grpcClient, volumeID, "")
fid := framework.NewFileID(volumeID, 123456, 0xA1B2C3D4)
data := []byte("hello-volume-server-integration")
client := framework.NewHTTPClient()
uploadResp := framework.UploadBytes(t, client, cluster.VolumeAdminURL(), fid, data)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload status: expected 201, got %d", uploadResp.StatusCode)
}
getResp := framework.ReadBytes(t, client, cluster.VolumeAdminURL(), fid)
getBody := framework.ReadAllAndClose(t, getResp)
if getResp.StatusCode != http.StatusOK {
t.Fatalf("get status: expected 200, got %d", getResp.StatusCode)
}
if string(getBody) != string(data) {
t.Fatalf("get body mismatch: got %q want %q", string(getBody), string(data))
}
etag := getResp.Header.Get("ETag")
if etag == "" {
t.Fatalf("expected ETag header from GET response")
}
notModifiedReq := mustNewRequest(t, http.MethodGet, cluster.VolumeAdminURL()+"/"+fid)
notModifiedReq.Header.Set("If-None-Match", etag)
notModifiedResp := framework.DoRequest(t, client, notModifiedReq)
_ = framework.ReadAllAndClose(t, notModifiedResp)
if notModifiedResp.StatusCode != http.StatusNotModified {
t.Fatalf("if-none-match expected 304, got %d", notModifiedResp.StatusCode)
}
rangeReq := mustNewRequest(t, http.MethodGet, cluster.VolumeAdminURL()+"/"+fid)
rangeReq.Header.Set("Range", "bytes=0-4")
rangeResp := framework.DoRequest(t, client, rangeReq)
rangeBody := framework.ReadAllAndClose(t, rangeResp)
if rangeResp.StatusCode != http.StatusPartialContent {
t.Fatalf("range status: expected 206, got %d", rangeResp.StatusCode)
}
if got, want := string(rangeBody), "hello"; got != want {
t.Fatalf("range body mismatch: got %q want %q", got, want)
}
invalidRangeReq := mustNewRequest(t, http.MethodGet, cluster.VolumeAdminURL()+"/"+fid)
invalidRangeReq.Header.Set("Range", "bytes=9999-10000")
invalidRangeResp := framework.DoRequest(t, client, invalidRangeReq)
_ = framework.ReadAllAndClose(t, invalidRangeResp)
if invalidRangeResp.StatusCode != http.StatusRequestedRangeNotSatisfiable {
t.Fatalf("invalid range expected 416, got %d", invalidRangeResp.StatusCode)
}
headResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodHead, cluster.VolumeAdminURL()+"/"+fid))
headBody := framework.ReadAllAndClose(t, headResp)
if headResp.StatusCode != http.StatusOK {
t.Fatalf("head status: expected 200, got %d", headResp.StatusCode)
}
if got := headResp.Header.Get("Content-Length"); got != strconv.Itoa(len(data)) {
t.Fatalf("head content-length mismatch: got %q want %d", got, len(data))
}
if len(headBody) != 0 {
t.Fatalf("head body should be empty, got %d bytes", len(headBody))
}
headNotModifiedReq := mustNewRequest(t, http.MethodHead, cluster.VolumeAdminURL()+"/"+fid)
headNotModifiedReq.Header.Set("If-None-Match", etag)
headNotModifiedResp := framework.DoRequest(t, client, headNotModifiedReq)
headNotModifiedBody := framework.ReadAllAndClose(t, headNotModifiedResp)
if headNotModifiedResp.StatusCode != http.StatusNotModified {
t.Fatalf("head if-none-match expected 304, got %d", headNotModifiedResp.StatusCode)
}
if len(headNotModifiedBody) != 0 {
t.Fatalf("head if-none-match body should be empty, got %d bytes", len(headNotModifiedBody))
}
deleteResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, cluster.VolumeAdminURL()+"/"+fid))
_ = framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusAccepted {
t.Fatalf("delete status: expected 202, got %d", deleteResp.StatusCode)
}
notFoundResp := framework.ReadBytes(t, client, cluster.VolumeAdminURL(), fid)
_ = framework.ReadAllAndClose(t, notFoundResp)
if notFoundResp.StatusCode != http.StatusNotFound {
t.Fatalf("read after delete: expected 404, got %d", notFoundResp.StatusCode)
}
}
func TestInvalidReadPathReturnsBadRequest(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
cluster := framework.StartSingleVolumeCluster(t, matrix.P1())
client := framework.NewHTTPClient()
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, cluster.VolumeAdminURL()+"/invalid,needle"))
_ = framework.ReadAllAndClose(t, resp)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("invalid read expected 400, got %d", resp.StatusCode)
}
}
-730
View File
@@ -1,730 +0,0 @@
package volume_server_http_test
import (
"bytes"
"context"
"io"
"net/http"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
type pausableReader struct {
remaining int64
pauseAfter int64
paused bool
unblock <-chan struct{}
}
func (r *pausableReader) Read(p []byte) (int, error) {
if r.remaining <= 0 {
return 0, io.EOF
}
if !r.paused && r.pauseAfter > 0 {
n := int64(len(p))
if n > r.pauseAfter {
n = r.pauseAfter
}
for i := int64(0); i < n; i++ {
p[i] = 'a'
}
r.remaining -= n
r.pauseAfter -= n
if r.pauseAfter == 0 {
r.paused = true
}
return int(n), nil
}
if r.paused {
<-r.unblock
r.paused = false
}
n := int64(len(p))
if n > r.remaining {
n = r.remaining
}
for i := int64(0); i < n; i++ {
p[i] = 'b'
}
r.remaining -= n
return int(n), nil
}
func TestUploadLimitTimeoutAndReplicateBypass(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P8())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(98)
framework.AllocateVolume(t, grpcClient, volumeID, "")
const blockedUploadSize = 2 * 1024 * 1024 // over 1MB P8 upload limit
unblockFirstUpload := make(chan struct{})
firstUploadDone := make(chan error, 1)
firstFID := framework.NewFileID(volumeID, 880001, 0x1A2B3C4D)
go func() {
req, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+firstFID, &pausableReader{
remaining: blockedUploadSize,
pauseAfter: 1,
unblock: unblockFirstUpload,
})
if err != nil {
firstUploadDone <- err
return
}
req.Header.Set("Content-Type", "application/octet-stream")
req.ContentLength = blockedUploadSize
resp, err := (&http.Client{}).Do(req)
if resp != nil {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}
firstUploadDone <- err
}()
// Give the first upload time to pass limit checks and block in body processing.
time.Sleep(300 * time.Millisecond)
replicateFID := framework.NewFileID(volumeID, 880002, 0x5E6F7A8B)
replicateReq, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+replicateFID+"?type=replicate", bytes.NewReader([]byte("replicate")))
if err != nil {
t.Fatalf("create replicate request: %v", err)
}
replicateReq.Header.Set("Content-Type", "application/octet-stream")
replicateReq.ContentLength = int64(len("replicate"))
replicateResp, err := framework.NewHTTPClient().Do(replicateReq)
if err != nil {
t.Fatalf("replicate request failed: %v", err)
}
_ = framework.ReadAllAndClose(t, replicateResp)
if replicateResp.StatusCode != http.StatusCreated {
t.Fatalf("replicate request expected 201 bypassing limit, got %d", replicateResp.StatusCode)
}
normalFID := framework.NewFileID(volumeID, 880003, 0x9C0D1E2F)
normalReq, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+normalFID, bytes.NewReader([]byte("normal")))
if err != nil {
t.Fatalf("create normal request: %v", err)
}
normalReq.Header.Set("Content-Type", "application/octet-stream")
normalReq.ContentLength = int64(len("normal"))
timeoutClient := &http.Client{Timeout: 10 * time.Second}
normalResp, err := timeoutClient.Do(normalReq)
if err != nil {
t.Fatalf("normal upload request failed: %v", err)
}
_ = framework.ReadAllAndClose(t, normalResp)
if normalResp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("normal upload expected 429 while limit blocked, got %d", normalResp.StatusCode)
}
close(unblockFirstUpload)
select {
case <-firstUploadDone:
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for blocked upload to finish")
}
}
func TestUploadLimitWaitThenProceed(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P8())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(111)
framework.AllocateVolume(t, grpcClient, volumeID, "")
const blockedUploadSize = 2 * 1024 * 1024
unblockFirstUpload := make(chan struct{})
firstUploadDone := make(chan error, 1)
firstFID := framework.NewFileID(volumeID, 880601, 0x6A2B3C4D)
go func() {
req, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+firstFID, &pausableReader{
remaining: blockedUploadSize,
pauseAfter: 1,
unblock: unblockFirstUpload,
})
if err != nil {
firstUploadDone <- err
return
}
req.Header.Set("Content-Type", "application/octet-stream")
req.ContentLength = blockedUploadSize
resp, err := (&http.Client{}).Do(req)
if resp != nil {
_ = framework.ReadAllAndClose(t, resp)
}
firstUploadDone <- err
}()
time.Sleep(300 * time.Millisecond)
type uploadResult struct {
resp *http.Response
err error
}
secondUploadDone := make(chan uploadResult, 1)
secondFID := framework.NewFileID(volumeID, 880602, 0x6A2B3C4E)
go func() {
req, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+secondFID, bytes.NewReader([]byte("wait-then-proceed")))
if err != nil {
secondUploadDone <- uploadResult{err: err}
return
}
req.Header.Set("Content-Type", "application/octet-stream")
req.ContentLength = int64(len("wait-then-proceed"))
resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
secondUploadDone <- uploadResult{resp: resp, err: err}
}()
time.Sleep(500 * time.Millisecond)
close(unblockFirstUpload)
select {
case firstErr := <-firstUploadDone:
if firstErr != nil {
t.Fatalf("first blocked upload failed: %v", firstErr)
}
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for first upload completion")
}
select {
case result := <-secondUploadDone:
if result.err != nil {
t.Fatalf("second upload failed: %v", result.err)
}
_ = framework.ReadAllAndClose(t, result.resp)
if result.resp.StatusCode != http.StatusCreated {
t.Fatalf("second upload expected 201 after waiting for slot, got %d", result.resp.StatusCode)
}
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for second upload completion")
}
}
func TestUploadLimitTimeoutThenRecovery(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P8())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(113)
framework.AllocateVolume(t, grpcClient, volumeID, "")
const blockedUploadSize = 2 * 1024 * 1024
unblockFirstUpload := make(chan struct{})
firstUploadDone := make(chan error, 1)
firstFID := framework.NewFileID(volumeID, 880801, 0x7A2B3C4D)
go func() {
req, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+firstFID, &pausableReader{
remaining: blockedUploadSize,
pauseAfter: 1,
unblock: unblockFirstUpload,
})
if err != nil {
firstUploadDone <- err
return
}
req.Header.Set("Content-Type", "application/octet-stream")
req.ContentLength = blockedUploadSize
resp, err := (&http.Client{}).Do(req)
if resp != nil {
_ = framework.ReadAllAndClose(t, resp)
}
firstUploadDone <- err
}()
time.Sleep(300 * time.Millisecond)
timeoutFID := framework.NewFileID(volumeID, 880802, 0x7A2B3C4E)
timeoutResp := framework.UploadBytes(t, &http.Client{Timeout: 10 * time.Second}, clusterHarness.VolumeAdminURL(), timeoutFID, []byte("should-timeout"))
_ = framework.ReadAllAndClose(t, timeoutResp)
if timeoutResp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("second upload under blocked pressure expected 429, got %d", timeoutResp.StatusCode)
}
close(unblockFirstUpload)
select {
case firstErr := <-firstUploadDone:
if firstErr != nil {
t.Fatalf("first blocked upload failed: %v", firstErr)
}
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for first upload completion")
}
recoveryFID := framework.NewFileID(volumeID, 880803, 0x7A2B3C4F)
recoveryResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), recoveryFID, []byte("recovered-upload"))
_ = framework.ReadAllAndClose(t, recoveryResp)
if recoveryResp.StatusCode != http.StatusCreated {
t.Fatalf("recovery upload expected 201, got %d", recoveryResp.StatusCode)
}
}
func TestDownloadLimitTimeoutReturnsTooManyRequests(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P8())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(99)
framework.AllocateVolume(t, grpcClient, volumeID, "")
largePayload := make([]byte, 12*1024*1024) // over 1MB P8 download limit
for i := range largePayload {
largePayload[i] = byte(i % 251)
}
downloadFID := framework.NewFileID(volumeID, 880101, 0x10203040)
uploadResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), downloadFID, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("large upload expected 201, got %d", uploadResp.StatusCode)
}
firstResp, err := (&http.Client{}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+downloadFID))
if err != nil {
t.Fatalf("first GET failed: %v", err)
}
if firstResp.StatusCode != http.StatusOK {
_ = framework.ReadAllAndClose(t, firstResp)
t.Fatalf("first GET expected 200, got %d", firstResp.StatusCode)
}
defer firstResp.Body.Close()
// Keep first response body unread so server write path stays in-flight.
time.Sleep(300 * time.Millisecond)
secondClient := &http.Client{Timeout: 10 * time.Second}
secondResp, err := secondClient.Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+downloadFID))
if err != nil {
t.Fatalf("second GET failed: %v", err)
}
_ = framework.ReadAllAndClose(t, secondResp)
if secondResp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("second GET expected 429 while first download holds limit, got %d", secondResp.StatusCode)
}
}
func TestDownloadLimitWaitThenProceedWithoutReplica(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P8())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(112)
framework.AllocateVolume(t, grpcClient, volumeID, "")
largePayload := make([]byte, 12*1024*1024)
for i := range largePayload {
largePayload[i] = byte(i % 251)
}
fid := framework.NewFileID(volumeID, 880701, 0x60708090)
uploadResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), fid, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("large upload expected 201, got %d", uploadResp.StatusCode)
}
firstResp, err := (&http.Client{}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid))
if err != nil {
t.Fatalf("first GET failed: %v", err)
}
if firstResp.StatusCode != http.StatusOK {
_ = framework.ReadAllAndClose(t, firstResp)
t.Fatalf("first GET expected 200, got %d", firstResp.StatusCode)
}
type readResult struct {
resp *http.Response
err error
}
secondReadDone := make(chan readResult, 1)
go func() {
resp, readErr := (&http.Client{Timeout: 10 * time.Second}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid))
secondReadDone <- readResult{resp: resp, err: readErr}
}()
time.Sleep(500 * time.Millisecond)
_ = firstResp.Body.Close()
select {
case result := <-secondReadDone:
if result.err != nil {
t.Fatalf("second GET failed: %v", result.err)
}
secondBody := framework.ReadAllAndClose(t, result.resp)
if result.resp.StatusCode != http.StatusOK {
t.Fatalf("second GET expected 200 after waiting for slot, got %d", result.resp.StatusCode)
}
if len(secondBody) != len(largePayload) {
t.Fatalf("second GET body size mismatch: got %d want %d", len(secondBody), len(largePayload))
}
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for second GET completion")
}
}
func TestDownloadLimitTimeoutThenRecovery(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P8())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(114)
framework.AllocateVolume(t, grpcClient, volumeID, "")
largePayload := make([]byte, 12*1024*1024)
for i := range largePayload {
largePayload[i] = byte(i % 251)
}
fid := framework.NewFileID(volumeID, 880901, 0x708090A0)
uploadResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), fid, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("large upload expected 201, got %d", uploadResp.StatusCode)
}
firstResp, err := (&http.Client{}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid))
if err != nil {
t.Fatalf("first GET failed: %v", err)
}
if firstResp.StatusCode != http.StatusOK {
_ = framework.ReadAllAndClose(t, firstResp)
t.Fatalf("first GET expected 200, got %d", firstResp.StatusCode)
}
time.Sleep(300 * time.Millisecond)
timeoutResp := framework.ReadBytes(t, &http.Client{Timeout: 10 * time.Second}, clusterHarness.VolumeAdminURL(), fid)
_ = framework.ReadAllAndClose(t, timeoutResp)
if timeoutResp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("second GET under blocked pressure expected 429, got %d", timeoutResp.StatusCode)
}
_ = firstResp.Body.Close()
recoveryResp := framework.ReadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), fid)
recoveryBody := framework.ReadAllAndClose(t, recoveryResp)
if recoveryResp.StatusCode != http.StatusOK {
t.Fatalf("recovery GET expected 200, got %d", recoveryResp.StatusCode)
}
if len(recoveryBody) != len(largePayload) {
t.Fatalf("recovery GET body size mismatch: got %d want %d", len(recoveryBody), len(largePayload))
}
}
func TestDownloadLimitOverageProxiesToReplica(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P8()
profile.ReadMode = "proxy"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
conn1, grpc1 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(1))
defer conn1.Close()
const volumeID = uint32(100)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req := &volume_server_pb.AllocateVolumeRequest{
VolumeId: volumeID,
Replication: "001",
Version: uint32(needle.GetCurrentVersion()),
}
if _, err := grpc0.AllocateVolume(ctx, req); err != nil {
t.Fatalf("allocate replicated volume on node0: %v", err)
}
if _, err := grpc1.AllocateVolume(ctx, req); err != nil {
t.Fatalf("allocate replicated volume on node1: %v", err)
}
largePayload := make([]byte, 12*1024*1024)
for i := range largePayload {
largePayload[i] = byte(i % 251)
}
fid := framework.NewFileID(volumeID, 880201, 0x0A0B0C0D)
uploadResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(0), fid, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("replicated large upload expected 201, got %d", uploadResp.StatusCode)
}
replicaReadURL := clusterHarness.VolumeAdminURL(1) + "/" + fid
if !waitForHTTPStatus(t, framework.NewHTTPClient(), replicaReadURL, http.StatusOK, 10*time.Second, func(resp *http.Response) {
_ = framework.ReadAllAndClose(t, resp)
}) {
t.Fatalf("replica did not become readable within deadline")
}
firstResp, err := (&http.Client{}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL(0)+"/"+fid))
if err != nil {
t.Fatalf("first GET failed: %v", err)
}
if firstResp.StatusCode != http.StatusOK {
_ = framework.ReadAllAndClose(t, firstResp)
t.Fatalf("first GET expected 200, got %d", firstResp.StatusCode)
}
defer firstResp.Body.Close()
time.Sleep(300 * time.Millisecond)
secondResp, err := framework.NewHTTPClient().Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL(0)+"/"+fid))
if err != nil {
t.Fatalf("second GET failed: %v", err)
}
secondBody := framework.ReadAllAndClose(t, secondResp)
if secondResp.StatusCode != http.StatusOK {
t.Fatalf("second GET expected 200 via replica proxy fallback, got %d", secondResp.StatusCode)
}
if len(secondBody) != len(largePayload) {
t.Fatalf("second GET proxied body size mismatch: got %d want %d", len(secondBody), len(largePayload))
}
}
func TestDownloadLimitProxiedRequestSkipsReplicaFallbackAndTimesOut(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
profile := matrix.P8()
profile.ReadMode = "proxy"
clusterHarness := framework.StartDualVolumeCluster(t, profile)
conn0, grpc0 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(0))
defer conn0.Close()
conn1, grpc1 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress(1))
defer conn1.Close()
const volumeID = uint32(106)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req := &volume_server_pb.AllocateVolumeRequest{
VolumeId: volumeID,
Replication: "001",
Version: uint32(needle.GetCurrentVersion()),
}
if _, err := grpc0.AllocateVolume(ctx, req); err != nil {
t.Fatalf("allocate replicated volume on node0: %v", err)
}
if _, err := grpc1.AllocateVolume(ctx, req); err != nil {
t.Fatalf("allocate replicated volume on node1: %v", err)
}
largePayload := make([]byte, 12*1024*1024)
for i := range largePayload {
largePayload[i] = byte(i % 251)
}
fid := framework.NewFileID(volumeID, 880202, 0x0A0B0D0E)
uploadResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(0), fid, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("replicated large upload expected 201, got %d", uploadResp.StatusCode)
}
// Ensure replica path is actually available, so a non-proxied request would proxy.
replicaReadURL := clusterHarness.VolumeAdminURL(1) + "/" + fid
if !waitForHTTPStatus(t, framework.NewHTTPClient(), replicaReadURL, http.StatusOK, 10*time.Second, func(resp *http.Response) {
_ = framework.ReadAllAndClose(t, resp)
}) {
t.Fatalf("replica did not become readable within deadline")
}
firstResp, err := (&http.Client{}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL(0)+"/"+fid))
if err != nil {
t.Fatalf("first GET failed: %v", err)
}
if firstResp.StatusCode != http.StatusOK {
_ = framework.ReadAllAndClose(t, firstResp)
t.Fatalf("first GET expected 200, got %d", firstResp.StatusCode)
}
defer firstResp.Body.Close()
time.Sleep(300 * time.Millisecond)
// proxied=true should bypass replica fallback and hit wait/timeout branch.
secondResp, err := framework.NewHTTPClient().Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL(0)+"/"+fid+"?proxied=true"))
if err != nil {
t.Fatalf("second GET failed: %v", err)
}
_ = framework.ReadAllAndClose(t, secondResp)
if secondResp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("second GET with proxied=true expected 429 timeout path, got %d", secondResp.StatusCode)
}
}
func TestUploadLimitDisabledAllowsConcurrentUploads(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(107)
framework.AllocateVolume(t, grpcClient, volumeID, "")
const blockedUploadSize = 2 * 1024 * 1024
unblockFirstUpload := make(chan struct{})
firstUploadDone := make(chan error, 1)
firstFID := framework.NewFileID(volumeID, 880301, 0x1A2B3C5D)
go func() {
req, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+firstFID, &pausableReader{
remaining: blockedUploadSize,
pauseAfter: 1,
unblock: unblockFirstUpload,
})
if err != nil {
firstUploadDone <- err
return
}
req.Header.Set("Content-Type", "application/octet-stream")
req.ContentLength = blockedUploadSize
resp, err := (&http.Client{}).Do(req)
if resp != nil {
_ = framework.ReadAllAndClose(t, resp)
}
firstUploadDone <- err
}()
time.Sleep(300 * time.Millisecond)
secondFID := framework.NewFileID(volumeID, 880302, 0x1A2B3C5E)
secondResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), secondFID, []byte("no-limit-second-upload"))
_ = framework.ReadAllAndClose(t, secondResp)
if secondResp.StatusCode != http.StatusCreated {
t.Fatalf("second upload with disabled limit expected 201, got %d", secondResp.StatusCode)
}
close(unblockFirstUpload)
select {
case <-firstUploadDone:
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for first upload completion")
}
}
func TestDownloadLimitDisabledAllowsConcurrentDownloads(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(108)
framework.AllocateVolume(t, grpcClient, volumeID, "")
largePayload := make([]byte, 12*1024*1024)
for i := range largePayload {
largePayload[i] = byte(i % 251)
}
fid := framework.NewFileID(volumeID, 880401, 0x20304050)
uploadResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), fid, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("large upload expected 201, got %d", uploadResp.StatusCode)
}
firstResp, err := (&http.Client{}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid))
if err != nil {
t.Fatalf("first GET failed: %v", err)
}
if firstResp.StatusCode != http.StatusOK {
_ = framework.ReadAllAndClose(t, firstResp)
t.Fatalf("first GET expected 200, got %d", firstResp.StatusCode)
}
defer firstResp.Body.Close()
time.Sleep(300 * time.Millisecond)
secondResp := framework.ReadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), fid)
secondBody := framework.ReadAllAndClose(t, secondResp)
if secondResp.StatusCode != http.StatusOK {
t.Fatalf("second GET with disabled limit expected 200, got %d", secondResp.StatusCode)
}
if len(secondBody) != len(largePayload) {
t.Fatalf("second GET body size mismatch: got %d want %d", len(secondBody), len(largePayload))
}
}
func TestDownloadLimitInvalidVidWhileOverLimitReturnsBadRequest(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P8())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(110)
framework.AllocateVolume(t, grpcClient, volumeID, "")
largePayload := make([]byte, 12*1024*1024)
for i := range largePayload {
largePayload[i] = byte(i % 251)
}
fid := framework.NewFileID(volumeID, 880501, 0x50607080)
uploadResp := framework.UploadBytes(t, framework.NewHTTPClient(), clusterHarness.VolumeAdminURL(), fid, largePayload)
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("large upload expected 201, got %d", uploadResp.StatusCode)
}
firstResp, err := (&http.Client{}).Do(mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid))
if err != nil {
t.Fatalf("first GET failed: %v", err)
}
if firstResp.StatusCode != http.StatusOK {
_ = framework.ReadAllAndClose(t, firstResp)
t.Fatalf("first GET expected 200, got %d", firstResp.StatusCode)
}
defer firstResp.Body.Close()
time.Sleep(300 * time.Millisecond)
invalidReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/not-a-vid,1234567890ab")
invalidResp := framework.DoRequest(t, framework.NewHTTPClient(), invalidReq)
_ = framework.ReadAllAndClose(t, invalidResp)
if invalidResp.StatusCode != http.StatusBadRequest {
t.Fatalf("invalid vid while over limit expected 400, got %d", invalidResp.StatusCode)
}
}
@@ -1,118 +0,0 @@
package volume_server_http_test
import (
"encoding/json"
"net/http"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestWriteUnchangedAndDeleteEdgeVariants(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(87)
framework.AllocateVolume(t, grpcClient, volumeID, "")
const key = uint64(999001)
const cookie = uint32(0xDEADBEEF)
fid := framework.NewFileID(volumeID, key, cookie)
client := framework.NewHTTPClient()
payload := []byte("unchanged-write-content")
firstUpload := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
firstUploadResp := framework.DoRequest(t, client, firstUpload)
_ = framework.ReadAllAndClose(t, firstUploadResp)
if firstUploadResp.StatusCode != http.StatusCreated {
t.Fatalf("first upload expected 201, got %d", firstUploadResp.StatusCode)
}
secondUpload := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, payload)
secondUploadResp := framework.DoRequest(t, client, secondUpload)
_ = framework.ReadAllAndClose(t, secondUploadResp)
if secondUploadResp.StatusCode != http.StatusNoContent {
t.Fatalf("second unchanged upload expected 204, got %d", secondUploadResp.StatusCode)
}
if secondUploadResp.Header.Get("ETag") == "" {
t.Fatalf("second unchanged upload expected ETag header")
}
wrongCookieFid := framework.NewFileID(volumeID, key, cookie+1)
wrongCookieDelete := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL()+"/"+wrongCookieFid))
_ = framework.ReadAllAndClose(t, wrongCookieDelete)
if wrongCookieDelete.StatusCode != http.StatusBadRequest {
t.Fatalf("delete with mismatched cookie expected 400, got %d", wrongCookieDelete.StatusCode)
}
missingDelete := framework.DoRequest(t, client, mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL()+"/"+framework.NewFileID(volumeID, key+1, cookie)))
missingDeleteBody := framework.ReadAllAndClose(t, missingDelete)
if missingDelete.StatusCode != http.StatusNotFound {
t.Fatalf("delete missing needle expected 404, got %d", missingDelete.StatusCode)
}
var payloadMap map[string]int64
if err := json.Unmarshal(missingDeleteBody, &payloadMap); err != nil {
t.Fatalf("decode delete missing response: %v", err)
}
if payloadMap["size"] != 0 {
t.Fatalf("delete missing needle expected size=0, got %d", payloadMap["size"])
}
}
func TestDeleteTimestampOverrideKeepsReadDeletedLastModifiedParity(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(88)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 999002, 0xABCD1234)
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(), fid, []byte("delete-ts-override"))
_ = framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
}
beforeDeleteResp := framework.ReadBytes(t, client, clusterHarness.VolumeAdminURL(), fid)
_ = framework.ReadAllAndClose(t, beforeDeleteResp)
if beforeDeleteResp.StatusCode != http.StatusOK {
t.Fatalf("pre-delete read expected 200, got %d", beforeDeleteResp.StatusCode)
}
lastModifiedBeforeDelete := beforeDeleteResp.Header.Get("Last-Modified")
if lastModifiedBeforeDelete == "" {
t.Fatalf("expected Last-Modified before delete")
}
deleteReq := mustNewRequest(t, http.MethodDelete, clusterHarness.VolumeAdminURL()+"/"+fid+"?ts=1700000000")
deleteResp := framework.DoRequest(t, client, deleteReq)
_ = framework.ReadAllAndClose(t, deleteResp)
if deleteResp.StatusCode != http.StatusAccepted {
t.Fatalf("delete with ts override expected 202, got %d", deleteResp.StatusCode)
}
readDeletedResp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid+"?readDeleted=true"))
_ = framework.ReadAllAndClose(t, readDeletedResp)
if readDeletedResp.StatusCode != http.StatusOK {
t.Fatalf("readDeleted after ts override expected 200, got %d", readDeletedResp.StatusCode)
}
lastModified := readDeletedResp.Header.Get("Last-Modified")
if lastModified == "" {
t.Fatalf("expected Last-Modified header on readDeleted response")
}
if lastModified != lastModifiedBeforeDelete {
t.Fatalf("expected readDeleted Last-Modified parity with pre-delete header, got %q want %q", lastModified, lastModifiedBeforeDelete)
}
}
@@ -1,74 +0,0 @@
package volume_server_http_test
import (
"net/http"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
)
func TestWriteInvalidVidAndFidReturnBadRequest(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
client := framework.NewHTTPClient()
invalidVidReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/invalid,12345678", []byte("x"))
invalidVidResp := framework.DoRequest(t, client, invalidVidReq)
_ = framework.ReadAllAndClose(t, invalidVidResp)
if invalidVidResp.StatusCode != http.StatusBadRequest {
t.Fatalf("write with invalid vid expected 400, got %d", invalidVidResp.StatusCode)
}
invalidFidReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/1,bad", []byte("x"))
invalidFidResp := framework.DoRequest(t, client, invalidFidReq)
_ = framework.ReadAllAndClose(t, invalidFidResp)
if invalidFidResp.StatusCode != http.StatusBadRequest {
t.Fatalf("write with invalid fid expected 400, got %d", invalidFidResp.StatusCode)
}
}
func TestWriteMalformedMultipartAndMD5Mismatch(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartSingleVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(98)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
fid := framework.NewFileID(volumeID, 772001, 0x1A2B3C4D)
malformedMultipartReq, err := http.NewRequest(http.MethodPost, clusterHarness.VolumeAdminURL()+"/"+fid, strings.NewReader("not-a-valid-multipart-body"))
if err != nil {
t.Fatalf("create malformed multipart request: %v", err)
}
malformedMultipartReq.Header.Set("Content-Type", "multipart/form-data")
malformedMultipartResp := framework.DoRequest(t, client, malformedMultipartReq)
malformedMultipartBody := framework.ReadAllAndClose(t, malformedMultipartResp)
if malformedMultipartResp.StatusCode != http.StatusBadRequest {
t.Fatalf("malformed multipart write expected 400, got %d", malformedMultipartResp.StatusCode)
}
if !strings.Contains(strings.ToLower(string(malformedMultipartBody)), "boundary") {
t.Fatalf("malformed multipart response should mention boundary parse failure, got %q", string(malformedMultipartBody))
}
md5MismatchReq := newUploadRequest(t, clusterHarness.VolumeAdminURL()+"/"+fid, []byte("content-md5-mismatch-body"))
md5MismatchReq.Header.Set("Content-MD5", "AAAAAAAAAAAAAAAAAAAAAA==")
md5MismatchResp := framework.DoRequest(t, client, md5MismatchReq)
md5MismatchBody := framework.ReadAllAndClose(t, md5MismatchResp)
if md5MismatchResp.StatusCode != http.StatusBadRequest {
t.Fatalf("content-md5 mismatch write expected 400, got %d", md5MismatchResp.StatusCode)
}
if !strings.Contains(string(md5MismatchBody), "Content-MD5") {
t.Fatalf("content-md5 mismatch response should mention Content-MD5, got %q", string(md5MismatchBody))
}
}
@@ -1,63 +0,0 @@
package matrix
import "time"
// Profile describes one runtime test matrix configuration.
type Profile struct {
Name string
ReadMode string
SplitPublicPort bool
EnableJWT bool
JWTSigningKey string
JWTReadKey string
EnableMaintain bool
ConcurrentUploadLimitMB int
ConcurrentDownloadLimitMB int
InflightUploadTimeout time.Duration
InflightDownloadTimeout time.Duration
ReplicatedLayout bool
HasErasureCoding bool
HasRemoteTier bool
}
// P1 is the baseline profile: one volume server, no JWT, proxy read mode.
func P1() Profile {
return Profile{
Name: "P1",
ReadMode: "proxy",
SplitPublicPort: false,
}
}
// P2 uses split public/admin ports to verify public read-only behavior.
func P2() Profile {
p := P1()
p.Name = "P2"
p.SplitPublicPort = true
return p
}
// P3 enables JWT verification for read/write flows.
func P3() Profile {
p := P1()
p.Name = "P3"
p.EnableJWT = true
p.JWTSigningKey = "volume-server-write-key"
p.JWTReadKey = "volume-server-read-key"
return p
}
// P8 enables upload/download throttling branches.
func P8() Profile {
p := P1()
p.Name = "P8"
p.ConcurrentUploadLimitMB = 1
p.ConcurrentDownloadLimitMB = 1
p.InflightUploadTimeout = 2 * time.Second
p.InflightDownloadTimeout = 2 * time.Second
return p
}
+2 -3
View File
@@ -9,14 +9,13 @@ import (
"github.com/gin-gonic/gin"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
// Access key status constants
const (
AccessKeyStatusActive = iam.AccessKeyStatusActive
AccessKeyStatusInactive = iam.AccessKeyStatusInactive
AccessKeyStatusActive = "Active"
AccessKeyStatusInactive = "Inactive"
)
type AdminData struct {
-4
View File
@@ -10,7 +10,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/seaweedfs/seaweedfs/weed/admin/maintenance"
"github.com/seaweedfs/seaweedfs/weed/admin/plugin"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/glog"
@@ -109,9 +108,6 @@ type AdminServer struct {
// Worker gRPC server
workerGrpcServer *WorkerGrpcServer
// Plugin system manager
PluginManager *plugin.Manager
// Collection statistics caching
collectionStatsCache map[string]collectionStats
lastCollectionStatsUpdate time.Time
@@ -8,7 +8,6 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
)
@@ -22,8 +21,8 @@ const (
accessKeyPrefix = "ABIA" // Service account access keys use ABIA prefix
// Status constants
StatusActive = iam.AccessKeyStatusActive
StatusInactive = iam.AccessKeyStatusInactive
StatusActive = "Active"
StatusInactive = "Inactive"
)
// GetServiceAccounts returns all service accounts, optionally filtered by parent user
-21
View File
@@ -26,7 +26,6 @@ type AdminHandlers struct {
maintenanceHandlers *MaintenanceHandlers
mqHandlers *MessageQueueHandlers
serviceAccountHandlers *ServiceAccountHandlers
pluginHandlers *PluginHandlers
}
// NewAdminHandlers creates a new instance of AdminHandlers
@@ -39,7 +38,6 @@ func NewAdminHandlers(adminServer *dash.AdminServer) *AdminHandlers {
maintenanceHandlers := NewMaintenanceHandlers(adminServer)
mqHandlers := NewMessageQueueHandlers(adminServer)
serviceAccountHandlers := NewServiceAccountHandlers(adminServer)
pluginHandlers := NewPluginHandlers(adminServer)
return &AdminHandlers{
adminServer: adminServer,
authHandlers: authHandlers,
@@ -50,7 +48,6 @@ func NewAdminHandlers(adminServer *dash.AdminServer) *AdminHandlers {
maintenanceHandlers: maintenanceHandlers,
mqHandlers: mqHandlers,
serviceAccountHandlers: serviceAccountHandlers,
pluginHandlers: pluginHandlers,
}
}
@@ -131,11 +128,6 @@ func (h *AdminHandlers) SetupRoutes(r *gin.Engine, authRequired bool, adminUser,
protected.POST("/maintenance/config/:taskType", dash.RequireWriteAccess(), h.maintenanceHandlers.UpdateTaskConfig)
protected.GET("/maintenance/tasks/:id", h.maintenanceHandlers.ShowTaskDetail)
// Plugin system routes
protected.GET("/plugins", h.pluginHandlers.ShowPlugins)
protected.GET("/plugins/jobs/:jobType", h.pluginHandlers.ShowPluginJobs)
protected.GET("/plugins/config/:jobType", h.pluginHandlers.ShowPluginConfig)
// API routes for AJAX calls
api := r.Group("/api")
api.Use(dash.RequireAuthAPI()) // Use API-specific auth middleware
@@ -250,19 +242,6 @@ func (h *AdminHandlers) SetupRoutes(r *gin.Engine, authRequired bool, adminUser,
maintenanceApi.PUT("/config", dash.RequireWriteAccess(), h.adminServer.UpdateMaintenanceConfigAPI)
}
// Plugin system API routes
pluginApi := api.Group("/plugin")
{
pluginApi.GET("/list", h.pluginHandlers.ListPluginsAPI)
pluginApi.GET("/jobs/:jobType", h.pluginHandlers.ListJobsAPI)
pluginApi.GET("/config/:jobType", h.pluginHandlers.GetConfigAPI)
pluginApi.POST("/config/:jobType/apply", dash.RequireWriteAccess(), h.pluginHandlers.SaveConfigAPI)
pluginApi.GET("/detection/history/:jobType", h.pluginHandlers.GetDetectionHistoryAPI)
pluginApi.GET("/execution/history/:jobType", h.pluginHandlers.GetExecutionHistoryAPI)
pluginApi.POST("/jobs/:jobType/trigger-detection", dash.RequireWriteAccess(), h.pluginHandlers.TriggerDetectionAPI)
pluginApi.POST("/jobs/:jobID/cancel", dash.RequireWriteAccess(), h.pluginHandlers.CancelJobAPI)
}
// Message Queue API routes
mqApi := api.Group("/mq")
{
-533
View File
@@ -1,533 +0,0 @@
package handlers
import (
"fmt"
"net/http"
"sort"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
"github.com/seaweedfs/seaweedfs/weed/admin/plugin"
"github.com/seaweedfs/seaweedfs/weed/admin/view/app"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// PluginHandlers handles HTTP requests for the plugin system
type PluginHandlers struct {
adminServer *dash.AdminServer
}
// NewPluginHandlers creates a new plugin handlers instance
func NewPluginHandlers(adminServer *dash.AdminServer) *PluginHandlers {
return &PluginHandlers{
adminServer: adminServer,
}
}
// ShowPlugins renders the main plugins page
func (h *PluginHandlers) ShowPlugins(c *gin.Context) {
data := h.getPluginsData()
html := app.PluginsPage(data)
c.Header("Content-Type", "text/html")
html.Render(c.Request.Context(), c.Writer)
}
// ShowPluginJobs renders the job monitoring page
func (h *PluginHandlers) ShowPluginJobs(c *gin.Context) {
jobType := c.Param("jobType")
data := h.getJobsData(jobType)
html := app.PluginJobsPage(data)
c.Header("Content-Type", "text/html")
html.Render(c.Request.Context(), c.Writer)
}
// ShowPluginConfig renders the plugin configuration page
func (h *PluginHandlers) ShowPluginConfig(c *gin.Context) {
jobType := c.Param("jobType")
data := h.getPluginConfigData(jobType)
html := app.PluginConfigPage(data)
c.Header("Content-Type", "text/html")
html.Render(c.Request.Context(), c.Writer)
}
// ListPluginsAPI returns JSON list of registered plugins
func (h *PluginHandlers) ListPluginsAPI(c *gin.Context) {
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
plugins := h.adminServer.PluginManager.ListConnectedPlugins()
// Convert to API response
var pluginList []map[string]interface{}
for _, p := range plugins {
pluginList = append(pluginList, map[string]interface{}{
"id": p.ID,
"name": p.Name,
"version": p.Version,
"protocol_version": p.ProtocolVersion,
"connected_at": p.ConnectedAt,
"last_heartbeat": p.LastHeartbeat,
"state": p.State.String(),
"healthy": p.IsHealthy(),
"pending_jobs": p.PendingJobs,
"running_jobs": p.RunningJobs,
"cpu_usage": p.CPUUsagePercent,
"memory_usage_mb": p.MemoryUsageMB,
})
}
c.JSON(http.StatusOK, gin.H{"plugins": pluginList})
}
// ListJobsAPI returns JSON list of jobs for a job type
func (h *PluginHandlers) ListJobsAPI(c *gin.Context) {
jobType := c.Param("jobType")
stateStr := c.DefaultQuery("state", "")
limit := 100
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
var state plugin.JobState
if stateStr != "" {
// Parse state string
switch stateStr {
case "pending":
state = plugin.JobStatePending
case "running":
state = plugin.JobStateRunning
case "completed":
state = plugin.JobStateCompleted
case "failed":
state = plugin.JobStateFailed
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"})
return
}
}
jobs := h.adminServer.PluginManager.ListJobs(jobType, state)
if limit > 0 && len(jobs) > limit {
jobs = jobs[:limit]
}
var jobList []map[string]interface{}
for _, j := range jobs {
jobList = append(jobList, map[string]interface{}{
"id": j.ID,
"type": j.Type,
"description": j.Description,
"state": j.State.String(),
"created_at": j.CreatedAt,
"updated_at": j.UpdatedAt,
"executor_id": j.ExecutorID,
"progress": j.ProgressPercent,
"retries": j.Retries,
})
}
c.JSON(http.StatusOK, gin.H{"jobs": jobList, "job_type": jobType})
}
// GetConfigAPI returns the configuration for a job type
func (h *PluginHandlers) GetConfigAPI(c *gin.Context) {
jobType := c.Param("jobType")
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
config, err := h.adminServer.PluginManager.GetConfig(jobType)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("config not found: %v", err)})
return
}
adminConfigMap := convertConfigFieldsToMap(config.AdminConfig)
workerConfigMap := convertConfigFieldsToMap(config.WorkerConfig)
c.JSON(http.StatusOK, gin.H{
"job_type": jobType,
"enabled": config.Enabled,
"admin_config": adminConfigMap,
"worker_config": workerConfigMap,
"created_at": config.CreatedAt,
"updated_at": config.UpdatedAt,
"created_by": config.CreatedBy,
})
}
// SaveConfigAPI saves the configuration for a job type
func (h *PluginHandlers) SaveConfigAPI(c *gin.Context) {
jobType := c.Param("jobType")
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
var req struct {
Enabled bool `json:"enabled"`
AdminConfig map[string]interface{} `json:"admin_config"`
WorkerConfig map[string]interface{} `json:"worker_config"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid request: %v", err)})
return
}
// Convert maps back to config fields
adminConfigFields := convertMapToConfigFields(req.AdminConfig)
workerConfigFields := convertMapToConfigFields(req.WorkerConfig)
err := h.adminServer.PluginManager.SaveConfig(jobType, req.Enabled, adminConfigFields, workerConfigFields)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to save config: %v", err)})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "message": "configuration saved"})
}
// GetDetectionHistoryAPI returns detection history for a job type
func (h *PluginHandlers) GetDetectionHistoryAPI(c *gin.Context) {
jobType := c.Param("jobType")
limitStr := c.DefaultQuery("limit", "10")
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
limit, err := strconv.Atoi(limitStr)
if err != nil || limit > 100 {
limit = 10
}
records := h.adminServer.PluginManager.GetDetectionHistory(jobType, limit)
var historyList []map[string]interface{}
for _, rec := range records {
historyList = append(historyList, map[string]interface{}{
"timestamp": rec.Timestamp,
"duration_ms": rec.DurationMs,
"jobs_detected": rec.JobsDetected,
"status": rec.Status,
"error": rec.Error,
"worker_id": rec.WorkerID,
"detailed_logs": rec.DetailedLogs,
})
}
c.JSON(http.StatusOK, gin.H{
"job_type": jobType,
"history": historyList,
"count": len(historyList),
})
}
// GetExecutionHistoryAPI returns execution history for a job type
func (h *PluginHandlers) GetExecutionHistoryAPI(c *gin.Context) {
jobType := c.Param("jobType")
limitStr := c.DefaultQuery("limit", "10")
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
limit, err := strconv.Atoi(limitStr)
if err != nil || limit > 100 {
limit = 10
}
records := h.adminServer.PluginManager.GetExecutionHistory(jobType, limit)
var historyList []map[string]interface{}
for _, rec := range records {
historyList = append(historyList, map[string]interface{}{
"job_id": rec.JobID,
"job_type": rec.JobType,
"started_at": rec.StartedAt,
"completed_at": rec.CompletedAt,
"duration_ms": rec.DurationMs,
"success": rec.Success,
"error": rec.Error,
"worker_id": rec.WorkerID,
"items_processed": rec.ItemsProcessed,
"execution_logs": rec.ExecutionLogs,
})
}
c.JSON(http.StatusOK, gin.H{
"job_type": jobType,
"history": historyList,
"count": len(historyList),
})
}
// TriggerDetectionAPI manually triggers detection for a job type
func (h *PluginHandlers) TriggerDetectionAPI(c *gin.Context) {
jobType := c.Param("jobType")
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
err := h.adminServer.PluginManager.TriggerDetection(jobType)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("detection failed: %v", err)})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "message": "detection triggered"})
}
// CancelJobAPI cancels a running job
func (h *PluginHandlers) CancelJobAPI(c *gin.Context) {
jobID := c.Param("jobID")
if h.adminServer.PluginManager == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "plugin manager not available"})
return
}
err := h.adminServer.PluginManager.CancelJob(jobID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("cancel failed: %v", err)})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "message": "job cancelled"})
}
// getPluginsData prepares data for the main plugins page
func (h *PluginHandlers) getPluginsData() map[string]interface{} {
data := map[string]interface{}{
"plugins": []map[string]interface{}{},
"job_types": []string{},
"total_plugins": 0,
"total_jobs": 0,
}
if h.adminServer.PluginManager == nil {
return data
}
// Get connected plugins
plugins := h.adminServer.PluginManager.ListConnectedPlugins()
var pluginList []map[string]interface{}
for _, p := range plugins {
pluginList = append(pluginList, map[string]interface{}{
"id": p.ID,
"name": p.Name,
"version": p.Version,
"connected_at": p.ConnectedAt.Format(time.RFC3339),
"state": p.State.String(),
"healthy": p.IsHealthy(),
"pending_jobs": p.PendingJobs,
"running_jobs": p.RunningJobs,
"cpu_usage": fmt.Sprintf("%.1f%%", p.CPUUsagePercent),
"memory_usage": fmt.Sprintf("%.1f MB", p.MemoryUsageMB),
})
}
// Get registered job types
jobTypes := h.adminServer.PluginManager.ListJobTypes()
sort.Strings(jobTypes) // Sort alphabetically
// Count jobs
totalJobs := 0
for _, jobType := range jobTypes {
jobs := h.adminServer.PluginManager.ListJobs(jobType, 0)
totalJobs += len(jobs)
}
data["plugins"] = pluginList
data["job_types"] = jobTypes
data["total_plugins"] = len(plugins)
data["total_jobs"] = totalJobs
return data
}
// getJobsData prepares data for the job monitoring page
func (h *PluginHandlers) getJobsData(jobType string) map[string]interface{} {
data := map[string]interface{}{
"job_type": jobType,
"jobs": []map[string]interface{}{},
"pending_count": 0,
"running_count": 0,
"completed_count": 0,
"failed_count": 0,
}
if h.adminServer.PluginManager == nil {
return data
}
// Get all jobs for this type
allJobs := h.adminServer.PluginManager.ListJobs(jobType, 0)
var jobsList []map[string]interface{}
pendingCount, runningCount, completedCount, failedCount := 0, 0, 0, 0
for _, job := range allJobs {
jobsList = append(jobsList, map[string]interface{}{
"id": job.ID,
"description": job.Description,
"state": job.State.String(),
"created_at": job.CreatedAt.Format(time.RFC3339),
"updated_at": job.UpdatedAt.Format(time.RFC3339),
"progress": job.ProgressPercent,
"executor_id": job.ExecutorID,
"retries": job.Retries,
})
switch job.State {
case plugin.JobStatePending:
pendingCount++
case plugin.JobStateRunning:
runningCount++
case plugin.JobStateCompleted:
completedCount++
case plugin.JobStateFailed:
failedCount++
}
}
data["jobs"] = jobsList
data["pending_count"] = pendingCount
data["running_count"] = runningCount
data["completed_count"] = completedCount
data["failed_count"] = failedCount
return data
}
// getPluginConfigData prepares data for the plugin configuration page
func (h *PluginHandlers) getPluginConfigData(jobType string) map[string]interface{} {
data := map[string]interface{}{
"job_type": jobType,
"enabled": false,
"admin_config": map[string]interface{}{},
"worker_config": map[string]interface{}{},
"schema": map[string]interface{}{},
"detection_history": []map[string]interface{}{},
"execution_history": []map[string]interface{}{},
}
if h.adminServer.PluginManager == nil {
return data
}
// Get config
config, err := h.adminServer.PluginManager.GetConfig(jobType)
if err == nil && config != nil {
data["enabled"] = config.Enabled
data["admin_config"] = convertConfigFieldsToMap(config.AdminConfig)
data["worker_config"] = convertConfigFieldsToMap(config.WorkerConfig)
}
// Get schema
// detector, err := h.adminServer.PluginManager.GetDetectorForJobType(jobType)
// if err == nil && detector != nil {
// data["schema"] = detector.ConfigSchema // Will be extended later
// }
// Get detection history
detectionRecords := h.adminServer.PluginManager.GetDetectionHistory(jobType, 10)
var detectionList []map[string]interface{}
for _, rec := range detectionRecords {
detectionList = append(detectionList, map[string]interface{}{
"timestamp": rec.Timestamp.Format(time.RFC3339),
"duration_ms": rec.DurationMs,
"jobs_detected": rec.JobsDetected,
"status": rec.Status,
"error": rec.Error,
"detailed_logs": rec.DetailedLogs,
})
}
data["detection_history"] = detectionList
// Get execution history
executionRecords := h.adminServer.PluginManager.GetExecutionHistory(jobType, 10)
var executionList []map[string]interface{}
for _, rec := range executionRecords {
executionList = append(executionList, map[string]interface{}{
"job_id": rec.JobID,
"started_at": rec.StartedAt.Format(time.RFC3339),
"completed_at": rec.CompletedAt.Format(time.RFC3339),
"duration_ms": rec.DurationMs,
"success": rec.Success,
"error": rec.Error,
"items_processed": rec.ItemsProcessed,
})
}
data["execution_history"] = executionList
return data
}
// Helper functions to convert between data formats
func convertConfigFieldsToMap(fields []*plugin_pb.ConfigFieldValue) map[string]interface{} {
result := make(map[string]interface{})
for _, field := range fields {
if field == nil {
continue
}
if field.StringValue != "" {
result[field.FieldName] = field.StringValue
} else if field.IntValue != 0 {
result[field.FieldName] = field.IntValue
} else if field.FloatValue != 0 {
result[field.FieldName] = field.FloatValue
} else if field.BoolValue {
result[field.FieldName] = field.BoolValue
} else if field.JsonValue != "" {
result[field.FieldName] = field.JsonValue
}
}
return result
}
func convertMapToConfigFields(m map[string]interface{}) []*plugin_pb.ConfigFieldValue {
var fields []*plugin_pb.ConfigFieldValue
for k, v := range m {
field := &plugin_pb.ConfigFieldValue{FieldName: k}
switch val := v.(type) {
case string:
field.StringValue = val
case float64:
// Try to detect if it's an int or bool
if val == float64(int64(val)) {
field.IntValue = int64(val)
} else {
field.FloatValue = float32(val)
}
case bool:
field.BoolValue = val
case int:
field.IntValue = int64(val)
}
fields = append(fields, field)
}
return fields
}
// convertConfigSchemaToMap converts schema to a map (placeholder for future use)
// func convertConfigSchemaToMap(schema interface{}) map[string]interface{} {
// // TODO: implement schema conversion when schema structure is finalized
// return make(map[string]interface{})
// }
-307
View File
@@ -1,307 +0,0 @@
package plugin
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// ConfigManager handles configuration persistence and retrieval
type ConfigManager struct {
dataDir string
configs map[string]*JobTypeConfig
mu sync.RWMutex
}
// NewConfigManager creates a new configuration manager
func NewConfigManager(dataDir string) (*ConfigManager, error) {
cm := &ConfigManager{
dataDir: filepath.Join(dataDir, "plugins"),
configs: make(map[string]*JobTypeConfig),
}
// Create plugins directory if it doesn't exist
if err := os.MkdirAll(cm.dataDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create plugin config directory: %w", err)
}
return cm, nil
}
// LoadConfig loads a configuration from disk
func (cm *ConfigManager) LoadConfig(jobType string) (*JobTypeConfig, error) {
cm.mu.Lock()
defer cm.mu.Unlock()
// Check cache first
if config, exists := cm.configs[jobType]; exists {
return config, nil
}
configPath := filepath.Join(cm.dataDir, jobType+".json")
// If file doesn't exist, create default config
if _, err := os.Stat(configPath); err != nil {
if os.IsNotExist(err) {
config := &JobTypeConfig{
JobType: jobType,
Enabled: false,
AdminConfig: make([]*plugin_pb.ConfigFieldValue, 0),
WorkerConfig: make([]*plugin_pb.ConfigFieldValue, 0),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
CreatedBy: "system",
}
cm.configs[jobType] = config
return config, nil
}
return nil, fmt.Errorf("failed to access config file: %w", err)
}
// Load from file
data, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
var configData map[string]interface{}
if err := json.Unmarshal(data, &configData); err != nil {
return nil, fmt.Errorf("failed to parse config file: %w", err)
}
config := &JobTypeConfig{
JobType: jobType,
AdminConfig: make([]*plugin_pb.ConfigFieldValue, 0),
WorkerConfig: make([]*plugin_pb.ConfigFieldValue, 0),
}
// Parse fields
if enabled, ok := configData["enabled"].(bool); ok {
config.Enabled = enabled
}
if createdBy, ok := configData["created_by"].(string); ok {
config.CreatedBy = createdBy
}
if createdAt, ok := configData["created_at"].(string); ok {
if t, err := time.Parse(time.RFC3339, createdAt); err == nil {
config.CreatedAt = t
}
}
if updatedAt, ok := configData["updated_at"].(string); ok {
if t, err := time.Parse(time.RFC3339, updatedAt); err == nil {
config.UpdatedAt = t
}
}
cm.configs[jobType] = config
return config, nil
}
// SaveConfig saves a configuration to disk
func (cm *ConfigManager) SaveConfig(config *JobTypeConfig) error {
cm.mu.Lock()
defer cm.mu.Unlock()
config.UpdatedAt = time.Now()
cm.configs[config.JobType] = config
configPath := filepath.Join(cm.dataDir, config.JobType+".json")
// Convert to JSON-serializable format
configData := map[string]interface{}{
"job_type": config.JobType,
"enabled": config.Enabled,
"created_by": config.CreatedBy,
"created_at": config.CreatedAt.Format(time.RFC3339),
"updated_at": config.UpdatedAt.Format(time.RFC3339),
"admin_config": cm.configValuesToJSON(config.AdminConfig),
"worker_config": cm.configValuesToJSON(config.WorkerConfig),
}
data, err := json.MarshalIndent(configData, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal config: %w", err)
}
if err := os.WriteFile(configPath, data, 0644); err != nil {
return fmt.Errorf("failed to write config file: %w", err)
}
return nil
}
// GetConfig retrieves a configuration
func (cm *ConfigManager) GetConfig(jobType string) (*JobTypeConfig, error) {
cm.mu.RLock()
if config, exists := cm.configs[jobType]; exists {
cm.mu.RUnlock()
return config, nil
}
cm.mu.RUnlock()
// Load from disk if not in cache
return cm.LoadConfig(jobType)
}
// UpdateConfig updates a configuration
func (cm *ConfigManager) UpdateConfig(jobType string, enabled bool, adminConfig, workerConfig []*plugin_pb.ConfigFieldValue, updatedBy string) (*JobTypeConfig, error) {
config, err := cm.GetConfig(jobType)
if err != nil {
return nil, err
}
config.SetConfig(enabled, adminConfig, workerConfig)
config.CreatedBy = updatedBy
if err := cm.SaveConfig(config); err != nil {
return nil, err
}
return config, nil
}
// ListConfigs lists all configurations
func (cm *ConfigManager) ListConfigs() []*JobTypeConfig {
cm.mu.RLock()
defer cm.mu.RUnlock()
configs := make([]*JobTypeConfig, 0, len(cm.configs))
for _, config := range cm.configs {
configs = append(configs, config)
}
return configs
}
// DeleteConfig deletes a configuration
func (cm *ConfigManager) DeleteConfig(jobType string) error {
cm.mu.Lock()
defer cm.mu.Unlock()
configPath := filepath.Join(cm.dataDir, jobType+".json")
if err := os.Remove(configPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to delete config file: %w", err)
}
delete(cm.configs, jobType)
return nil
}
// configValuesToJSON converts ConfigFieldValue slice to JSON
func (cm *ConfigManager) configValuesToJSON(values []*plugin_pb.ConfigFieldValue) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(values))
for _, val := range values {
item := map[string]interface{}{
"field_name": val.FieldName,
}
// Include non-empty values
if val.StringValue != "" {
item["string_value"] = val.StringValue
}
if val.IntValue != 0 {
item["int_value"] = val.IntValue
}
if val.FloatValue != 0 {
item["float_value"] = val.FloatValue
}
if val.BoolValue {
item["bool_value"] = val.BoolValue
}
if val.DurationValue != nil {
item["duration_value"] = val.DurationValue.String()
}
if len(val.MultiselectValues) > 0 {
item["multiselect_values"] = val.MultiselectValues
}
if val.JsonValue != "" {
item["json_value"] = val.JsonValue
}
result = append(result, item)
}
return result
}
// LoadAllConfigs loads all configurations from disk
func (cm *ConfigManager) LoadAllConfigs() error {
cm.mu.Lock()
defer cm.mu.Unlock()
entries, err := os.ReadDir(cm.dataDir)
if err != nil {
return fmt.Errorf("failed to read config directory: %w", err)
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
// Only load .json files
if filepath.Ext(entry.Name()) != ".json" {
continue
}
jobType := entry.Name()[:len(entry.Name())-5] // Remove .json
configPath := filepath.Join(cm.dataDir, entry.Name())
data, err := os.ReadFile(configPath)
if err != nil {
continue
}
var configData map[string]interface{}
if err := json.Unmarshal(data, &configData); err != nil {
continue
}
config := &JobTypeConfig{
JobType: jobType,
AdminConfig: make([]*plugin_pb.ConfigFieldValue, 0),
WorkerConfig: make([]*plugin_pb.ConfigFieldValue, 0),
}
// Parse fields
if enabled, ok := configData["enabled"].(bool); ok {
config.Enabled = enabled
}
if createdBy, ok := configData["created_by"].(string); ok {
config.CreatedBy = createdBy
}
if createdAt, ok := configData["created_at"].(string); ok {
if t, err := time.Parse(time.RFC3339, createdAt); err == nil {
config.CreatedAt = t
}
}
if updatedAt, ok := configData["updated_at"].(string); ok {
if t, err := time.Parse(time.RFC3339, updatedAt); err == nil {
config.UpdatedAt = t
}
}
cm.configs[jobType] = config
}
return nil
}
// GetDataDir returns the data directory path
func (cm *ConfigManager) GetDataDir() string {
return cm.dataDir
}
-390
View File
@@ -1,390 +0,0 @@
package plugin
import (
"context"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/grpc"
)
// Dispatcher handles job detection and dispatch to executors
type Dispatcher struct {
registry *Registry
queues map[string]*JobQueue
configMgr *ConfigManager
mu sync.RWMutex
// Detection scheduling
detectionIntervals map[string]time.Duration
detectionTickers map[string]*time.Ticker
stopChan chan struct{}
// Job counter for ID generation
jobCounter uint64
jobCounterMu sync.Mutex
// Active streams for execution
executionStreams map[string]*ExecutionStream
streamsMu sync.RWMutex
}
// ExecutionStream tracks an active job execution stream
type ExecutionStream struct {
JobID string
PluginID string
Connection *grpc.ClientConn
Context context.Context
Cancel context.CancelFunc
StartTime time.Time
LastUpdate time.Time
}
// NewDispatcher creates a new job dispatcher
func NewDispatcher(registry *Registry, configMgr *ConfigManager) *Dispatcher {
return &Dispatcher{
registry: registry,
queues: make(map[string]*JobQueue),
configMgr: configMgr,
detectionIntervals: make(map[string]time.Duration),
detectionTickers: make(map[string]*time.Ticker),
stopChan: make(chan struct{}),
executionStreams: make(map[string]*ExecutionStream),
}
}
// RegisterJobType registers a job type for detection and dispatch
func (d *Dispatcher) RegisterJobType(jobType string, detectionInterval time.Duration) error {
d.mu.Lock()
defer d.mu.Unlock()
if _, exists := d.queues[jobType]; exists {
return fmt.Errorf("job type %s already registered", jobType)
}
d.queues[jobType] = NewJobQueue(jobType)
d.detectionIntervals[jobType] = detectionInterval
return nil
}
// Start starts the dispatcher with detection scheduling
func (d *Dispatcher) Start() {
d.mu.Lock()
defer d.mu.Unlock()
for jobType, interval := range d.detectionIntervals {
ticker := time.NewTicker(interval)
d.detectionTickers[jobType] = ticker
go d.detectionLoop(jobType, ticker)
}
}
// Stop stops the dispatcher
func (d *Dispatcher) Stop() {
close(d.stopChan)
d.mu.Lock()
defer d.mu.Unlock()
for _, ticker := range d.detectionTickers {
ticker.Stop()
}
}
// detectionLoop periodically runs detection for a job type
func (d *Dispatcher) detectionLoop(jobType string, ticker *time.Ticker) {
for {
select {
case <-ticker.C:
d.runDetection(jobType)
case <-d.stopChan:
return
}
}
}
// runDetection runs detection for a job type and queues detected jobs
func (d *Dispatcher) runDetection(jobType string) {
// Get detector plugin
_, err := d.registry.GetDetectorForJobType(jobType)
if err != nil {
// No detector available, skip
return
}
// Get job type config
config, err := d.configMgr.GetConfig(jobType)
if err != nil || !config.Enabled {
// Config not found or disabled, skip
return
}
// TODO: Call detector plugin's DetectJobs method
// For now, this is a placeholder for the gRPC call
}
// QueueJob adds a job to the queue
func (d *Dispatcher) QueueJob(jobType string, req *plugin_pb.JobRequest, dedupKey string) (*Job, error) {
d.mu.RLock()
queue, exists := d.queues[jobType]
d.mu.RUnlock()
if !exists {
return nil, fmt.Errorf("job type %s not registered", jobType)
}
// Generate job ID
jobID := d.generateJobID()
return queue.AddJob(jobID, req, dedupKey)
}
// DispatchJob assigns a job to an available executor
func (d *Dispatcher) DispatchJob(jobType string) (*Job, *ConnectedPlugin, error) {
d.mu.RLock()
queue, exists := d.queues[jobType]
d.mu.RUnlock()
if !exists {
return nil, nil, fmt.Errorf("job type %s not registered", jobType)
}
// Get next pending job
job, err := queue.GetPendingJob()
if err != nil {
return nil, nil, err
}
// Get available executor
executor, err := d.registry.GetExecutorForJobType(jobType)
if err != nil {
// Put job back in queue
queue.mu.Lock()
queue.pendingQueue = append(queue.pendingQueue, job)
queue.mu.Unlock()
return nil, nil, err
}
job.ExecutorID = executor.ID
return job, executor, nil
}
// GetJob retrieves a job by ID across all queues
func (d *Dispatcher) GetJob(jobID string) (*Job, error) {
d.mu.RLock()
defer d.mu.RUnlock()
for _, queue := range d.queues {
job, err := queue.GetJob(jobID)
if err == nil {
return job, nil
}
}
return nil, fmt.Errorf("job %s not found", jobID)
}
// ListJobs returns jobs of a specific type and status
func (d *Dispatcher) ListJobs(jobType string, status JobState) []*Job {
d.mu.RLock()
queue, exists := d.queues[jobType]
d.mu.RUnlock()
if !exists {
return nil
}
return queue.ListJobs(status, 0)
}
// ListAllJobs returns all jobs across all queues
func (d *Dispatcher) ListAllJobs() []*Job {
d.mu.RLock()
defer d.mu.RUnlock()
var jobs []*Job
for _, queue := range d.queues {
jobs = append(jobs, queue.ListAllJobs()...)
}
return jobs
}
// UpdateJobProgress updates job progress
func (d *Dispatcher) UpdateJobProgress(jobID string, percent int32) error {
job, err := d.GetJob(jobID)
if err != nil {
return err
}
job.SetProgress(percent)
return nil
}
// CompleteJob marks a job as complete
func (d *Dispatcher) CompleteJob(jobID string, completed *plugin_pb.JobCompleted) error {
job, err := d.GetJob(jobID)
if err != nil {
return err
}
d.mu.RLock()
queue, exists := d.queues[job.Type]
d.mu.RUnlock()
if !exists {
return fmt.Errorf("job type %s not found", job.Type)
}
d.removeExecutionStream(jobID)
return queue.CompleteJob(jobID, completed)
}
// FailJob marks a job as failed
func (d *Dispatcher) FailJob(jobID string, failed *plugin_pb.JobFailed) error {
job, err := d.GetJob(jobID)
if err != nil {
return err
}
d.mu.RLock()
queue, exists := d.queues[job.Type]
d.mu.RUnlock()
if !exists {
return fmt.Errorf("job type %s not found", job.Type)
}
d.removeExecutionStream(jobID)
_, err = queue.FailJob(jobID, failed)
return err
}
// CancelJob cancels a job
func (d *Dispatcher) CancelJob(jobID string) error {
job, err := d.GetJob(jobID)
if err != nil {
return err
}
d.mu.RLock()
queue, exists := d.queues[job.Type]
d.mu.RUnlock()
if !exists {
return fmt.Errorf("job type %s not found", job.Type)
}
d.removeExecutionStream(jobID)
return queue.CancelJob(jobID)
}
// RetryJob retries a failed job
func (d *Dispatcher) RetryJob(jobID string) error {
job, err := d.GetJob(jobID)
if err != nil {
return err
}
state := job.GetState()
if state != JobStateFailed {
return fmt.Errorf("can only retry failed jobs, job is in %s state", state.String())
}
d.mu.RLock()
queue, exists := d.queues[job.Type]
d.mu.RUnlock()
if !exists {
return fmt.Errorf("job type %s not found", job.Type)
}
job.SetState(JobStatePending)
job.Retries++
queue.mu.Lock()
queue.pendingQueue = append(queue.pendingQueue, job)
queue.sortPendingQueue()
queue.mu.Unlock()
return nil
}
// generateJobID generates a unique job ID
func (d *Dispatcher) generateJobID() string {
d.jobCounterMu.Lock()
defer d.jobCounterMu.Unlock()
d.jobCounter++
return fmt.Sprintf("job-%d-%d", time.Now().Unix(), d.jobCounter)
}
// RegisterExecutionStream registers a new execution stream
func (d *Dispatcher) RegisterExecutionStream(jobID, pluginID string, ctx context.Context) *ExecutionStream {
d.streamsMu.Lock()
defer d.streamsMu.Unlock()
cancelCtx, cancel := context.WithCancel(ctx)
stream := &ExecutionStream{
JobID: jobID,
PluginID: pluginID,
Context: cancelCtx,
Cancel: cancel,
StartTime: time.Now(),
LastUpdate: time.Now(),
}
d.executionStreams[jobID] = stream
return stream
}
// removeExecutionStream removes an execution stream
func (d *Dispatcher) removeExecutionStream(jobID string) {
d.streamsMu.Lock()
defer d.streamsMu.Unlock()
stream, exists := d.executionStreams[jobID]
if exists {
stream.Cancel()
delete(d.executionStreams, jobID)
}
}
// GetStats returns dispatcher statistics
func (d *Dispatcher) GetStats() map[string]interface{} {
d.mu.RLock()
defer d.mu.RUnlock()
queueStats := make(map[string]interface{})
for jobType, queue := range d.queues {
queueStats[jobType] = queue.GetStats()
}
d.streamsMu.RLock()
activeStreams := len(d.executionStreams)
d.streamsMu.RUnlock()
return map[string]interface{}{
"queue_stats": queueStats,
"active_streams": activeStreams,
"registered_types": len(d.queues),
}
}
// TriggerDetection manually triggers detection for a job type
func (d *Dispatcher) TriggerDetection(jobType string, detector interface{}, config *JobTypeConfig) error {
// Record the detection run
record := &DetectionRecord{
Timestamp: time.Now(),
JobsDetected: 0,
Status: "started",
}
// TODO: Call detector to run detection
// For now, mark as completed with no jobs detected
record.DurationMs = 0
record.Status = "completed"
return nil
}
-461
View File
@@ -1,461 +0,0 @@
package plugin
import (
"context"
"fmt"
"io"
"sync"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/grpc"
)
// GrpcServer implements the plugin gRPC service
type GrpcServer struct {
plugin_pb.UnimplementedPluginServiceServer
plugin_pb.UnimplementedAdminQueryServiceServer
plugin_pb.UnimplementedAdminCommandServiceServer
registry *Registry
dispatcher *Dispatcher
configMgr *ConfigManager
// Active connections
connections map[string]*grpc.ClientStream
connMu sync.RWMutex
}
// NewGrpcServer creates a new gRPC server
func NewGrpcServer(registry *Registry, dispatcher *Dispatcher, configMgr *ConfigManager) *GrpcServer {
return &GrpcServer{
registry: registry,
dispatcher: dispatcher,
configMgr: configMgr,
connections: make(map[string]*grpc.ClientStream),
}
}
// ============================================================================
// PluginService Implementation
// ============================================================================
// Connect handles bidirectional streaming for plugin registration and lifecycle
func (s *GrpcServer) Connect(stream grpc.BidiStreamingServer[plugin_pb.PluginMessage, plugin_pb.AdminMessage]) error {
var pluginID string
for {
msg, err := stream.Recv()
if err == io.EOF {
// Stream closed normally
if pluginID != "" {
s.registry.UnregisterPlugin(pluginID)
}
return nil
}
if err != nil {
return err
}
// Handle different message types
switch content := msg.Content.(type) {
case *plugin_pb.PluginMessage_Register:
register := content.Register
pluginID = register.PluginId
_, _ = s.registry.RegisterPlugin(pluginID, register)
if err != nil {
return err
}
case *plugin_pb.PluginMessage_Heartbeat:
heartbeat := content.Heartbeat
if err := s.registry.UpdateHeartbeat(heartbeat.PluginId, heartbeat); err != nil {
return err
}
case *plugin_pb.PluginMessage_StatusUpdate:
// Handle job status updates
statusUpdate := content.StatusUpdate
if err := s.handleStatusUpdate(statusUpdate); err != nil {
return err
}
}
// Send acknowledgment
adminMsg := &plugin_pb.AdminMessage{
Content: &plugin_pb.AdminMessage_AdminCommand{
AdminCommand: &plugin_pb.AdminCommand{
CommandType: plugin_pb.AdminCommand_RELOAD_CONFIG,
},
},
}
if err := stream.Send(adminMsg); err != nil {
if pluginID != "" {
s.registry.UnregisterPlugin(pluginID)
}
return err
}
}
}
// ExecuteJob handles bidirectional streaming for job execution
func (s *GrpcServer) ExecuteJob(stream grpc.BidiStreamingServer[plugin_pb.JobExecutionMessage, plugin_pb.JobProgressMessage]) error {
var jobID string
for {
execMsg, err := stream.Recv()
if err == io.EOF {
// Stream closed normally
return nil
}
if err != nil {
return err
}
jobID = execMsg.JobId
// Handle different execution message types
switch content := execMsg.Content.(type) {
case *plugin_pb.JobExecutionMessage_JobStarted:
started := content.JobStarted
if err := s.handleJobStarted(jobID, started); err != nil {
return err
}
case *plugin_pb.JobExecutionMessage_Progress:
progress := content.Progress
if err := s.dispatcher.UpdateJobProgress(jobID, progress.ProgressPercent); err != nil {
return err
}
case *plugin_pb.JobExecutionMessage_Checkpoint:
checkpoint := content.Checkpoint
// Store checkpoint for resumption
if err := s.storeCheckpoint(jobID, checkpoint); err != nil {
return err
}
case *plugin_pb.JobExecutionMessage_JobCompleted:
completed := content.JobCompleted
if err := s.dispatcher.CompleteJob(jobID, completed); err != nil {
return err
}
case *plugin_pb.JobExecutionMessage_JobFailed:
failed := content.JobFailed
if err := s.dispatcher.FailJob(jobID, failed); err != nil {
return err
}
case *plugin_pb.JobExecutionMessage_LogEntry:
logEntry := content.LogEntry
if err := s.storeLogEntry(jobID, logEntry); err != nil {
return err
}
}
// Send progress update
progressMsg := &plugin_pb.JobProgressMessage{
JobId: jobID,
Content: &plugin_pb.JobProgressMessage_Update{
Update: &plugin_pb.JobProgressUpdate{
JobId: jobID,
ProgressPercent: 0,
CurrentStep: "processing",
StatusMessage: "Processing job",
Timestamp: nil,
},
},
}
if err := stream.Send(progressMsg); err != nil {
return err
}
}
}
// ============================================================================
// AdminQueryService Implementation
// ============================================================================
// GetPluginStats returns current plugin system statistics
func (s *GrpcServer) GetPluginStats(ctx context.Context, req *emptypb.Empty) (*plugin_pb.PluginStats, error) {
plugins := s.registry.ListPlugins()
jobs := s.dispatcher.ListAllJobs()
var totalJobs, pendingJobs, runningJobs, completedJobs, failedJobs int32
for _, job := range jobs {
totalJobs++
switch job.GetState() {
case JobStatePending:
pendingJobs++
case JobStateRunning:
runningJobs++
case JobStateCompleted:
completedJobs++
case JobStateFailed:
failedJobs++
}
}
stats := &plugin_pb.PluginStats{
TotalPlugins: int32(len(plugins)),
ActivePlugins: int32(len(plugins)),
TotalJobs: totalJobs,
PendingJobs: pendingJobs,
RunningJobs: runningJobs,
CompletedJobs: completedJobs,
FailedJobs: failedJobs,
}
return stats, nil
}
// ListPlugins returns all connected plugins
func (s *GrpcServer) ListPlugins(ctx context.Context, req *emptypb.Empty) (*plugin_pb.PluginList, error) {
plugins := s.registry.ListPlugins()
pluginInfos := make([]*plugin_pb.PluginInfo, 0, len(plugins))
for _, p := range plugins {
info := &plugin_pb.PluginInfo{
PluginId: p.ID,
Name: p.Name,
Version: p.Version,
ProtocolVersion: p.ProtocolVersion,
Healthy: p.IsHealthy(),
Status: p.GetState().String(),
}
// Add capabilities
for _, cap := range p.Capabilities {
info.Capabilities = append(info.Capabilities, cap)
}
pluginInfos = append(pluginInfos, info)
}
return &plugin_pb.PluginList{Plugins: pluginInfos}, nil
}
// ListJobs returns jobs filtered by type and status
func (s *GrpcServer) ListJobs(ctx context.Context, req *plugin_pb.ListJobsRequest) (*plugin_pb.JobList, error) {
var state JobState
switch req.Status {
case plugin_pb.ListJobsRequest_PENDING:
state = JobStatePending
case plugin_pb.ListJobsRequest_RUNNING:
state = JobStateRunning
case plugin_pb.ListJobsRequest_COMPLETED:
state = JobStateCompleted
case plugin_pb.ListJobsRequest_FAILED:
state = JobStateFailed
default:
state = JobStatePending
}
jobs := s.dispatcher.ListJobs(req.JobType, state)
jobPbs := make([]*plugin_pb.Job, 0, len(jobs))
for _, job := range jobs {
jobPb := &plugin_pb.Job{
JobId: job.ID,
JobType: job.Type,
Description: job.Description,
Priority: job.Priority,
CreatedAt: nil,
UpdatedAt: nil,
ExecutorPluginId: job.ExecutorID,
ProgressPercent: job.GetProgress(),
Config: job.Config,
}
jobPbs = append(jobPbs, jobPb)
}
return &plugin_pb.JobList{
Jobs: jobPbs,
TotalCount: int32(len(jobPbs)),
ReturnedCount: int32(len(jobPbs)),
}, nil
}
// GetJob returns detailed job information
func (s *GrpcServer) GetJob(ctx context.Context, req *plugin_pb.GetJobRequest) (*plugin_pb.JobDetail, error) {
job, err := s.dispatcher.GetJob(req.JobId)
if err != nil {
return nil, fmt.Errorf("job not found: %w", err)
}
jobPb := &plugin_pb.Job{
JobId: job.ID,
JobType: job.Type,
Description: job.Description,
Priority: job.Priority,
ExecutorPluginId: job.ExecutorID,
ProgressPercent: job.GetProgress(),
Config: job.Config,
}
detail := &plugin_pb.JobDetail{
Job: jobPb,
LogEntries: job.LogEntries,
CompletionInfo: job.CompletedInfo,
FailureInfo: job.FailedInfo,
CheckpointIds: job.CheckpointIDs,
}
return detail, nil
}
// GetJobExecutionLog returns job execution logs
func (s *GrpcServer) GetJobExecutionLog(req *plugin_pb.GetJobExecutionLogRequest, stream grpc.ServerStreamingServer[plugin_pb.ExecutionLogEntry]) error {
job, err := s.dispatcher.GetJob(req.JobId)
if err != nil {
return fmt.Errorf("job not found: %w", err)
}
// Send log entries
for _, entry := range job.LogEntries {
if err := stream.Send(entry); err != nil {
return err
}
}
return nil
}
// ============================================================================
// AdminCommandService Implementation
// ============================================================================
// UpdateJobTypeConfig updates configuration for a job type
func (s *GrpcServer) UpdateJobTypeConfig(ctx context.Context, req *plugin_pb.UpdateJobTypeConfigRequest) (*plugin_pb.JobTypeConfig, error) {
config := req.Config
_, err := s.configMgr.UpdateConfig(
config.JobType,
config.Enabled,
config.AdminConfig,
config.WorkerConfig,
"admin",
)
if err != nil {
return nil, fmt.Errorf("failed to update config: %w", err)
}
return config, nil
}
// CreateJob creates a new job
func (s *GrpcServer) CreateJob(ctx context.Context, req *plugin_pb.CreateJobRequest) (*plugin_pb.Job, error) {
jobReq := &plugin_pb.JobRequest{
JobType: req.JobType,
Description: req.Description,
Priority: req.Priority,
Config: req.Config,
Metadata: req.Metadata,
RequestSource: "admin",
}
job, err := s.dispatcher.QueueJob(req.JobType, jobReq, "")
if err != nil {
return nil, fmt.Errorf("failed to create job: %w", err)
}
return &plugin_pb.Job{
JobId: job.ID,
JobType: job.Type,
Description: job.Description,
Priority: job.Priority,
ProgressPercent: job.GetProgress(),
Config: job.Config,
}, nil
}
// CancelJob cancels a running job
func (s *GrpcServer) CancelJob(ctx context.Context, req *plugin_pb.CancelJobRequest) (*emptypb.Empty, error) {
if err := s.dispatcher.CancelJob(req.JobId); err != nil {
return nil, fmt.Errorf("failed to cancel job: %w", err)
}
return &emptypb.Empty{}, nil
}
// RetryJob retries a failed job
func (s *GrpcServer) RetryJob(ctx context.Context, req *plugin_pb.RetryJobRequest) (*plugin_pb.Job, error) {
if err := s.dispatcher.RetryJob(req.JobId); err != nil {
return nil, fmt.Errorf("failed to retry job: %w", err)
}
job, err := s.dispatcher.GetJob(req.JobId)
if err != nil {
return nil, fmt.Errorf("job not found: %w", err)
}
return &plugin_pb.Job{
JobId: job.ID,
JobType: job.Type,
Description: job.Description,
Priority: job.Priority,
ProgressPercent: job.GetProgress(),
Config: job.Config,
}, nil
}
// ============================================================================
// Helper Methods
// ============================================================================
// handleStatusUpdate handles execution status updates
func (s *GrpcServer) handleStatusUpdate(update *plugin_pb.ExecutionStatusUpdate) error {
if err := s.dispatcher.UpdateJobProgress(update.JobId, update.ProgressPercent); err != nil {
return err
}
return nil
}
// handleJobStarted handles job start messages
func (s *GrpcServer) handleJobStarted(jobID string, started *plugin_pb.JobStarted) error {
job, err := s.dispatcher.GetJob(jobID)
if err != nil {
return err
}
job.SetState(JobStateRunning)
return nil
}
// storeCheckpoint stores a job checkpoint
func (s *GrpcServer) storeCheckpoint(jobID string, checkpoint *plugin_pb.JobCheckpoint) error {
job, err := s.dispatcher.GetJob(jobID)
if err != nil {
return err
}
job.mu.Lock()
defer job.mu.Unlock()
job.CheckpointIDs = append(job.CheckpointIDs, checkpoint.CheckpointId)
return nil
}
// storeLogEntry stores a log entry for a job
func (s *GrpcServer) storeLogEntry(jobID string, logEntry *plugin_pb.ExecutionLog) error {
job, err := s.dispatcher.GetJob(jobID)
if err != nil {
return err
}
job.mu.Lock()
defer job.mu.Unlock()
job.LogEntries = append(job.LogEntries, &plugin_pb.ExecutionLogEntry{
Timestamp: logEntry.Timestamp,
Level: logEntry.Level,
Message: logEntry.Message,
Context: logEntry.Context,
})
return nil
}
-346
View File
@@ -1,346 +0,0 @@
package plugin
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// JobQueue manages jobs for a specific job type with priority and deduplication
type JobQueue struct {
jobType string
// Active jobs by ID
jobs map[string]*Job
// Priority queue
pendingQueue []*Job
// Completed jobs history (keeps last 1000)
completedHistory []*Job
maxHistorySize int
// Deduplication tracking
seenKeys map[string]bool
mu sync.RWMutex
// Retry configuration
maxRetries int32
retryBackoff time.Duration
retryBackoffMax time.Duration
}
// NewJobQueue creates a new job queue for a job type
func NewJobQueue(jobType string) *JobQueue {
return &JobQueue{
jobType: jobType,
jobs: make(map[string]*Job),
pendingQueue: make([]*Job, 0),
completedHistory: make([]*Job, 0),
maxHistorySize: 1000,
seenKeys: make(map[string]bool),
maxRetries: 3,
retryBackoff: time.Second,
retryBackoffMax: 5 * time.Minute,
}
}
// AddJob adds a new job to the queue with deduplication
func (q *JobQueue) AddJob(jobID string, req *plugin_pb.JobRequest, dedupKey string) (*Job, error) {
q.mu.Lock()
defer q.mu.Unlock()
// Check deduplication
if dedupKey != "" && q.seenKeys[dedupKey] {
return nil, fmt.Errorf("job with key %s already queued", dedupKey)
}
if _, exists := q.jobs[jobID]; exists {
return nil, fmt.Errorf("job %s already exists", jobID)
}
job := &Job{
ID: jobID,
Type: req.JobType,
Description: req.Description,
Priority: req.Priority,
State: JobStatePending,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Config: req.Config,
Metadata: req.Metadata,
Retries: 0,
}
q.jobs[jobID] = job
q.pendingQueue = append(q.pendingQueue, job)
if dedupKey != "" {
q.seenKeys[dedupKey] = true
}
// Sort by priority (higher priority first)
q.sortPendingQueue()
return job, nil
}
// GetPendingJob returns the next job to execute
func (q *JobQueue) GetPendingJob() (*Job, error) {
q.mu.Lock()
defer q.mu.Unlock()
if len(q.pendingQueue) == 0 {
return nil, fmt.Errorf("no pending jobs")
}
job := q.pendingQueue[0]
q.pendingQueue = q.pendingQueue[1:]
job.SetState(JobStateRunning)
return job, nil
}
// GetJob retrieves a job by ID
func (q *JobQueue) GetJob(jobID string) (*Job, error) {
q.mu.RLock()
defer q.mu.RUnlock()
job, exists := q.jobs[jobID]
if !exists {
return nil, fmt.Errorf("job %s not found", jobID)
}
return job, nil
}
// CompleteJob marks a job as completed
func (q *JobQueue) CompleteJob(jobID string, completed *plugin_pb.JobCompleted) error {
q.mu.Lock()
defer q.mu.Unlock()
job, exists := q.jobs[jobID]
if !exists {
return fmt.Errorf("job %s not found", jobID)
}
job.SetState(JobStateCompleted)
job.CompletedInfo = completed
q.addToHistory(job)
return nil
}
// FailJob marks a job as failed and determines if it should be retried
func (q *JobQueue) FailJob(jobID string, failed *plugin_pb.JobFailed) (*Job, error) {
q.mu.Lock()
defer q.mu.Unlock()
job, exists := q.jobs[jobID]
if !exists {
return nil, fmt.Errorf("job %s not found", jobID)
}
job.FailedInfo = failed
// Check if we should retry
if failed.Retryable && job.Retries < q.maxRetries {
job.Retries++
job.LastRetryTime = time.Now()
job.SetState(JobStatePending)
// Add back to queue with exponential backoff for retry
q.pendingQueue = append(q.pendingQueue, job)
q.sortPendingQueue()
return job, nil
}
// No retry, mark as failed
job.SetState(JobStateFailed)
q.addToHistory(job)
return job, nil
}
// PauseJob pauses a running job
func (q *JobQueue) PauseJob(jobID string) error {
q.mu.Lock()
defer q.mu.Unlock()
job, exists := q.jobs[jobID]
if !exists {
return fmt.Errorf("job %s not found", jobID)
}
if job.GetState() != JobStateRunning {
return fmt.Errorf("job %s is not running", jobID)
}
job.SetState(JobStatePaused)
return nil
}
// ResumeJob resumes a paused job
func (q *JobQueue) ResumeJob(jobID string) error {
q.mu.Lock()
defer q.mu.Unlock()
job, exists := q.jobs[jobID]
if !exists {
return fmt.Errorf("job %s not found", jobID)
}
if job.GetState() != JobStatePaused {
return fmt.Errorf("job %s is not paused", jobID)
}
job.SetState(JobStateRunning)
return nil
}
// CancelJob cancels a job
func (q *JobQueue) CancelJob(jobID string) error {
q.mu.Lock()
defer q.mu.Unlock()
job, exists := q.jobs[jobID]
if !exists {
return fmt.Errorf("job %s not found", jobID)
}
state := job.GetState()
if state != JobStatePending && state != JobStateRunning && state != JobStatePaused {
return fmt.Errorf("cannot cancel job in %s state", state.String())
}
job.SetState(JobStateCancelled)
// Remove from pending queue if present
for i, j := range q.pendingQueue {
if j.ID == jobID {
q.pendingQueue = append(q.pendingQueue[:i], q.pendingQueue[i+1:]...)
break
}
}
q.addToHistory(job)
return nil
}
// ListJobs returns jobs filtered by status
func (q *JobQueue) ListJobs(status JobState, limit int) []*Job {
q.mu.RLock()
defer q.mu.RUnlock()
var jobs []*Job
// Include pending jobs from queue
for _, job := range q.pendingQueue {
if job.GetState() == status {
jobs = append(jobs, job)
}
}
// Include all active jobs
for _, job := range q.jobs {
if job.GetState() == status {
jobs = append(jobs, job)
}
}
if limit > 0 && len(jobs) > limit {
jobs = jobs[:limit]
}
return jobs
}
// ListAllJobs returns all jobs
func (q *JobQueue) ListAllJobs() []*Job {
q.mu.RLock()
defer q.mu.RUnlock()
jobs := make([]*Job, 0, len(q.jobs))
for _, job := range q.jobs {
jobs = append(jobs, job)
}
// Add completed history
for _, job := range q.completedHistory {
jobs = append(jobs, job)
}
return jobs
}
// sortPendingQueue sorts the pending queue by priority (higher first)
func (q *JobQueue) sortPendingQueue() {
for i := 0; i < len(q.pendingQueue)-1; i++ {
for j := i + 1; j < len(q.pendingQueue); j++ {
if q.pendingQueue[j].Priority > q.pendingQueue[i].Priority {
q.pendingQueue[i], q.pendingQueue[j] = q.pendingQueue[j], q.pendingQueue[i]
}
}
}
}
// addToHistory adds a completed job to history
func (q *JobQueue) addToHistory(job *Job) {
q.completedHistory = append(q.completedHistory, job)
// Keep only last N entries
if len(q.completedHistory) > q.maxHistorySize {
q.completedHistory = q.completedHistory[len(q.completedHistory)-q.maxHistorySize:]
}
// Remove from active jobs
delete(q.jobs, job.ID)
}
// GetPendingCount returns number of pending jobs
func (q *JobQueue) GetPendingCount() int {
q.mu.RLock()
defer q.mu.RUnlock()
return len(q.pendingQueue)
}
// GetStats returns queue statistics
func (q *JobQueue) GetStats() map[string]interface{} {
q.mu.RLock()
defer q.mu.RUnlock()
var running, completed, failed, cancelled int
for _, job := range q.jobs {
switch job.GetState() {
case JobStateRunning:
running++
case JobStateCompleted:
completed++
case JobStateFailed:
failed++
case JobStateCancelled:
cancelled++
}
}
completed += len(q.completedHistory)
return map[string]interface{}{
"job_type": q.jobType,
"pending": len(q.pendingQueue),
"running": running,
"completed": completed,
"failed": failed,
"cancelled": cancelled,
"total": len(q.jobs) + len(q.completedHistory),
"history_size": len(q.completedHistory),
}
}
-542
View File
@@ -1,542 +0,0 @@
package plugin
import (
"context"
"fmt"
"net"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/grpc"
)
// Manager is the main plugin system manager
type Manager struct {
registry *Registry
dispatcher *Dispatcher
configMgr *ConfigManager
grpcServer *GrpcServer
// gRPC server
grpcListener net.Listener
grpc *grpc.Server
// Configuration
listenAddr string
dataDir string
healthCheckInterval time.Duration
// State
mu sync.RWMutex
running bool
stopChan chan struct{}
}
// NewManager creates a new plugin manager
func NewManager(listenAddr, dataDir string) (*Manager, error) {
// Create configuration manager
configMgr, err := NewConfigManager(dataDir)
if err != nil {
return nil, fmt.Errorf("failed to create config manager: %w", err)
}
// Create registry
registry := NewRegistry()
// Create dispatcher
dispatcher := NewDispatcher(registry, configMgr)
// Create gRPC server implementation
grpcServer := NewGrpcServer(registry, dispatcher, configMgr)
return &Manager{
registry: registry,
dispatcher: dispatcher,
configMgr: configMgr,
grpcServer: grpcServer,
listenAddr: listenAddr,
dataDir: dataDir,
healthCheckInterval: 30 * time.Second,
stopChan: make(chan struct{}),
}, nil
}
// Start starts the plugin manager and gRPC server
func (m *Manager) Start() error {
m.mu.Lock()
defer m.mu.Unlock()
if m.running {
return fmt.Errorf("plugin manager already running")
}
// Start registry health checks
m.registry.Start()
// Start dispatcher
m.dispatcher.Start()
// Create gRPC server
m.grpc = grpc.NewServer()
// Register services
plugin_pb.RegisterPluginServiceServer(m.grpc, m.grpcServer)
plugin_pb.RegisterAdminQueryServiceServer(m.grpc, m.grpcServer)
plugin_pb.RegisterAdminCommandServiceServer(m.grpc, m.grpcServer)
// Start listening
listener, err := net.Listen("tcp", m.listenAddr)
if err != nil {
return fmt.Errorf("failed to listen on %s: %w", m.listenAddr, err)
}
m.grpcListener = listener
// Start gRPC server in background
go func() {
if err := m.grpc.Serve(listener); err != nil && err != grpc.ErrServerStopped {
fmt.Printf("gRPC server error: %v\n", err)
}
}()
m.running = true
fmt.Printf("Plugin manager started on %s\n", m.listenAddr)
return nil
}
// Stop stops the plugin manager and gRPC server
func (m *Manager) Stop() error {
m.mu.Lock()
defer m.mu.Unlock()
if !m.running {
return fmt.Errorf("plugin manager not running")
}
close(m.stopChan)
// Stop dispatcher
m.dispatcher.Stop()
// Stop registry
m.registry.Stop()
// Stop gRPC server
if m.grpc != nil {
m.grpc.GracefulStop()
}
m.running = false
return nil
}
// IsRunning returns whether the manager is running
func (m *Manager) IsRunning() bool {
m.mu.RLock()
defer m.mu.RUnlock()
return m.running
}
// RegisterJobType registers a job type for detection and execution
func (m *Manager) RegisterJobType(jobType string, detectionInterval time.Duration) error {
m.mu.RLock()
running := m.running
m.mu.RUnlock()
if !running {
return fmt.Errorf("plugin manager not running")
}
// Register job type
if err := m.dispatcher.RegisterJobType(jobType, detectionInterval); err != nil {
return err
}
_, err := m.configMgr.LoadConfig(jobType)
if err != nil {
return err
}
return nil
}
// QueueJob queues a new job for execution
func (m *Manager) QueueJob(jobType string, description string, priority int64, metadata map[string]string) (*Job, error) {
m.mu.RLock()
running := m.running
m.mu.RUnlock()
if !running {
return nil, fmt.Errorf("plugin manager not running")
}
jobReq := &plugin_pb.JobRequest{
JobType: jobType,
Description: description,
Priority: priority,
Metadata: metadata,
RequestSource: "admin",
}
return m.dispatcher.QueueJob(jobType, jobReq, "")
}
// DispatchJob dispatches the next available job
func (m *Manager) DispatchJob(jobType string) (*Job, *ConnectedPlugin, error) {
m.mu.RLock()
running := m.running
m.mu.RUnlock()
if !running {
return nil, nil, fmt.Errorf("plugin manager not running")
}
return m.dispatcher.DispatchJob(jobType)
}
// GetJob retrieves a job by ID
func (m *Manager) GetJob(jobID string) (*Job, error) {
return m.dispatcher.GetJob(jobID)
}
// ListJobs returns jobs of a specific type and status
func (m *Manager) ListJobs(jobType string, status JobState) []*Job {
return m.dispatcher.ListJobs(jobType, status)
}
// ListAllJobs returns all jobs
func (m *Manager) ListAllJobs() []*Job {
return m.dispatcher.ListAllJobs()
}
// ListPlugins returns all connected plugins
func (m *Manager) ListPlugins() []*ConnectedPlugin {
return m.registry.ListPlugins()
}
// GetPlugin retrieves a plugin by ID
func (m *Manager) GetPlugin(pluginID string) (*ConnectedPlugin, error) {
return m.registry.GetPlugin(pluginID)
}
// ListPluginsByCapability returns plugins that support a job type
func (m *Manager) ListPluginsByCapability(jobType string) []*ConnectedPlugin {
return m.registry.ListPluginsByCapability(jobType)
}
// UpdateJobTypeConfig updates configuration for a job type
func (m *Manager) UpdateJobTypeConfig(jobType string, enabled bool, config []*plugin_pb.ConfigFieldValue) (*JobTypeConfig, error) {
return m.configMgr.UpdateConfig(jobType, enabled, config, nil, "admin")
}
// GetJobTypeConfig retrieves configuration for a job type
func (m *Manager) GetJobTypeConfig(jobType string) (*JobTypeConfig, error) {
return m.configMgr.GetConfig(jobType)
}
// CancelJob cancels a job
func (m *Manager) CancelJob(jobID string) error {
return m.dispatcher.CancelJob(jobID)
}
// RetryJob retries a failed job
func (m *Manager) RetryJob(jobID string) error {
return m.dispatcher.RetryJob(jobID)
}
// GetStats returns system statistics
func (m *Manager) GetStats() map[string]interface{} {
m.mu.RLock()
running := m.running
m.mu.RUnlock()
stats := map[string]interface{}{
"running": running,
}
if running {
stats["registry"] = m.registry.GetStats()
stats["dispatcher"] = m.dispatcher.GetStats()
}
return stats
}
// WaitForPluginConnection waits for a plugin to connect with timeout
func (m *Manager) WaitForPluginConnection(timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
plugins := m.registry.ListPlugins()
if len(plugins) > 0 {
return nil
}
time.Sleep(100 * time.Millisecond)
}
return fmt.Errorf("no plugin connected within %v", timeout)
}
// CreateTestJob creates a job for testing
func (m *Manager) CreateTestJob(jobType string, description string) (*Job, error) {
return m.QueueJob(jobType, description, 100, map[string]string{
"test": "true",
})
}
// GetHealthStatus returns the health status of the plugin system
func (m *Manager) GetHealthStatus() map[string]interface{} {
m.mu.RLock()
running := m.running
m.mu.RUnlock()
status := map[string]interface{}{
"running": running,
}
if !running {
return status
}
plugins := m.registry.ListPlugins()
var healthyCount int
for _, p := range plugins {
if p.IsHealthy() {
healthyCount++
}
}
jobs := m.dispatcher.ListAllJobs()
var runningJobs, pendingJobs, completedJobs, failedJobs int
for _, job := range jobs {
switch job.GetState() {
case JobStateRunning:
runningJobs++
case JobStatePending:
pendingJobs++
case JobStateCompleted:
completedJobs++
case JobStateFailed:
failedJobs++
}
}
status["plugins"] = map[string]interface{}{
"total": len(plugins),
"healthy": healthyCount,
}
status["jobs"] = map[string]interface{}{
"running": runningJobs,
"pending": pendingJobs,
"completed": completedJobs,
"failed": failedJobs,
"total": len(jobs),
}
return status
}
// LoadAllConfigs loads all configurations from disk
func (m *Manager) LoadAllConfigs() error {
return m.configMgr.LoadAllConfigs()
}
// GetDataDir returns the data directory
func (m *Manager) GetDataDir() string {
return m.configMgr.GetDataDir()
}
// QueryPluginService queries a plugin service for capabilities
func (m *Manager) QueryPluginService(ctx context.Context, pluginID string, addr string) (*plugin_pb.PluginRegister, error) {
// This would be implemented to connect to a plugin and query its capabilities
// For now, return a placeholder error
return nil, fmt.Errorf("not yet implemented")
}
// ExecuteDetection triggers detection for a job type
func (m *Manager) ExecuteDetection(ctx context.Context, jobType string) ([]*DetectedJobInfo, error) {
_, err := m.registry.GetDetectorForJobType(jobType)
if err != nil {
return nil, fmt.Errorf("no detector available for job type %s: %w", jobType, err)
}
// TODO: Call detector plugin's DetectJobs method
// This would require connecting to the plugin and calling its service
return nil, fmt.Errorf("detection not yet implemented")
}
// DetectedJobInfo holds information about a detected job
type DetectedJobInfo struct {
Key string
JobType string
Priority int64
Metadata map[string]string
Timestamp time.Time
}
// GetListenAddr returns the listen address
func (m *Manager) GetListenAddr() string {
m.mu.RLock()
defer m.mu.RUnlock()
return m.listenAddr
}
// GetContext returns a context for the manager
func (m *Manager) GetContext() context.Context {
return context.Background()
}
// Close closes the manager and releases resources
func (m *Manager) Close() error {
if m.IsRunning() {
return m.Stop()
}
return nil
}
// ListConnectedPlugins returns the list of connected plugins
func (m *Manager) ListConnectedPlugins() []*ConnectedPlugin {
return m.registry.ListPlugins()
}
// GetConfig retrieves configuration for a job type
func (m *Manager) GetConfig(jobType string) (*JobTypeConfig, error) {
return m.configMgr.GetConfig(jobType)
}
// SaveConfig saves configuration for a job type
func (m *Manager) SaveConfig(jobType string, enabled bool, adminConfig, workerConfig []*plugin_pb.ConfigFieldValue) error {
config := &JobTypeConfig{
JobType: jobType,
Enabled: enabled,
AdminConfig: adminConfig,
WorkerConfig: workerConfig,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
return m.configMgr.SaveConfig(config)
}
// GetDetectionHistory returns detection history for a job type
func (m *Manager) GetDetectionHistory(jobType string, limit int) []*DetectionRecord {
config, err := m.configMgr.GetConfig(jobType)
if err != nil || config == nil {
return []*DetectionRecord{}
}
config.mu.RLock()
defer config.mu.RUnlock()
// Return in reverse order (latest first)
var result []*DetectionRecord
start := len(config.DetectionHistory) - 1
if start < 0 {
return result
}
for i := start; i >= 0 && len(result) < limit; i-- {
result = append(result, config.DetectionHistory[i])
}
return result
}
// GetExecutionHistory returns execution history for a job type
func (m *Manager) GetExecutionHistory(jobType string, limit int) []*ExecutionRecord {
config, err := m.configMgr.GetConfig(jobType)
if err != nil || config == nil {
return []*ExecutionRecord{}
}
config.mu.RLock()
defer config.mu.RUnlock()
// Return in reverse order (latest first)
var result []*ExecutionRecord
start := len(config.ExecutionHistory) - 1
if start < 0 {
return result
}
for i := start; i >= 0 && len(result) < limit; i-- {
result = append(result, config.ExecutionHistory[i])
}
return result
}
// TriggerDetection manually triggers detection for a job type
func (m *Manager) TriggerDetection(jobType string) error {
detector, err := m.registry.GetDetectorForJobType(jobType)
if err != nil {
return fmt.Errorf("no detector for job type %s", jobType)
}
config, err := m.configMgr.GetConfig(jobType)
if err != nil || !config.Enabled {
return fmt.Errorf("job type %s not enabled", jobType)
}
// Call the dispatcher to run detection
return m.dispatcher.TriggerDetection(jobType, detector, config)
}
// ListJobTypes returns the list of registered job types
func (m *Manager) ListJobTypes() []string {
m.mu.RLock()
defer m.mu.RUnlock()
var jobTypes []string
for jobType := range m.dispatcher.queues {
jobTypes = append(jobTypes, jobType)
}
return jobTypes
}
// GetDetectorForJobType retrieves a detector for a job type
func (m *Manager) GetDetectorForJobType(jobType string) (interface{}, error) {
return m.registry.GetDetectorForJobType(jobType)
}
// RecordDetection records a detection event
func (m *Manager) RecordDetection(jobType string, record *DetectionRecord) error {
config, err := m.configMgr.GetConfig(jobType)
if err != nil || config == nil {
return err
}
config.mu.Lock()
defer config.mu.Unlock()
// Keep last 50 detection records
config.DetectionHistory = append(config.DetectionHistory, record)
if len(config.DetectionHistory) > 50 {
config.DetectionHistory = config.DetectionHistory[len(config.DetectionHistory)-50:]
}
return nil
}
// RecordExecution records a job execution event
func (m *Manager) RecordExecution(jobType string, record *ExecutionRecord) error {
config, err := m.configMgr.GetConfig(jobType)
if err != nil || config == nil {
return err
}
config.mu.Lock()
defer config.mu.Unlock()
// Keep last 100 execution records
config.ExecutionHistory = append(config.ExecutionHistory, record)
if len(config.ExecutionHistory) > 100 {
config.ExecutionHistory = config.ExecutionHistory[len(config.ExecutionHistory)-100:]
}
return nil
}
-333
View File
@@ -1,333 +0,0 @@
package plugin
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// Registry manages all connected plugins and their capabilities
type Registry struct {
plugins map[string]*ConnectedPlugin
// Index by job type and capability (detector/executor)
detectorsByJobType map[string][]*ConnectedPlugin
executorsByJobType map[string][]*ConnectedPlugin
mu sync.RWMutex
// Configuration
healthCheckInterval time.Duration
healthCheckTimeout time.Duration
healthCheckTicker *time.Ticker
stopChan chan struct{}
}
// NewRegistry creates a new plugin registry
func NewRegistry() *Registry {
return &Registry{
plugins: make(map[string]*ConnectedPlugin),
detectorsByJobType: make(map[string][]*ConnectedPlugin),
executorsByJobType: make(map[string][]*ConnectedPlugin),
healthCheckInterval: 30 * time.Second,
healthCheckTimeout: 90 * time.Second,
stopChan: make(chan struct{}),
}
}
// RegisterPlugin adds a new plugin to the registry
func (r *Registry) RegisterPlugin(pluginID string, register *plugin_pb.PluginRegister) (*ConnectedPlugin, error) {
r.mu.Lock()
defer r.mu.Unlock()
if _, exists := r.plugins[pluginID]; exists {
return nil, fmt.Errorf("plugin %s already registered", pluginID)
}
plugin := &ConnectedPlugin{
ID: pluginID,
Name: register.Name,
Version: register.Version,
ProtocolVersion: register.ProtocolVersion,
ConnectedAt: time.Now(),
LastHeartbeat: time.Now(),
State: PluginStateConnected,
Healthy: true,
Capabilities: make(map[string]*plugin_pb.JobTypeCapability),
StreamConnected: true,
}
// Index capabilities
for _, cap := range register.Capabilities {
plugin.Capabilities[cap.JobType] = cap
if cap.CanDetect {
r.detectorsByJobType[cap.JobType] = append(r.detectorsByJobType[cap.JobType], plugin)
}
if cap.CanExecute {
r.executorsByJobType[cap.JobType] = append(r.executorsByJobType[cap.JobType], plugin)
}
}
r.plugins[pluginID] = plugin
return plugin, nil
}
// UnregisterPlugin removes a plugin from the registry
func (r *Registry) UnregisterPlugin(pluginID string) error {
r.mu.Lock()
defer r.mu.Unlock()
plugin, exists := r.plugins[pluginID]
if !exists {
return fmt.Errorf("plugin %s not found", pluginID)
}
// Remove from capability indexes
for jobType := range plugin.Capabilities {
r.removePluginFromDetectors(jobType, plugin)
r.removePluginFromExecutors(jobType, plugin)
}
delete(r.plugins, pluginID)
plugin.SetState(PluginStateDisconnected)
return nil
}
// removePluginFromDetectors removes plugin from detector index for a job type
func (r *Registry) removePluginFromDetectors(jobType string, plugin *ConnectedPlugin) {
detectors := r.detectorsByJobType[jobType]
for i, p := range detectors {
if p.ID == plugin.ID {
r.detectorsByJobType[jobType] = append(detectors[:i], detectors[i+1:]...)
break
}
}
if len(r.detectorsByJobType[jobType]) == 0 {
delete(r.detectorsByJobType, jobType)
}
}
// removePluginFromExecutors removes plugin from executor index for a job type
func (r *Registry) removePluginFromExecutors(jobType string, plugin *ConnectedPlugin) {
executors := r.executorsByJobType[jobType]
for i, p := range executors {
if p.ID == plugin.ID {
r.executorsByJobType[jobType] = append(executors[:i], executors[i+1:]...)
break
}
}
if len(r.executorsByJobType[jobType]) == 0 {
delete(r.executorsByJobType, jobType)
}
}
// GetPlugin retrieves a plugin by ID
func (r *Registry) GetPlugin(pluginID string) (*ConnectedPlugin, error) {
r.mu.RLock()
defer r.mu.RUnlock()
plugin, exists := r.plugins[pluginID]
if !exists {
return nil, fmt.Errorf("plugin %s not found", pluginID)
}
return plugin, nil
}
// GetDetectorForJobType returns an available detector plugin for a job type
func (r *Registry) GetDetectorForJobType(jobType string) (*ConnectedPlugin, error) {
r.mu.RLock()
defer r.mu.RUnlock()
detectors, exists := r.detectorsByJobType[jobType]
if !exists || len(detectors) == 0 {
return nil, fmt.Errorf("no detector available for job type %s", jobType)
}
// Return the first healthy detector
for _, detector := range detectors {
if detector.IsHealthy() {
return detector, nil
}
}
return nil, fmt.Errorf("no healthy detector available for job type %s", jobType)
}
// GetExecutorForJobType returns an available executor plugin for a job type
func (r *Registry) GetExecutorForJobType(jobType string) (*ConnectedPlugin, error) {
r.mu.RLock()
defer r.mu.RUnlock()
executors, exists := r.executorsByJobType[jobType]
if !exists || len(executors) == 0 {
return nil, fmt.Errorf("no executor available for job type %s", jobType)
}
// Return the first healthy executor with lowest workload
var bestExecutor *ConnectedPlugin
var minLoad int32 = int32(^uint32(0) >> 1)
for _, executor := range executors {
if executor.IsHealthy() {
load := executor.PendingJobs + executor.RunningJobs
if load < minLoad {
minLoad = load
bestExecutor = executor
}
}
}
if bestExecutor == nil {
return nil, fmt.Errorf("no healthy executor available for job type %s", jobType)
}
return bestExecutor, nil
}
// ListPlugins returns all connected plugins
func (r *Registry) ListPlugins() []*ConnectedPlugin {
r.mu.RLock()
defer r.mu.RUnlock()
plugins := make([]*ConnectedPlugin, 0, len(r.plugins))
for _, plugin := range r.plugins {
plugins = append(plugins, plugin)
}
return plugins
}
// ListPluginsByCapability returns plugins that support a specific job type
func (r *Registry) ListPluginsByCapability(jobType string) []*ConnectedPlugin {
r.mu.RLock()
defer r.mu.RUnlock()
detectors := r.detectorsByJobType[jobType]
executors := r.executorsByJobType[jobType]
// Combine and deduplicate
pluginMap := make(map[string]*ConnectedPlugin)
for _, p := range detectors {
pluginMap[p.ID] = p
}
for _, p := range executors {
pluginMap[p.ID] = p
}
plugins := make([]*ConnectedPlugin, 0, len(pluginMap))
for _, p := range pluginMap {
plugins = append(plugins, p)
}
return plugins
}
// UpdateHeartbeat updates plugin heartbeat and health status
func (r *Registry) UpdateHeartbeat(pluginID string, heartbeat *plugin_pb.PluginHeartbeat) error {
r.mu.Lock()
plugin, exists := r.plugins[pluginID]
r.mu.Unlock()
if !exists {
return fmt.Errorf("plugin %s not found", pluginID)
}
plugin.UpdateHeartbeat(
heartbeat.CpuUsagePercent,
heartbeat.MemoryUsageMb,
heartbeat.PendingJobs,
int32(len(plugin.Capabilities)), // rough estimate
)
return nil
}
// Start starts the health check loop
func (r *Registry) Start() {
r.healthCheckTicker = time.NewTicker(r.healthCheckInterval)
go r.healthCheckLoop()
}
// Stop stops the health check loop
func (r *Registry) Stop() {
close(r.stopChan)
if r.healthCheckTicker != nil {
r.healthCheckTicker.Stop()
}
}
// healthCheckLoop periodically checks plugin health
func (r *Registry) healthCheckLoop() {
for {
select {
case <-r.healthCheckTicker.C:
r.checkHealth()
case <-r.stopChan:
return
}
}
}
// checkHealth checks the health of all plugins
func (r *Registry) checkHealth() {
r.mu.RLock()
plugins := make([]*ConnectedPlugin, 0, len(r.plugins))
for _, p := range r.plugins {
plugins = append(plugins, p)
}
r.mu.RUnlock()
now := time.Now()
for _, plugin := range plugins {
plugin.mu.RLock()
lastHeartbeat := plugin.LastHeartbeat
plugin.mu.RUnlock()
timeSinceHeartbeat := now.Sub(lastHeartbeat)
if timeSinceHeartbeat > r.healthCheckTimeout {
plugin.SetState(PluginStateUnhealthy)
plugin.mu.Lock()
plugin.Healthy = false
plugin.mu.Unlock()
} else if timeSinceHeartbeat > r.healthCheckTimeout/2 {
plugin.SetState(PluginStateUnhealthy)
} else {
plugin.SetState(PluginStateHealthy)
plugin.mu.Lock()
plugin.Healthy = true
plugin.mu.Unlock()
}
}
}
// GetStats returns registry statistics
func (r *Registry) GetStats() map[string]interface{} {
r.mu.RLock()
defer r.mu.RUnlock()
stats := map[string]interface{}{
"total_plugins": len(r.plugins),
"job_types": len(r.detectorsByJobType),
}
var healthyCount int
for _, p := range r.plugins {
if p.IsHealthy() {
healthyCount++
}
}
stats["healthy_plugins"] = healthyCount
jobTypeStats := make(map[string]map[string]interface{})
for jobType := range r.detectorsByJobType {
jobTypeStats[jobType] = map[string]interface{}{
"detectors": len(r.detectorsByJobType[jobType]),
"executors": len(r.executorsByJobType[jobType]),
}
}
stats["job_type_stats"] = jobTypeStats
return stats
}
-420
View File
@@ -1,420 +0,0 @@
package testing
import (
"context"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// TestHarness provides utilities for testing plugin functionality
type TestHarness struct {
ctx context.Context
cancel context.CancelFunc
adminServer *MockAdminServer
pluginClient plugin_pb.PluginService_ConnectClient
executionClient plugin_pb.PluginService_ExecuteJobClient
mu sync.RWMutex
createdJobs map[string]*plugin_pb.JobRequest
executedJobs map[string]*ExecutionTracker
progressUpdates map[string][]*plugin_pb.JobProgress
testDataDir string
}
// ExecutionTracker tracks the execution of a job
type ExecutionTracker struct {
JobID string
Status string
ProgressPercent int32
Messages []*plugin_pb.JobExecutionMessage
StartTime time.Time
LastUpdate time.Time
mu sync.RWMutex
}
// NewTestHarness creates a new test harness
func NewTestHarness(ctx context.Context) *TestHarness {
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithCancel(ctx)
return &TestHarness{
ctx: ctx,
cancel: cancel,
adminServer: NewMockAdminServer(),
createdJobs: make(map[string]*plugin_pb.JobRequest),
executedJobs: make(map[string]*ExecutionTracker),
progressUpdates: make(map[string][]*plugin_pb.JobProgress),
}
}
// Setup initializes the test harness and starts mock connections
func (h *TestHarness) Setup() error {
h.mu.Lock()
defer h.mu.Unlock()
if h.adminServer == nil {
h.adminServer = NewMockAdminServer()
}
return nil
}
// Teardown cleans up test resources
func (h *TestHarness) Teardown() error {
h.mu.Lock()
defer h.mu.Unlock()
if h.cancel != nil {
h.cancel()
}
if h.adminServer != nil {
h.adminServer.Close()
}
return nil
}
// GetContext returns the test context
func (h *TestHarness) GetContext() context.Context {
return h.ctx
}
// CreateJob creates a test job request
func (h *TestHarness) CreateJob(jobType, description string, priority int64, config []*plugin_pb.ConfigFieldValue) *plugin_pb.JobRequest {
h.mu.Lock()
defer h.mu.Unlock()
jobID := fmt.Sprintf("test-job-%d", time.Now().UnixNano())
job := &plugin_pb.JobRequest{
JobId: jobID,
JobType: jobType,
Description: description,
Priority: priority,
CreatedAt: timestamppb.Now(),
Config: config,
Metadata: make(map[string]string),
}
h.createdJobs[jobID] = job
return job
}
// ExecuteJob simulates job execution and returns a tracker
func (h *TestHarness) ExecuteJob(job *plugin_pb.JobRequest) *ExecutionTracker {
h.mu.Lock()
defer h.mu.Unlock()
tracker := &ExecutionTracker{
JobID: job.JobId,
Status: "running",
Messages: make([]*plugin_pb.JobExecutionMessage, 0),
StartTime: time.Now(),
}
h.executedJobs[job.JobId] = tracker
return tracker
}
// UpdateJobProgress updates the progress of a job
func (h *TestHarness) UpdateJobProgress(jobID string, progressPercent int32, currentStep, statusMessage string) {
h.mu.Lock()
defer h.mu.Unlock()
progress := &plugin_pb.JobProgress{
ProgressPercent: progressPercent,
CurrentStep: currentStep,
StatusMessage: statusMessage,
UpdatedAt: timestamppb.Now(),
}
h.progressUpdates[jobID] = append(h.progressUpdates[jobID], progress)
if tracker, ok := h.executedJobs[jobID]; ok {
tracker.mu.Lock()
tracker.ProgressPercent = progressPercent
tracker.LastUpdate = time.Now()
tracker.mu.Unlock()
}
}
// VerifyProgress checks if job progress meets expectations
func (h *TestHarness) VerifyProgress(jobID string, expectedPercent int32) error {
h.mu.RLock()
defer h.mu.RUnlock()
tracker, ok := h.executedJobs[jobID]
if !ok {
return fmt.Errorf("job not found: %s", jobID)
}
tracker.mu.RLock()
actual := tracker.ProgressPercent
tracker.mu.RUnlock()
if actual != expectedPercent {
return fmt.Errorf("progress mismatch for job %s: expected %d, got %d", jobID, expectedPercent, actual)
}
return nil
}
// CompleteJob marks a job as completed
func (h *TestHarness) CompleteJob(jobID string, summary string, output map[string]string) error {
h.mu.Lock()
defer h.mu.Unlock()
tracker, ok := h.executedJobs[jobID]
if !ok {
return fmt.Errorf("job not found: %s", jobID)
}
tracker.mu.Lock()
tracker.Status = "completed"
tracker.ProgressPercent = 100
tracker.LastUpdate = time.Now()
tracker.mu.Unlock()
completed := &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_JobCompleted{
JobCompleted: &plugin_pb.JobCompleted{
CompletedAt: timestamppb.Now(),
Summary: summary,
Output: output,
},
},
}
tracker.mu.Lock()
tracker.Messages = append(tracker.Messages, completed)
tracker.mu.Unlock()
return nil
}
// FailJob marks a job as failed
func (h *TestHarness) FailJob(jobID, errorCode, errorMessage string, retryable bool) error {
h.mu.Lock()
defer h.mu.Unlock()
tracker, ok := h.executedJobs[jobID]
if !ok {
return fmt.Errorf("job not found: %s", jobID)
}
tracker.mu.Lock()
tracker.Status = "failed"
tracker.LastUpdate = time.Now()
tracker.mu.Unlock()
failed := &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_JobFailed{
JobFailed: &plugin_pb.JobFailed{
ErrorCode: errorCode,
ErrorMessage: errorMessage,
Retryable: retryable,
FailedAt: timestamppb.Now(),
RetryCount: 0,
},
},
}
tracker.mu.Lock()
tracker.Messages = append(tracker.Messages, failed)
tracker.mu.Unlock()
return nil
}
// GetJobMessages returns all execution messages for a job
func (h *TestHarness) GetJobMessages(jobID string) []*plugin_pb.JobExecutionMessage {
h.mu.RLock()
defer h.mu.RUnlock()
tracker, ok := h.executedJobs[jobID]
if !ok {
return nil
}
tracker.mu.RLock()
defer tracker.mu.RUnlock()
return tracker.Messages
}
// GetJobStatus returns the current status of a job
func (h *TestHarness) GetJobStatus(jobID string) (string, error) {
h.mu.RLock()
defer h.mu.RUnlock()
tracker, ok := h.executedJobs[jobID]
if !ok {
return "", fmt.Errorf("job not found: %s", jobID)
}
tracker.mu.RLock()
defer tracker.mu.RUnlock()
return tracker.Status, nil
}
// GetAdminServer returns the mock admin server
func (h *TestHarness) GetAdminServer() *MockAdminServer {
h.mu.RLock()
defer h.mu.RUnlock()
return h.adminServer
}
// WaitForJobCompletion waits for a job to complete or timeout
func (h *TestHarness) WaitForJobCompletion(jobID string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for {
if time.Now().After(deadline) {
return fmt.Errorf("job completion timeout: %s", jobID)
}
status, err := h.GetJobStatus(jobID)
if err != nil {
return err
}
if status == "completed" || status == "failed" {
return nil
}
time.Sleep(100 * time.Millisecond)
}
}
// AssertJobExists verifies that a job was created
func (h *TestHarness) AssertJobExists(jobID string) error {
h.mu.RLock()
defer h.mu.RUnlock()
if _, ok := h.createdJobs[jobID]; !ok {
return fmt.Errorf("job does not exist: %s", jobID)
}
return nil
}
// AssertJobNotExists verifies that a job was not created
func (h *TestHarness) AssertJobNotExists(jobID string) error {
h.mu.RLock()
defer h.mu.RUnlock()
if _, ok := h.createdJobs[jobID]; ok {
return fmt.Errorf("job should not exist: %s", jobID)
}
return nil
}
// AssertJobStatus verifies that a job has the expected status
func (h *TestHarness) AssertJobStatus(jobID, expectedStatus string) error {
status, err := h.GetJobStatus(jobID)
if err != nil {
return err
}
if status != expectedStatus {
return fmt.Errorf("job status mismatch for %s: expected %s, got %s", jobID, expectedStatus, status)
}
return nil
}
// CreatePluginRegister creates a test plugin registration message
func CreatePluginRegister(pluginID, name, version string, capabilities []*plugin_pb.JobTypeCapability) *plugin_pb.PluginMessage {
return &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Register{
Register: &plugin_pb.PluginRegister{
PluginId: pluginID,
Name: name,
Version: version,
ProtocolVersion: "v1",
Capabilities: capabilities,
},
},
}
}
// CreatePluginHeartbeat creates a test plugin heartbeat message
func CreatePluginHeartbeat(pluginID string, pendingJobs, runningJobs int32, cpuUsage, memoryUsage float32) *plugin_pb.PluginMessage {
return &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Heartbeat{
Heartbeat: &plugin_pb.PluginHeartbeat{
PluginId: pluginID,
Timestamp: timestamppb.Now(),
UptimeSeconds: 3600,
PendingJobs: pendingJobs,
CpuUsagePercent: cpuUsage,
MemoryUsageMb: memoryUsage,
},
},
}
}
// CreateJobStartedMessage creates a job started message
func CreateJobStartedMessage(jobID, executorID string) *plugin_pb.JobExecutionMessage {
return &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_JobStarted{
JobStarted: &plugin_pb.JobStarted{
StartedAt: timestamppb.Now(),
ExecutorId: executorID,
},
},
}
}
// CreateJobProgressMessage creates a job progress message
func CreateJobProgressMessage(jobID string, progressPercent int32, currentStep, statusMessage string) *plugin_pb.JobExecutionMessage {
return &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_Progress{
Progress: &plugin_pb.JobProgress{
ProgressPercent: progressPercent,
CurrentStep: currentStep,
StatusMessage: statusMessage,
UpdatedAt: timestamppb.Now(),
},
},
}
}
// CreateJobCompletedMessage creates a job completed message
func CreateJobCompletedMessage(jobID, summary string, output map[string]string) *plugin_pb.JobExecutionMessage {
return &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_JobCompleted{
JobCompleted: &plugin_pb.JobCompleted{
CompletedAt: timestamppb.Now(),
Summary: summary,
Output: output,
},
},
}
}
// CreateJobFailedMessage creates a job failed message
func CreateJobFailedMessage(jobID, errorCode, errorMessage string, retryable bool) *plugin_pb.JobExecutionMessage {
return &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_JobFailed{
JobFailed: &plugin_pb.JobFailed{
ErrorCode: errorCode,
ErrorMessage: errorMessage,
Retryable: retryable,
FailedAt: timestamppb.Now(),
RetryCount: 0,
},
},
}
}
-262
View File
@@ -1,262 +0,0 @@
package testing
import (
"io"
"sync"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// MockAdminServer implements the PluginService for testing
type MockAdminServer struct {
mu sync.RWMutex
receivedPluginMessages []*plugin_pb.PluginMessage
receivedJobMessages []*plugin_pb.JobExecutionMessage
jobResponses map[string][]*plugin_pb.JobProgressMessage
pluginResponses map[string][]*plugin_pb.AdminMessage
streams map[string]*MockStream
closed bool
}
// MockStream represents a bidirectional stream
type MockStream struct {
mu sync.RWMutex
messages chan interface{}
closed bool
}
// NewMockAdminServer creates a new mock admin server
func NewMockAdminServer() *MockAdminServer {
return &MockAdminServer{
receivedPluginMessages: make([]*plugin_pb.PluginMessage, 0),
receivedJobMessages: make([]*plugin_pb.JobExecutionMessage, 0),
jobResponses: make(map[string][]*plugin_pb.JobProgressMessage),
pluginResponses: make(map[string][]*plugin_pb.AdminMessage),
streams: make(map[string]*MockStream),
}
}
// Connect implements the Connect RPC - bidirectional stream for plugin registration
func (m *MockAdminServer) Connect(stream plugin_pb.PluginService_ConnectServer) error {
m.mu.Lock()
if m.closed {
m.mu.Unlock()
return io.EOF
}
m.mu.Unlock()
// Receive messages from plugin
for {
msg, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
m.mu.Lock()
m.receivedPluginMessages = append(m.receivedPluginMessages, msg)
m.mu.Unlock()
// Send response if available
var response *plugin_pb.AdminMessage
if msg.GetRegister() != nil {
response = &plugin_pb.AdminMessage{
Content: &plugin_pb.AdminMessage_ConfigUpdate{
ConfigUpdate: &plugin_pb.ConfigUpdate{
JobType: "test_job_type",
},
},
}
}
if response != nil {
err = stream.Send(response)
if err != nil {
return err
}
}
}
}
// ExecuteJob implements the ExecuteJob RPC - bidirectional stream for job execution
func (m *MockAdminServer) ExecuteJob(stream plugin_pb.PluginService_ExecuteJobServer) error {
m.mu.Lock()
if m.closed {
m.mu.Unlock()
return io.EOF
}
m.mu.Unlock()
// Receive execution messages from plugin
for {
msg, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
m.mu.Lock()
m.receivedJobMessages = append(m.receivedJobMessages, msg)
m.mu.Unlock()
// Send progress update if available
jobID := msg.JobId
m.mu.RLock()
responses, ok := m.jobResponses[jobID]
m.mu.RUnlock()
if ok && len(responses) > 0 {
response := responses[0]
err = stream.Send(response)
if err != nil {
return err
}
m.mu.Lock()
m.jobResponses[jobID] = responses[1:]
m.mu.Unlock()
}
}
}
// AddJobResponse adds a pre-configured response for a specific job
func (m *MockAdminServer) AddJobResponse(jobID string, response *plugin_pb.JobProgressMessage) {
m.mu.Lock()
defer m.mu.Unlock()
m.jobResponses[jobID] = append(m.jobResponses[jobID], response)
}
// AddPluginResponse adds a pre-configured response for plugin messages
func (m *MockAdminServer) AddPluginResponse(response *plugin_pb.AdminMessage) {
m.mu.Lock()
defer m.mu.Unlock()
// Store responses indexed by a generic key for now
key := "default"
m.pluginResponses[key] = append(m.pluginResponses[key], response)
}
// GetReceivedPluginMessages returns all received plugin messages
func (m *MockAdminServer) GetReceivedPluginMessages() []*plugin_pb.PluginMessage {
m.mu.RLock()
defer m.mu.RUnlock()
// Return a copy
result := make([]*plugin_pb.PluginMessage, len(m.receivedPluginMessages))
copy(result, m.receivedPluginMessages)
return result
}
// GetReceivedJobMessages returns all received job execution messages
func (m *MockAdminServer) GetReceivedJobMessages() []*plugin_pb.JobExecutionMessage {
m.mu.RLock()
defer m.mu.RUnlock()
// Return a copy
result := make([]*plugin_pb.JobExecutionMessage, len(m.receivedJobMessages))
copy(result, m.receivedJobMessages)
return result
}
// GetReceivedJobMessages returns job execution messages filtered by job ID
func (m *MockAdminServer) GetJobMessages(jobID string) []*plugin_pb.JobExecutionMessage {
m.mu.RLock()
defer m.mu.RUnlock()
var result []*plugin_pb.JobExecutionMessage
for _, msg := range m.receivedJobMessages {
if msg.JobId == jobID {
result = append(result, msg)
}
}
return result
}
// CountReceivedMessages returns the count of received plugin messages
func (m *MockAdminServer) CountReceivedMessages() int {
m.mu.RLock()
defer m.mu.RUnlock()
return len(m.receivedPluginMessages)
}
// CountReceivedJobMessages returns the count of received job execution messages
func (m *MockAdminServer) CountReceivedJobMessages() int {
m.mu.RLock()
defer m.mu.RUnlock()
return len(m.receivedJobMessages)
}
// ClearMessages clears all recorded messages
func (m *MockAdminServer) ClearMessages() {
m.mu.Lock()
defer m.mu.Unlock()
m.receivedPluginMessages = make([]*plugin_pb.PluginMessage, 0)
m.receivedJobMessages = make([]*plugin_pb.JobExecutionMessage, 0)
}
// Close closes the mock server
func (m *MockAdminServer) Close() error {
m.mu.Lock()
defer m.mu.Unlock()
m.closed = true
return nil
}
// IsClosed returns whether the server is closed
func (m *MockAdminServer) IsClosed() bool {
m.mu.RLock()
defer m.mu.RUnlock()
return m.closed
}
// VerifyPluginRegistration verifies that a plugin registration was received
func (m *MockAdminServer) VerifyPluginRegistration(pluginID string) error {
messages := m.GetReceivedPluginMessages()
for _, msg := range messages {
if reg := msg.GetRegister(); reg != nil && reg.PluginId == pluginID {
return nil
}
}
return io.EOF
}
// VerifyJobExecution verifies that job execution messages were received for a job
func (m *MockAdminServer) VerifyJobExecution(jobID string) error {
messages := m.GetJobMessages(jobID)
if len(messages) == 0 {
return io.EOF
}
return nil
}
// VerifyJobCompletion verifies that a job completion message was received
func (m *MockAdminServer) VerifyJobCompletion(jobID string) error {
messages := m.GetJobMessages(jobID)
for _, msg := range messages {
if msg.GetJobCompleted() != nil {
return nil
}
}
return io.EOF
}
// VerifyJobFailure verifies that a job failure message was received
func (m *MockAdminServer) VerifyJobFailure(jobID string) error {
messages := m.GetJobMessages(jobID)
for _, msg := range messages {
if msg.GetJobFailed() != nil {
return nil
}
}
return io.EOF
}
-353
View File
@@ -1,353 +0,0 @@
package testing
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// MockPlugin simulates a plugin worker for testing
type MockPlugin struct {
ID string
Name string
Version string
ProtocolVersion string
Capabilities []*plugin_pb.JobTypeCapability
// Configuration
DetectionEnabled bool
ExecutionEnabled bool
FailureMode string // "" = success, "detection_error", "execution_error"
DetectionDelay time.Duration
ExecutionDelay time.Duration
// Tracking
mu sync.RWMutex
detectedJobs map[string]*plugin_pb.DetectedJob
executedJobs map[string]*JobExecution
registrationTime time.Time
callCount map[string]int
errors []string
}
// JobExecution tracks execution of a job
type JobExecution struct {
JobID string
Config []*plugin_pb.ConfigFieldValue
Status string
ProgressPercent int32
Messages []*plugin_pb.JobExecutionMessage
StartTime time.Time
EndTime time.Time
ErrorInfo *plugin_pb.JobFailed
mu sync.RWMutex
}
// NewMockPlugin creates a new mock plugin
func NewMockPlugin(id, name, version string) *MockPlugin {
return &MockPlugin{
ID: id,
Name: name,
Version: version,
ProtocolVersion: "v1",
Capabilities: make([]*plugin_pb.JobTypeCapability, 0),
DetectionEnabled: true,
ExecutionEnabled: true,
DetectionDelay: 100 * time.Millisecond,
ExecutionDelay: 100 * time.Millisecond,
detectedJobs: make(map[string]*plugin_pb.DetectedJob),
executedJobs: make(map[string]*JobExecution),
registrationTime: time.Now(),
callCount: make(map[string]int),
errors: make([]string, 0),
}
}
// AddCapability adds a job type capability to the plugin
func (mp *MockPlugin) AddCapability(jobType string, canDetect, canExecute bool) {
mp.mu.Lock()
defer mp.mu.Unlock()
capability := &plugin_pb.JobTypeCapability{
JobType: jobType,
CanDetect: canDetect,
CanExecute: canExecute,
Version: "v1",
}
mp.Capabilities = append(mp.Capabilities, capability)
}
// GetRegistrationMessage returns the plugin registration message
func (mp *MockPlugin) GetRegistrationMessage() *plugin_pb.PluginMessage {
mp.mu.RLock()
defer mp.mu.RUnlock()
return &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Register{
Register: &plugin_pb.PluginRegister{
PluginId: mp.ID,
Name: mp.Name,
Version: mp.Version,
ProtocolVersion: mp.ProtocolVersion,
Capabilities: mp.Capabilities,
},
},
}
}
// GetHeartbeatMessage returns a heartbeat message
func (mp *MockPlugin) GetHeartbeatMessage(pendingJobs, runningJobs int32, cpuUsage, memoryUsage float32) *plugin_pb.PluginMessage {
mp.mu.RLock()
defer mp.mu.RUnlock()
uptime := int64(time.Since(mp.registrationTime).Seconds())
return &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Heartbeat{
Heartbeat: &plugin_pb.PluginHeartbeat{
PluginId: mp.ID,
Timestamp: timestamppb.Now(),
UptimeSeconds: uptime,
PendingJobs: pendingJobs,
CpuUsagePercent: cpuUsage,
MemoryUsageMb: memoryUsage,
},
},
}
}
// SimulateDetection simulates job detection
func (mp *MockPlugin) SimulateDetection(jobType string, detectedCount int) ([]*plugin_pb.DetectedJob, error) {
mp.mu.Lock()
defer mp.mu.Unlock()
mp.callCount["detection"]++
if !mp.DetectionEnabled {
err := fmt.Errorf("detection disabled for plugin %s", mp.ID)
mp.errors = append(mp.errors, err.Error())
return nil, err
}
if mp.FailureMode == "detection_error" {
err := fmt.Errorf("simulated detection error")
mp.errors = append(mp.errors, err.Error())
return nil, err
}
time.Sleep(mp.DetectionDelay)
var jobs []*plugin_pb.DetectedJob
now := time.Now()
for i := 0; i < detectedCount; i++ {
jobKey := fmt.Sprintf("detected-job-%s-%d-%d", jobType, now.Unix(), i)
job := &plugin_pb.DetectedJob{
JobKey: jobKey,
JobType: jobType,
Description: fmt.Sprintf("Detected %s job %d", jobType, i),
Priority: int64(10 - i),
Metadata: make(map[string]string),
}
jobKey2 := fmt.Sprintf("%s-%d", jobType, i)
mp.detectedJobs[jobKey2] = job
jobs = append(jobs, job)
}
return jobs, nil
}
// SimulateExecution simulates job execution
func (mp *MockPlugin) SimulateExecution(jobID, jobType string, config []*plugin_pb.ConfigFieldValue) (*JobExecution, error) {
mp.mu.Lock()
mp.callCount["execution"]++
if !mp.ExecutionEnabled {
err := fmt.Errorf("execution disabled for plugin %s", mp.ID)
mp.errors = append(mp.errors, err.Error())
mp.mu.Unlock()
return nil, err
}
if mp.FailureMode == "execution_error" {
err := fmt.Errorf("simulated execution error")
mp.errors = append(mp.errors, err.Error())
mp.mu.Unlock()
return nil, err
}
execution := &JobExecution{
JobID: jobID,
Config: config,
Status: "running",
Messages: make([]*plugin_pb.JobExecutionMessage, 0),
StartTime: time.Now(),
}
mp.executedJobs[jobID] = execution
mp.mu.Unlock()
// Simulate progress updates
for progress := 0; progress <= 100; progress += 25 {
time.Sleep(mp.ExecutionDelay)
mp.mu.Lock()
if exec, ok := mp.executedJobs[jobID]; ok {
exec.mu.Lock()
exec.ProgressPercent = int32(progress)
msg := &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_Progress{
Progress: &plugin_pb.JobProgress{
ProgressPercent: int32(progress),
CurrentStep: fmt.Sprintf("Step %d", progress/25),
StatusMessage: fmt.Sprintf("Executing step at %d%%", progress),
UpdatedAt: timestamppb.Now(),
},
},
}
exec.Messages = append(exec.Messages, msg)
exec.mu.Unlock()
}
mp.mu.Unlock()
}
mp.mu.Lock()
if exec, ok := mp.executedJobs[jobID]; ok {
exec.mu.Lock()
exec.Status = "completed"
exec.ProgressPercent = 100
exec.EndTime = time.Now()
completed := &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_JobCompleted{
JobCompleted: &plugin_pb.JobCompleted{
CompletedAt: timestamppb.Now(),
Summary: fmt.Sprintf("Job %s completed successfully", jobID),
Output: map[string]string{
"result": "success",
"job_id": jobID,
},
},
},
}
exec.Messages = append(exec.Messages, completed)
exec.mu.Unlock()
}
mp.mu.Unlock()
return execution, nil
}
// SimulateExecutionFailure simulates a job execution failure
func (mp *MockPlugin) SimulateExecutionFailure(jobID string, errorCode, errorMessage string, retryable bool) (*JobExecution, error) {
mp.mu.Lock()
defer mp.mu.Unlock()
execution := &JobExecution{
JobID: jobID,
Status: "failed",
Messages: make([]*plugin_pb.JobExecutionMessage, 0),
StartTime: time.Now(),
EndTime: time.Now(),
}
failedMsg := &plugin_pb.JobFailed{
ErrorCode: errorCode,
ErrorMessage: errorMessage,
Retryable: retryable,
FailedAt: timestamppb.Now(),
RetryCount: 0,
}
msg := &plugin_pb.JobExecutionMessage{
JobId: jobID,
Content: &plugin_pb.JobExecutionMessage_JobFailed{
JobFailed: failedMsg,
},
}
execution.Messages = append(execution.Messages, msg)
execution.ErrorInfo = failedMsg
mp.executedJobs[jobID] = execution
return execution, nil
}
// GetExecutionMessages returns execution messages for a job
func (mp *MockPlugin) GetExecutionMessages(jobID string) []*plugin_pb.JobExecutionMessage {
mp.mu.RLock()
defer mp.mu.RUnlock()
if exec, ok := mp.executedJobs[jobID]; ok {
exec.mu.RLock()
defer exec.mu.RUnlock()
result := make([]*plugin_pb.JobExecutionMessage, len(exec.Messages))
copy(result, exec.Messages)
return result
}
return nil
}
// GetCallCount returns the number of times a method was called
func (mp *MockPlugin) GetCallCount(method string) int {
mp.mu.RLock()
defer mp.mu.RUnlock()
return mp.callCount[method]
}
// GetErrors returns all recorded errors
func (mp *MockPlugin) GetErrors() []string {
mp.mu.RLock()
defer mp.mu.RUnlock()
result := make([]string, len(mp.errors))
copy(result, mp.errors)
return result
}
// SetFailureMode sets the failure simulation mode
func (mp *MockPlugin) SetFailureMode(mode string) {
mp.mu.Lock()
defer mp.mu.Unlock()
mp.FailureMode = mode
}
// SetDetectionDelay sets the detection simulation delay
func (mp *MockPlugin) SetDetectionDelay(delay time.Duration) {
mp.mu.Lock()
defer mp.mu.Unlock()
mp.DetectionDelay = delay
}
// SetExecutionDelay sets the execution simulation delay
func (mp *MockPlugin) SetExecutionDelay(delay time.Duration) {
mp.mu.Lock()
defer mp.mu.Unlock()
mp.ExecutionDelay = delay
}
// Reset clears all state
func (mp *MockPlugin) Reset() {
mp.mu.Lock()
defer mp.mu.Unlock()
mp.detectedJobs = make(map[string]*plugin_pb.DetectedJob)
mp.executedJobs = make(map[string]*JobExecution)
mp.callCount = make(map[string]int)
mp.errors = make([]string, 0)
mp.FailureMode = ""
}
-256
View File
@@ -1,256 +0,0 @@
package plugin
import (
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// JobState represents the current state of a job
type JobState int32
const (
JobStatePending JobState = 0
JobStateRunning JobState = 1
JobStateCompleted JobState = 2
JobStateFailed JobState = 3
JobStateCancelled JobState = 4
JobStatePaused JobState = 5
)
// String returns string representation of JobState
func (s JobState) String() string {
switch s {
case JobStatePending:
return "pending"
case JobStateRunning:
return "running"
case JobStateCompleted:
return "completed"
case JobStateFailed:
return "failed"
case JobStateCancelled:
return "cancelled"
case JobStatePaused:
return "paused"
default:
return "unknown"
}
}
// PluginState represents the current state of a plugin connection
type PluginState int32
const (
PluginStateConnecting PluginState = 0
PluginStateConnected PluginState = 1
PluginStateHealthy PluginState = 2
PluginStateUnhealthy PluginState = 3
PluginStateDisconnected PluginState = 4
)
// String returns string representation of PluginState
func (s PluginState) String() string {
switch s {
case PluginStateConnecting:
return "connecting"
case PluginStateConnected:
return "connected"
case PluginStateHealthy:
return "healthy"
case PluginStateUnhealthy:
return "unhealthy"
case PluginStateDisconnected:
return "disconnected"
default:
return "unknown"
}
}
// Job represents a work unit in the plugin system
type Job struct {
ID string
Type string
Description string
Priority int64
State JobState
CreatedAt time.Time
UpdatedAt time.Time
ExecutorID string
ProgressPercent int32
Config []*plugin_pb.ConfigFieldValue
Metadata map[string]string
// Execution tracking
Retries int32
LastRetryTime time.Time
CompletedInfo *plugin_pb.JobCompleted
FailedInfo *plugin_pb.JobFailed
CheckpointIDs []string
LogEntries []*plugin_pb.ExecutionLogEntry
// Lock for thread-safe access
mu sync.RWMutex
}
// ConnectedPlugin represents a connected plugin worker
type ConnectedPlugin struct {
ID string
Name string
Version string
ProtocolVersion string
ConnectedAt time.Time
LastHeartbeat time.Time
State PluginState
Healthy bool
// Capabilities indexed by job type
Capabilities map[string]*plugin_pb.JobTypeCapability
// Current workload
PendingJobs int32
RunningJobs int32
// Resource usage
CPUUsagePercent float32
MemoryUsageMB float32
// Communication stream
StreamConnected bool
// Lock for thread-safe access
mu sync.RWMutex
}
// JobTypeConfig holds configuration for a specific job type
type JobTypeConfig struct {
JobType string
Enabled bool
AdminConfig []*plugin_pb.ConfigFieldValue
WorkerConfig []*plugin_pb.ConfigFieldValue
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy string
// History tracking
DetectionHistory []*DetectionRecord
ExecutionHistory []*ExecutionRecord
mu sync.RWMutex
}
// DetectionRecord holds information about a detection run
type DetectionRecord struct {
Timestamp time.Time
DurationMs int64
JobsDetected int
Status string
Error string
WorkerID string
DetailedLogs []string
}
// ExecutionRecord holds information about a job execution
type ExecutionRecord struct {
JobID string
JobType string
StartedAt time.Time
CompletedAt time.Time
DurationMs int64
Success bool
Error string
WorkerID string
ItemsProcessed int
ExecutionLogs []string
}
// GetState safely gets the job state
func (j *Job) GetState() JobState {
j.mu.RLock()
defer j.mu.RUnlock()
return j.State
}
// SetState safely sets the job state
func (j *Job) SetState(state JobState) {
j.mu.Lock()
defer j.mu.Unlock()
j.State = state
j.UpdatedAt = time.Now()
}
// GetProgress safely gets progress
func (j *Job) GetProgress() int32 {
j.mu.RLock()
defer j.mu.RUnlock()
return j.ProgressPercent
}
// SetProgress safely sets progress
func (j *Job) SetProgress(percent int32) {
j.mu.Lock()
defer j.mu.Unlock()
j.ProgressPercent = percent
j.UpdatedAt = time.Now()
}
// GetState safely gets plugin state
func (p *ConnectedPlugin) GetState() PluginState {
p.mu.RLock()
defer p.mu.RUnlock()
return p.State
}
// SetState safely sets plugin state
func (p *ConnectedPlugin) SetState(state PluginState) {
p.mu.Lock()
defer p.mu.Unlock()
p.State = state
p.LastHeartbeat = time.Now()
}
// IsHealthy safely checks if plugin is healthy
func (p *ConnectedPlugin) IsHealthy() bool {
p.mu.RLock()
defer p.mu.RUnlock()
return p.Healthy
}
// UpdateHeartbeat safely updates heartbeat
func (p *ConnectedPlugin) UpdateHeartbeat(cpu, memory float32, pending, running int32) {
p.mu.Lock()
defer p.mu.Unlock()
p.LastHeartbeat = time.Now()
p.CPUUsagePercent = cpu
p.MemoryUsageMB = memory
p.PendingJobs = pending
p.RunningJobs = running
}
// GetConfig safely gets configuration
func (c *JobTypeConfig) GetConfig() (*plugin_pb.JobTypeConfig, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return &plugin_pb.JobTypeConfig{
JobType: c.JobType,
Enabled: c.Enabled,
AdminConfig: c.AdminConfig,
WorkerConfig: c.WorkerConfig,
CreatedAt: timestamppb.New(c.CreatedAt),
UpdatedAt: timestamppb.New(c.UpdatedAt),
CreatedBy: c.CreatedBy,
}, nil
}
// SetConfig safely sets configuration
func (c *JobTypeConfig) SetConfig(enabled bool, adminConfig, workerConfig []*plugin_pb.ConfigFieldValue) {
c.mu.Lock()
defer c.mu.Unlock()
c.Enabled = enabled
c.AdminConfig = adminConfig
c.WorkerConfig = workerConfig
c.UpdatedAt = time.Now()
}
@@ -1,296 +0,0 @@
package balance
import (
"context"
"fmt"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/durationpb"
)
// Detector scans for volume distribution imbalance across servers
type Detector struct {
masterAddr string
}
// ServerVolumeInfo represents volume count on a server
type ServerVolumeInfo struct {
ServerID string
Rack string
VolumeCount int32
TotalVolumeGB int64
AvailableGB int64
WriteableCount int32
}
// VolumeInfo represents a volume that can be migrated
type VolumeInfo struct {
ID string
Collection string
SizeGB int64
SourceServer string
TargetServer string
Replicas int32
IsWriteable bool
LastModifiedAt time.Time
}
// NewDetector creates a new balance detector
func NewDetector(masterAddr string) *Detector {
return &Detector{
masterAddr: masterAddr,
}
}
// DetectJobs identifies volume distribution imbalance and returns migration jobs
// Returns DetectedJob items with priority based on imbalance severity
func (d *Detector) DetectJobs(ctx context.Context, config *plugin_pb.JobTypeConfig) ([]*plugin_pb.DetectedJob, error) {
var detectedJobs []*plugin_pb.DetectedJob
// Extract configuration parameters
imbalanceThreshold := float64(20) // default 20%
minServers := int32(2) // default 2
preferRackDiversity := false // default false
for _, cfv := range config.AdminConfig {
if cfv.FieldName == "imbalanceThreshold" {
imbalanceThreshold = float64(cfv.IntValue)
} else if cfv.FieldName == "minServers" {
minServers = int32(cfv.IntValue)
} else if cfv.FieldName == "preferRackDiversity" {
preferRackDiversity = cfv.BoolValue
}
}
glog.Infof("balance detector: scanning volume distribution (threshold=%.1f%%, minServers=%d, rackDiversity=%v)",
imbalanceThreshold, minServers, preferRackDiversity)
// Get server and volume information
serverInfo, volumes := d.scanServerVolumes(ctx)
if int32(len(serverInfo)) < minServers {
glog.Infof("balance detector: insufficient servers (%d < %d), skipping detection",
len(serverInfo), minServers)
return detectedJobs, nil
}
// Calculate volume distribution imbalance
imbalance, maxServer, minServer := d.calculateImbalance(serverInfo)
glog.Infof("balance detector: current imbalance=%.1f%%, max=%d volumes on %s, min=%d volumes on %s",
imbalance, maxServer.VolumeCount, maxServer.ServerID, minServer.VolumeCount, minServer.ServerID)
// Check if imbalance exceeds threshold
if imbalance <= imbalanceThreshold {
glog.Infof("balance detector: imbalance %.1f%% is within threshold %.1f%%, no rebalancing needed",
imbalance, imbalanceThreshold)
return detectedJobs, nil
}
glog.Infof("balance detector: imbalance %.1f%% exceeds threshold %.1f%%, triggering rebalancing",
imbalance, imbalanceThreshold)
// Generate migration jobs to reduce imbalance
migrations := d.generateMigrations(serverInfo, volumes, preferRackDiversity)
now := time.Now()
for i, migration := range migrations {
priority := int64((imbalance * 1000)) - int64(i*10) // Higher imbalance = higher priority
jobKey := fmt.Sprintf("balance_%s_to_%s_%s", migration.SourceServer, migration.TargetServer, now.Format("20060102150405"))
job := &plugin_pb.DetectedJob{
JobKey: jobKey,
JobType: "balance",
Description: fmt.Sprintf("Migrate volume %s from %s to %s (imbalance reduction: %.1f%%)",
migration.ID, migration.SourceServer, migration.TargetServer, imbalance),
Priority: priority,
EstimatedDuration: durationpb.New(time.Duration(migration.SizeGB) * time.Second),
Metadata: map[string]string{
"volume_id": migration.ID,
"collection": migration.Collection,
"source_server": migration.SourceServer,
"target_server": migration.TargetServer,
"volume_size_gb": fmt.Sprintf("%d", migration.SizeGB),
"imbalance": fmt.Sprintf("%.2f", imbalance),
"rack_diversity": fmt.Sprintf("%v", preferRackDiversity),
},
SuggestedConfig: []*plugin_pb.ConfigFieldValue{},
}
detectedJobs = append(detectedJobs, job)
glog.Infof("balance detector: detected migration job %s (priority=%d)", migration.ID, priority)
}
glog.Infof("balance detector: found %d migration jobs to reduce imbalance", len(detectedJobs))
return detectedJobs, nil
}
// calculateImbalance calculates volume distribution imbalance
// imbalance = (max_volumes - min_volumes) / avg_volumes * 100
func (d *Detector) calculateImbalance(servers []ServerVolumeInfo) (imbalance float64, maxServer, minServer ServerVolumeInfo) {
if len(servers) == 0 {
return 0, ServerVolumeInfo{}, ServerVolumeInfo{}
}
// Sort by volume count to find min and max
sorted := make([]ServerVolumeInfo, len(servers))
copy(sorted, servers)
sort.Slice(sorted, func(i, j int) bool {
return sorted[i].VolumeCount < sorted[j].VolumeCount
})
minServer = sorted[0]
maxServer = sorted[len(sorted)-1]
// Calculate average
totalVolumes := int32(0)
for _, s := range servers {
totalVolumes += s.VolumeCount
}
avgVolumes := float64(totalVolumes) / float64(len(servers))
// Avoid division by zero
if avgVolumes == 0 {
return 0, maxServer, minServer
}
// Calculate imbalance percentage
imbalance = float64(maxServer.VolumeCount-minServer.VolumeCount) / avgVolumes * 100
// Ensure it's not negative
if imbalance < 0 {
imbalance = 0
}
return imbalance, maxServer, minServer
}
// generateMigrations generates a list of volume migrations to reduce imbalance
func (d *Detector) generateMigrations(servers []ServerVolumeInfo, volumes []VolumeInfo, preferRackDiversity bool) []VolumeInfo {
var migrations []VolumeInfo
// Sort servers by volume count (descending)
serversCopy := make([]ServerVolumeInfo, len(servers))
copy(serversCopy, servers)
sort.Slice(serversCopy, func(i, j int) bool {
return serversCopy[i].VolumeCount > serversCopy[j].VolumeCount
})
// Calculate target volume count (average)
totalVolumes := int32(0)
for _, s := range serversCopy {
totalVolumes += s.VolumeCount
}
targetPerServer := totalVolumes / int32(len(serversCopy))
// For each overloaded server, select volumes to migrate
for _, sourceServer := range serversCopy {
if sourceServer.VolumeCount <= targetPerServer {
break // Rest are balanced
}
volumesToMove := sourceServer.VolumeCount - targetPerServer
// Find candidate volumes on this server
for _, vol := range volumes {
if volumesToMove <= 0 {
break
}
if vol.SourceServer != sourceServer.ServerID {
continue
}
// Skip read-only volumes
if !vol.IsWriteable {
continue
}
// Find a target server (underloaded, different if rack diversity preferred)
targetServer := d.selectTargetServer(serversCopy, sourceServer, preferRackDiversity)
if targetServer == nil {
continue
}
migration := VolumeInfo{
ID: vol.ID,
Collection: vol.Collection,
SizeGB: vol.SizeGB,
SourceServer: sourceServer.ServerID,
TargetServer: targetServer.ServerID,
Replicas: vol.Replicas,
IsWriteable: vol.IsWriteable,
}
migrations = append(migrations, migration)
volumesToMove--
// Update server counts
sourceServer.VolumeCount--
targetServer.VolumeCount++
}
}
// Sort by volume size (largest first for priority)
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].SizeGB > migrations[j].SizeGB
})
return migrations
}
// selectTargetServer finds a suitable target server for migration
func (d *Detector) selectTargetServer(servers []ServerVolumeInfo, sourceServer ServerVolumeInfo, preferRackDiversity bool) *ServerVolumeInfo {
// Sort by volume count (ascending) - pick least loaded
sort.Slice(servers, func(i, j int) bool {
return servers[i].VolumeCount < servers[j].VolumeCount
})
for i := range servers {
server := &servers[i]
// Skip source server
if server.ServerID == sourceServer.ServerID {
continue
}
// If rack diversity preferred, try to pick different rack
if preferRackDiversity && server.Rack == sourceServer.Rack {
continue
}
return server
}
// If rack diversity is preferred but all servers are in same rack, fallback to least loaded
if preferRackDiversity {
for i := range servers {
server := &servers[i]
if server.ServerID != sourceServer.ServerID {
return server
}
}
}
return nil
}
// scanServerVolumes performs a scan of servers and volumes from the master
// This is a placeholder that would connect to master in production
func (d *Detector) scanServerVolumes(ctx context.Context) ([]ServerVolumeInfo, []VolumeInfo) {
// TODO: Connect to master server at d.masterAddr and get:
// 1. List of data nodes with their rack information
// 2. Volume distribution across nodes
// 3. Volume metadata (size, collection, writeable status)
//
// For now, return empty lists as a framework
var servers []ServerVolumeInfo
var volumes []VolumeInfo
return servers, volumes
}
@@ -1,326 +0,0 @@
package balance
import (
"context"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Executor handles the 5-step volume migration execution process
type Executor struct {
jobID string
sourceServer string
targetServer string
volumeID string
config *plugin_pb.JobTypeConfig
parallelMigrations int32
maxBytesPerSecond int64
}
// ExecutionStep represents a single step in the migration process
type ExecutionStep struct {
StepNumber int
Name string
Description string
}
// MigrationState tracks the state of a migration
type MigrationState struct {
mu sync.Mutex
volumeReadonly bool
volumeCopied bool
volumeMounted bool
tailStarted bool
sourceDeleted bool
bytesTransferred int64
}
// NewExecutor creates a new balance executor
func NewExecutor(jobID string, config *plugin_pb.JobTypeConfig) *Executor {
parallelMigrations := int32(2)
maxBytesPerSecond := int64(0)
for _, cfv := range config.WorkerConfig {
if cfv.FieldName == "parallelMigrations" {
parallelMigrations = int32(cfv.IntValue)
} else if cfv.FieldName == "maxBytesPerSecond" {
maxBytesPerSecond = cfv.IntValue
}
}
return &Executor{
jobID: jobID,
config: config,
parallelMigrations: parallelMigrations,
maxBytesPerSecond: maxBytesPerSecond,
}
}
// Execute runs the 5-step volume migration process
// Step 1: markVolumeReadonly - Make source volume read-only
// Step 2: copyVolume - Copy to target server
// Step 3: mountVolume - Mount on target
// Step 4: tailUpdates - Tail live updates from source
// Step 5: deleteSourceVolume - Delete from source if balanced
// Returns progress updates via the progressChan
func (e *Executor) Execute(ctx context.Context, metadata map[string]string, progressChan chan<- *plugin_pb.JobProgress) error {
e.volumeID = metadata["volume_id"]
e.sourceServer = metadata["source_server"]
e.targetServer = metadata["target_server"]
glog.Infof("balance executor job=%s: starting migration (volume=%s, %s -> %s)",
e.jobID, e.volumeID, e.sourceServer, e.targetServer)
state := &MigrationState{}
steps := []ExecutionStep{
{StepNumber: 1, Name: "markVolumeReadonly", Description: "Make source volume read-only"},
{StepNumber: 2, Name: "copyVolume", Description: "Copy volume data to target server"},
{StepNumber: 3, Name: "mountVolume", Description: "Mount volume on target server"},
{StepNumber: 4, Name: "tailUpdates", Description: "Tail live updates from source"},
{StepNumber: 5, Name: "deleteSourceVolume", Description: "Delete volume from source server"},
}
totalSteps := len(steps)
for i, step := range steps {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
glog.Infof("balance executor job=%s: executing step %d: %s", e.jobID, step.StepNumber, step.Name)
// Send progress update before executing step
progress := int32((i * 100) / totalSteps)
progressChan <- &plugin_pb.JobProgress{
ProgressPercent: progress,
CurrentStep: step.Name,
StatusMessage: step.Description,
UpdatedAt: timestamppb.Now(),
}
var err error
switch step.StepNumber {
case 1:
err = e.markVolumeReadonly(ctx, state)
case 2:
err = e.copyVolume(ctx, state, progressChan)
case 3:
err = e.mountVolume(ctx, state)
case 4:
err = e.tailUpdates(ctx, state, progressChan)
case 5:
err = e.deleteSourceVolume(ctx, state)
}
if err != nil {
glog.Errorf("balance executor job=%s: step %d failed: %v", e.jobID, step.StepNumber, err)
// Attempt to rollback on error
e.rollbackMigration(ctx, state)
return fmt.Errorf("step %d (%s) failed: %w", step.StepNumber, step.Name, err)
}
glog.Infof("balance executor job=%s: step %d completed", e.jobID, step.StepNumber)
}
// Send final progress update
progressChan <- &plugin_pb.JobProgress{
ProgressPercent: 100,
CurrentStep: "complete",
StatusMessage: "Volume migration completed successfully",
UpdatedAt: timestamppb.Now(),
}
glog.Infof("balance executor job=%s: migration completed (volume=%s, transferred=%dB)",
e.jobID, e.volumeID, state.bytesTransferred)
return nil
}
// Step 1: markVolumeReadonly makes the source volume read-only to prepare for migration
func (e *Executor) markVolumeReadonly(ctx context.Context, state *MigrationState) error {
glog.Infof("balance executor job=%s: marking volume %s as read-only on %s",
e.jobID, e.volumeID, e.sourceServer)
// TODO: Connect to source server and mark volume as read-only
// 1. Get volume server connection
// 2. Send MarkVolumeReadonly RPC
// 3. Wait for confirmation
// 4. Verify volume is read-only
state.mu.Lock()
state.volumeReadonly = true
state.mu.Unlock()
glog.Infof("balance executor job=%s: volume %s is now read-only", e.jobID, e.volumeID)
return nil
}
// Step 2: copyVolume copies volume data from source to target server
func (e *Executor) copyVolume(ctx context.Context, state *MigrationState, progressChan chan<- *plugin_pb.JobProgress) error {
glog.Infof("balance executor job=%s: starting volume copy from %s to %s (bandwidth=%dB/s)",
e.jobID, e.sourceServer, e.targetServer, e.maxBytesPerSecond)
// TODO: Connect to both source and target servers and perform copy
// 1. Get volume metadata from source (size, collection, replicas)
// 2. Create volume on target server
// 3. Stream volume data from source to target
// 4. Respect bandwidth limit if maxBytesPerSecond > 0
// 5. Periodically send progress updates via progressChan
// 6. Verify checksum after transfer
// Simulate progress updates
startTime := time.Now()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
elapsed := time.Since(startTime)
// Simulate byte transfer (would be actual in production)
state.mu.Lock()
state.bytesTransferred = int64(elapsed.Seconds()) * 1024 * 1024 // 1MB/s simulation
state.mu.Unlock()
if elapsed > 5*time.Second {
// Copy complete after 5 seconds in simulation
state.mu.Lock()
state.volumeCopied = true
state.mu.Unlock()
glog.Infof("balance executor job=%s: volume copy completed (%dB transferred)",
e.jobID, state.bytesTransferred)
return nil
}
}
}
}
// Step 3: mountVolume mounts the copied volume on the target server
func (e *Executor) mountVolume(ctx context.Context, state *MigrationState) error {
glog.Infof("balance executor job=%s: mounting volume %s on target server %s",
e.jobID, e.volumeID, e.targetServer)
state.mu.Lock()
if !state.volumeCopied {
state.mu.Unlock()
return fmt.Errorf("volume not copied yet")
}
state.mu.Unlock()
// TODO: Connect to target server and mount the volume
// 1. Send MountVolume RPC with volume ID and collection
// 2. Wait for mount to complete
// 3. Verify volume is accessible and readable
state.mu.Lock()
state.volumeMounted = true
state.mu.Unlock()
glog.Infof("balance executor job=%s: volume %s mounted on %s", e.jobID, e.volumeID, e.targetServer)
return nil
}
// Step 4: tailUpdates tails live updates from source to target to keep them in sync
func (e *Executor) tailUpdates(ctx context.Context, state *MigrationState, progressChan chan<- *plugin_pb.JobProgress) error {
glog.Infof("balance executor job=%s: starting to tail updates from %s to %s",
e.jobID, e.sourceServer, e.targetServer)
state.mu.Lock()
if !state.volumeMounted {
state.mu.Unlock()
return fmt.Errorf("volume not mounted on target")
}
state.mu.Unlock()
// TODO: Stream updates from source to target
// 1. Get update stream from source volume
// 2. Apply updates to target volume
// 3. Handle concurrent writes
// 4. Report tail progress
// Simulate tail for a short duration
for i := 0; i < 3; i++ {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
state.mu.Lock()
state.tailStarted = true
state.mu.Unlock()
progressChan <- &plugin_pb.JobProgress{
ProgressPercent: int32(70 + i*5),
CurrentStep: "tailUpdates",
StatusMessage: fmt.Sprintf("Applying updates... (%d updates processed)", (i+1)*100),
UpdatedAt: timestamppb.Now(),
}
}
}
glog.Infof("balance executor job=%s: tail updates completed", e.jobID)
return nil
}
// Step 5: deleteSourceVolume deletes the volume from the source server after verification
func (e *Executor) deleteSourceVolume(ctx context.Context, state *MigrationState) error {
glog.Infof("balance executor job=%s: deleting volume %s from source server %s",
e.jobID, e.volumeID, e.sourceServer)
state.mu.Lock()
if !state.tailStarted {
state.mu.Unlock()
return fmt.Errorf("tail updates not completed")
}
state.mu.Unlock()
// TODO: Delete volume from source server
// 1. Verify target volume is healthy and in sync
// 2. Verify no new writes can occur to source volume
// 3. Send DeleteVolume RPC to source server
// 4. Wait for deletion to complete
// 5. Verify source volume is removed
state.mu.Lock()
state.sourceDeleted = true
state.mu.Unlock()
glog.Infof("balance executor job=%s: volume %s deleted from source %s", e.jobID, e.volumeID, e.sourceServer)
return nil
}
// rollbackMigration attempts to rollback the migration if an error occurs
func (e *Executor) rollbackMigration(ctx context.Context, state *MigrationState) {
glog.Warningf("balance executor job=%s: attempting rollback (readonly=%v, copied=%v, mounted=%v, deleted=%v)",
e.jobID, state.volumeReadonly, state.volumeCopied, state.volumeMounted, state.sourceDeleted)
// Only rollback if we've started but not completed
state.mu.Lock()
defer state.mu.Unlock()
// If volume was deleted, we can't fully rollback
if state.sourceDeleted {
glog.Errorf("balance executor job=%s: cannot rollback - volume already deleted from source", e.jobID)
return
}
// If target was mounted, unmount it
if state.volumeMounted {
glog.Infof("balance executor job=%s: unmounting target volume", e.jobID)
// TODO: Send UnmountVolume RPC to target server
}
// If source was made read-only, mark it as writable again
if state.volumeReadonly {
glog.Infof("balance executor job=%s: restoring source volume to writable", e.jobID)
// TODO: Send MarkVolumeWritable RPC to source server
}
glog.Infof("balance executor job=%s: rollback completed", e.jobID)
}
-137
View File
@@ -1,137 +0,0 @@
package balance
import (
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// GetConfigurationSchema returns the configuration schema for the balance job type
func GetConfigurationSchema() *plugin_pb.JobTypeConfigSchema {
return &plugin_pb.JobTypeConfigSchema{
JobType: "balance",
Version: "v1",
Description: "Automatically balance volume distribution across servers to optimize storage and performance",
AdminFields: []*plugin_pb.ConfigField{
{
Name: "imbalanceThreshold",
Label: "Imbalance Threshold (%)",
Description: "Trigger rebalancing when imbalance exceeds this percentage (1-100)",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "20",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "1",
ErrorMessage: "Imbalance threshold must be at least 1",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "100",
ErrorMessage: "Imbalance threshold must be at most 100",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 1,
MaxValue: 100,
},
},
{
Name: "minServers",
Label: "Minimum Servers",
Description: "Only rebalance when cluster has at least this many servers (2-10)",
FieldType: plugin_pb.ConfigField_INT,
Required: false,
DefaultValue: "2",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "2",
ErrorMessage: "Minimum servers must be at least 2",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "10",
ErrorMessage: "Minimum servers must be at most 10",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 2,
MaxValue: 10,
},
},
{
Name: "preferRackDiversity",
Label: "Prefer Rack Diversity",
Description: "Consider rack locations when balancing to improve fault tolerance",
FieldType: plugin_pb.ConfigField_BOOL,
Required: false,
DefaultValue: "false",
},
},
WorkerFields: []*plugin_pb.ConfigField{
{
Name: "parallelMigrations",
Label: "Parallel Migrations",
Description: "Number of concurrent volume migrations to perform (1-10)",
FieldType: plugin_pb.ConfigField_INT,
Required: false,
DefaultValue: "2",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "1",
ErrorMessage: "Parallel migrations must be at least 1",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "10",
ErrorMessage: "Parallel migrations must be at most 10",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 1,
MaxValue: 10,
},
},
{
Name: "maxBytesPerSecond",
Label: "Max Bytes Per Second",
Description: "Limit migration bandwidth (0 = unlimited, in bytes/sec)",
FieldType: plugin_pb.ConfigField_INT,
Required: false,
DefaultValue: "0",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "0",
ErrorMessage: "Max bytes per second must be non-negative",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 0,
},
},
},
FieldGroups: []*plugin_pb.ConfigGroup{
{
Name: "Balance Settings",
Label: "Balance Settings",
Description: "Configuration for volume rebalancing",
FieldNames: []string{
"imbalanceThreshold",
"minServers",
"preferRackDiversity",
},
},
{
Name: "advanced",
Label: "Advanced",
Description: "Advanced migration parameters",
FieldNames: []string{
"parallelMigrations",
"maxBytesPerSecond",
},
},
},
}
}
-368
View File
@@ -1,368 +0,0 @@
package balance
import (
"context"
"fmt"
"io"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Worker is the main balance plugin worker
type Worker struct {
id string
name string
version string
masterAddr string
httpPort int
// gRPC connection
conn *grpc.ClientConn
client plugin_pb.PluginServiceClient
// Detector and executor
detector *Detector
// Context and coordination
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
// Running jobs
jobsMu sync.RWMutex
runningJobs map[string]context.CancelFunc
}
// NewWorker creates a new balance worker
func NewWorker(id, masterAddr string, httpPort int) *Worker {
return &Worker{
id: id,
name: "balance_worker",
version: "v1",
masterAddr: masterAddr,
httpPort: httpPort,
runningJobs: make(map[string]context.CancelFunc),
detector: NewDetector(masterAddr),
}
}
// Start starts the worker and connects to the admin server
func (w *Worker) Start(ctx context.Context) error {
glog.Infof("balance worker: starting (id=%s, master=%s, httpPort=%d)", w.id, w.masterAddr, w.httpPort)
w.ctx, w.cancel = context.WithCancel(ctx)
// Connect to admin server via gRPC
// Admin server runs on httpPort + 10000
adminPort := w.httpPort + 10000
adminAddr := fmt.Sprintf("localhost:%d", adminPort)
glog.Infof("balance worker: connecting to admin at %s", adminAddr)
conn, err := grpc.Dial(adminAddr, grpc.WithInsecure())
if err != nil {
return fmt.Errorf("failed to connect to admin server: %w", err)
}
w.conn = conn
w.client = plugin_pb.NewPluginServiceClient(conn)
// Start connection handler in goroutine
w.wg.Add(1)
go w.handleConnection()
return nil
}
// Stop stops the worker and closes all connections
func (w *Worker) Stop() error {
glog.Infof("balance worker: stopping (id=%s)", w.id)
// Cancel context to signal all goroutines
if w.cancel != nil {
w.cancel()
}
// Wait for goroutines with timeout
done := make(chan struct{})
go func() {
w.wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(10 * time.Second):
glog.Warningf("balance worker: graceful shutdown timeout")
}
// Close gRPC connection
if w.conn != nil {
if err := w.conn.Close(); err != nil {
glog.Errorf("balance worker: error closing gRPC connection: %v", err)
}
}
glog.Infof("balance worker: stopped")
return nil
}
// handleConnection handles the bidirectional gRPC connection with the admin server
func (w *Worker) handleConnection() {
defer w.wg.Done()
glog.Infof("balance worker: establishing bidirectional stream")
// Create bidirectional stream
stream, err := w.client.Connect(w.ctx)
if err != nil {
glog.Errorf("balance worker: failed to create stream: %v", err)
return
}
// Send registration message
if err := w.sendRegistration(stream); err != nil {
glog.Errorf("balance worker: failed to send registration: %v", err)
return
}
// Start heartbeat goroutine
w.wg.Add(1)
go w.sendHeartbeats(stream)
// Start job executor goroutine
w.wg.Add(1)
go w.executeJobs(stream)
// Listen for messages from admin
w.listenForMessages(stream)
glog.Infof("balance worker: connection closed")
}
// sendRegistration sends the initial registration message
func (w *Worker) sendRegistration(stream plugin_pb.PluginService_ConnectClient) error {
capabilities := []*plugin_pb.JobTypeCapability{
{
JobType: "balance",
CanDetect: true,
CanExecute: true,
Version: "v1",
},
}
register := &plugin_pb.PluginRegister{
PluginId: w.id,
Name: w.name,
Version: w.version,
ProtocolVersion: "v1",
Capabilities: capabilities,
}
msg := &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Register{
Register: register,
},
}
return stream.Send(msg)
}
// sendHeartbeats sends periodic heartbeat messages
func (w *Worker) sendHeartbeats(stream plugin_pb.PluginService_ConnectClient) {
defer w.wg.Done()
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-ticker.C:
w.jobsMu.RLock()
pendingJobs := int32(len(w.runningJobs))
w.jobsMu.RUnlock()
heartbeat := &plugin_pb.PluginHeartbeat{
PluginId: w.id,
Timestamp: timestamppb.Now(),
UptimeSeconds: int64(time.Since(time.Now()).Seconds()),
PendingJobs: pendingJobs,
CpuUsagePercent: 0, // TODO: Get actual CPU usage
MemoryUsageMb: 0, // TODO: Get actual memory usage
}
msg := &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Heartbeat{
Heartbeat: heartbeat,
},
}
if err := stream.Send(msg); err != nil {
glog.Errorf("balance worker: failed to send heartbeat: %v", err)
return
}
}
}
}
// executeJobs periodically detects and executes jobs
func (w *Worker) executeJobs(stream plugin_pb.PluginService_ConnectClient) {
defer w.wg.Done()
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-ticker.C:
// TODO: Implement job detection and execution
// Query admin for jobs or use detector to find jobs
}
}
}
// listenForMessages listens for messages from the admin server
func (w *Worker) listenForMessages(stream plugin_pb.PluginService_ConnectClient) {
for {
msg, err := stream.Recv()
if err == io.EOF {
glog.Infof("balance worker: admin closed connection")
return
}
if err != nil {
glog.Errorf("balance worker: failed to receive message: %v", err)
return
}
if msg.Content == nil {
continue
}
switch content := msg.Content.(type) {
case *plugin_pb.AdminMessage_JobRequest:
w.handleJobRequest(content.JobRequest)
case *plugin_pb.AdminMessage_ConfigUpdate:
glog.Infof("balance worker: received config update: %s", content.ConfigUpdate.JobType)
case *plugin_pb.AdminMessage_AdminCommand:
w.handleAdminCommand(content.AdminCommand)
}
}
}
// handleJobRequest processes a job request from the admin
func (w *Worker) handleJobRequest(jobReq *plugin_pb.JobRequest) {
glog.Infof("balance worker: received job request (id=%s, type=%s)", jobReq.JobId, jobReq.JobType)
// Create job context
jobCtx, cancel := context.WithCancel(w.ctx)
w.jobsMu.Lock()
w.runningJobs[jobReq.JobId] = cancel
w.jobsMu.Unlock()
// Execute job in goroutine
w.wg.Add(1)
go func() {
defer w.wg.Done()
defer func() {
w.jobsMu.Lock()
delete(w.runningJobs, jobReq.JobId)
w.jobsMu.Unlock()
}()
w.executeJobRequest(jobCtx, jobReq)
}()
}
// executeJobRequest executes a single job request
func (w *Worker) executeJobRequest(ctx context.Context, jobReq *plugin_pb.JobRequest) {
// Build job config from request
config := &plugin_pb.JobTypeConfig{
JobType: jobReq.JobType,
AdminConfig: nil,
WorkerConfig: jobReq.Config,
}
// Create executor
executor := NewExecutor(jobReq.JobId, config)
// Progress channel
progressChan := make(chan *plugin_pb.JobProgress, 10)
// Execute job
go func() {
if err := executor.Execute(ctx, jobReq.Metadata, progressChan); err != nil {
glog.Errorf("balance worker: job execution failed (id=%s): %v", jobReq.JobId, err)
}
close(progressChan)
}()
// TODO: Send progress updates back to admin via ExecuteJob RPC
for progress := range progressChan {
_ = progress
glog.Infof("balance worker: job %s progress: %d%% (%s)", jobReq.JobId, progress.ProgressPercent, progress.CurrentStep)
}
}
// handleAdminCommand processes admin commands
func (w *Worker) handleAdminCommand(cmd *plugin_pb.AdminCommand) {
glog.Infof("balance worker: received admin command: %v", cmd.CommandType)
switch cmd.CommandType {
case plugin_pb.AdminCommand_RELOAD_CONFIG:
glog.Infof("balance worker: reloading configuration")
case plugin_pb.AdminCommand_ENABLE_JOB_TYPE:
glog.Infof("balance worker: enabling balance job type")
case plugin_pb.AdminCommand_DISABLE_JOB_TYPE:
glog.Infof("balance worker: disabling balance job type")
case plugin_pb.AdminCommand_SHUTDOWN:
glog.Infof("balance worker: received shutdown command")
w.Stop()
}
}
// GetCapabilities returns the worker's capabilities
func (w *Worker) GetCapabilities() []*plugin_pb.JobTypeCapability {
return []*plugin_pb.JobTypeCapability{
{
JobType: "balance",
CanDetect: true,
CanExecute: true,
Version: "v1",
},
}
}
// GetConfigurationSchema returns the configuration schema
func (w *Worker) GetConfigurationSchema() *plugin_pb.JobTypeConfigSchema {
return GetConfigurationSchema()
}
// Run is a convenience method that starts the worker and waits for context cancellation
func (w *Worker) Run(ctx context.Context) error {
if err := w.Start(ctx); err != nil {
return err
}
defer w.Stop()
<-ctx.Done()
return nil
}
// StartWorkerServer starts the balance worker with the given configuration
func StartWorkerServer(masterAddr string, httpPort int) error {
pluginID := fmt.Sprintf("balance_worker_%d", time.Now().Unix())
worker := NewWorker(pluginID, masterAddr, httpPort)
ctx := context.Background()
return worker.Run(ctx)
}
@@ -1,140 +0,0 @@
package erasure_coding
import (
"context"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/durationpb"
)
// Detector scans for volumes that are candidates for erasure coding
type Detector struct {
masterAddr string
}
// NewDetector creates a new erasure coding detector
func NewDetector(masterAddr string) *Detector {
return &Detector{
masterAddr: masterAddr,
}
}
// DetectJobs scans the master for volumes meeting EC criteria
// Returns a list of DetectedJob items sorted by priority (volume size)
func (d *Detector) DetectJobs(ctx context.Context, config *plugin_pb.JobTypeConfig) ([]*plugin_pb.DetectedJob, error) {
var detectedJobs []*plugin_pb.DetectedJob
// Get destination nodes from config
var destinationNodes []string
var ecM, ecN, stripeSize int64
for _, cfv := range config.AdminConfig {
if cfv.FieldName == "destination_data_nodes" {
if cfv.StringValue != "" {
// Parse comma-separated nodes
destinationNodes = append(destinationNodes, cfv.StringValue)
}
}
}
for _, cfv := range config.WorkerConfig {
if cfv.FieldName == "ec_m" {
ecM = cfv.IntValue
} else if cfv.FieldName == "ec_n" {
ecN = cfv.IntValue
} else if cfv.FieldName == "stripe_size" {
stripeSize = cfv.IntValue
}
}
if len(destinationNodes) == 0 {
glog.Warningf("erasure_coding detector: no destination nodes configured")
return detectedJobs, nil
}
if ecM == 0 {
ecM = 10
}
if ecN == 0 {
ecN = 4
}
if stripeSize == 0 {
stripeSize = 65536
}
glog.Infof("erasure_coding detector: scanning for volumes (ecM=%d, ecN=%d)", ecM, ecN)
// Scan master for volumes
// This would typically connect to the master server to get volume information
// For now, we create a framework that can be extended with actual master connectivity
volumes := d.scanVolumes(ctx)
for _, vol := range volumes {
// Check if volume is a candidate for EC
// Criteria: less than 90% full, not already encoded
if vol.fullnessPercent < 90 && !vol.isEncoded {
jobKey := fmt.Sprintf("ec_%s_%s", vol.id, time.Now().Format("20060102"))
// Priority is based on volume size (larger volumes get higher priority)
priority := int64(vol.sizeGB)
job := &plugin_pb.DetectedJob{
JobKey: jobKey,
JobType: "erasure_coding",
Description: fmt.Sprintf("Encode volume %s (%.1f%% full, %dGB)", vol.id, vol.fullnessPercent, vol.sizeGB),
Priority: priority,
EstimatedDuration: durationpb.New(time.Duration(vol.sizeGB) * time.Hour), // Rough estimate
Metadata: map[string]string{
"volume_id": vol.id,
"collection": vol.collection,
"fullness_pct": fmt.Sprintf("%.1f", vol.fullnessPercent),
"size_gb": fmt.Sprintf("%d", vol.sizeGB),
"data_nodes": fmt.Sprintf("%d", len(destinationNodes)),
},
SuggestedConfig: []*plugin_pb.ConfigFieldValue{
{
FieldName: "ec_m",
IntValue: ecM,
},
{
FieldName: "ec_n",
IntValue: ecN,
},
{
FieldName: "stripe_size",
IntValue: stripeSize,
},
},
}
detectedJobs = append(detectedJobs, job)
}
}
glog.Infof("erasure_coding detector: found %d candidate volumes", len(detectedJobs))
return detectedJobs, nil
}
// Volume represents a volume on the cluster
type volume struct {
id string
collection string
sizeGB int64
usedGB int64
fullnessPercent float64
isEncoded bool
replicaPlacement int32
dataNodes []string
}
// scanVolumes performs a scan of available volumes
// This is a placeholder implementation that would connect to master in production
func (d *Detector) scanVolumes(ctx context.Context) []volume {
// TODO: Connect to master server at d.masterAddr and get volume list
// For now, return empty list as a framework
var volumes []volume
return volumes
}
@@ -1,406 +0,0 @@
package erasure_coding
import (
"context"
stdtesting "testing"
"time"
plugintesting "github.com/seaweedfs/seaweedfs/weed/admin/plugin/testing"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// TestECSchemaGeneration tests that the EC plugin generates the correct configuration schema
func TestECSchemaGeneration(t *stdtesting.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
harness := plugintesting.NewTestHarness(ctx)
if err := harness.Setup(); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer harness.Teardown()
// Verify schema fields for EC job type
expectedFields := map[string]bool{
"data_shards": true,
"parity_shards": true,
"block_size": true,
"algorithm": true,
}
configFields := []*plugin_pb.ConfigField{
{
Name: "data_shards",
Label: "Data Shards",
Description: "Number of data shards",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "4",
},
{
Name: "parity_shards",
Label: "Parity Shards",
Description: "Number of parity shards",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "2",
},
{
Name: "block_size",
Label: "Block Size",
Description: "Block size in bytes",
FieldType: plugin_pb.ConfigField_INT,
Required: false,
DefaultValue: "65536",
},
{
Name: "algorithm",
Label: "Algorithm",
Description: "Erasure coding algorithm",
FieldType: plugin_pb.ConfigField_SELECT,
Required: true,
DefaultValue: "reed_solomon",
},
}
// Verify all expected fields are present
for _, field := range configFields {
if _, ok := expectedFields[field.Name]; ok {
if field.FieldType == plugin_pb.ConfigField_INT ||
field.FieldType == plugin_pb.ConfigField_SELECT {
delete(expectedFields, field.Name)
}
}
}
if len(expectedFields) > 0 {
t.Errorf("Missing expected schema fields: %v", expectedFields)
}
}
// TestECDetection tests that the EC plugin can detect jobs
func TestECDetection(t *stdtesting.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
harness := plugintesting.NewTestHarness(ctx)
if err := harness.Setup(); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer harness.Teardown()
// Create mock plugin
plugin := plugintesting.NewMockPlugin("ec-plugin-1", "Erasure Coding", "1.0.0")
plugin.AddCapability("erasure_coding", true, true)
// Simulate detection
detectedJobs, err := plugin.SimulateDetection("erasure_coding", 3)
if err != nil {
t.Fatalf("Detection failed: %v", err)
}
if len(detectedJobs) != 3 {
t.Errorf("Expected 3 detected jobs, got %d", len(detectedJobs))
}
for i, job := range detectedJobs {
if job.JobType != "erasure_coding" {
t.Errorf("Job %d has wrong type: expected erasure_coding, got %s", i, job.JobType)
}
if job.JobKey == "" {
t.Errorf("Job %d missing job key", i)
}
}
}
// TestECExecution tests that the EC plugin can execute jobs
func TestECExecution(t *stdtesting.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
harness := plugintesting.NewTestHarness(ctx)
if err := harness.Setup(); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer harness.Teardown()
// Create mock plugin
plugin := plugintesting.NewMockPlugin("ec-plugin-2", "Erasure Coding", "1.0.0")
plugin.AddCapability("erasure_coding", true, true)
// Create a test job
config := []*plugin_pb.ConfigFieldValue{
{
FieldName: "data_shards",
IntValue: 4,
},
{
FieldName: "parity_shards",
IntValue: 2,
},
}
jobID := "ec-job-test-001"
execution, err := plugin.SimulateExecution(jobID, "erasure_coding", config)
if err != nil {
t.Fatalf("Execution failed: %v", err)
}
if execution.Status != "completed" {
t.Errorf("Expected status 'completed', got %s", execution.Status)
}
if execution.ProgressPercent != 100 {
t.Errorf("Expected progress 100, got %d", execution.ProgressPercent)
}
messages := plugin.GetExecutionMessages(jobID)
if len(messages) == 0 {
t.Fatal("Expected execution messages")
}
// Check for completion message
hasCompletion := false
for _, msg := range messages {
if msg.GetJobCompleted() != nil {
hasCompletion = true
break
}
}
if !hasCompletion {
t.Error("Missing job completion message")
}
}
// TestECErrorHandling tests error scenarios in EC plugin
func TestECErrorHandling(t *stdtesting.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
harness := plugintesting.NewTestHarness(ctx)
if err := harness.Setup(); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer harness.Teardown()
// Test 1: Detection disabled
plugin := plugintesting.NewMockPlugin("ec-plugin-3", "Erasure Coding", "1.0.0")
plugin.AddCapability("erasure_coding", true, true)
plugin.DetectionEnabled = false
_, err := plugin.SimulateDetection("erasure_coding", 1)
if err == nil {
t.Error("Expected error when detection is disabled")
}
// Test 2: Execution failure scenario
plugin.Reset()
plugin.DetectionEnabled = true
plugin.ExecutionEnabled = true
jobID := "ec-job-fail-001"
execution, err := plugin.SimulateExecutionFailure(jobID, "INVALID_CONFIG", "Data shards must be > 0", true)
if err != nil {
t.Fatalf("Execution failure simulation failed: %v", err)
}
if execution.Status != "failed" {
t.Errorf("Expected status 'failed', got %s", execution.Status)
}
if execution.ErrorInfo.ErrorCode != "INVALID_CONFIG" {
t.Errorf("Expected error code 'INVALID_CONFIG', got %s", execution.ErrorInfo.ErrorCode)
}
if !execution.ErrorInfo.Retryable {
t.Error("Expected error to be retryable")
}
// Test 3: Simulated detection error
plugin.SetFailureMode("detection_error")
_, err = plugin.SimulateDetection("erasure_coding", 1)
if err == nil {
t.Error("Expected error in detection with failure mode set")
}
errors := plugin.GetErrors()
if len(errors) == 0 {
t.Error("Expected recorded errors")
}
}
// TestECIntegration tests the full EC plugin workflow
func TestECIntegration(t *stdtesting.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
harness := plugintesting.NewTestHarness(ctx)
if err := harness.Setup(); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer harness.Teardown()
// Create mock admin server
adminServer := harness.GetAdminServer()
_ = adminServer // Keep reference to prevent GC
// Create mock plugin
plugin := plugintesting.NewMockPlugin("ec-plugin-integration", "Erasure Coding", "1.0.0")
plugin.AddCapability("erasure_coding", true, true)
// Step 1: Plugin registration
regMsg := plugin.GetRegistrationMessage()
_ = regMsg // Keep reference
// Step 2: Detect jobs
detectedJobs, err := plugin.SimulateDetection("erasure_coding", 2)
if err != nil {
t.Fatalf("Detection failed: %v", err)
}
if len(detectedJobs) != 2 {
t.Errorf("Expected 2 detected jobs, got %d", len(detectedJobs))
}
// Step 3: Create jobs from detection
for i, detectedJob := range detectedJobs {
job := harness.CreateJob(
"erasure_coding",
detectedJob.Description,
detectedJob.Priority,
detectedJob.SuggestedConfig,
)
// Step 4: Execute job with plugin simulation
_, err := plugin.SimulateExecution(job.JobId, "erasure_coding", job.Config)
if err != nil {
t.Errorf("Failed to execute job %d: %v", i, err)
continue
}
// Track in harness
_ = harness.ExecuteJob(job)
// Complete the job
if err := harness.CompleteJob(job.JobId, "Erasure coding completed", map[string]string{
"blocks_encoded": "1000",
}); err != nil {
t.Errorf("Failed to complete job %d: %v", i, err)
}
// Verify job status
if err := harness.AssertJobStatus(job.JobId, "completed"); err != nil {
t.Errorf("Job %d status verification failed: %v", i, err)
}
// Verify progress
if err := harness.VerifyProgress(job.JobId, 100); err != nil {
t.Errorf("Job %d progress verification failed: %v", i, err)
}
}
// Verify call counts
detectionCalls := plugin.GetCallCount("detection")
if detectionCalls == 0 {
t.Error("Expected at least one detection call")
}
executionCalls := plugin.GetCallCount("execution")
if executionCalls != 2 {
t.Errorf("Expected 2 execution calls, got %d", executionCalls)
}
}
// TestECConfigurationValidation tests configuration field validation
func TestECConfigurationValidation(t *stdtesting.T) {
tests := []struct {
name string
config *plugin_pb.ConfigFieldValue
wantErr bool
}{
{
name: "valid data shards",
config: &plugin_pb.ConfigFieldValue{
FieldName: "data_shards",
IntValue: 4,
},
wantErr: false,
},
{
name: "invalid data shards - zero",
config: &plugin_pb.ConfigFieldValue{
FieldName: "data_shards",
IntValue: 0,
},
wantErr: true,
},
{
name: "valid parity shards",
config: &plugin_pb.ConfigFieldValue{
FieldName: "parity_shards",
IntValue: 2,
},
wantErr: false,
},
{
name: "negative parity shards",
config: &plugin_pb.ConfigFieldValue{
FieldName: "parity_shards",
IntValue: -1,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *stdtesting.T) {
// Validate configuration
var hasError bool
// Simple validation: data_shards > 0, parity_shards >= 0
if tt.config.FieldName == "data_shards" && tt.config.IntValue <= 0 {
hasError = true
}
if tt.config.FieldName == "parity_shards" && tt.config.IntValue < 0 {
hasError = true
}
if hasError != tt.wantErr {
t.Errorf("validation error: expected %v, got %v", tt.wantErr, hasError)
}
})
}
}
// BenchmarkECDetection benchmarks the detection performance
func BenchmarkECDetection(b *stdtesting.B) {
plugin := plugintesting.NewMockPlugin("ec-plugin-bench", "Erasure Coding", "1.0.0")
plugin.AddCapability("erasure_coding", true, true)
plugin.SetDetectionDelay(0) // No delay for benchmark
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = plugin.SimulateDetection("erasure_coding", 10)
}
}
// BenchmarkECExecution benchmarks the execution performance
func BenchmarkECExecution(b *stdtesting.B) {
plugin := plugintesting.NewMockPlugin("ec-plugin-bench-exec", "Erasure Coding", "1.0.0")
plugin.AddCapability("erasure_coding", true, true)
plugin.SetExecutionDelay(0) // No delay for benchmark
config := []*plugin_pb.ConfigFieldValue{
{
FieldName: "data_shards",
IntValue: 4,
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
jobID := "bench-job-" + string(rune(i))
_, _ = plugin.SimulateExecution(jobID, "erasure_coding", config)
}
}
@@ -1,211 +0,0 @@
package erasure_coding
import (
"context"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Executor handles the 6-step erasure coding execution process
type Executor struct {
jobID string
volumeID string
config *plugin_pb.JobTypeConfig
}
// NewExecutor creates a new erasure coding executor
func NewExecutor(jobID string, config *plugin_pb.JobTypeConfig) *Executor {
return &Executor{
jobID: jobID,
config: config,
}
}
// ExecutionStep represents a single step in the EC process
type ExecutionStep struct {
StepNumber int
Name string
Description string
}
// Execute runs the 6-step erasure coding process
// Returns progress updates via the progressChan
func (e *Executor) Execute(ctx context.Context, metadata map[string]string, progressChan chan<- *plugin_pb.JobProgress) error {
volumeID := metadata["volume_id"]
e.volumeID = volumeID
steps := []ExecutionStep{
{StepNumber: 1, Name: "markVolumeReadonly", Description: "Mark volume as read-only"},
{StepNumber: 2, Name: "copyVolumeFilesToWorker", Description: "Copy volume files to worker"},
{StepNumber: 3, Name: "generateEcShards", Description: "Generate erasure coding shards"},
{StepNumber: 4, Name: "distributeEcShards", Description: "Distribute shards to data nodes"},
{StepNumber: 5, Name: "mountEcShards", Description: "Mount shards on target nodes"},
{StepNumber: 6, Name: "deleteOriginalVolume", Description: "Delete original volume"},
}
totalSteps := len(steps)
for i, step := range steps {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
glog.Infof("erasure_coding executor job=%s: executing step %d: %s", e.jobID, step.StepNumber, step.Name)
// Send progress update before executing step
progress := int32((i * 100) / totalSteps)
progressChan <- &plugin_pb.JobProgress{
ProgressPercent: progress,
CurrentStep: step.Name,
StatusMessage: step.Description,
UpdatedAt: timestamppb.Now(),
}
var err error
switch step.StepNumber {
case 1:
err = e.markVolumeReadonly(ctx)
case 2:
err = e.copyVolumeFilesToWorker(ctx)
case 3:
err = e.generateEcShards(ctx)
case 4:
err = e.distributeEcShards(ctx)
case 5:
err = e.mountEcShards(ctx)
case 6:
err = e.deleteOriginalVolume(ctx)
}
if err != nil {
glog.Errorf("erasure_coding executor job=%s: step %d failed: %v", e.jobID, step.StepNumber, err)
return fmt.Errorf("step %d (%s) failed: %w", step.StepNumber, step.Name, err)
}
glog.Infof("erasure_coding executor job=%s: step %d completed", e.jobID, step.StepNumber)
}
// Send final progress update
progressChan <- &plugin_pb.JobProgress{
ProgressPercent: 100,
CurrentStep: "complete",
StatusMessage: "Erasure coding completed successfully",
UpdatedAt: timestamppb.Now(),
}
glog.Infof("erasure_coding executor job=%s: all steps completed", e.jobID)
return nil
}
// Step 1: markVolumeReadonly marks the volume as read-only
func (e *Executor) markVolumeReadonly(ctx context.Context) error {
glog.Infof("erasure_coding executor job=%s: marking volume %s as read-only", e.jobID, e.volumeID)
// TODO: Connect to master and mark volume as read-only
// This prevents new writes during encoding
return nil
}
// Step 2: copyVolumeFilesToWorker copies volume data to the worker
func (e *Executor) copyVolumeFilesToWorker(ctx context.Context) error {
glog.Infof("erasure_coding executor job=%s: copying volume files for %s", e.jobID, e.volumeID)
// TODO: Transfer volume files from storage nodes to worker
// This includes the .idx and .dat files
return nil
}
// Step 3: generateEcShards generates erasure coding shards
func (e *Executor) generateEcShards(ctx context.Context) error {
glog.Infof("erasure_coding executor job=%s: generating EC shards for volume %s", e.jobID, e.volumeID)
// Extract config values
var ecM, ecN, stripeSize int64
for _, cfv := range e.config.WorkerConfig {
if cfv.FieldName == "ec_m" {
ecM = cfv.IntValue
} else if cfv.FieldName == "ec_n" {
ecN = cfv.IntValue
} else if cfv.FieldName == "stripe_size" {
stripeSize = cfv.IntValue
}
}
if ecM == 0 {
ecM = 10
}
if ecN == 0 {
ecN = 4
}
if stripeSize == 0 {
stripeSize = 65536
}
glog.Infof("erasure_coding executor job=%s: encoding with M=%d, N=%d, stripe_size=%d", e.jobID, ecM, ecN, stripeSize)
// TODO: Use libReedSolomon or similar library to generate EC shards
// This creates M data shards and N parity shards
return nil
}
// Step 4: distributeEcShards distributes shards to data nodes
func (e *Executor) distributeEcShards(ctx context.Context) error {
glog.Infof("erasure_coding executor job=%s: distributing EC shards to destination nodes", e.jobID)
// Extract destination nodes from config
var destinationNodes []string
for _, cfv := range e.config.AdminConfig {
if cfv.FieldName == "destination_data_nodes" {
if cfv.StringValue != "" {
destinationNodes = append(destinationNodes, cfv.StringValue)
}
}
}
glog.Infof("erasure_coding executor job=%s: distributing to %d destination nodes", e.jobID, len(destinationNodes))
// TODO: Send shards to each destination data node
// Balance shards across available nodes
return nil
}
// Step 5: mountEcShards mounts the shards on their target nodes
func (e *Executor) mountEcShards(ctx context.Context) error {
glog.Infof("erasure_coding executor job=%s: mounting EC shards", e.jobID)
// TODO: Notify data nodes to mount the EC shards
// Register shards with master server
return nil
}
// Step 6: deleteOriginalVolume deletes the original volume if configured
func (e *Executor) deleteOriginalVolume(ctx context.Context) error {
// Check if delete_source is enabled
var deleteSource bool
for _, cfv := range e.config.AdminConfig {
if cfv.FieldName == "delete_source" {
deleteSource = cfv.BoolValue
}
}
if !deleteSource {
glog.Infof("erasure_coding executor job=%s: skipping deletion of original volume (delete_source=false)", e.jobID)
return nil
}
glog.Infof("erasure_coding executor job=%s: deleting original volume %s", e.jobID, e.volumeID)
// TODO: Delete the original volume from the master
// This frees up space on the storage nodes
return nil
}
@@ -1,162 +0,0 @@
package erasure_coding
import (
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// GetConfigurationSchema returns the configuration schema for the erasure coding job type
func GetConfigurationSchema() *plugin_pb.JobTypeConfigSchema {
return &plugin_pb.JobTypeConfigSchema{
JobType: "erasure_coding",
Version: "v1",
Description: "Automatically encode volumes using erasure coding for improved storage efficiency",
AdminFields: []*plugin_pb.ConfigField{
{
Name: "destination_data_nodes",
Label: "Destination Data Nodes",
Description: "List of data nodes where EC shards should be distributed",
FieldType: plugin_pb.ConfigField_STRING,
Required: true,
DefaultValue: "",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_LENGTH,
Value: "1",
ErrorMessage: "At least one destination node must be specified",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
Placeholder: "node1,node2,node3",
},
},
{
Name: "threshold",
Label: "Failure Threshold",
Description: "Number of data shards that can be lost before data is unrecoverable (1-99)",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "2",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "1",
ErrorMessage: "Threshold must be at least 1",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "99",
ErrorMessage: "Threshold must be at most 99",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 1,
MaxValue: 99,
},
},
{
Name: "delete_source",
Label: "Delete Source After Encoding",
Description: "Whether to delete the original volume after successful EC encoding",
FieldType: plugin_pb.ConfigField_BOOL,
Required: false,
DefaultValue: "true",
},
},
WorkerFields: []*plugin_pb.ConfigField{
{
Name: "ec_m",
Label: "Data Shards (M)",
Description: "Number of data shards for erasure coding",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "10",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "1",
ErrorMessage: "Data shards must be at least 1",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "32",
ErrorMessage: "Data shards must be at most 32",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 1,
MaxValue: 32,
},
},
{
Name: "ec_n",
Label: "Parity Shards (N)",
Description: "Number of parity shards for erasure coding",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "4",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "1",
ErrorMessage: "Parity shards must be at least 1",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "32",
ErrorMessage: "Parity shards must be at most 32",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 1,
MaxValue: 32,
},
},
{
Name: "stripe_size",
Label: "Stripe Size (bytes)",
Description: "Size of data chunks used in erasure coding (must be power of 2)",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "65536",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "4096",
ErrorMessage: "Stripe size must be at least 4096 bytes",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "1048576",
ErrorMessage: "Stripe size must be at most 1MB",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 4096,
MaxValue: 1048576,
},
},
},
FieldGroups: []*plugin_pb.ConfigGroup{
{
Name: "general",
Label: "General",
Description: "Basic configuration for erasure coding",
FieldNames: []string{
"destination_data_nodes",
"threshold",
"delete_source",
},
},
{
Name: "advanced",
Label: "Advanced",
Description: "Advanced erasure coding parameters",
FieldNames: []string{
"ec_m",
"ec_n",
"stripe_size",
},
},
},
}
}
@@ -1,368 +0,0 @@
package erasure_coding
import (
"context"
"fmt"
"io"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Worker is the main erasure coding plugin worker
type Worker struct {
id string
name string
version string
masterAddr string
httpPort int
// gRPC connection
conn *grpc.ClientConn
client plugin_pb.PluginServiceClient
// Detector and executor
detector *Detector
// Context and coordination
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
// Running jobs
jobsMu sync.RWMutex
runningJobs map[string]context.CancelFunc
}
// NewWorker creates a new erasure coding worker
func NewWorker(id, masterAddr string, httpPort int) *Worker {
return &Worker{
id: id,
name: "erasure_coding_worker",
version: "v1",
masterAddr: masterAddr,
httpPort: httpPort,
runningJobs: make(map[string]context.CancelFunc),
detector: NewDetector(masterAddr),
}
}
// Start starts the worker and connects to the admin server
func (w *Worker) Start(ctx context.Context) error {
glog.Infof("erasure_coding worker: starting (id=%s, master=%s, httpPort=%d)", w.id, w.masterAddr, w.httpPort)
w.ctx, w.cancel = context.WithCancel(ctx)
// Connect to admin server via gRPC
// Admin server runs on httpPort + 10000
adminPort := w.httpPort + 10000
adminAddr := fmt.Sprintf("localhost:%d", adminPort)
glog.Infof("erasure_coding worker: connecting to admin at %s", adminAddr)
conn, err := grpc.Dial(adminAddr, grpc.WithInsecure())
if err != nil {
return fmt.Errorf("failed to connect to admin server: %w", err)
}
w.conn = conn
w.client = plugin_pb.NewPluginServiceClient(conn)
// Start connection handler in goroutine
w.wg.Add(1)
go w.handleConnection()
return nil
}
// Stop stops the worker and closes all connections
func (w *Worker) Stop() error {
glog.Infof("erasure_coding worker: stopping (id=%s)", w.id)
// Cancel context to signal all goroutines
if w.cancel != nil {
w.cancel()
}
// Wait for goroutines with timeout
done := make(chan struct{})
go func() {
w.wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(10 * time.Second):
glog.Warningf("erasure_coding worker: graceful shutdown timeout")
}
// Close gRPC connection
if w.conn != nil {
if err := w.conn.Close(); err != nil {
glog.Errorf("erasure_coding worker: error closing gRPC connection: %v", err)
}
}
glog.Infof("erasure_coding worker: stopped")
return nil
}
// handleConnection handles the bidirectional gRPC connection with the admin server
func (w *Worker) handleConnection() {
defer w.wg.Done()
glog.Infof("erasure_coding worker: establishing bidirectional stream")
// Create bidirectional stream
stream, err := w.client.Connect(w.ctx)
if err != nil {
glog.Errorf("erasure_coding worker: failed to create stream: %v", err)
return
}
// Send registration message
if err := w.sendRegistration(stream); err != nil {
glog.Errorf("erasure_coding worker: failed to send registration: %v", err)
return
}
// Start heartbeat goroutine
w.wg.Add(1)
go w.sendHeartbeats(stream)
// Start job executor goroutine
w.wg.Add(1)
go w.executeJobs(stream)
// Listen for messages from admin
w.listenForMessages(stream)
glog.Infof("erasure_coding worker: connection closed")
}
// sendRegistration sends the initial registration message
func (w *Worker) sendRegistration(stream plugin_pb.PluginService_ConnectClient) error {
capabilities := []*plugin_pb.JobTypeCapability{
{
JobType: "erasure_coding",
CanDetect: true,
CanExecute: true,
Version: "v1",
},
}
register := &plugin_pb.PluginRegister{
PluginId: w.id,
Name: w.name,
Version: w.version,
ProtocolVersion: "v1",
Capabilities: capabilities,
}
msg := &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Register{
Register: register,
},
}
return stream.Send(msg)
}
// sendHeartbeats sends periodic heartbeat messages
func (w *Worker) sendHeartbeats(stream plugin_pb.PluginService_ConnectClient) {
defer w.wg.Done()
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-ticker.C:
w.jobsMu.RLock()
pendingJobs := int32(len(w.runningJobs))
w.jobsMu.RUnlock()
heartbeat := &plugin_pb.PluginHeartbeat{
PluginId: w.id,
Timestamp: timestamppb.Now(),
UptimeSeconds: int64(time.Since(time.Now()).Seconds()),
PendingJobs: pendingJobs,
CpuUsagePercent: 0, // TODO: Get actual CPU usage
MemoryUsageMb: 0, // TODO: Get actual memory usage
}
msg := &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Heartbeat{
Heartbeat: heartbeat,
},
}
if err := stream.Send(msg); err != nil {
glog.Errorf("erasure_coding worker: failed to send heartbeat: %v", err)
return
}
}
}
}
// executeJobs periodically detects and executes jobs
func (w *Worker) executeJobs(stream plugin_pb.PluginService_ConnectClient) {
defer w.wg.Done()
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-ticker.C:
// TODO: Implement job detection and execution
// Query admin for jobs or use detector to find jobs
}
}
}
// listenForMessages listens for messages from the admin server
func (w *Worker) listenForMessages(stream plugin_pb.PluginService_ConnectClient) {
for {
msg, err := stream.Recv()
if err == io.EOF {
glog.Infof("erasure_coding worker: admin closed connection")
return
}
if err != nil {
glog.Errorf("erasure_coding worker: failed to receive message: %v", err)
return
}
if msg.Content == nil {
continue
}
switch content := msg.Content.(type) {
case *plugin_pb.AdminMessage_JobRequest:
w.handleJobRequest(content.JobRequest)
case *plugin_pb.AdminMessage_ConfigUpdate:
glog.Infof("erasure_coding worker: received config update: %s", content.ConfigUpdate.JobType)
case *plugin_pb.AdminMessage_AdminCommand:
w.handleAdminCommand(content.AdminCommand)
}
}
}
// handleJobRequest processes a job request from the admin
func (w *Worker) handleJobRequest(jobReq *plugin_pb.JobRequest) {
glog.Infof("erasure_coding worker: received job request (id=%s, type=%s)", jobReq.JobId, jobReq.JobType)
// Create job context
jobCtx, cancel := context.WithCancel(w.ctx)
w.jobsMu.Lock()
w.runningJobs[jobReq.JobId] = cancel
w.jobsMu.Unlock()
// Execute job in goroutine
w.wg.Add(1)
go func() {
defer w.wg.Done()
defer func() {
w.jobsMu.Lock()
delete(w.runningJobs, jobReq.JobId)
w.jobsMu.Unlock()
}()
w.executeJobRequest(jobCtx, jobReq)
}()
}
// executeJobRequest executes a single job request
func (w *Worker) executeJobRequest(ctx context.Context, jobReq *plugin_pb.JobRequest) {
// Build job config from request
config := &plugin_pb.JobTypeConfig{
JobType: jobReq.JobType,
AdminConfig: nil,
WorkerConfig: jobReq.Config,
}
// Create executor
executor := NewExecutor(jobReq.JobId, config)
// Progress channel
progressChan := make(chan *plugin_pb.JobProgress, 10)
// Execute job
go func() {
if err := executor.Execute(ctx, jobReq.Metadata, progressChan); err != nil {
glog.Errorf("erasure_coding worker: job execution failed (id=%s): %v", jobReq.JobId, err)
}
close(progressChan)
}()
// TODO: Send progress updates back to admin via ExecuteJob RPC
for progress := range progressChan {
_ = progress
glog.Infof("erasure_coding worker: job %s progress: %d%%", jobReq.JobId, progress.ProgressPercent)
}
}
// handleAdminCommand processes admin commands
func (w *Worker) handleAdminCommand(cmd *plugin_pb.AdminCommand) {
glog.Infof("erasure_coding worker: received admin command: %v", cmd.CommandType)
switch cmd.CommandType {
case plugin_pb.AdminCommand_RELOAD_CONFIG:
glog.Infof("erasure_coding worker: reloading configuration")
case plugin_pb.AdminCommand_ENABLE_JOB_TYPE:
glog.Infof("erasure_coding worker: enabling erasure_coding job type")
case plugin_pb.AdminCommand_DISABLE_JOB_TYPE:
glog.Infof("erasure_coding worker: disabling erasure_coding job type")
case plugin_pb.AdminCommand_SHUTDOWN:
glog.Infof("erasure_coding worker: received shutdown command")
w.Stop()
}
}
// GetCapabilities returns the worker's capabilities
func (w *Worker) GetCapabilities() []*plugin_pb.JobTypeCapability {
return []*plugin_pb.JobTypeCapability{
{
JobType: "erasure_coding",
CanDetect: true,
CanExecute: true,
Version: "v1",
},
}
}
// GetConfigurationSchema returns the configuration schema
func (w *Worker) GetConfigurationSchema() *plugin_pb.JobTypeConfigSchema {
return GetConfigurationSchema()
}
// Run is a convenience method that starts the worker and waits for context cancellation
func (w *Worker) Run(ctx context.Context) error {
if err := w.Start(ctx); err != nil {
return err
}
defer w.Stop()
<-ctx.Done()
return nil
}
// StartWorkerServer starts the erasure coding worker with the given configuration
func StartWorkerServer(masterAddr string, httpPort int) error {
pluginID := fmt.Sprintf("ec_worker_%d", time.Now().Unix())
worker := NewWorker(pluginID, masterAddr, httpPort)
ctx := context.Background()
return worker.Run(ctx)
}
@@ -1,146 +0,0 @@
package vacuum
import (
"context"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/durationpb"
)
// Detector scans for volumes that are candidates for vacuuming
type Detector struct {
masterAddr string
}
// VolumeInfo represents volume information for vacuum detection
type VolumeInfo struct {
ID string
Collection string
SizeGB int64
UsedGB int64
GarbageRatio float64
CreatedAt time.Time
LastVacuumAt time.Time
Replicas int32
}
// NewDetector creates a new vacuum detector
func NewDetector(masterAddr string) *Detector {
return &Detector{
masterAddr: masterAddr,
}
}
// DetectJobs scans for volumes with high garbage ratio that meet vacuum criteria
// Returns a list of DetectedJob items sorted by garbage size (highest priority first)
func (d *Detector) DetectJobs(ctx context.Context, config *plugin_pb.JobTypeConfig) ([]*plugin_pb.DetectedJob, error) {
var detectedJobs []*plugin_pb.DetectedJob
// Extract configuration parameters
garbageThreshold := float64(30) // default 30%
minVolumeAge := 24 * time.Hour // default 24h
minInterval := 7 * 24 * time.Hour // default 7d
compactLevel := int64(2)
enableCleanup := true
for _, cfv := range config.AdminConfig {
if cfv.FieldName == "garbageThreshold" {
garbageThreshold = float64(cfv.IntValue)
} else if cfv.FieldName == "minVolumeAge" {
if dur, err := time.ParseDuration(cfv.StringValue); err == nil {
minVolumeAge = dur
}
} else if cfv.FieldName == "minInterval" {
if dur, err := time.ParseDuration(cfv.StringValue); err == nil {
minInterval = dur
}
}
}
for _, cfv := range config.WorkerConfig {
if cfv.FieldName == "compactLevel" {
compactLevel = cfv.IntValue
} else if cfv.FieldName == "enableCleanup" {
enableCleanup = cfv.BoolValue
}
}
glog.Infof("vacuum detector: scanning volumes (threshold=%.1f%%, minVolumeAge=%v, minInterval=%v)",
garbageThreshold, minVolumeAge, minInterval)
// Scan volumes from master
volumes := d.scanVolumes(ctx)
now := time.Now()
for _, vol := range volumes {
// Check if volume meets garbage ratio threshold
if vol.GarbageRatio < garbageThreshold/100.0 {
continue
}
// Check if volume is old enough
volumeAge := now.Sub(vol.CreatedAt)
if volumeAge < minVolumeAge {
continue
}
// Check if minimum interval has passed since last vacuum
timeSinceLastVacuum := now.Sub(vol.LastVacuumAt)
if timeSinceLastVacuum < minInterval {
continue
}
// Calculate priority based on garbage size (larger garbage = higher priority)
garbageGB := float64(vol.UsedGB) * vol.GarbageRatio
priority := int64(garbageGB * 1000) // Scale to get better ordering
jobKey := fmt.Sprintf("vacuum_%s_%s", vol.ID, now.Format("20060102150405"))
job := &plugin_pb.DetectedJob{
JobKey: jobKey,
JobType: "vacuum",
Description: fmt.Sprintf("Vacuum volume %s (garbage ratio %.1f%%, %dGB used, %.1fGB garbage)",
vol.ID, vol.GarbageRatio*100, vol.UsedGB, garbageGB),
Priority: priority,
EstimatedDuration: durationpb.New(time.Duration(vol.UsedGB) * time.Minute), // Rough estimate
Metadata: map[string]string{
"volume_id": vol.ID,
"collection": vol.Collection,
"garbage_ratio": fmt.Sprintf("%.2f", vol.GarbageRatio),
"garbage_size_gb": fmt.Sprintf("%.1f", garbageGB),
"used_gb": fmt.Sprintf("%d", vol.UsedGB),
"volume_age": volumeAge.String(),
"last_vacuum_ago": timeSinceLastVacuum.String(),
},
SuggestedConfig: []*plugin_pb.ConfigFieldValue{
{
FieldName: "compactLevel",
IntValue: compactLevel,
},
{
FieldName: "enableCleanup",
BoolValue: enableCleanup,
},
},
}
detectedJobs = append(detectedJobs, job)
glog.Infof("vacuum detector: detected job for volume %s (garbage=%.1fGB, priority=%d)",
vol.ID, garbageGB, priority)
}
glog.Infof("vacuum detector: found %d volumes to vacuum", len(detectedJobs))
return detectedJobs, nil
}
// scanVolumes performs a scan of available volumes from the master
// This is a placeholder that would connect to master in production
func (d *Detector) scanVolumes(ctx context.Context) []VolumeInfo {
// TODO: Connect to master server at d.masterAddr and get volume list
// For now, return empty list as a framework
var volumes []VolumeInfo
return volumes
}
@@ -1,186 +0,0 @@
package vacuum
import (
"context"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Executor handles the 3-step vacuum execution process
type Executor struct {
jobID string
volumeID string
config *plugin_pb.JobTypeConfig
}
// ExecutionStep represents a single step in the vacuum process
type ExecutionStep struct {
StepNumber int
Name string
Description string
}
// NewExecutor creates a new vacuum executor
func NewExecutor(jobID string, config *plugin_pb.JobTypeConfig) *Executor {
return &Executor{
jobID: jobID,
config: config,
}
}
// Execute runs the 3-step vacuum process
// Step 1: vacuumVolumeCheck - Verify conditions are still met
// Step 2: vacuumVolumeCompact - Compact and defragment volume
// Step 3: vacuumVolumeCleanup - Clean up deleted space if enableCleanup is true
// Returns progress updates via the progressChan
func (e *Executor) Execute(ctx context.Context, metadata map[string]string, progressChan chan<- *plugin_pb.JobProgress) error {
volumeID := metadata["volume_id"]
e.volumeID = volumeID
steps := []ExecutionStep{
{StepNumber: 1, Name: "vacuumVolumeCheck", Description: "Verify vacuum conditions are still met"},
{StepNumber: 2, Name: "vacuumVolumeCompact", Description: "Compact and defragment volume data"},
{StepNumber: 3, Name: "vacuumVolumeCleanup", Description: "Clean up deleted space"},
}
totalSteps := len(steps)
for i, step := range steps {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
glog.Infof("vacuum executor job=%s: executing step %d: %s", e.jobID, step.StepNumber, step.Name)
// Send progress update before executing step
progress := int32((i * 100) / totalSteps)
progressChan <- &plugin_pb.JobProgress{
ProgressPercent: progress,
CurrentStep: step.Name,
StatusMessage: step.Description,
UpdatedAt: timestamppb.Now(),
}
var err error
switch step.StepNumber {
case 1:
err = e.vacuumVolumeCheck(ctx)
case 2:
err = e.vacuumVolumeCompact(ctx)
case 3:
err = e.vacuumVolumeCleanup(ctx)
}
if err != nil {
glog.Errorf("vacuum executor job=%s: step %d failed: %v", e.jobID, step.StepNumber, err)
return fmt.Errorf("step %d (%s) failed: %w", step.StepNumber, step.Name, err)
}
glog.Infof("vacuum executor job=%s: step %d completed", e.jobID, step.StepNumber)
}
// Send final progress update
progressChan <- &plugin_pb.JobProgress{
ProgressPercent: 100,
CurrentStep: "complete",
StatusMessage: "Vacuum completed successfully",
UpdatedAt: timestamppb.Now(),
}
glog.Infof("vacuum executor job=%s: all steps completed", e.jobID)
return nil
}
// Step 1: vacuumVolumeCheck verifies that vacuum conditions are still met
// before proceeding with the operation
func (e *Executor) vacuumVolumeCheck(ctx context.Context) error {
glog.Infof("vacuum executor job=%s: checking vacuum eligibility for volume %s", e.jobID, e.volumeID)
// Extract garbage threshold from config
var garbageThreshold float64 = 30
for _, cfv := range e.config.AdminConfig {
if cfv.FieldName == "garbageThreshold" {
garbageThreshold = float64(cfv.IntValue)
}
}
// TODO: Connect to master and query volume status
// Check current garbage ratio
// Verify volume hasn't changed significantly since detection
// Return error if conditions no longer met
glog.Infof("vacuum executor job=%s: volume %s meets vacuum criteria (threshold=%.1f%%)",
e.jobID, e.volumeID, garbageThreshold)
return nil
}
// Step 2: vacuumVolumeCompact compacts and defragments the volume
// This is the main vacuum operation that reclaims space
func (e *Executor) vacuumVolumeCompact(ctx context.Context) error {
glog.Infof("vacuum executor job=%s: compacting volume %s", e.jobID, e.volumeID)
// Extract compaction level from config
var compactLevel int64 = 2
for _, cfv := range e.config.WorkerConfig {
if cfv.FieldName == "compactLevel" {
compactLevel = cfv.IntValue
}
}
glog.Infof("vacuum executor job=%s: using compaction level %d for volume %s",
e.jobID, compactLevel, e.volumeID)
// TODO: Connect to volume server and perform compaction
// 1. Read volume data, skip deleted entries
// 2. Rewrite volume file without garbage
// 3. Update volume metadata
// 4. Report compaction progress
//
// The compaction process should:
// - Read the volume's .dat and .idx files
// - Skip entries marked as deleted
// - Write new .dat file with only valid entries
// - Update .idx file with new offsets
// - Use compactLevel to determine aggressiveness:
// Level 0: Minimal compaction (fast, least space saved)
// Level 5: Aggressive compaction (slower, maximum space saved)
return nil
}
// Step 3: vacuumVolumeCleanup cleans up deleted space if enabled
// This step frees up disk space after compaction
func (e *Executor) vacuumVolumeCleanup(ctx context.Context) error {
// Extract enableCleanup flag from config
enableCleanup := true
for _, cfv := range e.config.WorkerConfig {
if cfv.FieldName == "enableCleanup" {
enableCleanup = cfv.BoolValue
}
}
if !enableCleanup {
glog.Infof("vacuum executor job=%s: skipping cleanup for volume %s (enableCleanup=false)",
e.jobID, e.volumeID)
return nil
}
glog.Infof("vacuum executor job=%s: cleaning up deleted space for volume %s", e.jobID, e.volumeID)
// TODO: Connect to volume server and perform cleanup
// 1. Frees unused space at the end of volume files
// 2. Truncates .dat file to actual size
// 3. Optimizes file system allocation
// 4. Updates volume metadata with new sizes
//
// The cleanup process should:
// - Trim excess capacity from the volume files
// - Update volume size metadata on master
// - Log space reclaimed
return nil
}
-131
View File
@@ -1,131 +0,0 @@
package vacuum
import (
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// GetConfigurationSchema returns the configuration schema for the vacuum job type
func GetConfigurationSchema() *plugin_pb.JobTypeConfigSchema {
return &plugin_pb.JobTypeConfigSchema{
JobType: "vacuum",
Version: "v1",
Description: "Automatically vacuum volumes to reclaim space by removing deleted entries",
AdminFields: []*plugin_pb.ConfigField{
{
Name: "garbageThreshold",
Label: "Garbage Threshold (%)",
Description: "Vacuum volumes when garbage ratio exceeds this percentage (0-100)",
FieldType: plugin_pb.ConfigField_INT,
Required: true,
DefaultValue: "30",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "0",
ErrorMessage: "Garbage threshold must be at least 0",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "100",
ErrorMessage: "Garbage threshold must be at most 100",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 0,
MaxValue: 100,
},
},
{
Name: "minVolumeAge",
Label: "Minimum Volume Age",
Description: "Skip vacuuming volumes created less than this duration ago (format: 24h, 7d, etc.)",
FieldType: plugin_pb.ConfigField_STRING,
Required: false,
DefaultValue: "24h",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_PATTERN,
Value: "^(\\d+[smhd])+$",
ErrorMessage: "Must be a valid duration (e.g., 24h, 7d, 30m)",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
Placeholder: "24h",
},
},
{
Name: "minInterval",
Label: "Minimum Interval Between Vacuums",
Description: "Don't vacuum the same volume more frequently than this interval (format: 7d, 168h, etc.)",
FieldType: plugin_pb.ConfigField_STRING,
Required: false,
DefaultValue: "7d",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_PATTERN,
Value: "^(\\d+[smhd])+$",
ErrorMessage: "Must be a valid duration (e.g., 7d, 168h, 1w)",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
Placeholder: "7d",
},
},
},
WorkerFields: []*plugin_pb.ConfigField{
{
Name: "compactLevel",
Label: "Compaction Level",
Description: "Compaction level for volume defragmentation (0-5, higher = more aggressive)",
FieldType: plugin_pb.ConfigField_INT,
Required: false,
DefaultValue: "2",
ValidationRules: []*plugin_pb.ValidationRule{
{
RuleType: plugin_pb.ValidationRule_MIN_VALUE,
Value: "0",
ErrorMessage: "Compaction level must be at least 0",
},
{
RuleType: plugin_pb.ValidationRule_MAX_VALUE,
Value: "5",
ErrorMessage: "Compaction level must be at most 5",
},
},
OptionsMsg: &plugin_pb.ConfigField_Options{
MinValue: 0,
MaxValue: 5,
},
},
{
Name: "enableCleanup",
Label: "Enable Space Cleanup",
Description: "Whether to clean up and release deleted space after compaction",
FieldType: plugin_pb.ConfigField_BOOL,
Required: false,
DefaultValue: "true",
},
},
FieldGroups: []*plugin_pb.ConfigGroup{
{
Name: "Vacuum Settings",
Label: "Vacuum Settings",
Description: "Configuration for volume vacuuming and garbage collection",
FieldNames: []string{
"garbageThreshold",
"minVolumeAge",
"minInterval",
},
},
{
Name: "advanced",
Label: "Advanced",
Description: "Advanced vacuum parameters",
FieldNames: []string{
"compactLevel",
"enableCleanup",
},
},
},
}
}
-368
View File
@@ -1,368 +0,0 @@
package vacuum
import (
"context"
"fmt"
"io"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Worker is the main vacuum plugin worker
type Worker struct {
id string
name string
version string
masterAddr string
httpPort int
// gRPC connection
conn *grpc.ClientConn
client plugin_pb.PluginServiceClient
// Detector and executor
detector *Detector
// Context and coordination
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
// Running jobs
jobsMu sync.RWMutex
runningJobs map[string]context.CancelFunc
}
// NewWorker creates a new vacuum worker
func NewWorker(id, masterAddr string, httpPort int) *Worker {
return &Worker{
id: id,
name: "vacuum_worker",
version: "v1",
masterAddr: masterAddr,
httpPort: httpPort,
runningJobs: make(map[string]context.CancelFunc),
detector: NewDetector(masterAddr),
}
}
// Start starts the worker and connects to the admin server
func (w *Worker) Start(ctx context.Context) error {
glog.Infof("vacuum worker: starting (id=%s, master=%s, httpPort=%d)", w.id, w.masterAddr, w.httpPort)
w.ctx, w.cancel = context.WithCancel(ctx)
// Connect to admin server via gRPC
// Admin server runs on httpPort + 10000
adminPort := w.httpPort + 10000
adminAddr := fmt.Sprintf("localhost:%d", adminPort)
glog.Infof("vacuum worker: connecting to admin at %s", adminAddr)
conn, err := grpc.Dial(adminAddr, grpc.WithInsecure())
if err != nil {
return fmt.Errorf("failed to connect to admin server: %w", err)
}
w.conn = conn
w.client = plugin_pb.NewPluginServiceClient(conn)
// Start connection handler in goroutine
w.wg.Add(1)
go w.handleConnection()
return nil
}
// Stop stops the worker and closes all connections
func (w *Worker) Stop() error {
glog.Infof("vacuum worker: stopping (id=%s)", w.id)
// Cancel context to signal all goroutines
if w.cancel != nil {
w.cancel()
}
// Wait for goroutines with timeout
done := make(chan struct{})
go func() {
w.wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(10 * time.Second):
glog.Warningf("vacuum worker: graceful shutdown timeout")
}
// Close gRPC connection
if w.conn != nil {
if err := w.conn.Close(); err != nil {
glog.Errorf("vacuum worker: error closing gRPC connection: %v", err)
}
}
glog.Infof("vacuum worker: stopped")
return nil
}
// handleConnection handles the bidirectional gRPC connection with the admin server
func (w *Worker) handleConnection() {
defer w.wg.Done()
glog.Infof("vacuum worker: establishing bidirectional stream")
// Create bidirectional stream
stream, err := w.client.Connect(w.ctx)
if err != nil {
glog.Errorf("vacuum worker: failed to create stream: %v", err)
return
}
// Send registration message
if err := w.sendRegistration(stream); err != nil {
glog.Errorf("vacuum worker: failed to send registration: %v", err)
return
}
// Start heartbeat goroutine
w.wg.Add(1)
go w.sendHeartbeats(stream)
// Start job executor goroutine
w.wg.Add(1)
go w.executeJobs(stream)
// Listen for messages from admin
w.listenForMessages(stream)
glog.Infof("vacuum worker: connection closed")
}
// sendRegistration sends the initial registration message
func (w *Worker) sendRegistration(stream plugin_pb.PluginService_ConnectClient) error {
capabilities := []*plugin_pb.JobTypeCapability{
{
JobType: "vacuum",
CanDetect: true,
CanExecute: true,
Version: "v1",
},
}
register := &plugin_pb.PluginRegister{
PluginId: w.id,
Name: w.name,
Version: w.version,
ProtocolVersion: "v1",
Capabilities: capabilities,
}
msg := &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Register{
Register: register,
},
}
return stream.Send(msg)
}
// sendHeartbeats sends periodic heartbeat messages
func (w *Worker) sendHeartbeats(stream plugin_pb.PluginService_ConnectClient) {
defer w.wg.Done()
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-ticker.C:
w.jobsMu.RLock()
pendingJobs := int32(len(w.runningJobs))
w.jobsMu.RUnlock()
heartbeat := &plugin_pb.PluginHeartbeat{
PluginId: w.id,
Timestamp: timestamppb.Now(),
UptimeSeconds: int64(time.Since(time.Now()).Seconds()),
PendingJobs: pendingJobs,
CpuUsagePercent: 0, // TODO: Get actual CPU usage
MemoryUsageMb: 0, // TODO: Get actual memory usage
}
msg := &plugin_pb.PluginMessage{
Content: &plugin_pb.PluginMessage_Heartbeat{
Heartbeat: heartbeat,
},
}
if err := stream.Send(msg); err != nil {
glog.Errorf("vacuum worker: failed to send heartbeat: %v", err)
return
}
}
}
}
// executeJobs periodically detects and executes jobs
func (w *Worker) executeJobs(stream plugin_pb.PluginService_ConnectClient) {
defer w.wg.Done()
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-ticker.C:
// TODO: Implement job detection and execution
// Query admin for jobs or use detector to find jobs
}
}
}
// listenForMessages listens for messages from the admin server
func (w *Worker) listenForMessages(stream plugin_pb.PluginService_ConnectClient) {
for {
msg, err := stream.Recv()
if err == io.EOF {
glog.Infof("vacuum worker: admin closed connection")
return
}
if err != nil {
glog.Errorf("vacuum worker: failed to receive message: %v", err)
return
}
if msg.Content == nil {
continue
}
switch content := msg.Content.(type) {
case *plugin_pb.AdminMessage_JobRequest:
w.handleJobRequest(content.JobRequest)
case *plugin_pb.AdminMessage_ConfigUpdate:
glog.Infof("vacuum worker: received config update: %s", content.ConfigUpdate.JobType)
case *plugin_pb.AdminMessage_AdminCommand:
w.handleAdminCommand(content.AdminCommand)
}
}
}
// handleJobRequest processes a job request from the admin
func (w *Worker) handleJobRequest(jobReq *plugin_pb.JobRequest) {
glog.Infof("vacuum worker: received job request (id=%s, type=%s)", jobReq.JobId, jobReq.JobType)
// Create job context
jobCtx, cancel := context.WithCancel(w.ctx)
w.jobsMu.Lock()
w.runningJobs[jobReq.JobId] = cancel
w.jobsMu.Unlock()
// Execute job in goroutine
w.wg.Add(1)
go func() {
defer w.wg.Done()
defer func() {
w.jobsMu.Lock()
delete(w.runningJobs, jobReq.JobId)
w.jobsMu.Unlock()
}()
w.executeJobRequest(jobCtx, jobReq)
}()
}
// executeJobRequest executes a single job request
func (w *Worker) executeJobRequest(ctx context.Context, jobReq *plugin_pb.JobRequest) {
// Build job config from request
config := &plugin_pb.JobTypeConfig{
JobType: jobReq.JobType,
AdminConfig: nil,
WorkerConfig: jobReq.Config,
}
// Create executor
executor := NewExecutor(jobReq.JobId, config)
// Progress channel
progressChan := make(chan *plugin_pb.JobProgress, 10)
// Execute job
go func() {
if err := executor.Execute(ctx, jobReq.Metadata, progressChan); err != nil {
glog.Errorf("vacuum worker: job execution failed (id=%s): %v", jobReq.JobId, err)
}
close(progressChan)
}()
// TODO: Send progress updates back to admin via ExecuteJob RPC
for progress := range progressChan {
_ = progress
glog.Infof("vacuum worker: job %s progress: %d%%", jobReq.JobId, progress.ProgressPercent)
}
}
// handleAdminCommand processes admin commands
func (w *Worker) handleAdminCommand(cmd *plugin_pb.AdminCommand) {
glog.Infof("vacuum worker: received admin command: %v", cmd.CommandType)
switch cmd.CommandType {
case plugin_pb.AdminCommand_RELOAD_CONFIG:
glog.Infof("vacuum worker: reloading configuration")
case plugin_pb.AdminCommand_ENABLE_JOB_TYPE:
glog.Infof("vacuum worker: enabling vacuum job type")
case plugin_pb.AdminCommand_DISABLE_JOB_TYPE:
glog.Infof("vacuum worker: disabling vacuum job type")
case plugin_pb.AdminCommand_SHUTDOWN:
glog.Infof("vacuum worker: received shutdown command")
w.Stop()
}
}
// GetCapabilities returns the worker's capabilities
func (w *Worker) GetCapabilities() []*plugin_pb.JobTypeCapability {
return []*plugin_pb.JobTypeCapability{
{
JobType: "vacuum",
CanDetect: true,
CanExecute: true,
Version: "v1",
},
}
}
// GetConfigurationSchema returns the configuration schema
func (w *Worker) GetConfigurationSchema() *plugin_pb.JobTypeConfigSchema {
return GetConfigurationSchema()
}
// Run is a convenience method that starts the worker and waits for context cancellation
func (w *Worker) Run(ctx context.Context) error {
if err := w.Start(ctx); err != nil {
return err
}
defer w.Stop()
<-ctx.Done()
return nil
}
// StartWorkerServer starts the vacuum worker with the given configuration
func StartWorkerServer(masterAddr string, httpPort int) error {
pluginID := fmt.Sprintf("vacuum_worker_%d", time.Now().Unix())
worker := NewWorker(pluginID, masterAddr, httpPort)
ctx := context.Background()
return worker.Run(ctx)
}
-74
View File
@@ -1,74 +0,0 @@
package app
import (
"fmt"
)
// formatNumber formats a number with commas
func formatNumber(n interface{}) string {
switch v := n.(type) {
case int:
return fmt.Sprintf("%d", v)
case int64:
return fmt.Sprintf("%d", v)
case float64:
return fmt.Sprintf("%.2f", v)
default:
return fmt.Sprintf("%v", v)
}
}
// formatBytes formats bytes as human-readable size
func formatBytes(bytes interface{}) string {
switch v := bytes.(type) {
case int:
return formatBytesValue(int64(v))
case int64:
return formatBytesValue(v)
case float64:
return formatBytesValue(int64(v))
default:
return fmt.Sprintf("%v", v)
}
}
func formatBytesValue(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGTPE"[exp])
}
// calculatePercent calculates percentage
func calculatePercent(current, total interface{}) float64 {
var c, t float64
switch v := current.(type) {
case int:
c = float64(v)
case int64:
c = float64(v)
case float64:
c = v
}
switch v := total.(type) {
case int:
t = float64(v)
case int64:
t = float64(v)
case float64:
t = v
}
if t == 0 {
return 0
}
return (c / t) * 100
}
-102
View File
@@ -1,102 +0,0 @@
package app
import (
"fmt"
)
templ PluginConfigPage(data map[string]interface{}) {
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2"><i class="fas fa-cog me-2"></i>{ fmt.Sprintf("%v", data["job_type"]) } Config</h1>
<a href="/plugins" class="btn btn-sm btn-secondary">Back</a>
</div>
<ul class="nav nav-tabs mb-4" role="tablist">
<li class="nav-item"><button class="nav-link active" id="config-tab" data-bs-toggle="tab" data-bs-target="#config" type="button">Configuration</button></li>
<li class="nav-item"><button class="nav-link" id="detection-tab" data-bs-toggle="tab" data-bs-target="#detection" type="button">Detection History</button></li>
<li class="nav-item"><button class="nav-link" id="execution-tab" data-bs-toggle="tab" data-bs-target="#execution" type="button">Execution History</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" id="config" role="tabpanel">
<div class="card shadow">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Configuration</h6>
</div>
<div class="card-body">
<div class="mb-3">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="enabled" checked?={ data["enabled"].(bool) }>
<label class="form-check-label" for="enabled">Enabled</label>
</div>
</div>
<div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>Configuration UI coming soon</div>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
<div class="tab-pane fade" id="detection" role="tabpanel">
<div class="card shadow">
<div class="card-header py-3">
<div class="d-flex justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Detection History</h6>
<button type="button" class="btn btn-sm btn-primary">Run Detection</button>
</div>
</div>
<div class="card-body">
if len(data["detection_history"].([]map[string]interface{})) == 0 {
<div class="alert alert-info">No detection history</div>
} else {
<table class="table table-sm">
<thead><tr><th>Timestamp</th><th>Duration</th><th>Jobs Found</th><th>Status</th></tr></thead>
<tbody>
for _, rec := range data["detection_history"].([]map[string]interface{}) {
<tr>
<td>{ fmt.Sprintf("%v", rec["timestamp"]) }</td>
<td>{ fmt.Sprintf("%vms", rec["duration_ms"]) }</td>
<td>{ fmt.Sprintf("%v", rec["jobs_detected"]) }</td>
<td><span class="badge bg-success">{ fmt.Sprintf("%v", rec["status"]) }</span></td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
</div>
<div class="tab-pane fade" id="execution" role="tabpanel">
<div class="card shadow">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Execution History</h6>
</div>
<div class="card-body">
if len(data["execution_history"].([]map[string]interface{})) == 0 {
<div class="alert alert-info">No execution history</div>
} else {
<table class="table table-sm">
<thead><tr><th>Job ID</th><th>Started</th><th>Duration</th><th>Items</th><th>Status</th></tr></thead>
<tbody>
for _, rec := range data["execution_history"].([]map[string]interface{}) {
<tr>
<td><code>{ fmt.Sprintf("%v", rec["job_id"]) }</code></td>
<td>{ fmt.Sprintf("%v", rec["started_at"]) }</td>
<td>{ fmt.Sprintf("%vms", rec["duration_ms"]) }</td>
<td>{ fmt.Sprintf("%v", rec["items_processed"]) }</td>
<td>
if rec["success"].(bool) {
<span class="badge bg-success">Success</span>
} else {
<span class="badge bg-danger">Failed</span>
}
</td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
</div>
</div>
}
-236
View File
@@ -1,236 +0,0 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.977
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import (
"fmt"
)
func PluginConfigPage(data map[string]interface{}) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom\"><h1 class=\"h2\"><i class=\"fas fa-cog me-2\"></i>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["job_type"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 9, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, " Config</h1><a href=\"/plugins\" class=\"btn btn-sm btn-secondary\">Back</a></div><ul class=\"nav nav-tabs mb-4\" role=\"tablist\"><li class=\"nav-item\"><button class=\"nav-link active\" id=\"config-tab\" data-bs-toggle=\"tab\" data-bs-target=\"#config\" type=\"button\">Configuration</button></li><li class=\"nav-item\"><button class=\"nav-link\" id=\"detection-tab\" data-bs-toggle=\"tab\" data-bs-target=\"#detection\" type=\"button\">Detection History</button></li><li class=\"nav-item\"><button class=\"nav-link\" id=\"execution-tab\" data-bs-toggle=\"tab\" data-bs-target=\"#execution\" type=\"button\">Execution History</button></li></ul><div class=\"tab-content\"><div class=\"tab-pane fade show active\" id=\"config\" role=\"tabpanel\"><div class=\"card shadow\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\">Configuration</h6></div><div class=\"card-body\"><div class=\"mb-3\"><div class=\"form-check form-switch\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enabled\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data["enabled"].(bool) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, " checked")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "> <label class=\"form-check-label\" for=\"enabled\">Enabled</label></div></div><div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i>Configuration UI coming soon</div><button type=\"button\" class=\"btn btn-primary\">Save</button></div></div></div><div class=\"tab-pane fade\" id=\"detection\" role=\"tabpanel\"><div class=\"card shadow\"><div class=\"card-header py-3\"><div class=\"d-flex justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\">Detection History</h6><button type=\"button\" class=\"btn btn-sm btn-primary\">Run Detection</button></div></div><div class=\"card-body\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(data["detection_history"].([]map[string]interface{})) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "<div class=\"alert alert-info\">No detection history</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<table class=\"table table-sm\"><thead><tr><th>Timestamp</th><th>Duration</th><th>Jobs Found</th><th>Status</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, rec := range data["detection_history"].([]map[string]interface{}) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<tr><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", rec["timestamp"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 55, Col: 51}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%vms", rec["duration_ms"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 56, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", rec["jobs_detected"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 57, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</td><td><span class=\"badge bg-success\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", rec["status"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 58, Col: 79}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</span></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</tbody></table>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</div></div></div><div class=\"tab-pane fade\" id=\"execution\" role=\"tabpanel\"><div class=\"card shadow\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\">Execution History</h6></div><div class=\"card-body\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(data["execution_history"].([]map[string]interface{})) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "<div class=\"alert alert-info\">No execution history</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "<table class=\"table table-sm\"><thead><tr><th>Job ID</th><th>Started</th><th>Duration</th><th>Items</th><th>Status</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, rec := range data["execution_history"].([]map[string]interface{}) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<tr><td><code>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", rec["job_id"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 82, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</code></td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", rec["started_at"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 83, Col: 52}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%vms", rec["duration_ms"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 84, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", rec["items_processed"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_config.templ`, Line: 85, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if rec["success"].(bool) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "<span class=\"badge bg-success\">Success</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "<span class=\"badge bg-danger\">Failed</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</tbody></table>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "</div></div></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
var _ = templruntime.GeneratedTemplate
-60
View File
@@ -1,60 +0,0 @@
package app
import (
"fmt"
)
templ PluginJobsPage(data map[string]interface{}) {
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2"><i class="fas fa-list me-2"></i>{ fmt.Sprintf("%v", data["job_type"]) } Jobs</h1>
<div>
<a href="/plugins" class="btn btn-sm btn-secondary me-2">Back</a>
<button type="button" class="btn btn-sm btn-primary" onclick="location.reload();">Refresh</button>
</div>
</div>
<div class="row mb-4">
<div class="col-lg-3"><div class="card"><div class="card-body"><div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div><div class="h5 mb-0">{ fmt.Sprintf("%v", data["pending_count"]) }</div></div></div></div>
<div class="col-lg-3"><div class="card"><div class="card-body"><div class="text-xs font-weight-bold text-info text-uppercase mb-1">Running</div><div class="h5 mb-0">{ fmt.Sprintf("%v", data["running_count"]) }</div></div></div></div>
<div class="col-lg-3"><div class="card"><div class="card-body"><div class="text-xs font-weight-bold text-success text-uppercase mb-1">Completed</div><div class="h5 mb-0">{ fmt.Sprintf("%v", data["completed_count"]) }</div></div></div></div>
<div class="col-lg-3"><div class="card"><div class="card-body"><div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Failed</div><div class="h5 mb-0">{ fmt.Sprintf("%v", data["failed_count"]) }</div></div></div></div>
</div>
<div class="card shadow">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Job List</h6>
</div>
<div class="card-body">
if len(data["jobs"].([]map[string]interface{})) == 0 {
<div class="alert alert-info">No jobs found</div>
} else {
<table class="table table-sm table-hover">
<thead><tr><th>Job ID</th><th>Description</th><th>State</th><th>Progress</th><th>Created</th></tr></thead>
<tbody>
for _, job := range data["jobs"].([]map[string]interface{}) {
<tr>
<td><code>{ fmt.Sprintf("%v", job["id"]) }</code></td>
<td>{ fmt.Sprintf("%v", job["description"]) }</td>
<td><span class={ "badge", jobStateClass(fmt.Sprintf("%v", job["state"])) }>{ fmt.Sprintf("%v", job["state"]) }</span></td>
<td>
<div class="progress" style="height: 20px;">
<div class="progress-bar" style={ "width: " + fmt.Sprintf("%v%%", job["progress"]) }></div>
</div>
</td>
<td><small>{ fmt.Sprintf("%v", job["created_at"]) }</small></td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
}
func jobStateClass(s string) string {
if s == "pending" { return "bg-warning" }
if s == "running" { return "bg-info" }
if s == "completed" { return "bg-success" }
if s == "failed" { return "bg-danger" }
return "bg-secondary"
}
-237
View File
@@ -1,237 +0,0 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.977
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import (
"fmt"
)
func PluginJobsPage(data map[string]interface{}) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom\"><h1 class=\"h2\"><i class=\"fas fa-list me-2\"></i>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["job_type"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 9, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, " Jobs</h1><div><a href=\"/plugins\" class=\"btn btn-sm btn-secondary me-2\">Back</a> <button type=\"button\" class=\"btn btn-sm btn-primary\" onclick=\"location.reload();\">Refresh</button></div></div><div class=\"row mb-4\"><div class=\"col-lg-3\"><div class=\"card\"><div class=\"card-body\"><div class=\"text-xs font-weight-bold text-warning text-uppercase mb-1\">Pending</div><div class=\"h5 mb-0\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["pending_count"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 17, Col: 212}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "</div></div></div></div><div class=\"col-lg-3\"><div class=\"card\"><div class=\"card-body\"><div class=\"text-xs font-weight-bold text-info text-uppercase mb-1\">Running</div><div class=\"h5 mb-0\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["running_count"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 18, Col: 209}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div></div></div><div class=\"col-lg-3\"><div class=\"card\"><div class=\"card-body\"><div class=\"text-xs font-weight-bold text-success text-uppercase mb-1\">Completed</div><div class=\"h5 mb-0\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["completed_count"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 19, Col: 216}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div></div></div></div><div class=\"col-lg-3\"><div class=\"card\"><div class=\"card-body\"><div class=\"text-xs font-weight-bold text-danger text-uppercase mb-1\">Failed</div><div class=\"h5 mb-0\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["failed_count"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 20, Col: 209}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</div></div></div></div></div><div class=\"card shadow\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\">Job List</h6></div><div class=\"card-body\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(data["jobs"].([]map[string]interface{})) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div class=\"alert alert-info\">No jobs found</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<table class=\"table table-sm table-hover\"><thead><tr><th>Job ID</th><th>Description</th><th>State</th><th>Progress</th><th>Created</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, job := range data["jobs"].([]map[string]interface{}) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<tr><td><code>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", job["id"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 36, Col: 48}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</code></td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", job["description"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 37, Col: 51}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 = []any{"badge", jobStateClass(fmt.Sprintf("%v", job["state"]))}
templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var9...)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "<span class=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var9).String())
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", job["state"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 38, Col: 117}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</span></td><td><div class=\"progress\" style=\"height: 20px;\"><div class=\"progress-bar\" style=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues("width: " + fmt.Sprintf("%v%%", job["progress"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 41, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "\"></div></div></td><td><small>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", job["created_at"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugin_jobs.templ`, Line: 44, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</small></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</tbody></table>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
func jobStateClass(s string) string {
if s == "pending" {
return "bg-warning"
}
if s == "running" {
return "bg-info"
}
if s == "completed" {
return "bg-success"
}
if s == "failed" {
return "bg-danger"
}
return "bg-secondary"
}
var _ = templruntime.GeneratedTemplate
-118
View File
@@ -1,118 +0,0 @@
package app
import (
"fmt"
)
templ PluginsPage(data map[string]interface{}) {
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2"><i class="fas fa-puzzle-piece me-2"></i>Plugin System</h1>
<button type="button" class="btn btn-sm btn-primary" onclick="location.reload();"><i class="fas fa-sync me-1"></i>Refresh</button>
</div>
<div class="row mb-4">
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-primary shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Connected Plugins</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">{ fmt.Sprintf("%v", data["total_plugins"]) }</div>
</div>
<div class="col-auto"><i class="fas fa-plug fa-2x text-gray-300"></i></div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-success shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-success text-uppercase mb-1">Total Jobs</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">{ fmt.Sprintf("%v", data["total_jobs"]) }</div>
</div>
<div class="col-auto"><i class="fas fa-tasks fa-2x text-gray-300"></i></div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-info shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-info text-uppercase mb-1">Job Types</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">{ fmt.Sprintf("%v", len(data["job_types"].([]string))) }</div>
</div>
<div class="col-auto"><i class="fas fa-cubes fa-2x text-gray-300"></i></div>
</div>
</div>
</div>
</div>
</div>
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-plug me-2"></i>Connected Plugins</h6>
</div>
<div class="card-body">
if len(data["plugins"].([]map[string]interface{})) == 0 {
<div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>No plugins connected</div>
} else {
<table class="table table-hover table-sm">
<thead><tr><th>Name</th><th>Version</th><th>State</th><th>Health</th><th>Jobs</th></tr></thead>
<tbody>
for _, p := range data["plugins"].([]map[string]interface{}) {
<tr>
<td>{ fmt.Sprintf("%v", p["name"]) }</td>
<td>{ fmt.Sprintf("%v", p["version"]) }</td>
<td><span class={ "badge", stateClass(fmt.Sprintf("%v", p["state"])) }>{ fmt.Sprintf("%v", p["state"]) }</span></td>
<td>
if p["healthy"].(bool) {
<span class="badge bg-success">Healthy</span>
} else {
<span class="badge bg-danger">Unhealthy</span>
}
</td>
<td>Running: { fmt.Sprintf("%v", p["running_jobs"]) }</td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-cubes me-2"></i>Job Types</h6>
</div>
<div class="card-body">
if len(data["job_types"].([]string)) == 0 {
<div class="alert alert-info">No job types available</div>
} else {
<div class="row">
for _, jt := range data["job_types"].([]string) {
<div class="col-lg-4 mb-3">
<div class="card">
<div class="card-body">
<h5 class="card-title">{ jt }</h5>
<a href={ templ.SafeURL("/plugins/config/" + jt) } class="btn btn-sm btn-primary">Config</a>
<a href={ templ.SafeURL("/plugins/jobs/" + jt) } class="btn btn-sm btn-info">Jobs</a>
</div>
</div>
</div>
}
</div>
}
</div>
</div>
}
func stateClass(s string) string {
if s == "healthy" { return "bg-success" }
if s == "connected" { return "bg-info" }
if s == "unhealthy" { return "bg-warning" }
return "bg-danger"
}
-274
View File
@@ -1,274 +0,0 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.977
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import (
"fmt"
)
func PluginsPage(data map[string]interface{}) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom\"><h1 class=\"h2\"><i class=\"fas fa-puzzle-piece me-2\"></i>Plugin System</h1><button type=\"button\" class=\"btn btn-sm btn-primary\" onclick=\"location.reload();\"><i class=\"fas fa-sync me-1\"></i>Refresh</button></div><div class=\"row mb-4\"><div class=\"col-xl-3 col-md-6 mb-4\"><div class=\"card border-left-primary shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-primary text-uppercase mb-1\">Connected Plugins</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["total_plugins"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 20, Col: 101}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "</div></div><div class=\"col-auto\"><i class=\"fas fa-plug fa-2x text-gray-300\"></i></div></div></div></div></div><div class=\"col-xl-3 col-md-6 mb-4\"><div class=\"card border-left-success shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-success text-uppercase mb-1\">Total Jobs</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", data["total_jobs"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 33, Col: 98}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "</div></div><div class=\"col-auto\"><i class=\"fas fa-tasks fa-2x text-gray-300\"></i></div></div></div></div></div><div class=\"col-xl-3 col-md-6 mb-4\"><div class=\"card border-left-info shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-info text-uppercase mb-1\">Job Types</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", len(data["job_types"].([]string))))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 46, Col: 113}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div></div><div class=\"col-auto\"><i class=\"fas fa-cubes fa-2x text-gray-300\"></i></div></div></div></div></div></div><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-plug me-2\"></i>Connected Plugins</h6></div><div class=\"card-body\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(data["plugins"].([]map[string]interface{})) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "<div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i>No plugins connected</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<table class=\"table table-hover table-sm\"><thead><tr><th>Name</th><th>Version</th><th>State</th><th>Health</th><th>Jobs</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, p := range data["plugins"].([]map[string]interface{}) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<tr><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", p["name"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 68, Col: 42}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", p["version"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 69, Col: 45}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 = []any{"badge", stateClass(fmt.Sprintf("%v", p["state"]))}
templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var7...)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "<span class=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var7).String())
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", p["state"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 70, Col: 110}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</span></td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if p["healthy"].(bool) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<span class=\"badge bg-success\">Healthy</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "<span class=\"badge bg-danger\">Unhealthy</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</td><td>Running: ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%v", p["running_jobs"]))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 78, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</tbody></table>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</div></div><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-cubes me-2\"></i>Job Types</h6></div><div class=\"card-body\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(data["job_types"].([]string)) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<div class=\"alert alert-info\">No job types available</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "<div class=\"row\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, jt := range data["job_types"].([]string) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "<div class=\"col-lg-4 mb-3\"><div class=\"card\"><div class=\"card-body\"><h5 class=\"card-title\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(jt)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 100, Col: 36}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</h5><a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 templ.SafeURL
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL("/plugins/config/" + jt))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 101, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "\" class=\"btn btn-sm btn-primary\">Config</a> <a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 templ.SafeURL
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL("/plugins/jobs/" + jt))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/plugins.templ`, Line: 102, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\" class=\"btn btn-sm btn-info\">Jobs</a></div></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
func stateClass(s string) string {
if s == "healthy" {
return "bg-success"
}
if s == "connected" {
return "bg-info"
}
if s == "unhealthy" {
return "bg-warning"
}
return "bg-danger"
}
var _ = templruntime.GeneratedTemplate
+2 -2
View File
@@ -126,7 +126,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
<code class="text-muted">{sa.AccessKeyId}</code>
</td>
<td>
if sa.Status == dash.StatusActive {
if sa.Status == "Active" {
<span class="badge bg-success">Active</span>
} else {
<span class="badge bg-secondary">Inactive</span>
@@ -141,7 +141,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
</button>
<button type="button" class="btn btn-outline-primary"
data-action="toggle-sa-status" data-sa-id={ sa.ID } data-current-status={ sa.Status }>
if sa.Status == dash.StatusActive {
if sa.Status == "Active" {
<i class="fas fa-pause"></i>
} else {
<i class="fas fa-play"></i>
@@ -121,7 +121,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if sa.Status == dash.StatusActive {
if sa.Status == "Active" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<span class=\"badge bg-success\">Active</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
@@ -188,7 +188,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if sa.Status == dash.StatusActive {
if sa.Status == "Active" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<i class=\"fas fa-pause\"></i>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
@@ -0,0 +1,232 @@
package app
import (
"testing"
)
// Test structs that mirror the actual configuration structure
type TestBaseConfigForTemplate struct {
Enabled bool `json:"enabled"`
ScanIntervalSeconds int `json:"scan_interval_seconds"`
MaxConcurrent int `json:"max_concurrent"`
}
type TestTaskConfigForTemplate struct {
TestBaseConfigForTemplate
TaskSpecificField float64 `json:"task_specific_field"`
AnotherSpecificField string `json:"another_specific_field"`
}
func TestGetTaskFieldValue_EmbeddedStructFields(t *testing.T) {
config := &TestTaskConfigForTemplate{
TestBaseConfigForTemplate: TestBaseConfigForTemplate{
Enabled: true,
ScanIntervalSeconds: 2400,
MaxConcurrent: 5,
},
TaskSpecificField: 0.18,
AnotherSpecificField: "test_value",
}
// Test embedded struct fields
tests := []struct {
fieldName string
expectedValue interface{}
description string
}{
{"enabled", true, "BaseConfig boolean field"},
{"scan_interval_seconds", 2400, "BaseConfig integer field"},
{"max_concurrent", 5, "BaseConfig integer field"},
{"task_specific_field", 0.18, "Task-specific float field"},
{"another_specific_field", "test_value", "Task-specific string field"},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
result := getTaskFieldValue(config, test.fieldName)
if result != test.expectedValue {
t.Errorf("Field %s: expected %v (%T), got %v (%T)",
test.fieldName, test.expectedValue, test.expectedValue, result, result)
}
})
}
}
func TestGetTaskFieldValue_NonExistentField(t *testing.T) {
config := &TestTaskConfigForTemplate{
TestBaseConfigForTemplate: TestBaseConfigForTemplate{
Enabled: true,
ScanIntervalSeconds: 1800,
MaxConcurrent: 3,
},
}
result := getTaskFieldValue(config, "non_existent_field")
if result != nil {
t.Errorf("Expected nil for non-existent field, got %v", result)
}
}
func TestGetTaskFieldValue_NilConfig(t *testing.T) {
var config *TestTaskConfigForTemplate = nil
result := getTaskFieldValue(config, "enabled")
if result != nil {
t.Errorf("Expected nil for nil config, got %v", result)
}
}
func TestGetTaskFieldValue_EmptyStruct(t *testing.T) {
config := &TestTaskConfigForTemplate{}
// Test that we can extract zero values
tests := []struct {
fieldName string
expectedValue interface{}
description string
}{
{"enabled", false, "Zero value boolean"},
{"scan_interval_seconds", 0, "Zero value integer"},
{"max_concurrent", 0, "Zero value integer"},
{"task_specific_field", 0.0, "Zero value float"},
{"another_specific_field", "", "Zero value string"},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
result := getTaskFieldValue(config, test.fieldName)
if result != test.expectedValue {
t.Errorf("Field %s: expected %v (%T), got %v (%T)",
test.fieldName, test.expectedValue, test.expectedValue, result, result)
}
})
}
}
func TestGetTaskFieldValue_NonStructConfig(t *testing.T) {
var config interface{} = "not a struct"
result := getTaskFieldValue(config, "enabled")
if result != nil {
t.Errorf("Expected nil for non-struct config, got %v", result)
}
}
func TestGetTaskFieldValue_PointerToStruct(t *testing.T) {
config := &TestTaskConfigForTemplate{
TestBaseConfigForTemplate: TestBaseConfigForTemplate{
Enabled: false,
ScanIntervalSeconds: 900,
MaxConcurrent: 2,
},
TaskSpecificField: 0.35,
}
// Test that pointers are handled correctly
enabledResult := getTaskFieldValue(config, "enabled")
if enabledResult != false {
t.Errorf("Expected false for enabled field, got %v", enabledResult)
}
intervalResult := getTaskFieldValue(config, "scan_interval_seconds")
if intervalResult != 900 {
t.Errorf("Expected 900 for scan_interval_seconds field, got %v", intervalResult)
}
}
func TestGetTaskFieldValue_FieldsWithJSONOmitempty(t *testing.T) {
// Test struct with omitempty tags
type TestConfigWithOmitempty struct {
TestBaseConfigForTemplate
OptionalField string `json:"optional_field,omitempty"`
}
config := &TestConfigWithOmitempty{
TestBaseConfigForTemplate: TestBaseConfigForTemplate{
Enabled: true,
ScanIntervalSeconds: 1200,
MaxConcurrent: 4,
},
OptionalField: "optional_value",
}
// Test that fields with omitempty are still found
result := getTaskFieldValue(config, "optional_field")
if result != "optional_value" {
t.Errorf("Expected 'optional_value' for optional_field, got %v", result)
}
// Test embedded fields still work
enabledResult := getTaskFieldValue(config, "enabled")
if enabledResult != true {
t.Errorf("Expected true for enabled field, got %v", enabledResult)
}
}
func TestGetTaskFieldValue_DeepEmbedding(t *testing.T) {
// Test with multiple levels of embedding
type DeepBaseConfig struct {
DeepField string `json:"deep_field"`
}
type MiddleConfig struct {
DeepBaseConfig
MiddleField int `json:"middle_field"`
}
type TopConfig struct {
MiddleConfig
TopField bool `json:"top_field"`
}
config := &TopConfig{
MiddleConfig: MiddleConfig{
DeepBaseConfig: DeepBaseConfig{
DeepField: "deep_value",
},
MiddleField: 123,
},
TopField: true,
}
// Test that deeply embedded fields are found
deepResult := getTaskFieldValue(config, "deep_field")
if deepResult != "deep_value" {
t.Errorf("Expected 'deep_value' for deep_field, got %v", deepResult)
}
middleResult := getTaskFieldValue(config, "middle_field")
if middleResult != 123 {
t.Errorf("Expected 123 for middle_field, got %v", middleResult)
}
topResult := getTaskFieldValue(config, "top_field")
if topResult != true {
t.Errorf("Expected true for top_field, got %v", topResult)
}
}
// Benchmark to ensure performance is reasonable
func BenchmarkGetTaskFieldValue(b *testing.B) {
config := &TestTaskConfigForTemplate{
TestBaseConfigForTemplate: TestBaseConfigForTemplate{
Enabled: true,
ScanIntervalSeconds: 1800,
MaxConcurrent: 3,
},
TaskSpecificField: 0.25,
AnotherSpecificField: "benchmark_test",
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
// Test both embedded and regular fields
_ = getTaskFieldValue(config, "enabled")
_ = getTaskFieldValue(config, "task_specific_field")
}
}
+68
View File
@@ -0,0 +1,68 @@
package app
import (
"fmt"
"strconv"
)
// getStatusColor returns Bootstrap color class for status
func getStatusColor(status string) string {
switch status {
case "active", "healthy":
return "success"
case "warning":
return "warning"
case "critical", "unreachable":
return "danger"
default:
return "secondary"
}
}
// formatBytes converts bytes to human readable format
func formatBytes(bytes int64) string {
if bytes == 0 {
return "0 B"
}
units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
var i int
value := float64(bytes)
for value >= 1024 && i < len(units)-1 {
value /= 1024
i++
}
if i == 0 {
return fmt.Sprintf("%.0f %s", value, units[i])
}
return fmt.Sprintf("%.1f %s", value, units[i])
}
// formatNumber formats large numbers with commas
func formatNumber(num int64) string {
if num == 0 {
return "0"
}
str := strconv.FormatInt(num, 10)
result := ""
for i, char := range str {
if i > 0 && (len(str)-i)%3 == 0 {
result += ","
}
result += string(char)
}
return result
}
// calculatePercent calculates percentage for progress bars
func calculatePercent(current, max int) int {
if max == 0 {
return 0
}
return (current * 100) / max
}
+2 -20
View File
@@ -332,27 +332,9 @@ templ Layout(c *gin.Context, content templ.Component) {
</li>
</ul>
</div>
<!-- PLUGIN SECTION -->
<div class="sidebar-menu-group">
<h6 class="sidebar-heading px-3 mt-4 mb-1 text-muted">
<span>PLUGINS</span>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
if currentPath == "/plugins" {
<a class="nav-link active" href="/plugins">
<i class="fas fa-puzzle-piece me-2"></i>Plugins
</a>
} else {
<a class="nav-link" href="/plugins">
<i class="fas fa-puzzle-piece me-2"></i>Plugins
</a>
}
</li>
</ul>
</div>
</div>
<!-- Main content -->
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="pt-3">
@content
+17 -32
View File
@@ -487,22 +487,7 @@ func Layout(c *gin.Context, content templ.Component) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "</li></ul></div><!-- PLUGIN SECTION --><div class=\"sidebar-menu-group\"><h6 class=\"sidebar-heading px-3 mt-4 mb-1 text-muted\"><span>PLUGINS</span></h6><ul class=\"nav flex-column\"><li class=\"nav-item\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if currentPath == "/plugins" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "<a class=\"nav-link active\" href=\"/plugins\"><i class=\"fas fa-puzzle-piece me-2\"></i>Plugins</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "<a class=\"nav-link\" href=\"/plugins\"><i class=\"fas fa-puzzle-piece me-2\"></i>Plugins</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "</li></ul></div></div><main class=\"col-md-9 ms-sm-auto col-lg-10 px-md-4\"><div class=\"pt-3\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "</li></ul></div></div><!-- Main content --><main class=\"col-md-9 ms-sm-auto col-lg-10 px-md-4\"><div class=\"pt-3\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -510,43 +495,43 @@ func Layout(c *gin.Context, content templ.Component) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</div></main></div></div><!-- Footer --><footer class=\"footer mt-auto py-3 bg-light\"><div class=\"container-fluid text-center\"><small class=\"text-muted\">&copy; ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</div></main></div></div><!-- Footer --><footer class=\"footer mt-auto py-3 bg-light\"><div class=\"container-fluid text-center\"><small class=\"text-muted\">&copy; ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", time.Now().Year()))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 368, Col: 60}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 350, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, " SeaweedFS Admin v")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, " SeaweedFS Admin v")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(version.VERSION_NUMBER)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 368, Col: 102}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 350, Col: 102}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, " ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if !strings.Contains(version.VERSION, "enterprise") {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "<span class=\"mx-2\">•</span> <a href=\"https://seaweedfs.com\" target=\"_blank\" class=\"text-decoration-none\"><i class=\"fas fa-star me-1\"></i>Enterprise Version Available</a>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "<span class=\"mx-2\">•</span> <a href=\"https://seaweedfs.com\" target=\"_blank\" class=\"text-decoration-none\"><i class=\"fas fa-star me-1\"></i>Enterprise Version Available</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "</small></div></footer><!-- Bootstrap JS --><script src=\"/static/js/bootstrap.bundle.min.js\"></script><!-- Modal Alerts JS (replaces native alert/confirm) --><script src=\"/static/js/modal-alerts.js\"></script><!-- Custom JS --><script src=\"/static/js/admin.js\"></script><script src=\"/static/js/iam-utils.js\"></script><script src=\"/static/js/s3tables.js\"></script></body></html>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "</small></div></footer><!-- Bootstrap JS --><script src=\"/static/js/bootstrap.bundle.min.js\"></script><!-- Modal Alerts JS (replaces native alert/confirm) --><script src=\"/static/js/modal-alerts.js\"></script><!-- Custom JS --><script src=\"/static/js/admin.js\"></script><script src=\"/static/js/iam-utils.js\"></script><script src=\"/static/js/s3tables.js\"></script></body></html>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -575,56 +560,56 @@ func LoginForm(c *gin.Context, title string, errorMessage string) templ.Componen
templ_7745c5c3_Var28 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "<!doctype html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "<!doctype html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(title)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 396, Col: 17}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 378, Col: 17}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, " - Login</title><link rel=\"icon\" href=\"/static/favicon.ico\" type=\"image/x-icon\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><link href=\"/static/css/bootstrap.min.css\" rel=\"stylesheet\"><link href=\"/static/css/fontawesome.min.css\" rel=\"stylesheet\"></head><body class=\"bg-light\"><div class=\"container\"><div class=\"row justify-content-center min-vh-100 align-items-center\"><div class=\"col-md-6 col-lg-4\"><div class=\"card shadow\"><div class=\"card-body p-5\"><div class=\"text-center mb-4\"><i class=\"fas fa-server fa-3x text-primary mb-3\"></i><h4 class=\"card-title\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, " - Login</title><link rel=\"icon\" href=\"/static/favicon.ico\" type=\"image/x-icon\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><link href=\"/static/css/bootstrap.min.css\" rel=\"stylesheet\"><link href=\"/static/css/fontawesome.min.css\" rel=\"stylesheet\"></head><body class=\"bg-light\"><div class=\"container\"><div class=\"row justify-content-center min-vh-100 align-items-center\"><div class=\"col-md-6 col-lg-4\"><div class=\"card shadow\"><div class=\"card-body p-5\"><div class=\"text-center mb-4\"><i class=\"fas fa-server fa-3x text-primary mb-3\"></i><h4 class=\"card-title\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(title)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 410, Col: 57}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 392, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "</h4><p class=\"text-muted\">Please sign in to continue</p></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "</h4><p class=\"text-muted\">Please sign in to continue</p></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if errorMessage != "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "<div class=\"alert alert-danger\" role=\"alert\"><i class=\"fas fa-exclamation-triangle me-2\"></i> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "<div class=\"alert alert-danger\" role=\"alert\"><i class=\"fas fa-exclamation-triangle me-2\"></i> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(errorMessage)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 417, Col: 45}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 399, Col: 45}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "</div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "<form method=\"POST\" action=\"/login\"><div class=\"mb-3\"><label for=\"username\" class=\"form-label\">Username</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-user\"></i></span> <input type=\"text\" class=\"form-control\" id=\"username\" name=\"username\" required></div></div><div class=\"mb-4\"><label for=\"password\" class=\"form-label\">Password</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-lock\"></i></span> <input type=\"password\" class=\"form-control\" id=\"password\" name=\"password\" required></div></div><button type=\"submit\" class=\"btn btn-primary w-100\"><i class=\"fas fa-sign-in-alt me-2\"></i>Sign In</button></form></div></div></div></div></div><script src=\"/static/js/bootstrap.bundle.min.js\"></script></body></html>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "<form method=\"POST\" action=\"/login\"><div class=\"mb-3\"><label for=\"username\" class=\"form-label\">Username</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-user\"></i></span> <input type=\"text\" class=\"form-control\" id=\"username\" name=\"username\" required></div></div><div class=\"mb-4\"><label for=\"password\" class=\"form-label\">Password</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-lock\"></i></span> <input type=\"password\" class=\"form-control\" id=\"password\" name=\"password\" required></div></div><button type=\"submit\" class=\"btn btn-primary w-100\"><i class=\"fas fa-sign-in-alt me-2\"></i>Sign In</button></form></div></div></div></div></div><script src=\"/static/js/bootstrap.bundle.min.js\"></script></body></html>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -251,132 +251,6 @@ func TestPolicyEnforcement(t *testing.T) {
}
}
// TestSessionPolicyBoundary verifies that inline session policies restrict permissions.
func TestSessionPolicyBoundary(t *testing.T) {
iamManager := setupIntegratedIAMSystem(t)
ctx := context.Background()
stsService := iamManager.GetSTSService()
require.NotNil(t, stsService)
sessionPolicy := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::test-bucket/allowed/*"]}]}`
sessionId, err := sts.GenerateSessionId()
require.NoError(t, err)
expiresAt := time.Now().Add(time.Hour)
principal := "arn:aws:sts::000000000000:assumed-role/S3ReadOnlyRole/policy-session"
claims := sts.NewSTSSessionClaims(sessionId, stsService.Config.Issuer, expiresAt).
WithSessionName("policy-session").
WithRoleInfo("arn:aws:iam::role/S3ReadOnlyRole", principal, principal).
WithSessionPolicy(sessionPolicy)
sessionToken, err := stsService.GetTokenGenerator().GenerateJWTWithClaims(claims)
require.NoError(t, err)
allowed, err := iamManager.IsActionAllowed(ctx, &ActionRequest{
Principal: principal,
Action: "s3:GetObject",
Resource: "arn:aws:s3:::test-bucket/allowed/file.txt",
SessionToken: sessionToken,
})
require.NoError(t, err)
assert.True(t, allowed, "Session policy should allow GetObject within allowed prefix")
allowed, err = iamManager.IsActionAllowed(ctx, &ActionRequest{
Principal: principal,
Action: "s3:GetObject",
Resource: "arn:aws:s3:::test-bucket/other/file.txt",
SessionToken: sessionToken,
})
require.NoError(t, err)
assert.False(t, allowed, "Session policy should deny GetObject outside allowed prefix")
allowed, err = iamManager.IsActionAllowed(ctx, &ActionRequest{
Principal: principal,
Action: "s3:ListBucket",
Resource: "arn:aws:s3:::test-bucket",
SessionToken: sessionToken,
})
require.NoError(t, err)
assert.False(t, allowed, "Session policy should deny ListBucket when not explicitly allowed")
}
// TestAssumeRoleWithWebIdentitySessionPolicy verifies Policy downscoping is applied to web identity sessions.
func TestAssumeRoleWithWebIdentitySessionPolicy(t *testing.T) {
iamManager := setupIntegratedIAMSystem(t)
ctx := context.Background()
validJWTToken := createTestJWT(t, "https://test-issuer.com", "test-user-123", "test-signing-key")
sessionPolicy := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::test-bucket/allowed/*"]}]}`
assumeRequest := &sts.AssumeRoleWithWebIdentityRequest{
RoleArn: "arn:aws:iam::role/S3ReadOnlyRole",
WebIdentityToken: validJWTToken,
RoleSessionName: "policy-web-identity",
Policy: &sessionPolicy,
}
response, err := iamManager.AssumeRoleWithWebIdentity(ctx, assumeRequest)
require.NoError(t, err)
allowed, err := iamManager.IsActionAllowed(ctx, &ActionRequest{
Principal: response.AssumedRoleUser.Arn,
Action: "s3:GetObject",
Resource: "arn:aws:s3:::test-bucket/allowed/file.txt",
SessionToken: response.Credentials.SessionToken,
})
require.NoError(t, err)
assert.True(t, allowed, "Session policy should allow GetObject within allowed prefix")
allowed, err = iamManager.IsActionAllowed(ctx, &ActionRequest{
Principal: response.AssumedRoleUser.Arn,
Action: "s3:GetObject",
Resource: "arn:aws:s3:::test-bucket/other/file.txt",
SessionToken: response.Credentials.SessionToken,
})
require.NoError(t, err)
assert.False(t, allowed, "Session policy should deny GetObject outside allowed prefix")
}
// TestAssumeRoleWithCredentialsSessionPolicy verifies Policy downscoping is applied to credentials sessions.
func TestAssumeRoleWithCredentialsSessionPolicy(t *testing.T) {
iamManager := setupIntegratedIAMSystem(t)
ctx := context.Background()
sessionPolicy := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["filer:CreateEntry"],"Resource":["arn:aws:filer::path/user-docs/allowed/*"]}]}`
assumeRequest := &sts.AssumeRoleWithCredentialsRequest{
RoleArn: "arn:aws:iam::role/LDAPUserRole",
Username: "testuser",
Password: "testpass",
RoleSessionName: "policy-ldap",
ProviderName: "test-ldap",
Policy: &sessionPolicy,
}
response, err := iamManager.AssumeRoleWithCredentials(ctx, assumeRequest)
require.NoError(t, err)
allowed, err := iamManager.IsActionAllowed(ctx, &ActionRequest{
Principal: response.AssumedRoleUser.Arn,
Action: "filer:CreateEntry",
Resource: "arn:aws:filer::path/user-docs/allowed/file.txt",
SessionToken: response.Credentials.SessionToken,
})
require.NoError(t, err)
assert.True(t, allowed, "Session policy should allow CreateEntry within allowed prefix")
allowed, err = iamManager.IsActionAllowed(ctx, &ActionRequest{
Principal: response.AssumedRoleUser.Arn,
Action: "filer:CreateEntry",
Resource: "arn:aws:filer::path/user-docs/other/file.txt",
SessionToken: response.Credentials.SessionToken,
})
require.NoError(t, err)
assert.False(t, allowed, "Session policy should deny CreateEntry outside allowed prefix")
}
// TestSessionExpiration tests session expiration and cleanup
func TestSessionExpiration(t *testing.T) {
iamManager := setupIntegratedIAMSystem(t)
+50 -131
View File
@@ -7,12 +7,11 @@ import (
"fmt"
"strings"
"github.com/golang-jwt/jwt/v5"
"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"
"github.com/seaweedfs/seaweedfs/weed/iam/utils"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
)
// maxPoliciesForEvaluation defines an upper bound on the number of policies that
@@ -25,7 +24,6 @@ type IAMManager struct {
stsService *sts.STSService
policyEngine *policy.PolicyEngine
roleStore RoleStore
userStore UserStore
filerAddressProvider func() string // Function to get current filer address
initialized bool
}
@@ -51,11 +49,6 @@ type RoleStoreConfig struct {
StoreConfig map[string]interface{} `json:"storeConfig,omitempty"`
}
// UserStore defines the interface for retrieving IAM user policy attachments.
type UserStore interface {
GetUser(ctx context.Context, username string) (*iam_pb.Identity, error)
}
// RoleDefinition defines a role with its trust policy and attached policies
type RoleDefinition struct {
// RoleName is the name of the role
@@ -100,11 +93,6 @@ func NewIAMManager() *IAMManager {
return &IAMManager{}
}
// SetUserStore assigns the user store used to resolve IAM user policy attachments.
func (m *IAMManager) SetUserStore(store UserStore) {
m.userStore = store
}
// Initialize initializes the IAM manager with all components
func (m *IAMManager) Initialize(config *IAMConfig, filerAddressProvider func() string) error {
if config == nil {
@@ -116,7 +104,15 @@ func (m *IAMManager) Initialize(config *IAMConfig, filerAddressProvider func() s
// Initialize STS service
m.stsService = sts.NewSTSService()
if err := m.stsService.Initialize(config.STS); err != nil {
// 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 {
return fmt.Errorf("failed to initialize STS service: %w", err)
}
@@ -323,30 +319,12 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
return false, fmt.Errorf("IAM manager not initialized")
}
// Validate session token if present
// We always try to validate with the internal STS service first if it's a SeaweedFS token.
// This ensures that session policies embedded in the token are correctly extracted and enforced.
var sessionInfo *sts.SessionInfo
if request.SessionToken != "" {
// Parse unverified to check issuer
parsed, _, err := new(jwt.Parser).ParseUnverified(request.SessionToken, jwt.MapClaims{})
isInternal := false
if err == nil {
if claims, ok := parsed.Claims.(jwt.MapClaims); ok {
if issuer, ok := claims["iss"].(string); ok && m.stsService != nil && m.stsService.Config != nil {
if issuer == m.stsService.Config.Issuer {
isInternal = true
}
}
}
}
if isInternal || !isOIDCToken(request.SessionToken) {
var err error
sessionInfo, err = m.stsService.ValidateSessionToken(ctx, request.SessionToken)
if err != nil {
return false, fmt.Errorf("invalid session: %w", err)
}
// Validate session token if present (skip for OIDC tokens which are already validated,
// and skip for empty tokens which represent static access keys)
if request.SessionToken != "" && !isOIDCToken(request.SessionToken) {
_, err := m.stsService.ValidateSessionToken(ctx, request.SessionToken)
if err != nil {
return false, fmt.Errorf("invalid session: %w", err)
}
}
@@ -365,17 +343,7 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
// Add principal to context for policy matching
// The PolicyEngine checks RequestContext["principal"] or RequestContext["aws:PrincipalArn"]
evalCtx.RequestContext["principal"] = request.Principal
evalCtx.RequestContext["aws:PrincipalArn"] = request.Principal // AWS standard key
// Check if this is an admin request - bypass policy evaluation if so
// This mirrors the logic in auth_signature_v4.go but applies it at authorization time
isAdmin := false
if request.RequestContext != nil {
if val, ok := request.RequestContext["is_admin"].(bool); ok && val {
isAdmin = true
}
// Print full request context for debugging
}
evalCtx.RequestContext["aws:PrincipalArn"] = request.Principal
// Parse principal ARN to extract details for context variables (e.g. ${aws:username})
arnInfo := utils.ParsePrincipalARN(request.Principal)
@@ -390,9 +358,6 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
evalCtx.RequestContext["aws:username"] = awsUsername
evalCtx.RequestContext["aws:userid"] = arnInfo.RoleName
} else if userName := utils.ExtractUserNameFromPrincipal(request.Principal); userName != "" {
evalCtx.RequestContext["aws:username"] = userName
evalCtx.RequestContext["aws:userid"] = userName
}
if arnInfo.AccountID != "" {
evalCtx.RequestContext["aws:PrincipalAccount"] = arnInfo.AccountID
@@ -408,83 +373,58 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
}
}
var baseResult *policy.EvaluationResult
var err error
if isAdmin {
// Admin always has base access allowed
baseResult = &policy.EvaluationResult{Effect: policy.EffectAllow}
} else {
// If explicit policy names are provided (e.g. from user identity), evaluate them directly
if len(request.PolicyNames) > 0 {
policies := request.PolicyNames
if len(policies) == 0 {
// Extract role name from principal ARN
roleName := utils.ExtractRoleNameFromPrincipal(request.Principal)
if roleName == "" {
userName := utils.ExtractUserNameFromPrincipal(request.Principal)
if userName == "" {
return false, fmt.Errorf("could not extract role from principal: %s", request.Principal)
}
if m.userStore == nil {
return false, fmt.Errorf("user store unavailable for principal: %s", request.Principal)
}
user, err := m.userStore.GetUser(ctx, userName)
if err != nil || user == nil {
return false, fmt.Errorf("user not found for principal: %s (user=%s)", request.Principal, userName)
}
policies = user.GetPolicyNames()
} else {
// Get role definition
roleDef, err := m.roleStore.GetRole(ctx, m.getFilerAddress(), roleName)
if err != nil {
return false, fmt.Errorf("role not found: %s", roleName)
}
policies = roleDef.AttachedPolicies
}
}
if bucketPolicyName != "" {
// Enforce an upper bound on the number of policies to avoid excessive allocations
if len(policies) >= maxPoliciesForEvaluation {
return false, fmt.Errorf("too many policies for evaluation: %d >= %d", len(policies), maxPoliciesForEvaluation)
}
// Create a new slice to avoid modifying the original and append the bucket policy
// Create a new slice to avoid modifying the request and append the bucket policy
copied := make([]string, len(policies))
copy(copied, policies)
policies = append(copied, bucketPolicyName)
}
baseResult, err = m.policyEngine.Evaluate(ctx, "", evalCtx, policies)
result, err := m.policyEngine.Evaluate(ctx, "", evalCtx, policies)
if err != nil {
return false, fmt.Errorf("policy evaluation failed: %w", err)
}
return result.Effect == policy.EffectAllow, nil
}
// Base policy must allow; if it doesn't, deny immediately (session policy can only further restrict)
if baseResult.Effect != policy.EffectAllow {
return false, nil
// Extract role name from principal ARN
roleName := utils.ExtractRoleNameFromPrincipal(request.Principal)
if roleName == "" {
return false, fmt.Errorf("could not extract role from principal: %s", request.Principal)
}
// If there's a session policy, it must also allow the action
if sessionInfo != nil && sessionInfo.SessionPolicy != "" {
var sessionPolicy policy.PolicyDocument
if err := json.Unmarshal([]byte(sessionInfo.SessionPolicy), &sessionPolicy); err != nil {
return false, fmt.Errorf("invalid session policy JSON: %w", err)
}
if err := policy.ValidatePolicyDocument(&sessionPolicy); err != nil {
return false, fmt.Errorf("invalid session policy document: %w", err)
}
sessionResult, err := m.policyEngine.EvaluatePolicyDocument(ctx, evalCtx, "session-policy", &sessionPolicy, policy.EffectDeny)
if err != nil {
return false, fmt.Errorf("session policy evaluation failed: %w", err)
}
if sessionResult.Effect != policy.EffectAllow {
// Session policy does not allow this action
return false, nil
}
// Get role definition
roleDef, err := m.roleStore.GetRole(ctx, m.getFilerAddress(), roleName)
if err != nil {
return false, fmt.Errorf("role not found: %s", roleName)
}
return true, nil
// Evaluate policies attached to the role
policies := roleDef.AttachedPolicies
if bucketPolicyName != "" {
// Enforce an upper bound on the number of policies to avoid excessive allocations
if len(policies) >= maxPoliciesForEvaluation {
return false, fmt.Errorf("too many policies for evaluation: %d >= %d", len(policies), maxPoliciesForEvaluation)
}
// Create a new slice to avoid modifying the role definition and append the bucket policy
copied := make([]string, len(policies))
copy(copied, policies)
policies = append(copied, bucketPolicyName)
}
result, err := m.policyEngine.Evaluate(ctx, "", evalCtx, policies)
if err != nil {
return false, fmt.Errorf("policy evaluation failed: %w", err)
}
return result.Effect == policy.EffectAllow, nil
}
// ValidateTrustPolicy validates if a principal can assume a role (for testing)
@@ -712,28 +652,7 @@ func isOIDCToken(token string) bool {
}
// JWT tokens typically start with "eyJ" (base64 encoded JSON starting with "{")
if !strings.HasPrefix(token, "eyJ") {
return false
}
parsed, _, err := new(jwt.Parser).ParseUnverified(token, jwt.MapClaims{})
if err != nil {
return false
}
claims, ok := parsed.Claims.(jwt.MapClaims)
if !ok {
return false
}
if typ, ok := claims["typ"].(string); ok && typ == sts.TokenTypeSession {
return false
}
if typ, ok := claims[sts.JWTClaimTokenType].(string); ok && typ == sts.TokenTypeSession {
return false
}
return true
return strings.HasPrefix(token, "eyJ")
}
// TrustPolicyValidator interface implementation
@@ -0,0 +1,108 @@
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")
}
-62
View File
@@ -474,68 +474,6 @@ func (e *PolicyEngine) EvaluateTrustPolicy(ctx context.Context, trustPolicy *Pol
return result, nil
}
// EvaluatePolicyDocument evaluates a single policy document without storing it.
// defaultEffect controls the fallback result when no statements match.
func (e *PolicyEngine) EvaluatePolicyDocument(ctx context.Context, evalCtx *EvaluationContext, policyName string, policyDoc *PolicyDocument, defaultEffect Effect) (*EvaluationResult, error) {
if !e.initialized {
return nil, fmt.Errorf("policy engine not initialized")
}
if evalCtx == nil {
return nil, fmt.Errorf("evaluation context cannot be nil")
}
if policyDoc == nil {
return nil, fmt.Errorf("policy document cannot be nil")
}
if policyName == "" {
policyName = "inline-policy"
}
result := &EvaluationResult{
Effect: defaultEffect,
EvaluationDetails: &EvaluationDetails{
Principal: evalCtx.Principal,
Action: evalCtx.Action,
Resource: evalCtx.Resource,
PoliciesEvaluated: []string{policyName},
},
}
var matchingStatements []StatementMatch
explicitDeny := false
hasAllow := false
for _, statement := range policyDoc.Statement {
if e.statementMatches(&statement, evalCtx) {
match := StatementMatch{
PolicyName: policyName,
StatementSid: statement.Sid,
Effect: Effect(statement.Effect),
Reason: "Action, Resource, and Condition matched",
}
matchingStatements = append(matchingStatements, match)
if statement.Effect == "Deny" {
explicitDeny = true
} else if statement.Effect == "Allow" {
hasAllow = true
}
}
}
result.MatchingStatements = matchingStatements
if explicitDeny {
result.Effect = EffectDeny
} else if hasAllow {
result.Effect = EffectAllow
}
return result, nil
}
// statementMatches checks if a statement matches the evaluation context
func (e *PolicyEngine) statementMatches(statement *Statement, evalCtx *EvaluationContext) bool {
// Check principal match (for trust policies)
-68
View File
@@ -1,68 +0,0 @@
package sts
import (
"encoding/base64"
"encoding/hex"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// TestTemporaryCredentialPrefix verifies that temporary credentials use ASIA prefix
// (not AKIA which is for permanent IAM user credentials)
func TestTemporaryCredentialPrefix(t *testing.T) {
sessionId := "test-session-for-prefix"
expiration := time.Now().Add(time.Hour)
credGen := NewCredentialGenerator()
cred, err := credGen.GenerateTemporaryCredentials(sessionId, expiration)
assert.NoError(t, err)
assert.NotNil(t, cred)
// Verify ASIA prefix for temporary credentials
assert.True(t, strings.HasPrefix(cred.AccessKeyId, "ASIA"),
"Temporary credentials must use ASIA prefix, got: %s", cred.AccessKeyId)
// Verify it's NOT using AKIA (permanent credentials)
assert.False(t, strings.HasPrefix(cred.AccessKeyId, "AKIA"),
"Temporary credentials must NOT use AKIA prefix (that's for permanent IAM keys)")
}
// TestTemporaryCredentialFormat verifies the full format of temporary credentials
func TestTemporaryCredentialFormat(t *testing.T) {
sessionId := "format-test-session"
expiration := time.Now().Add(time.Hour)
credGen := NewCredentialGenerator()
cred, err := credGen.GenerateTemporaryCredentials(sessionId, expiration)
assert.NoError(t, err)
assert.NotNil(t, cred)
// AWS temporary access key format: ASIA + 16 hex characters = 20 chars total
assert.Equal(t, 20, len(cred.AccessKeyId),
"Access key ID should be 20 characters (ASIA + 16 hex chars)")
// Verify it starts with ASIA
assert.True(t, strings.HasPrefix(cred.AccessKeyId, "ASIA"),
"Access key must start with ASIA prefix")
// Verify the rest is hex (after ASIA prefix)
hexPart := cred.AccessKeyId[4:]
assert.Equal(t, 16, len(hexPart), "Hex part should be 16 characters")
_, err = hex.DecodeString(hexPart)
assert.NoError(t, err, "The part after ASIA prefix should be valid hex")
// Verify secret key is not empty and is a valid base64-encoded SHA256 hash
assert.NotEmpty(t, cred.SecretAccessKey)
assert.Equal(t, 44, len(cred.SecretAccessKey),
"SecretAccessKey should be 44 characters for a base64-encoded 32-byte hash")
_, err = base64.StdEncoding.DecodeString(cred.SecretAccessKey)
assert.NoError(t, err, "SecretAccessKey should be a valid base64 string")
// Verify session token is not empty
assert.NotEmpty(t, cred.SessionToken)
}
-9
View File
@@ -31,8 +31,6 @@ type STSSessionClaims struct {
// Authorization data
Policies []string `json:"pol,omitempty"` // policies (abbreviated)
// SessionPolicy contains inline session policy JSON (optional)
SessionPolicy string `json:"spol,omitempty"`
// Identity provider information
IdentityProvider string `json:"idp"` // identity_provider
@@ -90,7 +88,6 @@ func (c *STSSessionClaims) ToSessionInfo() *SessionInfo {
AssumedRoleUser: c.AssumedRole,
Principal: c.Principal,
Policies: c.Policies,
SessionPolicy: c.SessionPolicy,
ExpiresAt: expiresAt,
IdentityProvider: c.IdentityProvider,
ExternalUserId: c.ExternalUserId,
@@ -151,12 +148,6 @@ func (c *STSSessionClaims) WithPolicies(policies []string) *STSSessionClaims {
return c
}
// WithSessionPolicy sets the inline session policy JSON for this session
func (c *STSSessionClaims) WithSessionPolicy(policy string) *STSSessionClaims {
c.SessionPolicy = policy
return c
}
// WithIdentityProvider sets identity provider information
func (c *STSSessionClaims) WithIdentityProvider(providerName, externalUserId, providerIssuer string) *STSSessionClaims {
c.IdentityProvider = providerName
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more