mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12251e7457 | ||
|
|
5016aad2c0 | ||
|
|
36832a89f5 | ||
|
|
af4b772c03 | ||
|
|
5d59db0503 | ||
|
|
e1a09416fc | ||
|
|
737cc0f330 | ||
|
|
ca42c5bbe4 | ||
|
|
d947f19f33 | ||
|
|
8fe0b68b7c | ||
|
|
6c826e710a | ||
|
|
9561d95507 | ||
|
|
5fec310f73 | ||
|
|
ac49cfd59b | ||
|
|
651a72e803 | ||
|
|
d1236ebf4f | ||
|
|
fe7afc9983 | ||
|
|
52f39d6e86 | ||
|
|
416040940b | ||
|
|
e181e2c035 | ||
|
|
e610dad2a1 | ||
|
|
2e423c0f31 | ||
|
|
a315f78b91 | ||
|
|
929c33980f | ||
|
|
559439bb9d | ||
|
|
6c98c9966e | ||
|
|
d44bbbfbfc | ||
|
|
06b4e46f4f | ||
|
|
89ed588b34 | ||
|
|
c9c487282b | ||
|
|
c3bfa48f25 | ||
|
|
b47bcd26c0 | ||
|
|
00f6ac592b | ||
|
|
89833c07d3 | ||
|
|
08889b0f7b | ||
|
|
706ad03d0c | ||
|
|
3475df1203 | ||
|
|
c9871ce290 | ||
|
|
eeef173dd0 | ||
|
|
317ee9d10c | ||
|
|
9c71020915 | ||
|
|
7110d326fa | ||
|
|
06bb1782e4 | ||
|
|
775095c50d | ||
|
|
7a53654b93 | ||
|
|
fbabfbd353 | ||
|
|
605907f522 | ||
|
|
afeb82ab87 | ||
|
|
e31cb80812 | ||
|
|
28c834c76f | ||
|
|
51a209cf60 | ||
|
|
b114b318ae | ||
|
|
9ecd455310 | ||
|
|
ca4c8d977d | ||
|
|
5eead9409a | ||
|
|
a14cbc176b | ||
|
|
f1f720f5da | ||
|
|
d65c568cbb | ||
|
|
fe1d7a404d | ||
|
|
8815844278 | ||
|
|
93247d6de4 | ||
|
|
352ffdffe1 | ||
|
|
29e14f89f1 | ||
|
|
88c2f3c34d | ||
|
|
da2e90aefd | ||
|
|
a0be40e070 | ||
|
|
b94ad82472 | ||
|
|
cd5004cfbd | ||
|
|
5cbcfd311c | ||
|
|
76f361fa77 | ||
|
|
3d39324bc1 | ||
|
|
20f4fd9985 | ||
|
|
0fcd5173be | ||
|
|
749430dceb | ||
|
|
036191c78a | ||
|
|
34b236acfa | ||
|
|
1a7ab2ea82 | ||
|
|
ae93f87a46 | ||
|
|
6e950e0e7e | ||
|
|
ede766645a | ||
|
|
592d6d6021 | ||
|
|
f438cc3544 | ||
|
|
628363c4a6 | ||
|
|
8ae07e2a3f | ||
|
|
c6302fcb54 | ||
|
|
fff243d463 | ||
|
|
cb882ced46 | ||
|
|
c4e1885053 | ||
|
|
0f5e99f423 | ||
|
|
1220468a33 | ||
|
|
be9996962d | ||
|
|
96e5fea08e | ||
|
|
7f67995c24 | ||
|
|
9ae905e456 | ||
|
|
7364f148bd | ||
|
|
05f0f7e1c9 | ||
|
|
45ba71a189 | ||
|
|
c40db5a52d | ||
|
|
141413ad76 | ||
|
|
0a5c22b57e | ||
|
|
e77f8ae204 | ||
|
|
0007245c7f | ||
|
|
49f62df2cf | ||
|
|
06ccd0e9fc | ||
|
|
eaab3ec5d0 | ||
|
|
caaa53aee3 | ||
|
|
e725eb4079 | ||
|
|
08a7502b2c |
No files matched your search
@@ -217,6 +217,106 @@ jobs:
|
||||
print("✓ No blank lines in security+S3 command blocks")
|
||||
PYEOF
|
||||
|
||||
echo ""
|
||||
echo "=== Testing security+S3: -cert.file/-key.file gated on httpsPort (issue #9202) ==="
|
||||
# Regression test: when enableSecurity=true but *.httpsPort is 0 (the default),
|
||||
# the chart must NOT emit -cert.file / -key.file to the S3 frontend. Passing
|
||||
# them promotes weed s3's main -port to HTTPS (see weed/command/s3.go), which
|
||||
# makes the HTTP readinessProbe spam "TLS handshake error ... client sent an
|
||||
# HTTP request to an HTTPS server" into the pod log.
|
||||
#
|
||||
# When *.httpsPort > 0, both -port.https and cert/key args MUST be emitted
|
||||
# together so the opt-in HTTPS listener actually has credentials.
|
||||
python3 - "$CHART_DIR" <<'PYEOF'
|
||||
import subprocess, sys, yaml
|
||||
chart = sys.argv[1]
|
||||
|
||||
def render(values):
|
||||
args = ["helm", "template", "test", chart]
|
||||
for k, v in values.items():
|
||||
args += ["--set", f"{k}={v}"]
|
||||
return subprocess.check_output(args, text=True)
|
||||
|
||||
def script_of(manifest, kind_name):
|
||||
for doc in yaml.safe_load_all(manifest):
|
||||
if not doc or doc.get("kind") not in ("Deployment", "StatefulSet"):
|
||||
continue
|
||||
if doc["metadata"]["name"] != kind_name:
|
||||
continue
|
||||
for c in doc["spec"]["template"]["spec"]["containers"]:
|
||||
cmd = c.get("command", [])
|
||||
if len(cmd) >= 3 and cmd[0] == "/bin/sh" and cmd[1] == "-ec":
|
||||
return cmd[2]
|
||||
raise AssertionError(f"no container script for {kind_name}")
|
||||
|
||||
cases = [
|
||||
# (values, workload-name, httpsPort-set?, arg-prefix)
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"s3.enabled": "true"},
|
||||
"test-seaweedfs-s3", False, ""),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"s3.enabled": "true",
|
||||
"s3.httpsPort": "8443"},
|
||||
"test-seaweedfs-s3", True, ""),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"filer.s3.enabled": "true"},
|
||||
"test-seaweedfs-filer", False, "s3."),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"filer.s3.enabled": "true",
|
||||
"filer.s3.httpsPort": "8444"},
|
||||
"test-seaweedfs-filer", True, "s3."),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"allInOne.enabled": "true",
|
||||
"allInOne.s3.enabled": "true"},
|
||||
"test-seaweedfs-all-in-one", False, "s3."),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"allInOne.enabled": "true",
|
||||
"allInOne.s3.enabled": "true",
|
||||
"allInOne.s3.httpsPort": "8445"},
|
||||
"test-seaweedfs-all-in-one", True, "s3."),
|
||||
]
|
||||
|
||||
failed = False
|
||||
for values, name, https_on, prefix in cases:
|
||||
script = script_of(render(values), name)
|
||||
cert_flag = f"-{prefix}cert.file="
|
||||
key_flag = f"-{prefix}key.file="
|
||||
https_flag = f"-{prefix}port.https="
|
||||
has_cert = cert_flag in script
|
||||
has_key = key_flag in script
|
||||
has_https = https_flag in script
|
||||
label = f"{name} (httpsPort {'set' if https_on else 'unset'})"
|
||||
if https_on:
|
||||
if not (has_cert and has_key and has_https):
|
||||
print(f"FAIL: {label}: expected {cert_flag}, {key_flag}, {https_flag} all present "
|
||||
f"(got cert={has_cert} key={has_key} https={has_https})", file=sys.stderr)
|
||||
failed = True
|
||||
else:
|
||||
print(f"✓ {label}: cert/key/https args emitted together")
|
||||
else:
|
||||
if has_cert or has_key or has_https:
|
||||
print(f"FAIL: {label}: expected none of {cert_flag}/{key_flag}/{https_flag}; "
|
||||
f"main S3 -port would silently become HTTPS and break HTTP probes "
|
||||
f"(got cert={has_cert} key={has_key} https={has_https})", file=sys.stderr)
|
||||
failed = True
|
||||
else:
|
||||
print(f"✓ {label}: no TLS args emitted, main -port stays HTTP")
|
||||
|
||||
# bash -n: pin down that the rendered script parses. Guards against
|
||||
# a future helper change that leaves a dangling `\` with nothing
|
||||
# after it (every current caller already exits cleanly because
|
||||
# bash treats trailing `\<newline><EOF>` as line-continuation to
|
||||
# an empty line — but keep the contract explicit).
|
||||
parse = subprocess.run(["bash", "-n"], input=script, text=True,
|
||||
capture_output=True)
|
||||
if parse.returncode != 0:
|
||||
print(f"FAIL: {label}: bash -n rejected rendered script: {parse.stderr.strip()}",
|
||||
file=sys.stderr)
|
||||
failed = True
|
||||
|
||||
sys.exit(1 if failed else 0)
|
||||
PYEOF
|
||||
|
||||
echo "✅ All template rendering tests passed!"
|
||||
|
||||
- name: Create kind cluster
|
||||
|
||||
@@ -84,7 +84,7 @@ jobs:
|
||||
timeout-minutes: 25
|
||||
strategy:
|
||||
matrix:
|
||||
test-type: ["basic", "advanced", "policy-enforcement", "group"]
|
||||
test-type: ["basic", "advanced", "policy-enforcement", "group", "sts"]
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
@@ -138,6 +138,23 @@ jobs:
|
||||
make clean setup start-services wait-for-services
|
||||
go test -v -timeout 15m -run "TestIAMGroup" ./...
|
||||
;;
|
||||
"sts")
|
||||
echo "Running STS and service account tests..."
|
||||
make clean setup start-services wait-for-services
|
||||
# SigV4-signed STS calls need admin credentials matching test_config.json.
|
||||
# Tests default to "admin"/"admin" when env vars are unset, which don't exist.
|
||||
export STS_TEST_ACCESS_KEY=test-access-key
|
||||
export STS_TEST_SECRET_KEY=test-secret-key
|
||||
# The use_service_account_credentials subtest is excluded because
|
||||
# newly-created service-account access keys are not currently
|
||||
# persisted to the filer after CreateServiceAccount — a
|
||||
# pre-existing sync issue tracked separately from the
|
||||
# GetFederationToken routing fix this PR addresses.
|
||||
go test -v -timeout 15m \
|
||||
-run "TestSTS|TestAssumeRoleWithWebIdentity|TestServiceAccount" \
|
||||
-skip "TestServiceAccountLifecycle/use_service_account_credentials" \
|
||||
./...
|
||||
;;
|
||||
*)
|
||||
echo "Unknown test type: ${{ matrix.test-type }}"
|
||||
exit 1
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
name: "TLS Rotation Integration Tests"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
tls-rotation-tests:
|
||||
name: TLS Rotation Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: ^1.25
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Build weed binary
|
||||
run: |
|
||||
cd weed && go build -o weed .
|
||||
|
||||
- name: Run TLS Rotation Integration Tests
|
||||
working-directory: test/tls_rotation
|
||||
run: |
|
||||
go test -v -count=1 -timeout 5m
|
||||
|
||||
- name: Collect server logs on failure
|
||||
if: failure()
|
||||
run: |
|
||||
echo "Collecting master logs from temp directories..."
|
||||
mkdir -p /tmp/tls-rotation-test-logs
|
||||
find /tmp -maxdepth 1 -type d -name "TestMasterHTTPS*" 2>/dev/null | while read dir; do
|
||||
if [ -d "$dir" ]; then
|
||||
echo "Found test directory: $dir"
|
||||
cp -r "$dir" /tmp/tls-rotation-test-logs/ 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
echo "Collected logs:"
|
||||
find /tmp/tls-rotation-test-logs -type f -name "*.log" 2>/dev/null || echo "No logs found"
|
||||
|
||||
- name: Archive logs
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: tls-rotation-test-logs
|
||||
path: /tmp/tls-rotation-test-logs/
|
||||
retention-days: 14
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,237 @@
|
||||
# Parquet Pushdown Dev Plan
|
||||
|
||||
Companion to [PARQUET_PUSHDOWN_DESIGN.md](./PARQUET_PUSHDOWN_DESIGN.md). The design defines *what* the system does; this doc defines *how it lands in this codebase, in what order, with what milestones*.
|
||||
|
||||
## Status
|
||||
|
||||
Open questions resolved (see [Decisions Recorded](#decisions-recorded)). M0 is unblocked.
|
||||
|
||||
## Goals for the implementation
|
||||
|
||||
1. Ship the design's Phase 1 in production-quality form: a pushdown service that, given an Iceberg snapshot resolution, returns column-chunk byte ranges and prunes row groups using parsed-footer statistics.
|
||||
2. Establish the package layout, wire protocol, and trust-mode plumbing so later phases (scalar indexes, page-level pruning, deletes, vector search) attach without reshaping the surface.
|
||||
3. Avoid breaking any existing read path — pushdown is additive; standard S3 reads keep working.
|
||||
|
||||
## What already exists in the codebase
|
||||
|
||||
| Component | Path | Reuse |
|
||||
|---|---|---|
|
||||
| Iceberg-Go client and table/manifest types | `weed/s3api/iceberg/`, `weed/plugin/worker/iceberg/` | Catalog reads, manifest parsing, planning |
|
||||
| Parquet reader (`parquet-go/parquet-go v0.28.0`) | `weed/mq/logstore/`, `weed/query/engine/parquet_scanner.go` | Footer parse, ColumnIndex/OffsetIndex |
|
||||
| SQL/value type conversion | `weed/query/engine/parquet_scanner.go`, `weed/query/sqltypes/` | Predicate constant typing |
|
||||
| Iceberg compaction worker (uses iceberg-go for planning) | `weed/plugin/worker/iceberg/planning_index.go` | Reference for snapshot → file-list resolution |
|
||||
| Filer gRPC + protobuf scaffolding | `weed/pb/filer_pb/`, `weed/server/filer_grpc_server.go` | Wire-protocol pattern, auth |
|
||||
| S3 IAM / bucket ACL | `weed/s3api/`, `weed/iam/` | Trust enforcement on data files |
|
||||
| Substrait Go SDK (already a transitive dep) | `github.com/substrait-io/substrait-go/v7` | Predicate decode in v2 |
|
||||
|
||||
The dependencies needed for v1 (`parquet-go`, `iceberg-go`, `RoaringBitmap/roaring`, `substrait-go/v7`) are already in `go.mod` (some as indirect; will become direct).
|
||||
|
||||
## Architectural decisions for v1
|
||||
|
||||
These are commitments unless an open question below changes them.
|
||||
|
||||
- **Residency: catalog server (planning) + volume servers (heavy execution).** Pushdown is *not* a separate daemon. Planning (snapshot resolution, file-level pruning, side-index registry, footer cache, request validation) runs inside the existing catalog-server role — today colocated with the S3 gateway's Iceberg REST handlers in `weed/s3api/iceberg/`. Heavy execution (local index lookup, scalar predicate evaluation against indexes, vector distance + local top-K) runs on the volume server next to the data. The S3 gateway remains the compatibility path for unmodified readers. Rationale: the catalog already knows tables, snapshots, and table-to-files mapping, which is exactly what the planner needs — adding a separate daemon would duplicate that state. Heavy work goes to the volume servers so a single hot table cannot bottleneck cluster-wide planning. A standalone query-worker tier remains an option (design's Phase 4) only if measurements demand it.
|
||||
- **Wire protocol: gRPC.** New service definition `parquet_pushdown_pb.ParquetPushdown` in `weed/pb/parquet_pushdown_pb/`. REST/HTTP shim only if a connector requires it. JSON variant deferred.
|
||||
- **Trust mode for v1: catalog-validated, with connector-trusted as a developer-only flag.** The default deployment validates every request's `DataFiles` and `Deletes` against the Iceberg catalog at the requested snapshot before serving (full rules in [Trust Model](./PARQUET_PUSHDOWN_DESIGN.md#trust-model-and-catalog-validation)). Connector-trusted is supported but only enabled by an explicit flag for local development and benchmarks; it is not the default and is rejected in production builds. Manifest-signed is not on the roadmap.
|
||||
- **Predicate engine for v1: built-in subset evaluator.** The wire format accepts Substrait `ExtendedExpression`, but v1 implements only: comparisons (`=, !=, <, <=, >, >=`), `IN`, `BETWEEN`, `IS NULL`, and boolean `AND/OR/NOT` over them. Anything outside this subset returns `unsupported predicate`, and the connector falls back to a standard scan. Full Substrait evaluation lands in Phase 2.
|
||||
- **Side-index physical location:** co-located with the data in a hidden `.index/` directory next to each Parquet file or its parent folder, governed by the same filer ACLs as the data. Path layout matches the design's `<parquet_parent>/.index/<file_name>/<identity>/...` (file-scoped) and `<parquet_parent>/.index/<identity>/...` (folder-scoped) shapes — see [Physical Layout](./PARQUET_PUSHDOWN_DESIGN.md#physical-layout). The hidden-prefix name is configurable for deployments whose readers do not respect dot-prefix conventions.
|
||||
- **Parquet library: `parquet-go/parquet-go`** (already in use elsewhere in the repo). Apache `arrow-go/v18/parquet` is *not* introduced.
|
||||
- **Bitmap library: `RoaringBitmap/roaring`.** Used for position-delete bitmaps and DV decoding.
|
||||
|
||||
## Code layout
|
||||
|
||||
Code lives in two trees that match the architecture's two tiers. The proto stays shared.
|
||||
|
||||
**Catalog-server side** — registered on the gRPC server hosted by the catalog (today colocated with the S3 gateway's Iceberg REST handlers in `weed/s3api/iceberg/`):
|
||||
|
||||
```text
|
||||
weed/s3api/iceberg/pushdown/
|
||||
service.go # SeaweedParquetPushdown service entry
|
||||
request_validation.go # request-shape limits, trust-mode enforcement
|
||||
catalog/ # Phase 1: catalog-validated mode
|
||||
validator.go # cross-checks request DataFiles against manifest
|
||||
footer/
|
||||
cache.go # parsed-footer LRU, keyed by file identity
|
||||
parser.go # footer + ColumnIndex/OffsetIndex extraction
|
||||
predicate/
|
||||
substrait_decode.go # decode Substrait ExtendedExpression
|
||||
iceberg_decode.go # decode Iceberg Expression JSON
|
||||
eval_subset.go # v1 built-in evaluator (comparisons + boolean)
|
||||
rowgroup_prune.go # zone-map pruning for v1
|
||||
registry/ # Phase 2: side-index registry
|
||||
schema.go # registry rows + filer-backed CRUD
|
||||
reconciler.go # background freshness checker
|
||||
delete/ # Phase 2: Iceberg delete metadata
|
||||
position.go # tracks v2 position-delete files + DVs
|
||||
equality.go # tracks v2 equality-delete files
|
||||
loader.go # FileHandle + Loader (filer-backed for production)
|
||||
stats.go # PushdownStats accumulation
|
||||
```
|
||||
|
||||
**Volume-server side** (lands in Phase 3) — registered on the volume server's gRPC surface so index lookup, predicate evaluation, and vector compute run colocated with data:
|
||||
|
||||
```text
|
||||
weed/server/volume_grpc_pushdown.go # entry point on the volume server
|
||||
weed/storage/pushdown/
|
||||
index/
|
||||
bloom/ # Phase 3
|
||||
bitmap/ # Phase 3
|
||||
btree/ # Phase 3
|
||||
page/ # Phase 3
|
||||
vector/ivf/ # Phase 3
|
||||
exec/
|
||||
predicate.go # evaluate v1 predicate subset against indexes
|
||||
vector.go # local distance + top-K
|
||||
bitmap_merge.go # delete-bitmap union / subtraction
|
||||
```
|
||||
|
||||
**Shared proto** stays as today:
|
||||
|
||||
```text
|
||||
weed/pb/parquet_pushdown.proto # request/response messages
|
||||
weed/pb/parquet_pushdown_pb/ # generated
|
||||
```
|
||||
|
||||
Tests live alongside the code. Cross-tier integration tests live in `test/parquet_pushdown/`.
|
||||
|
||||
> **Existing code at `weed/parquet_pushdown/`** (M0 + M1) was scaffolded under the prior standalone-daemon decision. A code-move commit relocates the package to `weed/s3api/iceberg/pushdown/`, drops the `weed pushdown` subcommand and the standalone-daemon bootstrap, and rewires the service into the existing s3api gRPC server. That move is sequenced as the first task of M2 work in the revised milestones below.
|
||||
|
||||
## Milestones
|
||||
|
||||
Milestones are organized by the design's four-phase rollout: catalog candidates, catalog index registry, volume execution, optional workers. M0 and M1 already shipped under the previous standalone-daemon decision; **M2-rebase** is the first task of the revised plan and unblocks everything that follows.
|
||||
|
||||
### Already shipped under the prior architecture
|
||||
|
||||
Two milestones live at `weed/parquet_pushdown/` and need the rebase below before further work:
|
||||
|
||||
- **M0 (shipped):** proto + service skeleton + bufconn integration test.
|
||||
- **M1 (shipped):** parsed-footer cache + file/range-level pushdown for predicate-less requests.
|
||||
|
||||
### M2-rebase — Move pushdown into the catalog server (1 PR)
|
||||
|
||||
- Move `weed/parquet_pushdown/` to `weed/s3api/iceberg/pushdown/`. Update import paths.
|
||||
- Drop `weed pushdown` and `weed pushdown.ping`; remove `weed/parquet_pushdown/daemon/`. The standalone-daemon path is retired.
|
||||
- Register `SeaweedParquetPushdown` on the s3api gRPC server alongside the existing Iceberg REST handlers, gated by a `-pushdown.enabled` flag (default off until Phase 1 ships).
|
||||
- Update the existing M0/M1 tests to exercise the service via the s3api gRPC registration rather than a bufconn-only listener.
|
||||
- Acceptance: existing M0/M1 tests pass against the relocated package; `weed s3 -pushdown.enabled` exposes the service.
|
||||
|
||||
### Phase 1: Catalog returns candidate files / row groups / ranges
|
||||
|
||||
#### M3 — Row-group zone-map pruning (1 PR)
|
||||
|
||||
- `predicate/eval_subset.go`: evaluator for the v1 predicate subset.
|
||||
- `predicate/rowgroup_prune.go`: read row-group statistics from the parsed footer, drop row groups where the predicate cannot be true, return per-data-file `RowGroupRef` list.
|
||||
- `predicate/substrait_decode.go`: decode just enough Substrait to feed the subset evaluator; everything else returns `unsupported`.
|
||||
- Acceptance:
|
||||
- Predicate `WHERE timestamp BETWEEN t1 AND t2` against a 5M-row partitioned Iceberg table prunes to the expected row groups.
|
||||
- `unsupported predicate` returns a status the connector can recognize and fall back from.
|
||||
|
||||
#### M4 — Catalog-validated trust mode (1 PR; required for Phase 1)
|
||||
|
||||
- `catalog/validator.go`: read the Iceberg snapshot via the existing internal Iceberg package (decision 6 below), verify `(Path, SizeBytes, RecordCount, DataSequenceNumber, PartitionSpecId, PartitionValues)` for each `DataFile` and that the `Deletes` list matches the manifest's attached delete files.
|
||||
- Configurable per-endpoint: `pushdown.trust=catalog-validated|connector-trusted` (default `catalog-validated`; `connector-trusted` requires an explicit dev-mode flag).
|
||||
- Cache validated planning result keyed by `(table, SnapshotId)` to amortize manifest reads across requests in the same snapshot.
|
||||
- Acceptance: a tampered request (omitted delete file, wrong sequence number, file not in manifest, wrong partition values) is rejected with `permission_denied`. Cache hit/miss visible in `PushdownStats`.
|
||||
|
||||
**End of design Phase 1.** Phase 1 does not ship without M2-rebase + M3 + M4.
|
||||
|
||||
### Phase 2: Catalog tracks side-index registry
|
||||
|
||||
#### M5 — Index registry schema and CRUD (1 PR)
|
||||
|
||||
- `registry/schema.go`: registry rows of shape `(table, file_identity, kind, field_id) -> (.index path, build identity, build_time, healthy)`. Stored in the filer under a system path, separate from the table's bucket prefix.
|
||||
- CRUD APIs (gRPC + internal Go) for register, lookup, mark-stale, delete.
|
||||
- Planner consults the registry to know which indexes exist; missing entries fall through gracefully and are reported in stats.
|
||||
- Acceptance: register, lookup, list, and delete round-trips pass; planner stats show `indexes_used` / `indexes_missing` correctly populated.
|
||||
|
||||
#### M6 — Iceberg delete metadata in the registry (1 PR)
|
||||
|
||||
- Register position-delete files, equality-delete files, and v3 deletion vectors as registry entries attached to the data file they target.
|
||||
- Planner resolves applicable deletes per the design's applicability rules (sequence + partition + file scope, with per-row `file_path` filter for multi-target position-delete files).
|
||||
- Acceptance: planner returns the same data-file → delete-files mapping as a brute-force Iceberg manifest scan.
|
||||
|
||||
#### M7 — Background reconciler (1 PR)
|
||||
|
||||
- Worker that iterates the registry, verifies each `.index/` payload exists at the recorded path with the recorded identity, marks stale rows, and rebuilds when possible.
|
||||
- Compaction / snapshot expiration eviction: registry rows whose `file_identity` is no longer referenced by any active snapshot are reclaimable.
|
||||
- Acceptance: tampering with an index payload causes the next request to report it missing; reconciler restores the registry on the next pass.
|
||||
|
||||
### Phase 3: Volume servers execute local index/vector pushdown
|
||||
|
||||
#### M8 — Volume-server bloom-filter index (1–2 PRs)
|
||||
|
||||
- Build path: a worker reads Parquet column chunks and writes SplitBlock Bloom Filters to `.index/<file_name>/<identity>/bloom.fid_<id>` next to the data needles. Registry entry written on completion.
|
||||
- Read path: volume server gains a `PushdownExec` gRPC service that, given a (path, identity, kind, field_id, predicate), returns a per-row-group bitmap of surviving rows. Catalog plans for predicates touching bloom-able columns include the volume-server endpoint.
|
||||
- Acceptance: equality predicate `WHERE user_id = 'x'` against a 10M-row column with no matches reads zero column-chunk bytes after planning.
|
||||
|
||||
#### M9 — Volume-server bitmap and B-tree (1 PR each)
|
||||
|
||||
- `index/bitmap/` for low/medium-cardinality columns; integrates with `RoaringBitmap`.
|
||||
- `index/btree/` for sortable columns; range and point-lookup predicates.
|
||||
- Acceptance: ≥10× row-group reduction vs M3's footer-only pruning on the standard test workload.
|
||||
|
||||
#### M10 — Volume-server page-level pruning (1 PR)
|
||||
|
||||
- `index/page/`: wraps Parquet's `ColumnIndex` + `OffsetIndex` per [Page-Level Index](./PARQUET_PUSHDOWN_DESIGN.md#3-page-level-index); row-range translation across columns; dictionary-page byte-range inclusion.
|
||||
- Volume server returns `PageRef` entries with byte ranges for each projected column.
|
||||
- Acceptance: predicate selectivity ≥0.99 returns ≤1 page per surviving row group across all projected columns.
|
||||
|
||||
#### M11 — Volume-server delete bitmap evaluation (1 PR)
|
||||
|
||||
- v2 position-delete bitmap merge per the design's filter-by-`file_path` rule; cached with the registry's identity key.
|
||||
- v3 deletion-vector (Puffin `deletion-vector-v1`) reader + cache.
|
||||
- v2 equality-delete per-pair bitmap evaluation, accelerated by the volume server's scalar indexes.
|
||||
- Acceptance: a reference table with both delete forms returns identical row sets to a Spark scan of the same snapshot.
|
||||
|
||||
#### M12 — Volume-server vector index (1 PR)
|
||||
|
||||
- Partitioned IVF index per [Filtered-ANN strategy](./PARQUET_PUSHDOWN_DESIGN.md#filtered-ann-strategy); per-partition top-K runs entirely on the volume server. Catalog merges per-partition top-Ks across volume servers.
|
||||
- Acceptance: recall ≥0.95 vs brute force at top-20, 10× end-to-end speedup on the standard test set.
|
||||
|
||||
#### M13 — Hybrid scalar+vector pushdown (1 PR)
|
||||
|
||||
- Planner selects partitioned-IVF, post-filter+overscan, or filtered-HNSW per the design's strategy section based on selectivity estimate.
|
||||
- Acceptance: hybrid query that combines `tenant_id = 'x' AND timestamp >= t` with `ORDER BY embedding <-> q LIMIT 20` returns recall-correct results in <2× the cost of the lighter clause alone.
|
||||
|
||||
**End of design Phase 3.**
|
||||
|
||||
### Phase 4: Optional standalone query workers
|
||||
|
||||
Built only if profiling shows planning, hot-path coordination, or cross-volume merges become a bottleneck. Out of scope until measurements demand it.
|
||||
|
||||
### Connector integrations (parallel with Phases 1–3)
|
||||
|
||||
These run in parallel with Phases 1–3 once the catalog API stabilizes (post-M4). Each consumer reads byte ranges directly via S3 (compatibility path) or dispatches to volume-server endpoints (hot path) per request.
|
||||
|
||||
- DuckDB extension as PoC; consumes the gRPC API directly.
|
||||
- Trino connector pushdown.
|
||||
- Spark DataSource / Iceberg integration.
|
||||
|
||||
## Test strategy
|
||||
|
||||
- **Unit tests:** every package, with parquet-go in-memory fixtures.
|
||||
- **Integration tests:** `test/parquet_pushdown/` — spins up filer + a small Iceberg catalog (reuse `weed/s3api/iceberg/` infrastructure), generates Parquet data with `parquet-go` writers, compares pushdown results to a brute-force scan.
|
||||
- **Correctness oracle:** every milestone validates that pushdown output is a *strict subset* of a brute-force Iceberg+Parquet scan with the same predicate, and that the projected-column byte ranges decode to the same rows. The oracle is the safety net that lets us refactor index internals freely.
|
||||
- **Performance suite:** runs in CI weekly, not on every PR. Tracks footer-cache hit rate, row-group reduction, page reduction, end-to-end query latency vs a baseline standard scan.
|
||||
|
||||
## Decisions Recorded
|
||||
|
||||
These were the open questions before M0. All have been resolved; recording for traceability and to anchor future amendments.
|
||||
|
||||
1. **Residency:** catalog server (planning, registry, footer cache) + volume servers (local index lookup, predicate eval, vector compute). Standalone daemons are *not* introduced; query workers as an extra tier remain a future option contingent on measurements. (See [Architectural decisions](#architectural-decisions-for-v1).)
|
||||
2. **Service surface:** new `weed/pb/parquet_pushdown_pb/` package; not extending `filer_pb`.
|
||||
3. **Trust mode:** catalog-validated is the default and required for Phase 1 shipping; connector-trusted is a dev-only flag rejected in production builds.
|
||||
4. **Side-index path:** co-located in a hidden `.index/` directory next to the Parquet data, under the same parent folder. File-scoped: `<parquet_parent>/.index/<file_name>/<identity>/...`. Folder-scoped: `<parquet_parent>/.index/<identity>/...`. Hidden-prefix name configurable for non-dot-aware readers.
|
||||
5. **Predicate subset for v1:** `=`, `!=`, `<`, `<=`, `>`, `>=`, `IN`, `BETWEEN`, `IS NULL`, boolean `AND/OR/NOT`. `LIKE` deferred to the inverted-index milestone. Wire format is Substrait `ExtendedExpression` from M0.
|
||||
6. **Iceberg snapshot integration:** route through the existing internal Iceberg packages (`weed/s3api/iceberg/`, `weed/plugin/worker/iceberg/`); do not add a parallel `iceberg-go` integration in `weed/parquet_pushdown/`.
|
||||
7. **Auth:** reuse the filer's existing auth. The request principal must have read access to every `DataFile` listed; the daemon enforces this by re-using the filer's authorization on every blob fetch.
|
||||
8. **Test corpus:** generated from scratch in `test/parquet_pushdown/fixtures/`, parameterized over (with-position-deletes, with-equality-deletes, with-DVs, partitioned/unpartitioned).
|
||||
9. **Phase 1 done bar:** passing CI tests + an I/O-reduction benchmark on a reference query. Connector PoC slips to M12.
|
||||
10. **Performance regression budget for v1:** ≤10% added latency vs a direct ranged GET on a 10 MiB single-file scan in the worst case (predicate prunes nothing). The threshold is exposed as a configuration knob (`pushdown.max_overhead_pct`, default `10`) so deployments can tighten or loosen it without code changes.
|
||||
|
||||
## Risk register
|
||||
|
||||
- **Iceberg-Go maturity for v3 deletion vectors / Puffin.** If `iceberg-go v0.5.0` does not expose Puffin DV blobs, M8 needs a vendored Puffin parser. Spike during M0 to verify.
|
||||
- **parquet-go ColumnIndex/OffsetIndex completeness.** M6 depends on full ColumnIndex/OffsetIndex support. If the library returns nil for some files, fall back to row-group-only pruning per the design.
|
||||
- **Catalog read latency.** M3's per-request manifest read must be cacheable per snapshot, otherwise the catalog-validated mode adds >100ms per request. Cache eviction strategy is part of M3's spec.
|
||||
- **Trust boundary leakage.** A pushdown response must not return data references that a direct read would deny. The auth check (open question 7) is load-bearing; integration tests in M0 must include negative cases.
|
||||
@@ -39,7 +39,7 @@ require (
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/jackc/pgx/v5 v5.9.0
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
@@ -303,7 +303,7 @@ require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.0 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect
|
||||
|
||||
@@ -577,8 +577,8 @@ github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK
|
||||
github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24=
|
||||
github.com/Azure/go-autorest/autorest/to v0.4.1 h1:CxNHBqdzTr7rLtdrtb5CMjJcDut+WNGCVv7OmS5+lTc=
|
||||
github.com/Azure/go-autorest/autorest/to v0.4.1/go.mod h1:EtaofgU4zmtvn1zT2ARsjRFdq9vXx0YWtmElwL+GZ9M=
|
||||
github.com/Azure/go-ntlmssp v0.1.0 h1:DjFo6YtWzNqNvQdrwEyr/e4nhU3vRiwenz5QX7sFz+A=
|
||||
github.com/Azure/go-ntlmssp v0.1.0/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
|
||||
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
|
||||
@@ -1403,8 +1403,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.9.0 h1:T/dI+2TvmI2H8s/KH1/lXIbz1CUFk3gn5oTjr0/mBsE=
|
||||
github.com/jackc/pgx/v5 v5.9.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
|
||||
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
|
||||
|
||||
@@ -247,9 +247,9 @@ spec:
|
||||
{{- $httpsPort := .Values.allInOne.s3.httpsPort | default .Values.s3.httpsPort }}
|
||||
{{- if $httpsPort }}
|
||||
-s3.port.https={{ $httpsPort }} \
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.s3.tlsArgs" (dict "root" . "prefix" "s3.") | nindent 14 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if or .Values.allInOne.s3.enableAuth .Values.s3.enableAuth .Values.filer.s3.enableAuth }}
|
||||
-s3.config=/etc/sw/s3/seaweedfs_s3_config \
|
||||
{{- end }}
|
||||
|
||||
@@ -200,9 +200,9 @@ spec:
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
{{- if .Values.filer.s3.httpsPort }}
|
||||
-s3.port.https={{ .Values.filer.s3.httpsPort }} \
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.s3.tlsArgs" (dict "root" . "prefix" "s3.") | nindent 14 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.filer.s3.enableAuth }}
|
||||
-s3.config=/etc/sw/seaweedfs_s3_config \
|
||||
{{- end }}
|
||||
|
||||
@@ -127,9 +127,9 @@ spec:
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
{{- if .Values.s3.httpsPort }}
|
||||
-port.https={{ .Values.s3.httpsPort }} \
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.s3.tlsArgs" (dict "root" . "prefix" "") | nindent 14 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.s3.domainName }}
|
||||
-domainName={{ .Values.s3.domainName }} \
|
||||
{{- end }}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
MARP ?= npx @marp-team/marp-cli
|
||||
SRC := seaweedfs-production-setup.md
|
||||
PDF := $(SRC:.md=.pdf)
|
||||
HTML := $(SRC:.md=.html)
|
||||
PPTX := $(SRC:.md=.pptx)
|
||||
FLAGS := --allow-local-files
|
||||
|
||||
.PHONY: all pdf html pptx watch clean
|
||||
|
||||
all: pdf
|
||||
|
||||
pdf: $(PDF)
|
||||
|
||||
html: $(HTML)
|
||||
|
||||
pptx: $(PPTX)
|
||||
|
||||
$(PDF): $(SRC)
|
||||
$(MARP) $(SRC) --pdf $(FLAGS) -o $@
|
||||
|
||||
$(HTML): $(SRC)
|
||||
$(MARP) $(SRC) --html $(FLAGS) -o $@
|
||||
|
||||
$(PPTX): $(SRC)
|
||||
$(MARP) $(SRC) --pptx $(FLAGS) -o $@
|
||||
|
||||
watch:
|
||||
$(MARP) $(SRC) --watch --html $(FLAGS)
|
||||
|
||||
clean:
|
||||
rm -f $(PDF) $(HTML) $(PPTX)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 738 KiB |
@@ -0,0 +1,118 @@
|
||||
---
|
||||
marp: true
|
||||
theme: default
|
||||
paginate: true
|
||||
---
|
||||
|
||||
# SeaweedFS Production Setup
|
||||
|
||||
A walkthrough of the recommended deployment topology
|
||||
|
||||
- Storage layer
|
||||
- File access layer
|
||||
- Backend operations
|
||||
- Erasure coding for durability
|
||||
|
||||
---
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
# Storage Layer
|
||||
|
||||
**3 Masters + Volume Servers**
|
||||
|
||||
- **Masters (run 3)**
|
||||
- Form a Raft quorum; tolerate 1 failure
|
||||
- Track volume locations and cluster topology
|
||||
- Lightweight; not on the data path for reads/writes after lookup
|
||||
|
||||
- **Volume Servers (scale out)**
|
||||
- Hold the actual needle data on local disks
|
||||
- Add more servers for capacity and throughput
|
||||
- Heartbeat to masters; clients talk to them directly for I/O
|
||||
|
||||
Rule of thumb: start with 3 masters, then grow volume servers with data.
|
||||
|
||||
---
|
||||
|
||||
# File Access Layer
|
||||
|
||||
**Filer + DB for metadata**
|
||||
|
||||
- Filer serves POSIX-like directory and file metadata
|
||||
- Metadata store options: PostgreSQL, MySQL, Redis, Cassandra, TiKV, etc.
|
||||
- Run **3 filers** for HA
|
||||
- Filers are stateless relative to each other — state lives in the DB
|
||||
|
||||
**S3 Servers**
|
||||
|
||||
- Expose the S3 API on top of the filer
|
||||
- Scale the count based on throughput requirements
|
||||
- Can be co-located with filers or run independently
|
||||
|
||||
---
|
||||
|
||||
# Backend Operations
|
||||
|
||||
**1 Admin Server + a few Workers**
|
||||
|
||||
- **Admin server (1 is enough)**
|
||||
- Coordinates background jobs: balancing, EC encoding, vacuum, replication fixes
|
||||
- **Not on the data path** — a restart does not affect object store reads/writes
|
||||
- No HA required for normal operation
|
||||
|
||||
- **Workers (a few)**
|
||||
- Execute long-running tasks issued by the admin server
|
||||
- Horizontally scalable based on maintenance workload
|
||||
|
||||
Keeps housekeeping off the hot path.
|
||||
|
||||
---
|
||||
|
||||
# Production Topology Summary
|
||||
|
||||
| Component | Count | Role |
|
||||
|----------------|----------------------|-----------------------------------|
|
||||
| Master | 3 | Raft quorum, topology, volume map |
|
||||
| Volume Server | N (scale out) | Stores data needles |
|
||||
| Filer | 3 | Metadata gateway |
|
||||
| Metadata DB | HA cluster | Persists filer metadata |
|
||||
| S3 Server | N (by throughput) | S3 API frontend |
|
||||
| Admin | 1 | Background job coordinator |
|
||||
| Worker | A few | Executes admin-scheduled tasks |
|
||||
|
||||
---
|
||||
|
||||
# Erasure Coding for Durability
|
||||
|
||||
Prefer **many volume servers** so EC shards spread across failure domains.
|
||||
|
||||
**Example: 8 volume servers, EC 5+3**
|
||||
|
||||
- Each volume becomes 5 data shards + 3 parity shards
|
||||
- Shards are placed on 8 distinct volume servers
|
||||
- **Tolerates up to 3 simultaneous volume server failures**
|
||||
- Storage overhead: 1.6x vs 3x for full replication
|
||||
|
||||
```
|
||||
Volume -> [D1][D2][D3][D4][D5] + [P1][P2][P3]
|
||||
| | | | | | | |
|
||||
VS1 VS2 VS3 VS4 VS5 VS6 VS7 VS8
|
||||
```
|
||||
|
||||
More volume servers = more EC layouts available (e.g. 10+4, 6+3).
|
||||
|
||||
---
|
||||
|
||||
# Getting Started Checklist
|
||||
|
||||
1. Provision 3 master nodes (small boxes are fine)
|
||||
2. Provision volume servers sized to your data footprint
|
||||
3. Stand up an HA metadata DB, then 3 filers pointing at it
|
||||
4. Add S3 servers sized to required throughput
|
||||
5. Run 1 admin + a few workers for background maintenance
|
||||
6. Once you have enough volume servers, enable EC (e.g. 5+3 on 8 servers)
|
||||
|
||||
Scale each layer independently as usage grows.
|
||||
Generated
+2
-2
@@ -3350,9 +3350,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.10"
|
||||
version = "0.103.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef"
|
||||
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"ring",
|
||||
|
||||
@@ -339,6 +339,7 @@ message ReceiveFileInfo {
|
||||
bool is_ec_volume = 4;
|
||||
uint32 shard_id = 5;
|
||||
uint64 file_size = 6;
|
||||
uint32 disk_id = 7; // EC shard disk; 0 = auto-select (see VolumeEcShardsCopyRequest.disk_id)
|
||||
}
|
||||
|
||||
message ReceiveFileResponse {
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 70 B After Width: | Height: | Size: 6.6 KiB |
@@ -1425,13 +1425,43 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// Determine file path
|
||||
let path = if info.is_ec_volume {
|
||||
let store = self.state.store.read().unwrap();
|
||||
// Go prefers a HardDriveType location, then falls back to first
|
||||
let dir = store
|
||||
.locations
|
||||
.iter()
|
||||
.find(|loc| loc.disk_type == DiskType::HardDrive)
|
||||
.or_else(|| store.locations.first())
|
||||
.map(|loc| loc.directory.clone());
|
||||
// std::fs::File::create truncates in place; a mounted
|
||||
// EcVolume holds fds on the same inodes, so overwriting
|
||||
// corrupts live readers.
|
||||
if store.has_ec_volume(VolumeId(info.volume_id)) {
|
||||
resp_error = Some(format!(
|
||||
"ec volume {} is mounted; unmount before ReceiveFile",
|
||||
info.volume_id
|
||||
));
|
||||
break;
|
||||
}
|
||||
// disk_id=0 means "unset" (protobuf default), so auto-select
|
||||
// mirrors VolumeEcShardsCopy: prefer a disk already holding
|
||||
// this volume's shards, then any HDD, then any disk.
|
||||
let vid = VolumeId(info.volume_id);
|
||||
let dir = if info.disk_id > 0 {
|
||||
let count = store.locations.len();
|
||||
if (info.disk_id as usize) >= count {
|
||||
resp_error = Some(format!(
|
||||
"invalid disk_id {}: only have {} disks",
|
||||
info.disk_id, count
|
||||
));
|
||||
break;
|
||||
}
|
||||
Some(store.locations[info.disk_id as usize].directory.clone())
|
||||
} else {
|
||||
let loc_idx = store
|
||||
.find_free_location_predicate(|loc| loc.has_ec_volume(vid))
|
||||
.or_else(|| {
|
||||
store.find_free_location_predicate(|loc| {
|
||||
loc.disk_type == DiskType::HardDrive
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
store.find_free_location_predicate(|_| true)
|
||||
});
|
||||
loc_idx.map(|i| store.locations[i].directory.clone())
|
||||
};
|
||||
drop(store);
|
||||
let dir = match dir {
|
||||
Some(d) => d,
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -82,9 +81,25 @@ func TestFcntlLockHelper(t *testing.T) {
|
||||
start, _ := strconv.ParseInt(os.Getenv("LOCK_START"), 10, 64)
|
||||
length, _ := strconv.ParseInt(os.Getenv("LOCK_LEN"), 10, 64)
|
||||
|
||||
f, err := os.OpenFile(filePath, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "open: %v\n", err)
|
||||
// The parent test process created the file on the FUSE mount just before
|
||||
// spawning this subprocess. A fresh lookup from a different process can
|
||||
// briefly return ENOENT while the mount's dentry state propagates, so
|
||||
// retry on ENOENT before giving up.
|
||||
var f *os.File
|
||||
var openErr error
|
||||
for attempt := 0; attempt < 40; attempt++ {
|
||||
f, openErr = os.OpenFile(filePath, os.O_RDWR, 0)
|
||||
if openErr == nil {
|
||||
break
|
||||
}
|
||||
if !errors.Is(openErr, os.ErrNotExist) && !errors.Is(openErr, syscall.ENOENT) {
|
||||
break
|
||||
}
|
||||
_, _ = os.ReadDir(filepath.Dir(filePath))
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if openErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "open: %v\n", openErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer f.Close()
|
||||
@@ -617,9 +632,14 @@ func testFcntlReleaseOnClose(t *testing.T, fw *FuseTestFramework) {
|
||||
// reader goroutines (blocking FUSE SETLKW can starve unlock processing).
|
||||
func testConcurrentLockContention(t *testing.T, fw *FuseTestFramework) {
|
||||
path := filepath.Join(fw.GetMountPoint(), "lock_contention.txt")
|
||||
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
// Hold a master fd open for the whole subtest. Workers take flock on their
|
||||
// own fds; master stays passive. Keeping this reference pinned avoids the
|
||||
// re-open-after-concurrent-close code path, which has shown an unresolved
|
||||
// mount/metaCache coherence bug where a freshly-opened fd sees ENOENT for
|
||||
// tens of seconds after a burst of concurrent Release calls.
|
||||
master, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, f.Close())
|
||||
defer master.Close()
|
||||
|
||||
numWorkers := 8
|
||||
writesPerWorker := 5
|
||||
@@ -720,45 +740,57 @@ func testConcurrentLockContention(t *testing.T, fw *FuseTestFramework) {
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
if runtime.GOOS == "darwin" {
|
||||
for _, err := range errs {
|
||||
if err != nil && strings.Contains(err.Error(), "no such file or directory") {
|
||||
t.Skip("lock contention file disappeared on darwin FUSE; skipping flaky check")
|
||||
}
|
||||
}
|
||||
}
|
||||
require.Empty(t, errs, "concurrent lock contention errors: %v", errs)
|
||||
|
||||
flush := func() {
|
||||
verify, err := openWithRetry(os.O_RDWR)
|
||||
if err != nil && runtime.GOOS == "darwin" && strings.Contains(err.Error(), "no such file or directory") {
|
||||
t.Skip("lock contention file disappeared on darwin FUSE; skipping flaky check")
|
||||
}
|
||||
require.NoError(t, err)
|
||||
defer verify.Close()
|
||||
require.NoError(t, verify.Sync())
|
||||
}
|
||||
flush()
|
||||
// Flush via the master fd. fsync on any fd to the file forces the
|
||||
// kernel to send FUSE_FSYNC, which drains workers' writes to the filer.
|
||||
require.NoError(t, master.Sync())
|
||||
|
||||
expectedLines := numWorkers * writesPerWorker
|
||||
expectedBytes := expectedLines * recordSize
|
||||
var data []byte
|
||||
require.Eventually(t, func() bool {
|
||||
verify, err := openWithRetry(os.O_RDONLY)
|
||||
if err != nil {
|
||||
if runtime.GOOS == "darwin" && strings.Contains(err.Error(), "no such file or directory") {
|
||||
t.Skip("lock contention file disappeared on darwin FUSE; skipping flaky check")
|
||||
}
|
||||
var lastReadErr error
|
||||
ok := assert.Eventually(t, func() bool {
|
||||
if _, err := master.Seek(0, io.SeekStart); err != nil {
|
||||
lastReadErr = fmt.Errorf("seek: %w", err)
|
||||
return false
|
||||
}
|
||||
defer verify.Close()
|
||||
|
||||
data, err = io.ReadAll(verify)
|
||||
d, err := io.ReadAll(master)
|
||||
if err != nil {
|
||||
lastReadErr = fmt.Errorf("read: %w", err)
|
||||
return false
|
||||
}
|
||||
data = d
|
||||
lastReadErr = nil
|
||||
return len(data) == expectedBytes
|
||||
}, 15*time.Second, 100*time.Millisecond, "file should eventually contain exactly %d records from all workers", expectedLines)
|
||||
if !ok {
|
||||
// Diagnostics: dump what the mount currently shows for the parent dir
|
||||
// and the target path, so post-mortem analysis has something to go on.
|
||||
parent := filepath.Dir(path)
|
||||
if entries, readErr := os.ReadDir(parent); readErr != nil {
|
||||
t.Logf("diag: ReadDir(%q) failed: %v", parent, readErr)
|
||||
} else {
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
t.Logf("diag: ReadDir(%q) returned %d entries: %v", parent, len(names), names)
|
||||
}
|
||||
if fi, statErr := os.Stat(path); statErr != nil {
|
||||
t.Logf("diag: Stat(%q) failed: %v", path, statErr)
|
||||
} else {
|
||||
t.Logf("diag: Stat(%q) ok: size=%d mode=%s", path, fi.Size(), fi.Mode())
|
||||
}
|
||||
if freshFd, openErr := os.OpenFile(path, os.O_RDONLY, 0); openErr != nil {
|
||||
t.Logf("diag: fresh open(%q, O_RDONLY) failed: %v", path, openErr)
|
||||
} else {
|
||||
fresh, readErr := io.ReadAll(freshFd)
|
||||
freshFd.Close()
|
||||
t.Logf("diag: fresh open(%q) read %d bytes (err=%v)", path, len(fresh), readErr)
|
||||
}
|
||||
t.Fatalf("read back incomplete: got %d bytes, want %d (lastReadErr=%v)", len(data), expectedBytes, lastReadErr)
|
||||
}
|
||||
actualLines := bytes.Count(data, []byte("\n"))
|
||||
assert.Equal(t, expectedLines, actualLines,
|
||||
"file should contain exactly %d lines from all workers", expectedLines)
|
||||
|
||||
@@ -208,8 +208,6 @@ func (c *p2pTestCluster) startFiler(configDir string) error {
|
||||
"-port.grpc="+strconv.Itoa(c.filerGrpcPort),
|
||||
"-master="+c.masterAddress(),
|
||||
"-defaultStoreDir="+filerDir,
|
||||
// default is -mount.p2p=true; be explicit so the intent is grep-able.
|
||||
"-mount.p2p=true",
|
||||
)
|
||||
return c.startCmd(c.filerCmd, "filer")
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestOffsetManagement(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("ConsumerGroupResumption", func(t *testing.T) {
|
||||
testConsumerGroupResumption(t, addr, topic2, groupID+"2")
|
||||
testConsumerGroupResumption(t, gateway, addr, topic2, groupID+"2")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ func testBasicOffsetCommitFetch(t *testing.T, addr, topic, groupID string) {
|
||||
t.Logf("SUCCESS: Offset management test completed - consumed %d + %d messages", len(consumed1), len(consumed2))
|
||||
}
|
||||
|
||||
func testConsumerGroupResumption(t *testing.T, addr, topic, groupID string) {
|
||||
func testConsumerGroupResumption(t *testing.T, gateway *testutil.GatewayTestServer, addr, topic, groupID string) {
|
||||
client := testutil.NewKafkaGoClient(t, addr)
|
||||
msgGen := testutil.NewMessageGenerator()
|
||||
|
||||
@@ -97,10 +97,18 @@ func testConsumerGroupResumption(t *testing.T, addr, topic, groupID string) {
|
||||
for i, msg := range consumed1 {
|
||||
t.Logf(" Message %d: offset=%d, partition=%d, value=%s", i, msg.Offset, msg.Partition, string(msg.Value))
|
||||
}
|
||||
gateway.LogConsumerGroupSnapshot(groupID)
|
||||
|
||||
// Simulate consumer restart by consuming remaining messages with same group ID
|
||||
t.Logf("=== Phase 3: Second consumer (simulated restart) - consuming remaining messages with same group %s ===", groupID)
|
||||
consumed2, err := client.ConsumeWithGroup(topic, groupID, 2)
|
||||
consumed2, err := client.ConsumeWithGroupDebug(topic, groupID, 2, func(info testutil.ConsumeGroupRetryDebug) {
|
||||
t.Logf("Consumer restart attempt %d/%d for group %s failed before receiving any messages: %v",
|
||||
info.Attempt, info.MaxAttempts, info.GroupID, info.Err)
|
||||
gateway.LogConsumerGroupSnapshot(groupID)
|
||||
})
|
||||
if err != nil {
|
||||
gateway.LogConsumerGroupSnapshot(groupID)
|
||||
}
|
||||
testutil.AssertNoError(t, err, "Failed to consume after restart")
|
||||
t.Logf("Second consumer consumed %d messages:", len(consumed2))
|
||||
for i, msg := range consumed2 {
|
||||
|
||||
+8
-8
@@ -22,9 +22,9 @@ require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.0 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37 // indirect
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264 // indirect
|
||||
github.com/IBM/go-sdk-core/v5 v5.21.0 // indirect
|
||||
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd // indirect
|
||||
@@ -43,12 +43,12 @@ require (
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/aws/aws-sdk-go v1.55.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 // indirect
|
||||
@@ -62,7 +62,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 // indirect
|
||||
github.com/aws/smithy-go v1.24.2 // indirect
|
||||
github.com/aws/smithy-go v1.25.0 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/boombuler/barcode v1.1.0 // indirect
|
||||
@@ -104,7 +104,7 @@ require (
|
||||
github.com/geoffgarside/ber v1.2.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.2.5 // indirect
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.6.2 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.8.0 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
@@ -134,7 +134,7 @@ require (
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd // indirect
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
@@ -194,7 +194,7 @@ require (
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11 // indirect
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18 // indirect
|
||||
github.com/rclone/rclone v1.73.1 // indirect
|
||||
github.com/rclone/rclone v1.73.5 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
github.com/rdleal/intervalst v1.5.0 // indirect
|
||||
github.com/relvacode/iso8601 v1.7.0 // indirect
|
||||
|
||||
+16
-16
@@ -51,8 +51,8 @@ github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 h1:jWQK1GI+LeGGUKBAD
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4/go.mod h1:8mwH4klAm9DUgR2EEHyEEAQlRDvLPyg5fQry3y+cDew=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3 h1:sxgSqOB9CDToiaVFpxuvb5wGgGqWa3lCShcm5o0n3bE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3/go.mod h1:XdED8i399lEVblYHTZM8eXaP07gv4Z58IL6ueMlVlrg=
|
||||
github.com/Azure/go-ntlmssp v0.1.0 h1:DjFo6YtWzNqNvQdrwEyr/e4nhU3vRiwenz5QX7sFz+A=
|
||||
github.com/Azure/go-ntlmssp v0.1.0/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
|
||||
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
|
||||
@@ -61,8 +61,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37 h1:W8S9TrAyZ4//3PXsU6+Bi+fe/6uIL986GyS7PVzIDL4=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38 h1:YCyHs3wUXEe2BEWn40vcoyaQ2ruHNmNwkasfo3Th16A=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264 h1:lMHTplAYI9FtmCo/QOcpRxmPA5REVAct1r2riQmDQKw=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264/go.mod h1:wGqkOzRu/ClJibvDgcfuJNAqI2nLhe8g91tPlDKRCdE=
|
||||
github.com/IBM/go-sdk-core/v5 v5.21.0 h1:DUnYhvC4SoC8T84rx5omnhY3+xcQg/Whyoa3mDPIMkk=
|
||||
@@ -112,8 +112,8 @@ github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc/go.mod h1:w648aMHEgFYS6xb0KVMMtZ2uMeemhiKCuD2vj6gY52A=
|
||||
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6 h1:1AX0AthnBQzMx1vbmir3Y4WsnJgiydmnJjiLu+LvXOg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6/go.mod h1:dy0UzBIfwSeot4grGvY1AqFWN5zgziMmWGzysDnHFcQ=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 h1:opVIRo/ZbbI8OIqSOKmpFaY7IwfFUOCCXBsUpJOwDdI=
|
||||
@@ -122,8 +122,8 @@ github.com/aws/aws-sdk-go-v2/credentials v1.19.14 h1:n+UcGWAIZHkXzYt87uMFBv/l8TH
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14/go.mod h1:cJKuyWB59Mqi0jM3nFYQRmnHVQIcgoxjEMAbLkpr62w=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 h1:NUS3K4BTDArQqNu2ih7yeDLaS3bmHD0YndtA6UP884g=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21/go.mod h1:YWNWJQNjKigKY1RHVJCuupeWDrrHjRqHm0N9rdrWzYI=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 h1:Zy6Tme1AA13kX8x3CnkHx5cqdGWGaj/anwOiWGnA0Xo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12/go.mod h1:ql4uXYKoTM9WUAUSmthY4AtPVrlTBZOvnBJTiCUdPxI=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1 h1:IbWiN670htmBioc+Zj32vSpJgQ2+OYSlvTvfQ1nCORQ=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1/go.mod h1:tw/B596EUhBWDFGdDGuLC21fVU4A3s4/5Efy8S39W18=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A=
|
||||
@@ -150,8 +150,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 h1:dzztQ1YmfPrxdrOiuZRMF6f
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19/go.mod h1:YO8TrYtFdl5w/4vmjL8zaBSsiNp3w0L1FfKVKenZT7w=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 h1:p8ogvvLugcR/zLBXTXrTkj0RYBUdErbMnAFFp12Lm/U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10/go.mod h1:60dv0eZJfeVXfbT1tFJinbHrDfSJ2GZl4Q//OSSNAVw=
|
||||
github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=
|
||||
github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/smithy-go v1.25.0 h1:Sz/XJ64rwuiKtB6j98nDIPyYrV1nVNJ4YU74gttcl5U=
|
||||
github.com/aws/smithy-go v1.25.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
@@ -281,8 +281,8 @@ github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 h1:JnrjqG5iR07/8k7N
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348/go.mod h1:Czxo/d1g948LtrALAZdL04TL/HnkopquAjxYUuI02bo=
|
||||
github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk=
|
||||
github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
|
||||
github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
|
||||
github.com/go-git/go-billy/v5 v5.8.0 h1:I8hjc3LbBlXTtVuFNJuwYuMiHvQJDq1AT6u4DwDzZG0=
|
||||
github.com/go-git/go-billy/v5 v5.8.0/go.mod h1:RpvI/rw4Vr5QA+Z60c6d6LXH0rYJo0uD5SqfmrrheCY=
|
||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
@@ -427,8 +427,8 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c h1:r+KtxPyrhsYeNbsfeqTfEM8xRdwgV6LuNhLZxpXecb4=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c/go.mod h1:vdPya4AIcDjvng4ViaAzqjegJf0VHYpYHQguFx5xBp0=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd h1:dSIuz2mpJAPQfhHYtG57D0qwSkgC/vQ69gHfeyQ4kxA=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd/go.mod h1:vdPya4AIcDjvng4ViaAzqjegJf0VHYpYHQguFx5xBp0=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
|
||||
@@ -594,8 +594,8 @@ github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11 h1:4MI2
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11/go.mod h1:3HLX7dwZgvB7nt+Yl/xdzVPcargQ1yBmJEUg3n+jMKM=
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18 h1:Lc+d3ISfQaMJKWZOE7z4ZSY4RVmdzbn1B0IM8xN18qM=
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18/go.mod h1:LB2kCEaZMzNn3ocdz+qYfxXmuLxxN0ka62KJd2x53Bc=
|
||||
github.com/rclone/rclone v1.73.1 h1:FCGZUd7sXO8+nIpbuXGPkd+f23o/ZACefrHtRGDAiDM=
|
||||
github.com/rclone/rclone v1.73.1/go.mod h1:T9HeSXv/SI9qJFkYLqsjY/5ljIFWJTVmTrG7H/4JrPY=
|
||||
github.com/rclone/rclone v1.73.5 h1:r8a9JHYIWUqk7hNRJuMJ3cROkKfB2zmfkADg8ZLYh6I=
|
||||
github.com/rclone/rclone v1.73.5/go.mod h1:WVv8gvA/lEl/Y37e8I8yosm7ZY+Szq7ujXbJS8Ol63o=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
|
||||
|
||||
@@ -31,6 +31,15 @@ type SaramaClient struct {
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
type ConsumeGroupRetryDebug struct {
|
||||
Attempt int
|
||||
MaxAttempts int
|
||||
Topic string
|
||||
GroupID string
|
||||
ExpectedCount int
|
||||
Err error
|
||||
}
|
||||
|
||||
// NewKafkaGoClient creates a new kafka-go test client
|
||||
func NewKafkaGoClient(t *testing.T, brokerAddr string) *KafkaGoClient {
|
||||
return &KafkaGoClient{
|
||||
@@ -142,6 +151,14 @@ func (k *KafkaGoClient) ConsumeMessages(topicName string, expectedCount int) ([]
|
||||
// member's LeaveGroup / session cleanup and can surface as an i/o timeout on
|
||||
// the first FetchMessage.
|
||||
func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCount int) ([]kafka.Message, error) {
|
||||
return k.consumeWithGroup(topicName, groupID, expectedCount, nil)
|
||||
}
|
||||
|
||||
func (k *KafkaGoClient) ConsumeWithGroupDebug(topicName, groupID string, expectedCount int, onRetry func(ConsumeGroupRetryDebug)) ([]kafka.Message, error) {
|
||||
return k.consumeWithGroup(topicName, groupID, expectedCount, onRetry)
|
||||
}
|
||||
|
||||
func (k *KafkaGoClient) consumeWithGroup(topicName, groupID string, expectedCount int, onRetry func(ConsumeGroupRetryDebug)) ([]kafka.Message, error) {
|
||||
k.t.Helper()
|
||||
|
||||
const maxJoinAttempts = 5
|
||||
@@ -158,6 +175,16 @@ func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCoun
|
||||
if progressed {
|
||||
return messages, err
|
||||
}
|
||||
if onRetry != nil {
|
||||
onRetry(ConsumeGroupRetryDebug{
|
||||
Attempt: attempt,
|
||||
MaxAttempts: maxJoinAttempts,
|
||||
Topic: topicName,
|
||||
GroupID: groupID,
|
||||
ExpectedCount: expectedCount,
|
||||
Err: err,
|
||||
})
|
||||
}
|
||||
if attempt == maxJoinAttempts {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package testutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -111,6 +112,31 @@ func (g *GatewayTestServer) CleanupAndClose() {
|
||||
}
|
||||
}
|
||||
|
||||
// LogConsumerGroupSnapshot dumps the gateway's current view of a consumer group.
|
||||
func (g *GatewayTestServer) LogConsumerGroupSnapshot(groupID string) {
|
||||
g.t.Helper()
|
||||
|
||||
handler := g.GetHandler()
|
||||
if handler == nil {
|
||||
g.t.Logf("Consumer group snapshot for %s unavailable: handler is nil", groupID)
|
||||
return
|
||||
}
|
||||
|
||||
snapshot := handler.DebugGroupSnapshot(groupID)
|
||||
if snapshot == nil {
|
||||
g.t.Logf("Consumer group snapshot for %s unavailable", groupID)
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := json.MarshalIndent(snapshot, "", " ")
|
||||
if err != nil {
|
||||
g.t.Logf("Consumer group snapshot for %s could not be marshaled: %v", groupID, err)
|
||||
return
|
||||
}
|
||||
|
||||
g.t.Logf("Consumer group snapshot for %s:\n%s", groupID, string(payload))
|
||||
}
|
||||
|
||||
// SMQAvailabilityMode indicates whether SeaweedMQ is available for testing
|
||||
type SMQAvailabilityMode int
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -338,15 +340,29 @@ func TestServiceAccountValidation(t *testing.T) {
|
||||
// callIAMAPI is a helper to make IAM API calls
|
||||
func callIAMAPI(t *testing.T, action string, params url.Values) (*http.Response, error) {
|
||||
params.Set("Action", action)
|
||||
body := params.Encode()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, TestIAMEndpoint+"/",
|
||||
strings.NewReader(params.Encode()))
|
||||
strings.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// Sign with SigV4 when admin credentials are provided via env vars.
|
||||
// IAM write APIs (CreateUser, CreateServiceAccount, etc.) require an
|
||||
// authenticated admin caller; unsigned requests get routed to the STS
|
||||
// fallback and rejected as an unknown action.
|
||||
if accessKey := os.Getenv("STS_TEST_ACCESS_KEY"); accessKey != "" {
|
||||
secretKey := os.Getenv("STS_TEST_SECRET_KEY")
|
||||
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
|
||||
signer := v4.NewSigner(creds)
|
||||
if _, err := signer.Sign(req, strings.NewReader(body), "iam", "us-east-1", time.Now()); err != nil {
|
||||
return nil, fmt.Errorf("failed to sign IAM request: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
@@ -49,25 +49,30 @@ func TestSTSAssumeRoleValidation(t *testing.T) {
|
||||
t.Fatal("AssumeRole action is not implemented in the running server - please rebuild weed binary with new code and restart the server")
|
||||
}
|
||||
|
||||
t.Run("missing_role_arn", func(t *testing.T) {
|
||||
t.Run("missing_role_arn_defaults_to_caller_identity", func(t *testing.T) {
|
||||
// SeaweedFS intentionally allows AssumeRole without RoleArn to support
|
||||
// S3-compatible clients that omit it. In that case the session is tied
|
||||
// to the caller's own identity (User Context assumption). See
|
||||
// handleAssumeRole in weed/s3api/s3api_sts.go.
|
||||
resp, err := callSTSAPIWithSigV4(t, url.Values{
|
||||
"Action": {"AssumeRole"},
|
||||
"Version": {"2011-06-15"},
|
||||
"RoleSessionName": {"test-session"},
|
||||
// RoleArn is missing
|
||||
// RoleArn is missing on purpose
|
||||
}, "test-access-key", "test-secret-key")
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
|
||||
"Should fail without RoleArn")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
var errResp STSErrorTestResponse
|
||||
err = xml.Unmarshal(body, &errResp)
|
||||
require.NoError(t, err, "Failed to parse error response: %s", string(body))
|
||||
assert.Equal(t, "MissingParameter", errResp.Error.Code)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Should succeed without RoleArn (user-context assumption): %s", string(body))
|
||||
|
||||
var assumeResp AssumeRoleTestResponse
|
||||
require.NoError(t, xml.Unmarshal(body, &assumeResp),
|
||||
"Failed to parse response: %s", string(body))
|
||||
assert.NotEmpty(t, assumeResp.Result.Credentials.AccessKeyId,
|
||||
"AccessKeyId should be issued for user-context assumption")
|
||||
})
|
||||
|
||||
t.Run("missing_role_session_name", func(t *testing.T) {
|
||||
@@ -337,7 +342,10 @@ func callSTSAPIWithSigV4(t *testing.T, params url.Values, accessKey, secretKey s
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Host", req.URL.Host)
|
||||
// Do NOT set req.Header["Host"] — aws-sdk-go v1 v4.Signer reads the host
|
||||
// from req.URL.Host/req.Host, and a manual Host header makes the signer
|
||||
// emit `host;host` in SignedHeaders, producing a different signature than
|
||||
// the server calculates from canonical headers.
|
||||
|
||||
// Sign request with AWS Signature V4 using official SDK
|
||||
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
|
||||
|
||||
@@ -323,8 +323,11 @@ spark = (SparkSession.builder
|
||||
func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Helper()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
masterGrpcPort := env.masterPort + 10000
|
||||
cmd := exec.Command("weed", "shell",
|
||||
cmd := exec.CommandContext(ctx, "weed", "shell",
|
||||
fmt.Sprintf("-master=localhost:%d.%d", env.masterPort, masterGrpcPort),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("s3tables.bucket -create -name %s -account 000000000000\nexit\n", bucketName))
|
||||
|
||||
@@ -118,3 +118,63 @@ func MustFreeMiniPort(t *testing.T, name string) int {
|
||||
t.Helper()
|
||||
return MustFreeMiniPorts(t, []string{name})[0]
|
||||
}
|
||||
|
||||
// AllocatePortSet atomically allocates miniCount master-style port pairs (each
|
||||
// with port and port+GrpcPortOffset reserved) plus regularCount additional
|
||||
// distinct ports. All listeners are held open until the entire batch is
|
||||
// allocated, so a mini gRPC port cannot be recycled as a regular port mid-batch.
|
||||
func AllocatePortSet(miniCount, regularCount int) (mini []int, regular []int, err error) {
|
||||
const (
|
||||
minPort = 10000
|
||||
maxPort = 55000
|
||||
)
|
||||
reserved := make(map[int]bool)
|
||||
mini = make([]int, 0, miniCount)
|
||||
var listeners []net.Listener
|
||||
defer func() {
|
||||
for _, l := range listeners {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for idx := 0; idx < miniCount; idx++ {
|
||||
found := false
|
||||
for i := 0; i < 1000; i++ {
|
||||
port := minPort + rand.Intn(maxPort-minPort)
|
||||
grpcPort := port + GrpcPortOffset
|
||||
if reserved[port] || reserved[grpcPort] {
|
||||
continue
|
||||
}
|
||||
l1, lErr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if lErr != nil {
|
||||
continue
|
||||
}
|
||||
l2, lErr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", grpcPort))
|
||||
if lErr != nil {
|
||||
l1.Close()
|
||||
continue
|
||||
}
|
||||
listeners = append(listeners, l1, l2)
|
||||
reserved[port] = true
|
||||
reserved[grpcPort] = true
|
||||
mini = append(mini, port)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if !found {
|
||||
return nil, nil, fmt.Errorf("failed to allocate mini port %d of %d", idx+1, miniCount)
|
||||
}
|
||||
}
|
||||
|
||||
regular = make([]int, 0, regularCount)
|
||||
for i := 0; i < regularCount; i++ {
|
||||
l, lErr := net.Listen("tcp", "127.0.0.1:0")
|
||||
if lErr != nil {
|
||||
return nil, nil, lErr
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
regular = append(regular, l.Addr().(*net.TCPAddr).Port)
|
||||
}
|
||||
|
||||
return mini, regular, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package testutil
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAllocatePortSetNoGrpcCollision(t *testing.T) {
|
||||
// Run a few iterations to catch the OS-recycles-just-closed-port race
|
||||
// that previously hit regular ports when the mini gRPC offset was freed
|
||||
// between AllocateMiniPorts and AllocatePorts calls.
|
||||
for iter := 0; iter < 20; iter++ {
|
||||
mini, regular, err := AllocatePortSet(1, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("iter %d: AllocatePortSet: %v", iter, err)
|
||||
}
|
||||
if len(mini) != 1 || len(regular) != 3 {
|
||||
t.Fatalf("iter %d: unexpected counts mini=%d regular=%d", iter, len(mini), len(regular))
|
||||
}
|
||||
reserved := map[int]bool{
|
||||
mini[0]: true,
|
||||
mini[0] + GrpcPortOffset: true,
|
||||
}
|
||||
for _, p := range regular {
|
||||
if reserved[p] {
|
||||
t.Fatalf("iter %d: regular port %d collides with mini pair %d/%d",
|
||||
iter, p, mini[0], mini[0]+GrpcPortOffset)
|
||||
}
|
||||
reserved[p] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Package tls_rotation exercises HTTPS certificate rotation end-to-end:
|
||||
// start a real `weed master` with an HTTPS listener, capture the leaf
|
||||
// served at handshake time, rewrite the cert/key files on disk, and
|
||||
// assert that a subsequent handshake sees the new leaf — all without
|
||||
// stopping the master process. The test shortens the reloader's refresh
|
||||
// window to ~half a second via WEED_TLS_CERT_REFRESH_INTERVAL so it
|
||||
// completes in seconds rather than hours.
|
||||
package tls_rotation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestMasterHTTPSCertRotation boots `weed master` with HTTPS, confirms
|
||||
// the initial leaf is served, rotates the cert/key pair on disk, and
|
||||
// asserts the rotated leaf is served on subsequent TLS handshakes.
|
||||
func TestMasterHTTPSCertRotation(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping HTTPS rotation integration test in -short mode")
|
||||
}
|
||||
|
||||
weedBin := findWeedBinary(t)
|
||||
|
||||
dir := t.TempDir()
|
||||
tlsDir := filepath.Join(dir, "tls")
|
||||
if err := os.MkdirAll(tlsDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir tls: %v", err)
|
||||
}
|
||||
certPath := filepath.Join(tlsDir, "server.crt")
|
||||
keyPath := filepath.Join(tlsDir, "server.key")
|
||||
|
||||
ca, caKey := generateCA(t)
|
||||
leafSerial1 := big.NewInt(10001)
|
||||
leafSerial2 := big.NewInt(10002)
|
||||
|
||||
// Initial leaf on disk.
|
||||
writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial1)
|
||||
|
||||
masterDir := filepath.Join(dir, "master")
|
||||
if err := os.MkdirAll(masterDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir master: %v", err)
|
||||
}
|
||||
// Empty security.toml so the master doesn't pick up a user's
|
||||
// ~/.seaweedfs/security.toml during the test.
|
||||
if err := os.WriteFile(filepath.Join(masterDir, "security.toml"), []byte("# test\n"), 0o644); err != nil {
|
||||
t.Fatalf("write security.toml: %v", err)
|
||||
}
|
||||
|
||||
// Master auto-derives gRPC port as port+10000 when -port.grpc is
|
||||
// unset, so both must fit in uint16. Pin both explicitly.
|
||||
port, grpcPort := getFreeTCPPort(t), getFreeTCPPort(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, weedBin, "master",
|
||||
"-ip", "127.0.0.1",
|
||||
"-port", strconv.Itoa(port),
|
||||
"-port.grpc", strconv.Itoa(grpcPort),
|
||||
"-mdir", masterDir,
|
||||
)
|
||||
cmd.Dir = masterDir
|
||||
cmd.Env = append(os.Environ(),
|
||||
// Isolate HOME so the subprocess cannot pick up a developer's
|
||||
// ~/.seaweedfs/security.toml. Viper's AddConfigPath uses the
|
||||
// literal string "$HOME/.seaweedfs" without env expansion today,
|
||||
// so this is only belt-and-braces — but it insures us against a
|
||||
// future viper upgrade that does expand env vars.
|
||||
"HOME="+dir,
|
||||
"WEED_HTTPS_MASTER_CERT="+certPath,
|
||||
"WEED_HTTPS_MASTER_KEY="+keyPath,
|
||||
// Short refresh window so rotation completes in seconds.
|
||||
"WEED_TLS_CERT_REFRESH_INTERVAL=500ms",
|
||||
)
|
||||
logPath := filepath.Join(masterDir, "master.log")
|
||||
logOut, err := os.Create(logPath)
|
||||
if err != nil {
|
||||
t.Fatalf("create master log: %v", err)
|
||||
}
|
||||
cmd.Stdout = logOut
|
||||
cmd.Stderr = logOut
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start master: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Signal(syscall.SIGTERM)
|
||||
done := make(chan struct{})
|
||||
go func() { _ = cmd.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
_ = cmd.Process.Kill()
|
||||
<-done
|
||||
}
|
||||
}
|
||||
_ = logOut.Close()
|
||||
if t.Failed() {
|
||||
if b, readErr := os.ReadFile(logPath); readErr == nil {
|
||||
t.Logf("master.log:\n%s", string(b))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
caPool := x509.NewCertPool()
|
||||
caPool.AddCert(ca)
|
||||
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", port)
|
||||
|
||||
// 1. Wait for the initial leaf to appear. Master takes a few seconds
|
||||
// to open its HTTPS listener.
|
||||
waitForCert(t, addr, caPool, leafSerial1, 30*time.Second, "initial cert")
|
||||
|
||||
// Sanity: same handshake twice still observes the initial leaf.
|
||||
got, err := peekServerCert(addr, caPool)
|
||||
if err != nil || got == nil || got.SerialNumber.Cmp(leafSerial1) != 0 {
|
||||
t.Fatalf("second probe before rotation did not return initial leaf: cert=%v err=%v", got, err)
|
||||
}
|
||||
|
||||
// 2. Rotate on disk. pemfile watches mtime, so each file's write is
|
||||
// an atomic rename (tempfile in the same directory).
|
||||
writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial2)
|
||||
|
||||
// 3. Wait for new leaf to take over. With a 500ms refresh and no
|
||||
// connection pooling (tls.Dial opens a fresh conn each time), this
|
||||
// should take a couple of seconds.
|
||||
waitForCert(t, addr, caPool, leafSerial2, 15*time.Second, "rotated cert")
|
||||
}
|
||||
|
||||
// waitForCert polls until a TLS handshake against addr yields a peer
|
||||
// cert with the expected serial, or fails the test at the deadline.
|
||||
// The last handshake error is surfaced in the fatal message so that a
|
||||
// CI flake makes the root cause obvious (master didn't come up, TLS
|
||||
// handshake rejected, CA pool mismatch, etc.).
|
||||
func waitForCert(t *testing.T, addr string, caPool *x509.CertPool, wantSerial *big.Int, within time.Duration, label string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(within)
|
||||
var lastErr error
|
||||
var lastSerial *big.Int
|
||||
for time.Now().Before(deadline) {
|
||||
cert, err := peekServerCert(addr, caPool)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
} else if cert != nil {
|
||||
lastSerial = cert.SerialNumber
|
||||
if cert.SerialNumber.Cmp(wantSerial) == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("timeout waiting for %s (want serial %s, last seen %v, last err %v)", label, wantSerial, lastSerial, lastErr)
|
||||
}
|
||||
|
||||
// peekServerCert opens a one-shot TLS connection and returns the leaf.
|
||||
// Errors (dial failure, handshake rejection, empty peer chain) are
|
||||
// returned rather than swallowed, so the caller can surface them when
|
||||
// the test times out.
|
||||
func peekServerCert(addr string, caPool *x509.CertPool) (*x509.Certificate, error) {
|
||||
d := &net.Dialer{Timeout: 2 * time.Second}
|
||||
conn, err := tls.DialWithDialer(d, "tcp", addr, &tls.Config{
|
||||
RootCAs: caPool,
|
||||
ServerName: "localhost",
|
||||
MinVersion: tls.VersionTLS12,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
state := conn.ConnectionState()
|
||||
if len(state.PeerCertificates) == 0 {
|
||||
return nil, fmt.Errorf("handshake returned empty peer chain")
|
||||
}
|
||||
return state.PeerCertificates[0], nil
|
||||
}
|
||||
|
||||
func getFreeTCPPort(t *testing.T) int {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen ephemeral: %v", err)
|
||||
}
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
_ = ln.Close()
|
||||
return port
|
||||
}
|
||||
|
||||
func findWeedBinary(t *testing.T) string {
|
||||
t.Helper()
|
||||
candidates := []string{
|
||||
"../../weed/weed",
|
||||
"../weed/weed",
|
||||
"./weed",
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if _, err := os.Stat(c); err == nil {
|
||||
abs, absErr := filepath.Abs(c)
|
||||
if absErr == nil {
|
||||
return abs
|
||||
}
|
||||
return c
|
||||
}
|
||||
}
|
||||
if path, err := exec.LookPath("weed"); err == nil {
|
||||
return path
|
||||
}
|
||||
t.Skip("weed binary not found — build with `cd weed && go build` first")
|
||||
return ""
|
||||
}
|
||||
|
||||
// --- cert fixtures -------------------------------------------------------
|
||||
|
||||
// generateCA returns a self-signed CA cert and its private key.
|
||||
func generateCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("gen CA key: %v", err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "tls-rotation-test-CA"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("create CA cert: %v", err)
|
||||
}
|
||||
parsed, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatalf("parse CA cert: %v", err)
|
||||
}
|
||||
return parsed, key
|
||||
}
|
||||
|
||||
// writeLeaf signs a new leaf cert with the given serial and writes it
|
||||
// plus its key to the given paths via atomic rename — the pattern
|
||||
// Kubernetes (cert-manager → Secret volume mount) produces in practice.
|
||||
func writeLeaf(t *testing.T, certPath, keyPath string, ca *x509.Certificate, caKey *ecdsa.PrivateKey, serial *big.Int) {
|
||||
t.Helper()
|
||||
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("gen leaf key: %v", err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{
|
||||
CommonName: "localhost",
|
||||
},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
|
||||
DNSNames: []string{"localhost"},
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, ca, &leafKey.PublicKey, caKey)
|
||||
if err != nil {
|
||||
t.Fatalf("create leaf cert: %v", err)
|
||||
}
|
||||
|
||||
atomicWritePEM(t, certPath, "CERTIFICATE", der)
|
||||
|
||||
keyDER, err := x509.MarshalECPrivateKey(leafKey)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal leaf key: %v", err)
|
||||
}
|
||||
atomicWritePEM(t, keyPath, "EC PRIVATE KEY", keyDER)
|
||||
}
|
||||
|
||||
// atomicWritePEM writes a PEM file via tempfile-in-same-directory plus
|
||||
// rename, matching what kubelet does when it swaps the ..data symlink
|
||||
// for a renewed Secret. Ensures the reader never sees a truncated file.
|
||||
func atomicWritePEM(t *testing.T, path, blockType string, der []byte) {
|
||||
t.Helper()
|
||||
dir := filepath.Dir(path)
|
||||
tmp, err := os.CreateTemp(dir, ".tls-*")
|
||||
if err != nil {
|
||||
t.Fatalf("create tempfile: %v", err)
|
||||
}
|
||||
ok := false
|
||||
defer func() {
|
||||
if !ok {
|
||||
_ = os.Remove(tmp.Name())
|
||||
}
|
||||
}()
|
||||
if err := pem.Encode(tmp, &pem.Block{Type: blockType, Bytes: der}); err != nil {
|
||||
tmp.Close()
|
||||
t.Fatalf("pem encode: %v", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
t.Fatalf("close tempfile: %v", err)
|
||||
}
|
||||
if err := os.Chmod(tmp.Name(), 0o600); err != nil {
|
||||
t.Fatalf("chmod tempfile: %v", err)
|
||||
}
|
||||
if err := os.Rename(tmp.Name(), path); err != nil {
|
||||
t.Fatalf("rename tempfile onto %s: %v", path, err)
|
||||
}
|
||||
ok = true
|
||||
}
|
||||
@@ -54,12 +54,25 @@ type Cluster struct {
|
||||
masterCmd *exec.Cmd
|
||||
volumeCmd *exec.Cmd
|
||||
|
||||
volumeDataDirs []string
|
||||
|
||||
cleanupOnce sync.Once
|
||||
}
|
||||
|
||||
// StartSingleVolumeCluster boots one master and one volume server.
|
||||
func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
return StartSingleVolumeClusterWithDataDirs(t, profile, 1)
|
||||
}
|
||||
|
||||
// StartSingleVolumeClusterWithDataDirs boots one master and one volume server
|
||||
// with dataDirCount separate data directories (passed to -dir as a comma list).
|
||||
// Each directory becomes its own DiskLocation on the volume server, letting
|
||||
// tests exercise multi-disk EC placement paths.
|
||||
func StartSingleVolumeClusterWithDataDirs(t testing.TB, profile matrix.Profile, dataDirCount int) *Cluster {
|
||||
t.Helper()
|
||||
if dataDirCount < 1 {
|
||||
t.Fatalf("dataDirCount must be >= 1, got %d", dataDirCount)
|
||||
}
|
||||
|
||||
weedBinary, err := FindOrBuildWeedBinary()
|
||||
if err != nil {
|
||||
@@ -74,8 +87,19 @@ func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
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} {
|
||||
volumeDataDirs := make([]string, dataDirCount)
|
||||
// Single-dir layout stays at baseDir/volume so existing fixtures
|
||||
// (CorruptDatFile etc.) that hardcode that path keep working. Only
|
||||
// multi-dir clusters get the "volumeN" layout.
|
||||
for i := 0; i < dataDirCount; i++ {
|
||||
if dataDirCount == 1 {
|
||||
volumeDataDirs[i] = filepath.Join(baseDir, "volume")
|
||||
} else {
|
||||
volumeDataDirs[i] = filepath.Join(baseDir, fmt.Sprintf("volume%d", i))
|
||||
}
|
||||
}
|
||||
setupDirs := append([]string{configDir, logsDir, masterDataDir}, volumeDataDirs...)
|
||||
for _, dir := range setupDirs {
|
||||
if mkErr := os.MkdirAll(dir, 0o755); mkErr != nil {
|
||||
t.Fatalf("create %s: %v", dir, mkErr)
|
||||
}
|
||||
@@ -85,17 +109,12 @@ func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
ports, err := testutil.AllocatePorts(3)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
c := &Cluster{
|
||||
testingTB: t,
|
||||
@@ -125,11 +144,12 @@ func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
t.Fatalf("wait for master readiness: %v\nmaster log tail:\n%s", err, masterLog)
|
||||
}
|
||||
|
||||
if err = c.startVolume(volumeDataDir); err != nil {
|
||||
if err = c.startVolume(volumeDataDirs); err != nil {
|
||||
masterLog := c.tailLog("master.log")
|
||||
c.Stop()
|
||||
t.Fatalf("start volume: %v\nmaster log tail:\n%s", err, masterLog)
|
||||
}
|
||||
c.volumeDataDirs = volumeDataDirs
|
||||
if err = c.waitForHTTP(c.VolumeAdminURL() + "/status"); err != nil {
|
||||
volumeLog := c.tailLog("volume.log")
|
||||
c.Stop()
|
||||
@@ -189,12 +209,16 @@ func (c *Cluster) startMaster(dataDir string) error {
|
||||
return c.masterCmd.Start()
|
||||
}
|
||||
|
||||
func (c *Cluster) startVolume(dataDir string) error {
|
||||
func (c *Cluster) startVolume(dataDirs []string) error {
|
||||
logFile, err := os.Create(filepath.Join(c.logsDir, "volume.log"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
maxPerDir := make([]string, len(dataDirs))
|
||||
for i := range dataDirs {
|
||||
maxPerDir[i] = "16"
|
||||
}
|
||||
args := []string{
|
||||
"-config_dir=" + c.configDir,
|
||||
"volume",
|
||||
@@ -202,8 +226,8 @@ func (c *Cluster) startVolume(dataDir string) error {
|
||||
"-port=" + strconv.Itoa(c.volumePort),
|
||||
"-port.grpc=" + strconv.Itoa(c.volumeGrpcPort),
|
||||
"-port.public=" + strconv.Itoa(c.volumePubPort),
|
||||
"-dir=" + dataDir,
|
||||
"-max=16",
|
||||
"-dir=" + strings.Join(dataDirs, ","),
|
||||
"-max=" + strings.Join(maxPerDir, ","),
|
||||
"-master=127.0.0.1:" + strconv.Itoa(c.masterPort),
|
||||
"-readMode=" + c.profile.ReadMode,
|
||||
"-concurrentUploadLimitMB=" + strconv.Itoa(c.profile.ConcurrentUploadLimitMB),
|
||||
@@ -420,3 +444,10 @@ func (c *Cluster) VolumePublicURL() string {
|
||||
func (c *Cluster) BaseDir() string {
|
||||
return c.baseDir
|
||||
}
|
||||
|
||||
// VolumeDataDirs returns the data directories the volume server was started with.
|
||||
// Index 0 corresponds to DiskLocation 0, index 1 to DiskLocation 1, and so on.
|
||||
// Tests can scan these directories to verify where files physically landed.
|
||||
func (c *Cluster) VolumeDataDirs() []string {
|
||||
return append([]string(nil), c.volumeDataDirs...)
|
||||
}
|
||||
@@ -93,22 +93,17 @@ func StartMixedVolumeCluster(t testing.TB, profile matrix.Profile, goCount, rust
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
// 2 ports per server (admin, grpc); add 1 more when public port is split out.
|
||||
portsPerServer := 2
|
||||
if profile.SplitPublicPort {
|
||||
portsPerServer = 3
|
||||
}
|
||||
ports, err := testutil.AllocatePorts(total * portsPerServer)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, total*portsPerServer)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate volume ports: %v", err)
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
isRust := make([]bool, total)
|
||||
for i := goCount; i < total; i++ {
|
||||
|
||||
@@ -75,13 +75,6 @@ func StartMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCount i
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
// Allocate ports for all volume servers (3 ports per server: admin, grpc, public)
|
||||
// If SplitPublicPort is true, we need an additional port per server
|
||||
portsPerServer := 3
|
||||
@@ -89,10 +82,12 @@ func StartMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCount i
|
||||
portsPerServer = 4
|
||||
}
|
||||
totalPorts := serverCount * portsPerServer
|
||||
ports, err := testutil.AllocatePorts(totalPorts)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, totalPorts)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate volume ports: %v", err)
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
c := &MultiVolumeCluster{
|
||||
testingTB: t,
|
||||
|
||||
@@ -86,13 +86,6 @@ func StartRustMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCou
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
// Allocate ports for all volume servers (3 ports per server: admin, grpc, public)
|
||||
// If SplitPublicPort is true, we need an additional port per server
|
||||
portsPerServer := 3
|
||||
@@ -100,10 +93,12 @@ func StartRustMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCou
|
||||
portsPerServer = 4
|
||||
}
|
||||
totalPorts := serverCount * portsPerServer
|
||||
ports, err := testutil.AllocatePorts(totalPorts)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, totalPorts)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate volume ports: %v", err)
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
c := &RustMultiVolumeCluster{
|
||||
testingTB: t,
|
||||
|
||||
@@ -80,17 +80,12 @@ func StartRustVolumeCluster(t testing.TB, profile matrix.Profile) *RustCluster {
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
ports, err := testutil.AllocatePorts(3)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
rc := &RustCluster{
|
||||
testingTB: t,
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package volume_server_grpc_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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"
|
||||
)
|
||||
|
||||
// Sends EC shards with disk_id={1, 2, 0} and verifies each lands on the
|
||||
// requested disk (0 → auto-select → disk 0 for a fresh volume).
|
||||
func TestReceiveFileEcShardHonorsDiskID(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
const dataDirCount = 3
|
||||
clusterHarness := framework.StartSingleVolumeClusterWithDataDirs(t, matrix.P1(), dataDirCount)
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
dataDirs := clusterHarness.VolumeDataDirs()
|
||||
if len(dataDirs) != dataDirCount {
|
||||
t.Fatalf("expected %d data dirs, got %d: %v", dataDirCount, len(dataDirs), dataDirs)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
const volumeID = uint32(9184)
|
||||
const collection = "ec-disk-placement"
|
||||
|
||||
// DiskId=0 triggers auto-select. Since this test never calls
|
||||
// VolumeEcShardsMount, loc.FindEcVolume returns false on every disk, so
|
||||
// the "already holds shards" preference is skipped and auto-select falls
|
||||
// through to the first HDD (dir 0). If shards get mounted between uploads
|
||||
// in a future revision, the expected dir for DiskId=0 becomes the first
|
||||
// disk that already holds a shard.
|
||||
shards := []struct {
|
||||
shardID uint32
|
||||
requestedDisk uint32
|
||||
expectedDirIdx int
|
||||
}{
|
||||
{shardID: 0, requestedDisk: 1, expectedDirIdx: 1},
|
||||
{shardID: 5, requestedDisk: 2, expectedDirIdx: 2},
|
||||
{shardID: 13, requestedDisk: 0, expectedDirIdx: 0},
|
||||
}
|
||||
shardExt := func(id uint32) string { return fmt.Sprintf(".ec%02d", id) }
|
||||
|
||||
for _, s := range shards {
|
||||
payload := []byte(fmt.Sprintf("ec-shard-payload-%02d", s.shardID))
|
||||
stream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: shardExt(s.shardID),
|
||||
Collection: collection,
|
||||
IsEcVolume: true,
|
||||
ShardId: s.shardID,
|
||||
FileSize: uint64(len(payload)),
|
||||
DiskId: s.requestedDisk,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payload},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send content for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
resp, err := stream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile close for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
if resp.GetError() != "" {
|
||||
t.Fatalf("ReceiveFile shard %d error response: %s", s.shardID, resp.GetError())
|
||||
}
|
||||
if resp.GetBytesWritten() != uint64(len(payload)) {
|
||||
t.Fatalf("ReceiveFile shard %d bytes_written mismatch: got %d want %d",
|
||||
s.shardID, resp.GetBytesWritten(), len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
// Scan every data dir and record which shard files live where.
|
||||
perDirShards := make(map[int][]uint32)
|
||||
for dirIdx, dir := range dataDirs {
|
||||
for _, s := range shards {
|
||||
shardPath := filepath.Join(dir, fmt.Sprintf("%s_%d%s", collection, volumeID, shardExt(s.shardID)))
|
||||
if _, err := os.Stat(shardPath); err == nil {
|
||||
perDirShards[dirIdx] = append(perDirShards[dirIdx], s.shardID)
|
||||
} else if !os.IsNotExist(err) {
|
||||
t.Fatalf("unexpected stat error for %s: %v", shardPath, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, s := range shards {
|
||||
found := false
|
||||
for _, got := range perDirShards[s.expectedDirIdx] {
|
||||
if got == s.shardID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("shard %d (requestedDisk=%d) expected on dir[%d], full layout: %v",
|
||||
s.shardID, s.requestedDisk, s.expectedDirIdx, perDirShards)
|
||||
}
|
||||
for dirIdx, ids := range perDirShards {
|
||||
if dirIdx == s.expectedDirIdx {
|
||||
continue
|
||||
}
|
||||
for _, id := range ids {
|
||||
if id == s.shardID {
|
||||
t.Fatalf("shard %d leaked onto dir[%d]: full layout: %v", s.shardID, dirIdx, perDirShards)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("disk_id honored: shard placement = %v", perDirShards)
|
||||
}
|
||||
|
||||
func TestReceiveFileEcShardRejectsInvalidDiskID(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
const dataDirCount = 2
|
||||
clusterHarness := framework.StartSingleVolumeClusterWithDataDirs(t, matrix.P1(), dataDirCount)
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
const volumeID = uint32(91840)
|
||||
const collection = "ec-invalid-disk"
|
||||
payload := []byte("invalid-disk-id-payload")
|
||||
|
||||
stream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create: %v", err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".ec00",
|
||||
Collection: collection,
|
||||
IsEcVolume: true,
|
||||
ShardId: 0,
|
||||
FileSize: uint64(len(payload)),
|
||||
DiskId: 99,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info: %v", err)
|
||||
}
|
||||
resp, err := stream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile close: %v", err)
|
||||
}
|
||||
if resp.GetError() == "" {
|
||||
t.Fatalf("expected invalid disk_id rejection, got success response: %+v", resp)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package volume_server_grpc_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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 TestReceiveFileRejectsOverwriteOfMountedEcShard(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
const volumeID = uint32(91841)
|
||||
framework.AllocateVolume(t, grpcClient, volumeID, "")
|
||||
|
||||
httpClient := framework.NewHTTPClient()
|
||||
fid := framework.NewFileID(volumeID, 918401, 0x9184CAFE)
|
||||
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid,
|
||||
[]byte("ec-receive-overwrite-content-for-issue-9184-repro"))
|
||||
_ = 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()
|
||||
|
||||
if _, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
|
||||
VolumeId: volumeID,
|
||||
Collection: "",
|
||||
}); err != nil {
|
||||
t.Fatalf("VolumeEcShardsGenerate: %v", err)
|
||||
}
|
||||
|
||||
if _, err := grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
|
||||
VolumeId: volumeID,
|
||||
Collection: "",
|
||||
ShardIds: []uint32{0},
|
||||
}); err != nil {
|
||||
t.Fatalf("VolumeEcShardsMount: %v", err)
|
||||
}
|
||||
|
||||
dataDir := filepath.Join(clusterHarness.BaseDir(), "volume")
|
||||
shardPath := filepath.Join(dataDir, fmt.Sprintf("%d.ec00", volumeID))
|
||||
origInfo, err := os.Stat(shardPath)
|
||||
if err != nil {
|
||||
t.Fatalf("stat mounted shard %s: %v", shardPath, err)
|
||||
}
|
||||
origSize := origInfo.Size()
|
||||
if origSize == 0 {
|
||||
t.Fatalf("mounted shard %s unexpectedly empty", shardPath)
|
||||
}
|
||||
|
||||
readStream, err := grpcClient.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
|
||||
VolumeId: volumeID,
|
||||
ShardId: 0,
|
||||
Offset: 0,
|
||||
Size: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeEcShardRead (pre): %v", err)
|
||||
}
|
||||
if _, err := readStream.Recv(); err != nil {
|
||||
t.Fatalf("VolumeEcShardRead Recv (pre): %v", err)
|
||||
}
|
||||
|
||||
overwritePayload := []byte("bug-9184-overwrite")
|
||||
receiveStream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create: %v", err)
|
||||
}
|
||||
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".ec00",
|
||||
Collection: "",
|
||||
IsEcVolume: true,
|
||||
ShardId: 0,
|
||||
FileSize: uint64(len(overwritePayload)),
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info: %v", err)
|
||||
}
|
||||
resp, err := receiveStream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Logf("ReceiveFile rejected at stream level: %v", err)
|
||||
} else {
|
||||
if resp.GetError() == "" {
|
||||
t.Fatalf("expected ReceiveFile to reject overwrite of mounted shard, got success: %+v", resp)
|
||||
}
|
||||
if !strings.Contains(resp.GetError(), "mounted") {
|
||||
t.Fatalf("expected error to mention mounted; got: %s", resp.GetError())
|
||||
}
|
||||
}
|
||||
|
||||
afterInfo, err := os.Stat(shardPath)
|
||||
if err != nil {
|
||||
t.Fatalf("stat shard after rejected overwrite: %v", err)
|
||||
}
|
||||
if afterInfo.Size() != origSize {
|
||||
t.Fatalf("shard %s was modified despite rejection: size was %d, now %d",
|
||||
shardPath, origSize, afterInfo.Size())
|
||||
}
|
||||
|
||||
postStream, err := grpcClient.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
|
||||
VolumeId: volumeID,
|
||||
ShardId: 0,
|
||||
Offset: 0,
|
||||
Size: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeEcShardRead (post): %v", err)
|
||||
}
|
||||
if _, err := postStream.Recv(); err != nil {
|
||||
t.Fatalf("VolumeEcShardRead Recv (post): %v", err)
|
||||
}
|
||||
|
||||
t.Logf("ReceiveFile correctly refused overwrite; mounted shard intact at %d bytes", afterInfo.Size())
|
||||
}
|
||||
|
||||
func TestReceiveFileAllowsEcShardWhenNoMount(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
clusterHarness := framework.StartVolumeCluster(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(91843)
|
||||
const collection = "ec-receive-no-mount"
|
||||
payload := []byte("ok-to-receive-not-mounted")
|
||||
|
||||
stream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create: %v", err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".ec00",
|
||||
Collection: collection,
|
||||
IsEcVolume: true,
|
||||
ShardId: 0,
|
||||
FileSize: uint64(len(payload)),
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info: %v", err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payload},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send content: %v", err)
|
||||
}
|
||||
resp, err := stream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile close: %v", err)
|
||||
}
|
||||
if resp.GetError() != "" {
|
||||
t.Fatalf("expected success on unmounted volume, got error: %s", resp.GetError())
|
||||
}
|
||||
if resp.GetBytesWritten() != uint64(len(payload)) {
|
||||
t.Fatalf("bytes_written mismatch: got %d want %d", resp.GetBytesWritten(), len(payload))
|
||||
}
|
||||
}
|
||||
@@ -1061,7 +1061,7 @@ func s3TablesErrorStatus(err error) int {
|
||||
return http.StatusNotFound
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
return http.StatusForbidden
|
||||
case s3tables.ErrCodeBucketAlreadyExists, s3tables.ErrCodeNamespaceAlreadyExists, s3tables.ErrCodeTableAlreadyExists, s3tables.ErrCodeConflict:
|
||||
case s3tables.ErrCodeBucketAlreadyExists, s3tables.ErrCodeNamespaceAlreadyExists, s3tables.ErrCodeTableAlreadyExists, s3tables.ErrCodeBucketNotEmpty, s3tables.ErrCodeNamespaceNotEmpty, s3tables.ErrCodeConflict:
|
||||
return http.StatusConflict
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,21 +247,29 @@ func (s *AdminServer) CreateAccessKey(username string, req *CreateAccessKeyReque
|
||||
req = &CreateAccessKeyRequest{}
|
||||
}
|
||||
|
||||
// Validate provided keys
|
||||
if req.AccessKey != "" && (len(req.AccessKey) < 4 || len(req.AccessKey) > 128) {
|
||||
return nil, fmt.Errorf("access key must be between 4 and 128 characters: %w", ErrInvalidInput)
|
||||
// Validate provided keys (shared with the IAM API and embedded IAM paths).
|
||||
if req.AccessKey != "" {
|
||||
if err := iam.ValidateCallerSuppliedAccessKeyId(req.AccessKey); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", err.Error(), ErrInvalidInput)
|
||||
}
|
||||
}
|
||||
if req.SecretKey != "" && (len(req.SecretKey) < 8 || len(req.SecretKey) > 128) {
|
||||
return nil, fmt.Errorf("secret key must be between 8 and 128 characters: %w", ErrInvalidInput)
|
||||
if req.SecretKey != "" {
|
||||
if err := iam.ValidateCallerSuppliedSecretAccessKey(req.SecretKey); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", err.Error(), ErrInvalidInput)
|
||||
}
|
||||
}
|
||||
// Enforce the both-or-none rule to match the IAM API and embedded IAM
|
||||
// paths — silently generating the missing half lets a caller end up
|
||||
// with a credential they did not fully choose.
|
||||
if (req.AccessKey != "") != (req.SecretKey != "") {
|
||||
return nil, fmt.Errorf("access key and secret key must be supplied together: %w", ErrInvalidInput)
|
||||
}
|
||||
|
||||
// Use provided keys or generate new ones
|
||||
accessKey := req.AccessKey
|
||||
secretKey := req.SecretKey
|
||||
if accessKey == "" {
|
||||
accessKey = generateAccessKey()
|
||||
}
|
||||
secretKey := req.SecretKey
|
||||
if secretKey == "" {
|
||||
secretKey = generateSecretKey()
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 6.6 KiB |
@@ -23,6 +23,15 @@ function getCSRFToken() {
|
||||
return tokenMeta.getAttribute('content') || '';
|
||||
}
|
||||
|
||||
function s3tWriteHeaders(extra) {
|
||||
const headers = Object.assign({}, extra || {});
|
||||
const csrfToken = getCSRFToken();
|
||||
if (csrfToken) {
|
||||
headers['X-CSRF-Token'] = csrfToken;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize S3 Tables Buckets Page
|
||||
*/
|
||||
@@ -104,7 +113,7 @@ function initS3TablesBuckets() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/buckets'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -133,7 +142,7 @@ function initS3TablesBuckets() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/bucket-policy'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ bucket_arn: bucketArn, policy: policy })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -239,7 +248,7 @@ function initS3TablesTables() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tables'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -267,7 +276,7 @@ function initS3TablesTables() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/table-policy'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ bucket_arn: dataBucketArn, namespace: dataNamespace, name: document.getElementById('s3tablesTablePolicyName').value, policy: policy })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -306,10 +315,6 @@ function initIcebergNamespaces() {
|
||||
if (!container) return;
|
||||
const bucketArn = container.dataset.bucketArn || '';
|
||||
const catalogName = container.dataset.catalogName || '';
|
||||
const csrfTokenInput = document.getElementById('icebergNamespaceCsrfToken');
|
||||
if (csrfTokenInput) {
|
||||
csrfTokenInput.value = getCSRFToken();
|
||||
}
|
||||
|
||||
const namespaceInput = document.getElementById('icebergNamespaceName');
|
||||
if (namespaceInput) {
|
||||
@@ -330,14 +335,9 @@ function initIcebergNamespaces() {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const csrfToken = csrfTokenInput ? csrfTokenInput.value : getCSRFToken();
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (csrfToken) {
|
||||
headers['X-CSRF-Token'] = csrfToken;
|
||||
}
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/namespaces'), {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ bucket_arn: bucketArn, name: name })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -433,10 +433,6 @@ function initIcebergTables() {
|
||||
if (!container) return;
|
||||
const bucketArn = container.dataset.bucketArn || '';
|
||||
const namespace = container.dataset.namespace || '';
|
||||
const csrfTokenInput = document.getElementById('icebergTableCsrfToken');
|
||||
if (csrfTokenInput) {
|
||||
csrfTokenInput.value = getCSRFToken();
|
||||
}
|
||||
|
||||
initIcebergDeleteModal();
|
||||
|
||||
@@ -476,14 +472,9 @@ function initIcebergTables() {
|
||||
payload.metadata = metadata;
|
||||
}
|
||||
try {
|
||||
const csrfToken = csrfTokenInput ? csrfTokenInput.value : getCSRFToken();
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (csrfToken) {
|
||||
headers['X-CSRF-Token'] = csrfToken;
|
||||
}
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tables'), {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -530,7 +521,7 @@ async function deleteS3TablesBucket() {
|
||||
const bucketArn = document.getElementById('deleteS3TablesBucketModal').dataset.bucketArn;
|
||||
if (!bucketArn) return;
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/buckets?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/buckets?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete bucket');
|
||||
@@ -561,7 +552,7 @@ async function deleteS3TablesBucketPolicy() {
|
||||
const bucketArn = document.getElementById('s3tablesBucketPolicyArn').value;
|
||||
if (!bucketArn) return;
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/bucket-policy?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/bucket-policy?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete policy');
|
||||
@@ -590,7 +581,7 @@ async function deleteS3TablesTable() {
|
||||
query.set('version', versionToken);
|
||||
}
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete table');
|
||||
@@ -621,12 +612,7 @@ async function deleteIcebergTable() {
|
||||
query.set('version', versionToken);
|
||||
}
|
||||
try {
|
||||
const csrfToken = getCSRFToken();
|
||||
const requestOptions = { method: 'DELETE' };
|
||||
if (csrfToken) {
|
||||
requestOptions.headers = { 'X-CSRF-Token': csrfToken };
|
||||
}
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), requestOptions);
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to drop table');
|
||||
@@ -665,7 +651,7 @@ async function deleteS3TablesTablePolicy() {
|
||||
const dataNamespace = dataContainer.dataset.namespace || '';
|
||||
const query = new URLSearchParams({ bucket: dataBucketArn, namespace: dataNamespace, name: document.getElementById('s3tablesTablePolicyName').value });
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/table-policy?${query.toString()}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/table-policy?${query.toString()}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete policy');
|
||||
@@ -872,7 +858,7 @@ async function updateS3TablesTags(resourceArn, tags) {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tags'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ resource_arn: resourceArn, tags: tags })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -899,7 +885,7 @@ async function deleteS3TablesTags() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tags'), {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ resource_arn: resourceArn, tag_keys: tagKeys })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
@@ -261,11 +261,11 @@ func TestTargetSelectionScenarios(t *testing.T) {
|
||||
expectedTargets: 4, // All 4 disks available
|
||||
},
|
||||
{
|
||||
name: "Vacuum task - avoid conflicting disks",
|
||||
name: "Vacuum task - cross-type tasks do not block per disk",
|
||||
topology: createTopologyWithConflicts(),
|
||||
taskType: TaskTypeVacuum,
|
||||
excludeNode: "",
|
||||
expectedTargets: 1, // Only 1 disk without conflicts (conflicts exclude more disks)
|
||||
expectedTargets: 4, // All 4 disks available; per-volume safety is enforced by HasAnyTask
|
||||
},
|
||||
}
|
||||
|
||||
@@ -279,8 +279,6 @@ func TestTargetSelectionScenarios(t *testing.T) {
|
||||
for _, disk := range availableDisks {
|
||||
assert.NotEqual(t, tt.excludeNode, disk.NodeID,
|
||||
"Available disk should not be on excluded node")
|
||||
|
||||
assert.Less(t, disk.LoadCount, 2, "Disk load should be less than 2")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -353,12 +351,10 @@ func TestDiskLoadCalculation(t *testing.T) {
|
||||
assert.Equal(t, 1, targetDisk.LoadCount)
|
||||
}
|
||||
|
||||
// TestTaskConflictDetection tests task conflict detection
|
||||
func TestTaskConflictDetection(t *testing.T) {
|
||||
func TestCrossTypeTasksDoNotBlockPerDisk(t *testing.T) {
|
||||
topology := NewActiveTopology(10)
|
||||
topology.UpdateTopology(createSampleTopology())
|
||||
|
||||
// Add a balance task
|
||||
err := topology.AddPendingTask(TaskSpec{
|
||||
TaskID: "balance1",
|
||||
TaskType: TaskTypeBalance,
|
||||
@@ -371,13 +367,10 @@ func TestTaskConflictDetection(t *testing.T) {
|
||||
{ServerID: "10.0.0.2:8080", DiskID: 1},
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err, "Should add balance task successfully")
|
||||
topology.AssignTask("balance1")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, topology.AssignTask("balance1"))
|
||||
|
||||
// Try to get available disks for vacuum (conflicts with balance)
|
||||
availableDisks := topology.GetAvailableDisks(TaskTypeVacuum, "")
|
||||
|
||||
// Source disk should not be available due to conflict
|
||||
sourceDiskAvailable := false
|
||||
for _, disk := range availableDisks {
|
||||
if disk.NodeID == "10.0.0.1:8080" && disk.DiskID == 0 {
|
||||
@@ -385,7 +378,34 @@ func TestTaskConflictDetection(t *testing.T) {
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.False(t, sourceDiskAvailable, "Source disk should not be available due to task conflict")
|
||||
assert.True(t, sourceDiskAvailable,
|
||||
"Source disk should remain available for an unrelated task type")
|
||||
}
|
||||
|
||||
// Regression for #9147: a 4-disk cluster with one in-flight balance task must
|
||||
// still expose all 4 disks to EC placement so MinTotalDisks can be satisfied.
|
||||
func TestECPlanningNotBlockedByUnrelatedBalance(t *testing.T) {
|
||||
topology := NewActiveTopology(10)
|
||||
topology.UpdateTopology(createSampleTopology()) // 2 nodes x 2 disks
|
||||
|
||||
err := topology.AddPendingTask(TaskSpec{
|
||||
TaskID: "balance1",
|
||||
TaskType: TaskTypeBalance,
|
||||
VolumeID: 42,
|
||||
VolumeSize: 1024 * 1024 * 1024,
|
||||
Sources: []TaskSourceSpec{
|
||||
{ServerID: "10.0.0.1:8080", DiskID: 0},
|
||||
},
|
||||
Destinations: []TaskDestinationSpec{
|
||||
{ServerID: "10.0.0.2:8080", DiskID: 0},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, topology.AssignTask("balance1"))
|
||||
|
||||
ecCandidates := topology.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 0)
|
||||
assert.Equal(t, 4, len(ecCandidates),
|
||||
"EC must still see all 4 disks even with an unrelated in-flight balance")
|
||||
}
|
||||
|
||||
// TestPublicInterfaces tests the public interface methods
|
||||
|
||||
@@ -236,21 +236,13 @@ func (at *ActiveTopology) getPlanningCapacityUnsafe(disk *activeDisk) StorageSlo
|
||||
}
|
||||
}
|
||||
|
||||
// isDiskAvailableForPlanning checks if disk can accept new tasks considering pending load
|
||||
// isDiskAvailableForPlanning checks if disk can accept new tasks considering
|
||||
// pending load. See isDiskAvailable for the cross-type policy.
|
||||
func (at *ActiveTopology) isDiskAvailableForPlanning(disk *activeDisk, taskType TaskType) bool {
|
||||
// Check total load including pending tasks
|
||||
totalLoad := len(disk.pendingTasks) + len(disk.assignedTasks)
|
||||
if MaxTotalTaskLoadPerDisk > 0 && totalLoad >= MaxTotalTaskLoadPerDisk {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for conflicting task types in active tasks only
|
||||
for _, task := range disk.assignedTasks {
|
||||
if at.areTaskTypesConflicting(task.TaskType, taskType) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -64,44 +64,17 @@ func (at *ActiveTopology) assignTaskToDisk(task *taskState) {
|
||||
}
|
||||
}
|
||||
|
||||
// isDiskAvailable checks if a disk can accept new tasks
|
||||
// isDiskAvailable checks if a disk can accept new tasks. Per-volume safety is
|
||||
// enforced by HasAnyTask at detection time, so cross-type tasks on the same
|
||||
// disk are intentionally not considered conflicting (see #9147).
|
||||
func (at *ActiveTopology) isDiskAvailable(disk *activeDisk, taskType TaskType) bool {
|
||||
// Check if disk has too many pending and active tasks
|
||||
activeLoad := len(disk.pendingTasks) + len(disk.assignedTasks)
|
||||
if MaxConcurrentTasksPerDisk > 0 && activeLoad >= MaxConcurrentTasksPerDisk {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for conflicting task types
|
||||
for _, task := range disk.assignedTasks {
|
||||
if at.areTaskTypesConflicting(task.TaskType, taskType) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// areTaskTypesConflicting checks if two task types conflict
|
||||
func (at *ActiveTopology) areTaskTypesConflicting(existing, new TaskType) bool {
|
||||
// Examples of conflicting task types
|
||||
conflictMap := map[TaskType][]TaskType{
|
||||
TaskTypeVacuum: {TaskTypeBalance, TaskTypeErasureCoding},
|
||||
TaskTypeBalance: {TaskTypeVacuum, TaskTypeErasureCoding},
|
||||
TaskTypeErasureCoding: {TaskTypeVacuum, TaskTypeBalance},
|
||||
}
|
||||
|
||||
if conflicts, exists := conflictMap[existing]; exists {
|
||||
for _, conflictType := range conflicts {
|
||||
if conflictType == new {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// cleanupRecentTasks removes old recent tasks
|
||||
func (at *ActiveTopology) cleanupRecentTasks() {
|
||||
cutoff := time.Now().Add(-time.Duration(at.recentTaskWindowSeconds) * time.Second)
|
||||
|
||||
@@ -231,7 +231,6 @@ templ Groups(data dash.GroupsPageData) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/iam-utils.js"></script>
|
||||
<script>
|
||||
// Groups page JavaScript
|
||||
let currentGroupName = '';
|
||||
@@ -243,7 +242,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/api/groups', {
|
||||
const response = await fetch(basePath('/api/groups'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: name })
|
||||
@@ -269,7 +268,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
|
||||
async function refreshGroupDetails(requestedName) {
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(requestedName));
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(requestedName)));
|
||||
if (!response.ok) throw new Error('Failed to fetch group');
|
||||
if (requestedName !== currentGroupName) return; // stale response
|
||||
const group = await response.json();
|
||||
@@ -339,7 +338,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
const username = document.getElementById('addMemberSelect').value;
|
||||
if (!username) return;
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members', {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: username })
|
||||
@@ -358,7 +357,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
|
||||
async function removeMember(username) {
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username), {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username)), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -377,7 +376,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
const policyName = document.getElementById('attachPolicySelect').value;
|
||||
if (!policyName) return;
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies', {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ policy_name: policyName })
|
||||
@@ -396,7 +395,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
|
||||
async function detachPolicy(policyName) {
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName), {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName)), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -414,7 +413,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
async function toggleGroupStatus() {
|
||||
const enabled = document.getElementById('groupEnabledSwitch').checked;
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/status', {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/status'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled: enabled })
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalGroups))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 38, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 38, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.ActiveGroups))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 57, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 57, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -82,7 +82,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 96, Col: 63}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 96, Col: 63}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -95,7 +95,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", group.MemberCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 99, Col: 109}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 99, Col: 109}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -108,7 +108,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", group.PolicyCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 102, Col: 114}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 102, Col: 114}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -136,7 +136,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 113, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 113, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -149,7 +149,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs("View group " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 115, Col: 90}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 115, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -162,7 +162,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs("View " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 116, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 116, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -175,7 +175,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 120, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 120, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -188,7 +188,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs("Delete group " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 122, Col: 92}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 122, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -201,7 +201,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs("Delete " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 123, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 123, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -229,7 +229,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 189, Col: 67}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 189, Col: 67}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -242,7 +242,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 189, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 189, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -265,7 +265,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(policy)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 206, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 206, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -278,7 +278,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(policy)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 206, Col: 78}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 206, Col: 78}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -289,7 +289,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"attachPolicyToGroup()\"><i class=\"fas fa-plus\"></i> Attach</button></div></div><div id=\"policiesList\"></div></div><!-- Settings Tab --><div class=\"tab-pane fade\" id=\"settingsPane\" role=\"tabpanel\"><div class=\"form-check form-switch mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"groupEnabledSwitch\" checked onchange=\"toggleGroupStatus()\"> <label class=\"form-check-label\" for=\"groupEnabledSwitch\">Group Enabled</label></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div></div><script src=\"/static/js/iam-utils.js\"></script><script>\n // Groups page JavaScript\n let currentGroupName = '';\n\n async function createGroup() {\n const name = document.getElementById('groupName').value.trim();\n if (!name) {\n showAlert('Group name is required', 'error');\n return;\n }\n try {\n const response = await fetch('/api/groups', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: name })\n });\n if (response.ok) {\n showAlert('Group created successfully', 'success');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to create group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to create group: ' + error.message, 'error');\n }\n }\n\n async function viewGroup(name) {\n currentGroupName = name;\n document.getElementById('viewGroupTitle').textContent = 'Group: ' + name;\n await refreshGroupDetails(name);\n new bootstrap.Modal(document.getElementById('viewGroupModal')).show();\n }\n\n async function refreshGroupDetails(requestedName) {\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(requestedName));\n if (!response.ok) throw new Error('Failed to fetch group');\n if (requestedName !== currentGroupName) return; // stale response\n const group = await response.json();\n\n // Render members using DOM APIs to prevent XSS\n const membersList = document.getElementById('membersList');\n membersList.innerHTML = '';\n const membersTable = document.createElement('table');\n membersTable.className = 'table table-sm';\n const membersTbody = document.createElement('tbody');\n if (group.members && group.members.length > 0) {\n for (const member of group.members) {\n const tr = membersTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = member;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => removeMember(member);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = membersTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No members';\n }\n membersTable.appendChild(membersTbody);\n membersList.appendChild(membersTable);\n\n // Render policies using DOM APIs to prevent XSS\n const policiesList = document.getElementById('policiesList');\n policiesList.innerHTML = '';\n const policiesTable = document.createElement('table');\n policiesTable.className = 'table table-sm';\n const policiesTbody = document.createElement('tbody');\n if (group.policy_names && group.policy_names.length > 0) {\n for (const policy of group.policy_names) {\n const tr = policiesTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = policy;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.classNLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"attachPolicyToGroup()\"><i class=\"fas fa-plus\"></i> Attach</button></div></div><div id=\"policiesList\"></div></div><!-- Settings Tab --><div class=\"tab-pane fade\" id=\"settingsPane\" role=\"tabpanel\"><div class=\"form-check form-switch mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"groupEnabledSwitch\" checked onchange=\"toggleGroupStatus()\"> <label class=\"form-check-label\" for=\"groupEnabledSwitch\">Group Enabled</label></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div></div><script>\n // Groups page JavaScript\n let currentGroupName = '';\n\n async function createGroup() {\n const name = document.getElementById('groupName').value.trim();\n if (!name) {\n showAlert('Group name is required', 'error');\n return;\n }\n try {\n const response = await fetch(basePath('/api/groups'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: name })\n });\n if (response.ok) {\n showAlert('Group created successfully', 'success');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to create group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to create group: ' + error.message, 'error');\n }\n }\n\n async function viewGroup(name) {\n currentGroupName = name;\n document.getElementById('viewGroupTitle').textContent = 'Group: ' + name;\n await refreshGroupDetails(name);\n new bootstrap.Modal(document.getElementById('viewGroupModal')).show();\n }\n\n async function refreshGroupDetails(requestedName) {\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(requestedName)));\n if (!response.ok) throw new Error('Failed to fetch group');\n if (requestedName !== currentGroupName) return; // stale response\n const group = await response.json();\n\n // Render members using DOM APIs to prevent XSS\n const membersList = document.getElementById('membersList');\n membersList.innerHTML = '';\n const membersTable = document.createElement('table');\n membersTable.className = 'table table-sm';\n const membersTbody = document.createElement('tbody');\n if (group.members && group.members.length > 0) {\n for (const member of group.members) {\n const tr = membersTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = member;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => removeMember(member);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = membersTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No members';\n }\n membersTable.appendChild(membersTbody);\n membersList.appendChild(membersTable);\n\n // Render policies using DOM APIs to prevent XSS\n const policiesList = document.getElementById('policiesList');\n policiesList.innerHTML = '';\n const policiesTable = document.createElement('table');\n policiesTable.className = 'table table-sm';\n const policiesTbody = document.createElement('tbody');\n if (group.policy_names && group.policy_names.length > 0) {\n for (const policy of group.policy_names) {\n const tr = policiesTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = policy;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outlineLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -504,6 +504,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
const STATUS_ACTIVE = 'Active';
|
||||
const STATUS_INACTIVE = 'Inactive';
|
||||
|
||||
// Use basePath() from admin.js for -urlPrefix; it is loaded in the layout footer before DOMContentLoaded fires.
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
// Event delegation for user action buttons
|
||||
@@ -591,7 +592,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
// Load buckets
|
||||
async function loadBuckets() {
|
||||
try {
|
||||
const response = await fetch('/api/s3/buckets');
|
||||
const response = await fetch(basePath('/api/s3/buckets'));
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
availableBuckets = (data.buckets || []).map(bucket => ({ name: bucket.name, type: 's3' }));
|
||||
@@ -605,7 +606,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
availableBuckets = [];
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/api/s3tables/buckets');
|
||||
const response = await fetch(basePath('/api/s3tables/buckets'));
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const tableBuckets = (data.buckets || data.tableBuckets || []).map(bucket => ({ name: bucket.name, type: 's3tables' }));
|
||||
@@ -623,7 +624,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
// Load policies
|
||||
async function loadPolicies() {
|
||||
try {
|
||||
const response = await fetch('/api/object-store/policies');
|
||||
const response = await fetch(basePath('/api/object-store/policies'));
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const policies = data.policies || [];
|
||||
@@ -910,7 +911,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function showUserDetails(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
document.getElementById('userDetailsContent').innerHTML = createUserDetailsContent(user);
|
||||
@@ -929,7 +930,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function editUser(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
|
||||
@@ -1008,7 +1009,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function manageAccessKeys(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
document.getElementById('accessKeysUsername').textContent = username;
|
||||
@@ -1029,7 +1030,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
showDeleteConfirm(username, async function() {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
@@ -1074,7 +1075,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/users', {
|
||||
const response = await fetch(basePath('/api/users'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1118,13 +1119,13 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
|
||||
try {
|
||||
// Fetch all groups
|
||||
const groupsResp = await fetch('/api/groups');
|
||||
const groupsResp = await fetch(basePath('/api/groups'));
|
||||
if (!groupsResp.ok) return;
|
||||
const groupsData = await groupsResp.json();
|
||||
const allGroups = groupsData.groups || [];
|
||||
|
||||
// Fetch user details to get current groups
|
||||
const userResp = await fetch(`/api/users/${encodeURIComponent(username)}`);
|
||||
const userResp = await fetch(basePath(`/api/users/${encodeURIComponent(username)}`));
|
||||
if (!userResp.ok) return;
|
||||
const user = await userResp.json();
|
||||
const userGroups = user.groups || [];
|
||||
@@ -1172,7 +1173,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
if (!groupName) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members`, {
|
||||
const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members`), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: username })
|
||||
@@ -1192,7 +1193,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function removeUserFromGroupInEdit(groupName) {
|
||||
const username = document.getElementById('editUsername').value;
|
||||
try {
|
||||
const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`, {
|
||||
const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -1237,7 +1238,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1374,7 +1375,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function refreshAccessKeysList(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);
|
||||
@@ -1387,7 +1388,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
// Update access key status
|
||||
async function updateAccessKeyStatus(username, accessKey, status) {
|
||||
try {
|
||||
const response = await fetch(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1473,7 +1474,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}/access-keys`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys`), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1514,7 +1515,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const encodedAccessKey = encodeURIComponent(accessKey);
|
||||
const response = await fetch(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalUsers))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 38, Col: 71}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 38, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.Users)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 58, Col: 71}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 58, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 78, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 78, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -85,7 +85,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 127, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 127, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -108,7 +108,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(user.Email)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 133, Col: 59}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 133, Col: 59}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -121,7 +121,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(user.AccessKey)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 135, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 135, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -134,7 +134,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 140, Col: 121}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 140, Col: 121}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -152,7 +152,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 145, Col: 117}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 145, Col: 117}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -171,7 +171,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 151, Col: 126}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 151, Col: 126}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -190,7 +190,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 157, Col: 119}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 157, Col: 119}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -219,7 +219,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 189, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 189, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -240,7 +240,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</div><div class=\"mb-3\"><label for=\"email\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"email\" name=\"email\"></div><div class=\"mb-3\"><label for=\"actions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"actions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</option></optgroup></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple permissions</small></div><div class=\"mb-3\"><label class=\"form-label\">Bucket Scope</label> <small class=\"form-text text-muted d-block mb-2\">Apply selected permissions to specific buckets or all buckets</small><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"allBuckets\" value=\"all\" checked onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"allBuckets\">All Buckets</label></div><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"specificBuckets\" value=\"specific\" onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"specificBuckets\">Specific Buckets</label></div><div id=\"bucketSelectionList\" class=\"mt-2\" style=\"display: none;\"><select multiple class=\"form-select\" id=\"selectedBuckets\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple buckets</small></div></div><div class=\"mb-3\"><label for=\"policies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"policies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple policies</small></div><div class=\"mb-3 form-check\"><input type=\"checkbox\" class=\"form-check-input\" id=\"generateKey\" name=\"generateKey\" checked> <label class=\"form-check-label\" for=\"generateKey\">Generate access key automatically</label></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateUser()\">Create User</button></div></div></div></div><!-- Edit User Modal --><div class=\"modal fade\" id=\"editUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-edit me-2\"></i>Edit User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"editUserForm\"><input type=\"hidden\" id=\"editUsername\" name=\"username\"><div class=\"mb-3\"Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</div><div class=\"mb-3\"><label for=\"email\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"email\" name=\"email\"></div><div class=\"mb-3\"><label for=\"actions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"actions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</option></optgroup></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple permissions</small></div><div class=\"mb-3\"><label class=\"form-label\">Bucket Scope</label> <small class=\"form-text text-muted d-block mb-2\">Apply selected permissions to specific buckets or all buckets</small><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"allBuckets\" value=\"all\" checked onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"allBuckets\">All Buckets</label></div><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"specificBuckets\" value=\"specific\" onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"specificBuckets\">Specific Buckets</label></div><div id=\"bucketSelectionList\" class=\"mt-2\" style=\"display: none;\"><select multiple class=\"form-select\" id=\"selectedBuckets\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple buckets</small></div></div><div class=\"mb-3\"><label for=\"policies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"policies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple policies</small></div><div class=\"mb-3 form-check\"><input type=\"checkbox\" class=\"form-check-input\" id=\"generateKey\" name=\"generateKey\" checked> <label class=\"form-check-label\" for=\"generateKey\">Generate access key automatically</label></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateUser()\">Create User</button></div></div></div></div><!-- Edit User Modal --><div class=\"modal fade\" id=\"editUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-edit me-2\"></i>Edit User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"editUserForm\"><input type=\"hidden\" id=\"editUsername\" name=\"username\"><div class=\"mb-3\"Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -368,7 +368,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
document: policyDocument
|
||||
};
|
||||
|
||||
fetch('/api/object-store/policies', {
|
||||
fetch(basePath('/api/object-store/policies'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -408,7 +408,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
`;
|
||||
|
||||
// Fetch policy data
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName))
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Policy not found');
|
||||
@@ -494,7 +494,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
document.getElementById('editPolicyDocument').value = 'Loading...';
|
||||
|
||||
// Fetch policy data
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName))
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Policy not found');
|
||||
@@ -534,7 +534,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
document: policyDocument
|
||||
};
|
||||
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -636,7 +636,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
|
||||
function deletePolicy(policyName) {
|
||||
showDeleteConfirm(policyName, function() {
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {
|
||||
method: 'DELETE'
|
||||
})
|
||||
.then(response => response.json())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 34, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 34, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 54, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 54, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 74, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 74, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -85,7 +85,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 123, Col: 68}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 123, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -98,7 +98,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Document.Version)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 126, Col: 100}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 126, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -111,7 +111,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", len(policy.Document.Statement)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 129, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 129, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -124,7 +124,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(policy.CreatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 132, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 132, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -137,7 +137,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(policy.UpdatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 135, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 135, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -150,7 +150,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 139, Col: 168}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 139, Col: 168}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -163,7 +163,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 142, Col: 171}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 142, Col: 171}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -176,7 +176,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 145, Col: 174}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 145, Col: 174}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -193,7 +193,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.adLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.adLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -712,7 +712,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
// Only fetch if not already populated
|
||||
if (ownerSelect.options.length <= 1) {
|
||||
try {
|
||||
const response = await fetch('/api/users');
|
||||
const response = await fetch(basePath('/api/users'));
|
||||
const data = await response.json();
|
||||
const users = data.users || [];
|
||||
|
||||
@@ -756,7 +756,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch('/api/s3/buckets', {
|
||||
fetch(basePath('/api/s3/buckets'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -846,7 +846,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
quota_enabled: enabled
|
||||
};
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}/quota`, {
|
||||
fetch(basePath(`/api/s3/buckets/${bucketName}/quota`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -897,7 +897,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
// Fetch users if not cached
|
||||
try {
|
||||
if (!cachedUsers) {
|
||||
const response = await fetch('/api/users');
|
||||
const response = await fetch(basePath('/api/users'));
|
||||
const data = await response.json();
|
||||
cachedUsers = data.users || [];
|
||||
}
|
||||
@@ -941,7 +941,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
const owner = document.getElementById('bucketOwnerSelect').value;
|
||||
const data = { owner: owner };
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}/owner`, {
|
||||
fetch(basePath(`/api/s3/buckets/${bucketName}/owner`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -988,7 +988,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
detailsModalInstance.show();
|
||||
|
||||
// Fetch bucket details
|
||||
fetch('/api/s3/buckets/' + bucketName)
|
||||
fetch(basePath('/api/s3/buckets/' + bucketName))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.error) {
|
||||
@@ -1017,7 +1017,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;
|
||||
if (!bucketName) return;
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}`, {
|
||||
fetch(basePath(`/api/s3/buckets/${bucketName}`), {
|
||||
method: 'DELETE'
|
||||
})
|
||||
.then(response => response.json())
|
||||
@@ -1172,7 +1172,7 @@ function displayBucketDetails(data) {
|
||||
}
|
||||
|
||||
// Fetch all buckets from the API (not just the current page)
|
||||
fetch('/api/s3/buckets')
|
||||
fetch(basePath('/api/s3/buckets'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.error) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -81,7 +81,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 42, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 42, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -94,7 +94,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(data.TotalSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 62, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 62, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -107,7 +107,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 83, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 83, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -165,7 +165,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var5 templ.SafeURL
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 160, Col: 124}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 160, Col: 124}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -178,7 +178,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 163, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 163, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -196,7 +196,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 169, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 169, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -219,7 +219,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 175, Col: 92}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 175, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -232,7 +232,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.LogicalSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 177, Col: 85}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 177, Col: 85}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -250,7 +250,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1fx overhead", float64(bucket.PhysicalSize)/float64(bucket.LogicalSize)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 180, Col: 144}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 180, Col: 144}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -268,7 +268,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.PhysicalSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 184, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 184, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -295,7 +295,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var12).String())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 1, Col: 0}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 1, Col: 0}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -308,7 +308,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Quota))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 189, Col: 86}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 189, Col: 86}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -326,7 +326,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%% used", float64(bucket.LogicalSize)/float64(bucket.Quota)*100))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 193, Col: 146}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 193, Col: 146}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -384,7 +384,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 223, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 223, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -397,7 +397,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 223, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 223, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -420,7 +420,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var18 templ.SafeURL
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 232, Col: 128}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 232, Col: 128}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -433,7 +433,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 239, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 239, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -446,7 +446,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 245, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 245, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -459,7 +459,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 246, Col: 92}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 246, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -472,7 +472,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 252, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 252, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -485,7 +485,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 253, Col: 125}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 253, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -498,7 +498,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 254, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 254, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -511,7 +511,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 260, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 260, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -540,7 +540,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -553,7 +553,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalBuckets)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 185}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 185}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -566,7 +566,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 229}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 229}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -584,7 +584,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 299, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 299, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -613,7 +613,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 315, Col: 97}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 315, Col: 97}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -631,7 +631,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 319, Col: 129}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 319, Col: 129}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -644,7 +644,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 319, Col: 152}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 319, Col: 152}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -668,7 +668,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 327, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 327, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -696,13 +696,13 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 352, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 352, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -336,7 +336,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
async function showSADetails(id) {
|
||||
try {
|
||||
const encodedId = encodeURIComponent(id);
|
||||
const response = await fetch(`/api/service-accounts/${encodedId}`);
|
||||
const response = await fetch(basePath(`/api/service-accounts/${encodedId}`));
|
||||
if (response.ok) {
|
||||
const sa = await response.json();
|
||||
document.getElementById('saDetailsContent').innerHTML = createSADetailsContent(sa);
|
||||
@@ -355,7 +355,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
const newStatus = currentStatus === 'Active' ? 'Inactive' : 'Active';
|
||||
try {
|
||||
const encodedId = encodeURIComponent(id);
|
||||
const response = await fetch(`/api/service-accounts/${encodedId}`, {
|
||||
const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
@@ -378,7 +378,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
showDeleteConfirm(id, async function() {
|
||||
try {
|
||||
const encodedId = encodeURIComponent(id);
|
||||
const response = await fetch(`/api/service-accounts/${encodedId}`, {
|
||||
const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
@@ -427,7 +427,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/service-accounts', {
|
||||
const response = await fetch(basePath('/api/service-accounts'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(saData)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalAccounts))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 38, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 38, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.ActiveAccounts))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 58, Col: 75}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 58, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 78, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 78, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -85,7 +85,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 118, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 118, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -98,7 +98,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ParentUser)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 123, Col: 62}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 123, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -111,7 +111,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(sa.AccessKeyId)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 126, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 126, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -139,7 +139,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(sa.CreateDate.Format("2006-01-02"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 135, Col: 83}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 135, Col: 83}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -152,7 +152,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 139, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 139, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -165,7 +165,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 143, Col: 109}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 143, Col: 109}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -178,7 +178,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(sa.Status)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 143, Col: 143}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 143, Col: 143}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -206,7 +206,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 151, Col: 102}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 151, Col: 102}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -230,7 +230,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 182, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 182, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -248,7 +248,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 205, Col: 56}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 205, Col: 56}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -261,7 +261,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 205, Col: 65}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 205, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -272,7 +272,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</select> <small class=\"form-text text-muted\">The service account will inherit permissions from this user</small></div><div class=\"mb-3\"><label for=\"description\" class=\"form-label\">Description</label> <textarea class=\"form-control\" id=\"description\" name=\"description\" rows=\"2\" placeholder=\"What is this service account used for?\"></textarea></div><div class=\"mb-3\"><label for=\"expiration\" class=\"form-label\">Expiration (optional)</label> <input type=\"datetime-local\" class=\"form-control\" id=\"expiration\" name=\"expiration\"> <small class=\"form-text text-muted\">Leave empty for no expiration</small></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateServiceAccount()\">Create</button></div></div></div></div><!-- Service Account Details Modal --><div class=\"modal fade\" id=\"saDetailsModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-robot me-2\"></i>Service Account Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"saDetailsContent\"><!-- Content will be loaded dynamically --></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Credentials Display Modal --><div class=\"modal fade\" id=\"credentialsModal\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header bg-success text-white\"><h5 class=\"modal-title\"><i class=\"fas fa-check-circle me-2\"></i>Service Account Created Successfully</h5></div><div class=\"modal-body\"><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Important:</strong> This is the only time you will see the secret access key. Please save it securely.</div><div class=\"mb-4\"><h6 class=\"text-muted mb-3\">AWS CLI Configuration</h6><p class=\"text-muted small\">Use these credentials to configure AWS CLI or SDKs:</p><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_ACCESS_KEY_ID</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displayAccessKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displayAccessKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_SECRET_ACCESS_KEY</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displaySecretKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displaySecretKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div></div><div class=\"bg-light p-3 rounded\"><h6 class=\"text-muted mb-2\">Example AWS CLI Usage:</h6><div class=\"font-monospace small\"><div>export AWS_ACCESS_KEY_ID=<span id=\"exampleAccessKey\"></span></div><div>export AWS_SECRET_ACCESS_KEY=<span id=\"exampleSecretKey\"></span></div><div>export AWS_ENDPOINT_URL=http://localhost:8333</div><div class=\"mt-2\"># List buckets</div><div>aws s3 ls</div><div class=\"mt-2\"># Upload a file</div><div>aws s3 cp myfile.txt s3://mybucket/</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-primary\" onclick=\"closeCredentialsModal()\"><i class=\"fas fa-check me-1\"></i>I have saved the credentials</button></div></div></div></div><!-- JavaScript for service account management --><script>\n document.addEventListener('DOMContentLoaded', function() {\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n const saId = button.getAttribute('data-sa-id');\n \n switch (action) {\n case 'show-sa-details':\n showSADetails(saId);\n break;\n case 'toggle-sa-status':\n toggleSAStatus(saId, button.getAttribute('data-current-status'));\n break;\n case 'delete-sa':\n deleteSA(saId);\n break;\n }\n });\n });\n\n async function showSADetails(id) {\n try {\n const encodedId = encodeURIComponent(id);\n Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</select> <small class=\"form-text text-muted\">The service account will inherit permissions from this user</small></div><div class=\"mb-3\"><label for=\"description\" class=\"form-label\">Description</label> <textarea class=\"form-control\" id=\"description\" name=\"description\" rows=\"2\" placeholder=\"What is this service account used for?\"></textarea></div><div class=\"mb-3\"><label for=\"expiration\" class=\"form-label\">Expiration (optional)</label> <input type=\"datetime-local\" class=\"form-control\" id=\"expiration\" name=\"expiration\"> <small class=\"form-text text-muted\">Leave empty for no expiration</small></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateServiceAccount()\">Create</button></div></div></div></div><!-- Service Account Details Modal --><div class=\"modal fade\" id=\"saDetailsModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-robot me-2\"></i>Service Account Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"saDetailsContent\"><!-- Content will be loaded dynamically --></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Credentials Display Modal --><div class=\"modal fade\" id=\"credentialsModal\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header bg-success text-white\"><h5 class=\"modal-title\"><i class=\"fas fa-check-circle me-2\"></i>Service Account Created Successfully</h5></div><div class=\"modal-body\"><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Important:</strong> This is the only time you will see the secret access key. Please save it securely.</div><div class=\"mb-4\"><h6 class=\"text-muted mb-3\">AWS CLI Configuration</h6><p class=\"text-muted small\">Use these credentials to configure AWS CLI or SDKs:</p><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_ACCESS_KEY_ID</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displayAccessKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displayAccessKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_SECRET_ACCESS_KEY</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displaySecretKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displaySecretKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div></div><div class=\"bg-light p-3 rounded\"><h6 class=\"text-muted mb-2\">Example AWS CLI Usage:</h6><div class=\"font-monospace small\"><div>export AWS_ACCESS_KEY_ID=<span id=\"exampleAccessKey\"></span></div><div>export AWS_SECRET_ACCESS_KEY=<span id=\"exampleSecretKey\"></span></div><div>export AWS_ENDPOINT_URL=http://localhost:8333</div><div class=\"mt-2\"># List buckets</div><div>aws s3 ls</div><div class=\"mt-2\"># Upload a file</div><div>aws s3 cp myfile.txt s3://mybucket/</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-primary\" onclick=\"closeCredentialsModal()\"><i class=\"fas fa-check me-1\"></i>I have saved the credentials</button></div></div></div></div><!-- JavaScript for service account management --><script>\n document.addEventListener('DOMContentLoaded', function() {\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n const saId = button.getAttribute('data-sa-id');\n \n switch (action) {\n case 'show-sa-details':\n showSADetails(saId);\n break;\n case 'toggle-sa-status':\n toggleSAStatus(saId, button.getAttribute('data-current-status'));\n break;\n case 'delete-sa':\n deleteSA(saId);\n break;\n }\n });\n });\n\n async function showSADetails(id) {\n try {\n const encodedId = encodeURIComponent(id);\n Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ templ Topics(data dash.TopicsData) {
|
||||
};
|
||||
|
||||
// Create the topic
|
||||
fetch('/api/mq/topics/create', {
|
||||
fetch(basePath('/api/mq/topics/create'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
@@ -354,7 +354,7 @@ templ Topics(data dash.TopicsData) {
|
||||
var detailsRow = document.getElementById('details-' + topicName.replace(/\./g, '_'));
|
||||
var contentDiv = detailsRow.querySelector('.topic-details-content');
|
||||
|
||||
fetch('/admin/topics/' + encodeURIComponent(topicName) + '/details')
|
||||
fetch(basePath('/admin/topics/' + encodeURIComponent(topicName) + '/details'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
var html = '<div class="row">';
|
||||
|
||||
@@ -40,7 +40,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 13, Col: 107}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 13, Col: 107}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -53,7 +53,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalTopics))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 22, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 22, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -66,7 +66,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.Topics)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 30, Col: 90}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 30, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -94,7 +94,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(topic.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 70, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 70, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -113,7 +113,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
return topic.Name[:idx]
|
||||
}())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 78, Col: 55}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 78, Col: 55}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -132,7 +132,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
return topic.Name[idx+1:]
|
||||
}())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 87, Col: 55}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 87, Col: 55}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -145,7 +145,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", topic.Partitions))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 90, Col: 116}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 90, Col: 116}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -163,7 +163,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d %s", topic.Retention.DisplayValue, topic.Retention.DisplayUnit))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 96, Col: 140}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 96, Col: 140}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -186,7 +186,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(topic.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 105, Col: 160}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 105, Col: 160}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -199,7 +199,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("details-%s", strings.ReplaceAll(topic.Name, ".", "_")))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 110, Col: 146}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 110, Col: 146}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -215,7 +215,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</div></div></div></div></div><!-- Create Topic Modal --><div class=\"modal fade\" id=\"createTopicModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-plus me-2\"></i>Create New Topic</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createTopicForm\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicNamespace\" class=\"form-label\">Namespace *</label> <input type=\"text\" class=\"form-control\" id=\"topicNamespace\" name=\"namespace\" required placeholder=\"e.g., default\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicName\" class=\"form-label\">Topic Name *</label> <input type=\"text\" class=\"form-control\" id=\"topicName\" name=\"name\" required placeholder=\"e.g., user-events\"></div></div></div><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"partitionCount\" class=\"form-label\">Partition Count *</label> <input type=\"number\" class=\"form-control\" id=\"partitionCount\" name=\"partitionCount\" required min=\"1\" max=\"100\" value=\"6\"></div></div></div><!-- Retention Configuration --><div class=\"card mt-3\"><div class=\"card-header\"><h6 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Retention Policy</h6></div><div class=\"card-body\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableRetention\" name=\"enableRetention\" onchange=\"toggleRetentionFields()\"> <label class=\"form-check-label\" for=\"enableRetention\">Enable data retention</label></div><div id=\"retentionFields\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionValue\" class=\"form-label\">Retention Duration</label> <input type=\"number\" class=\"form-control\" id=\"retentionValue\" name=\"retentionValue\" min=\"1\" value=\"7\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionUnit\" class=\"form-label\">Unit</label> <select class=\"form-control\" id=\"retentionUnit\" name=\"retentionUnit\"><option value=\"hours\">Hours</option> <option value=\"days\" selected>Days</option></select></div></div></div><div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i> Data older than this duration will be automatically purged to save storage space.</div></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createTopic()\"><i class=\"fas fa-plus me-1\"></i>Create Topic</button></div></div></div></div><script type=\"text/javascript\">\n // Topic management functions\n function showCreateTopicModal() {\n var modal = new bootstrap.Modal(document.getElementById('createTopicModal'));\n modal.show();\n }\n\n function toggleRetentionFields() {\n var enableRetention = document.getElementById('enableRetention').checked;\n var retentionFields = document.getElementById('retentionFields');\n \n if (enableRetention) {\n retentionFields.style.display = 'block';\n } else {\n retentionFields.style.display = 'none';\n }\n }\n\n function createTopic() {\n var form = document.getElementById('createTopicForm');\n var formData = new FormData(form);\n \n if (!form.checkValidity()) {\n form.classList.add('was-validated');\n return;\n }\n \n var namespace = formData.get('namespace');\n var name = formData.get('name');\n var partitionCount = formData.get('partitionCount');\n var enableRetention = formData.get('enableRetention');\n var retentionValue = enableRetention === 'on' ? parseInt(formData.get('retentionValue')) : 0;\n var retentionUnit = enableRetention === 'on' ? formData.get('retentionUnit') : 'hours';\n \n // Convert retention to seconds\n var retentionSeconds = 0;\n if (enableRetention === 'on' && retentionValue > 0) {\n if (retentionUnit === 'hours') {\n retentionSeconds = retentionValue * 3600;\n } else if (retentionUnit === 'days') {\n retentionSeconds = retentionValue * 86400;\n }\n }\n \n var topicData = {\n namespace: namespace,\n name: name,\n partition_count: parseInt(partitionCount),\n retention: {\n enabled: enableRetentLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</div></div></div></div></div><!-- Create Topic Modal --><div class=\"modal fade\" id=\"createTopicModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-plus me-2\"></i>Create New Topic</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createTopicForm\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicNamespace\" class=\"form-label\">Namespace *</label> <input type=\"text\" class=\"form-control\" id=\"topicNamespace\" name=\"namespace\" required placeholder=\"e.g., default\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicName\" class=\"form-label\">Topic Name *</label> <input type=\"text\" class=\"form-control\" id=\"topicName\" name=\"name\" required placeholder=\"e.g., user-events\"></div></div></div><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"partitionCount\" class=\"form-label\">Partition Count *</label> <input type=\"number\" class=\"form-control\" id=\"partitionCount\" name=\"partitionCount\" required min=\"1\" max=\"100\" value=\"6\"></div></div></div><!-- Retention Configuration --><div class=\"card mt-3\"><div class=\"card-header\"><h6 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Retention Policy</h6></div><div class=\"card-body\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableRetention\" name=\"enableRetention\" onchange=\"toggleRetentionFields()\"> <label class=\"form-check-label\" for=\"enableRetention\">Enable data retention</label></div><div id=\"retentionFields\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionValue\" class=\"form-label\">Retention Duration</label> <input type=\"number\" class=\"form-control\" id=\"retentionValue\" name=\"retentionValue\" min=\"1\" value=\"7\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionUnit\" class=\"form-label\">Unit</label> <select class=\"form-control\" id=\"retentionUnit\" name=\"retentionUnit\"><option value=\"hours\">Hours</option> <option value=\"days\" selected>Days</option></select></div></div></div><div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i> Data older than this duration will be automatically purged to save storage space.</div></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createTopic()\"><i class=\"fas fa-plus me-1\"></i>Create Topic</button></div></div></div></div><script type=\"text/javascript\">\n // Topic management functions\n function showCreateTopicModal() {\n var modal = new bootstrap.Modal(document.getElementById('createTopicModal'));\n modal.show();\n }\n\n function toggleRetentionFields() {\n var enableRetention = document.getElementById('enableRetention').checked;\n var retentionFields = document.getElementById('retentionFields');\n \n if (enableRetention) {\n retentionFields.style.display = 'block';\n } else {\n retentionFields.style.display = 'none';\n }\n }\n\n function createTopic() {\n var form = document.getElementById('createTopicForm');\n var formData = new FormData(form);\n \n if (!form.checkValidity()) {\n form.classList.add('was-validated');\n return;\n }\n \n var namespace = formData.get('namespace');\n var name = formData.get('name');\n var partitionCount = formData.get('partitionCount');\n var enableRetention = formData.get('enableRetention');\n var retentionValue = enableRetention === 'on' ? parseInt(formData.get('retentionValue')) : 0;\n var retentionUnit = enableRetention === 'on' ? formData.get('retentionUnit') : 'hours';\n \n // Convert retention to seconds\n var retentionSeconds = 0;\n if (enableRetention === 'on' && retentionValue > 0) {\n if (retentionUnit === 'hours') {\n retentionSeconds = retentionValue * 3600;\n } else if (retentionUnit === 'days') {\n retentionSeconds = retentionValue * 86400;\n }\n }\n \n var topicData = {\n namespace: namespace,\n name: name,\n partition_count: parseInt(partitionCount),\n retention: {\n enabled: enableRetentLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
+45
-30
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
@@ -411,43 +412,57 @@ func startAdminServer(ctx context.Context, options AdminOptions, enableUI bool,
|
||||
Handler: handler,
|
||||
}
|
||||
|
||||
// Decide TLS configuration BEFORE launching the server goroutine, so a
|
||||
// bad cert or a missing key surfaces as a startup error instead of a
|
||||
// silently returned goroutine that leaves startAdminServer blocked on
|
||||
// ctx.Done() with no listener.
|
||||
var (
|
||||
clientCertFile,
|
||||
certFile,
|
||||
keyFile string
|
||||
)
|
||||
useTLS := false
|
||||
useMTLS := false
|
||||
|
||||
if viper.GetString("https.admin.key") != "" {
|
||||
useTLS = true
|
||||
certFile = viper.GetString("https.admin.cert")
|
||||
keyFile = viper.GetString("https.admin.key")
|
||||
}
|
||||
|
||||
if viper.GetString("https.admin.ca") != "" {
|
||||
useMTLS = true
|
||||
clientCertFile = viper.GetString("https.admin.ca")
|
||||
}
|
||||
|
||||
if useMTLS {
|
||||
server.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
}
|
||||
|
||||
if useTLS {
|
||||
getCert, certProvider, certErr := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if certErr != nil {
|
||||
return fmt.Errorf("load admin HTTPS certificate: %w", certErr)
|
||||
}
|
||||
defer certProvider.Close()
|
||||
if server.TLSConfig == nil {
|
||||
server.TLSConfig = &tls.Config{}
|
||||
}
|
||||
server.TLSConfig.GetCertificate = getCert
|
||||
}
|
||||
|
||||
// Start server
|
||||
go func() {
|
||||
log.Printf("Starting SeaweedFS Admin Server on port %d", *options.port)
|
||||
|
||||
// start http or https server with security.toml
|
||||
var (
|
||||
clientCertFile,
|
||||
certFile,
|
||||
keyFile string
|
||||
)
|
||||
useTLS := false
|
||||
useMTLS := false
|
||||
|
||||
if viper.GetString("https.admin.key") != "" {
|
||||
useTLS = true
|
||||
certFile = viper.GetString("https.admin.cert")
|
||||
keyFile = viper.GetString("https.admin.key")
|
||||
}
|
||||
|
||||
if viper.GetString("https.admin.ca") != "" {
|
||||
useMTLS = true
|
||||
clientCertFile = viper.GetString("https.admin.ca")
|
||||
}
|
||||
|
||||
if useMTLS {
|
||||
server.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
}
|
||||
|
||||
var serveErr error
|
||||
if useTLS {
|
||||
log.Printf("Starting SeaweedFS Admin Server with TLS on port %d", *options.port)
|
||||
err = server.ListenAndServeTLS(certFile, keyFile)
|
||||
serveErr = server.ListenAndServeTLS("", "")
|
||||
} else {
|
||||
err = server.ListenAndServe()
|
||||
serveErr = server.ListenAndServe()
|
||||
}
|
||||
|
||||
if err != nil && err != http.ErrServerClosed {
|
||||
log.Printf("Failed to start server: %v", err)
|
||||
if serveErr != nil && serveErr != http.ErrServerClosed {
|
||||
log.Printf("Failed to start server: %v", serveErr)
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
@@ -37,6 +37,8 @@ var Commands = []*Command{
|
||||
cmdMqAgent,
|
||||
cmdMqBroker,
|
||||
cmdMqKafkaGateway,
|
||||
cmdPushdown,
|
||||
cmdPushdownPing,
|
||||
cmdS3,
|
||||
cmdScaffold,
|
||||
cmdServer,
|
||||
|
||||
+17
-26
@@ -15,8 +15,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider/pemfile"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
@@ -82,9 +80,7 @@ type FilerOptions struct {
|
||||
allowedOrigins *string
|
||||
exposeDirectoryData *bool
|
||||
tusBasePath *string
|
||||
certProvider certprovider.Provider
|
||||
s3ConfigFile *string // optional path to static S3 identity config
|
||||
mountPeerRegistryEnable *bool // accept MountRegister/MountList RPCs (peer chunk sharing tier 1)
|
||||
// shutdownCtx, when non-nil, tells startFiler to gracefully shut down its
|
||||
// HTTP/gRPC servers once the ctx is cancelled. Used by integration tests
|
||||
// and by weed mini; nil for standalone weed filer.
|
||||
@@ -127,7 +123,6 @@ func init() {
|
||||
f.allowedOrigins = cmdFiler.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
f.exposeDirectoryData = cmdFiler.Flag.Bool("exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
|
||||
f.tusBasePath = cmdFiler.Flag.String("tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
|
||||
f.mountPeerRegistryEnable = cmdFiler.Flag.Bool("mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
|
||||
// start s3 on filer
|
||||
filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway")
|
||||
@@ -315,15 +310,6 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// GetCertificateWithUpdate Auto refreshing TSL certificate
|
||||
func (fo *FilerOptions) GetCertificateWithUpdate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
certs, err := fo.certProvider.KeyMaterial(context.Background())
|
||||
if certs == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &certs.Certs[0], err
|
||||
}
|
||||
|
||||
func (fo *FilerOptions) startFiler() {
|
||||
|
||||
defaultMux := http.NewServeMux()
|
||||
@@ -388,7 +374,6 @@ func (fo *FilerOptions) startFiler() {
|
||||
AllowedOrigins: strings.Split(*fo.allowedOrigins, ","),
|
||||
TusBasePath: *fo.tusBasePath,
|
||||
CredentialManager: credentialManager,
|
||||
MountPeerRegistryEnabled: fo.mountPeerRegistryEnable != nil && *fo.mountPeerRegistryEnable,
|
||||
})
|
||||
if nfs_err != nil {
|
||||
glog.Fatalf("Filer startup error: %v", nfs_err)
|
||||
@@ -500,14 +485,11 @@ func (fo *FilerOptions) startFiler() {
|
||||
caCertFile := viper.GetString("https.filer.ca")
|
||||
disbaleTlsVerifyClientCert := viper.GetBool("https.filer.disable_tls_verify_client_cert")
|
||||
|
||||
pemfileOptions := pemfile.Options{
|
||||
CertFile: certFile,
|
||||
KeyFile: keyFile,
|
||||
RefreshDuration: security.CredRefreshingInterval,
|
||||
}
|
||||
if fo.certProvider, err = pemfile.NewProvider(pemfileOptions); err != nil {
|
||||
glog.Fatalf("pemfile.NewProvider(%v) failed: %v", pemfileOptions, err)
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if err != nil {
|
||||
glog.Fatalf("Filer failed to load HTTPS certificate: %v", err)
|
||||
}
|
||||
defer certProvider.Close()
|
||||
|
||||
caCertPool := x509.NewCertPool()
|
||||
if caCertFile != "" {
|
||||
@@ -524,12 +506,15 @@ func (fo *FilerOptions) startFiler() {
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
GetCertificate: fo.GetCertificateWithUpdate,
|
||||
GetCertificate: getCert,
|
||||
ClientAuth: clientAuth,
|
||||
ClientCAs: caCertPool,
|
||||
}
|
||||
|
||||
security.FixTlsConfig(util.GetViper(), tlsConfig)
|
||||
err = security.FixTlsConfig(util.GetViper(), tlsConfig)
|
||||
if err != nil {
|
||||
glog.Fatalf("Filer failed to fix TLS config: %v", err)
|
||||
}
|
||||
|
||||
var localTLSServer *http.Server
|
||||
if filerLocalListener != nil {
|
||||
@@ -552,10 +537,16 @@ func (fo *FilerOptions) startFiler() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
if socketServer != nil {
|
||||
socketServer.Shutdown(shutdownCtx)
|
||||
err = socketServer.Shutdown(shutdownCtx)
|
||||
if err != nil {
|
||||
glog.Warningf("socket server shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
if localTLSServer != nil {
|
||||
localTLSServer.Shutdown(shutdownCtx)
|
||||
err = localTLSServer.Shutdown(shutdownCtx)
|
||||
if err != nil {
|
||||
glog.Warningf("local TLS server shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
if err := httpS.Shutdown(shutdownCtx); err != nil {
|
||||
glog.Warningf("HTTPS server shutdown: %v", err)
|
||||
|
||||
@@ -161,11 +161,13 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
|
||||
// create filer sink
|
||||
filerSource := &source.FilerSource{}
|
||||
filerSource.DoInitialize(
|
||||
if err := filerSource.DoInitialize(
|
||||
sourceFiler.ToHttpAddress(),
|
||||
sourceFiler.ToGrpcAddress(),
|
||||
sourcePath,
|
||||
*backupOption.proxyByFiler)
|
||||
*backupOption.proxyByFiler); err != nil {
|
||||
return fmt.Errorf("filersource initialization failed: %v", err)
|
||||
}
|
||||
|
||||
if err := repl_util.InitializeSSEForReplication(filerSource); err != nil {
|
||||
return fmt.Errorf("SSE initialization failed: %v", err)
|
||||
|
||||
@@ -4,7 +4,9 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
elastic "github.com/olivere/elastic/v7"
|
||||
@@ -13,16 +15,17 @@ import (
|
||||
)
|
||||
|
||||
type EsDocument struct {
|
||||
Dir string `json:"dir,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
IsDirectory bool `json:"isDir,omitempty"`
|
||||
Size uint64 `json:"size,omitempty"`
|
||||
Uid uint32 `json:"uid,omitempty"`
|
||||
Gid uint32 `json:"gid,omitempty"`
|
||||
UserName string `json:"userName,omitempty"`
|
||||
Crtime int64 `json:"crtime,omitempty"`
|
||||
Mtime int64 `json:"mtime,omitempty"`
|
||||
Mime string `json:"mime,omitempty"`
|
||||
Dir string `json:"dir,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
IsDirectory bool `json:"isDir,omitempty"`
|
||||
Size uint64 `json:"size,omitempty"`
|
||||
Uid uint32 `json:"uid,omitempty"`
|
||||
Gid uint32 `json:"gid,omitempty"`
|
||||
UserName string `json:"userName,omitempty"`
|
||||
Crtime int64 `json:"crtime,omitempty"`
|
||||
Mtime int64 `json:"mtime,omitempty"`
|
||||
Mime string `json:"mime,omitempty"`
|
||||
Extended map[string]string `json:"extended,omitempty"`
|
||||
}
|
||||
|
||||
func toEsEntry(event *filer_pb.EventNotification) (*EsDocument, string) {
|
||||
@@ -40,10 +43,31 @@ func toEsEntry(event *filer_pb.EventNotification) (*EsDocument, string) {
|
||||
Crtime: entry.Attributes.Crtime,
|
||||
Mtime: entry.Attributes.Mtime,
|
||||
Mime: entry.Attributes.Mime,
|
||||
Extended: toExtendedStrings(entry.Extended),
|
||||
}
|
||||
return esEntry, id
|
||||
}
|
||||
|
||||
// toExtendedStrings converts the xattr map (e.g. S3 user metadata like
|
||||
// X-Amz-Meta-*) to string values so Elasticsearch indexes them as text
|
||||
// instead of base64-encoding the raw bytes. Non-UTF-8 values are prefixed
|
||||
// with "base64:" so consumers can distinguish encoded bytes from plain
|
||||
// strings that happen to look like base64.
|
||||
func toExtendedStrings(extended map[string][]byte) map[string]string {
|
||||
if len(extended) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]string, len(extended))
|
||||
for k, v := range extended {
|
||||
if utf8.Valid(v) {
|
||||
result[k] = string(v)
|
||||
} else {
|
||||
result[k] = "base64:" + base64.StdEncoding.EncodeToString(v)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func sendToElasticSearchFunc(servers string, esIndex string) (func(resp *filer_pb.SubscribeMetadataResponse) error, error) {
|
||||
options := []elastic.ClientOptionFunc{}
|
||||
options = append(options, elastic.SetURL(strings.Split(servers, ",")...))
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
func sendToElasticSearchFunc(servers string, esIndex string) (func(resp *filer_pb.SubscribeMetadataResponse) error, error) {
|
||||
return func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
return nil
|
||||
}, nil
|
||||
return nil, fmt.Errorf("this weed binary was built without Elasticsearch support. Rebuild with `-tags elastic` (see docker/Dockerfile.go_build) to use -es/-es.index")
|
||||
}
|
||||
+3
-1
@@ -195,7 +195,9 @@ func doFixOneVolume(basepath string, baseFileName string, collection string, vol
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
} else {
|
||||
os.Remove(indexFileName)
|
||||
if err := os.Remove(indexFileName); err != nil {
|
||||
glog.Errorf("failed to cleanup file %s:%v", indexFileName, err)
|
||||
}
|
||||
glog.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,7 +243,9 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
case "fusermount.path":
|
||||
fusermountPath = parameter.value
|
||||
case "config_dir":
|
||||
util.ConfigurationFileDirectory.Set(parameter.value)
|
||||
if err := util.ConfigurationFileDirectory.Set(parameter.value); err != nil {
|
||||
panic(fmt.Errorf("config_dir %s: %w", parameter.value, err))
|
||||
}
|
||||
// FUSE performance options
|
||||
case "writebackCache":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
|
||||
+20
-3
@@ -148,7 +148,9 @@ func runMaster(cmd *Command, args []string) bool {
|
||||
|
||||
parent, _ := util.FullPath(*m.metaFolder).DirAndName()
|
||||
if util.FileExists(string(parent)) && !util.FileExists(*m.metaFolder) {
|
||||
os.MkdirAll(*m.metaFolder, 0755)
|
||||
if err := os.MkdirAll(*m.metaFolder, 0755); err != nil {
|
||||
glog.Fatalf("Could not create Meta Folder %s: %v", *m.metaFolder, err)
|
||||
}
|
||||
}
|
||||
if err := util.TestFolderWritable(util.ResolvePath(*m.metaFolder)); err != nil {
|
||||
glog.Fatalf("Check Meta Folder (-mdir) Writable %s : %s", *m.metaFolder, err)
|
||||
@@ -324,11 +326,26 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
var tlsConfig *tls.Config
|
||||
if useMTLS {
|
||||
tlsConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
security.FixTlsConfig(util.GetViper(), tlsConfig)
|
||||
if err := security.FixTlsConfig(util.GetViper(), tlsConfig); err != nil {
|
||||
glog.Fatalf("failed to fix TLS config: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if useTLS {
|
||||
go newHttpServer(r, tlsConfig).ServeTLS(masterListener, certFile, keyFile)
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to load master HTTPS certificate: %v", err)
|
||||
}
|
||||
// Master runs ServeTLS in a goroutine and this function then blocks
|
||||
// on shutdownCtx / select{}; tie the pem refresh goroutine to the
|
||||
// existing interrupt hook instead of a local defer that would fire
|
||||
// while the server is still running.
|
||||
grace.OnInterrupt(certProvider.Close)
|
||||
if tlsConfig == nil {
|
||||
tlsConfig = &tls.Config{}
|
||||
}
|
||||
tlsConfig.GetCertificate = getCert
|
||||
go newHttpServer(r, tlsConfig).ServeTLS(masterListener, "", "")
|
||||
} else {
|
||||
go newHttpServer(r, nil).Serve(masterListener)
|
||||
}
|
||||
|
||||
+13
-9
@@ -82,11 +82,11 @@ var (
|
||||
// goroutines (registered via onMiniClientsShutdown / trackMiniClient) to
|
||||
// drain.
|
||||
type miniClientsState struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
preCancelMu sync.Mutex
|
||||
preCancelFns []func()
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
preCancelMu sync.Mutex
|
||||
preCancelFns []func()
|
||||
}
|
||||
|
||||
var miniClients *miniClientsState
|
||||
@@ -311,7 +311,6 @@ func initMiniFilerFlags() {
|
||||
miniFilerOptions.allowedOrigins = cmdMini.Flag.String("filer.allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
miniFilerOptions.exposeDirectoryData = cmdMini.Flag.Bool("filer.exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
|
||||
miniFilerOptions.tusBasePath = cmdMini.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path")
|
||||
miniFilerOptions.mountPeerRegistryEnable = cmdMini.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
}
|
||||
|
||||
// initMiniVolumeFlags initializes Volume server flag options
|
||||
@@ -808,8 +807,11 @@ func applyConfigFileOptions(options map[string]string) {
|
||||
if flag != nil {
|
||||
// Only set if not already set (by command line)
|
||||
if flag.Value.String() == flag.DefValue {
|
||||
flag.Value.Set(value)
|
||||
glog.V(2).Infof("Applied config file option: %s=%s", key, value)
|
||||
if err := flag.Value.Set(value); err != nil {
|
||||
glog.Warningf("Failed to apply config file option: %s=%s: %v", key, value, err)
|
||||
} else {
|
||||
glog.V(2).Infof("Applied config file option: %s=%s", key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1022,7 +1024,9 @@ func runMini(cmd *Command, args []string) bool {
|
||||
printWelcomeMessage()
|
||||
|
||||
// Save configuration to file for persistence and documentation
|
||||
saveMiniConfiguration(*miniDataFolders)
|
||||
if err := saveMiniConfiguration(*miniDataFolders); err != nil {
|
||||
glog.Warningf("failed to save mini configuration in %s: %v", *miniDataFolders, err)
|
||||
}
|
||||
|
||||
if MiniClusterCtx != nil {
|
||||
<-MiniClusterCtx.Done()
|
||||
|
||||
@@ -166,7 +166,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
unmount.Unmount(dir)
|
||||
if err := unmount.Unmount(dir); err != nil {
|
||||
glog.V(1).Infof("pre-mount cleanup unmount %s: %v", dir, err)
|
||||
}
|
||||
|
||||
// start on local unix socket
|
||||
if *option.localSocket == "" {
|
||||
@@ -186,7 +188,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
|
||||
// detect mount folder mode
|
||||
if *option.dirAutoCreate {
|
||||
os.MkdirAll(dir, os.FileMode(0777)&^umask)
|
||||
if err := os.MkdirAll(dir, os.FileMode(0777)&^umask); err != nil {
|
||||
glog.Fatalf("failed to create directory %s:%v", dir, err)
|
||||
}
|
||||
}
|
||||
fileInfo, err := os.Stat(dir)
|
||||
|
||||
@@ -357,8 +361,8 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
WritebackCache: option.writebackCache != nil && *option.writebackCache,
|
||||
PosixDirNlink: option.posixDirNlink != nil && *option.posixDirNlink,
|
||||
// Peer chunk sharing
|
||||
PeerEnabled: option.peerEnabled != nil && *option.peerEnabled,
|
||||
PeerListen: peerStringOrEmpty(option.peerListen),
|
||||
PeerEnabled: option.peerEnabled != nil && *option.peerEnabled,
|
||||
PeerListen: peerStringOrEmpty(option.peerListen),
|
||||
PeerAdvertise: peerStringOrEmpty(option.peerAdvertise),
|
||||
PeerDataCenter: peerStringOrEmpty(option.peerDataCenter),
|
||||
PeerRack: peerStringOrEmpty(option.peerRack),
|
||||
@@ -381,7 +385,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
glog.Fatalf("Mount fail: %v", err)
|
||||
}
|
||||
grace.OnInterrupt(func() {
|
||||
unmount.Unmount(dir)
|
||||
if err := unmount.Unmount(dir); err != nil {
|
||||
glog.Errorf("failed to unmount %s: %v", dir, err)
|
||||
}
|
||||
})
|
||||
|
||||
if mountOptions.fuseCommandPid != 0 {
|
||||
|
||||
@@ -3,6 +3,7 @@ package command
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/agent"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -84,7 +85,9 @@ func (mqAgentOpt *MessageQueueAgentOptions) startQueueAgent() bool {
|
||||
}
|
||||
|
||||
glog.Infof("Start Seaweed Message Queue Agent on %s:%d", *mqAgentOpt.ip, *mqAgentOpt.port)
|
||||
grpcS.Serve(grpcL)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("MQ Agent failed to start: %v", err)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -109,14 +110,16 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
reflection.Register(localGrpcS)
|
||||
go func() {
|
||||
glog.V(0).Infof("MQ Broker listening on localhost:%d", *mqBrokerOpt.port)
|
||||
if err := localGrpcS.Serve(localL); err != nil {
|
||||
if err := localGrpcS.Serve(localL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("MQ Broker localhost listener error: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ip, *mqBrokerOpt.port)
|
||||
grpcS.Serve(grpcL)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("Failed to serve MQ Broker: %v", err)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ type NfsOptions struct {
|
||||
readOnly *bool
|
||||
allowedClients *string
|
||||
volumeServerAccess *string
|
||||
portmapBind *string
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -34,6 +35,7 @@ func init() {
|
||||
nfsStandaloneOptions.readOnly = cmdNfs.Flag.Bool("readOnly", false, "export the filer path as read only")
|
||||
nfsStandaloneOptions.allowedClients = cmdNfs.Flag.String("allowedClients", "", "comma-separated client IPs, hostnames, or CIDRs allowed to connect")
|
||||
nfsStandaloneOptions.volumeServerAccess = cmdNfs.Flag.String("volumeServerAccess", "direct", "access volume servers by [direct|publicUrl|filerProxy]")
|
||||
nfsStandaloneOptions.portmapBind = cmdNfs.Flag.String("portmap.bind", "", "when set, bind a built-in portmap v2 responder on <ip>:111 so plain `mount -t nfs` works without client-side portmap bypass. Empty disables it. Binding port 111 requires root or CAP_NET_BIND_SERVICE and must not conflict with a system rpcbind.")
|
||||
}
|
||||
|
||||
var cmdNfs = &Command{
|
||||
@@ -53,6 +55,26 @@ Safer defaults (since export ACLs are still not implemented):
|
||||
|
||||
Override -ip.bind to a routable address only after you have reviewed
|
||||
-allowedClients and the readiness of the rest of your deployment.
|
||||
|
||||
Mounting from a Linux client
|
||||
----------------------------
|
||||
The server does not run portmap/rpcbind by default. That means Linux
|
||||
mount.nfs, which queries portmap on port 111 first, will fail with
|
||||
"portmap query failed" against the plain form:
|
||||
|
||||
mount -t nfs -o nfsvers=3,nolock <host>:/export /mnt
|
||||
|
||||
Either tell the client to bypass portmap:
|
||||
|
||||
mount -t nfs -o nfsvers=3,nolock,port=2049,mountport=2049,\
|
||||
proto=tcp,mountproto=tcp <host>:/export /mnt
|
||||
|
||||
or enable the built-in portmap responder on the server:
|
||||
|
||||
weed nfs ... -portmap.bind=0.0.0.0
|
||||
|
||||
Binding port 111 requires root or CAP_NET_BIND_SERVICE and must not
|
||||
collide with a system rpcbind.
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -85,6 +107,7 @@ func runNfs(cmd *Command, args []string) bool {
|
||||
AllowedClients: util.StringSplit(*nfsStandaloneOptions.allowedClients, ","),
|
||||
VolumeServerAccess: *nfsStandaloneOptions.volumeServerAccess,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
PortmapBind: *nfsStandaloneOptions.portmapBind,
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("NFS Server startup error: %v", err)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown"
|
||||
"github.com/seaweedfs/seaweedfs/weed/parquet_pushdown/daemon"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
)
|
||||
|
||||
var (
|
||||
pushdownOptions PushdownOptions
|
||||
)
|
||||
|
||||
type PushdownOptions struct {
|
||||
filer *string
|
||||
ip *string
|
||||
port *int
|
||||
trustMode *string
|
||||
connectorTrustedAck *bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdPushdown.Run = runPushdown // break init cycle
|
||||
pushdownOptions.filer = cmdPushdown.Flag.String("filer", "localhost:8888", "comma-separated filer server addresses for high availability")
|
||||
pushdownOptions.ip = cmdPushdown.Flag.String("ip", util.DetectedHostAddress(), "pushdown daemon gRPC listen ip address")
|
||||
pushdownOptions.port = cmdPushdown.Flag.Int("port", 18888, "pushdown daemon gRPC listen port")
|
||||
pushdownOptions.trustMode = cmdPushdown.Flag.String("trust", string(parquet_pushdown.TrustModeCatalogValidated), "trust mode: catalog-validated (default) or connector-trusted (dev only)")
|
||||
pushdownOptions.connectorTrustedAck = cmdPushdown.Flag.Bool("dev.connector_trusted_ack", false, "explicitly acknowledge running with -trust=connector-trusted; required for that mode")
|
||||
}
|
||||
|
||||
var cmdPushdown = &Command{
|
||||
UsageLine: "pushdown [-port=18888] [-filer=<ip:port>[,<ip:port>]...] [-trust=catalog-validated]",
|
||||
Short: "<WIP> start the SeaweedFS Parquet pushdown daemon (M0 skeleton)",
|
||||
Long: `start the SeaweedFS Parquet pushdown daemon.
|
||||
|
||||
The pushdown daemon is a standalone gRPC service that accelerates Parquet/
|
||||
Iceberg scans by pruning files, row groups, and pages before the engine
|
||||
reads data. See PARQUET_PUSHDOWN_DESIGN.md and PARQUET_PUSHDOWN_DEV_PLAN.md
|
||||
at the repo root for the full design and milestone plan.
|
||||
|
||||
M0 ships request validation and the gRPC surface only; pruning logic
|
||||
lands in M1+.
|
||||
|
||||
Trust modes:
|
||||
catalog-validated (default)
|
||||
Server validates each request's DataFiles and Deletes against the
|
||||
Iceberg catalog at the requested snapshot before serving.
|
||||
connector-trusted
|
||||
Skip catalog validation. Developer-only; production builds must
|
||||
not enable. Requires the explicit -dev.connector_trusted_ack flag.
|
||||
|
||||
Multiple filer addresses can be specified for high availability,
|
||||
separated by commas.`,
|
||||
}
|
||||
|
||||
func runPushdown(cmd *Command, args []string) bool {
|
||||
cfg := daemon.Config{
|
||||
IP: *pushdownOptions.ip,
|
||||
Port: *pushdownOptions.port,
|
||||
FilerAddresses: pb.ServerAddresses(*pushdownOptions.filer).ToAddresses(),
|
||||
TrustMode: parquet_pushdown.TrustMode(*pushdownOptions.trustMode),
|
||||
ConnectorTrustedAck: *pushdownOptions.connectorTrustedAck,
|
||||
Version: version.Version(),
|
||||
}
|
||||
if err := daemon.Run(cfg); err != nil {
|
||||
glog.Fatalf("pushdown daemon: %v", err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
pb "github.com/seaweedfs/seaweedfs/weed/pb/parquet_pushdown_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
var (
|
||||
pushdownPingOptions PushdownPingOptions
|
||||
)
|
||||
|
||||
type PushdownPingOptions struct {
|
||||
target *string
|
||||
timeout *time.Duration
|
||||
useTLS *bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdPushdownPing.Run = runPushdownPing
|
||||
pushdownPingOptions.target = cmdPushdownPing.Flag.String("server", "localhost:18888", "pushdown daemon gRPC address")
|
||||
pushdownPingOptions.timeout = cmdPushdownPing.Flag.Duration("timeout", 5*time.Second, "RPC deadline")
|
||||
pushdownPingOptions.useTLS = cmdPushdownPing.Flag.Bool("tls", false, "dial with TLS using grpc.client config")
|
||||
}
|
||||
|
||||
var cmdPushdownPing = &Command{
|
||||
UsageLine: "pushdown.ping [-server=<ip:port>]",
|
||||
Short: "<WIP> ping a running pushdown daemon (M0 smoke test)",
|
||||
Long: `ping a running pushdown daemon.
|
||||
|
||||
Calls the SeaweedParquetPushdown.Ping RPC and prints the daemon's
|
||||
reported version and trust mode. Used as a deployment smoke test
|
||||
and by the M0 integration test.`,
|
||||
}
|
||||
|
||||
func runPushdownPing(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
|
||||
dialOpt := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
if *pushdownPingOptions.useTLS {
|
||||
dialOpt = security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *pushdownPingOptions.timeout)
|
||||
defer cancel()
|
||||
|
||||
conn, err := grpc.NewClient(*pushdownPingOptions.target, dialOpt)
|
||||
if err != nil {
|
||||
glog.Errorf("dial %s: %v", *pushdownPingOptions.target, err)
|
||||
return false
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
resp, err := pb.NewSeaweedParquetPushdownClient(conn).Ping(ctx, &pb.PingRequest{})
|
||||
if err != nil {
|
||||
glog.Errorf("ping %s: %v", *pushdownPingOptions.target, err)
|
||||
return false
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stdout, "ok: server=%s version=%q trust=%q\n", *pushdownPingOptions.target, resp.Version, resp.TrustMode)
|
||||
return true
|
||||
}
|
||||
+8
-21
@@ -15,8 +15,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider/pemfile"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -62,7 +60,6 @@ type S3Options struct {
|
||||
localFilerSocket *string
|
||||
dataCenter *string
|
||||
localSocket *string
|
||||
certProvider certprovider.Provider
|
||||
idleTimeout *int
|
||||
concurrentUploadLimitMB *int
|
||||
concurrentFileUploadLimit *int
|
||||
@@ -228,15 +225,6 @@ func runS3(cmd *Command, args []string) bool {
|
||||
|
||||
}
|
||||
|
||||
// GetCertificateWithUpdate Auto refreshing TSL certificate
|
||||
func (s3opt *S3Options) GetCertificateWithUpdate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
certs, err := s3opt.certProvider.KeyMaterial(context.Background())
|
||||
if certs == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &certs.Certs[0], err
|
||||
}
|
||||
|
||||
// resolveExternalUrl returns the external URL from the flag or falls back to the S3_EXTERNAL_URL env var.
|
||||
func (s3opt *S3Options) resolveExternalUrl() string {
|
||||
if s3opt.externalUrl != nil && *s3opt.externalUrl != "" {
|
||||
@@ -376,7 +364,9 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
if err != nil {
|
||||
glog.Fatalf("Failed to listen on %s: %v", localSocket, err)
|
||||
}
|
||||
newHttpServer(router, nil).Serve(s3SocketListener)
|
||||
if err := newHttpServer(router, nil).Serve(s3SocketListener); err != nil && err != http.ErrServerClosed {
|
||||
glog.Fatalf("Failed to start S3 http server: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -415,14 +405,11 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
glog.Fatalf("S3 API Server error: -s3.port.https (%d) cannot be the same as -s3.port (%d)", *s3opt.portHttps, *s3opt.port)
|
||||
}
|
||||
|
||||
pemfileOptions := pemfile.Options{
|
||||
CertFile: *s3opt.tlsCertificate,
|
||||
KeyFile: *s3opt.tlsPrivateKey,
|
||||
RefreshDuration: security.CredRefreshingInterval,
|
||||
}
|
||||
if s3opt.certProvider, err = pemfile.NewProvider(pemfileOptions); err != nil {
|
||||
glog.Fatalf("pemfile.NewProvider(%v) failed: %v", pemfileOptions, err)
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(*s3opt.tlsCertificate, *s3opt.tlsPrivateKey)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API Server failed to load HTTPS certificate: %v", err)
|
||||
}
|
||||
grace.OnInterrupt(certProvider.Close)
|
||||
|
||||
caCertPool := x509.NewCertPool()
|
||||
if *s3opt.tlsCACertificate != "" {
|
||||
@@ -440,7 +427,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
GetCertificate: s3opt.GetCertificateWithUpdate,
|
||||
GetCertificate: getCert,
|
||||
ClientAuth: clientAuth,
|
||||
ClientCAs: caCertPool,
|
||||
}
|
||||
|
||||
@@ -130,7 +130,6 @@ func init() {
|
||||
filerOptions.diskType = cmdServer.Flag.String("filer.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
|
||||
filerOptions.exposeDirectoryData = cmdServer.Flag.Bool("filer.exposeDirectoryData", true, "expose directory data via filer. If false, filer UI will be innaccessible.")
|
||||
filerOptions.tusBasePath = cmdServer.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
|
||||
filerOptions.mountPeerRegistryEnable = cmdServer.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
|
||||
serverOptions.v.port = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
|
||||
serverOptions.v.portGrpc = cmdServer.Flag.Int("volume.port.grpc", 0, "volume server grpc listen port")
|
||||
|
||||
+33
-6
@@ -2,6 +2,7 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
httppprof "net/http/pprof"
|
||||
@@ -312,7 +313,7 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
}
|
||||
|
||||
// starting the cluster http server
|
||||
clusterHttpServer := v.startClusterHttpService(volumeMux)
|
||||
clusterHttpServer, closeCert := v.startClusterHttpService(volumeMux)
|
||||
|
||||
grace.OnReload(volumeServer.LoadNewVolumes)
|
||||
grace.OnReload(volumeServer.Reload)
|
||||
@@ -329,6 +330,9 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
}
|
||||
|
||||
shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
|
||||
if closeCert != nil {
|
||||
closeCert()
|
||||
}
|
||||
stopChan <- true
|
||||
})
|
||||
|
||||
@@ -337,6 +341,9 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
case <-stopChan:
|
||||
case <-v.shutdownCtx.Done():
|
||||
shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
|
||||
if closeCert != nil {
|
||||
closeCert()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
@@ -442,7 +449,13 @@ func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdo
|
||||
return publicHttpDown
|
||||
}
|
||||
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
|
||||
// startClusterHttpService starts the volume cluster HTTP server and
|
||||
// returns it along with a close func for the cert reloader's refresh
|
||||
// goroutine (nil when HTTPS is disabled). The caller is responsible
|
||||
// for invoking the close func on every shutdown path — both the
|
||||
// SIGTERM/grace.OnInterrupt path and the shutdownCtx path used by
|
||||
// mini/integration tests.
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) (httpdown.Server, func()) {
|
||||
var (
|
||||
certFile, keyFile string
|
||||
)
|
||||
@@ -461,14 +474,28 @@ func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpd
|
||||
httpDown := httpdown.HTTP{
|
||||
KillTimeout: time.Minute,
|
||||
StopTimeout: 30 * time.Second,
|
||||
CertFile: certFile,
|
||||
KeyFile: keyFile}
|
||||
}
|
||||
httpS := &http.Server{Handler: handler}
|
||||
|
||||
if viper.GetString("https.volume.ca") != "" {
|
||||
clientCertFile := viper.GetString("https.volume.ca")
|
||||
httpS.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
security.FixTlsConfig(util.GetViper(), httpS.TLSConfig)
|
||||
if err := security.FixTlsConfig(util.GetViper(), httpS.TLSConfig); err != nil {
|
||||
glog.Fatalf("Could not fix TLS config: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var closeCert func()
|
||||
if certFile != "" && keyFile != "" {
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if err != nil {
|
||||
glog.Fatalf("Volume server failed to load TLS certificate: %v", err)
|
||||
}
|
||||
closeCert = certProvider.Close
|
||||
if httpS.TLSConfig == nil {
|
||||
httpS.TLSConfig = &tls.Config{}
|
||||
}
|
||||
httpS.TLSConfig.GetCertificate = getCert
|
||||
}
|
||||
|
||||
clusterHttpServer := httpDown.Serve(httpS, listener)
|
||||
@@ -477,5 +504,5 @@ func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpd
|
||||
glog.Fatalf("Volume server fail to serve: %v", e)
|
||||
}
|
||||
}()
|
||||
return clusterHttpServer
|
||||
return clusterHttpServer, closeCert
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -150,7 +151,13 @@ func (wo *WebDavOption) startWebDav() bool {
|
||||
|
||||
if *wo.tlsPrivateKey != "" {
|
||||
glog.V(0).Infof("Start Seaweed WebDav Server %s at https %s", version.Version(), listenAddress)
|
||||
if err = httpS.ServeTLS(webDavListener, *wo.tlsCertificate, *wo.tlsPrivateKey); err != nil && err != http.ErrServerClosed {
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(*wo.tlsCertificate, *wo.tlsPrivateKey)
|
||||
if err != nil {
|
||||
glog.Fatalf("WebDav Server failed to load TLS certificate: %v", err)
|
||||
}
|
||||
defer certProvider.Close()
|
||||
httpS.TLSConfig = &tls.Config{GetCertificate: getCert}
|
||||
if err = httpS.ServeTLS(webDavListener, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
glog.Fatalf("WebDav Server Fail to serve: %v", err)
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -3,6 +3,9 @@ package grpc
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
@@ -50,6 +53,12 @@ func (store *IamGrpcStore) GetUser(ctx context.Context, username string) (*iam_p
|
||||
identity = resp.Identity
|
||||
return nil
|
||||
})
|
||||
// The filer-side handler returns gRPC NotFound when the user is absent;
|
||||
// translate back to the package sentinel so callers can use
|
||||
// errors.Is(err, credential.ErrUserNotFound) uniformly across stores.
|
||||
if err != nil && status.Code(err) == codes.NotFound {
|
||||
return nil, credential.ErrUserNotFound
|
||||
}
|
||||
return identity, err
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,14 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
PolicyNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
ServiceAccountIdPattern = regexp.MustCompile(`^sa:[A-Za-z0-9_-]+:[a-z0-9-]+$`)
|
||||
PolicyNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
// ServiceAccountIdPattern matches sa:<parent-user>:<uuid>. The parent-user
|
||||
// segment accepts every character allowed in an AWS IAM username
|
||||
// (`[\w+=,.@-]+` per
|
||||
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_User.html)
|
||||
// so service accounts created for users with e.g. `user@example.com`
|
||||
// don't fail validation at the persistence layer.
|
||||
ServiceAccountIdPattern = regexp.MustCompile(`^sa:[A-Za-z0-9_+=,.@-]+:[a-z0-9-]+$`)
|
||||
)
|
||||
|
||||
func ValidatePolicyName(name string) error {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package credential
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateServiceAccountId(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
id string
|
||||
wantErr bool
|
||||
}{
|
||||
{"simple", "sa:alice:abcdef0123456789", false},
|
||||
{"uppercase parent", "sa:ALICE:abcdef0123456789", false},
|
||||
{"hyphenated uuid suffix", "sa:alice:123e4567-e89b-12d3-a456-426614174000", false},
|
||||
{"with hyphen", "sa:test-user:abcdef0123456789", false},
|
||||
{"with underscore", "sa:test_user:abcdef0123456789", false},
|
||||
|
||||
// AWS IAM usernames accept `+=,.@-` in addition to alphanumerics
|
||||
// and underscore. Service account IDs must accept them too, or
|
||||
// callers with realistic usernames hit a validation error at the
|
||||
// persistence layer. See
|
||||
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_User.html
|
||||
{"email-style", "sa:alice@example.com:abcdef0123456789", false},
|
||||
{"with dot", "sa:first.last:abcdef0123456789", false},
|
||||
{"with plus", "sa:user+tag:abcdef0123456789", false},
|
||||
{"with equals", "sa:user=prod:abcdef0123456789", false},
|
||||
{"with comma", "sa:a,b:abcdef0123456789", false},
|
||||
|
||||
{"empty", "", true},
|
||||
{"missing prefix", "alice:abcdef0123456789", true},
|
||||
{"wrong prefix", "svc:alice:abcdef0123456789", true},
|
||||
{"uppercase uuid", "sa:alice:ABCDEF0123456789", true},
|
||||
{"missing uuid", "sa:alice:", true},
|
||||
{"missing user", "sa::abcdef0123456789", true},
|
||||
// Colon is not in the AWS IAM username set, and would break
|
||||
// the colon-separated layout.
|
||||
{"colon in user", "sa:a:b:abcdef0123456789", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := ValidateServiceAccountId(tc.id)
|
||||
if tc.wantErr && err == nil {
|
||||
t.Fatalf("expected error for %q, got nil", tc.id)
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Fatalf("unexpected error for %q: %v", tc.id, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,109 +2,14 @@ package redis3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stvp/tempredis"
|
||||
)
|
||||
|
||||
var names = []string{
|
||||
"cassandra.in.sh",
|
||||
"cassandra",
|
||||
"debug-cql.bat",
|
||||
"nodetool",
|
||||
"nodetool.bat",
|
||||
"source-conf.ps1",
|
||||
"sstableloader",
|
||||
"sstableloader.bat",
|
||||
"sstablescrub",
|
||||
"sstablescrub.bat",
|
||||
"sstableupgrade",
|
||||
"sstableupgrade.bat",
|
||||
"sstableutil",
|
||||
"sstableutil.bat",
|
||||
"sstableverify",
|
||||
"sstableverify.bat",
|
||||
"stop-server",
|
||||
"stop-server.bat",
|
||||
"stop-server.ps1",
|
||||
"cassandra.in.bat",
|
||||
"cqlsh.py",
|
||||
"cqlsh",
|
||||
"cassandra.ps1",
|
||||
"cqlsh.bat",
|
||||
"debug-cql",
|
||||
"cassandra.bat",
|
||||
}
|
||||
|
||||
func yTestNameList(t *testing.T) {
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Network: "unix",
|
||||
Addr: server.Socket(),
|
||||
})
|
||||
|
||||
store := newSkipListElementStore("/yyy/bin", client)
|
||||
var data []byte
|
||||
for _, name := range names {
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
nameList.WriteName(name)
|
||||
|
||||
nameList.ListNames("", func(name string) bool {
|
||||
println(name)
|
||||
return true
|
||||
})
|
||||
|
||||
if nameList.HasChanges() {
|
||||
data = nameList.ToBytes()
|
||||
}
|
||||
println()
|
||||
}
|
||||
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
nameList.ListNames("", func(name string) bool {
|
||||
println(name)
|
||||
return true
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func yBenchmarkNameList(b *testing.B) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Network: "unix",
|
||||
Addr: server.Socket(),
|
||||
})
|
||||
|
||||
store := newSkipListElementStore("/yyy/bin", client)
|
||||
var data []byte
|
||||
for i := 0; i < b.N; i++ {
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
|
||||
nameList.WriteName(strconv.Itoa(i) + "namexxxxxxxxxxxxxxxxxxx")
|
||||
|
||||
if nameList.HasChanges() {
|
||||
data = nameList.ToBytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRedis(b *testing.B) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -120,92 +25,3 @@ func BenchmarkRedis(b *testing.B) {
|
||||
client.ZAddNX(context.Background(), "/yyy/bin", redis.Z{Score: 0, Member: strconv.Itoa(i) + "namexxxxxxxxxxxxxxxxxxx"})
|
||||
}
|
||||
}
|
||||
|
||||
func xTestNameListAdd(t *testing.T) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
client.FlushAll(context.Background())
|
||||
|
||||
N := 364800
|
||||
|
||||
ts0 := time.Now()
|
||||
store := newSkipListElementStore("/y", client)
|
||||
var data []byte
|
||||
nameList := LoadItemList(data, "/y", client, store, 100000)
|
||||
for i := 0; i < N; i++ {
|
||||
nameList.WriteName(fmt.Sprintf("%8d", i))
|
||||
}
|
||||
|
||||
ts1 := time.Now()
|
||||
|
||||
for i := 0; i < N; i++ {
|
||||
client.ZAddNX(context.Background(), "/x", redis.Z{Score: 0, Member: fmt.Sprintf("name %8d", i)})
|
||||
}
|
||||
ts2 := time.Now()
|
||||
|
||||
fmt.Printf("%v %v", ts1.Sub(ts0), ts2.Sub(ts1))
|
||||
|
||||
/*
|
||||
keys := client.Keys(context.Background(), "/*m").Val()
|
||||
for _, k := range keys {
|
||||
println("key", k)
|
||||
for i, v := range client.ZRangeByLex(context.Background(), k, &redis.ZRangeBy{
|
||||
Min: "-",
|
||||
Max: "+",
|
||||
}).Val() {
|
||||
println(" ", i, v)
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
func xBenchmarkNameList(b *testing.B) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
store := newSkipListElementStore("/yyy/bin", client)
|
||||
var data []byte
|
||||
for i := 0; i < b.N; i++ {
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
|
||||
nameList.WriteName(fmt.Sprintf("name %8d", i))
|
||||
|
||||
if nameList.HasChanges() {
|
||||
data = nameList.ToBytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func xBenchmarkRedis(b *testing.B) {
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
client.ZAddNX(context.Background(), "/xxx/bin", redis.Z{Score: 0, Member: fmt.Sprintf("name %8d", i)})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestStringifyClaimValue covers the scalar types that can appear in
|
||||
// RequestContext so that both JSON-decoded (float64, json.Number) and typed
|
||||
// (int8..int64, uint..uint64, bool) values substitute correctly.
|
||||
func TestStringifyClaimValue(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value interface{}
|
||||
want string
|
||||
wantOk bool
|
||||
}{
|
||||
{name: "string", value: "alice", want: "alice", wantOk: true},
|
||||
{name: "bool true", value: true, want: "true", wantOk: true},
|
||||
{name: "bool false", value: false, want: "false", wantOk: true},
|
||||
{name: "float64 integer", value: float64(301), want: "301", wantOk: true},
|
||||
{name: "float64 fraction", value: 1.5, want: "1.5", wantOk: true},
|
||||
{name: "float32", value: float32(2.25), want: "2.25", wantOk: true},
|
||||
{name: "int", value: int(42), want: "42", wantOk: true},
|
||||
{name: "int8", value: int8(-5), want: "-5", wantOk: true},
|
||||
{name: "int16", value: int16(32000), want: "32000", wantOk: true},
|
||||
{name: "int32", value: int32(-123456), want: "-123456", wantOk: true},
|
||||
{name: "int64", value: int64(9999999999), want: "9999999999", wantOk: true},
|
||||
{name: "uint", value: uint(7), want: "7", wantOk: true},
|
||||
{name: "uint8", value: uint8(255), want: "255", wantOk: true},
|
||||
{name: "uint16", value: uint16(65535), want: "65535", wantOk: true},
|
||||
{name: "uint32", value: uint32(4000000000), want: "4000000000", wantOk: true},
|
||||
{name: "uint64", value: uint64(18000000000000000000), want: "18000000000000000000", wantOk: true},
|
||||
{name: "json.Number int", value: json.Number("301"), want: "301", wantOk: true},
|
||||
{name: "json.Number float", value: json.Number("1.5"), want: "1.5", wantOk: true},
|
||||
{name: "nil", value: nil, want: "", wantOk: false},
|
||||
{name: "slice unsupported", value: []string{"a", "b"}, want: "", wantOk: false},
|
||||
{name: "map unsupported", value: map[string]string{"a": "b"}, want: "", wantOk: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, ok := stringifyClaimValue(tt.value)
|
||||
assert.Equal(t, tt.wantOk, ok)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExpandPolicyVariablesDynamicJWTClaims verifies that arbitrary JWT claims
|
||||
// (not only the hardcoded jwt:sub/jwt:iss/jwt:aud/jwt:preferred_username)
|
||||
// can be substituted in policy patterns when present in the request context.
|
||||
// Reproduces the scenario in https://github.com/seaweedfs/seaweedfs/issues/9214
|
||||
// where ${jwt:project_path} was left unsubstituted.
|
||||
func TestExpandPolicyVariablesDynamicJWTClaims(t *testing.T) {
|
||||
evalCtx := &EvaluationContext{
|
||||
RequestContext: map[string]interface{}{
|
||||
"jwt:project_path": "some/namespace/project",
|
||||
"jwt:namespace_path": "some/namespace",
|
||||
"jwt:user_login": "mat",
|
||||
// JSON-decoded numeric claim
|
||||
"jwt:project_id": float64(301),
|
||||
// Dynamic SAML/OIDC claims
|
||||
"saml:department": "engineering",
|
||||
"oidc:tenant": "acme",
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
pattern string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "dynamic jwt claim substituted in resource arn",
|
||||
pattern: "arn:aws:s3:::softs/${jwt:project_path}/*",
|
||||
expected: "arn:aws:s3:::softs/some/namespace/project/*",
|
||||
},
|
||||
{
|
||||
name: "multiple dynamic jwt claims in one pattern",
|
||||
pattern: "${jwt:namespace_path}/${jwt:user_login}/data",
|
||||
expected: "some/namespace/mat/data",
|
||||
},
|
||||
{
|
||||
name: "dynamic numeric jwt claim is stringified",
|
||||
pattern: "projects/${jwt:project_id}/uploads",
|
||||
expected: "projects/301/uploads",
|
||||
},
|
||||
{
|
||||
name: "dynamic saml claim substituted",
|
||||
pattern: "dept/${saml:department}/*",
|
||||
expected: "dept/engineering/*",
|
||||
},
|
||||
{
|
||||
name: "dynamic oidc claim substituted",
|
||||
pattern: "tenants/${oidc:tenant}/data",
|
||||
expected: "tenants/acme/data",
|
||||
},
|
||||
{
|
||||
name: "missing jwt claim leaves placeholder intact",
|
||||
pattern: "softs/${jwt:missing_claim}/*",
|
||||
expected: "softs/${jwt:missing_claim}/*",
|
||||
},
|
||||
{
|
||||
name: "non-identity prefix is not substituted",
|
||||
pattern: "foo/${custom:project_path}/*",
|
||||
expected: "foo/${custom:project_path}/*",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := expandPolicyVariables(tt.pattern, evalCtx)
|
||||
assert.Equal(t, tt.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProjectUploadPolicy reproduces the GitLab OIDC policy from issue
|
||||
// #9214 end-to-end against the policy engine, proving that jwt:project_path
|
||||
// (a non-hardcoded JWT claim) is now substituted in Resource patterns so that
|
||||
// each project only gets access under its own prefix.
|
||||
func TestGitLabProjectUploadPolicy(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
require.NoError(t, engine.Initialize(&PolicyEngineConfig{
|
||||
DefaultEffect: "Deny",
|
||||
StoreType: "memory",
|
||||
}))
|
||||
|
||||
policyDoc := &PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []Statement{
|
||||
{
|
||||
Sid: "AllowPutInOwnFolder",
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:PutObject"},
|
||||
Resource: []string{"arn:aws:s3:::softs/${jwt:project_path}/*"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
require.NoError(t, engine.AddPolicy("", "GitlabProjectUploadPolicy", policyDoc))
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
mat := map[string]interface{}{
|
||||
"jwt:project_path": "some/namespace/project",
|
||||
}
|
||||
other := map[string]interface{}{
|
||||
"jwt:project_path": "other/namespace/project",
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
action string
|
||||
resource string
|
||||
reqCtx map[string]interface{}
|
||||
want Effect
|
||||
}{
|
||||
{
|
||||
name: "user writes into own project folder - allowed",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/some/namespace/project/build.zip",
|
||||
reqCtx: mat,
|
||||
want: EffectAllow,
|
||||
},
|
||||
{
|
||||
name: "user tries to write into another project - falls through to default Deny",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/other/namespace/project/build.zip",
|
||||
reqCtx: mat,
|
||||
want: EffectDeny,
|
||||
},
|
||||
{
|
||||
name: "different user writes into their own project - allowed",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/other/namespace/project/build.zip",
|
||||
reqCtx: other,
|
||||
want: EffectAllow,
|
||||
},
|
||||
{
|
||||
name: "user tries to GetObject - only PutObject allowed, default Deny",
|
||||
action: "s3:GetObject",
|
||||
resource: "arn:aws:s3:::softs/some/namespace/project/build.zip",
|
||||
reqCtx: mat,
|
||||
want: EffectDeny,
|
||||
},
|
||||
{
|
||||
name: "missing project_path claim - placeholder prevents match, default Deny",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/some/namespace/project/build.zip",
|
||||
reqCtx: map[string]interface{}{},
|
||||
want: EffectDeny,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
evalCtx := &EvaluationContext{
|
||||
Principal: "user",
|
||||
Action: tc.action,
|
||||
Resource: tc.resource,
|
||||
RequestContext: tc.reqCtx,
|
||||
}
|
||||
|
||||
result, err := engine.Evaluate(ctx, "", evalCtx, []string{"GitlabProjectUploadPolicy"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.want, result.Effect,
|
||||
"matching statements: %+v", result.MatchingStatements)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,11 @@ const (
|
||||
|
||||
var (
|
||||
policyVariablePattern = regexp.MustCompile(`\$\{([^}]+)\}`)
|
||||
safePolicyVariables = map[string]bool{
|
||||
// safePolicyVariables is the explicit allowlist of fixed-name variables.
|
||||
// Identity claims published under jwt:/saml:/oidc: are additionally accepted
|
||||
// as dynamic variables (see isSafePolicyVariable) so that any claim from a
|
||||
// cryptographically verified federated token can be used in policies.
|
||||
safePolicyVariables = map[string]bool{
|
||||
// AWS standard identity variables
|
||||
"aws:username": true,
|
||||
"aws:userid": true,
|
||||
@@ -32,20 +36,6 @@ var (
|
||||
"aws:principaltype": true,
|
||||
"aws:FederatedProvider": true,
|
||||
"aws:PrincipalServiceName": true,
|
||||
// SAML identity variables
|
||||
"saml:username": true,
|
||||
"saml:sub": true,
|
||||
"saml:aud": true,
|
||||
"saml:iss": true,
|
||||
// OIDC/JWT identity variables
|
||||
"oidc:sub": true,
|
||||
"oidc:aud": true,
|
||||
"oidc:iss": true,
|
||||
// JWT identity variables
|
||||
"jwt:preferred_username": true,
|
||||
"jwt:sub": true,
|
||||
"jwt:iss": true,
|
||||
"jwt:aud": true,
|
||||
// AWS request context (not from headers)
|
||||
"aws:SourceIp": true,
|
||||
"aws:SecureTransport": true,
|
||||
@@ -56,6 +46,20 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
// isSafePolicyVariable reports whether a policy variable may be substituted
|
||||
// with a value from RequestContext. The fixed allowlist covers AWS-defined
|
||||
// variables; any jwt:/saml:/oidc: claim is also allowed because those come
|
||||
// from a validated identity token (the STS session JWT or federated assertion)
|
||||
// and the claim set is controlled by the trusted identity provider.
|
||||
func isSafePolicyVariable(variable string) bool {
|
||||
if safePolicyVariables[variable] {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(variable, "jwt:") ||
|
||||
strings.HasPrefix(variable, "saml:") ||
|
||||
strings.HasPrefix(variable, "oidc:")
|
||||
}
|
||||
|
||||
// PolicyEngine evaluates policies against requests
|
||||
type PolicyEngine struct {
|
||||
config *PolicyEngineConfig
|
||||
@@ -1240,25 +1244,77 @@ func expandPolicyVariables(pattern string, evalCtx *EvaluationContext) string {
|
||||
// Extract variable name from ${variable}
|
||||
variable := match[2 : len(match)-1]
|
||||
|
||||
// Only substitute if variable is in the safe allowlist
|
||||
if !safePolicyVariables[variable] {
|
||||
return match // Leave unsafe variables as-is
|
||||
// Only substitute if the variable is in the allowlist or is a dynamic
|
||||
// identity-claim variable (jwt:/saml:/oidc:)
|
||||
if !isSafePolicyVariable(variable) {
|
||||
return match // Leave unrecognised variables as-is
|
||||
}
|
||||
|
||||
// Get value from request context
|
||||
if value, exists := evalCtx.RequestContext[variable]; exists {
|
||||
if str, ok := value.(string); ok {
|
||||
return str
|
||||
}
|
||||
value, exists := evalCtx.RequestContext[variable]
|
||||
if !exists {
|
||||
return match // Variable not supplied: leave placeholder so statement won't match
|
||||
}
|
||||
|
||||
// Variable not found or not a string, leave as-is
|
||||
if str, ok := stringifyClaimValue(value); ok {
|
||||
return str
|
||||
}
|
||||
|
||||
// Value is a non-scalar (array/object) we can't meaningfully substitute
|
||||
return match
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// stringifyClaimValue converts a claim value to its string form for policy
|
||||
// variable substitution. Returns (value, true) for scalar types that a JWT
|
||||
// claim can produce after JSON decoding, and ("", false) for slices/maps/nil.
|
||||
// JSON's generic decoder only produces float64 / json.Number for numbers, but
|
||||
// RequestContext can also be populated from typed sources (e.g., custom
|
||||
// providers or internal code), so all common integer widths — signed and
|
||||
// unsigned — are handled explicitly.
|
||||
func stringifyClaimValue(value interface{}) (string, bool) {
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return v, true
|
||||
case bool:
|
||||
return strconv.FormatBool(v), true
|
||||
case float64:
|
||||
// JSON-decoded numbers are float64; render integers without a decimal point
|
||||
if v == float64(int64(v)) {
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
}
|
||||
return strconv.FormatFloat(v, 'g', -1, 64), true
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(v), 'g', -1, 32), true
|
||||
case int:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int8:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int16:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int32:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int64:
|
||||
return strconv.FormatInt(v, 10), true
|
||||
case uint:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint8:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint16:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint32:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint64:
|
||||
return strconv.FormatUint(v, 10), true
|
||||
case json.Number:
|
||||
return v.String(), true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// evaluateStringConditionIgnoreCase evaluates string conditions with case insensitivity
|
||||
func (e *PolicyEngine) evaluateStringConditionIgnoreCase(block map[string]interface{}, evalCtx *EvaluationContext, shouldMatch bool, useWildcard bool, forAllValues bool) bool {
|
||||
for key, expectedValues := range block {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package iam
|
||||
|
||||
import "net/url"
|
||||
|
||||
// sensitiveFormKeys is the set of IAM request form parameters whose values
|
||||
// must never be written to logs. Matching is case-sensitive and uses the
|
||||
// exact AWS IAM parameter name. Extend this when adding IAM actions that
|
||||
// accept credentials, passwords, session tokens, or private keys.
|
||||
var sensitiveFormKeys = map[string]struct{}{
|
||||
"SecretAccessKey": {},
|
||||
"Password": {},
|
||||
"NewPassword": {},
|
||||
"OldPassword": {},
|
||||
"PrivateKey": {},
|
||||
"SessionToken": {},
|
||||
}
|
||||
|
||||
// RedactSensitiveFormValues returns a shallow copy of values with every
|
||||
// sensitive key (see sensitiveFormKeys) replaced by "[REDACTED]". Intended
|
||||
// for debug-level logging of IAM request forms so secrets do not leak into
|
||||
// log sinks.
|
||||
func RedactSensitiveFormValues(values url.Values) url.Values {
|
||||
safe := make(url.Values, len(values))
|
||||
for k, v := range values {
|
||||
if _, sensitive := sensitiveFormKeys[k]; sensitive {
|
||||
safe[k] = []string{"[REDACTED]"}
|
||||
} else {
|
||||
safe[k] = v
|
||||
}
|
||||
}
|
||||
return safe
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRedactSensitiveFormValues(t *testing.T) {
|
||||
in := url.Values{
|
||||
"Action": []string{"CreateAccessKey"},
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"AKIAALICE1"},
|
||||
"SecretAccessKey": []string{"very-secret"},
|
||||
"Password": []string{"hunter2"},
|
||||
"NewPassword": []string{"new-hunter2"},
|
||||
"OldPassword": []string{"old-hunter2"},
|
||||
"PrivateKey": []string{"-----BEGIN-----"},
|
||||
"SessionToken": []string{"tok"},
|
||||
}
|
||||
out := RedactSensitiveFormValues(in)
|
||||
|
||||
assert.Equal(t, []string{"CreateAccessKey"}, out["Action"])
|
||||
assert.Equal(t, []string{"alice"}, out["UserName"])
|
||||
assert.Equal(t, []string{"AKIAALICE1"}, out["AccessKeyId"])
|
||||
for _, k := range []string{"SecretAccessKey", "Password", "NewPassword", "OldPassword", "PrivateKey", "SessionToken"} {
|
||||
assert.Equal(t, []string{"[REDACTED]"}, out[k], "key %q should be redacted", k)
|
||||
}
|
||||
|
||||
// Input is not mutated.
|
||||
assert.Equal(t, []string{"very-secret"}, in["SecretAccessKey"])
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
|
||||
// ValidateCallerSuppliedAccessKeyId checks that a caller-supplied AccessKeyId
|
||||
// is 4 to 128 ASCII alphanumeric characters. Returns nil if valid.
|
||||
//
|
||||
// The alphanumeric restriction avoids characters that would break SigV4
|
||||
// canonicalization (e.g. '/' and '=' appear as delimiters in Credential
|
||||
// headers), so this is a stricter superset of the rule AWS enforces.
|
||||
func ValidateCallerSuppliedAccessKeyId(accessKeyId string) error {
|
||||
if len(accessKeyId) < 4 || len(accessKeyId) > 128 {
|
||||
return fmt.Errorf("AccessKeyId must be 4 to 128 alphanumeric characters")
|
||||
}
|
||||
for _, r := range accessKeyId {
|
||||
if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')) {
|
||||
return fmt.Errorf("AccessKeyId must be 4 to 128 alphanumeric characters")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCallerSuppliedSecretAccessKey checks that a caller-supplied
|
||||
// SecretAccessKey is 8 to 128 characters. Returns nil if valid.
|
||||
func ValidateCallerSuppliedSecretAccessKey(secretAccessKey string) error {
|
||||
if len(secretAccessKey) < 8 || len(secretAccessKey) > 128 {
|
||||
return fmt.Errorf("SecretAccessKey must be between 8 and 128 characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AccessKeyOwner identifies which entity in an S3ApiConfiguration already owns
|
||||
// a given AccessKeyId. Returned by FindAccessKeyOwner for collision checks on
|
||||
// caller-supplied credentials.
|
||||
type AccessKeyOwner struct {
|
||||
// Type is "user" or "service account".
|
||||
Type string
|
||||
// Name is the identity's Name (for users) or the service account's Id.
|
||||
Name string
|
||||
}
|
||||
|
||||
// FindAccessKeyOwner scans s3cfg for an identity or service account whose
|
||||
// credentials already contain accessKeyId. Returns nil if the key is free.
|
||||
//
|
||||
// Callers should log Name only at debug level — error responses returned to
|
||||
// the caller should not include owner identity to avoid information leaks.
|
||||
func FindAccessKeyOwner(s3cfg *iam_pb.S3ApiConfiguration, accessKeyId string) *AccessKeyOwner {
|
||||
if s3cfg == nil || accessKeyId == "" {
|
||||
return nil
|
||||
}
|
||||
for _, ident := range s3cfg.Identities {
|
||||
for _, cred := range ident.Credentials {
|
||||
if cred.AccessKey == accessKeyId {
|
||||
return &AccessKeyOwner{Type: "user", Name: ident.Name}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, sa := range s3cfg.ServiceAccounts {
|
||||
if sa.Credential != nil && sa.Credential.AccessKey == accessKeyId {
|
||||
return &AccessKeyOwner{Type: "service account", Name: sa.Id}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateCallerSuppliedAccessKeyId(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty", "", true},
|
||||
{"three chars", "abc", true},
|
||||
{"four chars ok", "abcd", false},
|
||||
{"mixed case alnum", "MyAppKey123", false},
|
||||
{"128 chars ok", strings.Repeat("a", 128), false},
|
||||
{"129 chars too long", strings.Repeat("a", 129), true},
|
||||
{"slash rejected", "foo/bar", true},
|
||||
{"equals rejected", "foo=bar", true},
|
||||
{"dash rejected", "foo-bar", true},
|
||||
{"underscore rejected", "foo_bar", true},
|
||||
{"unicode rejected", "fooö123", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := ValidateCallerSuppliedAccessKeyId(tc.input)
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCallerSuppliedSecretAccessKey(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty", "", true},
|
||||
{"seven chars", "abcdefg", true},
|
||||
{"eight chars ok", "abcdefgh", false},
|
||||
{"128 chars ok", strings.Repeat("a", 128), false},
|
||||
{"129 chars too long", strings.Repeat("a", 129), true},
|
||||
{"non-alnum allowed in secret", "sec/ret=1", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := ValidateCallerSuppliedSecretAccessKey(tc.input)
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindAccessKeyOwner(t *testing.T) {
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "AKIAALICE1", SecretKey: "s"},
|
||||
},
|
||||
},
|
||||
{Name: "bob"},
|
||||
},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{
|
||||
{Id: "svc-1", Credential: &iam_pb.Credential{AccessKey: "SVCKEY1"}},
|
||||
{Id: "svc-2"},
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("matches user", func(t *testing.T) {
|
||||
owner := FindAccessKeyOwner(s3cfg, "AKIAALICE1")
|
||||
assert.NotNil(t, owner)
|
||||
assert.Equal(t, "user", owner.Type)
|
||||
assert.Equal(t, "alice", owner.Name)
|
||||
})
|
||||
t.Run("matches service account", func(t *testing.T) {
|
||||
owner := FindAccessKeyOwner(s3cfg, "SVCKEY1")
|
||||
assert.NotNil(t, owner)
|
||||
assert.Equal(t, "service account", owner.Type)
|
||||
assert.Equal(t, "svc-1", owner.Name)
|
||||
})
|
||||
t.Run("no match", func(t *testing.T) {
|
||||
assert.Nil(t, FindAccessKeyOwner(s3cfg, "NOTTAKEN"))
|
||||
})
|
||||
t.Run("empty key", func(t *testing.T) {
|
||||
assert.Nil(t, FindAccessKeyOwner(s3cfg, ""))
|
||||
})
|
||||
t.Run("nil config", func(t *testing.T) {
|
||||
assert.Nil(t, FindAccessKeyOwner(nil, "anything"))
|
||||
})
|
||||
}
|
||||
@@ -929,13 +929,38 @@ func (iama *IamApiServer) CreateAccessKey(s3cfg *iam_pb.S3ApiConfiguration, valu
|
||||
userName := values.Get("UserName")
|
||||
status := iam.StatusTypeActive
|
||||
|
||||
accessKeyId, err := StringWithCharset(21, charsetUpper)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate access key: %w", err)}
|
||||
accessKeyId := values.Get("AccessKeyId")
|
||||
secretAccessKey := values.Get("SecretAccessKey")
|
||||
if accessKeyId != "" {
|
||||
if err := iamlib.ValidateCallerSuppliedAccessKeyId(accessKeyId); err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
}
|
||||
secretAccessKey, err := StringWithCharset(42, charset)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate secret key: %w", err)}
|
||||
if secretAccessKey != "" {
|
||||
if err := iamlib.ValidateCallerSuppliedSecretAccessKey(secretAccessKey); err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
}
|
||||
if (accessKeyId != "") != (secretAccessKey != "") {
|
||||
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("AccessKeyId and SecretAccessKey must be supplied together")}
|
||||
}
|
||||
if owner := iamlib.FindAccessKeyOwner(s3cfg, accessKeyId); owner != nil {
|
||||
glog.V(4).Infof("CreateAccessKey: supplied AccessKeyId already in use by %s %s", owner.Type, owner.Name)
|
||||
return resp, &IamError{Code: iam.ErrCodeEntityAlreadyExistsException, Error: fmt.Errorf("AccessKeyId is already in use")}
|
||||
}
|
||||
if accessKeyId == "" {
|
||||
var err error
|
||||
accessKeyId, err = StringWithCharset(21, charsetUpper)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate access key: %w", err)}
|
||||
}
|
||||
}
|
||||
if secretAccessKey == "" {
|
||||
var err error
|
||||
secretAccessKey, err = StringWithCharset(42, charset)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate secret key: %w", err)}
|
||||
}
|
||||
}
|
||||
|
||||
resp.CreateAccessKeyResult.AccessKey.AccessKeyId = &accessKeyId
|
||||
@@ -1085,7 +1110,7 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
glog.V(4).Infof("DoActions: %+v", values)
|
||||
glog.V(4).Infof("DoActions: %+v", iamlib.RedactSensitiveFormValues(values))
|
||||
var response iamlib.RequestIDSetter
|
||||
changed := true
|
||||
switch r.Form.Get("Action") {
|
||||
|
||||
@@ -3,6 +3,7 @@ package iamapi
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
@@ -629,3 +630,266 @@ func TestListAttachedUserPolicies(t *testing.T) {
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeNoSuchEntityException, iamErr.Code)
|
||||
}
|
||||
|
||||
func TestCreateAccessKeyWithCallerSuppliedKeys(t *testing.T) {
|
||||
iama := newTestIamApiServer(Policies{})
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
}
|
||||
values := url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"myappkey"},
|
||||
"SecretAccessKey": []string{"mysecret1234"},
|
||||
}
|
||||
resp, iamErr := iama.CreateAccessKey(s3cfg, values)
|
||||
assert.Nil(t, iamErr)
|
||||
assert.Equal(t, "myappkey", *resp.CreateAccessKeyResult.AccessKey.AccessKeyId)
|
||||
assert.Equal(t, "mysecret1234", *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey)
|
||||
assert.Equal(t, "alice", *resp.CreateAccessKeyResult.AccessKey.UserName)
|
||||
assert.Equal(t, "myappkey", s3cfg.Identities[0].Credentials[0].AccessKey)
|
||||
assert.Equal(t, "mysecret1234", s3cfg.Identities[0].Credentials[0].SecretKey)
|
||||
}
|
||||
|
||||
func TestCreateAccessKeyRandomGeneration(t *testing.T) {
|
||||
iama := newTestIamApiServer(Policies{})
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
}
|
||||
values := url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
}
|
||||
resp, iamErr := iama.CreateAccessKey(s3cfg, values)
|
||||
assert.Nil(t, iamErr)
|
||||
assert.NotEmpty(t, *resp.CreateAccessKeyResult.AccessKey.AccessKeyId)
|
||||
assert.NotEmpty(t, *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey)
|
||||
assert.Len(t, s3cfg.Identities[0].Credentials, 1)
|
||||
}
|
||||
|
||||
func TestCreateAccessKeyRejectsWeakKeys(t *testing.T) {
|
||||
iama := newTestIamApiServer(Policies{})
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
}
|
||||
// Too short
|
||||
values := url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"ab"},
|
||||
"SecretAccessKey": []string{"validsecret1"},
|
||||
}
|
||||
_, iamErr := iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
|
||||
// Short secret
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"validkey"},
|
||||
"SecretAccessKey": []string{"short"},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
|
||||
// SigV4 delimiters
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"foo/bar=baz"},
|
||||
"SecretAccessKey": []string{"validsecret1"},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
}
|
||||
|
||||
func TestCreateAccessKeyRejectsCollision(t *testing.T) {
|
||||
iama := newTestIamApiServer(Policies{})
|
||||
// Use a distinctive owner name ("ownerAlpha") that shares no substring
|
||||
// with the expected error message so the leak assertion is meaningful.
|
||||
const ownerName = "ownerAlpha"
|
||||
|
||||
t.Run("identity credential", func(t *testing.T) {
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: ownerName,
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "takenkey", SecretKey: "existingsecret"},
|
||||
},
|
||||
},
|
||||
{Name: "newuser"},
|
||||
},
|
||||
}
|
||||
values := url.Values{
|
||||
"UserName": []string{"newuser"},
|
||||
"AccessKeyId": []string{"takenkey"},
|
||||
"SecretAccessKey": []string{"newsecret123"},
|
||||
}
|
||||
_, iamErr := iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeEntityAlreadyExistsException, iamErr.Code)
|
||||
assert.NotContains(t, iamErr.Error.Error(), ownerName, "should not leak owner name")
|
||||
assert.Len(t, s3cfg.Identities[1].Credentials, 0)
|
||||
})
|
||||
|
||||
t.Run("service account credential", func(t *testing.T) {
|
||||
const saId = "svcAlpha"
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{Name: "newuser"},
|
||||
},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{
|
||||
{
|
||||
Id: saId,
|
||||
Credential: &iam_pb.Credential{AccessKey: "takenkey", SecretKey: "existingsecret"},
|
||||
},
|
||||
},
|
||||
}
|
||||
values := url.Values{
|
||||
"UserName": []string{"newuser"},
|
||||
"AccessKeyId": []string{"takenkey"},
|
||||
"SecretAccessKey": []string{"newsecret123"},
|
||||
}
|
||||
_, iamErr := iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeEntityAlreadyExistsException, iamErr.Code)
|
||||
assert.NotContains(t, iamErr.Error.Error(), saId, "should not leak owner id")
|
||||
// The service account's existing credential must be untouched, and
|
||||
// no new credential should be attached to the identity.
|
||||
assert.Equal(t, "takenkey", s3cfg.ServiceAccounts[0].Credential.AccessKey)
|
||||
assert.Equal(t, "existingsecret", s3cfg.ServiceAccounts[0].Credential.SecretKey)
|
||||
assert.Len(t, s3cfg.Identities[0].Credentials, 0)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateAccessKeyBoundary(t *testing.T) {
|
||||
iama := newTestIamApiServer(Policies{})
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
}
|
||||
// Exactly 4 chars - should pass
|
||||
values := url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"abcd"},
|
||||
"SecretAccessKey": []string{"secretkey123"},
|
||||
}
|
||||
resp, iamErr := iama.CreateAccessKey(s3cfg, values)
|
||||
assert.Nil(t, iamErr)
|
||||
assert.Equal(t, "abcd", *resp.CreateAccessKeyResult.AccessKey.AccessKeyId)
|
||||
|
||||
// Exactly 3 chars - should fail
|
||||
s3cfg.Identities[0].Credentials = nil
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"abc"},
|
||||
"SecretAccessKey": []string{"secretkey123"},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
|
||||
// Exactly 128 chars - should pass
|
||||
s3cfg.Identities[0].Credentials = nil
|
||||
ak128 := strings.Repeat("a", 128)
|
||||
sk128 := strings.Repeat("s", 128)
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{ak128},
|
||||
"SecretAccessKey": []string{sk128},
|
||||
}
|
||||
resp, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.Nil(t, iamErr)
|
||||
assert.Equal(t, ak128, *resp.CreateAccessKeyResult.AccessKey.AccessKeyId)
|
||||
assert.Equal(t, sk128, *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey)
|
||||
|
||||
// 129 chars AccessKeyId - should fail
|
||||
s3cfg.Identities[0].Credentials = nil
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{strings.Repeat("a", 129)},
|
||||
"SecretAccessKey": []string{sk128},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
|
||||
// 7-char SecretAccessKey - should fail
|
||||
s3cfg.Identities[0].Credentials = nil
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"validkey"},
|
||||
"SecretAccessKey": []string{"1234567"},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
|
||||
// Exactly 8-char SecretAccessKey - should pass (lower boundary)
|
||||
s3cfg.Identities[0].Credentials = nil
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"validkey"},
|
||||
"SecretAccessKey": []string{"12345678"},
|
||||
}
|
||||
resp, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.Nil(t, iamErr)
|
||||
assert.Equal(t, "12345678", *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey)
|
||||
|
||||
// 129-char SecretAccessKey - should fail
|
||||
s3cfg.Identities[0].Credentials = nil
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"validkey"},
|
||||
"SecretAccessKey": []string{strings.Repeat("s", 129)},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
}
|
||||
|
||||
func TestCreateAccessKeyRejectsPartialSupply(t *testing.T) {
|
||||
iama := newTestIamApiServer(Policies{})
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
}
|
||||
// AccessKeyId supplied, SecretAccessKey omitted
|
||||
values := url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"myappkey"},
|
||||
}
|
||||
_, iamErr := iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
assert.Len(t, s3cfg.Identities[0].Credentials, 0)
|
||||
|
||||
// SecretAccessKey supplied, AccessKeyId omitted
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"SecretAccessKey": []string{"secretkey123"},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
assert.Len(t, s3cfg.Identities[0].Credentials, 0)
|
||||
|
||||
// Partial supply wins over collision: only AccessKeyId supplied, and
|
||||
// it matches an existing credential. We must see InvalidInput, not
|
||||
// EntityAlreadyExists — the both-or-none rule is more fundamental.
|
||||
s3cfg = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "ownerAlpha",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "takenkey", SecretKey: "s"},
|
||||
},
|
||||
},
|
||||
{Name: "alice"},
|
||||
},
|
||||
}
|
||||
values = url.Values{
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"takenkey"},
|
||||
}
|
||||
_, iamErr = iama.CreateAccessKey(s3cfg, values)
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, iamErr.Code)
|
||||
}
|
||||
@@ -583,7 +583,15 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, fuse.Status)
|
||||
// our IsDirectoryCached check and FindEntry (e.g. markDirectoryReadThrough).
|
||||
// If it's no longer cached, fall through to the filer lookup below.
|
||||
if wfs.metaCache.IsDirectoryCached(dirPath) {
|
||||
glog.V(4).Infof("lookupEntry cache miss (dir cached) %s", fullpath)
|
||||
// If the kernel is still tracking this path's inode, the entry
|
||||
// was known to exist recently; a cached-dir miss here suggests
|
||||
// metaCache/parent-cache coherence drift. Log visibly so the
|
||||
// next occurrence shows up in mount.log without -v=4.
|
||||
if _, inodeFound := wfs.inodeToPath.GetInode(fullpath); inodeFound {
|
||||
glog.Warningf("lookupEntry: %s missing from cache while parent %s is cached; inode still tracked (possible coherence bug)", fullpath, dirPath)
|
||||
} else {
|
||||
glog.V(4).Infof("lookupEntry cache miss (dir cached) %s", fullpath)
|
||||
}
|
||||
return nil, fuse.ENOENT
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@ import (
|
||||
|
||||
func (wfs *WFS) Lookup(cancel <-chan struct{}, header *fuse.InHeader, name string, out *fuse.EntryOut) (code fuse.Status) {
|
||||
|
||||
if s := checkName(name); s != fuse.OK {
|
||||
var s fuse.Status
|
||||
if name, s = checkName(name); s != fuse.OK {
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,8 @@ func (wfs *WFS) Mkdir(cancel <-chan struct{}, in *fuse.MkdirIn, name string, out
|
||||
return fuse.Status(syscall.ENOSPC)
|
||||
}
|
||||
|
||||
if s := checkName(name); s != fuse.OK {
|
||||
var s fuse.Status
|
||||
if name, s = checkName(name); s != fuse.OK {
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -65,7 +66,12 @@ func (wfs *WFS) Mkdir(cancel <-chan struct{}, in *fuse.MkdirIn, name string, out
|
||||
// explicitly below instead of using defer so the kernel gets local values.
|
||||
|
||||
request := &filer_pb.CreateEntryRequest{
|
||||
Directory: string(dirFullPath),
|
||||
// Defensive: dirFullPath is clean by construction for mount-originated
|
||||
// mutations, but could carry invalid-UTF-8 bytes if metaCache was
|
||||
// populated from a non-gRPC source (direct store write, legacy import).
|
||||
// Sanitizing here keeps the marshal strictly per-request on the off
|
||||
// chance invalid bytes do reach us.
|
||||
Directory: dirFullPath.Sanitized(),
|
||||
Entry: newEntry,
|
||||
Signatures: []int32{wfs.signature},
|
||||
SkipCheckParentDirectory: true,
|
||||
@@ -124,6 +130,9 @@ func (wfs *WFS) Rmdir(cancel <-chan struct{}, header *fuse.InHeader, name string
|
||||
return fuse.Status(syscall.ENOTEMPTY)
|
||||
}
|
||||
|
||||
// Sanitize before it reaches DeleteEntryRequest.Name; see sanitizeFuseName.
|
||||
name = sanitizeFuseName(name)
|
||||
|
||||
dirFullPath, code := wfs.inodeToPath.GetPath(header.NodeId)
|
||||
if code != fuse.OK {
|
||||
return
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package mount
|
||||
|
||||
import "github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
import (
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
/**
|
||||
* Open a file
|
||||
@@ -133,6 +136,17 @@ func (wfs *WFS) invalidateOpenMtimeCache(inode uint64) {
|
||||
}
|
||||
|
||||
func (wfs *WFS) Release(cancel <-chan struct{}, in *fuse.ReleaseIn) {
|
||||
// Flush is usually sent before Release, but the FUSE protocol does not
|
||||
// guarantee it. Route every Release through doFlush so a dirty handle
|
||||
// (e.g. a deferred create with no intervening Flush) is not dropped.
|
||||
// doFlush itself inspects dirtyMetadata / asyncFlushPending and fast-paths
|
||||
// the clean case, so the duplicate call after a normal Flush is cheap.
|
||||
if fh := wfs.GetHandle(FileHandleId(in.Fh)); fh != nil {
|
||||
allowAsync := in.ReleaseFlags&fuse.FUSE_RELEASE_FLOCK_UNLOCK == 0
|
||||
if status := wfs.doFlush(fh, in.Uid, in.Gid, allowAsync); status != fuse.OK {
|
||||
glog.Warningf("release fh %d inode %d: fallback flush failed: %v", in.Fh, in.NodeId, status)
|
||||
}
|
||||
}
|
||||
if in.ReleaseFlags&fuse.FUSE_RELEASE_FLOCK_UNLOCK != 0 {
|
||||
wfs.posixLocks.ReleaseFlockOwner(in.NodeId, in.LockOwner)
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ import (
|
||||
* will be called instead.
|
||||
*/
|
||||
func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, out *fuse.CreateOut) (code fuse.Status) {
|
||||
if s := checkName(name); s != fuse.OK {
|
||||
var s fuse.Status
|
||||
if name, s = checkName(name); s != fuse.OK {
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -140,7 +141,8 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
*/
|
||||
func (wfs *WFS) Mknod(cancel <-chan struct{}, in *fuse.MknodIn, name string, out *fuse.EntryOut) (code fuse.Status) {
|
||||
|
||||
if s := checkName(name); s != fuse.OK {
|
||||
var s fuse.Status
|
||||
if name, s = checkName(name); s != fuse.OK {
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -167,6 +169,9 @@ func (wfs *WFS) Mknod(cancel <-chan struct{}, in *fuse.MknodIn, name string, out
|
||||
/** Remove a file */
|
||||
func (wfs *WFS) Unlink(cancel <-chan struct{}, header *fuse.InHeader, name string) (code fuse.Status) {
|
||||
|
||||
// Sanitize before it reaches DeleteEntryRequest.Name; see sanitizeFuseName.
|
||||
name = sanitizeFuseName(name)
|
||||
|
||||
dirFullPath, code := wfs.inodeToPath.GetPath(header.NodeId)
|
||||
if code != fuse.OK {
|
||||
if code == fuse.ENOENT {
|
||||
@@ -251,7 +256,8 @@ func (wfs *WFS) Unlink(cancel <-chan struct{}, header *fuse.InHeader, name strin
|
||||
// Always let the filer decide whether to delete chunks based on its authoritative data.
|
||||
// The filer has the correct hard link count and will only delete chunks when appropriate.
|
||||
deleteReq := &filer_pb.DeleteEntryRequest{
|
||||
Directory: string(dirFullPath),
|
||||
// See weedfs_dir_mkrm.go Mkdir for why Directory is sanitized.
|
||||
Directory: dirFullPath.Sanitized(),
|
||||
Name: name,
|
||||
IsDeleteData: true,
|
||||
Signatures: []int32{wfs.signature},
|
||||
|
||||
@@ -110,10 +110,10 @@ func newCreateTestWFS(t *testing.T) (*WFS, *createEntryTestServer) {
|
||||
}
|
||||
|
||||
wfs := &WFS{
|
||||
option: option,
|
||||
signature: 1,
|
||||
inodeToPath: NewInodeToPath(root, 0),
|
||||
fhMap: NewFileHandleToInode(),
|
||||
option: option,
|
||||
signature: 1,
|
||||
inodeToPath: NewInodeToPath(root, 0),
|
||||
fhMap: NewFileHandleToInode(),
|
||||
fhLockTable: util.NewLockTable[FileHandleId](),
|
||||
hardLinkLockTable: util.NewLockTable[string](),
|
||||
}
|
||||
@@ -204,6 +204,53 @@ func TestCreateCreatesAndOpensFile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseFlushesDirtyCreateIfFlushWasSkipped(t *testing.T) {
|
||||
wfs, testServer := newCreateTestWFS(t)
|
||||
|
||||
out := &fuse.CreateOut{}
|
||||
status := wfs.Create(make(chan struct{}), &fuse.CreateIn{
|
||||
InHeader: fuse.InHeader{
|
||||
NodeId: 1,
|
||||
Caller: fuse.Caller{
|
||||
Owner: fuse.Owner{
|
||||
Uid: 123,
|
||||
Gid: 456,
|
||||
},
|
||||
},
|
||||
},
|
||||
Flags: syscall.O_WRONLY | syscall.O_CREAT,
|
||||
Mode: 0o640,
|
||||
}, "release_flush.txt", out)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("Create status = %v, want OK", status)
|
||||
}
|
||||
|
||||
wfs.Release(make(chan struct{}), &fuse.ReleaseIn{
|
||||
InHeader: fuse.InHeader{
|
||||
NodeId: out.NodeId,
|
||||
Caller: fuse.Caller{Owner: fuse.Owner{Uid: 123, Gid: 456}},
|
||||
},
|
||||
Fh: out.Fh,
|
||||
})
|
||||
|
||||
snapshot := testServer.snapshot()
|
||||
if snapshot.directory != "/" {
|
||||
t.Fatalf("CreateEntry directory = %q, want %q", snapshot.directory, "/")
|
||||
}
|
||||
if snapshot.name != "release_flush.txt" {
|
||||
t.Fatalf("CreateEntry name = %q, want %q", snapshot.name, "release_flush.txt")
|
||||
}
|
||||
if snapshot.uid != 123 || snapshot.gid != 456 {
|
||||
t.Fatalf("CreateEntry uid/gid = %d/%d, want 123/456", snapshot.uid, snapshot.gid)
|
||||
}
|
||||
if snapshot.mode != 0o640 {
|
||||
t.Fatalf("CreateEntry mode = %o, want %o", snapshot.mode, 0o640)
|
||||
}
|
||||
if fh := wfs.GetHandle(FileHandleId(out.Fh)); fh != nil {
|
||||
t.Fatal("Release should remove the file handle after fallback flush")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateEntryClearsDirtyPagesForOpenHandle(t *testing.T) {
|
||||
wfs, _ := newCreateTestWFS(t)
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ func (wfs *WFS) Link(cancel <-chan struct{}, in *fuse.LinkIn, name string, out *
|
||||
return fuse.Status(syscall.ENOSPC)
|
||||
}
|
||||
|
||||
if s := checkName(name); s != fuse.OK {
|
||||
var s fuse.Status
|
||||
if name, s = checkName(name); s != fuse.OK {
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
@@ -169,7 +169,12 @@ func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string
|
||||
return fuse.Status(syscall.ENOSPC)
|
||||
}
|
||||
|
||||
if s := checkName(newName); s != fuse.OK {
|
||||
// Both names end up in StreamRenameEntryRequest (proto string fields), so
|
||||
// sanitize both. checkName handles newName's length check; oldName may
|
||||
// legitimately be a pre-existing entry whose bytes were not validated.
|
||||
oldName = sanitizeFuseName(oldName)
|
||||
var s fuse.Status
|
||||
if newName, s = checkName(newName); s != fuse.OK {
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ func (wfs *WFS) Symlink(cancel <-chan struct{}, header *fuse.InHeader, target st
|
||||
if wfs.IsOverQuotaWithUncommitted() {
|
||||
return fuse.Status(syscall.ENOSPC)
|
||||
}
|
||||
if s := checkName(name); s != fuse.OK {
|
||||
var s fuse.Status
|
||||
if name, s = checkName(name); s != fuse.OK {
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,13 @@ import (
|
||||
|
||||
func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFunctionType {
|
||||
|
||||
// Backstop: FUSE entry points sanitize names before they reach
|
||||
// inodeToPath, but async flush paths (e.g. writebackCache, handles whose
|
||||
// RememberPath was set from an older code path) may still carry bytes
|
||||
// that predate sanitization. Proto3 string fields require valid UTF-8,
|
||||
// so scrub the full path once here before every AssignVolume call.
|
||||
assignPath := fullPath.Sanitized()
|
||||
|
||||
return func(reader io.Reader, filename string, offset int64, tsNs int64, _ uint64) (chunk *filer_pb.FileChunk, err error) {
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
@@ -43,7 +50,7 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
|
||||
TtlSec: wfs.option.TtlSec,
|
||||
DiskType: string(wfs.option.DiskType),
|
||||
DataCenter: wfs.option.DataCenter,
|
||||
Path: string(fullPath),
|
||||
Path: assignPath,
|
||||
},
|
||||
uploadOption, genFileUrlFn, reader,
|
||||
)
|
||||
|
||||
+20
-3
@@ -76,12 +76,29 @@ func (wfs *WFS) mapPbIdFromLocalToFiler(entry *filer_pb.Entry) {
|
||||
entry.Attributes.Uid, entry.Attributes.Gid = wfs.option.UidGidMapper.LocalToFiler(entry.Attributes.Uid, entry.Attributes.Gid)
|
||||
}
|
||||
|
||||
func checkName(name string) fuse.Status {
|
||||
// sanitizeFuseName scrubs a name arriving from the kernel before it is placed
|
||||
// in a proto string field. Linux (and macOS) pass raw bytes for filenames;
|
||||
// apps like GNOME Trash produce partial files whose names contain binary
|
||||
// payloads. Proto3 `string` fields require valid UTF-8, so an unsanitized
|
||||
// name causes gRPC to fail the whole AssignVolume / CreateEntry / DeleteEntry
|
||||
// RPC with "grpc: error while marshaling: string field contains invalid
|
||||
// UTF-8", which surfaces to userspace as EIO. Sanitizing at every FUSE
|
||||
// boundary keeps filer RPCs marshalable and prevents a single ill-named file
|
||||
// from poisoning the shared gRPC channel for every other in-flight request.
|
||||
//
|
||||
// Delegates to util.SanitizeUTF8Name so the replacement character is chosen
|
||||
// in exactly one place across the codebase.
|
||||
func sanitizeFuseName(name string) string {
|
||||
return util.SanitizeUTF8Name(name)
|
||||
}
|
||||
|
||||
func checkName(name string) (string, fuse.Status) {
|
||||
name = sanitizeFuseName(name)
|
||||
// The Linux FUSE kernel module enforces NAME_MAX=255 at the VFS layer.
|
||||
// Return ENAMETOOLONG early to avoid creating entries that cannot be
|
||||
// looked up via normal syscalls (stat, chmod, etc.).
|
||||
if len(name) > 255 {
|
||||
return fuse.Status(syscall.ENAMETOOLONG)
|
||||
return name, fuse.Status(syscall.ENAMETOOLONG)
|
||||
}
|
||||
return fuse.OK
|
||||
return name, fuse.OK
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
)
|
||||
|
||||
// TestSanitizeFuseName_InvalidBytesReplaced reproduces the filename from
|
||||
// seaweedfs#9139: GNOME Trash "partial" files carry raw binary bytes
|
||||
// (\x10\x98=\\\x8a\x7f) that are not valid UTF-8. The sanitizer must return a
|
||||
// UTF-8-valid string so the subsequent proto marshal cannot fail.
|
||||
func TestSanitizeFuseName_InvalidBytesReplaced(t *testing.T) {
|
||||
raw := "\x10\x98=\\\x8a\x7f.trashinfo.9a51454f.partial"
|
||||
out := sanitizeFuseName(raw)
|
||||
if !utf8.ValidString(out) {
|
||||
t.Fatalf("sanitizeFuseName returned non-UTF-8: %q", out)
|
||||
}
|
||||
// The replacement must be URL-safe: these sanitized names flow into HTTP
|
||||
// URLs (volume-server uploads, filer HTTP API, S3/WebDAV gateways), so a
|
||||
// '?' would be interpreted as the query-string delimiter and split the
|
||||
// path. Explicitly assert the replacement char is neither '?' nor U+FFFD.
|
||||
if strings.ContainsRune(out, '?') {
|
||||
t.Fatalf("sanitizer produced non-URL-safe '?' in %q", out)
|
||||
}
|
||||
if strings.ContainsRune(out, 0xFFFD) {
|
||||
t.Fatalf("expected single-byte replacement, got U+FFFD in %q", out)
|
||||
}
|
||||
// Valid bytes (\x10, \x3D '=', \x5C '\\', \x7F) must be preserved; only
|
||||
// \x98 and \x8A — the standalone continuation bytes — get replaced.
|
||||
if !strings.HasSuffix(out, ".trashinfo.9a51454f.partial") {
|
||||
t.Fatalf("trailing valid bytes were dropped: %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeFuseName_PassThroughValidUTF8(t *testing.T) {
|
||||
// An already-valid UTF-8 string must be returned unchanged — no heap
|
||||
// allocation, no alteration of byte content. Preserving identity matters
|
||||
// because the overwhelming hot path is valid input.
|
||||
for _, s := range []string{
|
||||
"plain.txt",
|
||||
"日本語.txt",
|
||||
"🦑 squid",
|
||||
"",
|
||||
strings.Repeat("a", 255),
|
||||
} {
|
||||
if got := sanitizeFuseName(s); got != s {
|
||||
t.Fatalf("sanitizeFuseName(%q) = %q, want unchanged", s, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckName_SanitizesBeforeLengthCheck verifies the caller contract: the
|
||||
// returned name is always safe to put into a proto string field, and the
|
||||
// length guard still fires on over-long inputs.
|
||||
func TestCheckName_SanitizesBeforeLengthCheck(t *testing.T) {
|
||||
bad := "foo\x80bar"
|
||||
got, s := checkName(bad)
|
||||
if s != fuse.OK {
|
||||
t.Fatalf("checkName(%q) status = %v, want OK", bad, s)
|
||||
}
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatalf("checkName did not sanitize: %q", got)
|
||||
}
|
||||
|
||||
tooLong := strings.Repeat("x", 300)
|
||||
if _, s := checkName(tooLong); s != fuse.Status(syscall.ENAMETOOLONG) {
|
||||
t.Fatalf("checkName length guard lost: status=%v", s)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user