Compare commits

..
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 19af53a363 terraform/provider: make the unknown endpoint test check the unknown-setting error
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:03:54 -08:00
Chris LuandClaude Opus 5.5 ae14b2b27e terraform/provider: say the smoke test runs the version the chart deploys
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:03:44 -08:00
Chris LuandClaude Opus 5.5 91d7746ae4 terraform/provider: restore the BucketOwner-only note on the request payment resource
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:03:38 -08:00
Chris LuandClaude Opus 5.5 9123cccb65 terraform/provider: treat omitted public access block flags as false when comparing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:03:11 -08:00
Chris LuandClaude Opus 5.5 0add6aa830 terraform/provider: point BucketAlreadyExists on bucket create to terraform import
SeaweedFS answers BucketAlreadyExists both for another identity's bucket
and for the caller's own bucket that has an ACL, so the create cannot
adopt it safely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:02:47 -08:00
Chris LuandClaude Opus 5.5 d44b8be5d7 terraform/provider: do not adopt an IAM user found after a failed CreateUser attempt
A retry that hits EntityAlreadyExists cannot tell whether the failed
attempt or another client created the user, so ask for an import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:59:53 -08:00
Chris LuandClaude Opus 5.5 05ebcbbe03 terraform/provider: stop on any uncertain CreateAccessKey failure and name the keys it left
Only NoSuchEntity (user not visible yet) is retried. Any other failure,
including cancellation and a failure on the last attempt, lists the
user's keys once more and reports the new ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:59:35 -08:00
Chris LuandClaude Opus 5.5 af41b25e77 terraform/provider: document import IDs and the object lock versioning destroy case
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:26:01 -08:00
Chris LuandClaude Opus 5.5 751c0ce99c terraform/provider: reject an explicitly empty compaction strategy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:25:29 -08:00
Chris LuandClaude Opus 5.5 e419cc2888 terraform/provider: keep a created S3 Tables object in state when its cleanup fails
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:25:14 -08:00
Chris LuandClaude Opus 5.5 a3eb844ca5 terraform/provider: do not replace a table when only metadata formatting differs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:24:36 -08:00
Chris LuandClaude Opus 5.5 af6ba0fcc4 terraform/provider: compare table metadata with the server's omitted required=false
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:24:02 -08:00
Chris LuandClaude Opus 5.5 f9c95a9add terraform/provider: reject an empty namespace or name for a table policy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:23:31 -08:00
Chris LuandClaude Opus 5.5 b55016fa4a terraform/provider: keep an empty OIDC list as a known empty set
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:23:11 -08:00
Chris LuandClaude Opus 5.5 943db98861 terraform/provider: reject empty or padded OIDC client IDs, thumbprints and URL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:23:04 -08:00
Chris LuandClaude Opus 5.5 08fce91408 terraform/provider: add new group members before removing old ones
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:22:41 -08:00
Chris LuandClaude Opus 5.5 58f480b252 terraform/provider: stop retrying CreateAccessKey when a failed attempt left a key
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:22:22 -08:00
Chris LuandClaude Opus 5.5 d65ca4462c terraform/provider: keep a configured expiration that names the same instant
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:21:49 -08:00
Chris LuandClaude Opus 5.5 53dd95db12 terraform/provider: resend a service account expiration only when it changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:21:46 -08:00
Chris LuandClaude Opus 5.5 f283b55063 terraform/provider: keep omitted role settings so a trust policy change updates in place
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:20:57 -08:00
Chris LuandClaude Opus 5.5 e2acfabb00 terraform/provider: refuse to adopt an existing IAM user unless a retried create made it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:20:54 -08:00
Chris LuandClaude Opus 5.5 63cc1f3848 terraform/provider: treat empty and absent lists alike when comparing bucket configuration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:20:11 -08:00
Chris LuandClaude Opus 5.5 ed5ef96d35 terraform/provider: report bucket configuration settings SeaweedFS did not store
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:20:01 -08:00
Chris LuandClaude Opus 5.5 8c0c08bd06 terraform/provider: clear tags of an adopted bucket when the config sets none
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:19:20 -08:00
Chris LuandClaude Opus 5.5 607f1c9d4b terraform/provider: do not adopt a bucket owned by another identity
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:19:18 -08:00
Chris LuandClaude Opus 5.5 7c2501f44c terraform/provider: reject unknown provider settings instead of using the environment
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:18:57 -08:00
Chris LuandClaude Opus 5.5 6d8903236e terraform/provider: compare single statements, empty Sid and scalar conditions canonically
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:18:31 -08:00
Chris LuandClaude Opus 5.5 80aeefaec0 terraform/provider: keep large JSON numbers exact when normalizing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:18:29 -08:00
Chris LuandClaude Opus 5.5 fae64ed81e terraform/provider: make the smoke test and local build portable
Use the in-repo chart by default and check it before touching the
cluster, bind the port-forward to 127.0.0.1 and fail when it does not
start, build from the module directory, and point dev_overrides at the
directory holding the binary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:17:49 -08:00
Chris LuandClaude Opus 5.5 fbd11378cb terraform/provider: use the root IAM path in the full example
The user resource accepts only "/", so the example failed at user
creation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:49:03 -08:00
Chris LuandClaude Opus 5.5 498e071c56 terraform/provider: keep service account settings left out of the config
description, expiration and status are optional and computed, so a
change to another attribute planned them as unknown and Update sent
empty values. SeaweedFS reads an empty Expiration as "never expires".
Carry the prior state forward for unknown values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:48:52 -08:00
Chris LuandClaude Opus 5.5 2374de1883 terraform/provider: read IAM policy documents without query unescaping
SeaweedFS returns user, group and managed policy documents as raw JSON
and role trust policies path-escaped. Query unescaping turned a "+" in a
resource into a space and failed on a literal "%". Return valid JSON as
is and path-unescape anything else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:48:29 -08:00
Chris LuandClaude Opus 5.5 654aab49dd terraform/provider: keep configured JSON in state after apply
Bucket, group, managed and S3 Tables policies stored the compacted JSON
sent to the server, so a policy written as a heredoc or with file()
failed apply with an inconsistent result. Keep the planned string, and
keep configured table metadata while the server's copy is semantically
equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:47:56 -08:00
Chris LuandClaude Opus 5.5 4da7268362 terraform: vet and unit-test the provider in CI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:41:19 -08:00
Chris LuandClaude Opus 5.5 a63c809c47 terraform/provider: build and test in-tree
Drop the standalone repo's release and git-hook instructions, credit the
original author, and list the provider in the terraform layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:41:18 -08:00
Chris LuandClaude Opus 5.5 0ea30aa456 terraform/provider: import the SeaweedFS Terraform provider
Import terraform-provider-seaweedfs by Luís Costa (MIT) as a nested Go
module. It manages S3 buckets and their configuration (tags, CORS,
lifecycle, versioning, policy, encryption, public access block,
ownership controls, request payment, quota), IAM users, access keys,
groups, roles, policies, attachments, OIDC providers and service
accounts, and S3 Tables buckets, namespaces, tables, policies and
maintenance configuration.

The module path and the provider source address move to seaweedfs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:40:59 -08:00
105 changed files with 11926 additions and 1846 deletions

No files matched your search

+20
View File
@@ -56,6 +56,26 @@ jobs:
tofu -chdir="$ex" validate
done
provider:
name: provider build, vet and unit tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: terraform/provider/go.mod
cache-dependency-path: terraform/provider/go.sum
- name: vet
working-directory: terraform/provider
run: go vet ./...
- name: unit tests
working-directory: terraform/provider
run: go test -race ./...
smoke:
name: local cluster smoke test (real weed)
runs-on: ubuntu-latest
+1042 -1030
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 54 KiB

@@ -13,7 +13,6 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
@@ -50,11 +49,11 @@ func TestMasterImportPersistenceFailureExitsAndRecovers(t *testing.T) {
cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep))
out, runErr := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
t.Fatalf("master did not fail-stop with exit74: %v context=%v\n%s", runErr, ctx.Err(), out)
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != 1 {
t.Fatalf("master did not fail-stop with exit1: %v context=%v\n%s", runErr, ctx.Err(), out)
}
text := string(out)
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "reason=lifecycle_persist_failed") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
t.Fatalf("missing single persistence ERROR: %s", text)
}
oldRaw, err := json.Marshal(old)
@@ -26,13 +26,6 @@ import (
// refuses an interval above half the freshness window (a longer loop gap
// reads as the master's own pause), so the window is 60 s: the dead
// primary's loss then comes at most a window after its last report.
//
// The failover is predicted within gapLoop + gapWindow + gapLoop of the
// kill: the tick that ends creation comes at most a loop after it, the
// loss a window after that tick's silence floor, and the tick that reads
// the loss at most a loop later. The test waits twice that.
const gapLoop, gapWindow = 30 * time.Second, 60 * time.Second
func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
bins := buildG54Binaries(t)
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
@@ -55,8 +48,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
}
master := h.start(t, "blockmaster", bins.master,
"--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", gapLoop.String(),
"--freshness-window", gapWindow.String(), "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s",
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
for _, b := range hosts {
lockDir := b.root + ".locks"
@@ -91,8 +84,7 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
// 3. The next tick reads the survivors' write: creation ended, and the
// gate fails the volume over.
var p2 *host
predicted := gapLoop + gapWindow + gapLoop
poll(t, 2*predicted, fmt.Sprintf("no survivor became primary at epoch 2 within %v, twice the predicted %v (the volume held as creating, or the gate's replace not acted on: see the master's 'decision=replace' lines)", 2*predicted, predicted), func() bool {
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
for _, b := range survivors {
if statusIsPrimaryAt(b.status, 2) {
p2 = b
@@ -32,9 +32,8 @@ func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) {
// non-nil error replaces that step's result. Tests only.
var dirFault atomic.Pointer[func(step string) error]
// ExitDurabilityUnknown is the process exit code of a fail-stop whose
// persisted outcome is unknown (sysexits EX_IOERR): an authority record's
// rename here, or blockmaster's lifecycle store persistence failure.
// ExitDurabilityUnknown is the process exit code of the fail-stop after a
// record's rename whose durability is unknown (sysexits EX_IOERR).
const ExitDurabilityUnknown = 74
// failStopDurabilityUnknown ends the process: the rename is done but the
+25 -102
View File
@@ -32,7 +32,6 @@ type TopologyController struct {
unsupported map[string]UnsupportedEvidence
convergenceStuck map[string]*ConvergenceStuckEvidence
bootGrace map[string]*primaryBootGrace // volume/replica -> current incarnation's grace
outcome map[string]string // volume -> what the last intake did with it (LastOutcome); kept like bootGrace
now func() time.Time
}
@@ -45,21 +44,10 @@ func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasi
unsupported: make(map[string]UnsupportedEvidence),
convergenceStuck: make(map[string]*ConvergenceStuckEvidence),
bootGrace: make(map[string]*primaryBootGrace),
outcome: make(map[string]string),
now: time.Now,
}
}
// LastOutcome says what the last snapshot intake that carried the volume
// as supported did with it: the ask it enqueued, or why it enqueued none
// ("" before any). The master logs it beside a promotion gate's replace
// decision, so a decision the controller did not act on says why.
func (c *TopologyController) LastOutcome(volumeID string) string {
c.mu.Lock()
defer c.mu.Unlock()
return c.outcome[volumeID]
}
// SetNowForTest overrides the controller's clock source. Tests
// use this to drive RetryWindow / Stuck transitions deterministically.
// Production code MUST NOT call this.
@@ -137,21 +125,6 @@ func (c *TopologyController) SubmitClusterSnapshot(snap ClusterSnapshot) error {
// desired state live; SubmitObservedState always processes the
// report.
func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error {
return c.submitObservedState(snap, report, nil)
}
// SubmitObservedStateOutcomes is SubmitObservedState that also returns what
// this intake did with each volume it carried (supported, pending or
// unsupported), read while the intake still holds the controller's lock: a
// later intake (the background observation host shares the controller)
// cannot change it. A volume this intake did not carry has no entry.
func (c *TopologyController) SubmitObservedStateOutcomes(snap ClusterSnapshot, report SupportabilityReport) (map[string]string, error) {
out := map[string]string{}
err := c.submitObservedState(snap, report, out)
return out, err
}
func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report SupportabilityReport, outcomes map[string]string) error {
// Validate non-empty supported snapshots the same way
// SubmitClusterSnapshot does. Empty supported + empty report
// is allowed (no-op).
@@ -190,7 +163,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
// stale unsupported record from a prior build is cleared,
// because pending is a transitional state, not a fault.
delete(c.unsupported, vid)
c.outcome[vid] = "no ask: supportability pending"
}
for vid, ev := range report.Unsupported {
c.clearDesiredLocked(vid)
@@ -208,7 +180,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
Basis: AuthorityBasis{},
Reason: joinReasons(ev.Reasons),
}
c.outcome[vid] = "no ask: unsupported: " + joinReasons(ev.Reasons)
}
// Process supported volumes via the existing decision path.
@@ -225,17 +196,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
currentLine, hasLine := c.reader.VolumeAuthorityLine(vol.VolumeID)
c.processSupportedVolumeLocked(vol, snap, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
}
if outcomes != nil {
for vid := range report.Pending {
outcomes[vid] = c.outcome[vid]
}
for vid := range report.Unsupported {
outcomes[vid] = c.outcome[vid]
}
for _, vol := range volumes {
outcomes[vol.VolumeID] = c.outcome[vol.VolumeID]
}
}
return nil
}
@@ -292,13 +252,11 @@ func (c *TopologyController) processSupportedVolumeLocked(
if vol.Authority.Assigned && !volumeIncludesReplica(vol, vol.Authority.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, vol.Authority, "snapshot authority outside accepted topology: "+vol.Authority.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: snapshot authority outside accepted topology"
return
}
if hasLine && !volumeIncludesReplica(vol, currentLine.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, currentLine, "publisher authority on replica outside accepted topology: "+currentLine.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: publisher authority outside accepted topology"
return
}
@@ -311,44 +269,24 @@ func (c *TopologyController) processSupportedVolumeLocked(
// Stale snapshot: do not emit from a stale basis, but keep any
// existing desired (publish-until-observed convergence record).
if !basisMatchesLine(vol.Authority, currentLine, hasLine) {
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: stale snapshot basis %s@%d, line %s@%d", vol.Authority.ReplicaID, vol.Authority.Epoch, currentLine.ReplicaID, currentLine.Epoch)
return
}
// Stale slot facts: likewise keep any existing desired and emit
// nothing from this snapshot.
if staleFacts {
c.outcome[vol.VolumeID] = "no ask: superseded slot facts"
return
}
ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
if !emit {
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: " + reason
return
}
// Same-ask dedupe: while the identical ask is pending (queued, or
// taken by the publisher and still being applied), do not
// re-enqueue. Without this guard, repeated identical supported
// feeds would mint a new Reassign epoch each iteration —
// authority churn. An identical ask that is no longer pending
// ended without a publication (lost): enqueue it again, keeping
// its DesiredAt so a repeatedly lost ask still reports Stuck.
// Same-ask dedupe: if the identical ask is already the current
// desired, do not re-enqueue. Without this guard, repeated
// identical supported feeds would mint a new Reassign epoch
// each iteration — authority churn.
if prev, ok := c.desired[vol.VolumeID]; ok && sameAsk(prev.Ask, ask) {
since := prev.DesiredAt.UTC().Format(time.RFC3339Nano)
if c.queue.pending(vol.VolumeID) {
c.outcome[vol.VolumeID] = fmt.Sprintf("already desired since %s: %s %s (%s)", since, ask.Intent, ask.ReplicaID, prev.Reason)
return
}
// Not pending also after the publisher published it since the line
// was read: lost only while the line is still the one decided against.
if line, ok := c.reader.VolumeAuthorityLine(vol.VolumeID); ok != hasLine || line != currentLine {
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: the line moved to %s@%d while deciding against %s@%d", line.ReplicaID, line.Epoch, currentLine.ReplicaID, currentLine.Epoch)
return
}
c.queue.enqueue(ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued again %s %s (%s): desired since %s, its last ask ended without a publication", ask.Intent, ask.ReplicaID, prev.Reason, since)
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
return
}
@@ -370,7 +308,6 @@ func (c *TopologyController) processSupportedVolumeLocked(
}
c.desired[vol.VolumeID] = desired
c.queue.enqueue(ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued %s %s (%s)", ask.Intent, ask.ReplicaID, reason)
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
}
@@ -535,7 +472,7 @@ func (c *TopologyController) decideVolume(
if !hasLine {
cands := placeableCandidates(vol, serverIndex)
if len(cands) == 0 {
return AssignmentAsk{}, "no placeable candidate for the first line", false
return AssignmentAsk{}, "", false
}
best := choosePlacementCandidate(cands, projectedLoad)
return AssignmentAsk{
@@ -550,7 +487,7 @@ func (c *TopologyController) decideVolume(
current, ok := candidateByReplica(vol, currentLine.ReplicaID)
if !ok {
return AssignmentAsk{}, "the line's replica is not in the snapshot", false
return AssignmentAsk{}, "", false
}
if candidateAcceptable(current, serverIndex) {
@@ -563,20 +500,19 @@ func (c *TopologyController) decideVolume(
// current primary is alive, so it is a planned move: the same
// guard as a failback (the target in every acknowledgement set).
if target.PromotionEvidence.Kind != adapter.PrimaryKindPromotion || !target.PlannedMoveAllowed {
return AssignmentAsk{}, "the current primary is acceptable; rebalance target " + target.ReplicaID + " has no planned-move evidence", false
return AssignmentAsk{}, "", false
}
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: target.ReplicaID,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: IntentReassign,
Evidence: plannedEvidence(target.PromotionEvidence),
Incarnation: target.Incarnation,
ExpectCurrent: expectedLineOf(currentLine),
VolumeID: vol.VolumeID,
ReplicaID: target.ReplicaID,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: IntentReassign,
Evidence: plannedEvidence(target.PromotionEvidence),
Incarnation: target.Incarnation,
}, "rebalance", true
}
return AssignmentAsk{}, "the current primary is acceptable", false
return AssignmentAsk{}, "", false
}
// A restarted current primary that is placeable but not ready yet
@@ -586,13 +522,9 @@ func (c *TopologyController) decideVolume(
if !superseded && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh (primary boot grace)", true
}
if superseded {
return AssignmentAsk{}, "the current primary holds its boot grace (by its newer recorded fact)", false
}
return AssignmentAsk{}, "the current primary holds its boot grace", false
return AssignmentAsk{}, "", false
}
why := "no acceptable candidate besides the current primary"
other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID)
if len(other) > 0 {
best := chooseFailoverCandidate(other, projectedLoad)
@@ -600,17 +532,15 @@ func (c *TopologyController) decideVolume(
// its target (one decider): no evidence, no promotion.
if best.PromotionEvidence.Kind == adapter.PrimaryKindPromotion {
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: best.ReplicaID,
DataAddr: best.DataAddr,
CtrlAddr: best.CtrlAddr,
Intent: IntentReassign,
Evidence: best.PromotionEvidence,
Incarnation: best.Incarnation,
ExpectCurrent: expectedLineOf(currentLine),
VolumeID: vol.VolumeID,
ReplicaID: best.ReplicaID,
DataAddr: best.DataAddr,
CtrlAddr: best.CtrlAddr,
Intent: IntentReassign,
Evidence: best.PromotionEvidence,
Incarnation: best.Incarnation,
}, "failover", true
}
why = "failover target " + best.ReplicaID + " has no promotion evidence"
}
// No promotion-ready peer exists. Keep the current authority endpoint fresh
// when the current replica is still reachable/eligible; this preserves
@@ -618,7 +548,7 @@ func (c *TopologyController) decideVolume(
if candidatePlaceable(current, serverIndex) && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh", true
}
return AssignmentAsk{}, why, false
return AssignmentAsk{}, "", false
}
// endpointStale reports whether the current primary's line needs a new
@@ -641,17 +571,10 @@ func refreshAsk(volumeID string, current ReplicaCandidate, line AuthorityBasis)
CtrlAddr: current.CtrlAddr,
Intent: IntentRefreshEndpoint,
Incarnation: current.Incarnation,
ExpectCurrent: expectedLineOf(line),
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr},
}
}
// expectedLineOf conditions an ask on the line it was decided against: a
// publication that lands while the ask waits in the queue (an operator's
// failback) refuses it instead of being overwritten.
func expectedLineOf(line AuthorityBasis) *ExpectedLine {
return &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}
}
func volumeIncludesReplica(vol VolumeTopologySnapshot, replicaID string) bool {
for _, slot := range vol.Slots {
if slot.ReplicaID == replicaID {
@@ -1,252 +0,0 @@
package authority
import (
"context"
"errors"
"strings"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
)
// The same-ask dedupe holds a desired Reassign only while that ask is
// pending: queued, or taken by the publisher and still being applied. An
// ask the publisher took and ended without publishing (its apply refused
// it) is lost, and the next intake of the same state enqueues it again.
// Holding the lost ask as "already desired" would keep the volume on its
// old primary for good.
func TestALostReassignIsEnqueuedAgainOnTheNextIntake(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
ctrl := NewTopologyController(TopologyControllerConfig{}, reader)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
submit := func() {
t.Helper()
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
}
submit()
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("first intake: %+v, want Reassign r2", ask)
}
// The publisher holds the ask (applying it): the same state again is
// deduplicated, nothing is queued twice.
submit()
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "already desired since ") {
t.Fatalf("while the ask is being applied: outcome %q, want already desired", out)
}
// The apply ended without a publication (the line is still r1@1) and
// the publisher waits for its next ask: the ask is lost.
next := make(chan AssignmentAsk, 1)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
go func() {
if ask, err := ctrl.Next(ctx); err == nil {
next <- ask
}
}()
synctest.Wait() // the publisher is back in Next, holding nothing
submit()
select {
case ask := <-next:
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("after the loss: %+v, want Reassign r2 again", ask)
}
case <-ctx.Done():
t.Fatalf("a lost Reassign was never enqueued again; the controller's outcome: %q", ctrl.LastOutcome("v1"))
}
})
}
// A Reassign lost again and again keeps its first DesiredAt across every
// re-enqueue, so it still becomes Stuck once the retry window passes from
// that first desire: a retry that re-anchored DesiredAt would never report
// the volume stuck however long its asks keep failing.
func TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck(t *testing.T) {
const window = 10 * time.Second
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
ctrl := NewTopologyController(TopologyControllerConfig{RetryWindow: window}, reader)
clk := newFakeClock(time.Date(2026, 12, 5, 9, 0, 0, 0, time.UTC))
ctrl.SetNowForTest(clk.Now)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
first := clk.Now()
ended, cancel := context.WithCancel(context.Background())
cancel() // the publisher's next call after an apply that published nothing
for cycle := 0; cycle < 4; cycle++ {
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if cycle > 0 && !strings.HasPrefix(ctrl.LastOutcome("v1"), "enqueued again Reassign r2") {
t.Fatalf("cycle %d: outcome %q, want the lost ask enqueued again", cycle, ctrl.LastOutcome("v1"))
}
if d, ok := ctrl.DesiredFor("v1"); !ok || !d.DesiredAt.Equal(first) {
t.Fatalf("cycle %d at +%v: desired %+v (ok=%v), want DesiredAt kept at the first desire %v", cycle, clk.Now().Sub(first), d, ok, first)
}
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("cycle %d: took %+v, want Reassign r2", cycle, ask)
}
_, _ = ctrl.Next(ended) // the apply ended without a publication: the ask is lost
clk.Advance(4 * time.Second)
}
// +16 s since the first desire, past the 10 s window: the latest intake
// (+12 s) found the desire unconfirmed past the window.
ev, stuck := ctrl.LastConvergenceStuck("v1")
if !stuck {
t.Fatalf("a Reassign lost on every apply for %v is not reported stuck (window %v)", clk.Now().Sub(first), window)
}
if !ev.DesiredAt.Equal(first) || ev.Ask.ReplicaID != "r2" {
t.Fatalf("stuck evidence %+v, want the first desire (%v) of Reassign r2", ev, first)
}
}
// publishOnRead runs publish once, right after the controller's skip+1-th
// line read: the publisher applies its ask between the read an intake decides
// against and that intake's dedupe.
type publishOnRead struct {
*fakeBasisReader
skip int
publish func()
}
func (r *publishOnRead) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) {
line, ok := r.fakeBasisReader.VolumeAuthorityLine(volumeID)
if r.publish != nil {
if r.skip > 0 {
r.skip--
} else {
p := r.publish
r.publish = nil
p()
}
}
return line, ok
}
// An ask the publisher publishes, and then asks past, while an intake is
// deciding against the line read before that publication is not lost: the
// intake must not enqueue it again, or a planned move would be minted twice.
func TestAnAskPublishedDuringTheIntakeIsNotEnqueuedAgain(t *testing.T) {
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
publishing := &publishOnRead{fakeBasisReader: reader}
ctrl := NewTopologyController(TopologyControllerConfig{}, publishing)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("first intake: %+v, want Reassign r2", ask)
}
ended, cancel := context.WithCancel(context.Background())
cancel()
publishing.skip = 1 // the intake's load count reads the line first
publishing.publish = func() {
reader.Set("v1", "r2", AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"})
_, _ = ctrl.Next(ended) // published: the publisher is back for its next ask
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if out := ctrl.LastOutcome("v1"); strings.HasPrefix(out, "enqueued again") {
t.Fatalf("an ask published during the intake was enqueued again: %q", out)
}
expectNoNext(t, ctrl)
}
// A controller Reassign waits in the queue until the publisher takes it. A
// publication that lands meanwhile outside the queue (an operator's failback)
// is not overwritten by the ask decided against the older line, whether the
// ask is a first one or a lost one enqueued again.
func TestAQueuedReassignDoesNotOverwriteALaterPublication(t *testing.T) {
for _, lost := range []bool{false, true} {
holder := &basisReaderHolder{}
ctrl := NewTopologyController(TopologyControllerConfig{}, holder)
pub := NewPublisher(ctrl)
holder.set(pub)
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
line, _ := pub.VolumeAuthorityLine("v1")
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if lost {
nextAskOrFail(t, ctrl)
ended, cancel := context.WithCancel(context.Background())
cancel()
_, _ = ctrl.Next(ended) // the apply ended without a publication
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "enqueued again Reassign r2") {
t.Fatalf("outcome %q, want the lost ask enqueued again", out)
}
}
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r3", DataAddr: "d3", CtrlAddr: "c3", Intent: IntentReassign,
Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 10, Basis: adapter.BasisPlanned},
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch}}); err != nil {
t.Fatalf("failback: %v", err)
}
ask := nextAskOrFail(t, ctrl)
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("lost=%v: took %+v, want Reassign r2", lost, ask)
}
if err := pub.apply(ask); !errors.Is(err, ErrExpectedLineMoved) {
t.Fatalf("lost=%v: the queued Reassign decided against %s@%d: err=%v, want ErrExpectedLineMoved", lost, line.ReplicaID, line.Epoch, err)
}
if after, _ := pub.VolumeAuthorityLine("v1"); after.ReplicaID != "r3" || after.Epoch != line.Epoch+1 {
t.Fatalf("lost=%v: line %+v, want the failback's r3@%d", lost, after, line.Epoch+1)
}
}
}
-17
View File
@@ -14,10 +14,6 @@ type assignmentQueue struct {
items map[string]AssignmentAsk
order []string
wake chan struct{}
// taken is the volume of the ask the publisher took last and is still
// applying: it is cleared when the publisher asks for its next one (the
// publisher applies one ask at a time, between two calls of next).
taken string
}
func newAssignmentQueue() *assignmentQueue {
@@ -46,19 +42,7 @@ func (q *assignmentQueue) discard(volumeID string) {
delete(q.items, volumeID)
}
// pending reports whether volumeID's ask is queued or still being applied.
// A desired ask that is neither ended without a publication (lost).
func (q *assignmentQueue) pending(volumeID string) bool {
q.mu.Lock()
defer q.mu.Unlock()
_, queued := q.items[volumeID]
return queued || q.taken == volumeID
}
func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
q.mu.Lock()
q.taken = "" // the publisher is done with the ask it took last
q.mu.Unlock()
for {
q.mu.Lock()
if len(q.order) > 0 {
@@ -70,7 +54,6 @@ func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
continue
}
delete(q.items, vid)
q.taken = vid
q.mu.Unlock()
return ask, nil
}
@@ -1,72 +0,0 @@
package master
import (
"log"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// bindingFailingProbe is switchProbe whose fencing round first makes the
// master's workspace binding store fail a write (its file replaced by a
// directory, so the write's rename fails), which latches the store
// uncertain: every later read answers restart-required. It does this once.
type bindingFailingProbe struct {
*switchProbe
once sync.Once
fault func()
}
func (p *bindingFailingProbe) FencePromotionCandidates(volume string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
p.once.Do(p.fault)
return p.switchProbe.FencePromotionCandidates(volume, current, survivors)
}
// A binding store that turns uncertain while the gate probes (the probe runs
// without the workspace lock) makes the tick's post-probe binding read fail.
// The tick returns the error and its replace decision is reported as not
// submitted, with the error, instead of vanishing with the tick.
func TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted(t *testing.T) {
buf := &lockedBuffer{}
dir := t.TempDir()
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0), LifecycleStoreDir: dir})
defer closeTestMaster(t, h)
base, ok := h.promotionProber.(*switchProbe)
if !ok {
t.Fatalf("fixture: the master's prober is %T, want *switchProbe", h.promotionProber)
}
var faultErr error
h.SetPromotionEvidenceProvider(&bindingFailingProbe{switchProbe: base, fault: func() {
file := filepath.Join(dir, "workspace-bindings", "bindings.json")
if err := os.RemoveAll(file); err != nil {
faultErr = err
return
}
if err := os.MkdirAll(file, 0o755); err != nil {
faultErr = err
return
}
if err := h.lifecycle.WorkspaceBindings.Retire("vol-other", "node-x", 1); err == nil {
faultErr = os.ErrInvalid // the write was expected to fail
}
}})
ineligible := restarting
ineligible.eligible = false
ingestRF3Incarnations(t, h, ineligible, readySlot("r2-a"), readySlot("r3-a"))
_, err := h.RunLifecycleProductTick()
if faultErr != nil {
t.Fatalf("fixture: the binding store did not fail its write: %v", faultErr)
}
if err == nil || !strings.Contains(err.Error(), "restart required") {
t.Fatalf("tick error %v, want the binding store's restart-required error", err)
}
pattern := `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) not submitted: the workspace bindings could not be read after the probe: .*restart required`
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
@@ -1,150 +0,0 @@
package master
import (
"log"
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// A replace decision of the promotion gate is followed, on the master's
// log, by what became of it: the ask the controller enqueued, why it
// enqueued none, or that it was not submitted. A replace the controller
// does not act on is otherwise silent until the volume fails to fail over.
func TestAReplaceDecisionLogsWhatTheControllerDidWithIt(t *testing.T) {
// The gate's replace of the lost r1, fed to a controller bound to r1@1.
replaced := func(t *testing.T) (*Host, *lockedBuffer, *authority.TopologyController, authority.ClusterSnapshot) {
t.Helper()
ctrl, pub, stop := lossCluster(t, authority.TopologyControllerConfig{})
stop() // the enqueued ask stays queued: the outcome is the controller's alone
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
h.ctrl = ctrl
snap := lossTicks(h)
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
return h, buf, ctrl, snap
}
submit := func(t *testing.T, h *Host, ctrl *authority.TopologyController, snap authority.ClusterSnapshot) {
t.Helper()
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
h.reportReplaces("", nil, outcomes)
}
want := func(t *testing.T, buf *lockedBuffer, pattern string) {
t.Helper()
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
t.Run("enqueued", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
want(t, buf, `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
})
t.Run("the same decision again: already desired", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.noteGateReplace("vol-rf3", "replace(fenced_at=2)") // the next tick decides the same
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: already desired since \S+: Reassign r[23] \(failover\)`)
})
t.Run("not acted on: says why", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
for i := range snap.Volumes[0].Slots {
snap.Volumes[0].Slots[i].PromotionEvidence = adapter.PrimaryEvidence{}
}
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: no ask: failover target r[23] has no promotion evidence`)
})
t.Run("not submitted", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
want(t, buf, `decision=replace\(fenced_at=2\) not submitted: the placements changed during the probe`)
})
t.Run("an intake after the submission does not change its report", func(t *testing.T) {
// The background observation host shares the controller: its intake
// may land between the tick's submit and the report.
h, buf, ctrl, snap := replaced(t)
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
stale := snap
stale.Volumes = append([]authority.VolumeTopologySnapshot(nil), snap.Volumes...)
stale.Volumes[0].Authority.Epoch++ // a basis the publisher does not hold
if err := ctrl.SubmitClusterSnapshot(stale); err != nil {
t.Fatal(err)
}
if o := ctrl.LastOutcome("vol-rf3"); !strings.HasPrefix(o, "no ask: stale snapshot basis") {
t.Fatalf("fixture: the intervening intake did not record its own outcome: %q", o)
}
h.reportReplaces("", nil, outcomes)
want(t, buf, `decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
if strings.Contains(buf.String(), "decision=replace(fenced_at=2) controller: no ask: stale") {
t.Fatalf("the report took the later intake's outcome:\n%s", buf.String())
}
})
t.Run("a submission that did not carry the volume", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("", nil, map[string]string{})
want(t, buf, `decision=replace\(fenced_at=2\) controller: no outcome \(the submission did not carry the volume\)`)
})
t.Run("one report per decision", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.reportReplaces("", nil, nil) // nothing decided since: nothing to report
if n := strings.Count(buf.String(), "decision=replace(fenced_at=2) controller:"); n != 1 {
t.Fatalf("%d reports of one decision:\n%s", n, buf.String())
}
})
}
// The same through the production tick on the supported gate: an
// established volume whose primary turns ineligible is replaced by a fencing
// round; the gate's replace is reported with the controller's enqueued
// failover, and the publication is logged. The publication line comes from
// the publisher's observer after the line is visible, so it is waited for
// (bounded); the two lines are not ordered against each other.
func TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication(t *testing.T) {
buf := &lockedBuffer{}
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0)})
defer closeTestMaster(t, h)
ineligible := restarting
ineligible.eligible = false
supportedCreatingTick(t, h, ineligible)
expectFailoverToR2(t, h, "fenced survivors")
for _, pattern := range []string{
`promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r2 \(failover\)`,
`blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 \(Reassign\)`,
} {
waitLogLine(t, buf, pattern, 5*time.Second)
}
}
// waitLogLine waits up to limit for a line of buf matching pattern.
func waitLogLine(t *testing.T, buf *lockedBuffer, pattern string, limit time.Duration) {
t.Helper()
re := regexp.MustCompile(pattern)
for end := time.Now().Add(limit); !re.MatchString(buf.String()); time.Sleep(10 * time.Millisecond) {
if time.Now().After(end) {
t.Fatalf("no log line matching %q within %v:\n%s", pattern, limit, buf.String())
}
}
}
// Every publication is on the master's log, with or without an event log.
func TestAPublicationIsLogged(t *testing.T) {
h, buf := lossMaster(t, &fenceProbe{})
h.recordAuthorityPublishedEvent(authority.PublishEvent{
Info: adapter.AssignmentInfo{VolumeID: "vol-rf3", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1},
Ask: authority.AssignmentAsk{VolumeID: "vol-rf3", ReplicaID: "r2", Intent: authority.IntentReassign},
})
if !strings.Contains(buf.String(), "blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 (Reassign)") {
t.Fatalf("publication not logged:\n%s", buf.String())
}
}
@@ -1,60 +0,0 @@
package master
import (
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
)
// A fenced replace decided by the gate reaches the controller as a failover
// whatever the gate's reason. Here the gate replaces a primary only it reads
// as unacceptable: its node reads format level 0 on a level-1 cluster (not
// placement-eligible), while the primary's own slot flags still read
// reachable and ready, and it still reports (no loss is recorded). The
// controller judges acceptability by those flags alone, so unless the gate
// marks the replaced primary unacceptable in what it submits, the controller
// answers "the current primary is acceptable" on every tick and the fenced
// decision never publishes.
func TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign(t *testing.T) {
ctrl, pub, _ := lossCluster(t, authority.TopologyControllerConfig{})
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
h.ctrl = ctrl
h.boot = &bootstrap.DurableAuthorityBootstrap{Publisher: pub}
h.reads = newReadsLevels(time.Hour)
h.reads.note("s1", "vol-rf3", "p-r1", 0) // the primary's node reads the old level
h.reads.note("s2", "vol-rf3", "p-r2", 1)
h.reads.note("s3", "vol-rf3", "p-r3", 1)
h.format.v.Store(1)
t0 := time.Date(2026, 12, 5, 8, 0, 0, 0, time.UTC)
for tick := range 3 {
now := t0.Add(time.Duration(tick) * time.Second)
snap := silentPrimary() // r1's flags read reachable and ready
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
if snap.Volumes[0].Authority.Epoch != 1 {
break // published
}
heard := map[string]time.Time{"r1": now, "r2": now, "r3": now} // r1 still reports: no loss
h.notePrimaryLosses(rx(heard, now), &snap)
h.takeGateReplaces()
h.applyPromotionEvidenceGate(&snap)
if l := gateLine(t, buf.String(), "vol-rf3"); !regexp.MustCompile(`primary_lost=false decision=replace\(fenced_at=2\)$`).MatchString(l) {
t.Fatalf("tick %d: gate line %q; want a fenced replace with no loss recorded", tick, l)
}
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
h.reportReplaces("", nil, outcomes)
}
if strings.Contains(buf.String(), "controller: no ask: the current primary is acceptable") {
t.Fatalf("the controller kept a primary the gate replaced:\n%s", buf.String())
}
if !regexp.MustCompile(`decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`).MatchString(buf.String()) {
t.Fatalf("the fenced replace was not enqueued as a failover:\n%s", buf.String())
}
waitLossLine(t, pub, "vol-rf3", func(l authority.AuthorityBasis) bool { return l.Epoch == 2 && l.ReplicaID != "r1" })
}
+1 -2
View File
@@ -152,9 +152,8 @@ type Host struct {
attest *storeAttestations // primaries' attested write-ACK stores
healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6)
log *log.Logger
gateNoteMu sync.Mutex // guards gateNoteLast and gateReplaces
gateNoteMu sync.Mutex // guards gateNoteLast
gateNoteLast map[string]string // per kind, the last skip or drop a product-loop tick logged (noteGate)
gateReplaces []gateReplace // this tick's replace decisions, reported after the submit (reportReplaces)
primaryLossMu sync.Mutex // guards primaryLoss
primaryLoss primaryLosses // per volume, the recorded loss of the current primary (primary_loss.go)
boot *bootstrap.DurableAuthorityBootstrap
@@ -6,7 +6,6 @@ import (
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
@@ -16,11 +15,11 @@ func lifecycleFailStop(logger *log.Logger) lifecycle.PersistenceFailureHandler {
once.Do(func() {
// Arm termination before touching the logger: its writer or output
// mutex may be blocked. ERROR delivery is best effort in that case.
time.AfterFunc(time.Second, func() { os.Exit(authority.ExitDurabilityUnknown) })
logger.Printf("ERROR reason=lifecycle_persist_failed lifecycle persistence failure store=%q record=%q error=%q; exiting so the supervisor restarts from durable state", failure.Store, failure.Record, failure.Err)
time.AfterFunc(time.Second, func() { os.Exit(1) })
logger.Printf("ERROR lifecycle persistence failure store=%q record=%q error=%q; exiting so the supervisor restarts from durable state", failure.Store, failure.Record, failure.Err)
// A graceful close can wait on the writer that discovered the error.
// The supervisor restarts; Open establishes the recovery barriers.
os.Exit(authority.ExitDurabilityUnknown)
os.Exit(1)
})
}
}
@@ -20,7 +20,6 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
@@ -34,15 +33,15 @@ func TestLifecyclePersistenceFailureStopsTheProcess(t *testing.T) {
cmd.Env = append(os.Environ(), "LIFECYCLE_EXIT_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind)
out, err := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
t.Fatalf("master failed to exit74: %v context=%v\n%s", err, ctx.Err(), out)
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("master failed to exit1: %v context=%v\n%s", err, ctx.Err(), out)
}
text := string(out)
record := "new.json"
if kind == "volumes" {
record = "kept.json"
}
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "reason=lifecycle_persist_failed") || !strings.Contains(text, record) || !strings.Contains(text, filepath.Join(root, "lifecycle")) {
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, record) || !strings.Contains(text, filepath.Join(root, "lifecycle")) {
t.Fatalf("missing single record/store/error line: %s", text)
}
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceRecoveryChild$", "-test.timeout=8s")
@@ -135,8 +134,8 @@ func TestLifecycleFailStopExitsWithBlockedLogger(t *testing.T) {
out, err := cmd.CombinedOutput()
exited := time.Now()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
t.Fatalf("blocked logger prevented own exit74: %v context=%v\n%s", err, ctx.Err(), out)
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("blocked logger prevented own exit1: %v context=%v\n%s", err, ctx.Err(), out)
}
var triggered int64
for _, line := range strings.Split(string(out), "\n") {
+7 -72
View File
@@ -263,7 +263,6 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
receipts := h.obs.Store().Snapshot()
build := authority.BuildSnapshot(receipts, topology, h.Publisher())
h.notePrimaryLosses(receipts, &build.Snapshot)
h.takeGateReplaces() // only this tick's decisions are reported
probeCount, blockedCount, directAsks := h.applyPromotionEvidenceGate(&build.Snapshot)
supported := supportedSnapshotVolumes(build.Snapshot)
unsupportedProbeCount, unsupportedBlockedCount, unsupportedDirectAsks := h.applyUnsupportedPromotionEvidenceGate(placements, build.Report, supported)
@@ -276,16 +275,13 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
defer h.workspaceMu.Unlock()
if !reflect.DeepEqual(captured, h.lifecycle.Placements.ListPlacements()) {
h.noteGate(gateNoteTick, "decisions not submitted: the placements changed during the probe")
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
for _, p := range placements {
if _, bound, err := h.lifecycle.WorkspaceBindings.Get(p.VolumeID); err != nil {
h.reportReplaces("not submitted: the workspace bindings could not be read after the probe: "+err.Error(), nil, nil)
return false, probeCount, blockedCount, nil, err
} else if bound {
h.noteGate(gateNoteTick, "decisions not submitted: volume "+p.VolumeID+" got a workspace binding during the probe")
h.reportReplaces("not submitted: volume "+p.VolumeID+" got a workspace binding during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
@@ -293,58 +289,12 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
for _, slot := range v.Slots {
if err := h.lifecycle.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: v.VolumeID, DataAddr: slot.DataAddr, CtrlAddr: slot.CtrlAddr}); err != nil {
h.noteGate(gateNoteTick, fmt.Sprintf("decisions not submitted: volume %s replica %s endpoints are bound elsewhere: %v", v.VolumeID, slot.ReplicaID, err))
h.reportReplaces(fmt.Sprintf("not submitted: volume %s replica %s endpoints are bound elsewhere", v.VolumeID, slot.ReplicaID), nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
}
h.noteGate(gateNoteTick, "")
// The outcomes are this submission's own, read under the controller's
// lock: the background observation host may submit right after it.
outcomes, err := h.ctrl.SubmitObservedStateOutcomes(build.Snapshot, build.Report)
h.reportReplaces("", err, outcomes)
return true, probeCount, blockedCount, directAsks, err
}
// gateReplace is one replace decision of a tick's promotion gate.
type gateReplace struct{ volumeID, decision string }
func (h *Host) noteGateReplace(volumeID, decision string) {
h.gateNoteMu.Lock()
h.gateReplaces = append(h.gateReplaces, gateReplace{volumeID, decision})
h.gateNoteMu.Unlock()
}
func (h *Host) takeGateReplaces() []gateReplace {
h.gateNoteMu.Lock()
defer h.gateNoteMu.Unlock()
out := h.gateReplaces
h.gateReplaces = nil
return out
}
// reportReplaces logs what became of each replace decision of this tick:
// not submitted (notSubmitted says why), a failed submit, or what the
// controller did with the volume (an enqueued ask, or why none). A decision
// the controller does not act on is otherwise silent until the volume is
// seen not to fail over.
func (h *Host) reportReplaces(notSubmitted string, submitErr error, outcomes map[string]string) {
for _, d := range h.takeGateReplaces() {
outcome := ""
switch {
case notSubmitted != "":
outcome = notSubmitted
case submitErr != nil:
outcome = "submit failed: " + submitErr.Error()
default:
if o, ok := outcomes[d.volumeID]; ok {
outcome = "controller: " + o
} else {
outcome = "controller: no outcome (the submission did not carry the volume)"
}
}
h.log.Printf("blockmaster: promotion gate volume=%s decision=%s %s", d.volumeID, d.decision, outcome)
}
return true, probeCount, blockedCount, directAsks, h.ctrl.SubmitObservedState(build.Snapshot, build.Report)
}
func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, int, []authority.AssignmentAsk) {
@@ -426,7 +376,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
// decision names, on the gate's line, the branch this tick took, so a
// volume that keeps a lost primary says why.
decision := ""
replaceDecided := false // the gate decided to replace the primary (reported after the submit)
switch {
case !replaceWanted:
decision = "keep_current(" + gateAcceptance(vol.Slots[currentIdx], serverIndex, h.placementEligible(vol.Slots[currentIdx].ServerID)) + ")"
@@ -453,7 +402,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
} else if (len(allowed) > 0 || emptyVolumeSurvivors(result, ok)) && replacing {
result, allowed = h.fencedDecision(vol.VolumeID, vol.Authority, result, len(candidates))
fencedReplace = len(allowed) > 0
replaceDecided = true
decision = fmt.Sprintf("replace(fenced_at=%d)", vol.Authority.Epoch+1)
if len(allowed) == 0 {
decision = "replace(fencing_round_published_nothing)"
@@ -469,12 +417,8 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
}
}
if decision == "" && replacing {
replaceDecided = true
decision = "replace(no_candidate_to_fence)"
}
if replaceDecided {
h.noteGateReplace(vol.VolumeID, decision)
}
if ok {
h.log.Printf("blockmaster: promotion gate volume=%s current=%s current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v primary_lost=%t decision=%s",
vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed, lost, decision)
@@ -500,15 +444,12 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
slot.PlannedMoveAllowed = false
}
}
// A fenced replacement reaches the controller as a failover,
// whatever the gate's reason (a recorded loss, or a primary only
// the gate reads as unacceptable, such as one on a node below the
// cluster's format level): its slot no longer reads acceptable, so
// the controller publishes the fenced target with its fenced
// evidence (the line is minted only at the fenced epoch), never
// keeping the old line by its own acceptability predicate nor
// A fenced replacement of a lost primary reaches the controller as
// a failover: its slot no longer reads acceptable, so the controller
// publishes the fenced target with its fenced evidence (the line is
// minted only at the fenced epoch), never keeping the old line nor
// routing the target as a planned rebalance without that epoch.
if fencedReplace {
if lost && fencedReplace {
current := &vol.Slots[currentIdx]
current.Reachable, current.ReadyForPrimary = false, false
}
@@ -1016,19 +957,13 @@ func (h *Host) recordVolumeBlockedEvent(volumeID, reason string) {
}
func (h *Host) recordAuthorityPublishedEvent(event authority.PublishEvent) {
if h == nil {
if h == nil || h.events == nil {
return
}
message := fmt.Sprintf("authority published replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
if event.Ask.Intent == authority.IntentReassign {
message = fmt.Sprintf("authority reassigned to replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
}
if h.log != nil {
h.log.Printf("blockmaster: volume=%s %s (%s)", event.Info.VolumeID, message, event.Ask.Intent)
}
if h.events == nil {
return
}
h.events.append(ops.ClusterEvent{
VolumeID: event.Info.VolumeID,
ReplicaID: event.Info.ReplicaID,
+6 -44
View File
@@ -9,7 +9,7 @@ The design is described in three documents, and this one collects their machines
**Conventions.** These are the same as in the design documents.
- Code references name a file and a function, not a line number. Test references name the test function and its file.
- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it; an entry naming a model checked outside the repository says so. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)).
- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)).
- Status:
- `ACTIVE`: a Go test in this repository asserts the statement.
- `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row.
@@ -60,7 +60,7 @@ stateDiagram-v2
Ready --> Ready: changed files synced, renamed, directory synced
Ready --> Faulted: record put/import persistence failure
Recovering --> Faulted: recovery directory sync failure
Faulted --> Exited: one ERROR attempt, exit 74 within 1 s
Faulted --> Exited: one ERROR attempt, exit 1 within 1 s
Exited --> Recovering: supervisor restarts
```
@@ -71,7 +71,7 @@ stateDiagram-v2
| Ready | Ready | a changed put or import: changed files are durable before rename (per-file fsync, or one `syncfs` on a qualified filesystem) and one directory barrier precedes publication; an unchanged record does no I/O and keeps its SeenAt | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `core/lifecycle/node_inventory.go` `ImportNodes`, `registrationLocked`; `core/lifecycle/placement_intent.go` `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-NODE-REGISTRATION-FRESHNESS-001` |
| Ready | Faulted | a put or import returns a `RecordPersistenceError`; the store latches it, so later mutations return `ErrLifecycleRecoveryRequired`, before calling the process policy; a marshal error before any I/O does not latch | `core/lifecycle/record_file.go` `latchPersistenceFailure`; each store's `putLocked`, `ImportNodes`, `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
| Recovering | Faulted | a store open's records-directory sync fails; `New` hands the `RecordPersistenceError` to the process policy | `core/lifecycle/record_file.go` `syncRecordDirectory`; `core/host/master/host.go` `New` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
| Faulted | Exited | the policy arms a one-second exit timer, attempts one ERROR line, then exits 74 | `core/host/master/lifecycle_failure.go` `lifecycleFailStop` | `INV-LIFECYCLE-FAILSTOP-001` |
| Faulted | Exited | the policy arms a one-second exit timer, attempts one ERROR line, then exits 1 | `core/host/master/lifecycle_failure.go` `lifecycleFailStop` | `INV-LIFECYCLE-FAILSTOP-001` |
| Exited | Recovering | the supervisor restarts blockmaster (`Restart=on-failure`) | `deploy/systemd/sw-blockmaster.service` | `INV-LIFECYCLE-FAILSTOP-001` |
A store latches the error before calling the process policy. A failed step may
@@ -88,10 +88,7 @@ before rename; startup reports the chosen path for the node and placement
stores, each probed at its own directory. The filesystem-wide sync can
also wait for unrelated writeback on that filesystem.
The executable arms a one-second process-exit timer before logging
and exits with status 74 (durability unknown) immediately after the log
returns. The best-effort log reason is `lifecycle_persist_failed`; status 74
alone does not identify a lifecycle fault, since authority-store faults use
the same status. The process does not wait for graceful
and exits immediately after the log returns, rather than waiting for graceful
shutdown behind a writer. Embedders without this process policy must reopen a
failed store before any further mutation. Removal errors do not invoke this
policy: the in-memory record and its published snapshot stay present until
@@ -192,7 +189,7 @@ flowchart LR
|---|---|---|---|---|
| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; new addresses, or the same addresses for another primary process (the line's incarnation differs); a no-op when both are unchanged; refused (`ErrExpectedLineMoved`) when the ask names the line it was decided against and the volume's line is no longer that one (replica, epoch, addresses) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/directive.go` `expectedLineMoved` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`, `INV-AUTH-RESTART-REISSUE-001` |
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move; refused (`ErrExpectedLineMoved`) when the ask names the line it was decided against (the controller's rebalance and failover, an operator's failback) and the volume's line is no longer that one, compared by replica and epoch, and by addresses only when the ask names them (the controller's moves do; an operator's failback names replica and epoch only, so an endpoint move to other addresses does not refuse it): a queued controller move never overwrites a reassign or an endpoint move to other addresses that landed after its decision; a same-address endpoint reissue (new endpoint version or incarnation, same addresses) still matches, and the move's epoch bump fences it | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume`; `core/authority/directive.go` `expectedLineMoved`; `core/authority/controller.go` `decideVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing; a write whose outcome is unknown (the directory fsync after the rename failed) fail-stops blockmaster, so no caller is told it failed | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` |
| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` |
@@ -201,34 +198,6 @@ flowchart LR
| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` |
| DeleteReserved, removed from the desired spec | Retired metadata (reservation permanent) | no live lease, then a fresh bounded HEAD read proves deleted or absent; unread/live/deleting keeps the records. Remove authority durably, then placement and bindings, then the volume record; a crash retries the remaining removals. A startup lease skip schedules one more pass after the latest observed barrier, also without the product loop; full passes log skips. The store and its resweep inputs are untouched | `core/host/master/spec_retirement.go` `ReconcileDeletedSpecVolumes`, `startPostFloorRetirement`; `core/authority/workspace_retirement.go` `RetireDeletedWorkspace` | `INV-SPEC-DELETE-RETIRE-001`, `INV-SPEC-DELETE-RETRY-001` |
**Controller ask, per volume (between the promotion gate and the publisher).**
The topology controller turns a supported snapshot into at most one ask per volume. The publisher drains the controller's queue one ask at a time (its `Run` loop, between two calls of `next`). A fenced replace decided by the supported gate is submitted with the replaced primary's slot unacceptable, whatever the gate's reason, so the controller's own acceptability predicate never keeps that primary. An ask is pending while it is queued or held by the publisher; an identical ask is deduplicated only while it is pending.
```mermaid
stateDiagram-v2
[*] --> Queued: intake decides an ask (desired, DesiredAt set)
Queued --> Held: publisher takes it (next)
Held --> Published: apply publishes (line moves)
Held --> Lost: apply ends without a publication (publisher calls next again)
Lost --> Queued: next intake decides the identical ask (DesiredAt kept)
Queued --> Queued: identical ask decided (already desired)
Held --> Held: identical ask decided (already desired)
Published --> [*]: snapshot observes the new line (desired confirmed)
```
| From | To | Event and guard | Enforced in | Protects |
|---|---|---|---|---|
| no desired ask | Queued | an intake of a supported snapshot decides an ask; the desired entry records DesiredAt. A fenced replace (with or without a recorded loss) reaches the controller with the replaced primary's slot unreachable and not ready, so its intake decides the failover to the fenced target | `core/authority/controller.go` `processSupportedVolumeLocked`, `decideVolume`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-PROMOTE-REPLACE-HANDOFF-001`, `INV-PROMOTE-REPLACE-HANDOFF-002` |
| Queued | Held | the publisher takes the ask; the queue records the volume it holds | `core/authority/queue.go` `next` | `INV-AUTH-DESIRED-RETRY-001` |
| Queued or Held | (no change) | an intake decides the identical ask while it is pending: deduplicated (`already desired since T`), nothing queued twice | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/queue.go` `pending` | `INV-AUTH-DESIRED-RETRY-001` |
| Held | Published | the apply publishes the line (epoch minted by the publisher) | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-EPOCH-MINT-001` |
| Held | Lost | the apply ends without a publication (refused, or dropped); the publisher asks for its next ask, which clears the held volume | `core/authority/queue.go` `next` | `INV-AUTH-DESIRED-RETRY-001` |
| Lost | Queued (DesiredAt kept) | an intake decides the identical ask while the line, re-read after the pending check, is still the one it decided against (an ask published during the intake is not lost): enqueued again (`enqueued again ...`), the desired entry and its DesiredAt unchanged | `core/authority/controller.go` `processSupportedVolumeLocked` | `INV-AUTH-DESIRED-RETRY-001`, `INV-AUTH-DESIRED-RETRY-002` |
| any desired (unconfirmed) | Stuck evidence | DesiredAt + retry window passed without the line observed; a repeatedly lost ask reaches it from its first desire | `core/authority/convergence.go` `evaluateStuckLocked` | `INV-AUTH-DESIRED-RETRY-002` |
Model: PromoLive r6, checked outside the repository (it is not in `docs/spec/`), models this handoff with the intake split as the code does it (read the line and decide; after the publisher may have run, enqueue only if the ask is not pending and the line is still the one read). `RoundProgress` and `QueuedMatchesLine` hold; the mutants `dedupe_keeps_lost`, `predicate_split` and `nonatomic_submit` are each caught. The retry window and the Stuck evidence are not modelled; their test is the evidence.
**Volume creation phase, in blockmaster's store record** (`core/host/master/store_attestation.go`, decided by `inCreationPhase` in `core/host/master/product_loop.go`). Every replacement entry (both promotion gates, the operator's failover and planned move, the rebalance) acts only on Established.
```mermaid
@@ -1038,8 +1007,6 @@ Notes:
| `INV-CLI-TYPED-REFUSAL-001` | The chunk CLI reports a restore the master refused for a foreign source as `restore_source_not_own` (from the master's typed reason, never its text) and a volume the master does not know as `volume_not_found`. | M2 none → created (restore refusal); CLI volume resolve | `core/host/master/services.go` `CreateVolume`; `core/rpc/lifecycleclient/reason.go` `WithReason`, `Reason`; `cmd/sw-block/chunk_b.go` `chunkRestore`, `run` | `TestOpsChunkTypedRefusalCodes` (`cmd/sw-block/chunk_typed_codes_test.go`), `TestReasonRoundTrip` (`core/rpc/lifecycleclient/reason_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing` (`core/host/master/restore_refusal_catalog_test.go`) | — (reporting only; the refusal is `INV-CREATE-ONE-IDENTITY-001`'s). Limits: other FailedPrecondition refusals stay the generic `not_admitted` | ACTIVE |
| `INV-CLI-RESTORE-VERB-001` | `volume restore --abort` changes nothing unless the master records this command's source, snapshot and request id for the target and this host's settings name exactly it (volume, master, `--layout-id` alone in the extra arguments); a re-run counts only this replica's published line as placed. | client (no state machine): the CLI side of M2 restore create, placement and delete | `cmd/sw-block/volume_backup.go` `volumeRestoreAbort`, `volumeRestore`, `restorePlaced`; `core/host/master/services.go` `lifecycleVolumeResponse` | `TestVolumeRestoreAbortRefusesAForeignTarget`, `TestVolumeRestoreAbortRefusesAnotherLocalInstallation`, `TestVolumeRestoreAbortInterruptedAtEveryStepCompletes`, `TestVolumeRestoreCrashTableBothWays`, `TestVolumeRestorePublicationDuringThePlacement`, `TestVolumeRestorePlacementOfAnotherLineRefuses`, `TestVolumeRestoreCreatesPlacesAndStarts`, `TestVolumeBackupTakesOneSnapshotAndRerunReplays`, `TestVolumeBackupRefusals`, `TestVolumeBackupIncompleteAnswerIsUnknown` (`cmd/sw-block/volume_backup_test.go`), `TestGetVolumeAnswersTheRecordedRestoreTuple` (`core/host/master/volume_restore_tuple_test.go`) | — (the command's model is checked outside the repository; its trace is on the pull request) | ACTIVE |
| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`); also in `core/authority/layout_granted_epoch_guard_test.go` | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-DESIRED-RETRY-001` | The controller deduplicates a desired ask only while it is pending: queued, or taken by the publisher and still being applied. An identical ask that ended without a publication, the line still the one it was decided against, is enqueued again on the next intake. | M2 controller ask: Queued or Held (deduplicated); Held → Lost; Lost → Queued | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/queue.go` `pending`, `next` | `TestALostReassignIsEnqueuedAgainOnTheNextIntake`, `TestAnAskPublishedDuringTheIntakeIsNotEnqueuedAgain` (`core/authority/controller_lost_ask_test.go`) | PromoLive r6 (outside the repository) `QueuedMatchesLine`, `RoundProgress` (mutants `dedupe_keeps_lost`, `nonatomic_submit`) | ACTIVE |
| `INV-AUTH-DESIRED-RETRY-002` | An ask enqueued again keeps its first DesiredAt, so an ask lost on every apply still becomes Stuck once the retry window passes from that first desire. | M2 controller ask: Lost → Queued (DesiredAt kept); Stuck evidence | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/convergence.go` `evaluateStuckLocked` | `TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck` (`core/authority/controller_lost_ask_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (the retry; the retry window and Stuck are not modelled: the test is the evidence) | ACTIVE |
| `INV-AUTH-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`, `refreshAsk` (conditional on the line it read); `core/host/master/product_loop.go` `RunLifecycleProductTick`, `restartedHolderRefresh` (the product loop's direct path for a workspace-bound RF1 volume, conditional on the line it read); `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestRF1RuntimeVolumeIsReissuedToARestartedHolder`, `TestRF1RuntimeLineNamingNoProcessIsReissued`, `TestRF1RefreshDecidedBeforeACrossHostMoveIsNotApplied` (`core/host/master/rf1_restart_reissue_test.go`); `TestRefreshIsConditionalOnTheLineItWasDecidedAgainst`, `TestControllerRefreshNamesTheLineItWasDecidedAgainst` (`core/authority/refresh_expected_line_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | ACTIVE |
| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE |
@@ -1059,7 +1026,7 @@ Notes:
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-NODE-REGISTRATION-FRESHNESS-001` | Replaying a node registration without an observation time preserves its stored SeenAt; unchanged non-time fields do not rewrite its record. A restart is not a fresh observation, also when the declaration changed; a live heartbeat supplies freshness independently. | M2 lifecycle registration replay (no authority transition) | `core/lifecycle/node_inventory.go` `ImportNodes`, `RegisterNode`, `registrationLocked`; `core/host/master/observation_snapshot.go` `nodeHeartbeat`; `core/lifecycle/verified_placement.go` `VerifyPlacementIntent` | `TestUnchangedNodeRestartDoesNotRefreshAStaleObservation`, `TestChangedNodeImportDoesNotRefreshAStaleObservation` (`core/lifecycle/node_import_freshness_test.go`); `TestObservationNodesReportTheNewestHeartbeat` (`core/host/master/observation_heartbeat_test.go`); live-holder process restart qualification pending | Observation time is evidence, not authority; a declaration is not an observation | STUB |
| `INV-LIFECYCLE-STORE-DURABLE-001` | A successful record put/import publishes only after complete replacement records and their directory are durable. Open syncs the records directory before publication. A possibly-applied failure blocks mutations until reopen; recovery reconciles complete old/new records. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `node_inventory.go` `ImportNodes`; `placement_intent.go` `ImportPlans`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`); `TestImportStepSyncsChangedFilesThenOneDirectory` (`core/lifecycle/import_step_sync_test.go`); `TestImportSyncfsFailureAndOrdering`, `TestImportSyncfsReturnedFailurePolicyAndReplay`, `TestImportSyncfsCrashBoundaries`, `TestSyncfsKernelGate`, `TestSyncfsFilesystemGate`, `TestImportBatchSelectsSyncfsByFilesystem`, `TestImportDurabilityModeProbesEachStoreDirectory` (`core/lifecycle/import_syncfs_test.go`); `TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk` (`core/lifecycle/import_recovery_test.go`); `TestVolumeEqualityRequiresRecovery` (`core/lifecycle/volume_recovery_test.go`); `TestNodeMarshalErrorDoesNotRequireRecovery` (`core/lifecycle/remove_retry_test.go`) | Lifecycle record publication, including startup-step durability barrier | ACTIVE |
| `INV-LIFECYCLE-FAILSTOP-001` | A supervised master exits 74 (durability unknown) within one second of a lifecycle put/import or open-barrier persistence failure, independently of logging. It attempts one ERROR; restart completes recovery barriers and import before serving. | Lifecycle process ready/recovering → faulted → exited → recovering | `core/host/master/lifecycle_failure.go` `lifecycleFailStop`; `host.go` `New`; `cmd/blockmaster/main.go` `run`; lifecycle store failure handlers | `TestMasterImportPersistenceFailureExitsAndRecovers` (`cmd/blockmaster/persist_exit_test.go`); `TestLifecyclePersistenceFailureStopsTheProcess`, `TestLifecycleFailStopExitsWithBlockedLogger` (`core/host/master/lifecycle_failure_test.go`) | Manual process-fault/recovery projection of lifecycle record durability; no new wire or format state | ACTIVE |
| `INV-LIFECYCLE-FAILSTOP-001` | A supervised master exits nonzero within one second of a lifecycle put/import or open-barrier persistence failure, independently of logging. It attempts one ERROR; restart completes recovery barriers and import before serving. | Lifecycle process ready/recovering → faulted → exited → recovering | `core/host/master/lifecycle_failure.go` `lifecycleFailStop`; `host.go` `New`; `cmd/blockmaster/main.go` `run`; lifecycle store failure handlers | `TestMasterImportPersistenceFailureExitsAndRecovers` (`cmd/blockmaster/persist_exit_test.go`); `TestLifecyclePersistenceFailureStopsTheProcess`, `TestLifecycleFailStopExitsWithBlockedLogger` (`core/host/master/lifecycle_failure_test.go`) | Manual process-fault/recovery projection of lifecycle record durability; no new wire or format state | ACTIVE |
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE |
| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners bind only loopback: --listen without mutual TLS, and the runtime HTTP listener always; a non-loopback address, and --insecure-external-bind, are refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_PlaintextControlListenersStayOnLoopback`, `TestManifests_NoPlaintextExternalBlockmasterBind` (`cmd/blockmaster/external_bind_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE |
@@ -1410,10 +1377,6 @@ Notes:
| `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
| `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | The automatic path never replaces a lost primary of a `best_effort` volume (a write may be on the primary alone, as for the operator's move): both gates hold it before any fencing round and show `best_effort_no_automatic_failover`. | M3 Supporting → promotion candidate (both gates) | `core/host/master/product_loop.go` `automaticFailoverHold` (supported gate before `fencedDecision`; unsupported gate before its candidates); `promotionAllowedReplicas` | `TestTheAutomaticPathHoldsABestEffortVolume` (`core/host/master/best_effort_hold_test.go`); `TestMountedFailover_ProductLoopRF3BestEffortIsHeldDespiteAHighestDurableSurvivor`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
| `INV-PROMOTE-ACK-PROFILE-MATCH-001` | The automatic path holds a lost primary's volume, before any fencing round and showing `ack_profile_mismatch`, when a probe answer names no ack profile or another than blockmaster's `--launcher-replication-ack`; blockmaster refuses to start with an unknown one. | M3 Supporting → promotion candidate (both gates) | `core/host/master/probe_round.go` `profileMismatch`; `core/host/master/product_loop.go` `automaticFailoverHold` (plain round), `fencedDecision` (fencing round); `core/host/volume/probe_round.go` `probeAnswer`; `cmd/blockvolume/main.go` `hostConfig`; `cmd/blockmaster/main.go` `parseFlags` | `TestTheAutomaticPathHoldsOnAnAckProfileMismatch`, `TestProbeRound_ReportsAnAckProfileMismatch`, `TestTheFencingRoundsAckProfileIsCheckedToo` (`core/host/master/ack_profile_mismatch_test.go`); `TestProbeAnswerNamesTheVolumesAckProfile` (`core/host/volume/probe_ack_profile_test.go`); `TestHostConfigAnswersTheVolumesOwnAckProfile` (`cmd/blockvolume/probe_ack_profile_test.go`); `TestBlockmasterRefusesAnUnknownLauncherReplicationAck` (`cmd/blockmaster/launcher_replication_ack_flag_test.go`) | — | ACTIVE |
| `INV-PROMOTE-DECISION-REPORTED-001` | Every replace decision of the supported promotion gate is logged once after its tick: with the controller's outcome from the same submission (read under its lock, so a later intake cannot change it), as not submitted and why, or as a failed submit. Diagnostics only: no decision changes. | M3 Supporting → promotion candidate (supported gate → controller → publisher) | `core/host/master/product_loop.go` `submitPlacementSnapshots`, `noteGateReplace`, `reportReplaces`; `core/authority/controller.go` `SubmitObservedStateOutcomes`, `LastOutcome` | `TestAReplaceDecisionLogsWhatTheControllerDidWithIt` (cases: enqueued, already desired, no ask with why, not submitted, an intake after the submission does not change its report, a submission that did not carry the volume, one report per decision), `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication`, `TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted` (`core/host/master/gate_controller_outcome_test.go`, `core/host/master/gate_binding_read_failure_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
| `INV-AUTHORITY-PUBLICATION-LOGGED-001` | Every authority publication is logged on the master's log with its volume, replica, epoch, endpoint version and intent, also when no event sink is set. Diagnostics only: no decision changes. | M3 controller → publisher (publication observer) | `core/host/master/product_loop.go` `recordAuthorityPublishedEvent` | `TestAPublicationIsLogged`, `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication` (`core/host/master/gate_controller_outcome_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
| `INV-PROMOTE-REPLACE-HANDOFF-001` | A fenced replace decided by the supported promotion gate, whatever its reason (a recorded loss, or a primary only the gate reads as unacceptable, such as one on a node below the cluster's format level), submits the replaced primary's slot as unreachable and not ready. | M2 controller ask: no desired ask → Queued (failover) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign` (`core/host/master/gate_controller_replace_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (mutant `predicate_split`) | ACTIVE |
| `INV-PROMOTE-REPLACE-HANDOFF-002` | The controller never keeps a primary the gate replaced by its own acceptability predicate: it publishes the fenced target with its fenced evidence, the line minted only at the fenced epoch. | M2 controller ask: no desired ask → Queued (failover); M3 Primary → another replica Primary at e+1 | `core/authority/controller.go` `decideVolume` | `TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign` (`core/host/master/gate_controller_replace_test.go`); `TestALostPrimarysFencedReplacementIsPublished` (`core/host/master/primary_loss_publish_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (mutant `predicate_split`) | ACTIVE |
| `INV-PRIMARY-ACK-PROFILE-001` | A primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (blockmaster's); otherwise its frontend is not Healthy and status names both profiles. So a lost primary, which does not answer, acknowledged under the master's profile. | M1 Primary → Serving (replicated line) | `core/host/master/services.go` `assignmentFact` (`ack_profile`); `core/host/volume/workspace_startup.go` `noteAckProfile`; `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/host/volume/status_server.go` | `TestPrimaryOfAReplicatedLineServesOnlyUnderTheMastersAckProfile` (`core/host/volume/ack_profile_refusal_test.go`); `TestAssignmentNamesTheMastersAckProfile` (`core/host/master/ack_profile_mismatch_test.go`) | — | ACTIVE |
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
@@ -1435,7 +1398,6 @@ Notes:
- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only.
- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`.
- `INV-PROMOTE-FRONTIER-PROBE-001`, `INV-PROMOTE-FRONTIER-UNKNOWN-001`, `INV-PROMOTE-FRONTIER-BEST-EFFORT-001`: new rows split from `INV-PROMOTE-FRONTIER-001`, kept beside it. N_peers is the number of replicas other than the current primary; for RF=3 (two peers) both must be seen under `sync_quorum`, one under `sync_all`. An unknown frontier is never read as zero. Heartbeat freshness is the observation store's rule (`FreshSlotCandidate`). The gate runs for every volume with two or more slots (RF=2 included); a primary change is published only with its evidence.
- `INV-PROMOTE-DECISION-REPORTED-001`: a decision is not submitted when the placements changed during the probe, a volume got a workspace binding, a replica's endpoints are bound elsewhere, or the workspace bindings could not be read after the probe; the line names which. `INV-AUTHORITY-PUBLICATION-LOGGED-001` was split from it.
- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values.
- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only.
- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence.
+1 -3
View File
@@ -262,9 +262,7 @@ follow the state-storage and low-write-load guidance in section 1 before restart
blockmaster must run under systemd or an equivalent restart supervisor. A node, placement
or volume lifecycle record write or recovery-directory sync failure attempts one `ERROR` naming the store,
record and error, ending with `exiting so the supervisor restarts from durable state`,
and exits with status 74 (durability unknown). The best-effort log reason
`lifecycle_persist_failed` identifies a lifecycle fault; status 74 alone does not,
because authority-store faults use the same status. Termination is armed before logging and occurs within one second even if the log writer or its lock is blocked; a blocked sink may lose that diagnostic. It does not remain alive with a failed store. The shipped
and exits with status 1. Termination is armed before logging and occurs within one second even if the log writer or its lock is blocked; a blocked sink may lose that diagnostic. It does not remain alive with a failed store. The shipped
`sw-blockmaster.service` has `Restart=on-failure` and `RestartSec=5s`; restart reloads
complete records through the recovery barriers before serving again.
@@ -33,8 +33,7 @@ writing guest:
`sw-block ops volumes --master-api <addr> -o json`, and if the primary moved, repeat the failover against it. A
read shows the line at that moment only: blockmaster applies the queued rebalance when its assignment queue reaches
it, not at a fixed time, so the primary can still move after any read, and the guest is then started again on the
new primary (item 4). Fixed in v1.1.2: blockmaster refuses a queued rebalance or failover when the volume's line
moved after it was decided.
new primary (item 4).
**Planned for a later release.** Supported replicated volumes are planned for a later release; v1.1.x keeps every replicated
configuration a preview. Replicated volumes are a preview: a primary cut off from the block master is not stopped
+1 -1
View File
@@ -57,7 +57,7 @@ v1.1.1 is a fix release of the v1.1 line. None of its changes alters a stored fo
- Affects replicated volumes (preview) whose acknowledgement profile allows a planned move: `sync-all`, or `sync-quorum` with two replicas.
- blockmaster may decide an automatic rebalance, which moves the primary to a less loaded server, just before an operator's `sw-block ops failover`. If that rebalance is applied after the failover, it moves the primary again, away from the replica the operator chose.
- No acknowledged write is lost: under these profiles every replica holds every acknowledged write.
- What to do: after `sw-block ops failover`, read the volume's line with `sw-block ops volumes --master-api <addr> -o json`; if `primary_replica` moved again, repeat the failover with `--expect-current <primary_replica>@<epoch>`. No read confirms that the primary stays: blockmaster applies the queued rebalance when its assignment queue reaches it, not at a fixed time, so it can still move the primary after any read, and the guest is then started again on the new primary. Fixed in v1.1.2: blockmaster refuses a queued rebalance or failover when the volume's line moved after it was decided, so one decided before an operator's failover is no longer applied after it. A rebalance decided after the failover can still move the primary, as any rebalance can.
- What to do: after `sw-block ops failover`, read the volume's line with `sw-block ops volumes --master-api <addr> -o json`; if `primary_replica` moved again, repeat the failover with `--expect-current <primary_replica>@<epoch>`. No read confirms that the primary stays: blockmaster applies the queued rebalance when its assignment queue reaches it, not at a fixed time, so it can still move the primary after any read, and the guest is then started again on the new primary. A fix is planned for a later v1.1.x release.
## Known issue: resuming an interrupted snapshot delete can stop the volume's snapshot deletes and cleaning
-11
View File
@@ -2,19 +2,8 @@
v1.1.2 is not yet released.
## Fixed
- **Replicated volumes (preview): a queued rebalance no longer undoes an operator failover.** blockmaster's automatic
rebalance and failover name the volume's line they were decided against, and blockmaster refuses one when that line
moved since (another replica or epoch, or other addresses). A rebalance decided just before `sw-block ops failover`
is no longer applied after it. This was a v1.1.1 known issue.
## Known issue: blockmaster restart can stall on a busy filesystem
- **Trigger:** blockmaster's state directory or its ancestors share a filesystem with heavy writes, such as the holders' local data.
- **Effect:** blockmaster's start syncs its state directories, which can wait for the filesystem journal. When the import has changed records, it also runs a `syncfs` for each store with changed records on ext4, XFS, btrfs or tmpfs (Linux 5.8 or later), which waits for every pending write on that filesystem, including the holders' data. Starts took from about 20 seconds to over 150 seconds in our tests (one start was not ready after 2 minutes); this is not an upper bound. A volume whose lease expires stops serving until blockmaster is back; it is then granted again on the same holder, with its data. A forced move during that time can lose writes after the last published HEAD (see [forced move](../volume-lifecycle.md#after-a-crash)).
- **What to do:** keep the holders' data off both the state directory's filesystem and the filesystem holding its ancestor directories. In practice, put the holders' data on its own filesystem, not the root filesystem. A different directory on the same filesystem is not enough. A dedicated state-directory mount alone does not isolate every startup sync: opening the store also syncs ancestors up to `/`, including `/var/lib` and `/var` with the shipped layout. Restart blockmaster at low write load on all those filesystems. This limitation also applies when the cluster spec has not changed.
## Lifecycle persistence failures
A blockmaster lifecycle put, import or open-barrier persistence failure exits with durability-unknown status 74 instead of generic status 1. Both immediate termination and the one-second fallback use that status. The best-effort ERROR diagnostic names `lifecycle_persist_failed`. Run blockmaster under supervision so a failed process restarts from durable state; record ordering, recovery barriers and import syncfs selection are unchanged.
+3
View File
@@ -33,6 +33,9 @@ terraform/
aws-ha-distributed/ 3 masters + 3 volumes (1/AZ) + 2 filers + 1 S3,
secure-by-default (mTLS via SSM-delivered certs)
aws-all-in-one/ single `weed server` instance via core directly
provider/ Terraform provider (Go) that manages S3 buckets and their
configuration, IAM and S3 Tables through a running cluster's
S3 and IAM APIs; see provider/README.md.
test/
local/ render a cluster with core and run it as real weed processes
on 127.0.0.1 (no cloud, no docker), then assert it works
+1
View File
@@ -0,0 +1 @@
/bin/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 LuisCosta
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+27
View File
@@ -0,0 +1,27 @@
SHELL := /bin/bash
.PHONY: fmt test test-race build docs check lint vuln
fmt:
go fmt ./...
terraform -chdir=examples/basic fmt
test:
go test ./...
test-race:
go test -race ./...
build:
go build ./...
docs:
go generate ./...
check: fmt test build
lint:
go vet ./...
vuln:
govulncheck ./...
+135
View File
@@ -0,0 +1,135 @@
# terraform-provider-seaweedfs
Terraform and OpenTofu provider for SeaweedFS S3, IAM, and S3 Tables APIs. The
provider targets SeaweedFS 4.51 API behavior and supports importing every
managed resource; each resource's documentation lists its import identifier.
Originally written by Luís Costa as
[terraform-provider-seaweedfs](https://github.com/luiscosta18/terraform-provider-seaweedfs)
and licensed under the MIT license in [LICENSE](LICENSE).
## Managed resources
- **S3 buckets:** bucket lifecycle and tags, CORS, lifecycle rules, versioning,
bucket policies, encryption, public access block, ownership controls,
requester-pays configuration, and SeaweedFS bucket quotas.
- **IAM:** users, access keys, inline user/group policies, groups and
authoritative group membership, roles and trust policies, managed policies,
user/group/role policy attachments, OIDC providers, and service accounts.
- **S3 Tables:** table buckets and policies, namespaces, Iceberg tables and
table policies, resource tags, and bucket/table maintenance configuration.
S3 bucket configuration documents and S3 Tables table metadata are passed as
JSON strings using the SeaweedFS/AWS API field names. IAM and S3 Tables policy
documents are JSON strings as well.
### Lifecycle and secret notes
- Destroying bucket versioning suspends versioning; S3 has no operation to
remove the versioning configuration. Request-payment destroy resets the
payer to the bucket owner, and quota destroy disables the quota.
- S3 Tables maintenance configuration has no delete API; destroy disables the
maintenance type.
- A service-account secret is returned only at creation and is retained in
Terraform state. `sensitive` masks CLI output but does not encrypt state.
Use an encrypted, access-controlled state backend and protect state backups.
- SeaweedFS stores one active managed-policy version; policy updates replace
that document in place.
Object data operations, cluster installation, and irreversible object-lock
configuration are intentionally not modeled as Terraform resources.
## SeaweedFS compatibility
IAM feature availability can vary between SeaweedFS deployments. In particular,
`CreateAccessKey` has returned `ServiceFailure: Internal server error` in some
deployments. Run the integration smoke test against the exact SeaweedFS version
and configuration you intend to use before relying on IAM resources.
## Build
```bash
cd terraform/provider
go build -o bin/terraform-provider-seaweedfs .
```
## Generate Docs
```bash
make docs
```
This runs `tfplugindocs` via `go generate` and updates files under `docs/`.
## Use locally with Terraform
Create `~/.terraformrc`:
```hcl
provider_installation {
dev_overrides {
"seaweedfs/seaweedfs" = "/absolute/path/to/seaweedfs/terraform/provider/bin"
}
direct {}
}
```
Then in your Terraform config:
```hcl
terraform {
required_providers {
seaweedfs = {
source = "seaweedfs/seaweedfs"
}
}
}
provider "seaweedfs" {
endpoint = "https://s3.example.com"
region = "us-east-1"
access_key = var.admin_access_key
secret_key = var.admin_secret_key
}
resource "seaweedfs_iam_user" "example" {
name = "example-user"
}
```
`endpoint`, `access_key`, and `secret_key` may alternatively be supplied by
`SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, and `SEAWEEDFS_SECRET_KEY`.
`SEAWEEDFS_REGION` defaults to `us-east-1`; `SEAWEEDFS_INSECURE` accepts
`true`/`false` and defaults to `false`. Explicit provider configuration takes
precedence over environment variables.
## Tests
```sh
make test-race
make lint
```
The `terraform: validate and test modules` workflow builds, vets and
unit-tests this module on every change under `terraform/`.
## Local SeaweedFS integration smoke test
The smoke fixture exercises bucket/tagging, core IAM, S3 Tables, and table
maintenance create/read behavior with OpenTofu against the SeaweedFS version the
chart deploys (by default the in-tree `k8s/charts/seaweedfs`, whose `appVersion`
sets the image tag; set `SEAWEEDFS_CHART` to use another chart):
```sh
make test-race
tofu fmt -check -recursive
./scripts/minikube-smoke.sh
```
The script requires a running Minikube profile, `seaweedfs-podman-smoke` by
default (set `MINIKUBE_PROFILE` to use another). It installs the chart from
`k8s/charts/seaweedfs` unless `SEAWEEDFS_CHART` points elsewhere, and forwards
the S3 port to `127.0.0.1:${SEAWEEDFS_LOCAL_PORT:-8333}`. It creates the namespace and Helm
resources if needed, but does not delete the cluster, release, or Terraform
resources. It applies the example automatically; use only a disposable test
cluster and review the local example state before any manual cleanup.
+23
View File
@@ -0,0 +1,23 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs Provider"
description: |-
---
# seaweedfs Provider
<!-- schema generated by tfplugindocs -->
## Schema
### Optional
- `access_key` (String, Sensitive) Admin access key. Falls back to SEAWEEDFS_ACCESS_KEY.
- `endpoint` (String) SeaweedFS S3/IAM endpoint. Falls back to SEAWEEDFS_ENDPOINT.
- `insecure` (Boolean) Skip TLS verification. Falls back to SEAWEEDFS_INSECURE.
- `region` (String) Signing region. Falls back to SEAWEEDFS_REGION. Default: us-east-1.
- `secret_key` (String, Sensitive) Admin secret key. Falls back to SEAWEEDFS_SECRET_KEY.
@@ -0,0 +1,29 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 bucket.
---
# seaweedfs_bucket (Resource)
Manages a SeaweedFS S3 bucket.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) Bucket name.
### Optional
- `tags` (Map of String) Bucket tags.
### Read-Only
- `arn` (String) Bucket ARN.
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_cors_configuration Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 bucket CORS configuration. Configuration is JSON encoded. Import using the bucket name.
---
# seaweedfs_bucket_cors_configuration (Resource)
Manages a SeaweedFS S3 bucket CORS configuration. Configuration is JSON encoded. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `configuration` (String) JSON encoded configuration document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_encryption Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 bucket default encryption configuration. Configuration is JSON encoded. Import using the bucket name.
---
# seaweedfs_bucket_encryption (Resource)
Manages a SeaweedFS S3 bucket default encryption configuration. Configuration is JSON encoded. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `configuration` (String) JSON encoded configuration document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_lifecycle_configuration Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 bucket lifecycle configuration. Configuration is JSON encoded. Import using the bucket name.
---
# seaweedfs_bucket_lifecycle_configuration (Resource)
Manages a SeaweedFS S3 bucket lifecycle configuration. Configuration is JSON encoded. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `configuration` (String) JSON encoded configuration document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_ownership_controls Resource - seaweedfs"
subcategory: ""
description: |-
Manages SeaweedFS S3 bucket ownership controls. Configuration is JSON encoded. Import using the bucket name.
---
# seaweedfs_bucket_ownership_controls (Resource)
Manages SeaweedFS S3 bucket ownership controls. Configuration is JSON encoded. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `configuration` (String) JSON encoded configuration document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_policy Resource - seaweedfs"
subcategory: ""
description: |-
Manages the S3 bucket policy in SeaweedFS. Import using the bucket name.
---
# seaweedfs_bucket_policy (Resource)
Manages the S3 bucket policy in SeaweedFS. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `policy` (String) JSON bucket policy document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_public_access_block Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 bucket public access block configuration where supported. SeaweedFS 4.51.0 returns NotImplemented for this API. Import using the bucket name.
---
# seaweedfs_bucket_public_access_block (Resource)
Manages a SeaweedFS S3 bucket public access block configuration where supported. SeaweedFS 4.51.0 returns NotImplemented for this API. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `configuration` (String) JSON encoded configuration document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,26 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_quota Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS-specific S3 bucket storage quota. Import using the bucket name.
---
# seaweedfs_bucket_quota (Resource)
Manages a SeaweedFS-specific S3 bucket storage quota. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `enabled` (Boolean) Whether SeaweedFS enforces the quota.
- `quota_bytes` (Number) Maximum bucket size in bytes. Use zero only when the quota is disabled.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_request_payment Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 bucket request payment configuration. Destroy resets the payer to BucketOwner. SeaweedFS accepts only BucketOwner; it rejects Requester with MalformedXML. Import using the bucket name.
---
# seaweedfs_bucket_request_payment (Resource)
Manages a SeaweedFS S3 bucket request payment configuration. Destroy resets the payer to BucketOwner. SeaweedFS accepts only `BucketOwner`; it rejects `Requester` with `MalformedXML`. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `configuration` (String) JSON encoded configuration document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_bucket_versioning Resource - seaweedfs"
subcategory: ""
description: |-
Manages SeaweedFS S3 bucket versioning. Configuration is JSON encoded; destroy suspends versioning because S3 cannot unset it. On a bucket with object lock, SeaweedFS rejects the suspension with InvalidBucketState, so remove the resource with terraform state rm instead of destroying it. Import using the bucket name.
---
# seaweedfs_bucket_versioning (Resource)
Manages SeaweedFS S3 bucket versioning. Configuration is JSON encoded; destroy suspends versioning because S3 cannot unset it. On a bucket with object lock, SeaweedFS rejects the suspension with InvalidBucketState, so remove the resource with `terraform state rm` instead of destroying it. Import using the bucket name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `bucket` (String) S3 bucket name.
- `configuration` (String) JSON encoded configuration document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,27 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_access_key Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS IAM access key for a user. Import using user_name,access_key_id; an imported key has no secret_access_key, because SeaweedFS returns the secret only at creation.
---
# seaweedfs_iam_access_key (Resource)
Manages a SeaweedFS IAM access key for a user. Import using `user_name,access_key_id`; an imported key has no `secret_access_key`, because SeaweedFS returns the secret only at creation.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `user_name` (String)
### Read-Only
- `access_key_id` (String)
- `id` (String) The ID of this resource.
- `secret_access_key` (String, Sensitive)
- `status` (String)
@@ -0,0 +1,24 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_group Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS IAM group. Group membership and attached policies are managed by separate resources. Import using the group name.
---
# seaweedfs_iam_group (Resource)
Manages a SeaweedFS IAM group. Group membership and attached policies are managed by separate resources. Import using the group name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `name` (String)
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_group_membership Resource - seaweedfs"
subcategory: ""
description: |-
Manages the complete user membership set for a SeaweedFS IAM group. Import using the group name.
---
# seaweedfs_iam_group_membership (Resource)
Manages the complete user membership set for a SeaweedFS IAM group. Import using the group name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `group_name` (String)
- `users` (Set of String) IAM user names that belong to the group.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,26 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_group_policy Resource - seaweedfs"
subcategory: ""
description: |-
Manages an inline IAM group policy in SeaweedFS. Import using group_name,policy_name.
---
# seaweedfs_iam_group_policy (Resource)
Manages an inline IAM group policy in SeaweedFS. Import using `group_name,policy_name`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `group_name` (String)
- `name` (String)
- `policy` (String) JSON policy document.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_group_policy_attachment Resource - seaweedfs"
subcategory: ""
description: |-
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM group. Import using group_name,policy_arn.
---
# seaweedfs_iam_group_policy_attachment (Resource)
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM group. Import using `group_name,policy_arn`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `group_name` (String) IAM group name.
- `policy_arn` (String) ARN of the managed IAM policy.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,27 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_oidc_provider Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS IAM OpenID Connect provider. Import using the provider ARN.
---
# seaweedfs_iam_oidc_provider (Resource)
Manages a SeaweedFS IAM OpenID Connect provider. Import using the provider ARN.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `client_ids` (Set of String) Client IDs allowed to use the provider.
- `thumbprints` (Set of String) TLS certificate thumbprints trusted for the provider. At least one is required.
- `url` (String) Issuer URL for the OIDC provider.
### Read-Only
- `arn` (String)
- `id` (String) The ID of this resource.
@@ -0,0 +1,26 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_policy Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS IAM managed policy. SeaweedFS stores one active policy version; updates replace that document in place. Import using the policy ARN or name.
---
# seaweedfs_iam_policy (Resource)
Manages a SeaweedFS IAM managed policy. SeaweedFS stores one active policy version; updates replace that document in place. Import using the policy ARN or name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `name` (String) Managed policy name.
- `policy` (String) JSON policy document.
### Read-Only
- `arn` (String) Managed policy ARN.
- `id` (String) The ID of this resource.
@@ -0,0 +1,30 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_role Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS IAM role. SeaweedFS roles do not support paths or mutable descriptions/session duration; changing those attributes replaces the role. Import using the role name.
---
# seaweedfs_iam_role (Resource)
Manages a SeaweedFS IAM role. SeaweedFS roles do not support paths or mutable descriptions/session duration; changing those attributes replaces the role. Import using the role name.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `assume_role_policy` (String) JSON trust policy document.
- `name` (String) IAM role name.
### Optional
- `description` (String) Role description.
- `max_session_duration` (Number) Maximum role session duration in seconds.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_role_policy_attachment Resource - seaweedfs"
subcategory: ""
description: |-
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM role. Import using role_name,policy_arn.
---
# seaweedfs_iam_role_policy_attachment (Resource)
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM role. Import using `role_name,policy_arn`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `policy_arn` (String) ARN of the managed IAM policy.
- `role_name` (String) IAM role name.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,33 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_service_account Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS IAM service account. The secret key is returned only at creation and is retained in Terraform state; mark state storage as sensitive. Import using the service account ID.
---
# seaweedfs_iam_service_account (Resource)
Manages a SeaweedFS IAM service account. The secret key is returned only at creation and is retained in Terraform state; mark state storage as sensitive. Import using the service account ID.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `parent_user` (String) IAM user that owns this service account.
### Optional
- `description` (String) Service account description. Set to an empty string to clear it.
- `expiration` (String) Expiration time in RFC3339 format. Set to an empty string to remove expiration.
- `status` (String) Credential status: Active or Inactive.
### Read-Only
- `access_key_id` (String)
- `id` (String) The ID of this resource.
- `secret_key` (String, Sensitive)
- `service_account_id` (String)
@@ -0,0 +1,30 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_user Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS IAM user using IAM query API calls.
---
# seaweedfs_iam_user (Resource)
Manages a SeaweedFS IAM user using IAM query API calls.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `name` (String) IAM user name.
### Optional
- `path` (String) IAM path for the user. SeaweedFS 4.51.0 supports only `/`.
### Read-Only
- `arn` (String) ARN returned by SeaweedFS.
- `id` (String) Terraform identifier for this resource. Equals user name.
- `user_id` (String) Unique user identifier returned by SeaweedFS.
@@ -0,0 +1,26 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_user_policy Resource - seaweedfs"
subcategory: ""
description: |-
Manages an inline IAM user policy in SeaweedFS. Import using user_name,policy_name.
---
# seaweedfs_iam_user_policy (Resource)
Manages an inline IAM user policy in SeaweedFS. Import using `user_name,policy_name`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `name` (String)
- `policy` (String) JSON policy document.
- `user_name` (String)
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_iam_user_policy_attachment Resource - seaweedfs"
subcategory: ""
description: |-
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM user. Import using user_name,policy_arn.
---
# seaweedfs_iam_user_policy_attachment (Resource)
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM user. Import using `user_name,policy_arn`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `policy_arn` (String) ARN of the managed IAM policy.
- `user_name` (String) IAM user name.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,37 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_table Resource - seaweedfs"
subcategory: ""
description: |-
Manages an Iceberg table in a SeaweedFS S3 Tables namespace. Table schema metadata is JSON encoded. Import using table_bucket_arn,namespace,table_name.
---
# seaweedfs_table (Resource)
Manages an Iceberg table in a SeaweedFS S3 Tables namespace. Table schema metadata is JSON encoded. Import using `table_bucket_arn,namespace,table_name`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `format` (String) Table format, typically ICEBERG.
- `name` (String)
- `namespace` (String)
- `table_bucket_arn` (String)
### Optional
- `metadata` (String) Optional JSON encoded table metadata, including Iceberg schema fields.
- `tags` (Map of String) Tags applied to the table.
### Read-Only
- `created_at` (String)
- `id` (String) The ID of this resource.
- `metadata_location` (String)
- `modified_at` (String)
- `table_arn` (String)
- `version_token` (String)
@@ -0,0 +1,32 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_table_bucket Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 Tables bucket. Import using its table bucket ARN.
---
# seaweedfs_table_bucket (Resource)
Manages a SeaweedFS S3 Tables bucket. Import using its table bucket ARN.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `name` (String) Table bucket name.
### Optional
- `format` (String) Table format served by the bucket, such as ICEBERG.
- `tags` (Map of String) Tags applied to the table bucket.
### Read-Only
- `arn` (String)
- `created_at` (String)
- `id` (String) The ID of this resource.
- `owner_account_id` (String)
@@ -0,0 +1,31 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_table_bucket_maintenance_configuration Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 Tables maintenance configuration. Import using table_bucket_arn. Deletion disables the configuration because the S3 Tables API has no delete operation.
---
# seaweedfs_table_bucket_maintenance_configuration (Resource)
Manages a SeaweedFS S3 Tables maintenance configuration. Import using `table_bucket_arn`. Deletion disables the configuration because the S3 Tables API has no delete operation.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `status` (String) Whether the maintenance operation is enabled or disabled.
- `table_bucket_arn` (String)
### Optional
- `non_current_days` (Number) Age in days after which non-current files may be removed.
- `unreferenced_days` (Number) Age in days after which unreferenced files may be removed.
### Read-Only
- `id` (String) The ID of this resource.
- `type` (String) The bucket maintenance type is icebergUnreferencedFileRemoval.
@@ -0,0 +1,25 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_table_bucket_policy Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 Tables table bucket policy policy. Import using table_bucket_arn.
---
# seaweedfs_table_bucket_policy (Resource)
Manages a SeaweedFS S3 Tables table bucket policy policy. Import using `table_bucket_arn`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `policy` (String) JSON resource policy.
- `table_bucket_arn` (String)
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,35 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_table_maintenance_configuration Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 Tables maintenance configuration. Import using table_bucket_arn,namespace,table_name,type. Deletion disables the configuration because the S3 Tables API has no delete operation.
---
# seaweedfs_table_maintenance_configuration (Resource)
Manages a SeaweedFS S3 Tables maintenance configuration. Import using `table_bucket_arn,namespace,table_name,type`. Deletion disables the configuration because the S3 Tables API has no delete operation.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `name` (String)
- `namespace` (String)
- `status` (String) Whether the maintenance operation is enabled or disabled.
- `table_bucket_arn` (String)
- `type` (String) Maintenance type: icebergCompaction or icebergSnapshotManagement.
### Optional
- `max_snapshot_age_hours` (Number) Maximum snapshot age in hours. Only applies to icebergSnapshotManagement.
- `min_snapshots_to_keep` (Number) Minimum snapshots to retain. Only applies to icebergSnapshotManagement.
- `strategy` (String) Compaction strategy: auto, binpack, or sort. Only applies to icebergCompaction.
- `target_file_size_mb` (Number) Target compacted file size in MiB. Only applies to icebergCompaction.
### Read-Only
- `id` (String) The ID of this resource.
@@ -0,0 +1,27 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_table_namespace Resource - seaweedfs"
subcategory: ""
description: |-
Manages a namespace in a SeaweedFS S3 Tables bucket. Use a dot-separated path for nested namespaces. Import using table_bucket_arn,namespace.
---
# seaweedfs_table_namespace (Resource)
Manages a namespace in a SeaweedFS S3 Tables bucket. Use a dot-separated path for nested namespaces. Import using `table_bucket_arn,namespace`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `namespace` (String) Namespace name or dot-separated namespace path.
- `table_bucket_arn` (String)
### Read-Only
- `created_at` (String)
- `id` (String) The ID of this resource.
- `owner_account_id` (String)
@@ -0,0 +1,27 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "seaweedfs_table_policy Resource - seaweedfs"
subcategory: ""
description: |-
Manages a SeaweedFS S3 Tables table policy policy. Import using table_bucket_arn,namespace,table_name.
---
# seaweedfs_table_policy (Resource)
Manages a SeaweedFS S3 Tables table policy policy. Import using `table_bucket_arn,namespace,table_name`.
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `name` (String)
- `namespace` (String)
- `policy` (String) JSON resource policy.
- `table_bucket_arn` (String)
### Read-Only
- `id` (String) The ID of this resource.
+69
View File
@@ -0,0 +1,69 @@
terraform {
required_version = ">= 1.6.0"
required_providers {
seaweedfs = {
source = "seaweedfs/seaweedfs"
version = ">= 0.1.0"
}
}
}
provider "seaweedfs" {
endpoint = var.endpoint
region = var.region
access_key = var.access_key
secret_key = var.secret_key
insecure = var.insecure
}
resource "seaweedfs_iam_user" "test" {
name = var.user_name
}
resource "seaweedfs_bucket" "test" {
count = var.create_bucket ? 1 : 0
bucket = var.bucket_name
tags = {
managed_by = "terraform"
project = "homelab"
}
}
resource "seaweedfs_iam_user_policy" "test" {
count = var.create_user_policy ? 1 : 0
user_name = seaweedfs_iam_user.test.name
name = var.policy_name
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["s3:*"]
Resource = [
"arn:aws:s3:::${var.bucket_name}",
"arn:aws:s3:::${var.bucket_name}/*",
]
}]
})
}
resource "seaweedfs_iam_access_key" "test" {
count = var.create_access_key ? 1 : 0
user_name = seaweedfs_iam_user.test.name
}
output "user_name" {
value = seaweedfs_iam_user.test.name
}
output "user_arn" {
value = seaweedfs_iam_user.test.arn
}
output "bucket_name" {
value = var.create_bucket ? seaweedfs_bucket.test[0].bucket : null
}
output "access_key_id" {
value = var.create_access_key ? seaweedfs_iam_access_key.test[0].access_key_id : null
sensitive = true
}
@@ -0,0 +1,64 @@
variable "endpoint" {
type = string
description = "SeaweedFS endpoint."
}
variable "region" {
type = string
description = "SigV4 region."
default = "us-east-1"
}
variable "access_key" {
type = string
description = "Admin access key."
sensitive = true
}
variable "secret_key" {
type = string
description = "Admin secret key."
sensitive = true
}
variable "insecure" {
type = bool
description = "Skip TLS verification."
default = false
}
variable "user_name" {
type = string
description = "User to create."
default = "tf-seaweedfs-test-user"
}
variable "bucket_name" {
type = string
description = "Bucket to create for testing."
default = "tf-seaweedfs-test-bucket"
}
variable "policy_name" {
type = string
description = "Inline policy name for the test user."
default = "tf-seaweedfs-test-policy"
}
variable "create_bucket" {
type = bool
description = "Whether to create the test bucket."
default = true
}
variable "create_user_policy" {
type = bool
description = "Whether to create and attach a user inline policy."
default = true
}
variable "create_access_key" {
type = bool
description = "Whether to create an IAM access key for the user."
default = false
}
+95
View File
@@ -0,0 +1,95 @@
terraform {
required_version = ">= 1.6.0"
required_providers {
seaweedfs = {
source = "seaweedfs/seaweedfs"
version = ">= 0.1.0"
}
}
}
provider "seaweedfs" {
endpoint = var.seaweedfs_endpoint
region = var.seaweedfs_region
access_key = var.admin_access_key
secret_key = var.admin_secret_key
}
resource "seaweedfs_bucket" "smoke" {
bucket = "terraform-provider-smoke"
tags = {
environment = "local"
managed-by = "terraform"
}
}
resource "seaweedfs_iam_user" "smoke" {
name = "terraform-provider-smoke"
}
resource "seaweedfs_iam_access_key" "smoke" {
user_name = seaweedfs_iam_user.smoke.name
}
resource "seaweedfs_iam_user_policy" "smoke" {
user_name = seaweedfs_iam_user.smoke.name
name = "S3SmokePolicy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["s3:*"]
Resource = ["arn:aws:s3:::terraform-provider-smoke", "arn:aws:s3:::terraform-provider-smoke/*"]
}]
})
}
resource "seaweedfs_table_bucket" "lake" {
name = "terraform-provider-smoke-lake"
format = "ICEBERG"
tags = {
environment = "local"
managed-by = "terraform"
}
}
resource "seaweedfs_table_bucket_maintenance_configuration" "cleanup" {
table_bucket_arn = seaweedfs_table_bucket.lake.arn
status = "enabled"
unreferenced_days = 30
}
resource "seaweedfs_table_namespace" "analytics" {
table_bucket_arn = seaweedfs_table_bucket.lake.arn
namespace = "analytics"
}
resource "seaweedfs_table" "orders" {
table_bucket_arn = seaweedfs_table_bucket.lake.arn
namespace = seaweedfs_table_namespace.analytics.namespace
name = "orders"
format = "ICEBERG"
metadata = jsonencode({
iceberg = {
schema = {
fields = [
{
name = "order_id"
type = "long"
required = true
}
]
}
}
})
}
resource "seaweedfs_table_maintenance_configuration" "compaction" {
table_bucket_arn = seaweedfs_table_bucket.lake.arn
namespace = seaweedfs_table_namespace.analytics.namespace
name = seaweedfs_table.orders.name
type = "icebergCompaction"
status = "enabled"
strategy = "binpack"
target_file_size_mb = 512
}
@@ -0,0 +1,20 @@
variable "seaweedfs_endpoint" {
type = string
description = "SeaweedFS S3/IAM endpoint."
}
variable "seaweedfs_region" {
type = string
description = "AWS SigV4 signing region."
default = "us-east-1"
}
variable "admin_access_key" {
type = string
sensitive = true
}
variable "admin_secret_key" {
type = string
sensitive = true
}
+44
View File
@@ -0,0 +1,44 @@
module github.com/seaweedfs/seaweedfs/terraform/provider
go 1.27.4
require (
github.com/aws/aws-sdk-go-v2 v1.49.0
github.com/aws/aws-sdk-go-v2/credentials v1.21.7
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3
github.com/aws/smithy-go v1.28.13
github.com/hashicorp/terraform-plugin-framework v1.17.0
github.com/hashicorp/terraform-plugin-go v0.29.0
)
require (
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-plugin v1.7.0 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/hashicorp/terraform-plugin-log v0.10.0 // indirect
github.com/hashicorp/terraform-registry-address v0.4.0 // indirect
github.com/hashicorp/terraform-svchost v0.1.1 // indirect
github.com/hashicorp/yamux v0.1.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/oklog/run v1.1.0 // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
golang.org/x/net v0.62.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.11 // indirect
)
+125
View File
@@ -0,0 +1,125 @@
github.com/aws/aws-sdk-go-v2 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
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/credentials v1.21.7 h1:KtckEwHoY6AlldyiX4QAtekiL0S/AITVIYdqZnWWWcA=
github.com/aws/aws-sdk-go-v2/credentials v1.21.7/go.mod h1:YnM7TYbV1J65/yn/4E0Rnj9A/UO2OTeiGNZP8tcYKRw=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 h1:XKIkHY7yRHnTJrixMmcA1qIm3qenDe/vmOtf/xiuWYE=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15/go.mod h1:HqYW3gHCQl0tF6dO7kXgc0wFe1Yng0hgCEI7Xa3rK54=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27/go.mod h1:LpMjYa8iT3kMkAxsVCGfyXkBDOOKsziY6S2wSpEvY70=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 h1:ds6Pm/S5xYXPmiqyebd0AeK0zHAAO7qHP1+JZauFnpA=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15/go.mod h1:WqaHpxUhwzsE+NYp2TQitKclpwhi1XYp6wMsdg+yd/k=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ=
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 h1:HwxWTbTrIHm5qY+CAEur0s/figc3qwvLWsNkF4RPToo=
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
github.com/aws/smithy-go v1.28.13 h1:cBdveQH7NJe99gJKArwOKc11/57r17Gjq374TgDs6LY=
github.com/aws/smithy-go v1.28.13/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
github.com/hashicorp/go-plugin v1.7.0 h1:YghfQH/0QmPNc/AZMTFE3ac8fipZyZECHdDPshfk+mA=
github.com/hashicorp/go-plugin v1.7.0/go.mod h1:BExt6KEaIYx804z8k4gRzRLEvxKVb+kn0NMcihqOqb8=
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/terraform-plugin-framework v1.17.0 h1:JdX50CFrYcYFY31gkmitAEAzLKoBgsK+iaJjDC8OexY=
github.com/hashicorp/terraform-plugin-framework v1.17.0/go.mod h1:4OUXKdHNosX+ys6rLgVlgklfxN3WHR5VHSOABeS/BM0=
github.com/hashicorp/terraform-plugin-go v0.29.0 h1:1nXKl/nSpaYIUBU1IG/EsDOX0vv+9JxAltQyDMpq5mU=
github.com/hashicorp/terraform-plugin-go v0.29.0/go.mod h1:vYZbIyvxyy0FWSmDHChCqKvI40cFTDGSb3D8D70i9GM=
github.com/hashicorp/terraform-plugin-log v0.10.0 h1:eu2kW6/QBVdN4P3Ju2WiB2W3ObjkAsyfBsL3Wh1fj3g=
github.com/hashicorp/terraform-plugin-log v0.10.0/go.mod h1:/9RR5Cv2aAbrqcTSdNmY1NRHP4E3ekrXRGjqORpXyB0=
github.com/hashicorp/terraform-registry-address v0.4.0 h1:S1yCGomj30Sao4l5BMPjTGZmCNzuv7/GDTDX99E9gTk=
github.com/hashicorp/terraform-registry-address v0.4.0/go.mod h1:LRS1Ay0+mAiRkUyltGT+UHWkIqTFvigGn/LbMshfflE=
github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ=
github.com/hashicorp/terraform-svchost v0.1.1/go.mod h1:mNsjQfZyf/Jhz35v6/0LWcv26+X7JPS+buii2c9/ctc=
github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=
github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5XumQh94=
github.com/jhump/protoreflect v1.17.0/go.mod h1:h9+vUUL38jiBzck8ck+6G/aeMX8Z4QUY/NiJPwPNi+8=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU=
github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8=
github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+34
View File
@@ -0,0 +1,34 @@
package main
import (
"context"
"flag"
"log"
"github.com/hashicorp/terraform-plugin-framework/providerserver"
"github.com/seaweedfs/seaweedfs/terraform/provider/seaweedfs"
)
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs@v0.25.0 generate --provider-name seaweedfs
var (
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
var debug bool
flag.BoolVar(&debug, "debug", false, "set to true to run the provider with support for debuggers")
flag.Parse()
opts := providerserver.ServeOpts{
Address: "registry.terraform.io/seaweedfs/seaweedfs",
Debug: debug,
}
if err := providerserver.Serve(context.Background(), seaweedfs.NewProvider, opts); err != nil {
log.Fatal(err.Error())
}
}
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
CHART=${SEAWEEDFS_CHART:-$ROOT/../../k8s/charts/seaweedfs}
NAMESPACE=${SEAWEEDFS_NAMESPACE:-seaweedfs}
RELEASE=${SEAWEEDFS_RELEASE:-seaweedfs}
PROFILE=${MINIKUBE_PROFILE:-seaweedfs-podman-smoke}
LOCAL_PORT=${SEAWEEDFS_LOCAL_PORT:-8333}
ENDPOINT="http://127.0.0.1:$LOCAL_PORT"
for tool in minikube kubectl helm tofu curl python3; do
command -v "$tool" >/dev/null || {
echo "missing required tool: $tool" >&2
exit 1
}
done
if [ ! -e "$CHART" ]; then
echo "SeaweedFS chart not found: $CHART (set SEAWEEDFS_CHART)" >&2
exit 1
fi
helm show chart "$CHART" >/dev/null
MINIKUBE_ROOTLESS=true minikube -p "$PROFILE" status >/dev/null 2>&1 || {
echo "Minikube profile $PROFILE is unavailable. Start it with the host-compatible driver." >&2
exit 2
}
kubectl config use-context "$PROFILE" >/dev/null
kubectl get namespace "$NAMESPACE" >/dev/null 2>&1 || kubectl create namespace "$NAMESPACE"
if ! kubectl -n "$NAMESPACE" get secret seaweedfs-iam-config >/dev/null 2>&1; then
IAM_CONFIG=$(mktemp)
trap 'rm -f -- "$IAM_CONFIG"' EXIT
python3 - "$IAM_CONFIG" <<'PY'
import base64
import json
import os
import secrets
import sys
config = {
"sts": {
"issuer": "https://seaweedfs.test",
"signingKey": base64.b64encode(secrets.token_bytes(32)).decode("ascii"),
},
"roleStore": {"storeType": "memory"},
"oidcProviderStore": {"storeType": "memory"},
}
with open(sys.argv[1], "w", encoding="utf-8") as config_file:
json.dump(config, config_file)
os.chmod(sys.argv[1], 0o600)
PY
kubectl -n "$NAMESPACE" create secret generic seaweedfs-iam-config \
--from-file=iam-config.json="$IAM_CONFIG" \
--dry-run=client -o yaml | kubectl apply -f -
rm -f -- "$IAM_CONFIG"
trap - EXIT
fi
helm upgrade --install "$RELEASE" "$CHART" \
--namespace "$NAMESPACE" \
--values "$ROOT/test-fixtures/minikube-values.yaml" \
--wait --timeout 10m
kubectl -n "$NAMESPACE" rollout status deployment/"$RELEASE"-all-in-one --timeout=5m
PORT_FORWARD_LOG=$(mktemp)
kubectl -n "$NAMESPACE" port-forward --address 127.0.0.1 service/"$RELEASE"-all-in-one "$LOCAL_PORT":8333 >"$PORT_FORWARD_LOG" 2>&1 &
PF_PID=$!
cleanup() {
kill "$PF_PID" 2>/dev/null || true
rm -f -- "$PORT_FORWARD_LOG"
if [[ -n "${TMP_CONFIG:-}" ]]; then
rm -f -- "$TMP_CONFIG"
fi
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
attempt=1
while [ "$attempt" -le 30 ]; do
if ! kill -0 "$PF_PID" 2>/dev/null; then
echo "kubectl port-forward exited:" >&2
cat "$PORT_FORWARD_LOG" >&2
exit 1
fi
if grep -q "Forwarding from 127.0.0.1:$LOCAL_PORT" "$PORT_FORWARD_LOG" &&
curl -sS --max-time 1 -o /dev/null "$ENDPOINT/" 2>/dev/null; then
break
fi
attempt=$((attempt + 1))
sleep 1
done
if [ "$attempt" -gt 30 ]; then
echo "SeaweedFS S3 gateway did not become ready on $ENDPOINT" >&2
cat "$PORT_FORWARD_LOG" >&2
exit 1
fi
mkdir -p "$ROOT/bin"
(cd "$ROOT" && go build -o bin/terraform-provider-seaweedfs .)
TMP_CONFIG=$(mktemp)
cat >"$TMP_CONFIG" <<EOF
provider_installation {
dev_overrides {
"seaweedfs/seaweedfs" = "$ROOT/bin"
}
direct {}
}
EOF
export TF_CLI_CONFIG_FILE="$TMP_CONFIG"
export TF_IN_AUTOMATION=1
cd "$ROOT/examples/full"
tofu validate
tofu apply -input=false -auto-approve \
-var="seaweedfs_endpoint=$ENDPOINT" \
-var="admin_access_key=terraform-admin" \
-var="admin_secret_key=terraform-admin-secret-key-000000000001"
tofu plan -input=false -detailed-exitcode \
-var="seaweedfs_endpoint=$ENDPOINT" \
-var="admin_access_key=terraform-admin" \
-var="admin_secret_key=terraform-admin-secret-key-000000000001"
+613
View File
@@ -0,0 +1,613 @@
package seaweedfs
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
)
type iamClientConfig struct {
Endpoint string
Region string
AccessKey string
SecretKey string
Insecure bool
}
type iamClient struct {
endpoint string
region string
creds aws.CredentialsProvider
signer *v4.Signer
http *http.Client
s3 *s3.Client
}
type iamError struct {
Code string
Message string
}
type iamErrorEnvelope struct {
Code string `xml:"Code"`
Message string `xml:"Message"`
Error iamAPIError `xml:"Error"`
}
type iamAPIError struct {
Code string `xml:"Code"`
Message string `xml:"Message"`
}
type createAccessKeyResponse struct {
AccessKey iamAccessKey `xml:"CreateAccessKeyResult>AccessKey"`
}
type listAccessKeysResponse struct {
Items []iamAccessKeyMetadata `xml:"ListAccessKeysResult>AccessKeyMetadata>member"`
}
type getUserPolicyResponse struct {
UserName string `xml:"GetUserPolicyResult>UserName"`
PolicyName string `xml:"GetUserPolicyResult>PolicyName"`
PolicyDocument string `xml:"GetUserPolicyResult>PolicyDocument"`
}
type iamAccessKey struct {
UserName string `xml:"UserName"`
AccessKeyID string `xml:"AccessKeyId"`
Status string `xml:"Status"`
SecretAccessKey string `xml:"SecretAccessKey"`
}
type iamAccessKeyMetadata struct {
UserName string `xml:"UserName"`
AccessKeyID string `xml:"AccessKeyId"`
Status string `xml:"Status"`
}
type s3Tagging struct {
XMLName xml.Name `xml:"Tagging"`
TagSet []s3Tag `xml:"TagSet>Tag"`
}
type s3Tag struct {
Key string `xml:"Key"`
Value string `xml:"Value"`
}
func (e iamError) Error() string {
if e.Code == "" && e.Message == "" {
return "unknown IAM error"
}
return fmt.Sprintf("%s: %s", e.Code, e.Message)
}
type createUserResponse struct {
User iamUser `xml:"CreateUserResult>User"`
}
type getUserResponse struct {
User iamUser `xml:"GetUserResult>User"`
}
type iamUser struct {
UserName string `xml:"UserName"`
Arn string `xml:"Arn"`
UserID string `xml:"UserId"`
Path string `xml:"Path"`
}
func newIAMClient(cfg iamClientConfig) (*iamClient, error) {
if cfg.Endpoint == "" {
return nil, errors.New("endpoint is required")
}
if cfg.Region == "" {
cfg.Region = "us-east-1"
}
if cfg.AccessKey == "" || cfg.SecretKey == "" {
return nil, errors.New("access_key and secret_key are required")
}
tr := &http.Transport{}
if cfg.Insecure {
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec
}
client := &iamClient{
endpoint: strings.TrimRight(cfg.Endpoint, "/"),
region: cfg.Region,
creds: credentials.NewStaticCredentialsProvider(
cfg.AccessKey,
cfg.SecretKey,
"",
),
signer: v4.NewSigner(),
http: &http.Client{
Transport: tr,
Timeout: 30 * time.Second,
},
}
client.s3 = s3.New(s3.Options{
Region: client.region,
Credentials: client.creds,
HTTPClient: client.http,
BaseEndpoint: aws.String(client.endpoint),
UsePathStyle: true,
})
return client, nil
}
func (c *iamClient) CreateUser(ctx context.Context, userName string, path string) (getUserResponse, error) {
vals := url.Values{}
vals.Set("Action", "CreateUser")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
if path != "" {
vals.Set("Path", path)
}
var out createUserResponse
if err := c.doIAMAction(ctx, vals, &out); err != nil {
return getUserResponse{}, err
}
return getUserResponse{User: out.User}, nil
}
func (c *iamClient) GetUser(ctx context.Context, userName string) (getUserResponse, error) {
vals := url.Values{}
vals.Set("Action", "GetUser")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
var out getUserResponse
if err := c.doIAMAction(ctx, vals, &out); err != nil {
return getUserResponse{}, err
}
return out, nil
}
func (c *iamClient) DeleteUser(ctx context.Context, userName string) error {
vals := url.Values{}
vals.Set("Action", "DeleteUser")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
return c.doIAMAction(ctx, vals, nil)
}
func (c *iamClient) CreateAccessKey(ctx context.Context, userName string) (iamAccessKey, error) {
vals := url.Values{}
vals.Set("Action", "CreateAccessKey")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
var out createAccessKeyResponse
if err := c.doIAMAction(ctx, vals, &out); err != nil {
return iamAccessKey{}, err
}
return out.AccessKey, nil
}
func (c *iamClient) ListAccessKeys(ctx context.Context, userName string) ([]iamAccessKeyMetadata, error) {
vals := url.Values{}
vals.Set("Action", "ListAccessKeys")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
var out listAccessKeysResponse
if err := c.doIAMAction(ctx, vals, &out); err != nil {
return nil, err
}
return out.Items, nil
}
func (c *iamClient) DeleteAccessKey(ctx context.Context, userName string, accessKeyID string) error {
vals := url.Values{}
vals.Set("Action", "DeleteAccessKey")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
vals.Set("AccessKeyId", accessKeyID)
return c.doIAMAction(ctx, vals, nil)
}
func (c *iamClient) PutUserPolicy(ctx context.Context, userName string, policyName string, policyDocument string) error {
vals := url.Values{}
vals.Set("Action", "PutUserPolicy")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
vals.Set("PolicyName", policyName)
vals.Set("PolicyDocument", policyDocument)
return c.doIAMAction(ctx, vals, nil)
}
func (c *iamClient) GetUserPolicy(ctx context.Context, userName string, policyName string) (string, error) {
vals := url.Values{}
vals.Set("Action", "GetUserPolicy")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
vals.Set("PolicyName", policyName)
var out getUserPolicyResponse
if err := c.doIAMAction(ctx, vals, &out); err != nil {
return "", err
}
decoded, err := decodeIAMDocument(out.PolicyDocument)
if err != nil {
return out.PolicyDocument, nil
}
return decoded, nil
}
func (c *iamClient) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
vals := url.Values{}
vals.Set("Action", "DeleteUserPolicy")
vals.Set("Version", "2010-05-08")
vals.Set("UserName", userName)
vals.Set("PolicyName", policyName)
return c.doIAMAction(ctx, vals, nil)
}
func (c *iamClient) CreateBucket(ctx context.Context, name string) error {
path := "/" + name
_, err := c.doSignedRequest(ctx, "s3", http.MethodPut, c.endpoint+path, "", "", nil)
return err
}
func (c *iamClient) HeadBucket(ctx context.Context, name string) error {
path := "/" + name
_, err := c.doSignedRequest(ctx, "s3", http.MethodHead, c.endpoint+path, "", "", nil)
return err
}
func (c *iamClient) DeleteBucket(ctx context.Context, name string) error {
path := "/" + name
_, err := c.doSignedRequest(ctx, "s3", http.MethodDelete, c.endpoint+path, "", "", nil)
return err
}
func (c *iamClient) GetBucketTags(ctx context.Context, name string) (map[string]string, error) {
out, err := c.s3.GetBucketTagging(ctx, &s3.GetBucketTaggingInput{
Bucket: aws.String(name),
})
if err != nil {
if isNoSuchTagSetError(err) {
return map[string]string{}, nil
}
return nil, fmt.Errorf("get bucket tagging: %w", err)
}
tags := make(map[string]string, len(out.TagSet))
for _, tag := range out.TagSet {
tags[aws.ToString(tag.Key)] = aws.ToString(tag.Value)
}
return tags, nil
}
func (c *iamClient) PutBucketTags(ctx context.Context, name string, tags map[string]string) error {
keys := make([]string, 0, len(tags))
for k := range tags {
keys = append(keys, k)
}
sort.Strings(keys)
tagSet := make([]s3types.Tag, 0, len(tags))
for _, key := range keys {
value := tags[key]
tagSet = append(tagSet, s3types.Tag{
Key: aws.String(key),
Value: aws.String(value),
})
}
_, err := c.s3.PutBucketTagging(ctx, &s3.PutBucketTaggingInput{
Bucket: aws.String(name),
Tagging: &s3types.Tagging{
TagSet: tagSet,
},
})
if err != nil {
return fmt.Errorf("put bucket tagging: %w", err)
}
return nil
}
func (c *iamClient) DeleteBucketTags(ctx context.Context, name string) error {
_, err := c.s3.DeleteBucketTagging(ctx, &s3.DeleteBucketTaggingInput{
Bucket: aws.String(name),
})
if err != nil {
return fmt.Errorf("delete bucket tagging: %w", err)
}
return nil
}
func (c *iamClient) doIAMAction(ctx context.Context, form url.Values, out any) error {
body := form.Encode()
_, err := c.doSignedRequest(
ctx,
"iam",
http.MethodPost,
c.endpoint+"/",
"application/x-www-form-urlencoded",
body,
out,
)
return err
}
func (c *iamClient) doSignedRequest(
ctx context.Context,
service string,
method string,
requestURL string,
contentType string,
body string,
out any,
) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, method, requestURL, bytes.NewBufferString(body))
if err != nil {
return nil, err
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
req.Header.Set("Host", req.URL.Host)
creds, err := c.creds.Retrieve(ctx)
if err != nil {
return nil, fmt.Errorf("retrieve credentials: %w", err)
}
sum := sha256.Sum256([]byte(body))
hash := fmt.Sprintf("%x", sum)
if service == "s3" {
req.Header.Set("X-Amz-Content-Sha256", hash)
}
ctx = v4.SetPayloadHash(ctx, hash)
if err := c.signer.SignHTTP(ctx, creds, req, hash, service, c.region, time.Now()); err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response body: %w", err)
}
if resp.StatusCode >= 400 {
return nil, parseAPIError(resp.StatusCode, data)
}
if out != nil {
if err := xml.Unmarshal(data, out); err != nil {
return nil, fmt.Errorf("decode xml response: %w", err)
}
}
return data, nil
}
func parseAPIError(status int, data []byte) error {
var envelope iamErrorEnvelope
if xmlErr := xml.Unmarshal(data, &envelope); xmlErr == nil {
apiErr := iamError{
Code: envelope.Error.Code,
Message: envelope.Error.Message,
}
if apiErr.Code == "" {
apiErr.Code = envelope.Code
}
if apiErr.Message == "" {
apiErr.Message = envelope.Message
}
if apiErr.Code == "" || apiErr.Message == "" {
var direct iamAPIError
if xmlErr := xml.Unmarshal(data, &direct); xmlErr == nil {
if apiErr.Code == "" {
apiErr.Code = direct.Code
}
if apiErr.Message == "" {
apiErr.Message = direct.Message
}
}
}
if apiErr.Code != "" || apiErr.Message != "" {
if apiErr.Code == "" {
apiErr.Code = fmt.Sprintf("HTTP%d", status)
}
if apiErr.Message == "" {
apiErr.Message = strings.TrimSpace(string(data))
}
return apiErr
}
}
var jsonAPIError struct {
Code string `json:"code"`
Type string `json:"__type"`
Message string `json:"message"`
}
if jsonErr := json.Unmarshal(data, &jsonAPIError); jsonErr == nil && (jsonAPIError.Code != "" || jsonAPIError.Type != "") {
if jsonAPIError.Code == "" {
jsonAPIError.Code = jsonAPIError.Type
}
if separator := strings.LastIndex(jsonAPIError.Code, "#"); separator >= 0 {
jsonAPIError.Code = jsonAPIError.Code[separator+1:]
}
return iamError{
Code: jsonAPIError.Code,
Message: jsonAPIError.Message,
}
}
return iamError{
Code: fmt.Sprintf("HTTP%d", status),
Message: strings.TrimSpace(string(data)),
}
}
func isNoSuchEntityError(err error) bool {
var apiErr iamError
if errors.As(err, &apiErr) {
return apiErr.Code == "NoSuchEntity"
}
return false
}
func isEntityAlreadyExistsError(err error) bool {
var apiErr iamError
if errors.As(err, &apiErr) {
return apiErr.Code == "EntityAlreadyExists"
}
return false
}
func isServiceFailureError(err error) bool {
var apiErr iamError
if errors.As(err, &apiErr) {
return apiErr.Code == "ServiceFailure" || apiErr.Code == "HTTP500" || apiErr.Code == "HTTP503"
}
return false
}
func isRetryableIAMError(err error) bool {
return isNoSuchEntityError(err) || isServiceFailureError(err)
}
func retryIAMEventuallyConsistent(ctx context.Context, attempts int, fn func() error) error {
if attempts < 1 {
attempts = 1
}
delay := 200 * time.Millisecond
var lastErr error
for i := 0; i < attempts; i++ {
err := fn()
if err == nil {
return nil
}
if !isRetryableIAMError(err) {
return err
}
lastErr = err
if i == attempts-1 {
break
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
delay *= 2
if delay > 2*time.Second {
delay = 2 * time.Second
}
}
return lastErr
}
func retryIAMRead(ctx context.Context, attempts int, fn func() error) error {
if attempts < 1 {
attempts = 1
}
delay := 200 * time.Millisecond
var lastErr error
for i := 0; i < attempts; i++ {
err := fn()
if err == nil {
return nil
}
if isNoSuchEntityError(err) || !isServiceFailureError(err) {
return err
}
lastErr = err
if i == attempts-1 {
break
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
delay *= 2
}
}
return lastErr
}
func isNoSuchBucketError(err error) bool {
var apiErr iamError
if errors.As(err, &apiErr) {
return apiErr.Code == "NoSuchBucket" || apiErr.Code == "NotFound" || apiErr.Code == "HTTP404" || apiErr.Code == "NoSuchKey" || apiErr.Code == "NoSuchEntity"
}
return false
}
func isBucketAlreadyExistsError(err error) bool {
var apiErr iamError
if errors.As(err, &apiErr) {
return apiErr.Code == "BucketAlreadyOwnedByYou"
}
return false
}
func isBucketTakenError(err error) bool {
var apiErr iamError
if errors.As(err, &apiErr) {
return apiErr.Code == "BucketAlreadyExists"
}
return false
}
func isNoSuchTagSetError(err error) bool {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
return apiErr.ErrorCode() == "NoSuchTagSet"
}
return false
}
@@ -0,0 +1,70 @@
package seaweedfs
import (
"context"
"fmt"
)
type iamAttachedPolicy struct {
Name string `xml:"PolicyName"`
ARN string `xml:"PolicyArn"`
}
func (c *iamClient) AttachManagedPolicy(ctx context.Context, principalType, principalName, policyARN string, attach bool) error {
action := "Attach" + titleIAMPrincipal(principalType) + "Policy"
if !attach {
action = "Detach" + titleIAMPrincipal(principalType) + "Policy"
}
values := iamActionValues(action)
values.Set(titleIAMPrincipal(principalType)+"Name", principalName)
values.Set("PolicyArn", policyARN)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("%s managed policy: %w", action, err)
}
return nil
}
func (c *iamClient) ListAttachedManagedPolicies(ctx context.Context, principalType, principalName string) ([]iamAttachedPolicy, error) {
action := "ListAttached" + titleIAMPrincipal(principalType) + "Policies"
values := iamActionValues(action)
values.Set(titleIAMPrincipal(principalType)+"Name", principalName)
var response struct {
UserResult struct {
Policies []iamAttachedPolicy `xml:"AttachedPolicies>member"`
} `xml:"ListAttachedUserPoliciesResult"`
GroupResult struct {
Policies []iamAttachedPolicy `xml:"AttachedPolicies>member"`
} `xml:"ListAttachedGroupPoliciesResult"`
RoleResult struct {
Policies []iamAttachedPolicy `xml:"AttachedPolicies>member"`
} `xml:"ListAttachedRolePoliciesResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return nil, fmt.Errorf("%s: %w", action, err)
}
switch principalType {
case "user":
return response.UserResult.Policies, nil
case "group":
return response.GroupResult.Policies, nil
case "role":
return response.RoleResult.Policies, nil
default:
return nil, fmt.Errorf("unsupported IAM principal type %q", principalType)
}
}
func titleIAMPrincipal(principalType string) string {
switch principalType {
case "user":
return "User"
case "group":
return "Group"
case "role":
return "Role"
default:
return ""
}
}
@@ -0,0 +1,46 @@
package seaweedfs
import (
"context"
"fmt"
)
func (c *iamClient) PutGroupPolicy(ctx context.Context, groupName, policyName, document string) error {
values := iamActionValues("PutGroupPolicy")
values.Set("GroupName", groupName)
values.Set("PolicyName", policyName)
values.Set("PolicyDocument", document)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("put group policy: %w", err)
}
return nil
}
func (c *iamClient) GetGroupPolicy(ctx context.Context, groupName, policyName string) (string, error) {
values := iamActionValues("GetGroupPolicy")
values.Set("GroupName", groupName)
values.Set("PolicyName", policyName)
var response struct {
Result struct {
PolicyDocument string `xml:"PolicyDocument"`
} `xml:"GetGroupPolicyResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return "", fmt.Errorf("get group policy: %w", err)
}
document, err := decodeIAMDocument(response.Result.PolicyDocument)
if err != nil {
return "", fmt.Errorf("decode group policy: %w", err)
}
return document, nil
}
func (c *iamClient) DeleteGroupPolicy(ctx context.Context, groupName, policyName string) error {
values := iamActionValues("DeleteGroupPolicy")
values.Set("GroupName", groupName)
values.Set("PolicyName", policyName)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("delete group policy: %w", err)
}
return nil
}
@@ -0,0 +1,71 @@
package seaweedfs
import (
"context"
"fmt"
)
type iamGroup struct {
Name string `xml:"GroupName"`
Users []iamGroupUser `xml:"Users>member"`
}
type iamGroupUser struct {
Name string `xml:"UserName"`
}
func (c *iamClient) CreateGroup(ctx context.Context, name string) error {
values := iamActionValues("CreateGroup")
values.Set("GroupName", name)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("create group: %w", err)
}
return nil
}
func (c *iamClient) GetGroup(ctx context.Context, name string) (iamGroup, error) {
values := iamActionValues("GetGroup")
values.Set("GroupName", name)
var response struct {
Result struct {
Group struct {
Name string `xml:"GroupName"`
} `xml:"Group"`
Users []iamGroupUser `xml:"Users>member"`
} `xml:"GetGroupResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamGroup{}, fmt.Errorf("get group: %w", err)
}
return iamGroup{Name: response.Result.Group.Name, Users: response.Result.Users}, nil
}
func (c *iamClient) DeleteGroup(ctx context.Context, name string) error {
values := iamActionValues("DeleteGroup")
values.Set("GroupName", name)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("delete group: %w", err)
}
return nil
}
func (c *iamClient) AddUserToGroup(ctx context.Context, groupName, userName string) error {
values := iamActionValues("AddUserToGroup")
values.Set("GroupName", groupName)
values.Set("UserName", userName)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("add user %q to group %q: %w", userName, groupName, err)
}
return nil
}
func (c *iamClient) RemoveUserFromGroup(ctx context.Context, groupName, userName string) error {
values := iamActionValues("RemoveUserFromGroup")
values.Set("GroupName", groupName)
values.Set("UserName", userName)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("remove user %q from group %q: %w", userName, groupName, err)
}
return nil
}
@@ -0,0 +1,88 @@
package seaweedfs
import (
"context"
"fmt"
"net/url"
)
type iamOIDCProvider struct {
ARN string `xml:"OpenIDConnectProviderArn"`
URL string `xml:"Url"`
ClientIDs []string `xml:"ClientIDList>member"`
Thumbprints []string `xml:"ThumbprintList>member"`
}
func (c *iamClient) CreateOIDCProvider(ctx context.Context, providerURL string, clientIDs, thumbprints []string) (string, error) {
values := iamActionValues("CreateOpenIDConnectProvider")
values.Set("Url", providerURL)
setIAMMembers(values, "ClientIDList", clientIDs)
setIAMMembers(values, "ThumbprintList", thumbprints)
var response struct {
Result struct {
ARN string `xml:"OpenIDConnectProviderArn"`
} `xml:"CreateOpenIDConnectProviderResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return "", fmt.Errorf("create OIDC provider: %w", err)
}
return response.Result.ARN, nil
}
func (c *iamClient) GetOIDCProvider(ctx context.Context, arn string) (iamOIDCProvider, error) {
values := iamActionValues("GetOpenIDConnectProvider")
values.Set("OpenIDConnectProviderArn", arn)
var response struct {
Result iamOIDCProvider `xml:"GetOpenIDConnectProviderResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamOIDCProvider{}, fmt.Errorf("get OIDC provider: %w", err)
}
response.Result.ARN = arn
return response.Result, nil
}
func (c *iamClient) DeleteOIDCProvider(ctx context.Context, arn string) error {
values := iamActionValues("DeleteOpenIDConnectProvider")
values.Set("OpenIDConnectProviderArn", arn)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("delete OIDC provider: %w", err)
}
return nil
}
func (c *iamClient) AddOIDCClientID(ctx context.Context, arn, clientID string) error {
values := iamActionValues("AddClientIDToOpenIDConnectProvider")
values.Set("OpenIDConnectProviderArn", arn)
values.Set("ClientID", clientID)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("add OIDC client ID: %w", err)
}
return nil
}
func (c *iamClient) RemoveOIDCClientID(ctx context.Context, arn, clientID string) error {
values := iamActionValues("RemoveClientIDFromOpenIDConnectProvider")
values.Set("OpenIDConnectProviderArn", arn)
values.Set("ClientID", clientID)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("remove OIDC client ID: %w", err)
}
return nil
}
func (c *iamClient) UpdateOIDCThumbprints(ctx context.Context, arn string, thumbprints []string) error {
values := iamActionValues("UpdateOpenIDConnectProviderThumbprint")
values.Set("OpenIDConnectProviderArn", arn)
setIAMMembers(values, "ThumbprintList", thumbprints)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("update OIDC thumbprints: %w", err)
}
return nil
}
func setIAMMembers(values url.Values, key string, members []string) {
for index, member := range members {
values.Set(fmt.Sprintf("%s.member.%d", key, index+1), member)
}
}
@@ -0,0 +1,100 @@
package seaweedfs
import (
"context"
"fmt"
"strings"
)
type iamManagedPolicy struct {
Name string `xml:"PolicyName"`
ARN string `xml:"Arn"`
DefaultVersion string `xml:"DefaultVersionId"`
}
func (c *iamClient) CreateManagedPolicy(ctx context.Context, name, document string) (iamManagedPolicy, error) {
values := iamActionValues("CreatePolicy")
values.Set("PolicyName", name)
values.Set("PolicyDocument", document)
var response struct {
Result struct {
Policy iamManagedPolicy `xml:"Policy"`
} `xml:"CreatePolicyResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamManagedPolicy{}, fmt.Errorf("create managed policy: %w", err)
}
return response.Result.Policy, nil
}
func (c *iamClient) GetManagedPolicy(ctx context.Context, arn string) (iamManagedPolicy, error) {
values := iamActionValues("GetPolicy")
values.Set("PolicyArn", arn)
var response struct {
Result struct {
Policy iamManagedPolicy `xml:"Policy"`
} `xml:"GetPolicyResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamManagedPolicy{}, fmt.Errorf("get managed policy: %w", err)
}
return response.Result.Policy, nil
}
func (c *iamClient) GetManagedPolicyDocument(ctx context.Context, arn, version string) (string, error) {
values := iamActionValues("GetPolicyVersion")
values.Set("PolicyArn", arn)
values.Set("VersionId", version)
var response struct {
Result struct {
Version struct {
Document string `xml:"Document"`
} `xml:"PolicyVersion"`
} `xml:"GetPolicyVersionResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return "", fmt.Errorf("get managed policy document: %w", err)
}
document, err := decodeIAMDocument(response.Result.Version.Document)
if err != nil {
return "", fmt.Errorf("decode managed policy document: %w", err)
}
return document, nil
}
func (c *iamClient) UpdateManagedPolicy(ctx context.Context, arn, document string) error {
values := iamActionValues("CreatePolicyVersion")
values.Set("PolicyArn", arn)
values.Set("PolicyDocument", document)
values.Set("SetAsDefault", "true")
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("update managed policy: %w", err)
}
return nil
}
func (c *iamClient) DeleteManagedPolicy(ctx context.Context, arn string) error {
values := iamActionValues("DeletePolicy")
values.Set("PolicyArn", arn)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("delete managed policy: %w", err)
}
return nil
}
func iamPolicyARN(name string) string {
return "arn:aws:iam:::policy/" + name
}
func iamPolicyNameFromARN(arn string) (string, error) {
const delimiter = ":policy/"
found := strings.LastIndex(arn, delimiter)
if found < 0 {
return "", fmt.Errorf("invalid managed policy ARN %q", arn)
}
name := arn[found+len(delimiter):]
if name == "" || strings.Contains(name, "/") {
return "", fmt.Errorf("invalid managed policy ARN %q", arn)
}
return name, nil
}
@@ -0,0 +1,107 @@
package seaweedfs
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
)
type iamRole struct {
Name string `xml:"RoleName"`
ID string `xml:"RoleId"`
ARN string `xml:"Arn"`
Path string `xml:"Path"`
AssumeRolePolicy string `xml:"AssumeRolePolicyDocument"`
Description string `xml:"Description"`
MaxSessionDuration int64 `xml:"MaxSessionDuration"`
}
func (c *iamClient) CreateRole(ctx context.Context, name, trustPolicy, description string, maxSessionDuration int64) (iamRole, error) {
values := iamActionValues("CreateRole")
values.Set("RoleName", name)
values.Set("AssumeRolePolicyDocument", trustPolicy)
if description != "" {
values.Set("Description", description)
}
if maxSessionDuration != 0 {
values.Set("MaxSessionDuration", strconv.FormatInt(maxSessionDuration, 10))
}
var response struct {
Result struct {
Role iamRole `xml:"Role"`
} `xml:"CreateRoleResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamRole{}, fmt.Errorf("create role: %w", err)
}
decoded, err := decodeIAMDocument(response.Result.Role.AssumeRolePolicy)
if err != nil {
return iamRole{}, fmt.Errorf("decode role trust policy: %w", err)
}
response.Result.Role.AssumeRolePolicy = decoded
return response.Result.Role, nil
}
func (c *iamClient) GetRole(ctx context.Context, name string) (iamRole, error) {
values := iamActionValues("GetRole")
values.Set("RoleName", name)
var response struct {
Result struct {
Role iamRole `xml:"Role"`
} `xml:"GetRoleResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamRole{}, fmt.Errorf("get role: %w", err)
}
var err error
response.Result.Role.AssumeRolePolicy, err = decodeIAMDocument(response.Result.Role.AssumeRolePolicy)
if err != nil {
return iamRole{}, fmt.Errorf("decode role trust policy: %w", err)
}
return response.Result.Role, nil
}
func (c *iamClient) UpdateAssumeRolePolicy(ctx context.Context, name, trustPolicy string) error {
values := iamActionValues("UpdateAssumeRolePolicy")
values.Set("RoleName", name)
values.Set("PolicyDocument", trustPolicy)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("update role trust policy: %w", err)
}
return nil
}
func (c *iamClient) DeleteRole(ctx context.Context, name string) error {
values := iamActionValues("DeleteRole")
values.Set("RoleName", name)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("delete role: %w", err)
}
return nil
}
func iamActionValues(action string) url.Values {
values := url.Values{}
values.Set("Action", action)
values.Set("Version", "2010-05-08")
return values
}
func parseIAMImportID(id string) (string, error) {
if id == "" || strings.TrimSpace(id) != id {
return "", fmt.Errorf("expected a non-empty IAM resource name")
}
return id, nil
}
func decodeIAMDocument(document string) (string, error) {
if document == "" || json.Valid([]byte(document)) {
return document, nil
}
return url.PathUnescape(document)
}
@@ -0,0 +1,74 @@
package seaweedfs
import (
"context"
"fmt"
)
type iamServiceAccount struct {
ID string `xml:"ServiceAccountId"`
ParentUser string `xml:"ParentUser"`
Description string `xml:"Description"`
AccessKeyID string `xml:"AccessKeyId"`
SecretAccessKey string `xml:"SecretAccessKey"`
Status string `xml:"Status"`
CreateDate string `xml:"CreateDate"`
Expiration string `xml:"Expiration"`
}
func (c *iamClient) CreateServiceAccount(ctx context.Context, parentUser, description, expiration string) (iamServiceAccount, error) {
values := iamActionValues("CreateServiceAccount")
values.Set("ParentUser", parentUser)
values.Set("Description", description)
if expiration != "" {
values.Set("Expiration", expiration)
}
var response struct {
Result struct {
Account iamServiceAccount `xml:"ServiceAccount"`
} `xml:"CreateServiceAccountResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamServiceAccount{}, fmt.Errorf("create service account: %w", err)
}
return response.Result.Account, nil
}
func (c *iamClient) GetServiceAccount(ctx context.Context, id string) (iamServiceAccount, error) {
values := iamActionValues("GetServiceAccount")
values.Set("ServiceAccountId", id)
var response struct {
Result struct {
Account iamServiceAccount `xml:"ServiceAccount"`
} `xml:"GetServiceAccountResult"`
}
if err := c.doIAMAction(ctx, values, &response); err != nil {
return iamServiceAccount{}, fmt.Errorf("get service account: %w", err)
}
return response.Result.Account, nil
}
func (c *iamClient) UpdateServiceAccount(ctx context.Context, id, status, description string, expiration *string) error {
values := iamActionValues("UpdateServiceAccount")
values.Set("ServiceAccountId", id)
if status != "" {
values.Set("Status", status)
}
values.Set("Description", description)
if expiration != nil {
values.Set("Expiration", *expiration)
}
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("update service account: %w", err)
}
return nil
}
func (c *iamClient) DeleteServiceAccount(ctx context.Context, id string) error {
values := iamActionValues("DeleteServiceAccount")
values.Set("ServiceAccountId", id)
if err := c.doIAMAction(ctx, values, nil); err != nil {
return fmt.Errorf("delete service account: %w", err)
}
return nil
}
@@ -0,0 +1,84 @@
package seaweedfs
import (
"context"
"fmt"
"net/http"
"net/url"
)
const (
s3TableMaintenanceCompaction = "icebergCompaction"
s3TableMaintenanceSnapshotManagement = "icebergSnapshotManagement"
s3TableMaintenanceUnreferencedFiles = "icebergUnreferencedFileRemoval"
)
type s3TableMaintenanceSettings struct {
IcebergCompaction *s3TableCompactionSettings `json:"icebergCompaction,omitempty"`
IcebergSnapshotManagement *s3TableSnapshotManagementSettings `json:"icebergSnapshotManagement,omitempty"`
IcebergUnreferencedFileRemoval *s3TableUnreferencedFileRemovalSettings `json:"icebergUnreferencedFileRemoval,omitempty"`
}
type s3TableCompactionSettings struct {
Strategy string `json:"strategy,omitempty"`
TargetFileSizeMB *int64 `json:"targetFileSizeMB,omitempty"`
}
type s3TableSnapshotManagementSettings struct {
MinSnapshotsToKeep *int64 `json:"minSnapshotsToKeep,omitempty"`
MaxSnapshotAgeHours *int64 `json:"maxSnapshotAgeHours,omitempty"`
}
type s3TableUnreferencedFileRemovalSettings struct {
UnreferencedDays *int64 `json:"unreferencedDays,omitempty"`
NonCurrentDays *int64 `json:"nonCurrentDays,omitempty"`
}
type s3TableMaintenanceValue struct {
Status string `json:"status"`
Settings *s3TableMaintenanceSettings `json:"settings,omitempty"`
}
type s3TableMaintenanceResponse struct {
Configuration map[string]*s3TableMaintenanceValue `json:"configuration"`
}
func (c *iamClient) PutS3TableBucketMaintenanceConfiguration(ctx context.Context, arn string, value s3TableMaintenanceValue) error {
request := struct {
Value s3TableMaintenanceValue `json:"value"`
}{Value: value}
path := "/buckets/" + arn + "/maintenance/" + s3TableMaintenanceUnreferencedFiles
if err := c.S3TablesRequest(ctx, http.MethodPut, path, nil, request, nil); err != nil {
return fmt.Errorf("put S3 table bucket maintenance configuration: %w", err)
}
return nil
}
func (c *iamClient) GetS3TableBucketMaintenanceConfiguration(ctx context.Context, arn string) (map[string]*s3TableMaintenanceValue, error) {
var response s3TableMaintenanceResponse
path := "/buckets/" + arn + "/maintenance"
if err := c.S3TablesRequest(ctx, http.MethodGet, path, nil, nil, &response); err != nil {
return nil, fmt.Errorf("get S3 table bucket maintenance configuration: %w", err)
}
return response.Configuration, nil
}
func (c *iamClient) PutS3TableMaintenanceConfiguration(ctx context.Context, arn, namespace, name, maintenanceType string, value s3TableMaintenanceValue) error {
request := struct {
Value s3TableMaintenanceValue `json:"value"`
}{Value: value}
path := "/tables/" + arn + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/maintenance/" + url.PathEscape(maintenanceType)
if err := c.S3TablesRequest(ctx, http.MethodPut, path, nil, request, nil); err != nil {
return fmt.Errorf("put S3 table maintenance configuration: %w", err)
}
return nil
}
func (c *iamClient) GetS3TableMaintenanceConfiguration(ctx context.Context, arn, namespace, name string) (map[string]*s3TableMaintenanceValue, error) {
var response s3TableMaintenanceResponse
path := "/tables/" + arn + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/maintenance"
if err := c.S3TablesRequest(ctx, http.MethodGet, path, nil, nil, &response); err != nil {
return nil, fmt.Errorf("get S3 table maintenance configuration: %w", err)
}
return response.Configuration, nil
}
@@ -0,0 +1,288 @@
package seaweedfs
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
type s3TableBucket struct {
ARN string `json:"arn"`
Name string `json:"name"`
OwnerAccountID string `json:"ownerAccountId"`
CreatedAt time.Time `json:"createdAt"`
Format string `json:"format"`
Tags map[string]string
}
type s3TableNamespace struct {
Namespace []string `json:"namespace"`
CreatedAt time.Time `json:"createdAt"`
OwnerAccountID string `json:"ownerAccountId"`
Properties map[string]string `json:"properties"`
}
type s3Table struct {
Name string `json:"name"`
TableARN string `json:"tableARN"`
Namespace []string `json:"namespace"`
Format string `json:"format"`
CreatedAt time.Time `json:"createdAt"`
ModifiedAt time.Time `json:"modifiedAt"`
OwnerAccountID string `json:"ownerAccountId"`
MetadataLocation string `json:"metadataLocation"`
VersionToken string `json:"versionToken"`
Metadata json.RawMessage `json:"metadata"`
Tags map[string]string
}
func (c *iamClient) S3TablesRequest(ctx context.Context, method, requestPath string, query url.Values, body, out any) error {
bodyString := ""
contentType := ""
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("encode S3 Tables request: %w", err)
}
bodyString = string(encoded)
contentType = "application/json"
}
requestURL := c.endpoint + requestPath
if len(query) > 0 {
requestURL += "?" + query.Encode()
}
response, err := c.doSignedRequest(ctx, "s3tables", method, requestURL, contentType, bodyString, nil)
if err != nil {
return err
}
if out != nil && len(response) > 0 {
if err := json.Unmarshal(response, out); err != nil {
return fmt.Errorf("decode S3 Tables response: %w", err)
}
}
return nil
}
func (c *iamClient) CreateS3TableBucket(ctx context.Context, name, format string, tags map[string]string) (string, error) {
request := struct {
Name string `json:"name"`
Format string `json:"format,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
}{Name: name, Format: format, Tags: tags}
var response struct {
ARN string `json:"arn"`
}
err := c.S3TablesRequest(ctx, http.MethodPut, "/buckets", nil, request, &response)
if err != nil {
return "", fmt.Errorf("create S3 table bucket: %w", err)
}
return response.ARN, nil
}
func (c *iamClient) GetS3TableBucket(ctx context.Context, arn string) (s3TableBucket, error) {
var response s3TableBucket
if err := c.S3TablesRequest(ctx, http.MethodGet, "/buckets/"+url.PathEscape(arn), nil, nil, &response); err != nil {
return s3TableBucket{}, fmt.Errorf("get S3 table bucket: %w", err)
}
tags, err := c.GetS3TableTags(ctx, arn)
if err != nil {
return s3TableBucket{}, err
}
response.Tags = tags
return response, nil
}
func (c *iamClient) DeleteS3TableBucket(ctx context.Context, arn string) error {
if err := c.S3TablesRequest(ctx, http.MethodDelete, "/buckets/"+url.PathEscape(arn), nil, nil, nil); err != nil {
return fmt.Errorf("delete S3 table bucket: %w", err)
}
return nil
}
func (c *iamClient) CreateS3TableNamespace(ctx context.Context, bucketARN, namespace string) error {
request := struct {
Namespace []string `json:"namespace"`
}{Namespace: []string{namespace}}
if err := c.S3TablesRequest(ctx, http.MethodPut, "/namespaces/"+url.PathEscape(bucketARN), nil, request, nil); err != nil {
return fmt.Errorf("create S3 table namespace: %w", err)
}
return nil
}
func (c *iamClient) GetS3TableNamespace(ctx context.Context, bucketARN, namespace string) (s3TableNamespace, error) {
var response s3TableNamespace
if err := c.S3TablesRequest(ctx, http.MethodGet, "/namespaces/"+url.PathEscape(bucketARN)+"/"+url.PathEscape(namespace), nil, nil, &response); err != nil {
return s3TableNamespace{}, fmt.Errorf("get S3 table namespace: %w", err)
}
return response, nil
}
func (c *iamClient) DeleteS3TableNamespace(ctx context.Context, bucketARN, namespace string) error {
if err := c.S3TablesRequest(ctx, http.MethodDelete, "/namespaces/"+url.PathEscape(bucketARN)+"/"+url.PathEscape(namespace), nil, nil, nil); err != nil {
return fmt.Errorf("delete S3 table namespace: %w", err)
}
return nil
}
func (c *iamClient) CreateS3Table(ctx context.Context, bucketARN, namespace, name, format string, metadata json.RawMessage, tags map[string]string) (s3Table, error) {
request := struct {
Name string `json:"name"`
Format string `json:"format"`
Metadata json.RawMessage `json:"metadata,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
}{Name: name, Format: format, Metadata: metadata, Tags: tags}
var response struct {
TableARN string `json:"tableARN"`
VersionToken string `json:"versionToken"`
}
requestPath := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace)
if err := c.S3TablesRequest(ctx, http.MethodPut, requestPath, nil, request, &response); err != nil {
return s3Table{}, fmt.Errorf("create S3 table: %w", err)
}
return s3Table{TableARN: response.TableARN, VersionToken: response.VersionToken}, nil
}
func (c *iamClient) GetS3Table(ctx context.Context, bucketARN, namespace, name string) (s3Table, error) {
query := url.Values{}
query.Set("tableBucketARN", bucketARN)
query.Set("namespace", namespace)
query.Set("name", name)
var response s3Table
if err := c.S3TablesRequest(ctx, http.MethodGet, "/get-table", query, nil, &response); err != nil {
return s3Table{}, fmt.Errorf("get S3 table: %w", err)
}
tags, err := c.GetS3TableTags(ctx, response.TableARN)
if err != nil {
return s3Table{}, err
}
response.Tags = tags
return response, nil
}
func (c *iamClient) DeleteS3Table(ctx context.Context, bucketARN, namespace, name, versionToken string) error {
query := url.Values{}
if versionToken != "" {
query.Set("versionToken", versionToken)
}
requestPath := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name)
if err := c.S3TablesRequest(ctx, http.MethodDelete, requestPath, query, nil, nil); err != nil {
return fmt.Errorf("delete S3 table: %w", err)
}
return nil
}
func (c *iamClient) PutS3TablePolicy(ctx context.Context, bucketARN, namespace, name, policy string) error {
request := struct {
ResourcePolicy string `json:"resourcePolicy"`
}{ResourcePolicy: policy}
if namespace == "" {
if err := c.S3TablesRequest(ctx, http.MethodPut, "/buckets/"+url.PathEscape(bucketARN)+"/policy", nil, request, nil); err != nil {
return fmt.Errorf("put S3 table bucket policy: %w", err)
}
return nil
}
requestPath := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/policy"
if err := c.S3TablesRequest(ctx, http.MethodPut, requestPath, nil, request, nil); err != nil {
return fmt.Errorf("put S3 table policy: %w", err)
}
return nil
}
func (c *iamClient) GetS3TablePolicy(ctx context.Context, bucketARN, namespace, name string) (string, error) {
requestPath := "/buckets/" + url.PathEscape(bucketARN) + "/policy"
if namespace != "" {
requestPath = "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/policy"
}
var response struct {
ResourcePolicy string `json:"resourcePolicy"`
}
if err := c.S3TablesRequest(ctx, http.MethodGet, requestPath, nil, nil, &response); err != nil {
return "", fmt.Errorf("get S3 table policy: %w", err)
}
return response.ResourcePolicy, nil
}
func (c *iamClient) DeleteS3TablePolicy(ctx context.Context, bucketARN, namespace, name string) error {
requestPath := "/buckets/" + url.PathEscape(bucketARN) + "/policy"
if namespace != "" {
requestPath = "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/policy"
}
if err := c.S3TablesRequest(ctx, http.MethodDelete, requestPath, nil, nil, nil); err != nil {
return fmt.Errorf("delete S3 table policy: %w", err)
}
return nil
}
func (c *iamClient) GetS3TableTags(ctx context.Context, arn string) (map[string]string, error) {
var response struct {
Tags map[string]string `json:"tags"`
}
if err := c.S3TablesRequest(ctx, http.MethodGet, "/tag/"+url.PathEscape(arn), nil, nil, &response); err != nil {
return nil, fmt.Errorf("list S3 Tables tags: %w", err)
}
if response.Tags == nil {
response.Tags = map[string]string{}
}
return response.Tags, nil
}
func (c *iamClient) TagS3TableResource(ctx context.Context, arn string, tags map[string]string) error {
request := struct {
ResourceARN string `json:"resourceArn"`
Tags map[string]string `json:"tags"`
}{ResourceARN: arn, Tags: tags}
if err := c.S3TablesRequest(ctx, http.MethodPost, "/tag/"+url.PathEscape(arn), nil, request, nil); err != nil {
return fmt.Errorf("tag S3 Tables resource: %w", err)
}
return nil
}
func (c *iamClient) UntagS3TableResource(ctx context.Context, arn string, keys []string) error {
query := url.Values{}
for _, key := range keys {
query.Add("tagKeys", key)
}
if err := c.S3TablesRequest(ctx, http.MethodDelete, "/tag/"+url.PathEscape(arn), query, nil, nil); err != nil {
return fmt.Errorf("untag S3 Tables resource: %w", err)
}
return nil
}
func (c *iamClient) SetS3TableTags(ctx context.Context, arn string, desired map[string]string) error {
current, err := c.GetS3TableTags(ctx, arn)
if err != nil {
return err
}
var remove []string
for key := range current {
if _, exists := desired[key]; !exists {
remove = append(remove, key)
}
}
sort.Strings(remove)
if len(remove) > 0 {
if err := c.UntagS3TableResource(ctx, arn, remove); err != nil {
return err
}
}
if len(desired) > 0 {
if err := c.TagS3TableResource(ctx, arn, desired); err != nil {
return err
}
}
return nil
}
func isNoSuchS3TablesEntityError(err error) bool {
var apiErr iamError
if !errors.As(err, &apiErr) {
return false
}
return strings.HasPrefix(apiErr.Code, "NoSuch")
}
+540
View File
@@ -0,0 +1,540 @@
package seaweedfs
import (
"context"
"encoding/xml"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func TestIAMClientUserLifecycle(t *testing.T) {
t.Parallel()
users := map[string]bool{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Fatalf("unexpected method: %s", r.Method)
}
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read request body: %v", err)
}
_ = r.Body.Close()
form, err := url.ParseQuery(string(body))
if err != nil {
t.Fatalf("parse form body: %v", err)
}
action := form.Get("Action")
name := form.Get("UserName")
switch action {
case "CreateUser":
users[name] = true
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(`<CreateUserResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><CreateUserResult><User><Path>/</Path><UserName>` + name + `</UserName><UserId>uid-123</UserId><Arn>arn:aws:iam::123456789012:user/` + name + `</Arn></User></CreateUserResult></CreateUserResponse>`))
case "GetUser":
if !users[name] {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<ErrorResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><Error><Code>NoSuchEntity</Code><Message>Not found</Message></Error></ErrorResponse>`))
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(`<GetUserResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><GetUserResult><User><Path>/</Path><UserName>` + name + `</UserName><UserId>uid-123</UserId><Arn>arn:aws:iam::123456789012:user/` + name + `</Arn></User></GetUserResult></GetUserResponse>`))
case "DeleteUser":
delete(users, name)
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(`<DeleteUserResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><ResponseMetadata><RequestId>req-1</RequestId></ResponseMetadata></DeleteUserResponse>`))
default:
t.Fatalf("unexpected action: %s", action)
}
}))
defer srv.Close()
client, err := newIAMClient(iamClientConfig{
Endpoint: srv.URL,
Region: "us-east-1",
AccessKey: "test-key",
SecretKey: "test-secret",
})
if err != nil {
t.Fatalf("new client: %v", err)
}
ctx := context.Background()
userName := "test-user"
created, err := client.CreateUser(ctx, userName, "/")
if err != nil {
t.Fatalf("create user: %v", err)
}
if created.User.UserName != userName {
t.Fatalf("expected created username %q, got %q", userName, created.User.UserName)
}
readUser, err := client.GetUser(ctx, userName)
if err != nil {
t.Fatalf("get user: %v", err)
}
if readUser.User.UserName != userName {
t.Fatalf("expected read username %q, got %q", userName, readUser.User.UserName)
}
if err := client.DeleteUser(ctx, userName); err != nil {
t.Fatalf("delete user: %v", err)
}
_, err = client.GetUser(ctx, userName)
if err == nil {
t.Fatal("expected no-such-entity error after delete, got nil")
}
if !isNoSuchEntityError(err) {
t.Fatalf("expected NoSuchEntity error, got: %v", err)
}
}
func TestIAMClientCreateFromServiceFailure(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`<ErrorResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><Error><Code>ServiceFailure</Code><Message>Internal server error</Message></Error></ErrorResponse>`))
}))
defer srv.Close()
client, err := newIAMClient(iamClientConfig{
Endpoint: srv.URL,
Region: "us-east-1",
AccessKey: "test-key",
SecretKey: "test-secret",
})
if err != nil {
t.Fatalf("new client: %v", err)
}
_, err = client.CreateUser(context.Background(), "x", "/")
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "ServiceFailure") {
t.Fatalf("expected ServiceFailure in error, got: %v", err)
}
}
func TestIsNoSuchBucketError(t *testing.T) {
for _, code := range []string{"NoSuchBucket", "NotFound", "HTTP404"} {
t.Run(code, func(t *testing.T) {
if !isNoSuchBucketError(iamError{Code: code}) {
t.Fatalf("isNoSuchBucketError(%q) = false, want true", code)
}
})
}
if isNoSuchBucketError(iamError{Code: "AccessDenied"}) {
t.Fatal("isNoSuchBucketError(AccessDenied) = true, want false")
}
}
func TestIAMClientAccessKeyPolicyAndBucket(t *testing.T) {
t.Parallel()
users := map[string]bool{"alice": true}
keys := map[string]string{}
policies := map[string]string{}
buckets := map[string]bool{}
bucketTags := map[string]map[string]string{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, hasTagging := r.URL.Query()["tagging"]
if hasTagging {
bucket := strings.TrimPrefix(r.URL.Path, "/")
if !buckets[bucket] {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<Error><Code>NoSuchBucket</Code><Message>Not Found</Message></Error>`))
return
}
switch r.Method {
case http.MethodGet:
tags := bucketTags[bucket]
if len(tags) == 0 {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<Error><Code>NoSuchTagSet</Code><Message>No tags</Message></Error>`))
return
}
var out s3Tagging
for key, value := range tags {
out.TagSet = append(out.TagSet, s3Tag{
Key: key,
Value: value,
})
}
data, err := xml.Marshal(out)
if err != nil {
t.Fatalf("marshal tagging xml: %v", err)
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(data)
case http.MethodPut:
var in s3Tagging
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read tagging body: %v", err)
}
if err := xml.Unmarshal(body, &in); err != nil {
t.Fatalf("unmarshal tagging body: %v", err)
}
tags := map[string]string{}
for _, tag := range in.TagSet {
tags[tag.Key] = tag.Value
}
bucketTags[bucket] = tags
w.WriteHeader(http.StatusOK)
case http.MethodDelete:
delete(bucketTags, bucket)
w.WriteHeader(http.StatusNoContent)
default:
t.Fatalf("unexpected tagging method: %s", r.Method)
}
return
}
if r.Method == http.MethodPut || r.Method == http.MethodHead || r.Method == http.MethodDelete {
bucket := strings.TrimPrefix(r.URL.Path, "/")
switch r.Method {
case http.MethodPut:
buckets[bucket] = true
w.WriteHeader(http.StatusOK)
case http.MethodHead:
if !buckets[bucket] {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<Error><Code>NoSuchBucket</Code><Message>Not Found</Message></Error>`))
return
}
w.WriteHeader(http.StatusOK)
case http.MethodDelete:
delete(buckets, bucket)
w.WriteHeader(http.StatusNoContent)
}
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read request body: %v", err)
}
_ = r.Body.Close()
form, err := url.ParseQuery(string(body))
if err != nil {
t.Fatalf("parse form body: %v", err)
}
action := form.Get("Action")
user := form.Get("UserName")
switch action {
case "CreateAccessKey":
if !users[user] {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>NoSuchEntity</Code><Message>Not found</Message></Error></ErrorResponse>`))
return
}
keys[user] = "AKIA_TEST"
_, _ = w.Write([]byte(`<CreateAccessKeyResponse><CreateAccessKeyResult><AccessKey><UserName>` + user + `</UserName><AccessKeyId>AKIA_TEST</AccessKeyId><Status>Active</Status><SecretAccessKey>SECRET123</SecretAccessKey></AccessKey></CreateAccessKeyResult></CreateAccessKeyResponse>`))
case "ListAccessKeys":
if keys[user] == "" {
_, _ = w.Write([]byte(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata></AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`))
return
}
_, _ = w.Write([]byte(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata><member><UserName>` + user + `</UserName><AccessKeyId>` + keys[user] + `</AccessKeyId><Status>Active</Status></member></AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`))
case "DeleteAccessKey":
delete(keys, user)
_, _ = w.Write([]byte(`<DeleteAccessKeyResponse/>`))
case "PutUserPolicy":
policies[user+":"+form.Get("PolicyName")] = form.Get("PolicyDocument")
_, _ = w.Write([]byte(`<PutUserPolicyResponse/>`))
case "GetUserPolicy":
key := user + ":" + form.Get("PolicyName")
val, ok := policies[key]
if !ok {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>NoSuchEntity</Code><Message>Not found</Message></Error></ErrorResponse>`))
return
}
_, _ = w.Write([]byte(`<GetUserPolicyResponse><GetUserPolicyResult><UserName>` + user + `</UserName><PolicyName>` + form.Get("PolicyName") + `</PolicyName><PolicyDocument>` + val + `</PolicyDocument></GetUserPolicyResult></GetUserPolicyResponse>`))
case "DeleteUserPolicy":
delete(policies, user+":"+form.Get("PolicyName"))
_, _ = w.Write([]byte(`<DeleteUserPolicyResponse/>`))
default:
t.Fatalf("unexpected action: %s", action)
}
}))
defer srv.Close()
client, err := newIAMClient(iamClientConfig{
Endpoint: srv.URL,
Region: "us-east-1",
AccessKey: "test-key",
SecretKey: "test-secret",
})
if err != nil {
t.Fatalf("new client: %v", err)
}
ctx := context.Background()
ak, err := client.CreateAccessKey(ctx, "alice")
if err != nil {
t.Fatalf("create access key: %v", err)
}
if ak.AccessKeyID != "AKIA_TEST" || ak.SecretAccessKey != "SECRET123" {
t.Fatalf("unexpected access key response: %+v", ak)
}
list, err := client.ListAccessKeys(ctx, "alice")
if err != nil {
t.Fatalf("list access keys: %v", err)
}
if len(list) != 1 || list[0].AccessKeyID != "AKIA_TEST" {
t.Fatalf("unexpected key list: %+v", list)
}
if err := client.PutUserPolicy(ctx, "alice", "p1", "%7B%22Version%22%3A%222012-10-17%22%7D"); err != nil {
t.Fatalf("put user policy: %v", err)
}
pol, err := client.GetUserPolicy(ctx, "alice", "p1")
if err != nil {
t.Fatalf("get user policy: %v", err)
}
if !strings.Contains(pol, "Version") {
t.Fatalf("unexpected policy decode: %s", pol)
}
if err := client.DeleteUserPolicy(ctx, "alice", "p1"); err != nil {
t.Fatalf("delete user policy: %v", err)
}
if err := client.CreateBucket(ctx, "b1"); err != nil {
t.Fatalf("create bucket: %v", err)
}
if err := client.HeadBucket(ctx, "b1"); err != nil {
t.Fatalf("head bucket: %v", err)
}
tags, err := client.GetBucketTags(ctx, "b1")
if err != nil {
t.Fatalf("get empty bucket tags: %v", err)
}
if len(tags) != 0 {
t.Fatalf("expected no tags, got: %+v", tags)
}
if err := client.PutBucketTags(ctx, "b1", map[string]string{
"env": "prod",
"team": "platform",
}); err != nil {
t.Fatalf("put bucket tags: %v", err)
}
tags, err = client.GetBucketTags(ctx, "b1")
if err != nil {
t.Fatalf("get bucket tags: %v", err)
}
if tags["env"] != "prod" || tags["team"] != "platform" {
t.Fatalf("unexpected tags: %+v", tags)
}
if err := client.DeleteBucketTags(ctx, "b1"); err != nil {
t.Fatalf("delete bucket tags: %v", err)
}
tags, err = client.GetBucketTags(ctx, "b1")
if err != nil {
t.Fatalf("get empty bucket tags after delete: %v", err)
}
if len(tags) != 0 {
t.Fatalf("expected no tags after delete, got: %+v", tags)
}
if err := client.DeleteBucket(ctx, "b1"); err != nil {
t.Fatalf("delete bucket: %v", err)
}
if err := client.DeleteAccessKey(ctx, "alice", "AKIA_TEST"); err != nil {
t.Fatalf("delete access key: %v", err)
}
}
func TestPoliciesSemanticallyEqual(t *testing.T) {
t.Parallel()
a := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:*"],"Resource":"*"}]}`
b := `{
"Statement": [
{
"Resource": "*",
"Action": [
"s3:*"
],
"Effect": "Allow"
}
],
"Version": "2012-10-17"
}`
if !policiesSemanticallyEqual(a, b) {
t.Fatalf("expected policies to be semantically equal")
}
}
func TestPoliciesNormalizeSingletonStatementValues(t *testing.T) {
t.Parallel()
configured := `{"Statement":[{"Action":"sts:AssumeRole","Effect":"Allow","Principal":{"AWS":"*"},"Resource":"*"}],"Version":"2012-10-17"}`
seaweedFS := `{"Statement":[{"Action":["sts:AssumeRole"],"Effect":"Allow","Principal":{"AWS":"*"},"Resource":["*"]}],"Version":"2012-10-17"}`
if !policiesSemanticallyEqual(configured, seaweedFS) {
t.Fatal("expected equivalent policy documents to compare equal")
}
trustPolicy := `{"Statement":[{"Action":"sts:AssumeRole","Effect":"Allow","Principal":{"AWS":"*"}}],"Version":"2012-10-17"}`
seaweedFSTrustPolicy := `{"Statement":[{"Action":["sts:AssumeRole"],"Effect":"Allow","Principal":{"AWS":"*"},"Resource":[""]}],"Version":"2012-10-17"}`
if !policiesSemanticallyEqual(trustPolicy, seaweedFSTrustPolicy) {
t.Fatal("expected empty server-generated trust-policy resource to be ignored")
}
}
func TestSignedS3RequestIncludesPayloadHash(t *testing.T) {
t.Parallel()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if got := req.Header.Get("X-Amz-Content-Sha256"); got == "" {
t.Error("expected X-Amz-Content-Sha256 header")
}
if !strings.Contains(req.Header.Get("Authorization"), "x-amz-content-sha256") {
t.Error("expected payload hash header to be signed")
}
w.WriteHeader(http.StatusNoContent)
}))
defer server.Close()
client, err := newIAMClient(iamClientConfig{
Endpoint: server.URL,
Region: "us-east-1",
AccessKey: "test-key",
SecretKey: "test-secret",
})
if err != nil {
t.Fatalf("new client: %v", err)
}
if _, err := client.doSignedRequest(context.Background(), "s3", http.MethodPut,
server.URL+"/bucket?seaweedfs-quota=", "application/json", `{"quota_size":1}`, nil); err != nil {
t.Fatalf("signed S3 request: %v", err)
}
}
func TestRetryIAMEventuallyConsistent(t *testing.T) {
t.Parallel()
attempts := 0
err := retryIAMEventuallyConsistent(context.Background(), 4, func() error {
attempts++
if attempts < 3 {
return iamError{Code: "ServiceFailure", Message: "temporary"}
}
return nil
})
if err != nil {
t.Fatalf("expected success after retries, got: %v", err)
}
if attempts != 3 {
t.Fatalf("expected 3 attempts, got %d", attempts)
}
}
func TestRetryIAMEventuallyConsistentStopsOnNonRetryableError(t *testing.T) {
t.Parallel()
nonRetryable := errors.New("boom")
attempts := 0
err := retryIAMEventuallyConsistent(context.Background(), 5, func() error {
attempts++
return nonRetryable
})
if !errors.Is(err, nonRetryable) {
t.Fatalf("expected non-retryable error, got: %v", err)
}
if attempts != 1 {
t.Fatalf("expected 1 attempt, got %d", attempts)
}
}
func TestRetryIAMReadDoesNotRetryNoSuchEntity(t *testing.T) {
t.Parallel()
attempts := 0
err := retryIAMRead(context.Background(), 5, func() error {
attempts++
return iamError{Code: "NoSuchEntity", Message: "missing"}
})
if !isNoSuchEntityError(err) {
t.Fatalf("expected NoSuchEntity, got: %v", err)
}
if attempts != 1 {
t.Fatalf("expected 1 attempt, got %d", attempts)
}
}
func TestIAMErrorHelpers(t *testing.T) {
t.Parallel()
if !isEntityAlreadyExistsError(iamError{Code: "EntityAlreadyExists", Message: "exists"}) {
t.Fatalf("expected EntityAlreadyExists helper to match")
}
if isBucketAlreadyExistsError(iamError{Code: "BucketAlreadyExists", Message: "taken"}) {
t.Fatal("a bucket owned by another identity must not be adopted")
}
if !isBucketAlreadyExistsError(iamError{Code: "BucketAlreadyOwnedByYou", Message: "exists"}) {
t.Fatalf("expected BucketAlreadyOwnedByYou helper to match")
}
if !isRetryableIAMError(iamError{Code: "ServiceFailure", Message: "temporary"}) {
t.Fatalf("expected ServiceFailure to be retryable")
}
}
func TestJSONNormalizersPreserveLargeNumbers(t *testing.T) {
t.Parallel()
raw := `{"current-snapshot-id":9007199254740993}`
normalized, err := normalizeJSONString(raw)
if err != nil {
t.Fatalf("normalize: %v", err)
}
if normalized != raw {
t.Fatalf("normalized = %s, want %s", normalized, raw)
}
if policiesSemanticallyEqual(raw, `{"current-snapshot-id":9007199254740992}`) {
t.Fatal("expected distinct integers to compare different")
}
if _, err := normalizeJSONString(`{"a":1} {"b":2}`); err == nil {
t.Fatal("expected trailing JSON to be rejected")
}
}
func TestPoliciesNormalizeStatementShapeSidAndConditions(t *testing.T) {
t.Parallel()
configured := `{"Version":"2012-10-17","Statement":{"Sid":"","Effect":"Allow","Action":"s3:GetObject","Resource":"*","Condition":{"StringEquals":{"aws:username":"alice"}}}}`
seaweedFS := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["*"],"Condition":{"StringEquals":{"aws:username":["alice"]}}}]}`
if !policiesSemanticallyEqual(configured, seaweedFS) {
t.Fatal("expected equivalent policy documents to compare equal")
}
if policiesSemanticallyEqual(seaweedFS, `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["*"],"Condition":{"StringEquals":{"aws:username":["alice","bob"]}}}]}`) {
t.Fatal("expected different condition values to compare different")
}
}
@@ -0,0 +1,190 @@
package seaweedfs
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func TestS3TablesRequestUsesS3TablesSigningScope(t *testing.T) {
t.Parallel()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPut || req.URL.Path != "/buckets" {
t.Errorf("request = %s %s, want PUT /buckets", req.Method, req.URL.Path)
}
if !strings.Contains(req.Header.Get("Authorization"), "/s3tables/aws4_request") {
t.Errorf("Authorization scope = %q, want s3tables service", req.Header.Get("Authorization"))
}
body, err := io.ReadAll(req.Body)
if err != nil {
t.Errorf("read request body: %v", err)
return
}
var request struct {
Name string `json:"name"`
Format string `json:"format"`
Tags map[string]string `json:"tags"`
}
if err := json.Unmarshal(body, &request); err != nil {
t.Errorf("decode request body: %v", err)
return
}
if request.Name != "lake" || request.Format != "ICEBERG" || request.Tags["env"] != "test" {
t.Errorf("request body = %#v", request)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"arn":"arn:aws:s3tables:us-east-1:123456789012:bucket/lake"}`))
}))
defer server.Close()
client, err := newIAMClient(iamClientConfig{
Endpoint: server.URL,
Region: "us-east-1",
AccessKey: "test-key",
SecretKey: "test-secret",
})
if err != nil {
t.Fatalf("new client: %v", err)
}
arn, err := client.CreateS3TableBucket(context.Background(), "lake", "ICEBERG", map[string]string{"env": "test"})
if err != nil {
t.Fatalf("create table bucket: %v", err)
}
if arn != "arn:aws:s3tables:us-east-1:123456789012:bucket/lake" {
t.Fatalf("ARN = %q", arn)
}
}
func TestS3TablesJSONNotFoundErrorsAreRecognized(t *testing.T) {
t.Parallel()
err := parseAPIError(http.StatusNotFound, []byte(`{"__type":"com.amazonaws.s3tables#NoSuchTable","message":"not found"}`))
if !isNoSuchS3TablesEntityError(err) {
t.Fatalf("expected S3 Tables not-found error, got %v", err)
}
}
func TestIAMGroupAndRoleClientResponses(t *testing.T) {
t.Parallel()
trustPolicy := `{"Version":"2012-10-17","Statement":[]}`
encodedTrustPolicy := url.QueryEscape(trustPolicy)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
body, err := io.ReadAll(req.Body)
if err != nil {
t.Errorf("read request body: %v", err)
return
}
values, err := url.ParseQuery(string(body))
if err != nil {
t.Errorf("parse IAM request: %v", err)
return
}
switch values.Get("Action") {
case "GetGroup":
_, _ = fmt.Fprint(w, `<GetGroupResponse><GetGroupResult><Group><GroupName>operators</GroupName></Group><Users><member><UserName>alice</UserName></member><member><UserName>bob</UserName></member></Users></GetGroupResult></GetGroupResponse>`)
case "GetRole":
_, _ = fmt.Fprintf(w, `<GetRoleResponse><GetRoleResult><Role><RoleName>reader</RoleName><Arn>arn:aws:iam:::role/reader</Arn><AssumeRolePolicyDocument>%s</AssumeRolePolicyDocument><MaxSessionDuration>3600</MaxSessionDuration></Role></GetRoleResult></GetRoleResponse>`, encodedTrustPolicy)
default:
t.Errorf("unexpected IAM action %q", values.Get("Action"))
}
}))
defer server.Close()
client, err := newIAMClient(iamClientConfig{
Endpoint: server.URL,
Region: "us-east-1",
AccessKey: "test-key",
SecretKey: "test-secret",
})
if err != nil {
t.Fatalf("new client: %v", err)
}
group, err := client.GetGroup(context.Background(), "operators")
if err != nil {
t.Fatalf("get group: %v", err)
}
if group.Name != "operators" || len(group.Users) != 2 || group.Users[1].Name != "bob" {
t.Fatalf("group response = %#v", group)
}
role, err := client.GetRole(context.Background(), "reader")
if err != nil {
t.Fatalf("get role: %v", err)
}
if role.Name != "reader" || role.AssumeRolePolicy != trustPolicy || role.MaxSessionDuration != 3600 {
t.Fatalf("role response = %#v", role)
}
}
func TestIAMImportIDParsers(t *testing.T) {
t.Parallel()
if name, err := parseIAMImportID("reader-role"); err != nil || name != "reader-role" {
t.Fatalf("parse IAM ID = %q, %v", name, err)
}
if _, err := iamPolicyNameFromARN("arn:aws:iam:::policy/"); err == nil {
t.Fatal("expected invalid empty policy name error")
}
if name, err := iamPolicyNameFromARN("arn:aws:iam:::policy/ReadOnly"); err != nil || name != "ReadOnly" {
t.Fatalf("parse policy ARN = %q, %v", name, err)
}
}
func TestExpirationToUnix(t *testing.T) {
t.Parallel()
unix, err := expirationToUnix("2030-01-02T03:04:05Z")
if err != nil {
t.Fatalf("expirationToUnix() error = %v", err)
}
if unix != "1893553445" {
t.Fatalf("expiration = %s, want 1893553445", unix)
}
if _, err := expirationToUnix("not-a-time"); err == nil {
t.Fatal("expected malformed expiration error")
}
}
func TestDecodeIAMDocument(t *testing.T) {
t.Parallel()
raw := `{"Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::bucket/a+b/100%/*"}]}`
for name, document := range map[string]string{
"raw JSON": raw,
"path escaped": url.PathEscape(raw),
"query escaped": strings.ReplaceAll(url.QueryEscape(raw), "+", "%20"),
} {
decoded, err := decodeIAMDocument(document)
if err != nil {
t.Fatalf("%s: decode: %v", name, err)
}
if decoded != raw {
t.Fatalf("%s: decoded %q, want %q", name, decoded, raw)
}
}
}
func TestValidateOIDCProviderSettings(t *testing.T) {
valid := []string{"abc"}
if err := validateOIDCProviderSettings("https://issuer.example", valid, valid); err != nil {
t.Fatalf("valid settings rejected: %v", err)
}
for name, err := range map[string]error{
"empty thumbprint": validateOIDCProviderSettings("https://issuer.example", valid, []string{"", "abc"}),
"empty client id": validateOIDCProviderSettings("https://issuer.example", []string{"", "abc"}, valid),
"no thumbprints": validateOIDCProviderSettings("https://issuer.example", valid, nil),
"padded url": validateOIDCProviderSettings(" https://issuer.example", valid, valid),
"padded thumbprint": validateOIDCProviderSettings("https://issuer.example", valid, []string{"abc "}),
} {
if err == nil {
t.Errorf("%s: expected an error", name)
}
}
}
+124
View File
@@ -0,0 +1,124 @@
package seaweedfs
import (
"encoding/json"
"errors"
"io"
"strings"
)
func decodeJSONValue(raw string) (any, error) {
decoder := json.NewDecoder(strings.NewReader(raw))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return nil, err
}
if _, err := decoder.Token(); err != io.EOF {
return nil, errors.New("invalid JSON: unexpected data after the top-level value")
}
return value, nil
}
func normalizeJSONString(raw string) (string, error) {
value, err := decodeJSONValue(raw)
if err != nil {
return "", err
}
normalized, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(normalized), nil
}
func policiesSemanticallyEqual(a string, b string) bool {
na, errA := normalizePolicyDocument(a)
nb, errB := normalizePolicyDocument(b)
if errA == nil && errB == nil {
return na == nb
}
return strings.TrimSpace(a) == strings.TrimSpace(b)
}
func normalizePolicyDocument(raw string) (string, error) {
value, err := decodeJSONValue(raw)
if err != nil {
return "", err
}
value = omitNullJSONValues(value)
document, ok := value.(map[string]any)
if !ok {
return "", errors.New("policy document must be a JSON object")
}
statements, ok := document["Statement"].([]any)
if !ok {
if statement, isObject := document["Statement"].(map[string]any); isObject {
statements = []any{statement}
document["Statement"] = statements
}
}
for _, rawStatement := range statements {
statement, ok := rawStatement.(map[string]any)
if !ok {
continue
}
if sid, ok := statement["Sid"].(string); ok && sid == "" {
delete(statement, "Sid")
}
if conditions, ok := statement["Condition"].(map[string]any); ok {
for _, rawOperator := range conditions {
operator, ok := rawOperator.(map[string]any)
if !ok {
continue
}
for key, conditionValue := range operator {
if _, isList := conditionValue.([]any); !isList {
operator[key] = []any{conditionValue}
}
}
}
}
for _, key := range []string{"Action", "NotAction", "Resource", "NotResource"} {
if item, ok := statement[key].(string); ok {
if key == "Resource" && item == "" {
delete(statement, key)
continue
}
statement[key] = []any{item}
}
if key == "Resource" {
if items, ok := statement[key].([]any); ok && len(items) == 1 && items[0] == "" {
delete(statement, key)
}
}
}
}
normalized, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(normalized), nil
}
func omitNullJSONValues(value any) any {
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
if child == nil {
delete(typed, key)
continue
}
typed[key] = omitNullJSONValues(child)
}
case []any:
for i, child := range typed {
typed[i] = omitNullJSONValues(child)
}
}
return value
}
+262
View File
@@ -0,0 +1,262 @@
package seaweedfs
import (
"context"
"fmt"
"os"
"strconv"
"sync"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var _ provider.Provider = &seaweedfsProvider{}
func NewProvider() provider.Provider {
return &seaweedfsProvider{}
}
type seaweedfsProvider struct{}
type seaweedfsProviderModel struct {
Endpoint types.String `tfsdk:"endpoint"`
Region types.String `tfsdk:"region"`
AccessKey types.String `tfsdk:"access_key"`
SecretKey types.String `tfsdk:"secret_key"`
Insecure types.Bool `tfsdk:"insecure"`
}
type providerData struct {
client *iamClient
lockMu sync.Mutex
userLocks map[string]*sync.Mutex
iamLocks map[string]*sync.Mutex
bucketLocks map[string]*sync.Mutex
}
func (d *providerData) withUserLock(userName string, fn func() error) error {
lock := d.getUserLock(userName)
lock.Lock()
defer lock.Unlock()
return fn()
}
func (d *providerData) getUserLock(userName string) *sync.Mutex {
d.lockMu.Lock()
defer d.lockMu.Unlock()
if d.userLocks == nil {
d.userLocks = map[string]*sync.Mutex{}
}
if lock, ok := d.userLocks[userName]; ok {
return lock
}
lock := &sync.Mutex{}
d.userLocks[userName] = lock
return lock
}
func (d *providerData) getBucketLock(bucket string) *sync.Mutex {
d.lockMu.Lock()
defer d.lockMu.Unlock()
if d.bucketLocks == nil {
d.bucketLocks = map[string]*sync.Mutex{}
}
if lock, ok := d.bucketLocks[bucket]; ok {
return lock
}
lock := &sync.Mutex{}
d.bucketLocks[bucket] = lock
return lock
}
func (d *providerData) getIAMPrincipalLock(kind, name string) *sync.Mutex {
key := kind + "/" + name
d.lockMu.Lock()
defer d.lockMu.Unlock()
if d.iamLocks == nil {
d.iamLocks = map[string]*sync.Mutex{}
}
if lock, ok := d.iamLocks[key]; ok {
return lock
}
lock := &sync.Mutex{}
d.iamLocks[key] = lock
return lock
}
func (p *seaweedfsProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "seaweedfs"
}
func (p *seaweedfsProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"endpoint": schema.StringAttribute{
Optional: true,
Description: "SeaweedFS S3/IAM endpoint. Falls back to SEAWEEDFS_ENDPOINT.",
},
"region": schema.StringAttribute{
Optional: true,
Description: "Signing region. Falls back to SEAWEEDFS_REGION. Default: us-east-1.",
},
"access_key": schema.StringAttribute{
Optional: true,
Sensitive: true,
Description: "Admin access key. Falls back to SEAWEEDFS_ACCESS_KEY.",
},
"secret_key": schema.StringAttribute{
Optional: true,
Sensitive: true,
Description: "Admin secret key. Falls back to SEAWEEDFS_SECRET_KEY.",
},
"insecure": schema.BoolAttribute{
Optional: true,
Description: "Skip TLS verification. Falls back to SEAWEEDFS_INSECURE.",
},
},
}
}
func (p *seaweedfsProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var config seaweedfsProviderModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
for _, setting := range []struct {
name string
unknown bool
}{
{"endpoint", config.Endpoint.IsUnknown()},
{"region", config.Region.IsUnknown()},
{"access_key", config.AccessKey.IsUnknown()},
{"secret_key", config.SecretKey.IsUnknown()},
{"insecure", config.Insecure.IsUnknown()},
} {
if setting.unknown {
resp.Diagnostics.AddAttributeError(
path.Root(setting.name),
"Unknown SeaweedFS provider setting",
fmt.Sprintf("The provider cannot be configured while %q is unknown. Set it to a value known at plan time, or leave it unset to use the environment variable.", setting.name),
)
}
}
if resp.Diagnostics.HasError() {
return
}
region := stringConfigValue(config.Region, "SEAWEEDFS_REGION", os.Getenv)
if region == "" {
region = "us-east-1"
}
insecure, err := boolConfigValue(config.Insecure, "SEAWEEDFS_INSECURE", os.Getenv)
if err != nil {
resp.Diagnostics.AddError(
"Invalid SeaweedFS provider configuration",
fmt.Sprintf("SEAWEEDFS_INSECURE must be a boolean: %s", err),
)
return
}
endpoint := stringConfigValue(config.Endpoint, "SEAWEEDFS_ENDPOINT", os.Getenv)
accessKey := stringConfigValue(config.AccessKey, "SEAWEEDFS_ACCESS_KEY", os.Getenv)
secretKey := stringConfigValue(config.SecretKey, "SEAWEEDFS_SECRET_KEY", os.Getenv)
client, err := newIAMClient(iamClientConfig{
Endpoint: endpoint,
Region: region,
AccessKey: accessKey,
SecretKey: secretKey,
Insecure: insecure,
})
if err != nil {
resp.Diagnostics.AddError(
"Unable to configure SeaweedFS IAM client",
fmt.Sprintf("Failed to build client: %s", err),
)
return
}
data := &providerData{
client: client,
userLocks: map[string]*sync.Mutex{},
iamLocks: map[string]*sync.Mutex{},
bucketLocks: map[string]*sync.Mutex{},
}
resp.ResourceData = data
resp.DataSourceData = data
}
func stringConfigValue(value types.String, envName string, getenv func(string) string) string {
if !value.IsNull() && !value.IsUnknown() && value.ValueString() != "" {
return value.ValueString()
}
return getenv(envName)
}
func boolConfigValue(value types.Bool, envName string, getenv func(string) string) (bool, error) {
if !value.IsNull() && !value.IsUnknown() {
return value.ValueBool(), nil
}
raw := getenv(envName)
if raw == "" {
return false, nil
}
return strconv.ParseBool(raw)
}
func (p *seaweedfsProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewBucketResource,
NewBucketCORSConfigurationResource,
NewBucketLifecycleConfigurationResource,
NewBucketVersioningResource,
NewBucketPolicyResource,
NewBucketEncryptionResource,
NewBucketPublicAccessBlockResource,
NewBucketOwnershipControlsResource,
NewBucketRequestPaymentResource,
NewBucketQuotaResource,
NewS3TableBucketResource,
NewS3TableBucketPolicyResource,
NewS3TableBucketMaintenanceConfigurationResource,
NewS3TableNamespaceResource,
NewS3TableResource,
NewS3TablePolicyResource,
NewS3TableMaintenanceConfigurationResource,
NewIAMUserResource,
NewIAMGroupResource,
NewIAMGroupMembershipResource,
NewIAMGroupPolicyResource,
NewIAMRoleResource,
NewIAMPolicyResource,
NewIAMOIDCProviderResource,
NewIAMServiceAccountResource,
NewIAMUserPolicyAttachmentResource,
NewIAMGroupPolicyAttachmentResource,
NewIAMRolePolicyAttachmentResource,
NewIAMAccessKeyResource,
NewIAMUserPolicyResource,
}
}
func (p *seaweedfsProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return nil
}
@@ -0,0 +1,121 @@
package seaweedfs
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)
func TestStringConfigValue(t *testing.T) {
t.Parallel()
getenv := func(key string) string {
if key == "SEAWEEDFS_ENDPOINT" {
return "http://localhost:8333"
}
return ""
}
if got := stringConfigValue(types.StringNull(), "SEAWEEDFS_ENDPOINT", getenv); got != "http://localhost:8333" {
t.Fatalf("environment fallback = %q", got)
}
if got := stringConfigValue(types.StringValue("https://s3.example.test"), "SEAWEEDFS_ENDPOINT", getenv); got != "https://s3.example.test" {
t.Fatalf("explicit value = %q", got)
}
}
func TestBoolConfigValue(t *testing.T) {
t.Parallel()
tests := []struct {
name string
value types.Bool
env string
want bool
wantErr bool
}{
{name: "default false", value: types.BoolNull(), want: false},
{name: "environment true", value: types.BoolNull(), env: "true", want: true},
{name: "explicit false overrides environment", value: types.BoolValue(false), env: "true", want: false},
{name: "invalid environment value", value: types.BoolNull(), env: "yes", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := boolConfigValue(tt.value, "SEAWEEDFS_INSECURE", func(string) string {
return tt.env
})
if (err != nil) != tt.wantErr {
t.Fatalf("error = %v, wantErr %v", err, tt.wantErr)
}
if err == nil && got != tt.want {
t.Fatalf("value = %t, want %t", got, tt.want)
}
})
}
}
func TestConfigureRejectsUnknownEndpoint(t *testing.T) {
t.Setenv("SEAWEEDFS_ENDPOINT", "http://127.0.0.1:8333")
t.Setenv("SEAWEEDFS_ACCESS_KEY", "test-key")
t.Setenv("SEAWEEDFS_SECRET_KEY", "test-secret")
ctx := context.Background()
p := &seaweedfsProvider{}
var schemaResp provider.SchemaResponse
p.Schema(ctx, provider.SchemaRequest{}, &schemaResp)
objectType := schemaResp.Schema.Type().TerraformType(ctx).(tftypes.Object)
values := map[string]tftypes.Value{}
for name, attrType := range objectType.AttributeTypes {
values[name] = tftypes.NewValue(attrType, nil)
}
values["endpoint"] = tftypes.NewValue(tftypes.String, tftypes.UnknownValue)
var resp provider.ConfigureResponse
p.Configure(ctx, provider.ConfigureRequest{Config: tfsdk.Config{
Schema: schemaResp.Schema,
Raw: tftypes.NewValue(objectType, values),
}}, &resp)
if !resp.Diagnostics.HasError() || resp.Diagnostics.Errors()[0].Summary() != "Unknown SeaweedFS provider setting" {
t.Fatalf("diagnostics = %v, want the unknown endpoint rejected", resp.Diagnostics)
}
if resp.ResourceData != nil {
t.Fatal("expected no client when the endpoint is unknown")
}
}
func TestRegisteredResourcesHaveSchemasAndImport(t *testing.T) {
t.Parallel()
provider := &seaweedfsProvider{}
constructors := provider.Resources(t.Context())
if len(constructors) == 0 {
t.Fatal("provider registered no resources")
}
for _, construct := range constructors {
r := construct()
if _, ok := r.(resource.ResourceWithImportState); !ok {
t.Errorf("%T does not support import", r)
}
var metadata resource.MetadataResponse
r.Metadata(t.Context(), resource.MetadataRequest{ProviderTypeName: "seaweedfs"}, &metadata)
if metadata.TypeName == "" {
t.Errorf("%T returned an empty resource type name", r)
}
var schemaResponse resource.SchemaResponse
r.Schema(t.Context(), resource.SchemaRequest{}, &schemaResponse)
if schemaResponse.Diagnostics.HasError() {
t.Errorf("%s schema diagnostics: %v", metadata.TypeName, schemaResponse.Diagnostics)
}
if len(schemaResponse.Schema.Attributes) == 0 {
t.Errorf("%s schema has no attributes", metadata.TypeName)
}
}
}
@@ -0,0 +1,273 @@
package seaweedfs
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &bucketResource{}
_ resource.ResourceWithConfigure = &bucketResource{}
_ resource.ResourceWithImportState = &bucketResource{}
)
func NewBucketResource() resource.Resource {
return &bucketResource{}
}
type bucketResource struct {
client *iamClient
data *providerData
}
type bucketResourceModel struct {
ID types.String `tfsdk:"id"`
Bucket types.String `tfsdk:"bucket"`
ARN types.String `tfsdk:"arn"`
Tags types.Map `tfsdk:"tags"`
}
func (r *bucketResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_bucket"
}
func (r *bucketResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS S3 bucket.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
},
"bucket": schema.StringAttribute{
Required: true,
Description: "Bucket name.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"arn": schema.StringAttribute{
Computed: true,
Description: "Bucket ARN.",
},
"tags": schema.MapAttribute{
Optional: true,
Computed: true,
ElementType: types.StringType,
Description: "Bucket tags.",
},
},
}
}
func (r *bucketResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *bucketResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan bucketResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.CreateBucket(ctx, plan.Bucket.ValueString()); err != nil {
if isBucketTakenError(err) {
resp.Diagnostics.AddError(
"Bucket already exists",
fmt.Sprintf("Bucket %q already exists. SeaweedFS reports this for a bucket owned by another identity, and also for a bucket of yours that has an ACL. If the bucket is yours, import it with `terraform import` to manage it.", plan.Bucket.ValueString()),
)
return
}
if !isBucketAlreadyExistsError(err) {
resp.Diagnostics.AddError("Failed to create bucket", err.Error())
return
}
if headErr := r.client.HeadBucket(ctx, plan.Bucket.ValueString()); headErr != nil {
resp.Diagnostics.AddError("Failed to verify existing bucket", headErr.Error())
return
}
}
planTags, diags := stringMapFromTerraformMap(ctx, plan.Tags)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
if len(planTags) > 0 {
if err := r.client.PutBucketTags(ctx, plan.Bucket.ValueString(), planTags); err != nil {
resp.Diagnostics.AddError("Failed to set bucket tags", err.Error())
return
}
} else if !plan.Tags.IsNull() && !plan.Tags.IsUnknown() {
if err := r.client.DeleteBucketTags(ctx, plan.Bucket.ValueString()); err != nil {
resp.Diagnostics.AddError("Failed to clear bucket tags", err.Error())
return
}
}
remoteTags, err := r.client.GetBucketTags(ctx, plan.Bucket.ValueString())
if err != nil {
resp.Diagnostics.AddError("Failed to read bucket tags", err.Error())
return
}
tagsValue, diags := terraformMapFromStringMap(ctx, remoteTags)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
state := bucketResourceModel{
ID: types.StringValue(plan.Bucket.ValueString()),
Bucket: types.StringValue(plan.Bucket.ValueString()),
ARN: types.StringValue("arn:aws:s3:::" + plan.Bucket.ValueString()),
Tags: tagsValue,
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state bucketResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.HeadBucket(ctx, state.Bucket.ValueString()); err != nil {
if isNoSuchBucketError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read bucket", err.Error())
return
}
tags, err := r.client.GetBucketTags(ctx, state.Bucket.ValueString())
if err != nil {
resp.Diagnostics.AddError("Failed to read bucket tags", err.Error())
return
}
tagsValue, diags := terraformMapFromStringMap(ctx, tags)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
state.ID = types.StringValue(state.Bucket.ValueString())
state.ARN = types.StringValue("arn:aws:s3:::" + state.Bucket.ValueString())
state.Tags = tagsValue
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan bucketResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
tags, diags := stringMapFromTerraformMap(ctx, plan.Tags)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
if len(tags) == 0 {
if err := r.client.DeleteBucketTags(ctx, plan.Bucket.ValueString()); err != nil && !isNoSuchBucketError(err) {
resp.Diagnostics.AddError("Failed to delete bucket tags", err.Error())
return
}
} else {
if err := r.client.PutBucketTags(ctx, plan.Bucket.ValueString(), tags); err != nil {
resp.Diagnostics.AddError("Failed to update bucket tags", err.Error())
return
}
}
remoteTags, err := r.client.GetBucketTags(ctx, plan.Bucket.ValueString())
if err != nil {
resp.Diagnostics.AddError("Failed to read bucket tags", err.Error())
return
}
tagsValue, diags := terraformMapFromStringMap(ctx, remoteTags)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
state := bucketResourceModel{
ID: types.StringValue(plan.Bucket.ValueString()),
Bucket: types.StringValue(plan.Bucket.ValueString()),
ARN: types.StringValue("arn:aws:s3:::" + plan.Bucket.ValueString()),
Tags: tagsValue,
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state bucketResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.DeleteBucket(ctx, state.Bucket.ValueString()); err != nil && !isNoSuchBucketError(err) {
resp.Diagnostics.AddError("Failed to delete bucket", err.Error())
}
}
func (r *bucketResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), req.ID)...)
}
func stringMapFromTerraformMap(ctx context.Context, value types.Map) (map[string]string, diag.Diagnostics) {
if value.IsNull() || value.IsUnknown() {
return map[string]string{}, nil
}
out := map[string]string{}
diags := value.ElementsAs(ctx, &out, false)
return out, diags
}
func terraformMapFromStringMap(ctx context.Context, values map[string]string) (types.Map, diag.Diagnostics) {
if values == nil {
values = map[string]string{}
}
return types.MapValueFrom(ctx, types.StringType, values)
}
@@ -0,0 +1,596 @@
package seaweedfs
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type bucketConfigurationModel struct {
ID types.String `tfsdk:"id"`
Bucket types.String `tfsdk:"bucket"`
Configuration types.String `tfsdk:"configuration"`
}
type bucketConfigurationOperations struct {
suffix string
description string
normalize func(string) (string, error)
get func(context.Context, *iamClient, string) (string, error)
put func(context.Context, *iamClient, string, string) error
delete func(context.Context, *iamClient, string) error
}
type bucketConfigurationResource struct {
client *iamClient
data *providerData
ops bucketConfigurationOperations
}
var (
_ resource.Resource = &bucketConfigurationResource{}
_ resource.ResourceWithConfigure = &bucketConfigurationResource{}
_ resource.ResourceWithImportState = &bucketConfigurationResource{}
)
func NewBucketCORSConfigurationResource() resource.Resource {
return newBucketConfigurationResource(bucketConfigurationOperations{
suffix: "bucket_cors_configuration",
description: "Manages a SeaweedFS S3 bucket CORS configuration. Configuration is JSON encoded.",
normalize: normalizeBucketConfiguration[s3types.CORSConfiguration],
get: getBucketCORSConfiguration,
put: putBucketCORSConfiguration,
delete: deleteBucketCORSConfiguration,
})
}
func NewBucketLifecycleConfigurationResource() resource.Resource {
return newBucketConfigurationResource(bucketConfigurationOperations{
suffix: "bucket_lifecycle_configuration",
description: "Manages a SeaweedFS S3 bucket lifecycle configuration. Configuration is JSON encoded.",
normalize: normalizeBucketConfiguration[s3types.BucketLifecycleConfiguration],
get: getBucketLifecycleConfiguration,
put: putBucketLifecycleConfiguration,
delete: deleteBucketLifecycleConfiguration,
})
}
func NewBucketVersioningResource() resource.Resource {
return newBucketConfigurationResource(bucketConfigurationOperations{
suffix: "bucket_versioning",
description: "Manages SeaweedFS S3 bucket versioning. Configuration is JSON encoded; destroy suspends versioning because S3 cannot unset it. On a bucket with object lock, SeaweedFS rejects the suspension with InvalidBucketState, so remove the resource with `terraform state rm` instead of destroying it.",
normalize: normalizeBucketConfiguration[s3types.VersioningConfiguration],
get: getBucketVersioning,
put: putBucketVersioning,
delete: suspendBucketVersioning,
})
}
func NewBucketEncryptionResource() resource.Resource {
return newBucketConfigurationResource(bucketConfigurationOperations{
suffix: "bucket_encryption",
description: "Manages a SeaweedFS S3 bucket default encryption configuration. Configuration is JSON encoded.",
normalize: normalizeBucketEncryptionConfiguration,
get: getBucketEncryption,
put: putBucketEncryption,
delete: deleteBucketEncryption,
})
}
func NewBucketPublicAccessBlockResource() resource.Resource {
return newBucketConfigurationResource(bucketConfigurationOperations{
suffix: "bucket_public_access_block",
description: "Manages a SeaweedFS S3 bucket public access block configuration where supported. SeaweedFS 4.51.0 returns NotImplemented for this API.",
normalize: normalizeBucketPublicAccessBlockConfiguration,
get: getBucketPublicAccessBlock,
put: putBucketPublicAccessBlock,
delete: deleteBucketPublicAccessBlock,
})
}
func NewBucketOwnershipControlsResource() resource.Resource {
return newBucketConfigurationResource(bucketConfigurationOperations{
suffix: "bucket_ownership_controls",
description: "Manages SeaweedFS S3 bucket ownership controls. Configuration is JSON encoded.",
normalize: normalizeBucketConfiguration[s3types.OwnershipControls],
get: getBucketOwnershipControls,
put: putBucketOwnershipControls,
delete: deleteBucketOwnershipControls,
})
}
func NewBucketRequestPaymentResource() resource.Resource {
return newBucketConfigurationResource(bucketConfigurationOperations{
suffix: "bucket_request_payment",
description: "Manages a SeaweedFS S3 bucket request payment configuration. Destroy resets the payer to BucketOwner. SeaweedFS accepts only `BucketOwner`; it rejects `Requester` with `MalformedXML`.",
normalize: normalizeBucketConfiguration[s3types.RequestPaymentConfiguration],
get: getBucketRequestPayment,
put: putBucketRequestPayment,
delete: resetBucketRequestPayment,
})
}
func newBucketConfigurationResource(ops bucketConfigurationOperations) resource.Resource {
return &bucketConfigurationResource{ops: ops}
}
func (r *bucketConfigurationResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_" + r.ops.suffix
}
func (r *bucketConfigurationResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: r.ops.description + " Import using the bucket name.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"bucket": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "S3 bucket name.",
},
"configuration": schema.StringAttribute{
Required: true,
Description: "JSON encoded configuration document.",
},
},
}
}
func (r *bucketConfigurationResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *bucketConfigurationResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan bucketConfigurationModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.ops.put(ctx, r.client, plan.Bucket.ValueString(), plan.Configuration.ValueString()); err != nil {
resp.Diagnostics.AddError("Failed to create bucket configuration", err.Error())
return
}
state := plan
if !r.refresh(ctx, &state, &resp.Diagnostics) {
if !resp.Diagnostics.HasError() {
resp.Diagnostics.AddError("Bucket configuration not found after create", "SeaweedFS accepted the write but did not return the configuration on read.")
}
return
}
if state.Configuration.ValueString() != plan.Configuration.ValueString() {
resp.Diagnostics.AddError("Bucket configuration not fully applied", fmt.Sprintf("SeaweedFS stored %s, which differs from the configured document.", state.Configuration.ValueString()))
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketConfigurationResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state bucketConfigurationModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if !r.refresh(ctx, &state, &resp.Diagnostics) {
if !resp.Diagnostics.HasError() {
resp.State.RemoveResource(ctx)
}
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketConfigurationResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan bucketConfigurationModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.ops.put(ctx, r.client, plan.Bucket.ValueString(), plan.Configuration.ValueString()); err != nil {
resp.Diagnostics.AddError("Failed to update bucket configuration", err.Error())
return
}
state := plan
if !r.refresh(ctx, &state, &resp.Diagnostics) {
if !resp.Diagnostics.HasError() {
resp.Diagnostics.AddError("Bucket configuration not found after update", "SeaweedFS accepted the write but did not return the configuration on read.")
}
return
}
if state.Configuration.ValueString() != plan.Configuration.ValueString() {
resp.Diagnostics.AddError("Bucket configuration not fully applied", fmt.Sprintf("SeaweedFS stored %s, which differs from the configured document.", state.Configuration.ValueString()))
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketConfigurationResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state bucketConfigurationModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.ops.delete(ctx, r.client, state.Bucket.ValueString()); err != nil && !isMissingBucketConfiguration(err) {
resp.Diagnostics.AddError("Failed to delete bucket configuration", err.Error())
}
}
func (r *bucketConfigurationResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
bucket, err := parseBucketImportID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), bucket)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), bucket)...)
}
func parseBucketImportID(id string) (string, error) {
if id == "" || strings.TrimSpace(id) != id || strings.Contains(id, ",") {
return "", errors.New("expected import ID in the format `bucket_name`")
}
return id, nil
}
func (r *bucketConfigurationResource) refresh(ctx context.Context, state *bucketConfigurationModel, diags *diag.Diagnostics) bool {
raw, err := r.ops.get(ctx, r.client, state.Bucket.ValueString())
if err != nil {
if isMissingBucketConfiguration(err) {
return false
}
diags.AddError("Failed to read bucket configuration", err.Error())
return false
}
normalized, err := normalizeBucketConfigurationForComparison(r.ops.normalize, raw)
if err != nil {
diags.AddError("Failed to normalize bucket configuration", err.Error())
return false
}
if state.Configuration.IsNull() || state.Configuration.IsUnknown() {
state.Configuration = types.StringValue(normalized)
} else {
desired, err := normalizeBucketConfigurationForComparison(r.ops.normalize, state.Configuration.ValueString())
if err != nil {
diags.AddError("Failed to normalize configured bucket configuration", err.Error())
return false
}
if desired != normalized {
state.Configuration = types.StringValue(normalized)
}
}
state.ID = types.StringValue(state.Bucket.ValueString())
return true
}
func decodeBucketConfiguration(raw string, value any) error {
decoder := json.NewDecoder(strings.NewReader(raw))
decoder.DisallowUnknownFields()
if err := decoder.Decode(value); err != nil {
return fmt.Errorf("decode JSON configuration: %w", err)
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return errors.New("configuration must contain exactly one JSON value")
}
return nil
}
func encodeBucketConfiguration(value any) (string, error) {
encoded, err := json.Marshal(value)
if err != nil {
return "", fmt.Errorf("encode bucket configuration: %w", err)
}
return string(encoded), nil
}
func normalizeBucketConfiguration[T any](raw string) (string, error) {
var configuration T
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return "", err
}
return encodeBucketConfiguration(configuration)
}
func normalizeBucketEncryptionConfiguration(raw string) (string, error) {
var configuration s3types.ServerSideEncryptionConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return "", err
}
for i := range configuration.Rules {
if configuration.Rules[i].BucketKeyEnabled != nil && !*configuration.Rules[i].BucketKeyEnabled {
configuration.Rules[i].BucketKeyEnabled = nil
}
}
return encodeBucketConfiguration(configuration)
}
func normalizeBucketPublicAccessBlockConfiguration(raw string) (string, error) {
var configuration s3types.PublicAccessBlockConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return "", err
}
for _, flag := range []**bool{&configuration.BlockPublicAcls, &configuration.IgnorePublicAcls, &configuration.BlockPublicPolicy, &configuration.RestrictPublicBuckets} {
if *flag == nil {
*flag = aws.Bool(false)
}
}
return encodeBucketConfiguration(configuration)
}
func normalizeBucketConfigurationForComparison(normalize func(string) (string, error), raw string) (string, error) {
typed, err := normalize(raw)
if err != nil {
return "", err
}
value, err := decodeJSONValue(typed)
if err != nil {
return "", err
}
normalized, err := json.Marshal(omitEmptyJSONLists(omitNullJSONValues(value)))
if err != nil {
return "", err
}
return string(normalized), nil
}
func omitEmptyJSONLists(value any) any {
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
if list, ok := child.([]any); ok && len(list) == 0 {
delete(typed, key)
continue
}
typed[key] = omitEmptyJSONLists(child)
}
case []any:
for i, child := range typed {
typed[i] = omitEmptyJSONLists(child)
}
}
return value
}
func isMissingBucketConfiguration(err error) bool {
var iamErr iamError
if errors.As(err, &iamErr) && (iamErr.Code == "NoSuchBucket" || iamErr.Code == "HTTP404") {
return true
}
var apiErr smithy.APIError
if !errors.As(err, &apiErr) {
return false
}
switch apiErr.ErrorCode() {
case "NoSuchBucket", "NotFound", "NoSuchBucketPolicy", "NoSuchCORSConfiguration", "NoSuchLifecycleConfiguration",
"ServerSideEncryptionConfigurationNotFoundError", "NoSuchPublicAccessBlockConfiguration",
"NoSuchOwnershipControls", "OwnershipControlsNotFoundError", "NoSuchConfiguration":
return true
default:
return false
}
}
func putBucketCORSConfiguration(ctx context.Context, client *iamClient, bucket, raw string) error {
var configuration s3types.CORSConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return err
}
_, err := client.s3.PutBucketCors(ctx, &s3.PutBucketCorsInput{
Bucket: aws.String(bucket),
CORSConfiguration: &configuration,
})
return err
}
func getBucketCORSConfiguration(ctx context.Context, client *iamClient, bucket string) (string, error) {
output, err := client.s3.GetBucketCors(ctx, &s3.GetBucketCorsInput{Bucket: aws.String(bucket)})
if err != nil {
return "", err
}
return encodeBucketConfiguration(s3types.CORSConfiguration{CORSRules: output.CORSRules})
}
func deleteBucketCORSConfiguration(ctx context.Context, client *iamClient, bucket string) error {
_, err := client.s3.DeleteBucketCors(ctx, &s3.DeleteBucketCorsInput{Bucket: aws.String(bucket)})
return err
}
func putBucketLifecycleConfiguration(ctx context.Context, client *iamClient, bucket, raw string) error {
var configuration s3types.BucketLifecycleConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return err
}
_, err := client.s3.PutBucketLifecycleConfiguration(ctx, &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &configuration,
})
return err
}
func getBucketLifecycleConfiguration(ctx context.Context, client *iamClient, bucket string) (string, error) {
output, err := client.s3.GetBucketLifecycleConfiguration(ctx, &s3.GetBucketLifecycleConfigurationInput{Bucket: aws.String(bucket)})
if err != nil {
return "", err
}
return encodeBucketConfiguration(s3types.BucketLifecycleConfiguration{Rules: output.Rules})
}
func deleteBucketLifecycleConfiguration(ctx context.Context, client *iamClient, bucket string) error {
_, err := client.s3.DeleteBucketLifecycle(ctx, &s3.DeleteBucketLifecycleInput{Bucket: aws.String(bucket)})
return err
}
func putBucketVersioning(ctx context.Context, client *iamClient, bucket, raw string) error {
var configuration s3types.VersioningConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return err
}
_, err := client.s3.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{
Bucket: aws.String(bucket),
VersioningConfiguration: &configuration,
})
return err
}
func getBucketVersioning(ctx context.Context, client *iamClient, bucket string) (string, error) {
output, err := client.s3.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(bucket)})
if err != nil {
return "", err
}
return encodeBucketConfiguration(s3types.VersioningConfiguration{Status: output.Status, MFADelete: s3types.MFADelete(output.MFADelete)})
}
func suspendBucketVersioning(ctx context.Context, client *iamClient, bucket string) error {
return putBucketVersioning(ctx, client, bucket, `{"Status":"Suspended"}`)
}
func putBucketEncryption(ctx context.Context, client *iamClient, bucket, raw string) error {
var configuration s3types.ServerSideEncryptionConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return err
}
_, err := client.s3.PutBucketEncryption(ctx, &s3.PutBucketEncryptionInput{
Bucket: aws.String(bucket),
ServerSideEncryptionConfiguration: &configuration,
})
return err
}
func getBucketEncryption(ctx context.Context, client *iamClient, bucket string) (string, error) {
output, err := client.s3.GetBucketEncryption(ctx, &s3.GetBucketEncryptionInput{Bucket: aws.String(bucket)})
if err != nil {
return "", err
}
return encodeBucketConfiguration(output.ServerSideEncryptionConfiguration)
}
func deleteBucketEncryption(ctx context.Context, client *iamClient, bucket string) error {
_, err := client.s3.DeleteBucketEncryption(ctx, &s3.DeleteBucketEncryptionInput{Bucket: aws.String(bucket)})
return err
}
func putBucketPublicAccessBlock(ctx context.Context, client *iamClient, bucket, raw string) error {
var configuration s3types.PublicAccessBlockConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return err
}
_, err := client.s3.PutPublicAccessBlock(ctx, &s3.PutPublicAccessBlockInput{
Bucket: aws.String(bucket),
PublicAccessBlockConfiguration: &configuration,
})
return err
}
func getBucketPublicAccessBlock(ctx context.Context, client *iamClient, bucket string) (string, error) {
output, err := client.s3.GetPublicAccessBlock(ctx, &s3.GetPublicAccessBlockInput{Bucket: aws.String(bucket)})
if err != nil {
return "", err
}
return encodeBucketConfiguration(output.PublicAccessBlockConfiguration)
}
func deleteBucketPublicAccessBlock(ctx context.Context, client *iamClient, bucket string) error {
_, err := client.s3.DeletePublicAccessBlock(ctx, &s3.DeletePublicAccessBlockInput{Bucket: aws.String(bucket)})
return err
}
func putBucketOwnershipControls(ctx context.Context, client *iamClient, bucket, raw string) error {
var configuration s3types.OwnershipControls
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return err
}
_, err := client.s3.PutBucketOwnershipControls(ctx, &s3.PutBucketOwnershipControlsInput{
Bucket: aws.String(bucket),
OwnershipControls: &configuration,
})
return err
}
func getBucketOwnershipControls(ctx context.Context, client *iamClient, bucket string) (string, error) {
output, err := client.s3.GetBucketOwnershipControls(ctx, &s3.GetBucketOwnershipControlsInput{Bucket: aws.String(bucket)})
if err != nil {
return "", err
}
return encodeBucketConfiguration(output.OwnershipControls)
}
func deleteBucketOwnershipControls(ctx context.Context, client *iamClient, bucket string) error {
_, err := client.s3.DeleteBucketOwnershipControls(ctx, &s3.DeleteBucketOwnershipControlsInput{Bucket: aws.String(bucket)})
return err
}
func putBucketRequestPayment(ctx context.Context, client *iamClient, bucket, raw string) error {
var configuration s3types.RequestPaymentConfiguration
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
return err
}
_, err := client.s3.PutBucketRequestPayment(ctx, &s3.PutBucketRequestPaymentInput{
Bucket: aws.String(bucket),
RequestPaymentConfiguration: &configuration,
})
return err
}
func getBucketRequestPayment(ctx context.Context, client *iamClient, bucket string) (string, error) {
output, err := client.s3.GetBucketRequestPayment(ctx, &s3.GetBucketRequestPaymentInput{Bucket: aws.String(bucket)})
if err != nil {
return "", err
}
return encodeBucketConfiguration(s3types.RequestPaymentConfiguration{Payer: output.Payer})
}
func resetBucketRequestPayment(ctx context.Context, client *iamClient, bucket string) error {
return putBucketRequestPayment(ctx, client, bucket, `{"Payer":"BucketOwner"}`)
}
@@ -0,0 +1,214 @@
package seaweedfs
import (
"context"
"net/url"
"testing"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)
func TestDecodeBucketConfiguration(t *testing.T) {
tests := []struct {
name string
raw string
wantErr bool
}{
{
name: "valid CORS document",
raw: `{"CORSRules":[{"AllowedMethods":["GET"],"AllowedOrigins":["https://example.com"]}]}`,
},
{
name: "malformed JSON",
raw: `{"CORSRules":`,
wantErr: true,
},
{
name: "unknown field",
raw: `{"CORSRules":[],"unexpected":true}`,
wantErr: true,
},
{
name: "multiple JSON values",
raw: `{"CORSRules":[]} {}`,
wantErr: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var configuration s3types.CORSConfiguration
err := decodeBucketConfiguration(test.raw, &configuration)
if (err != nil) != test.wantErr {
t.Fatalf("decodeBucketConfiguration() error = %v, wantErr %v", err, test.wantErr)
}
})
}
}
func TestNormalizeBucketConfiguration(t *testing.T) {
raw := `{"CORSRules":[{"AllowedOrigins":["https://example.com"],"AllowedMethods":["GET"]}]}`
got, err := normalizeBucketConfiguration[s3types.CORSConfiguration](raw)
if err != nil {
t.Fatalf("normalizeBucketConfiguration() error = %v", err)
}
var configuration s3types.CORSConfiguration
if err := decodeBucketConfiguration(got, &configuration); err != nil {
t.Fatalf("normalized configuration did not decode: %v", err)
}
if len(configuration.CORSRules) != 1 ||
len(configuration.CORSRules[0].AllowedMethods) != 1 ||
configuration.CORSRules[0].AllowedMethods[0] != "GET" ||
len(configuration.CORSRules[0].AllowedOrigins) != 1 ||
configuration.CORSRules[0].AllowedOrigins[0] != "https://example.com" {
t.Fatalf("normalized configuration lost values: %s", got)
}
again, err := normalizeBucketConfiguration[s3types.CORSConfiguration](got)
if err != nil {
t.Fatalf("normalizing the canonical configuration again: %v", err)
}
if again != got {
t.Fatalf("normalization is not stable: first %s, then %s", got, again)
}
}
func TestBucketConfigurationComparisonUsesTypedValues(t *testing.T) {
desired := `{"corsRules":[{"allowedOrigins":["https://example.com"],"allowedMethods":["GET"]}]}`
remote := `{"CORSRules":[{"AllowedMethods":["GET"],"AllowedOrigins":["https://example.com"],"ExposeHeaders":null,"ID":null,"MaxAgeSeconds":null,"AllowedHeaders":null}]}`
desiredNormalized, err := normalizeBucketConfigurationForComparison(normalizeBucketConfiguration[s3types.CORSConfiguration], desired)
if err != nil {
t.Fatalf("normalize desired configuration: %v", err)
}
remoteNormalized, err := normalizeBucketConfigurationForComparison(normalizeBucketConfiguration[s3types.CORSConfiguration], remote)
if err != nil {
t.Fatalf("normalize remote configuration: %v", err)
}
if desiredNormalized != remoteNormalized {
t.Fatalf("typed configurations differ:\nwant %s\ngot %s", desiredNormalized, remoteNormalized)
}
}
func TestBucketConfigurationComparisonTreatsEmptyListsAsAbsent(t *testing.T) {
desired := `{"CORSRules":[{"AllowedHeaders":[],"AllowedMethods":["GET"],"AllowedOrigins":["*"]}]}`
remote := `{"CORSRules":[{"AllowedMethods":["GET"],"AllowedOrigins":["*"]}]}`
normalize := normalizeBucketConfiguration[s3types.CORSConfiguration]
desiredNormalized, err := normalizeBucketConfigurationForComparison(normalize, desired)
if err != nil {
t.Fatalf("normalize desired configuration: %v", err)
}
remoteNormalized, err := normalizeBucketConfigurationForComparison(normalize, remote)
if err != nil {
t.Fatalf("normalize remote configuration: %v", err)
}
if desiredNormalized != remoteNormalized {
t.Fatalf("configurations differ:\nwant %s\ngot %s", desiredNormalized, remoteNormalized)
}
}
func TestIsMissingBucketConfigurationWhenBucketIsGone(t *testing.T) {
for _, code := range []string{"NoSuchBucket", "HTTP404"} {
if !isMissingBucketConfiguration(iamError{Code: code}) {
t.Errorf("isMissingBucketConfiguration(%q) = false, want true", code)
}
}
}
func TestParseBucketImportID(t *testing.T) {
tests := []struct {
name string
id string
want string
wantErr bool
}{
{name: "bucket name", id: "media-bucket", want: "media-bucket"},
{name: "empty", id: "", wantErr: true},
{name: "whitespace", id: " media-bucket ", wantErr: true},
{name: "composite", id: "media-bucket,extra", wantErr: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := parseBucketImportID(test.id)
if (err != nil) != test.wantErr {
t.Fatalf("parseBucketImportID() error = %v, wantErr %v", err, test.wantErr)
}
if got != test.want {
t.Fatalf("parseBucketImportID() = %q, want %q", got, test.want)
}
})
}
}
func TestBucketQuotaURL(t *testing.T) {
endpoint := "http://localhost:8333"
parsed, err := url.Parse(bucketQuotaURL(endpoint, "media-bucket"))
if err != nil {
t.Fatalf("url.Parse() error = %v", err)
}
if parsed.Path != "/media-bucket" {
t.Errorf("path = %q, want %q", parsed.Path, "/media-bucket")
}
if parsed.Query().Get("seaweedfs-quota") != "" || !parsed.Query().Has("seaweedfs-quota") {
t.Errorf("query = %q, want seaweedfs-quota selector", parsed.RawQuery)
}
}
func TestBucketConfigurationCreateReportsUnappliedSettings(t *testing.T) {
ctx := context.Background()
stored := ""
r := &bucketConfigurationResource{
data: &providerData{},
ops: bucketConfigurationOperations{
normalize: normalizeBucketConfiguration[s3types.VersioningConfiguration],
put: func(_ context.Context, _ *iamClient, _ string, configuration string) error {
stored = `{"Status":"Enabled"}`
return nil
},
get: func(context.Context, *iamClient, string) (string, error) { return stored, nil },
},
}
var schemaResp resource.SchemaResponse
r.Schema(ctx, resource.SchemaRequest{}, &schemaResp)
objectType := schemaResp.Schema.Type().TerraformType(ctx).(tftypes.Object)
plan := tfsdk.Plan{Schema: schemaResp.Schema, Raw: tftypes.NewValue(objectType, map[string]tftypes.Value{
"id": tftypes.NewValue(tftypes.String, tftypes.UnknownValue),
"bucket": tftypes.NewValue(tftypes.String, "b1"),
"configuration": tftypes.NewValue(tftypes.String, `{"Status":"Enabled","MFADelete":"Enabled"}`),
})}
resp := resource.CreateResponse{State: tfsdk.State{Schema: schemaResp.Schema, Raw: tftypes.NewValue(objectType, nil)}}
r.Create(ctx, resource.CreateRequest{Plan: plan}, &resp)
if !resp.Diagnostics.HasError() {
t.Fatal("expected a diagnostic for the setting SeaweedFS did not store")
}
var state bucketConfigurationModel
resp.Diagnostics.Append(resp.State.Get(ctx, &state)...)
if got := state.Configuration.ValueString(); got != `{"MFADelete":"","Status":"Enabled"}` {
t.Fatalf("state configuration = %s, want the stored document", got)
}
}
func TestPublicAccessBlockComparisonTreatsOmittedFlagsAsFalse(t *testing.T) {
normalize := func(raw string) string {
t.Helper()
got, err := normalizeBucketConfigurationForComparison(normalizeBucketPublicAccessBlockConfiguration, raw)
if err != nil {
t.Fatalf("normalize %s: %v", raw, err)
}
return got
}
configured := normalize(`{"BlockPublicAcls":true}`)
stored := normalize(`{"BlockPublicAcls":true,"IgnorePublicAcls":false,"BlockPublicPolicy":false,"RestrictPublicBuckets":false}`)
if configured != stored {
t.Fatalf("omitted flags compare different: %s vs %s", configured, stored)
}
if normalize(`{"BlockPublicAcls":false}`) == configured {
t.Fatal("true and false flags compare equal")
}
}
@@ -0,0 +1,202 @@
package seaweedfs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &bucketPolicyResource{}
_ resource.ResourceWithConfigure = &bucketPolicyResource{}
_ resource.ResourceWithImportState = &bucketPolicyResource{}
)
type bucketPolicyResource struct {
client *iamClient
data *providerData
}
type bucketPolicyResourceModel struct {
ID types.String `tfsdk:"id"`
Bucket types.String `tfsdk:"bucket"`
Policy types.String `tfsdk:"policy"`
}
func NewBucketPolicyResource() resource.Resource {
return &bucketPolicyResource{}
}
func (r *bucketPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_bucket_policy"
}
func (r *bucketPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages the S3 bucket policy in SeaweedFS. Import using the bucket name.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"bucket": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "S3 bucket name.",
},
"policy": schema.StringAttribute{
Required: true,
Description: "JSON bucket policy document.",
},
},
}
}
func (r *bucketPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *bucketPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan bucketPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
normalized, err := normalizeJSONString(plan.Policy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid bucket policy", err.Error())
return
}
_, err = r.client.s3.PutBucketPolicy(ctx, &s3.PutBucketPolicyInput{
Bucket: aws.String(plan.Bucket.ValueString()),
Policy: aws.String(normalized),
})
if err != nil {
resp.Diagnostics.AddError("Failed to create bucket policy", err.Error())
return
}
plan.ID = types.StringValue(plan.Bucket.ValueString())
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *bucketPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state bucketPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
output, err := r.client.s3.GetBucketPolicy(ctx, &s3.GetBucketPolicyInput{Bucket: aws.String(state.Bucket.ValueString())})
if err != nil {
if isMissingBucketPolicy(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read bucket policy", err.Error())
return
}
state.ID = types.StringValue(state.Bucket.ValueString())
remotePolicy := aws.ToString(output.Policy)
if !policiesSemanticallyEqual(state.Policy.ValueString(), remotePolicy) {
state.Policy = types.StringValue(remotePolicy)
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan bucketPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
normalized, err := normalizeJSONString(plan.Policy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid bucket policy", err.Error())
return
}
_, err = r.client.s3.PutBucketPolicy(ctx, &s3.PutBucketPolicyInput{
Bucket: aws.String(plan.Bucket.ValueString()),
Policy: aws.String(normalized),
})
if err != nil {
resp.Diagnostics.AddError("Failed to update bucket policy", err.Error())
return
}
plan.ID = types.StringValue(plan.Bucket.ValueString())
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *bucketPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state bucketPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
_, err := r.client.s3.DeleteBucketPolicy(ctx, &s3.DeleteBucketPolicyInput{Bucket: aws.String(state.Bucket.ValueString())})
if err != nil && !isMissingBucketPolicy(err) {
resp.Diagnostics.AddError("Failed to delete bucket policy", err.Error())
}
}
func (r *bucketPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
bucket, err := parseBucketImportID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), bucket)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), bucket)...)
}
func isMissingBucketPolicy(err error) bool {
var apiErr smithy.APIError
if !errors.As(err, &apiErr) {
return false
}
switch apiErr.ErrorCode() {
case "NoSuchBucket", "NoSuchBucketPolicy":
return true
default:
return false
}
}
@@ -0,0 +1,233 @@
package seaweedfs
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &bucketQuotaResource{}
_ resource.ResourceWithConfigure = &bucketQuotaResource{}
_ resource.ResourceWithImportState = &bucketQuotaResource{}
)
type bucketQuotaResource struct {
client *iamClient
data *providerData
}
type bucketQuotaResourceModel struct {
ID types.String `tfsdk:"id"`
Bucket types.String `tfsdk:"bucket"`
QuotaBytes types.Int64 `tfsdk:"quota_bytes"`
Enabled types.Bool `tfsdk:"enabled"`
}
type bucketQuotaConfiguration struct {
QuotaSize int64 `json:"quota_size"`
QuotaUnit string `json:"quota_unit"`
QuotaEnabled bool `json:"quota_enabled"`
}
func NewBucketQuotaResource() resource.Resource {
return &bucketQuotaResource{}
}
func (r *bucketQuotaResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_bucket_quota"
}
func (r *bucketQuotaResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS-specific S3 bucket storage quota. Import using the bucket name.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"bucket": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "S3 bucket name.",
},
"quota_bytes": schema.Int64Attribute{
Required: true,
Description: "Maximum bucket size in bytes. Use zero only when the quota is disabled.",
},
"enabled": schema.BoolAttribute{
Required: true,
Description: "Whether SeaweedFS enforces the quota.",
},
},
}
}
func (r *bucketQuotaResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *bucketQuotaResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan bucketQuotaResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.put(ctx, plan); err != nil {
resp.Diagnostics.AddError("Failed to create bucket quota", err.Error())
return
}
if !r.refresh(ctx, &plan, &resp.Diagnostics) {
if !resp.Diagnostics.HasError() {
resp.Diagnostics.AddError("Bucket quota not found after create", "SeaweedFS accepted the write but did not return the quota on read.")
}
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *bucketQuotaResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state bucketQuotaResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if !r.refresh(ctx, &state, &resp.Diagnostics) {
if !resp.Diagnostics.HasError() {
resp.State.RemoveResource(ctx)
}
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *bucketQuotaResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan bucketQuotaResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(plan.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.put(ctx, plan); err != nil {
resp.Diagnostics.AddError("Failed to update bucket quota", err.Error())
return
}
if !r.refresh(ctx, &plan, &resp.Diagnostics) {
if !resp.Diagnostics.HasError() {
resp.Diagnostics.AddError("Bucket quota not found after update", "SeaweedFS accepted the write but did not return the quota on read.")
}
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *bucketQuotaResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state bucketQuotaResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock(state.Bucket.ValueString())
lock.Lock()
defer lock.Unlock()
_, err := r.client.doSignedRequest(ctx, "s3", http.MethodPut,
bucketQuotaURL(r.client.endpoint, state.Bucket.ValueString()), "application/json",
`{"quota_size":0,"quota_unit":"B","quota_enabled":false}`, nil)
if err != nil && !isNoSuchBucketError(err) {
resp.Diagnostics.AddError("Failed to delete bucket quota", err.Error())
}
}
func (r *bucketQuotaResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
bucket, err := parseBucketImportID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), bucket)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), bucket)...)
}
func (r *bucketQuotaResource) put(ctx context.Context, model bucketQuotaResourceModel) error {
if model.QuotaBytes.ValueInt64() < 0 {
return fmt.Errorf("quota_bytes must not be negative")
}
configuration, err := json.Marshal(bucketQuotaConfiguration{
QuotaSize: model.QuotaBytes.ValueInt64(),
QuotaUnit: "B",
QuotaEnabled: model.Enabled.ValueBool(),
})
if err != nil {
return fmt.Errorf("encode bucket quota: %w", err)
}
_, err = r.client.doSignedRequest(ctx, "s3", http.MethodPut,
bucketQuotaURL(r.client.endpoint, model.Bucket.ValueString()), "application/json",
string(configuration), nil)
return err
}
func (r *bucketQuotaResource) refresh(ctx context.Context, state *bucketQuotaResourceModel, diags *diag.Diagnostics) bool {
response, err := r.client.doSignedRequest(ctx, "s3", http.MethodGet,
bucketQuotaURL(r.client.endpoint, state.Bucket.ValueString()), "", "", nil)
if err != nil {
if isNoSuchBucketError(err) {
return false
}
diags.AddError("Failed to read bucket quota", err.Error())
return false
}
var configuration bucketQuotaConfiguration
if err := json.Unmarshal(response, &configuration); err != nil {
diags.AddError("Failed to decode bucket quota", err.Error())
return false
}
if configuration.QuotaUnit != "B" {
diags.AddError("Unexpected bucket quota unit", fmt.Sprintf("Expected SeaweedFS to return quota_unit B, got %q", configuration.QuotaUnit))
return false
}
state.ID = types.StringValue(state.Bucket.ValueString())
state.QuotaBytes = types.Int64Value(configuration.QuotaSize)
state.Enabled = types.BoolValue(configuration.QuotaEnabled)
return true
}
func bucketQuotaURL(endpoint, bucket string) string {
query := url.Values{}
query.Set("seaweedfs-quota", "")
return endpoint + "/" + url.PathEscape(bucket) + "?" + query.Encode()
}
@@ -0,0 +1,31 @@
package seaweedfs
import (
"context"
"net/http"
"strings"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)
func TestBucketCreateDoesNotAdoptTakenBucket(t *testing.T) {
ctx := context.Background()
client := testIAMClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
}
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`<Error><Code>BucketAlreadyExists</Code><Message>taken</Message></Error>`))
})
r := &bucketResource{client: client, data: &providerData{}}
plan, state := testResourcePlan(ctx, r, map[string]tftypes.Value{
"bucket": tftypes.NewValue(tftypes.String, "photos"),
})
resp := resource.CreateResponse{State: state}
r.Create(ctx, resource.CreateRequest{Plan: plan}, &resp)
if !resp.Diagnostics.HasError() || !strings.Contains(resp.Diagnostics.Errors()[0].Detail(), "terraform import") {
t.Fatalf("diagnostics = %v, want an import hint", resp.Diagnostics)
}
}
@@ -0,0 +1,225 @@
package seaweedfs
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamAccessKeyResource{}
_ resource.ResourceWithConfigure = &iamAccessKeyResource{}
_ resource.ResourceWithImportState = &iamAccessKeyResource{}
)
func NewIAMAccessKeyResource() resource.Resource {
return &iamAccessKeyResource{}
}
type iamAccessKeyResource struct {
client *iamClient
data *providerData
}
type iamAccessKeyResourceModel struct {
ID types.String `tfsdk:"id"`
UserName types.String `tfsdk:"user_name"`
AccessKeyID types.String `tfsdk:"access_key_id"`
SecretAccessKey types.String `tfsdk:"secret_access_key"`
Status types.String `tfsdk:"status"`
}
func (r *iamAccessKeyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_access_key"
}
func (r *iamAccessKeyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS IAM access key for a user. Import using `user_name,access_key_id`; an imported key has no `secret_access_key`, because SeaweedFS returns the secret only at creation.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"user_name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"access_key_id": schema.StringAttribute{
Computed: true,
},
"secret_access_key": schema.StringAttribute{
Computed: true,
Sensitive: true,
},
"status": schema.StringAttribute{
Computed: true,
},
},
}
}
func (r *iamAccessKeyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamAccessKeyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamAccessKeyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
userName := plan.UserName.ValueString()
var key iamAccessKey
err := r.data.withUserLock(userName, func() error {
var keys []iamAccessKeyMetadata
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
var innerErr error
keys, innerErr = r.client.ListAccessKeys(ctx, userName)
return innerErr
}); err != nil {
return err
}
known := map[string]bool{}
for _, existing := range keys {
known[existing.AccessKeyID] = true
}
var createErr error
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
key, createErr = r.client.CreateAccessKey(ctx, userName)
if isNoSuchEntityError(createErr) {
return createErr
}
return nil
}); err != nil {
return err
}
if createErr != nil {
return r.uncertainCreateError(ctx, userName, known, createErr)
}
return nil
})
if err != nil {
resp.Diagnostics.AddError("Failed to create IAM access key", err.Error())
return
}
state := iamAccessKeyResourceModel{
ID: types.StringValue(key.AccessKeyID),
UserName: types.StringValue(plan.UserName.ValueString()),
AccessKeyID: types.StringValue(key.AccessKeyID),
SecretAccessKey: types.StringValue(key.SecretAccessKey),
Status: types.StringValue(key.Status),
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamAccessKeyResource) uncertainCreateError(ctx context.Context, userName string, known map[string]bool, createErr error) error {
checkCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
keys, err := r.client.ListAccessKeys(checkCtx, userName)
if err != nil {
return fmt.Errorf("CreateAccessKey failed: %w; listing the access keys of user %s also failed (%v), so check whether a new key was created and delete or import it before retrying", createErr, userName, err)
}
var created []string
for _, existing := range keys {
if !known[existing.AccessKeyID] {
created = append(created, existing.AccessKeyID)
}
}
if len(created) > 0 {
return fmt.Errorf("CreateAccessKey failed: %w; the failed attempt left access key %s on user %s, delete or import it before retrying", createErr, strings.Join(created, ", "), userName)
}
return fmt.Errorf("CreateAccessKey failed: %w; no new access key is visible on user %s, but the request may still commit, so check the user's access keys before retrying", createErr, userName)
}
func (r *iamAccessKeyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamAccessKeyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var keys []iamAccessKeyMetadata
err := retryIAMEventuallyConsistent(ctx, 10, func() error {
var innerErr error
keys, innerErr = r.client.ListAccessKeys(ctx, state.UserName.ValueString())
return innerErr
})
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM access key", err.Error())
return
}
found := false
status := ""
for _, key := range keys {
if key.AccessKeyID == state.AccessKeyID.ValueString() {
found = true
status = key.Status
break
}
}
if !found {
resp.State.RemoveResource(ctx)
return
}
state.ID = types.StringValue(state.AccessKeyID.ValueString())
state.Status = types.StringValue(status)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamAccessKeyResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
resp.Diagnostics.AddError("Update not supported", "seaweedfs_iam_access_key supports replacement only.")
}
func (r *iamAccessKeyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamAccessKeyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.data.withUserLock(state.UserName.ValueString(), func() error {
return retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.DeleteAccessKey(ctx, state.UserName.ValueString(), state.AccessKeyID.ValueString())
})
}); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM access key", err.Error())
}
}
func (r *iamAccessKeyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
parts := strings.Split(req.ID, ",")
if len(parts) != 2 {
resp.Diagnostics.AddError("Invalid import ID", "Expected import id in format `user_name,access_key_id`.")
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), parts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_name"), parts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("access_key_id"), parts[1])...)
}
@@ -0,0 +1,126 @@
package seaweedfs
import (
"context"
"net/http"
"strings"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)
func TestIAMAccessKeyCreateDoesNotRetryOverACommittedKey(t *testing.T) {
ctx := context.Background()
keys := []string{"EXISTING"}
creates := 0
client := testIAMClient(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
switch r.Form.Get("Action") {
case "ListAccessKeys":
var members strings.Builder
for _, id := range keys {
members.WriteString(`<member><UserName>alice</UserName><AccessKeyId>` + id + `</AccessKeyId><Status>Active</Status></member>`)
}
_, _ = w.Write([]byte(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata>` + members.String() + `</AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`))
case "CreateAccessKey":
creates++
keys = append(keys, "ORPHAN")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>ServiceFailure</Code><Message>deadline exceeded</Message></Error></ErrorResponse>`))
default:
t.Errorf("unexpected action %s", r.Form.Get("Action"))
}
})
r := &iamAccessKeyResource{client: client, data: &providerData{}}
plan, state := testResourcePlan(ctx, r, map[string]tftypes.Value{
"user_name": tftypes.NewValue(tftypes.String, "alice"),
})
resp := resource.CreateResponse{State: state}
r.Create(ctx, resource.CreateRequest{Plan: plan}, &resp)
if !resp.Diagnostics.HasError() {
t.Fatal("expected create to fail")
}
if creates != 1 {
t.Fatalf("CreateAccessKey called %d times, want 1", creates)
}
if detail := resp.Diagnostics.Errors()[0].Detail(); !strings.Contains(detail, "ORPHAN") {
t.Fatalf("diagnostic %q does not name the orphaned key", detail)
}
}
func TestIAMAccessKeyCreateReportsKeyCommittedByCanceledRequest(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
keys := []string{"EXISTING"}
creates := 0
client := testIAMClient(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
switch r.Form.Get("Action") {
case "ListAccessKeys":
var members strings.Builder
for _, id := range keys {
members.WriteString(`<member><UserName>alice</UserName><AccessKeyId>` + id + `</AccessKeyId><Status>Active</Status></member>`)
}
_, _ = w.Write([]byte(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata>` + members.String() + `</AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`))
case "CreateAccessKey":
creates++
keys = append(keys, "ORPHAN")
cancel()
<-r.Context().Done()
default:
t.Errorf("unexpected action %s", r.Form.Get("Action"))
}
})
r := &iamAccessKeyResource{client: client, data: &providerData{}}
plan, state := testResourcePlan(ctx, r, map[string]tftypes.Value{
"user_name": tftypes.NewValue(tftypes.String, "alice"),
})
resp := resource.CreateResponse{State: state}
r.Create(ctx, resource.CreateRequest{Plan: plan}, &resp)
if !resp.Diagnostics.HasError() {
t.Fatal("expected create to fail")
}
if creates != 1 {
t.Fatalf("CreateAccessKey called %d times, want 1", creates)
}
if detail := resp.Diagnostics.Errors()[0].Detail(); !strings.Contains(detail, "ORPHAN") {
t.Fatalf("diagnostic %q does not name the orphaned key", detail)
}
}
func TestIAMAccessKeyCreateRetriesUntilUserIsVisible(t *testing.T) {
ctx := context.Background()
creates := 0
client := testIAMClient(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
switch r.Form.Get("Action") {
case "ListAccessKeys":
_, _ = w.Write([]byte(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata></AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`))
case "CreateAccessKey":
creates++
if creates == 1 {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>NoSuchEntity</Code><Message>no user</Message></Error></ErrorResponse>`))
return
}
_, _ = w.Write([]byte(`<CreateAccessKeyResponse><CreateAccessKeyResult><AccessKey><UserName>alice</UserName><AccessKeyId>NEW</AccessKeyId><SecretAccessKey>secret</SecretAccessKey><Status>Active</Status></AccessKey></CreateAccessKeyResult></CreateAccessKeyResponse>`))
default:
t.Errorf("unexpected action %s", r.Form.Get("Action"))
}
})
r := &iamAccessKeyResource{client: client, data: &providerData{}}
plan, state := testResourcePlan(ctx, r, map[string]tftypes.Value{
"user_name": tftypes.NewValue(tftypes.String, "alice"),
})
resp := resource.CreateResponse{State: state}
r.Create(ctx, resource.CreateRequest{Plan: plan}, &resp)
if resp.Diagnostics.HasError() {
t.Fatalf("create failed: %v", resp.Diagnostics)
}
var got iamAccessKeyResourceModel
resp.Diagnostics.Append(resp.State.Get(ctx, &got)...)
if creates != 2 || got.AccessKeyID.ValueString() != "NEW" {
t.Fatalf("creates = %d, access key = %q; want 2 and NEW", creates, got.AccessKeyID.ValueString())
}
}
@@ -0,0 +1,371 @@
package seaweedfs
import (
"context"
"fmt"
"sort"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamGroupResource{}
_ resource.ResourceWithConfigure = &iamGroupResource{}
_ resource.ResourceWithImportState = &iamGroupResource{}
)
type iamGroupResource struct {
client *iamClient
data *providerData
}
type iamGroupResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
}
func NewIAMGroupResource() resource.Resource {
return &iamGroupResource{}
}
func (r *iamGroupResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_group"
}
func (r *iamGroupResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS IAM group. Group membership and attached policies are managed by separate resources. Import using the group name.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"name": schema.StringAttribute{Required: true, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
},
}
}
func (r *iamGroupResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamGroupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamGroupResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", plan.Name.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.CreateGroup(ctx, plan.Name.ValueString()); err != nil {
resp.Diagnostics.AddError("Failed to create IAM group", err.Error())
return
}
plan.ID = types.StringValue(plan.Name.ValueString())
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamGroupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamGroupResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", state.Name.ValueString())
lock.Lock()
defer lock.Unlock()
group, err := r.client.GetGroup(ctx, state.Name.ValueString())
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM group", err.Error())
return
}
state.ID = types.StringValue(group.Name)
state.Name = types.StringValue(group.Name)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamGroupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamGroupResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.AddError("Unsupported IAM group update", "Group names are immutable; Terraform should replace the group.")
}
func (r *iamGroupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamGroupResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", state.Name.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.DeleteGroup(ctx, state.Name.ValueString()); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM group", err.Error())
}
}
func (r *iamGroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
name, err := parseIAMImportID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), name)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
}
var (
_ resource.Resource = &iamGroupMembershipResource{}
_ resource.ResourceWithConfigure = &iamGroupMembershipResource{}
_ resource.ResourceWithImportState = &iamGroupMembershipResource{}
)
type iamGroupMembershipResource struct {
client *iamClient
data *providerData
}
type iamGroupMembershipResourceModel struct {
ID types.String `tfsdk:"id"`
GroupName types.String `tfsdk:"group_name"`
Users types.Set `tfsdk:"users"`
}
func NewIAMGroupMembershipResource() resource.Resource {
return &iamGroupMembershipResource{}
}
func (r *iamGroupMembershipResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_group_membership"
}
func (r *iamGroupMembershipResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages the complete user membership set for a SeaweedFS IAM group. Import using the group name.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"group_name": schema.StringAttribute{Required: true, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
"users": schema.SetAttribute{
Required: true,
ElementType: types.StringType,
Description: "IAM user names that belong to the group.",
},
},
}
}
func (r *iamGroupMembershipResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamGroupMembershipResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamGroupMembershipResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
users, diags := stringSetElements(ctx, plan.Users)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.reconcile(ctx, plan.GroupName.ValueString(), users); err != nil {
resp.Diagnostics.AddError("Failed to create IAM group membership", err.Error())
return
}
plan.ID = types.StringValue(plan.GroupName.ValueString())
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamGroupMembershipResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamGroupMembershipResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
group, err := r.client.GetGroup(ctx, state.GroupName.ValueString())
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM group membership", err.Error())
return
}
users := make([]string, 0, len(group.Users))
for _, user := range group.Users {
users = append(users, user.Name)
}
sort.Strings(users)
state.ID = types.StringValue(group.Name)
state.GroupName = types.StringValue(group.Name)
var diags diag.Diagnostics
state.Users, diags = types.SetValueFrom(ctx, types.StringType, users)
resp.Diagnostics.Append(diags...)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamGroupMembershipResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamGroupMembershipResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
users, diags := stringSetElements(ctx, plan.Users)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.reconcile(ctx, plan.GroupName.ValueString(), users); err != nil {
resp.Diagnostics.AddError("Failed to update IAM group membership", err.Error())
return
}
group, err := r.client.GetGroup(ctx, plan.GroupName.ValueString())
if err != nil {
resp.Diagnostics.AddError("Failed to read updated IAM group membership", err.Error())
return
}
plan.ID = types.StringValue(group.Name)
plan.Users, diags = groupUsersToSet(ctx, group.Users)
resp.Diagnostics.Append(diags...)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamGroupMembershipResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamGroupMembershipResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
group, err := r.client.GetGroup(ctx, state.GroupName.ValueString())
if err != nil {
if isNoSuchEntityError(err) {
return
}
resp.Diagnostics.AddError("Failed to read IAM group before removing membership", err.Error())
return
}
for _, user := range group.Users {
if err := r.client.RemoveUserFromGroup(ctx, state.GroupName.ValueString(), user.Name); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to remove IAM group member", err.Error())
return
}
}
}
func (r *iamGroupMembershipResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
groupName, err := parseIAMImportID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), groupName)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("group_name"), groupName)...)
}
func (r *iamGroupMembershipResource) reconcile(ctx context.Context, groupName string, desired []string) error {
group, err := r.client.GetGroup(ctx, groupName)
if err != nil {
return err
}
desiredSet := make(map[string]struct{}, len(desired))
for _, user := range desired {
desiredSet[user] = struct{}{}
}
currentSet := make(map[string]struct{}, len(group.Users))
for _, user := range group.Users {
currentSet[user.Name] = struct{}{}
}
sort.Strings(desired)
for _, user := range desired {
if _, ok := currentSet[user]; ok {
continue
}
if err := r.client.AddUserToGroup(ctx, groupName, user); err != nil {
return err
}
}
for _, user := range group.Users {
if _, ok := desiredSet[user.Name]; ok {
continue
}
if err := r.client.RemoveUserFromGroup(ctx, groupName, user.Name); err != nil && !isNoSuchEntityError(err) {
return err
}
}
return nil
}
func stringSetElements(ctx context.Context, value types.Set) ([]string, diag.Diagnostics) {
if value.IsNull() || value.IsUnknown() {
return []string{}, nil
}
var elements []string
diags := value.ElementsAs(ctx, &elements, false)
return elements, diags
}
func groupUsersToSet(ctx context.Context, users []iamGroupUser) (types.Set, diag.Diagnostics) {
elements := make([]string, 0, len(users))
for _, user := range users {
elements = append(elements, user.Name)
}
sort.Strings(elements)
return types.SetValueFrom(ctx, types.StringType, elements)
}
@@ -0,0 +1,191 @@
package seaweedfs
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamGroupPolicyResource{}
_ resource.ResourceWithConfigure = &iamGroupPolicyResource{}
_ resource.ResourceWithImportState = &iamGroupPolicyResource{}
)
type iamGroupPolicyResource struct {
client *iamClient
data *providerData
}
type iamGroupPolicyResourceModel struct {
ID types.String `tfsdk:"id"`
GroupName types.String `tfsdk:"group_name"`
Name types.String `tfsdk:"name"`
Policy types.String `tfsdk:"policy"`
}
func NewIAMGroupPolicyResource() resource.Resource {
return &iamGroupPolicyResource{}
}
func (r *iamGroupPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_group_policy"
}
func (r *iamGroupPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages an inline IAM group policy in SeaweedFS. Import using `group_name,policy_name`.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"group_name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"policy": schema.StringAttribute{
Required: true,
Description: "JSON policy document.",
},
},
}
}
func (r *iamGroupPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamGroupPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamGroupPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
policy, err := normalizeJSONString(plan.Policy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid IAM group policy", err.Error())
return
}
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.PutGroupPolicy(ctx, plan.GroupName.ValueString(), plan.Name.ValueString(), policy)
}); err != nil {
resp.Diagnostics.AddError("Failed to create IAM group policy", err.Error())
return
}
plan.ID = types.StringValue(plan.GroupName.ValueString() + ":" + plan.Name.ValueString())
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamGroupPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamGroupPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
var remotePolicy string
err := retryIAMRead(ctx, 6, func() error {
var innerErr error
remotePolicy, innerErr = r.client.GetGroupPolicy(ctx, state.GroupName.ValueString(), state.Name.ValueString())
return innerErr
})
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM group policy", err.Error())
return
}
state.ID = types.StringValue(state.GroupName.ValueString() + ":" + state.Name.ValueString())
if !policiesSemanticallyEqual(state.Policy.ValueString(), remotePolicy) {
state.Policy = types.StringValue(remotePolicy)
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamGroupPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamGroupPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
policy, err := normalizeJSONString(plan.Policy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid IAM group policy", err.Error())
return
}
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.PutGroupPolicy(ctx, plan.GroupName.ValueString(), plan.Name.ValueString(), policy)
}); err != nil {
resp.Diagnostics.AddError("Failed to update IAM group policy", err.Error())
return
}
plan.ID = types.StringValue(plan.GroupName.ValueString() + ":" + plan.Name.ValueString())
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamGroupPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamGroupPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
lock.Lock()
defer lock.Unlock()
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.DeleteGroupPolicy(ctx, state.GroupName.ValueString(), state.Name.ValueString())
}); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM group policy", err.Error())
}
}
func (r *iamGroupPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
parts := strings.SplitN(req.ID, ",", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
resp.Diagnostics.AddError("Invalid import ID", "Expected import ID in the format `group_name,policy_name`.")
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), parts[0]+":"+parts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("group_name"), parts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), parts[1])...)
}
@@ -0,0 +1,37 @@
package seaweedfs
import (
"context"
"net/http"
"testing"
)
func TestIAMGroupMembershipKeepsOldMemberWhenAddFails(t *testing.T) {
members := map[string]bool{"alice": true}
client := testIAMClient(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
switch r.Form.Get("Action") {
case "GetGroup":
body := `<GetGroupResponse><GetGroupResult><Group><GroupName>g</GroupName></Group><Users>`
for name := range members {
body += `<member><UserName>` + name + `</UserName></member>`
}
_, _ = w.Write([]byte(body + `</Users></GetGroupResult></GetGroupResponse>`))
case "AddUserToGroup":
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>NoSuchEntity</Code><Message>no user</Message></Error></ErrorResponse>`))
case "RemoveUserFromGroup":
delete(members, r.Form.Get("UserName"))
_, _ = w.Write([]byte(`<RemoveUserFromGroupResponse></RemoveUserFromGroupResponse>`))
default:
t.Errorf("unexpected action %s", r.Form.Get("Action"))
}
})
r := &iamGroupMembershipResource{client: client}
if err := r.reconcile(context.Background(), "g", []string{"bob"}); err == nil {
t.Fatal("expected the failed add to be reported")
}
if !members["alice"] {
t.Fatal("existing member was removed before the replacement was added")
}
}
@@ -0,0 +1,326 @@
package seaweedfs
import (
"context"
"fmt"
"sort"
"strings"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamOIDCProviderResource{}
_ resource.ResourceWithConfigure = &iamOIDCProviderResource{}
_ resource.ResourceWithImportState = &iamOIDCProviderResource{}
)
type iamOIDCProviderResource struct {
client *iamClient
data *providerData
}
type iamOIDCProviderResourceModel struct {
ID types.String `tfsdk:"id"`
ARN types.String `tfsdk:"arn"`
URL types.String `tfsdk:"url"`
ClientIDs types.Set `tfsdk:"client_ids"`
Thumbprints types.Set `tfsdk:"thumbprints"`
}
func NewIAMOIDCProviderResource() resource.Resource {
return &iamOIDCProviderResource{}
}
func (r *iamOIDCProviderResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_oidc_provider"
}
func (r *iamOIDCProviderResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS IAM OpenID Connect provider. Import using the provider ARN.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"arn": schema.StringAttribute{Computed: true},
"url": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Issuer URL for the OIDC provider.",
},
"client_ids": schema.SetAttribute{
Required: true,
ElementType: types.StringType,
Description: "Client IDs allowed to use the provider.",
},
"thumbprints": schema.SetAttribute{
Required: true,
ElementType: types.StringType,
Description: "TLS certificate thumbprints trusted for the provider. At least one is required.",
},
},
}
}
func (r *iamOIDCProviderResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamOIDCProviderResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamOIDCProviderResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
clientIDs, diags := stringSetElements(ctx, plan.ClientIDs)
resp.Diagnostics.Append(diags...)
thumbprints, thumbDiags := stringSetElements(ctx, plan.Thumbprints)
resp.Diagnostics.Append(thumbDiags...)
if resp.Diagnostics.HasError() {
return
}
if err := validateOIDCProviderSettings(plan.URL.ValueString(), clientIDs, thumbprints); err != nil {
resp.Diagnostics.AddError("Invalid OIDC provider settings", err.Error())
return
}
sort.Strings(clientIDs)
sort.Strings(thumbprints)
lock := r.data.getIAMPrincipalLock("oidc", plan.URL.ValueString())
lock.Lock()
defer lock.Unlock()
arn, err := r.client.CreateOIDCProvider(ctx, plan.URL.ValueString(), clientIDs, thumbprints)
if err != nil {
resp.Diagnostics.AddError("Failed to create IAM OIDC provider", err.Error())
return
}
if arn == "" {
resp.Diagnostics.AddError("Invalid OIDC provider response", "SeaweedFS did not return the created provider ARN.")
return
}
plan.ID = types.StringValue(arn)
plan.ARN = types.StringValue(arn)
plan.ClientIDs, diags = types.SetValueFrom(ctx, types.StringType, clientIDs)
resp.Diagnostics.Append(diags...)
plan.Thumbprints, thumbDiags = types.SetValueFrom(ctx, types.StringType, thumbprints)
resp.Diagnostics.Append(thumbDiags...)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamOIDCProviderResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamOIDCProviderResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
arn := state.ARN.ValueString()
if arn == "" {
arn = state.ID.ValueString()
}
lock := r.data.getIAMPrincipalLock("oidc", arn)
lock.Lock()
defer lock.Unlock()
provider, err := r.client.GetOIDCProvider(ctx, arn)
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM OIDC provider", err.Error())
return
}
state.ID = types.StringValue(arn)
state.ARN = types.StringValue(arn)
state.URL = types.StringValue(provider.URL)
clientIDs, diags := types.SetValueFrom(ctx, types.StringType, nonNilStrings(provider.ClientIDs))
resp.Diagnostics.Append(diags...)
state.ClientIDs = clientIDs
thumbprints, thumbDiags := types.SetValueFrom(ctx, types.StringType, nonNilStrings(provider.Thumbprints))
resp.Diagnostics.Append(thumbDiags...)
state.Thumbprints = thumbprints
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamOIDCProviderResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamOIDCProviderResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
desiredClientIDs, diags := stringSetElements(ctx, plan.ClientIDs)
resp.Diagnostics.Append(diags...)
desiredThumbprints, thumbDiags := stringSetElements(ctx, plan.Thumbprints)
resp.Diagnostics.Append(thumbDiags...)
if resp.Diagnostics.HasError() {
return
}
if err := validateOIDCProviderSettings(plan.URL.ValueString(), desiredClientIDs, desiredThumbprints); err != nil {
resp.Diagnostics.AddError("Invalid OIDC provider settings", err.Error())
return
}
sort.Strings(desiredClientIDs)
sort.Strings(desiredThumbprints)
arn := plan.ARN.ValueString()
if plan.ARN.IsUnknown() || arn == "" {
var state iamOIDCProviderResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
arn = state.ARN.ValueString()
if arn == "" {
arn = state.ID.ValueString()
}
}
if arn == "" {
resp.Diagnostics.AddError("Missing OIDC provider ARN", "Terraform state and plan do not contain the provider ARN.")
return
}
lock := r.data.getIAMPrincipalLock("oidc", arn)
lock.Lock()
defer lock.Unlock()
current, err := r.client.GetOIDCProvider(ctx, arn)
if err != nil {
resp.Diagnostics.AddError("Failed to read IAM OIDC provider before update", err.Error())
return
}
currentClientIDs := make(map[string]struct{}, len(current.ClientIDs))
desiredClientSet := make(map[string]struct{}, len(desiredClientIDs))
for _, id := range current.ClientIDs {
currentClientIDs[id] = struct{}{}
}
for _, id := range desiredClientIDs {
desiredClientSet[id] = struct{}{}
if _, exists := currentClientIDs[id]; !exists {
if err := r.client.AddOIDCClientID(ctx, arn, id); err != nil {
resp.Diagnostics.AddError("Failed to add OIDC client ID", err.Error())
return
}
}
}
for _, id := range current.ClientIDs {
if _, exists := desiredClientSet[id]; !exists {
if err := r.client.RemoveOIDCClientID(ctx, arn, id); err != nil {
resp.Diagnostics.AddError("Failed to remove OIDC client ID", err.Error())
return
}
}
}
if !sameStringSet(current.Thumbprints, desiredThumbprints) {
if err := r.client.UpdateOIDCThumbprints(ctx, arn, desiredThumbprints); err != nil {
resp.Diagnostics.AddError("Failed to update OIDC thumbprints", err.Error())
return
}
}
provider, err := r.client.GetOIDCProvider(ctx, arn)
if err != nil {
resp.Diagnostics.AddError("Failed to read updated IAM OIDC provider", err.Error())
return
}
plan.ID = types.StringValue(arn)
plan.ARN = types.StringValue(arn)
plan.URL = types.StringValue(provider.URL)
clientIDs, diags := types.SetValueFrom(ctx, types.StringType, nonNilStrings(provider.ClientIDs))
resp.Diagnostics.Append(diags...)
plan.ClientIDs = clientIDs
thumbprints, thumbDiags := types.SetValueFrom(ctx, types.StringType, nonNilStrings(provider.Thumbprints))
resp.Diagnostics.Append(thumbDiags...)
plan.Thumbprints = thumbprints
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamOIDCProviderResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamOIDCProviderResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
arn := state.ARN.ValueString()
if arn == "" {
arn = state.ID.ValueString()
}
lock := r.data.getIAMPrincipalLock("oidc", arn)
lock.Lock()
defer lock.Unlock()
if err := r.client.DeleteOIDCProvider(ctx, arn); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM OIDC provider", err.Error())
}
}
func (r *iamOIDCProviderResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
arn, err := parseIAMImportID(req.ID)
if err != nil || !strings.HasPrefix(arn, "arn:") {
if err == nil {
err = fmt.Errorf("expected an OIDC provider ARN")
}
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("arn"), arn)...)
}
func nonNilStrings(values []string) []string {
if values == nil {
return []string{}
}
return values
}
func validateOIDCProviderSettings(url string, clientIDs, thumbprints []string) error {
if strings.TrimSpace(url) != url {
return fmt.Errorf("url must not have leading or trailing whitespace")
}
if len(thumbprints) == 0 {
return fmt.Errorf("at least one TLS certificate thumbprint must be configured")
}
for _, list := range []struct {
name string
values []string
}{{"client_ids", clientIDs}, {"thumbprints", thumbprints}} {
for _, value := range list.values {
if value == "" || strings.TrimSpace(value) != value {
return fmt.Errorf("%s entries must be non-empty and have no leading or trailing whitespace, got %q", list.name, value)
}
}
}
return nil
}
func sameStringSet(left, right []string) bool {
if len(left) != len(right) {
return false
}
leftSorted := append([]string(nil), left...)
rightSorted := append([]string(nil), right...)
sort.Strings(leftSorted)
sort.Strings(rightSorted)
for i := range leftSorted {
if leftSorted[i] != rightSorted[i] {
return false
}
}
return true
}
@@ -0,0 +1,218 @@
package seaweedfs
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamPolicyResource{}
_ resource.ResourceWithConfigure = &iamPolicyResource{}
_ resource.ResourceWithImportState = &iamPolicyResource{}
)
type iamPolicyResource struct {
client *iamClient
data *providerData
}
type iamPolicyResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
ARN types.String `tfsdk:"arn"`
Policy types.String `tfsdk:"policy"`
}
func NewIAMPolicyResource() resource.Resource {
return &iamPolicyResource{}
}
func (r *iamPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_policy"
}
func (r *iamPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS IAM managed policy. SeaweedFS stores one active policy version; updates replace that document in place. Import using the policy ARN or name.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Managed policy name.",
},
"arn": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "Managed policy ARN.",
},
"policy": schema.StringAttribute{
Required: true,
Description: "JSON policy document.",
},
},
}
}
func (r *iamPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
policy, err := normalizeJSONString(plan.Policy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid IAM policy", err.Error())
return
}
managedPolicy, err := r.client.CreateManagedPolicy(ctx, plan.Name.ValueString(), policy)
if err != nil {
resp.Diagnostics.AddError("Failed to create IAM policy", err.Error())
return
}
arn := managedPolicy.ARN
if arn == "" {
arn = iamPolicyARN(plan.Name.ValueString())
}
plan.ID = types.StringValue(arn)
plan.ARN = types.StringValue(arn)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
arn := state.ARN.ValueString()
if arn == "" {
arn = state.ID.ValueString()
}
if !strings.HasPrefix(arn, "arn:") {
arn = iamPolicyARN(state.Name.ValueString())
}
policy, err := r.client.GetManagedPolicy(ctx, arn)
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM policy", err.Error())
return
}
document, err := r.client.GetManagedPolicyDocument(ctx, arn, policy.DefaultVersion)
if err != nil {
resp.Diagnostics.AddError("Failed to read IAM policy document", err.Error())
return
}
normalized, err := normalizeJSONString(document)
if err != nil {
resp.Diagnostics.AddError("Invalid IAM policy returned by SeaweedFS", err.Error())
return
}
state.ID = types.StringValue(policy.ARN)
state.ARN = types.StringValue(policy.ARN)
state.Name = types.StringValue(policy.Name)
if !policiesSemanticallyEqual(state.Policy.ValueString(), normalized) {
state.Policy = types.StringValue(normalized)
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
var state iamPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
policy, err := normalizeJSONString(plan.Policy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid IAM policy", err.Error())
return
}
arn := plan.ARN.ValueString()
if plan.ARN.IsUnknown() || arn == "" {
arn = state.ARN.ValueString()
}
if arn == "" {
arn = iamPolicyARN(plan.Name.ValueString())
}
if err := r.client.UpdateManagedPolicy(ctx, arn, policy); err != nil {
resp.Diagnostics.AddError("Failed to update IAM policy", err.Error())
return
}
plan.ID = types.StringValue(arn)
plan.ARN = types.StringValue(arn)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
arn := state.ARN.ValueString()
if arn == "" {
arn = iamPolicyARN(state.Name.ValueString())
}
if err := r.client.DeleteManagedPolicy(ctx, arn); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM policy", err.Error())
}
}
func (r *iamPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
id := req.ID
name := id
arn := id
if strings.HasPrefix(id, "arn:") {
var err error
name, err = iamPolicyNameFromARN(id)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
} else {
var err error
name, err = parseIAMImportID(id)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
arn = iamPolicyARN(name)
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("arn"), arn)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
}
@@ -0,0 +1,226 @@
package seaweedfs
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type iamPolicyAttachmentOperations struct {
suffix string
principalType string
principalAttr string
}
type iamPolicyAttachmentResource struct {
client *iamClient
data *providerData
ops iamPolicyAttachmentOperations
}
type iamPolicyAttachmentResourceModel struct {
ID types.String
PrincipalName types.String
PolicyARN types.String
}
type iamPolicyAttachmentTerraformData interface {
GetAttribute(context.Context, path.Path, interface{}) diag.Diagnostics
}
var (
_ resource.Resource = &iamPolicyAttachmentResource{}
_ resource.ResourceWithConfigure = &iamPolicyAttachmentResource{}
_ resource.ResourceWithImportState = &iamPolicyAttachmentResource{}
)
func NewIAMUserPolicyAttachmentResource() resource.Resource {
return newIAMPolicyAttachmentResource(iamPolicyAttachmentOperations{
suffix: "iam_user_policy_attachment", principalType: "user", principalAttr: "user_name",
})
}
func NewIAMGroupPolicyAttachmentResource() resource.Resource {
return newIAMPolicyAttachmentResource(iamPolicyAttachmentOperations{
suffix: "iam_group_policy_attachment", principalType: "group", principalAttr: "group_name",
})
}
func NewIAMRolePolicyAttachmentResource() resource.Resource {
return newIAMPolicyAttachmentResource(iamPolicyAttachmentOperations{
suffix: "iam_role_policy_attachment", principalType: "role", principalAttr: "role_name",
})
}
func newIAMPolicyAttachmentResource(ops iamPolicyAttachmentOperations) resource.Resource {
return &iamPolicyAttachmentResource{ops: ops}
}
func (r *iamPolicyAttachmentResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_" + r.ops.suffix
}
func (r *iamPolicyAttachmentResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: fmt.Sprintf("Manages attachment of an existing managed IAM policy to a SeaweedFS IAM %s. Import using `%s,policy_arn`.", r.ops.principalType, r.ops.principalAttr),
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
r.ops.principalAttr: schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: fmt.Sprintf("IAM %s name.", r.ops.principalType),
},
"policy_arn": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "ARN of the managed IAM policy.",
},
},
}
}
func (r *iamPolicyAttachmentResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamPolicyAttachmentResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
plan, diags := r.modelFromData(ctx, req.Plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
principal := plan.PrincipalName.ValueString()
lock := r.principalLock(principal)
lock.Lock()
defer lock.Unlock()
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.AttachManagedPolicy(ctx, r.ops.principalType, principal, plan.PolicyARN.ValueString(), true)
}); err != nil {
resp.Diagnostics.AddError("Failed to attach IAM policy", err.Error())
return
}
plan.ID = types.StringValue(principal + "," + plan.PolicyARN.ValueString())
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
}
func (r *iamPolicyAttachmentResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
state, diags := r.modelFromData(ctx, req.State)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
principal := state.PrincipalName.ValueString()
lock := r.principalLock(principal)
lock.Lock()
defer lock.Unlock()
var attachedPolicies []iamAttachedPolicy
err := retryIAMRead(ctx, 6, func() error {
var innerErr error
attachedPolicies, innerErr = r.client.ListAttachedManagedPolicies(ctx, r.ops.principalType, principal)
return innerErr
})
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM policy attachment", err.Error())
return
}
found := false
for _, attached := range attachedPolicies {
if attached.ARN == state.PolicyARN.ValueString() {
found = true
break
}
}
if !found {
resp.State.RemoveResource(ctx)
return
}
state.ID = types.StringValue(principal + "," + state.PolicyARN.ValueString())
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, state)...)
}
func (r *iamPolicyAttachmentResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
resp.Diagnostics.AddError("Unsupported IAM policy attachment update", "Changing the IAM principal or policy requires replacing this attachment.")
}
func (r *iamPolicyAttachmentResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
state, diags := r.modelFromData(ctx, req.State)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
principal := state.PrincipalName.ValueString()
lock := r.principalLock(principal)
lock.Lock()
defer lock.Unlock()
if err := r.client.AttachManagedPolicy(ctx, r.ops.principalType, principal, state.PolicyARN.ValueString(), false); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to detach IAM policy", err.Error())
}
}
func (r *iamPolicyAttachmentResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
parts := strings.SplitN(req.ID, ",", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" || strings.TrimSpace(parts[0]) != parts[0] || strings.TrimSpace(parts[1]) != parts[1] {
resp.Diagnostics.AddError("Invalid import ID", "Expected import ID in the format `principal_name,policy_arn`.")
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), types.StringValue(req.ID))...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root(r.ops.principalAttr), parts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("policy_arn"), parts[1])...)
}
func (r *iamPolicyAttachmentResource) modelFromData(ctx context.Context, data iamPolicyAttachmentTerraformData) (iamPolicyAttachmentResourceModel, diag.Diagnostics) {
var model iamPolicyAttachmentResourceModel
var diags diag.Diagnostics
diags.Append(data.GetAttribute(ctx, path.Root("id"), &model.ID)...)
diags.Append(data.GetAttribute(ctx, path.Root(r.ops.principalAttr), &model.PrincipalName)...)
diags.Append(data.GetAttribute(ctx, path.Root("policy_arn"), &model.PolicyARN)...)
return model, diags
}
func (r *iamPolicyAttachmentResource) writeState(ctx context.Context, state *tfsdk.State, model iamPolicyAttachmentResourceModel) diag.Diagnostics {
var diags diag.Diagnostics
diags.Append(state.SetAttribute(ctx, path.Root("id"), model.ID)...)
diags.Append(state.SetAttribute(ctx, path.Root(r.ops.principalAttr), model.PrincipalName)...)
diags.Append(state.SetAttribute(ctx, path.Root("policy_arn"), model.PolicyARN)...)
return diags
}
func (r *iamPolicyAttachmentResource) principalLock(name string) interface {
Lock()
Unlock()
} {
if r.ops.principalType == "user" {
return r.data.getUserLock(name)
}
return r.data.getIAMPrincipalLock(r.ops.principalType, name)
}
@@ -0,0 +1,225 @@
package seaweedfs
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamRoleResource{}
_ resource.ResourceWithConfigure = &iamRoleResource{}
_ resource.ResourceWithImportState = &iamRoleResource{}
)
type iamRoleResource struct {
client *iamClient
data *providerData
}
type iamRoleResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
AssumeRolePolicy types.String `tfsdk:"assume_role_policy"`
Description types.String `tfsdk:"description"`
MaxSessionDuration types.Int64 `tfsdk:"max_session_duration"`
}
func NewIAMRoleResource() resource.Resource {
return &iamRoleResource{}
}
func (r *iamRoleResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_role"
}
func (r *iamRoleResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS IAM role. SeaweedFS roles do not support paths or mutable descriptions/session duration; changing those attributes replaces the role. Import using the role name.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "IAM role name.",
},
"assume_role_policy": schema.StringAttribute{
Required: true,
Description: "JSON trust policy document.",
},
"description": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
stringplanmodifier.RequiresReplace(),
},
Description: "Role description.",
},
"max_session_duration": schema.Int64Attribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
int64planmodifier.RequiresReplace(),
},
Description: "Maximum role session duration in seconds.",
},
},
}
}
func (r *iamRoleResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamRoleResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamRoleResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
normalized, err := normalizeJSONString(plan.AssumeRolePolicy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid role trust policy", err.Error())
return
}
maxSession := int64(0)
if !plan.MaxSessionDuration.IsNull() && !plan.MaxSessionDuration.IsUnknown() {
maxSession = plan.MaxSessionDuration.ValueInt64()
}
lock := r.data.getIAMPrincipalLock("role", plan.Name.ValueString())
lock.Lock()
defer lock.Unlock()
role, err := r.client.CreateRole(ctx, plan.Name.ValueString(), normalized, plan.Description.ValueString(), maxSession)
if err != nil {
resp.Diagnostics.AddError("Failed to create IAM role", err.Error())
return
}
if err := r.setState(&plan, role, &resp.Diagnostics); err != nil {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamRoleResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamRoleResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("role", state.Name.ValueString())
lock.Lock()
defer lock.Unlock()
role, err := r.client.GetRole(ctx, state.Name.ValueString())
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM role", err.Error())
return
}
if err := r.setState(&state, role, &resp.Diagnostics); err != nil {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamRoleResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamRoleResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
normalized, err := normalizeJSONString(plan.AssumeRolePolicy.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid role trust policy", err.Error())
return
}
lock := r.data.getIAMPrincipalLock("role", plan.Name.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.UpdateAssumeRolePolicy(ctx, plan.Name.ValueString(), normalized); err != nil {
resp.Diagnostics.AddError("Failed to update IAM role trust policy", err.Error())
return
}
role, err := r.client.GetRole(ctx, plan.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError("Failed to read updated IAM role", err.Error())
return
}
if err := r.setState(&plan, role, &resp.Diagnostics); err != nil {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamRoleResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamRoleResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getIAMPrincipalLock("role", state.Name.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.DeleteRole(ctx, state.Name.ValueString()); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM role", err.Error())
}
}
func (r *iamRoleResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
name, err := parseIAMImportID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), name)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
}
func (r *iamRoleResource) setState(state *iamRoleResourceModel, role iamRole, diags *diag.Diagnostics) error {
policy, err := normalizeJSONString(role.AssumeRolePolicy)
if err != nil {
diags.AddError("Invalid role trust policy returned by SeaweedFS", err.Error())
return err
}
if !state.AssumeRolePolicy.IsNull() && !state.AssumeRolePolicy.IsUnknown() &&
policiesSemanticallyEqual(state.AssumeRolePolicy.ValueString(), policy) {
policy = state.AssumeRolePolicy.ValueString()
}
state.ID = types.StringValue(role.Name)
state.Name = types.StringValue(role.Name)
state.AssumeRolePolicy = types.StringValue(policy)
state.Description = types.StringValue(role.Description)
state.MaxSessionDuration = types.Int64Value(role.MaxSessionDuration)
return nil
}
@@ -0,0 +1,303 @@
package seaweedfs
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamServiceAccountResource{}
_ resource.ResourceWithConfigure = &iamServiceAccountResource{}
_ resource.ResourceWithImportState = &iamServiceAccountResource{}
)
type iamServiceAccountResource struct {
client *iamClient
data *providerData
}
type iamServiceAccountResourceModel struct {
ID types.String `tfsdk:"id"`
ServiceAccountID types.String `tfsdk:"service_account_id"`
ParentUser types.String `tfsdk:"parent_user"`
Description types.String `tfsdk:"description"`
Expiration types.String `tfsdk:"expiration"`
Status types.String `tfsdk:"status"`
AccessKeyID types.String `tfsdk:"access_key_id"`
SecretAccessKey types.String `tfsdk:"secret_key"`
}
func NewIAMServiceAccountResource() resource.Resource {
return &iamServiceAccountResource{}
}
func (r *iamServiceAccountResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_service_account"
}
func (r *iamServiceAccountResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS IAM service account. The secret key is returned only at creation and is retained in Terraform state; mark state storage as sensitive. Import using the service account ID.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"service_account_id": schema.StringAttribute{Computed: true},
"parent_user": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "IAM user that owns this service account.",
},
"description": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "Service account description. Set to an empty string to clear it.",
},
"expiration": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "Expiration time in RFC3339 format. Set to an empty string to remove expiration.",
},
"status": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "Credential status: Active or Inactive.",
},
"access_key_id": schema.StringAttribute{Computed: true},
"secret_key": schema.StringAttribute{
Computed: true,
Sensitive: true,
},
},
}
}
func (r *iamServiceAccountResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamServiceAccountResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamServiceAccountResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
expiration, err := expirationToUnix(plan.Expiration.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid service account expiration", err.Error())
return
}
lock := r.data.getUserLock(plan.ParentUser.ValueString())
lock.Lock()
defer lock.Unlock()
account, err := r.client.CreateServiceAccount(ctx, plan.ParentUser.ValueString(), plan.Description.ValueString(), expiration)
if err != nil {
resp.Diagnostics.AddError("Failed to create IAM service account", err.Error())
return
}
if account.ID == "" || account.AccessKeyID == "" || account.SecretAccessKey == "" {
cleanupErr := r.client.DeleteServiceAccount(ctx, account.ID)
message := "SeaweedFS did not return the service account ID and credentials."
if cleanupErr != nil && !isNoSuchEntityError(cleanupErr) {
message += " Cleanup also failed: " + cleanupErr.Error()
}
resp.Diagnostics.AddError("Invalid service account response", message)
return
}
if !plan.Status.IsNull() && plan.Status.ValueString() != "" && plan.Status.ValueString() != account.Status {
if err := r.client.UpdateServiceAccount(ctx, account.ID, plan.Status.ValueString(), account.Description, nil); err != nil {
cleanupErr := r.client.DeleteServiceAccount(ctx, account.ID)
message := err.Error()
if cleanupErr != nil && !isNoSuchEntityError(cleanupErr) {
message += "; cleanup failed: " + cleanupErr.Error()
}
resp.Diagnostics.AddError("Failed to set initial service account status", message)
return
}
account.Status = plan.Status.ValueString()
}
r.setServiceAccountState(&plan, account)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamServiceAccountResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamServiceAccountResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
accountID := state.ServiceAccountID.ValueString()
if accountID == "" {
accountID = state.ID.ValueString()
}
lock := r.data.getUserLock(state.ParentUser.ValueString())
lock.Lock()
defer lock.Unlock()
account, err := r.client.GetServiceAccount(ctx, accountID)
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM service account", err.Error())
return
}
secret := state.SecretAccessKey
r.setServiceAccountState(&state, account)
state.SecretAccessKey = secret
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamServiceAccountResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamServiceAccountResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
var state iamServiceAccountResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
accountID := plan.ServiceAccountID.ValueString()
if plan.ServiceAccountID.IsUnknown() || accountID == "" {
accountID = state.ServiceAccountID.ValueString()
}
if accountID == "" {
accountID = state.ID.ValueString()
}
if accountID == "" {
resp.Diagnostics.AddError("Missing service account ID", "Terraform state and plan do not contain the service account ID.")
return
}
plan.ID = types.StringValue(accountID)
plan.ServiceAccountID = types.StringValue(accountID)
if plan.SecretAccessKey.IsUnknown() || plan.SecretAccessKey.IsNull() {
plan.SecretAccessKey = state.SecretAccessKey
}
var expiration *string
if !sameExpirationInstant(plan.Expiration.ValueString(), state.Expiration.ValueString()) {
unix, err := expirationToUnix(plan.Expiration.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid service account expiration", err.Error())
return
}
expiration = &unix
}
if plan.Status.ValueString() != "" && plan.Status.ValueString() != "Active" && plan.Status.ValueString() != "Inactive" {
resp.Diagnostics.AddError("Invalid service account status", "Status must be Active or Inactive.")
return
}
lock := r.data.getUserLock(plan.ParentUser.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.UpdateServiceAccount(ctx, accountID, plan.Status.ValueString(), plan.Description.ValueString(), expiration); err != nil {
resp.Diagnostics.AddError("Failed to update IAM service account", err.Error())
return
}
account, err := r.client.GetServiceAccount(ctx, accountID)
if err != nil {
resp.Diagnostics.AddError("Failed to read updated IAM service account", err.Error())
return
}
secret := plan.SecretAccessKey
r.setServiceAccountState(&plan, account)
plan.SecretAccessKey = secret
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *iamServiceAccountResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamServiceAccountResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
accountID := state.ServiceAccountID.ValueString()
if accountID == "" {
accountID = state.ID.ValueString()
}
lock := r.data.getUserLock(state.ParentUser.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.client.DeleteServiceAccount(ctx, accountID); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM service account", err.Error())
}
}
func (r *iamServiceAccountResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
id := req.ID
if !strings.HasPrefix(id, "sa:") || strings.TrimSpace(id) != id {
resp.Diagnostics.AddError("Invalid import ID", "Expected import ID in the format `sa:parent_user:identifier`.")
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), id)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("service_account_id"), id)...)
}
func (r *iamServiceAccountResource) setServiceAccountState(state *iamServiceAccountResourceModel, account iamServiceAccount) {
state.ID = types.StringValue(account.ID)
state.ServiceAccountID = types.StringValue(account.ID)
state.ParentUser = types.StringValue(account.ParentUser)
state.Description = types.StringValue(account.Description)
if state.Expiration.IsUnknown() || state.Expiration.IsNull() || !sameExpirationInstant(state.Expiration.ValueString(), account.Expiration) {
state.Expiration = types.StringValue(account.Expiration)
}
state.Status = types.StringValue(account.Status)
state.AccessKeyID = types.StringValue(account.AccessKeyID)
if account.SecretAccessKey != "" {
state.SecretAccessKey = types.StringValue(account.SecretAccessKey)
}
}
func sameExpirationInstant(a, b string) bool {
if a == b {
return true
}
ta, errA := time.Parse(time.RFC3339, a)
tb, errB := time.Parse(time.RFC3339, b)
return errA == nil && errB == nil && ta.Unix() == tb.Unix()
}
func expirationToUnix(value string) (string, error) {
if value == "" {
return "", nil
}
expiration, err := time.Parse(time.RFC3339, value)
if err != nil {
return "", fmt.Errorf("expiration must use RFC3339 format: %w", err)
}
return strconv.FormatInt(expiration.Unix(), 10), nil
}
@@ -0,0 +1,78 @@
package seaweedfs
import (
"context"
"net/http"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)
func TestIAMServiceAccountUpdateOmitsUnchangedExpiration(t *testing.T) {
ctx := context.Background()
for _, tc := range []struct {
name string
planExpiration string
wantSent bool
wantValue string
}{
{name: "unchanged", planExpiration: "2020-01-01T00:00:00Z"},
{name: "same instant in another zone", planExpiration: "2020-01-01T01:00:00+01:00"},
{name: "cleared", planExpiration: "", wantSent: true, wantValue: ""},
{name: "changed", planExpiration: "2040-01-01T00:00:00Z", wantSent: true, wantValue: "2208988800"},
} {
t.Run(tc.name, func(t *testing.T) {
sent, sentValue := false, ""
client := testIAMClient(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
switch r.Form.Get("Action") {
case "UpdateServiceAccount":
_, sent = r.PostForm["Expiration"]
sentValue = r.PostForm.Get("Expiration")
_, _ = w.Write([]byte(`<UpdateServiceAccountResponse></UpdateServiceAccountResponse>`))
case "GetServiceAccount":
_, _ = w.Write([]byte(`<GetServiceAccountResponse><GetServiceAccountResult><ServiceAccount><ServiceAccountId>sa:alice:1</ServiceAccountId><ParentUser>alice</ParentUser><Description>new</Description><AccessKeyId>AK</AccessKeyId><Status>Active</Status><Expiration>2020-01-01T00:00:00Z</Expiration></ServiceAccount></GetServiceAccountResult></GetServiceAccountResponse>`))
default:
t.Errorf("unexpected action %s", r.Form.Get("Action"))
}
})
r := &iamServiceAccountResource{client: client, data: &providerData{}}
common := map[string]tftypes.Value{
"id": tftypes.NewValue(tftypes.String, "sa:alice:1"),
"service_account_id": tftypes.NewValue(tftypes.String, "sa:alice:1"),
"parent_user": tftypes.NewValue(tftypes.String, "alice"),
"status": tftypes.NewValue(tftypes.String, "Active"),
"access_key_id": tftypes.NewValue(tftypes.String, "AK"),
"secret_key": tftypes.NewValue(tftypes.String, "secret"),
}
stateValues := map[string]tftypes.Value{
"description": tftypes.NewValue(tftypes.String, "old"),
"expiration": tftypes.NewValue(tftypes.String, "2020-01-01T00:00:00Z"),
}
planValues := map[string]tftypes.Value{
"description": tftypes.NewValue(tftypes.String, "new"),
"expiration": tftypes.NewValue(tftypes.String, tc.planExpiration),
}
for k, v := range common {
stateValues[k] = v
planValues[k] = v
}
plan, _ := testResourcePlan(ctx, r, planValues)
state := testResourceState(ctx, r, stateValues)
resp := resource.UpdateResponse{State: state}
r.Update(ctx, resource.UpdateRequest{Plan: plan, State: state}, &resp)
if resp.Diagnostics.HasError() {
t.Fatalf("update: %v", resp.Diagnostics)
}
if sent != tc.wantSent || sentValue != tc.wantValue {
t.Fatalf("Expiration sent=%v value=%q, want sent=%v value=%q", sent, sentValue, tc.wantSent, tc.wantValue)
}
var got iamServiceAccountResourceModel
resp.Diagnostics.Append(resp.State.Get(ctx, &got)...)
if tc.name == "same instant in another zone" && got.Expiration.ValueString() != tc.planExpiration {
t.Fatalf("state expiration = %q, want the configured %q", got.Expiration.ValueString(), tc.planExpiration)
}
})
}
}
@@ -0,0 +1,244 @@
package seaweedfs
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamUserResource{}
_ resource.ResourceWithConfigure = &iamUserResource{}
_ resource.ResourceWithImportState = &iamUserResource{}
)
func NewIAMUserResource() resource.Resource {
return &iamUserResource{}
}
type iamUserResource struct {
client *iamClient
data *providerData
}
type iamUserResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Path types.String `tfsdk:"path"`
ARN types.String `tfsdk:"arn"`
UserID types.String `tfsdk:"user_id"`
}
func (r *iamUserResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_user"
}
func (r *iamUserResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS IAM user using IAM query API calls.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
Description: "Terraform identifier for this resource. Equals user name.",
},
"name": schema.StringAttribute{
Required: true,
Description: "IAM user name.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"path": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("/"),
Description: "IAM path for the user. SeaweedFS 4.51.0 supports only `/`.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"arn": schema.StringAttribute{
Computed: true,
Description: "ARN returned by SeaweedFS.",
},
"user_id": schema.StringAttribute{
Computed: true,
Description: "Unique user identifier returned by SeaweedFS.",
},
},
}
}
func (r *iamUserResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError(
"Unexpected provider data type",
fmt.Sprintf("Expected *providerData, got %T", req.ProviderData),
)
return
}
r.client = data.client
r.data = data
}
func (r *iamUserResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamUserResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
if plan.Path.ValueString() != "/" {
resp.Diagnostics.AddError("Unsupported IAM user path", "SeaweedFS 4.51.0 supports only the root IAM path `/`.")
return
}
var user getUserResponse
var firstErr error
err := r.data.withUserLock(plan.Name.ValueString(), func() error {
return retryIAMEventuallyConsistent(ctx, 8, func() error {
var innerErr error
user, innerErr = r.client.CreateUser(ctx, plan.Name.ValueString(), plan.Path.ValueString())
if firstErr == nil {
firstErr = innerErr
}
return innerErr
})
})
if err != nil {
if isEntityAlreadyExistsError(err) && isEntityAlreadyExistsError(firstErr) {
resp.Diagnostics.AddError(
"IAM user already exists",
fmt.Sprintf("IAM user %q already exists. Import it with `terraform import` to manage it.", plan.Name.ValueString()),
)
return
}
if isEntityAlreadyExistsError(err) {
resp.Diagnostics.AddError(
"IAM user creation outcome unknown",
fmt.Sprintf("CreateUser first failed with %v, and a retry found IAM user %q already present. The failed attempt may have created it, or another client did. Check the user and import it with `terraform import` to manage it.", firstErr, plan.Name.ValueString()),
)
return
}
resp.Diagnostics.AddError(
"Failed to create IAM user",
err.Error(),
)
return
}
userPath := user.User.Path
if userPath == "" {
userPath = plan.Path.ValueString()
if userPath == "" {
userPath = "/"
}
}
// SeaweedFS may acknowledge CreateUser before the user is fully visible
// to subsequent IAM operations. Ensure visibility before finishing Create.
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
_, innerErr := r.client.GetUser(ctx, user.User.UserName)
return innerErr
}); err != nil {
resp.Diagnostics.AddError(
"Failed to verify IAM user visibility",
err.Error(),
)
return
}
state := iamUserResourceModel{
ID: types.StringValue(user.User.UserName),
Name: types.StringValue(user.User.UserName),
Path: types.StringValue(userPath),
ARN: types.StringValue(user.User.Arn),
UserID: types.StringValue(user.User.UserID),
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamUserResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamUserResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var user getUserResponse
err := retryIAMEventuallyConsistent(ctx, 6, func() error {
var innerErr error
user, innerErr = r.client.GetUser(ctx, state.Name.ValueString())
return innerErr
})
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(
"Failed to read IAM user",
err.Error(),
)
return
}
userPath := user.User.Path
if userPath == "" {
userPath = state.Path.ValueString()
if userPath == "" {
userPath = "/"
}
}
state.ID = types.StringValue(user.User.UserName)
state.Name = types.StringValue(user.User.UserName)
state.Path = types.StringValue(userPath)
state.ARN = types.StringValue(user.User.Arn)
state.UserID = types.StringValue(user.User.UserID)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamUserResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
resp.Diagnostics.AddError(
"Update not supported",
"seaweedfs_iam_user currently supports replacement on changes to name/path only.",
)
}
func (r *iamUserResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamUserResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.data.withUserLock(state.Name.ValueString(), func() error {
return retryIAMEventuallyConsistent(ctx, 8, func() error {
return r.client.DeleteUser(ctx, state.Name.ValueString())
})
}); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError(
"Failed to delete IAM user",
err.Error(),
)
}
}
func (r *iamUserResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), req.ID)...)
}
@@ -0,0 +1,200 @@
package seaweedfs
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &iamUserPolicyResource{}
_ resource.ResourceWithConfigure = &iamUserPolicyResource{}
_ resource.ResourceWithImportState = &iamUserPolicyResource{}
)
func NewIAMUserPolicyResource() resource.Resource {
return &iamUserPolicyResource{}
}
type iamUserPolicyResource struct {
client *iamClient
data *providerData
}
type iamUserPolicyResourceModel struct {
ID types.String `tfsdk:"id"`
UserName types.String `tfsdk:"user_name"`
Name types.String `tfsdk:"name"`
Policy types.String `tfsdk:"policy"`
}
func (r *iamUserPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iam_user_policy"
}
func (r *iamUserPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages an inline IAM user policy in SeaweedFS. Import using `user_name,policy_name`.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
},
"user_name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"policy": schema.StringAttribute{
Required: true,
Description: "JSON policy document.",
},
},
}
}
func (r *iamUserPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *iamUserPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan iamUserPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
policyToWrite := plan.Policy.ValueString()
if normalized, err := normalizeJSONString(policyToWrite); err == nil {
policyToWrite = normalized
}
if err := r.data.withUserLock(plan.UserName.ValueString(), func() error {
return retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.PutUserPolicy(ctx, plan.UserName.ValueString(), plan.Name.ValueString(), policyToWrite)
})
}); err != nil {
resp.Diagnostics.AddError("Failed to create IAM user policy", err.Error())
return
}
state := iamUserPolicyResourceModel{
ID: types.StringValue(plan.UserName.ValueString() + ":" + plan.Name.ValueString()),
UserName: types.StringValue(plan.UserName.ValueString()),
Name: types.StringValue(plan.Name.ValueString()),
Policy: types.StringValue(plan.Policy.ValueString()),
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamUserPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state iamUserPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var remotePolicy string
err := retryIAMRead(ctx, 6, func() error {
var innerErr error
remotePolicy, innerErr = r.client.GetUserPolicy(ctx, state.UserName.ValueString(), state.Name.ValueString())
return innerErr
})
if err != nil {
if isNoSuchEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read IAM user policy", err.Error())
return
}
state.ID = types.StringValue(state.UserName.ValueString() + ":" + state.Name.ValueString())
if !policiesSemanticallyEqual(state.Policy.ValueString(), remotePolicy) {
state.Policy = types.StringValue(remotePolicy)
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamUserPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan iamUserPolicyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
policyToWrite := plan.Policy.ValueString()
if normalized, err := normalizeJSONString(policyToWrite); err == nil {
policyToWrite = normalized
}
if err := r.data.withUserLock(plan.UserName.ValueString(), func() error {
return retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.PutUserPolicy(ctx, plan.UserName.ValueString(), plan.Name.ValueString(), policyToWrite)
})
}); err != nil {
resp.Diagnostics.AddError("Failed to update IAM user policy", err.Error())
return
}
state := iamUserPolicyResourceModel{
ID: types.StringValue(plan.UserName.ValueString() + ":" + plan.Name.ValueString()),
UserName: types.StringValue(plan.UserName.ValueString()),
Name: types.StringValue(plan.Name.ValueString()),
Policy: types.StringValue(plan.Policy.ValueString()),
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *iamUserPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state iamUserPolicyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.data.withUserLock(state.UserName.ValueString(), func() error {
return retryIAMEventuallyConsistent(ctx, 20, func() error {
return r.client.DeleteUserPolicy(ctx, state.UserName.ValueString(), state.Name.ValueString())
})
}); err != nil && !isNoSuchEntityError(err) {
resp.Diagnostics.AddError("Failed to delete IAM user policy", err.Error())
}
}
func (r *iamUserPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
parts := strings.SplitN(req.ID, ",", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
resp.Diagnostics.AddError(
"Invalid import ID",
"Expected import id in format `user_name,policy_name`.",
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), parts[0]+":"+parts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_name"), parts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), parts[1])...)
}
@@ -0,0 +1,59 @@
package seaweedfs
import (
"context"
"net/http"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)
func TestIAMUserCreateRejectsExistingUser(t *testing.T) {
ctx := context.Background()
for _, tc := range []struct {
name string
failFirst bool
wantSummary string
}{
{name: "collision on first attempt", wantSummary: "IAM user already exists"},
{name: "retried create that may have committed", failFirst: true, wantSummary: "IAM user creation outcome unknown"},
} {
t.Run(tc.name, func(t *testing.T) {
creates := 0
client := testIAMClient(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
switch r.Form.Get("Action") {
case "CreateUser":
creates++
if tc.failFirst && creates == 1 {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>ServiceFailure</Code><Message>timeout</Message></Error></ErrorResponse>`))
return
}
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>EntityAlreadyExists</Code><Message>exists</Message></Error></ErrorResponse>`))
default:
t.Errorf("unexpected action %s", r.Form.Get("Action"))
}
})
r := &iamUserResource{client: client, data: &providerData{}}
plan, state := testResourcePlan(ctx, r, map[string]tftypes.Value{
"name": tftypes.NewValue(tftypes.String, "alice"),
"path": tftypes.NewValue(tftypes.String, "/"),
})
resp := resource.CreateResponse{State: state}
r.Create(ctx, resource.CreateRequest{Plan: plan}, &resp)
if !resp.Diagnostics.HasError() || resp.Diagnostics.Errors()[0].Summary() != tc.wantSummary {
t.Fatalf("diagnostics = %v, want error %q", resp.Diagnostics, tc.wantSummary)
}
if !resp.State.Raw.IsNull() {
var got iamUserResourceModel
resp.Diagnostics.Append(resp.State.Get(ctx, &got)...)
if got.Name.ValueString() != "" {
t.Fatalf("state adopted user %q", got.Name.ValueString())
}
}
})
}
}
@@ -0,0 +1,573 @@
package seaweedfs
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type s3TableMaintenanceResource struct {
client *iamClient
data *providerData
table bool
}
type s3TableMaintenanceResourceModel struct {
ID types.String
TableBucketARN types.String
Namespace types.String
Name types.String
Type types.String
Status types.String
Strategy types.String
TargetFileSizeMB types.Int64
MinSnapshotsToKeep types.Int64
MaxSnapshotAgeHours types.Int64
UnreferencedDays types.Int64
NonCurrentDays types.Int64
}
type s3TableMaintenanceTerraformData interface {
GetAttribute(context.Context, path.Path, interface{}) diag.Diagnostics
}
var (
_ resource.Resource = &s3TableMaintenanceResource{}
_ resource.ResourceWithConfigure = &s3TableMaintenanceResource{}
_ resource.ResourceWithImportState = &s3TableMaintenanceResource{}
)
func NewS3TableBucketMaintenanceConfigurationResource() resource.Resource {
return &s3TableMaintenanceResource{}
}
func NewS3TableMaintenanceConfigurationResource() resource.Resource {
return &s3TableMaintenanceResource{table: true}
}
func (r *s3TableMaintenanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
suffix := "_table_bucket_maintenance_configuration"
if r.table {
suffix = "_table_maintenance_configuration"
}
resp.TypeName = req.ProviderTypeName + suffix
}
func (r *s3TableMaintenanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
attributes := map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true},
"table_bucket_arn": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"status": schema.StringAttribute{
Required: true,
Description: "Whether the maintenance operation is enabled or disabled.",
},
}
if r.table {
attributes["namespace"] = schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
}
attributes["name"] = schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
}
attributes["type"] = schema.StringAttribute{
Required: true,
Description: "Maintenance type: icebergCompaction or icebergSnapshotManagement.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
}
attributes["strategy"] = schema.StringAttribute{
Optional: true,
Description: "Compaction strategy: auto, binpack, or sort. Only applies to icebergCompaction.",
}
attributes["target_file_size_mb"] = schema.Int64Attribute{
Optional: true,
Description: "Target compacted file size in MiB. Only applies to icebergCompaction.",
}
attributes["min_snapshots_to_keep"] = schema.Int64Attribute{
Optional: true,
Description: "Minimum snapshots to retain. Only applies to icebergSnapshotManagement.",
}
attributes["max_snapshot_age_hours"] = schema.Int64Attribute{
Optional: true,
Description: "Maximum snapshot age in hours. Only applies to icebergSnapshotManagement.",
}
} else {
attributes["type"] = schema.StringAttribute{
Computed: true,
Description: "The bucket maintenance type is icebergUnreferencedFileRemoval.",
}
attributes["unreferenced_days"] = schema.Int64Attribute{
Optional: true,
Description: "Age in days after which unreferenced files may be removed.",
}
attributes["non_current_days"] = schema.Int64Attribute{
Optional: true,
Description: "Age in days after which non-current files may be removed.",
}
}
importDescription := "`table_bucket_arn`"
if r.table {
importDescription = "`table_bucket_arn,namespace,table_name,type`"
}
resp.Schema = schema.Schema{
Description: "Manages a SeaweedFS S3 Tables maintenance configuration. Import using " + importDescription + ". Deletion disables the configuration because the S3 Tables API has no delete operation.",
Attributes: attributes,
}
}
func (r *s3TableMaintenanceResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.client = data.client
r.data = data
}
func (r *s3TableMaintenanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
plan, diags := r.modelFromData(ctx, req.Plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
value, err := r.value(plan)
if err != nil {
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration", err.Error())
return
}
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.put(ctx, plan, value); err != nil {
resp.Diagnostics.AddError("Failed to create S3 Tables maintenance configuration", err.Error())
return
}
current, err := r.get(ctx, plan)
if err != nil {
message := r.cleanupFailedCreate(ctx, plan, err.Error())
resp.Diagnostics.AddError("Failed to read created S3 Tables maintenance configuration", message)
return
}
if current == nil {
message := r.cleanupFailedCreate(ctx, plan, "SeaweedFS did not return the configuration that was just created.")
resp.Diagnostics.AddError("Missing S3 Tables maintenance configuration", message)
return
}
if err := r.setState(&plan, current); err != nil {
message := r.cleanupFailedCreate(ctx, plan, err.Error())
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration returned by SeaweedFS", message)
return
}
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
}
func (r *s3TableMaintenanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
state, diags := r.modelFromData(ctx, req.State)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
lock.Lock()
defer lock.Unlock()
current, err := r.get(ctx, state)
if err != nil {
if isNoSuchS3TablesEntityError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Failed to read S3 Tables maintenance configuration", err.Error())
return
}
if current == nil {
resp.State.RemoveResource(ctx)
return
}
if err := r.setState(&state, current); err != nil {
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration returned by SeaweedFS", err.Error())
return
}
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, state)...)
}
func (r *s3TableMaintenanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
plan, diags := r.modelFromData(ctx, req.Plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
value, err := r.value(plan)
if err != nil {
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration", err.Error())
return
}
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.put(ctx, plan, value); err != nil {
resp.Diagnostics.AddError("Failed to update S3 Tables maintenance configuration", err.Error())
return
}
current, err := r.get(ctx, plan)
if err != nil {
resp.Diagnostics.AddError("Failed to read updated S3 Tables maintenance configuration", err.Error())
return
}
if current == nil {
resp.Diagnostics.AddError("Missing S3 Tables maintenance configuration", "SeaweedFS did not return the configuration that was just updated.")
return
}
if err := r.setState(&plan, current); err != nil {
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration returned by SeaweedFS", err.Error())
return
}
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
}
func (r *s3TableMaintenanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
state, diags := r.modelFromData(ctx, req.State)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
lock.Lock()
defer lock.Unlock()
if err := r.put(ctx, state, s3TableMaintenanceValue{Status: "disabled"}); err != nil && !isNoSuchS3TablesEntityError(err) {
resp.Diagnostics.AddError("Failed to disable S3 Tables maintenance configuration", err.Error())
}
}
func (r *s3TableMaintenanceResource) modelFromData(ctx context.Context, data s3TableMaintenanceTerraformData) (s3TableMaintenanceResourceModel, diag.Diagnostics) {
var model s3TableMaintenanceResourceModel
var diags diag.Diagnostics
diags.Append(data.GetAttribute(ctx, path.Root("id"), &model.ID)...)
diags.Append(data.GetAttribute(ctx, path.Root("table_bucket_arn"), &model.TableBucketARN)...)
diags.Append(data.GetAttribute(ctx, path.Root("type"), &model.Type)...)
diags.Append(data.GetAttribute(ctx, path.Root("status"), &model.Status)...)
if r.table {
diags.Append(data.GetAttribute(ctx, path.Root("namespace"), &model.Namespace)...)
diags.Append(data.GetAttribute(ctx, path.Root("name"), &model.Name)...)
diags.Append(data.GetAttribute(ctx, path.Root("strategy"), &model.Strategy)...)
diags.Append(data.GetAttribute(ctx, path.Root("target_file_size_mb"), &model.TargetFileSizeMB)...)
diags.Append(data.GetAttribute(ctx, path.Root("min_snapshots_to_keep"), &model.MinSnapshotsToKeep)...)
diags.Append(data.GetAttribute(ctx, path.Root("max_snapshot_age_hours"), &model.MaxSnapshotAgeHours)...)
} else {
diags.Append(data.GetAttribute(ctx, path.Root("unreferenced_days"), &model.UnreferencedDays)...)
diags.Append(data.GetAttribute(ctx, path.Root("non_current_days"), &model.NonCurrentDays)...)
}
return model, diags
}
func (r *s3TableMaintenanceResource) writeState(ctx context.Context, state *tfsdk.State, model s3TableMaintenanceResourceModel) diag.Diagnostics {
var diags diag.Diagnostics
diags.Append(state.SetAttribute(ctx, path.Root("id"), model.ID)...)
diags.Append(state.SetAttribute(ctx, path.Root("table_bucket_arn"), model.TableBucketARN)...)
diags.Append(state.SetAttribute(ctx, path.Root("type"), model.Type)...)
diags.Append(state.SetAttribute(ctx, path.Root("status"), model.Status)...)
if r.table {
diags.Append(state.SetAttribute(ctx, path.Root("namespace"), model.Namespace)...)
diags.Append(state.SetAttribute(ctx, path.Root("name"), model.Name)...)
diags.Append(state.SetAttribute(ctx, path.Root("strategy"), model.Strategy)...)
diags.Append(state.SetAttribute(ctx, path.Root("target_file_size_mb"), model.TargetFileSizeMB)...)
diags.Append(state.SetAttribute(ctx, path.Root("min_snapshots_to_keep"), model.MinSnapshotsToKeep)...)
diags.Append(state.SetAttribute(ctx, path.Root("max_snapshot_age_hours"), model.MaxSnapshotAgeHours)...)
} else {
diags.Append(state.SetAttribute(ctx, path.Root("unreferenced_days"), model.UnreferencedDays)...)
diags.Append(state.SetAttribute(ctx, path.Root("non_current_days"), model.NonCurrentDays)...)
}
return diags
}
func (r *s3TableMaintenanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
if !r.table {
arn, err := parseTableBucketARN(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), arn)...)
return
}
arn, namespace, name, maintenanceType, err := parseTableMaintenanceImportID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), arn)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("namespace"), namespace)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("type"), maintenanceType)...)
}
func (r *s3TableMaintenanceResource) get(ctx context.Context, model s3TableMaintenanceResourceModel) (*s3TableMaintenanceValue, error) {
maintenanceType := r.maintenanceType(model)
var configuration map[string]*s3TableMaintenanceValue
var err error
if r.table {
configuration, err = r.client.GetS3TableMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString(), model.Namespace.ValueString(), model.Name.ValueString())
} else {
configuration, err = r.client.GetS3TableBucketMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString())
}
if err != nil {
return nil, err
}
return configuration[maintenanceType], nil
}
func (r *s3TableMaintenanceResource) put(ctx context.Context, model s3TableMaintenanceResourceModel, value s3TableMaintenanceValue) error {
if r.table {
return r.client.PutS3TableMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString(), model.Namespace.ValueString(), model.Name.ValueString(), r.maintenanceType(model), value)
}
return r.client.PutS3TableBucketMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString(), value)
}
func (r *s3TableMaintenanceResource) maintenanceType(model s3TableMaintenanceResourceModel) string {
if !r.table {
return s3TableMaintenanceUnreferencedFiles
}
return model.Type.ValueString()
}
func (r *s3TableMaintenanceResource) value(model s3TableMaintenanceResourceModel) (s3TableMaintenanceValue, error) {
status := model.Status.ValueString()
if status != "enabled" && status != "disabled" {
return s3TableMaintenanceValue{}, fmt.Errorf("status must be either enabled or disabled")
}
settings := &s3TableMaintenanceSettings{}
hasSettings := false
if r.table {
switch model.Type.ValueString() {
case s3TableMaintenanceCompaction:
if !model.MinSnapshotsToKeep.IsNull() || !model.MaxSnapshotAgeHours.IsNull() {
return s3TableMaintenanceValue{}, fmt.Errorf("snapshot management settings cannot be used with %s", model.Type.ValueString())
}
strategy := model.Strategy.ValueString()
if !model.Strategy.IsNull() && !model.Strategy.IsUnknown() && strategy == "" {
return s3TableMaintenanceValue{}, fmt.Errorf("strategy must be auto, binpack, or sort; omit it to use the server default")
}
if strategy != "" && strategy != "auto" && strategy != "binpack" && strategy != "sort" {
return s3TableMaintenanceValue{}, fmt.Errorf("strategy must be auto, binpack, or sort")
}
compaction := &s3TableCompactionSettings{Strategy: strategy}
hasSettings = strategy != ""
if !model.TargetFileSizeMB.IsNull() {
compaction.TargetFileSizeMB = int64Pointer(model.TargetFileSizeMB.ValueInt64())
hasSettings = true
}
if hasSettings {
settings.IcebergCompaction = compaction
}
case s3TableMaintenanceSnapshotManagement:
if !model.Strategy.IsNull() && model.Strategy.ValueString() != "" || !model.TargetFileSizeMB.IsNull() {
return s3TableMaintenanceValue{}, fmt.Errorf("compaction settings cannot be used with %s", model.Type.ValueString())
}
snapshotManagement := &s3TableSnapshotManagementSettings{}
if !model.MinSnapshotsToKeep.IsNull() {
snapshotManagement.MinSnapshotsToKeep = int64Pointer(model.MinSnapshotsToKeep.ValueInt64())
hasSettings = true
}
if !model.MaxSnapshotAgeHours.IsNull() {
snapshotManagement.MaxSnapshotAgeHours = int64Pointer(model.MaxSnapshotAgeHours.ValueInt64())
hasSettings = true
}
if hasSettings {
settings.IcebergSnapshotManagement = snapshotManagement
}
default:
return s3TableMaintenanceValue{}, fmt.Errorf("type must be %s or %s", s3TableMaintenanceCompaction, s3TableMaintenanceSnapshotManagement)
}
} else {
if (!model.Strategy.IsNull() && model.Strategy.ValueString() != "") ||
!model.TargetFileSizeMB.IsNull() || !model.MinSnapshotsToKeep.IsNull() || !model.MaxSnapshotAgeHours.IsNull() {
return s3TableMaintenanceValue{}, fmt.Errorf("table maintenance settings cannot be used for bucket-level maintenance")
}
unreferencedFiles := &s3TableUnreferencedFileRemovalSettings{}
if !model.UnreferencedDays.IsNull() {
unreferencedFiles.UnreferencedDays = int64Pointer(model.UnreferencedDays.ValueInt64())
hasSettings = true
}
if !model.NonCurrentDays.IsNull() {
unreferencedFiles.NonCurrentDays = int64Pointer(model.NonCurrentDays.ValueInt64())
hasSettings = true
}
if hasSettings {
settings.IcebergUnreferencedFileRemoval = unreferencedFiles
}
}
for _, field := range []struct {
name string
value *int64
}{
{"target_file_size_mb", maintenanceSettingValue(settings, "target_file_size_mb")},
{"min_snapshots_to_keep", maintenanceSettingValue(settings, "min_snapshots_to_keep")},
{"max_snapshot_age_hours", maintenanceSettingValue(settings, "max_snapshot_age_hours")},
{"unreferenced_days", maintenanceSettingValue(settings, "unreferenced_days")},
{"non_current_days", maintenanceSettingValue(settings, "non_current_days")},
} {
if field.value != nil && (*field.value < 1 || *field.value > 2147483647) {
return s3TableMaintenanceValue{}, fmt.Errorf("%s must be between 1 and 2147483647", field.name)
}
}
if !hasSettings {
settings = nil
}
return s3TableMaintenanceValue{Status: status, Settings: settings}, nil
}
func (r *s3TableMaintenanceResource) setState(state *s3TableMaintenanceResourceModel, value *s3TableMaintenanceValue) error {
if value == nil || (value.Status != "enabled" && value.Status != "disabled") {
return fmt.Errorf("configuration must include a valid status")
}
state.Type = types.StringValue(r.maintenanceType(*state))
state.Status = types.StringValue(value.Status)
state.Strategy = types.StringNull()
state.TargetFileSizeMB = types.Int64Null()
state.MinSnapshotsToKeep = types.Int64Null()
state.MaxSnapshotAgeHours = types.Int64Null()
state.UnreferencedDays = types.Int64Null()
state.NonCurrentDays = types.Int64Null()
if value.Settings == nil {
state.ID = types.StringValue(r.resourceID(*state))
return nil
}
switch state.Type.ValueString() {
case s3TableMaintenanceCompaction:
if value.Settings.IcebergSnapshotManagement != nil || value.Settings.IcebergUnreferencedFileRemoval != nil {
return fmt.Errorf("settings do not match maintenance type %q", state.Type.ValueString())
}
if settings := value.Settings.IcebergCompaction; settings != nil {
if settings.Strategy != "" {
state.Strategy = types.StringValue(settings.Strategy)
}
if settings.TargetFileSizeMB != nil {
state.TargetFileSizeMB = types.Int64Value(*settings.TargetFileSizeMB)
}
}
case s3TableMaintenanceSnapshotManagement:
if value.Settings.IcebergCompaction != nil || value.Settings.IcebergUnreferencedFileRemoval != nil {
return fmt.Errorf("settings do not match maintenance type %q", state.Type.ValueString())
}
if settings := value.Settings.IcebergSnapshotManagement; settings != nil {
if settings.MinSnapshotsToKeep != nil {
state.MinSnapshotsToKeep = types.Int64Value(*settings.MinSnapshotsToKeep)
}
if settings.MaxSnapshotAgeHours != nil {
state.MaxSnapshotAgeHours = types.Int64Value(*settings.MaxSnapshotAgeHours)
}
}
case s3TableMaintenanceUnreferencedFiles:
if value.Settings.IcebergCompaction != nil || value.Settings.IcebergSnapshotManagement != nil {
return fmt.Errorf("settings do not match maintenance type %q", state.Type.ValueString())
}
if settings := value.Settings.IcebergUnreferencedFileRemoval; settings != nil {
if settings.UnreferencedDays != nil {
state.UnreferencedDays = types.Int64Value(*settings.UnreferencedDays)
}
if settings.NonCurrentDays != nil {
state.NonCurrentDays = types.Int64Value(*settings.NonCurrentDays)
}
}
default:
return fmt.Errorf("unsupported maintenance type %q", state.Type.ValueString())
}
state.ID = types.StringValue(r.resourceID(*state))
return nil
}
func maintenanceSettingValue(settings *s3TableMaintenanceSettings, name string) *int64 {
switch name {
case "target_file_size_mb":
if settings.IcebergCompaction != nil {
return settings.IcebergCompaction.TargetFileSizeMB
}
case "min_snapshots_to_keep":
if settings.IcebergSnapshotManagement != nil {
return settings.IcebergSnapshotManagement.MinSnapshotsToKeep
}
case "max_snapshot_age_hours":
if settings.IcebergSnapshotManagement != nil {
return settings.IcebergSnapshotManagement.MaxSnapshotAgeHours
}
case "unreferenced_days":
if settings.IcebergUnreferencedFileRemoval != nil {
return settings.IcebergUnreferencedFileRemoval.UnreferencedDays
}
case "non_current_days":
if settings.IcebergUnreferencedFileRemoval != nil {
return settings.IcebergUnreferencedFileRemoval.NonCurrentDays
}
}
return nil
}
func (r *s3TableMaintenanceResource) resourceID(model s3TableMaintenanceResourceModel) string {
if !r.table {
return model.TableBucketARN.ValueString()
}
return strings.Join([]string{
model.TableBucketARN.ValueString(),
model.Namespace.ValueString(),
model.Name.ValueString(),
model.Type.ValueString(),
}, ",")
}
func (r *s3TableMaintenanceResource) cleanupFailedCreate(ctx context.Context, model s3TableMaintenanceResourceModel, message string) string {
if err := r.put(ctx, model, s3TableMaintenanceValue{Status: "disabled"}); err != nil && !isNoSuchS3TablesEntityError(err) {
message += "; cleanup failed: " + err.Error()
}
return message
}
func parseTableMaintenanceImportID(id string) (string, string, string, string, error) {
parts := strings.SplitN(id, ",", 4)
if len(parts) != 4 || parts[0] == "" || parts[1] == "" || parts[2] == "" || parts[3] == "" {
return "", "", "", "", fmt.Errorf("expected import ID `table_bucket_arn,namespace,table_name,type`")
}
if _, err := parseTableBucketARN(parts[0]); err != nil {
return "", "", "", "", err
}
if parts[3] != s3TableMaintenanceCompaction && parts[3] != s3TableMaintenanceSnapshotManagement {
return "", "", "", "", fmt.Errorf("unsupported table maintenance type %q", parts[3])
}
return parts[0], parts[1], parts[2], parts[3], nil
}
func int64Pointer(value int64) *int64 {
return &value
}
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more