phase58: add rebuild target owner

This commit is contained in:
pingqiu committed 2026-06-23 16:51:52 -07:00
1 parent 3a89658ce4
commit be9fda550e
15 files changed
+1365 -111

No files matched your search

@@ -0,0 +1,38 @@
{{- if and .Values.rebuildTargetOwner.create .Values.rebuildTargetOwner.rbac.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner
namespace: {{ .Release.Namespace }}
labels:
{{- include "seaweed-block.labels" . | nindent 4 }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner
labels:
{{- include "seaweed-block.labels" . | nindent 4 }}
rules:
- apiGroups: ["block.seaweedfs.com"]
resources: ["swblockvolumes"]
verbs: ["get", "list", "watch"]
- apiGroups: ["block.seaweedfs.com"]
resources: ["swblockreplicarebuilds"]
verbs: ["get", "list", "watch", "create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner
labels:
{{- include "seaweed-block.labels" . | nindent 4 }}
subjects:
- kind: ServiceAccount
name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner
namespace: {{ .Release.Namespace }}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner
{{- end }}
@@ -0,0 +1,39 @@
{{- if .Values.rebuildTargetOwner.create }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: sw-block-rebuild-target-owner
namespace: {{ .Release.Namespace }}
labels:
{{- include "seaweed-block.labels" . | nindent 4 }}
app: sw-block-rebuild-target-owner
spec:
replicas: 1
selector:
matchLabels:
app: sw-block-rebuild-target-owner
template:
metadata:
labels:
app: sw-block-rebuild-target-owner
{{- include "seaweed-block.labels" . | nindent 8 }}
spec:
serviceAccountName: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner
{{- with .Values.rebuildTargetOwner.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
containers:
- name: rebuild-target-owner
image: {{ include "seaweed-block.image" . | quote }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
command: ["/usr/local/bin/sw-block"]
args:
- "ops"
- "rebuild-target-owner"
- "--namespace={{ .Release.Namespace }}"
{{- if .Values.rebuildTargetOwner.dryRun }}
- "--dry-run"
{{- end }}
- "--interval={{ .Values.rebuildTargetOwner.interval }}"
{{- end }}
@@ -156,6 +156,18 @@ authorityExecutor:
create: true
nodeSelector: {}
rebuildTargetOwner:
# Rebuild target owner. Disabled by default. When enabled it creates
# SwBlockReplicaRebuild target CRs from ready rebuild_returned_replica
# executor contracts. It does not write status, publish frontend paths,
# start rebuild traffic, or change authority.
create: false
dryRun: true
interval: 30s
rbac:
create: true
nodeSelector: {}
csiController:
replicas: 1
+68 -1
View File
@@ -51,6 +51,9 @@ var (
opsAuthorityExecutorClientFactory = func() (ops.AuthorityExecutorClient, error) {
return ops.NewInClusterKubernetesStatusClient()
}
opsRebuildTargetOwnerClientFactory = func() (ops.RebuildTargetOwnerClient, error) {
return ops.NewInClusterKubernetesStatusClient()
}
)
func run(args []string, stdout, stderr io.Writer) int {
@@ -68,7 +71,7 @@ func run(args []string, stdout, stderr io.Writer) int {
return ops.VolumeStatusExitInvalid
}
if len(args) < 2 {
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor")
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner")
usage(stderr)
return ops.VolumeStatusExitInvalid
}
@@ -99,6 +102,8 @@ func run(args []string, stdout, stderr io.Writer) int {
return runOpsLifecycleOwner(args[2:], stdout, stderr)
case "authority-executor":
return runOpsAuthorityExecutor(args[2:], stdout, stderr)
case "rebuild-target-owner":
return runOpsRebuildTargetOwner(args[2:], stdout, stderr)
default:
fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1])
usage(stderr)
@@ -106,6 +111,67 @@ func run(args []string, stdout, stderr io.Writer) int {
}
}
func runOpsRebuildTargetOwner(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block ops rebuild-target-owner", flag.ContinueOnError)
fs.SetOutput(stderr)
var (
dryRun bool
namespace string
interval time.Duration
)
fs.BoolVar(&dryRun, "dry-run", false, "evaluate rebuild target planning without creating SwBlockReplicaRebuild objects")
fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockVolume objects")
fs.DurationVar(&interval, "interval", 0, "repeat rebuild-target-owner reconciliation at this interval; 0 runs once")
if err := fs.Parse(args); err != nil {
return ops.VolumeStatusExitInvalid
}
if fs.NArg() != 0 {
fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: unexpected args %s\n", strings.Join(fs.Args(), " "))
return ops.VolumeStatusExitInvalid
}
runOnce := func() int {
client, err := opsRebuildTargetOwnerClientFactory()
if err != nil {
fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: %v\n", err)
return ops.VolumeStatusExitInvalid
}
result, err := (ops.RebuildTargetOwnerReconciler{
Namespace: namespace,
Client: client,
DryRun: dryRun,
}).Reconcile(context.Background())
if err != nil {
fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: %v\n", err)
return ops.VolumeStatusExitInvalid
}
mode := "target_mutation"
if dryRun {
mode = "dry_run"
}
fmt.Fprintf(stdout, "rebuild_target_owner=%s namespace=%s volumes=%d contracts=%d targets_planned=%d targets_existing=%d targets_created=%d invalid_contracts=%d mutation_allowed=%t storage_mutation_allowed=false frontend_publication_allowed=false failback_allowed=false\n",
mode,
namespace,
result.VolumeCount,
result.ContractCount,
result.TargetPlannedCount,
result.TargetExistingCount,
result.TargetCreateCount,
result.InvalidContractCount,
!dryRun && result.TargetCreateCount > 0)
return ops.VolumeStatusExitOK
}
if interval <= 0 {
return runOnce()
}
for {
code := runOnce()
if code != ops.VolumeStatusExitOK {
fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: iteration failed exit=%d; retrying in %s\n", code, interval)
}
time.Sleep(interval)
}
}
func runOpsAuthorityExecutor(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block ops authority-executor", flag.ContinueOnError)
fs.SetOutput(stderr)
@@ -1718,6 +1784,7 @@ func usage(w io.Writer) {
fmt.Fprintln(w, " sw-block ops operator-status --dry-run [--master-api <addr>|--from-bundle <dir>] [--cleanup-summary <file>] [--interval 30s]")
fmt.Fprintln(w, " sw-block ops lifecycle-owner [--dry-run] [--namespace <ns>] [--interval 30s]")
fmt.Fprintln(w, " sw-block ops authority-executor [--namespace <ns>] [--allowed-mutation-class ack_eligibility|rebuild_traffic] [--interval 30s]")
fmt.Fprintln(w, " sw-block ops rebuild-target-owner [--dry-run] [--namespace <ns>] [--interval 30s]")
}
func emptyCLI(value string) string {
+118
View File
@@ -662,6 +662,118 @@ func TestOpsAuthorityExecutorWritesRebuildPlannedStatus(t *testing.T) {
}
}
func TestOpsRebuildTargetOwnerCreatesTarget(t *testing.T) {
client := &lifecycleOwnerTestClient{
volumes: []ops.SwBlockVolumeObject{{
Ref: ops.OperatorObjectRef{
APIVersion: ops.SwBlockVolumeAPIVersion,
Kind: ops.SwBlockVolumeKind,
Namespace: "kube-system",
Name: "demo-pvc",
},
Status: ops.SwBlockVolumeCRDStatus{
VolumeID: "pvc-demo",
PVCName: "demo-pvc",
ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{
ActionType: ops.ManagedVolumeActionRebuildReturned,
ReplicaID: "r2",
Decision: ops.ReturnedReplicaExecutorContractDisabled,
Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled,
PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady,
PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied,
AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationRebuildTraffic},
}},
},
}},
}
oldFactory := opsRebuildTargetOwnerClientFactory
opsRebuildTargetOwnerClientFactory = func() (ops.RebuildTargetOwnerClient, error) {
return client, nil
}
t.Cleanup(func() { opsRebuildTargetOwnerClientFactory = oldFactory })
var stdout, stderr bytes.Buffer
code := run([]string{"ops", "rebuild-target-owner", "--namespace", "kube-system"}, &stdout, &stderr)
if code != ops.VolumeStatusExitOK {
t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String())
}
if len(client.rebuildCreates) != 1 {
t.Fatalf("rebuildCreates=%+v", client.rebuildCreates)
}
created := client.rebuildCreates[0]
if created.Ref.Name != "demo-pvc-r2-rebuild" ||
created.Spec.VolumeName != "demo-pvc" ||
created.Spec.ReplicaID != "r2" {
t.Fatalf("created=%+v", created)
}
out := stdout.String()
for _, want := range []string{
"rebuild_target_owner=target_mutation",
"namespace=kube-system",
"volumes=1",
"contracts=1",
"targets_planned=1",
"targets_existing=0",
"targets_created=1",
"mutation_allowed=true",
"storage_mutation_allowed=false",
"frontend_publication_allowed=false",
"failback_allowed=false",
} {
if !strings.Contains(out, want) {
t.Fatalf("stdout missing %q:\n%s", want, out)
}
}
}
func TestOpsRebuildTargetOwnerDryRunDoesNotCreateTarget(t *testing.T) {
client := &lifecycleOwnerTestClient{
volumes: []ops.SwBlockVolumeObject{{
Ref: ops.OperatorObjectRef{
Name: "demo-pvc",
},
Status: ops.SwBlockVolumeCRDStatus{
VolumeID: "pvc-demo",
PVCName: "demo-pvc",
ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{
ActionType: ops.ManagedVolumeActionRebuildReturned,
ReplicaID: "r2",
Decision: ops.ReturnedReplicaExecutorContractDisabled,
Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled,
PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady,
PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied,
AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationRebuildTraffic},
}},
},
}},
}
oldFactory := opsRebuildTargetOwnerClientFactory
opsRebuildTargetOwnerClientFactory = func() (ops.RebuildTargetOwnerClient, error) {
return client, nil
}
t.Cleanup(func() { opsRebuildTargetOwnerClientFactory = oldFactory })
var stdout, stderr bytes.Buffer
code := run([]string{"ops", "rebuild-target-owner", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr)
if code != ops.VolumeStatusExitOK {
t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String())
}
if len(client.rebuildCreates) != 0 {
t.Fatalf("dry-run creates=%+v", client.rebuildCreates)
}
out := stdout.String()
for _, want := range []string{
"rebuild_target_owner=dry_run",
"targets_planned=1",
"targets_created=0",
"mutation_allowed=false",
} {
if !strings.Contains(out, want) {
t.Fatalf("stdout missing %q:\n%s", want, out)
}
}
}
func TestOpsAuthorityExecutorExecutionPolicyBlocksWhenAckTargetMissing(t *testing.T) {
client := &lifecycleOwnerTestClient{
volumes: []ops.SwBlockVolumeObject{{
@@ -1037,6 +1149,7 @@ type lifecycleOwnerTestClient struct {
events []ops.OperatorKubernetesEvent
eligibilityWrites []lifecycleOwnerTestEligibilityWrite
rebuildWrites []lifecycleOwnerTestRebuildWrite
rebuildCreates []ops.SwBlockReplicaRebuildObject
}
type lifecycleOwnerTestPatch struct {
@@ -1076,6 +1189,11 @@ func (c *lifecycleOwnerTestClient) WriteReplicaRebuildStatus(_ context.Context,
return nil
}
func (c *lifecycleOwnerTestClient) CreateSwBlockReplicaRebuild(_ context.Context, _ string, obj ops.SwBlockReplicaRebuildObject) error {
c.rebuildCreates = append(c.rebuildCreates, obj)
return nil
}
func (c *lifecycleOwnerTestClient) PatchSwBlockVolumeFinalizers(_ context.Context, ref ops.OperatorObjectRef, finalizers []string) error {
c.patches = append(c.patches, lifecycleOwnerTestPatch{
ref: ref,
@@ -573,6 +573,62 @@ func TestPhase54D3AuthorityExecutorExecutionRBACIsNarrow(t *testing.T) {
}
}
func TestPhase58RebuildTargetOwnerPackagingIsNarrow(t *testing.T) {
values := readYAMLMap(t, "charts/seaweed-block/values.yaml")
rebuildTargetOwner := yamlMap(t, values, "rebuildTargetOwner")
assertYAMLBool(t, rebuildTargetOwner, "create", false)
assertYAMLBool(t, rebuildTargetOwner, "dryRun", true)
rbacValues := yamlMap(t, rebuildTargetOwner, "rbac")
assertYAMLBool(t, rbacValues, "create", true)
deploy := readRepoFile(t, "charts/seaweed-block/templates/rebuild-target-owner.yaml")
for _, want := range []string{
`kind: Deployment`,
`name: sw-block-rebuild-target-owner`,
`serviceAccountName: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner`,
`command: ["/usr/local/bin/sw-block"]`,
`- "rebuild-target-owner"`,
`- "--namespace={{ .Release.Namespace }}"`,
`{{- if .Values.rebuildTargetOwner.dryRun }}`,
`- "--dry-run"`,
`- "--interval={{ .Values.rebuildTargetOwner.interval }}"`,
} {
if !strings.Contains(deploy, want) {
t.Fatalf("rebuild-target-owner deployment missing %q\n%s", want, deploy)
}
}
rbac := readRepoFile(t, "charts/seaweed-block/templates/rebuild-target-owner-rbac.yaml")
for _, want := range []string{
`resources: ["swblockvolumes"]`,
`verbs: ["get", "list", "watch"]`,
`resources: ["swblockreplicarebuilds"]`,
`verbs: ["get", "list", "watch", "create"]`,
} {
if !strings.Contains(rbac, want) {
t.Fatalf("rebuild-target-owner RBAC missing %q\n%s", want, rbac)
}
}
for _, forbidden := range []string{
`resources: ["swblockvolumes/status"]`,
`resources: ["swblockvolumes/finalizers"]`,
`resources: ["swblockreplicarebuilds/status"]`,
`resources: ["events"]`,
`resources: ["pods"]`,
`resources: ["persistentvolumes"]`,
`resources: ["persistentvolumeclaims"]`,
`resources: ["storageclasses"]`,
`resources: ["secrets"]`,
`"update"`,
`"patch"`,
`"delete"`,
} {
if strings.Contains(rbac, forbidden) {
t.Fatalf("rebuild-target-owner RBAC contains forbidden fragment %q\n%s", forbidden, rbac)
}
}
}
func readRepoFile(t *testing.T, repoPath string) string {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", filepath.FromSlash(repoPath)))
@@ -230,6 +230,47 @@ func (c *KubernetesStatusClient) ListSwBlockReplicaRebuilds(ctx context.Context,
return out, nil
}
func (c *KubernetesStatusClient) CreateSwBlockReplicaRebuild(ctx context.Context, namespace string, obj SwBlockReplicaRebuildObject) error {
if namespace == "" || obj.Ref.Name == "" {
return fmt.Errorf("namespace and name are required for SwBlockReplicaRebuild create")
}
body, err := json.Marshal(map[string]any{
"apiVersion": SwBlockVolumeAPIVersion,
"kind": SwBlockReplicaRebuildKind,
"metadata": kubernetesMetadata{
Name: obj.Ref.Name,
Namespace: namespace,
},
"spec": obj.Spec,
})
if err != nil {
return fmt.Errorf("marshal SwBlockReplicaRebuild create: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.resourceCollectionURL(namespace, SwBlockReplicaRebuildPlural), bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
if c.BearerToken != "" {
req.Header.Set("Authorization", "Bearer "+c.BearerToken)
}
client := c.HTTPClient
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaRebuildPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Context, ref OperatorObjectRef, finalizers []string) error {
if ref.Namespace == "" || ref.Name == "" {
return fmt.Errorf("namespace and name are required for SwBlockVolume finalizer patch")
@@ -503,6 +503,69 @@ func TestKubernetesStatusClientPatchesOnlySwBlockVolumeFinalizers(t *testing.T)
}
}
func TestKubernetesStatusClientCreatesSwBlockReplicaRebuildWithoutStatus(t *testing.T) {
var request recordedStatusPatch
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(&request.Body); err != nil {
t.Fatalf("decode request body: %v", err)
}
request.Method = r.Method
request.Path = r.URL.Path
request.ContentType = r.Header.Get("Content-Type")
request.Authorization = r.Header.Get("Authorization")
w.WriteHeader(http.StatusCreated)
}))
defer server.Close()
err := (&KubernetesStatusClient{
BaseURL: server.URL,
BearerToken: "target-owner-token",
HTTPClient: server.Client(),
}).CreateSwBlockReplicaRebuild(context.Background(), "kube-system", SwBlockReplicaRebuildObject{
Ref: OperatorObjectRef{
Name: "demo-pvc-r2-rebuild",
},
Spec: SwBlockReplicaRebuildSpec{
VolumeName: "demo-pvc",
VolumeID: "pvc-demo",
PVCName: "demo-pvc",
ReplicaID: "r2",
},
})
if err != nil {
t.Fatalf("create rebuild target: %v", err)
}
if request.Method != http.MethodPost {
t.Fatalf("method=%s", request.Method)
}
if request.Path != "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockreplicarebuilds" {
t.Fatalf("path=%s", request.Path)
}
if request.ContentType != "application/json" {
t.Fatalf("content-type=%s", request.ContentType)
}
if request.Authorization != "Bearer target-owner-token" {
t.Fatalf("authorization=%s", request.Authorization)
}
if request.Body["apiVersion"] != SwBlockVolumeAPIVersion || request.Body["kind"] != SwBlockReplicaRebuildKind {
t.Fatalf("body identity=%+v", request.Body)
}
metadata := request.Body["metadata"].(map[string]any)
if metadata["name"] != "demo-pvc-r2-rebuild" || metadata["namespace"] != "kube-system" {
t.Fatalf("metadata=%+v", metadata)
}
spec := request.Body["spec"].(map[string]any)
if spec["volumeName"] != "demo-pvc" ||
spec["volumeID"] != "pvc-demo" ||
spec["pvcName"] != "demo-pvc" ||
spec["replicaID"] != "r2" {
t.Fatalf("spec=%+v", spec)
}
if _, ok := request.Body["status"]; ok {
t.Fatalf("target create must not include status: %+v", request.Body)
}
}
func TestKubernetesEventNameSeparatesTypeAndReason(t *testing.T) {
base := OperatorKubernetesEvent{
InvolvedObject: OperatorObjectRef{Name: "demo-pvc"},
@@ -0,0 +1,141 @@
package ops
import (
"context"
"fmt"
"strings"
"time"
)
type RebuildTargetOwnerClient interface {
ListSwBlockVolumes(ctx context.Context, namespace string) ([]SwBlockVolumeObject, error)
ListSwBlockReplicaRebuilds(ctx context.Context, namespace string) ([]SwBlockReplicaRebuildObject, error)
CreateSwBlockReplicaRebuild(ctx context.Context, namespace string, obj SwBlockReplicaRebuildObject) error
}
type RebuildTargetOwnerReconciler struct {
Namespace string
Client RebuildTargetOwnerClient
DryRun bool
Now func() time.Time
}
type RebuildTargetOwnerReconcileResult struct {
VolumeCount int `json:"volumeCount"`
ContractCount int `json:"contractCount"`
TargetPlannedCount int `json:"targetPlannedCount"`
TargetExistingCount int `json:"targetExistingCount"`
TargetCreateCount int `json:"targetCreateCount"`
InvalidContractCount int `json:"invalidContractCount"`
}
func (r RebuildTargetOwnerReconciler) Reconcile(ctx context.Context) (RebuildTargetOwnerReconcileResult, error) {
if r.Client == nil {
return RebuildTargetOwnerReconcileResult{}, fmt.Errorf("rebuild target owner client is required")
}
namespace := defaultString(r.Namespace, "default")
volumes, err := r.Client.ListSwBlockVolumes(ctx, namespace)
if err != nil {
return RebuildTargetOwnerReconcileResult{}, err
}
targets, err := r.Client.ListSwBlockReplicaRebuilds(ctx, namespace)
if err != nil {
return RebuildTargetOwnerReconcileResult{}, err
}
result := RebuildTargetOwnerReconcileResult{VolumeCount: len(volumes)}
for _, volume := range volumes {
for _, contract := range volume.Status.ExecutorContracts {
if contract.ActionType != ManagedVolumeActionRebuildReturned {
continue
}
result.ContractCount++
if !rebuildTargetOwnerContractReady(contract) {
result.InvalidContractCount++
continue
}
result.TargetPlannedCount++
if rebuildTargetOwnerHasTarget(volume, contract, targets) {
result.TargetExistingCount++
continue
}
obj := rebuildTargetOwnerObject(namespace, volume, contract)
if !r.DryRun {
if err := r.Client.CreateSwBlockReplicaRebuild(ctx, namespace, obj); err != nil {
return result, err
}
result.TargetCreateCount++
}
}
}
return result, nil
}
func rebuildTargetOwnerContractReady(contract SwBlockVolumeCRDExecutorContract) bool {
return contract.Decision == ReturnedReplicaExecutorContractDisabled &&
contract.Reason == ReturnedReplicaExecutorContractReasonExecutorDisabled &&
contract.PreflightDecision == ReturnedReplicaExecutorPreflightReady &&
contract.PreflightReason == ReturnedReplicaExecutorPreflightReasonSatisfied &&
authorityExecutorStringSliceContains(contract.AllowedMutationClass, AuthorityExecutorAllowedMutationRebuildTraffic) &&
contract.ReplicaID != ""
}
func rebuildTargetOwnerHasTarget(volume SwBlockVolumeObject, contract SwBlockVolumeCRDExecutorContract, targets []SwBlockReplicaRebuildObject) bool {
for _, target := range targets {
if target.Spec.ReplicaID != contract.ReplicaID {
continue
}
if target.Spec.VolumeName != "" && target.Spec.VolumeName == volume.Ref.Name {
return true
}
if target.Spec.VolumeID != "" && target.Spec.VolumeID == volume.Status.VolumeID {
return true
}
if target.Spec.PVCName != "" && target.Spec.PVCName == volume.Status.PVCName {
return true
}
}
return false
}
func rebuildTargetOwnerObject(namespace string, volume SwBlockVolumeObject, contract SwBlockVolumeCRDExecutorContract) SwBlockReplicaRebuildObject {
return SwBlockReplicaRebuildObject{
Ref: OperatorObjectRef{
APIVersion: SwBlockVolumeAPIVersion,
Kind: SwBlockReplicaRebuildKind,
Namespace: namespace,
Name: rebuildTargetOwnerName(volume.Ref.Name, contract.ReplicaID),
},
Spec: SwBlockReplicaRebuildSpec{
VolumeName: volume.Ref.Name,
VolumeID: volume.Status.VolumeID,
PVCName: volume.Status.PVCName,
ReplicaID: contract.ReplicaID,
},
}
}
func rebuildTargetOwnerName(volumeName, replicaID string) string {
name := strings.ToLower(strings.TrimSpace(volumeName + "-" + replicaID + "-rebuild"))
var b strings.Builder
lastDash := false
for _, r := range name {
ok := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
if ok {
b.WriteRune(r)
lastDash = false
continue
}
if !lastDash {
b.WriteByte('-')
lastDash = true
}
}
out := strings.Trim(b.String(), "-")
if out == "" {
return "rebuild-target"
}
if len(out) > 63 {
out = strings.TrimRight(out[:63], "-")
}
return out
}
@@ -0,0 +1,153 @@
package ops
import (
"context"
"testing"
)
func TestRebuildTargetOwnerDryRunPlansTargetWithoutCreate(t *testing.T) {
client := &fakeRebuildTargetOwnerClient{
volumes: []SwBlockVolumeObject{rebuildTargetOwnerTestVolume()},
}
result, err := (RebuildTargetOwnerReconciler{
Namespace: "kube-system",
Client: client,
DryRun: true,
}).Reconcile(context.Background())
if err != nil {
t.Fatalf("reconcile: %v", err)
}
if result.VolumeCount != 1 ||
result.ContractCount != 1 ||
result.TargetPlannedCount != 1 ||
result.TargetCreateCount != 0 ||
result.InvalidContractCount != 0 {
t.Fatalf("result=%+v", result)
}
if len(client.creates) != 0 {
t.Fatalf("dry-run created targets: %+v", client.creates)
}
}
func TestRebuildTargetOwnerCreatesMissingTarget(t *testing.T) {
client := &fakeRebuildTargetOwnerClient{
volumes: []SwBlockVolumeObject{rebuildTargetOwnerTestVolume()},
}
result, err := (RebuildTargetOwnerReconciler{
Namespace: "kube-system",
Client: client,
}).Reconcile(context.Background())
if err != nil {
t.Fatalf("reconcile: %v", err)
}
if result.TargetCreateCount != 1 || result.TargetExistingCount != 0 {
t.Fatalf("result=%+v", result)
}
if len(client.creates) != 1 {
t.Fatalf("creates=%+v", client.creates)
}
created := client.creates[0]
if created.Ref.Name != "demo-pvc-r2-rebuild" ||
created.Ref.Namespace != "kube-system" ||
created.Spec.VolumeName != "demo-pvc" ||
created.Spec.VolumeID != "pvc-demo" ||
created.Spec.PVCName != "demo-pvc" ||
created.Spec.ReplicaID != "r2" {
t.Fatalf("created=%+v", created)
}
if created.Status.State != "" {
t.Fatalf("target owner must not pre-populate status: %+v", created.Status)
}
}
func TestRebuildTargetOwnerSkipsExistingTarget(t *testing.T) {
client := &fakeRebuildTargetOwnerClient{
volumes: []SwBlockVolumeObject{rebuildTargetOwnerTestVolume()},
rebuilds: []SwBlockReplicaRebuildObject{{
Ref: OperatorObjectRef{
Namespace: "kube-system",
Name: "existing",
},
Spec: SwBlockReplicaRebuildSpec{
VolumeName: "demo-pvc",
ReplicaID: "r2",
},
}},
}
result, err := (RebuildTargetOwnerReconciler{
Namespace: "kube-system",
Client: client,
}).Reconcile(context.Background())
if err != nil {
t.Fatalf("reconcile: %v", err)
}
if result.TargetExistingCount != 1 || result.TargetCreateCount != 0 {
t.Fatalf("result=%+v", result)
}
if len(client.creates) != 0 {
t.Fatalf("unexpected creates=%+v", client.creates)
}
}
func TestRebuildTargetOwnerRejectsInvalidContract(t *testing.T) {
volume := rebuildTargetOwnerTestVolume()
volume.Status.ExecutorContracts[0].AllowedMutationClass = []string{AuthorityExecutorAllowedMutationAckEligibility}
client := &fakeRebuildTargetOwnerClient{
volumes: []SwBlockVolumeObject{volume},
}
result, err := (RebuildTargetOwnerReconciler{
Namespace: "kube-system",
Client: client,
}).Reconcile(context.Background())
if err != nil {
t.Fatalf("reconcile: %v", err)
}
if result.InvalidContractCount != 1 ||
result.TargetPlannedCount != 0 ||
result.TargetCreateCount != 0 {
t.Fatalf("result=%+v", result)
}
}
func rebuildTargetOwnerTestVolume() SwBlockVolumeObject {
return SwBlockVolumeObject{
Ref: OperatorObjectRef{
APIVersion: SwBlockVolumeAPIVersion,
Kind: SwBlockVolumeKind,
Namespace: "kube-system",
Name: "demo-pvc",
},
Status: SwBlockVolumeCRDStatus{
VolumeID: "pvc-demo",
PVCName: "demo-pvc",
ExecutorContracts: []SwBlockVolumeCRDExecutorContract{{
ActionType: ManagedVolumeActionRebuildReturned,
ReplicaID: "r2",
Decision: ReturnedReplicaExecutorContractDisabled,
Reason: ReturnedReplicaExecutorContractReasonExecutorDisabled,
PreflightDecision: ReturnedReplicaExecutorPreflightReady,
PreflightReason: ReturnedReplicaExecutorPreflightReasonSatisfied,
AllowedMutationClass: []string{AuthorityExecutorAllowedMutationRebuildTraffic},
}},
},
}
}
type fakeRebuildTargetOwnerClient struct {
volumes []SwBlockVolumeObject
rebuilds []SwBlockReplicaRebuildObject
creates []SwBlockReplicaRebuildObject
}
func (f *fakeRebuildTargetOwnerClient) ListSwBlockVolumes(context.Context, string) ([]SwBlockVolumeObject, error) {
return append([]SwBlockVolumeObject(nil), f.volumes...), nil
}
func (f *fakeRebuildTargetOwnerClient) ListSwBlockReplicaRebuilds(context.Context, string) ([]SwBlockReplicaRebuildObject, error) {
return append([]SwBlockReplicaRebuildObject(nil), f.rebuilds...), nil
}
func (f *fakeRebuildTargetOwnerClient) CreateSwBlockReplicaRebuild(_ context.Context, _ string, obj SwBlockReplicaRebuildObject) error {
f.creates = append(f.creates, obj)
return nil
}
+115 -110
View File
@@ -1,4 +1,4 @@
# Current Plan: Phase 57 Rebuild Progress Target
# Current Plan: Phase 58 Rebuild Target Owner
Status: complete.
@@ -6,176 +6,181 @@ Branch target: `phase54-returned-replica-reintegration-executor`
## Goal
Phase 56 made returned-replica rebuild/catch-up visible as a disabled executor
contract:
Phase 57 added `SwBlockReplicaRebuild.status` as the narrow status target for
future returned-replica rebuild progress. That still required a target CR to
exist before the executor could write planned rebuild status.
Phase 58 adds the missing owner for that target:
```text
authority.rebuild_returned_replica
allowed_mutation_class=rebuild_traffic
execution_enabled=false
SwBlockVolume.status.executorContracts[]
actionType=authority.rebuild_returned_replica
allowedMutationClass=rebuild_traffic
preflight=ready
|
v
SwBlockReplicaRebuild.spec
volumeName / volumeID / pvcName / replicaID
```
Phase 57 adds the next bounded control-plane target for that future executor:
```text
SwBlockReplicaRebuild.status
```
The authority executor may write a narrow planned-progress status to that target
when explicitly enabled for `rebuild_traffic`, while still not starting data
movement, not publishing any frontend, not changing primary authority, and not
touching `SwBlockVolume.status`.
The target owner may create the `SwBlockReplicaRebuild` main object. It does
not write status, start rebuild traffic, publish a frontend, fail back a
replica, or change primary authority.
## Scope
In scope:
- Add `SwBlockReplicaRebuild` CRD as a narrow rebuild/catch-up status target.
- Add Kubernetes status-writer support for
`swblockreplicarebuilds/status`.
- Extend authority-executor execution mode with
`--allowed-mutation-class rebuild_traffic`.
- Write only a planned rebuild status:
- `state=planned`;
- `reasonCode=rebuild_progress_planned`;
- `rebuildTrafficStarted=false`;
- `noFrontendPublication=true`;
- `noCrossVolumeIdentityChange=true`.
- Keep ACK eligibility and rebuild progress as separate target CRDs and
separate mutation classes.
- Gate RBAC so the executor can only read rebuild targets and write their
`/status` subresource.
- Add a `rebuild-target-owner` reconciler.
- Add `sw-block ops rebuild-target-owner`.
- Add Kubernetes create support for `SwBlockReplicaRebuild` main objects.
- Package an optional Helm Deployment and narrow RBAC identity.
- Gate live RBAC:
- can read `SwBlockVolume`;
- can read/create `SwBlockReplicaRebuild`;
- cannot patch/update/delete rebuild targets;
- cannot write rebuild target status;
- cannot write `SwBlockVolume` status/finalizers;
- cannot mutate events, pods, PVCs, or storage classes.
Out of scope:
- No rebuild data movement.
- No WAL/block copy.
- No rebuild status write by the target owner.
- No frontend publication.
- No failback.
- No primary authority change.
- No `SwBlockVolume.status` writes by authority-executor.
- No automatic creation of rebuild targets by this phase.
- No cross-volume mutation.
## Deliverables
### D1: SwBlockReplicaRebuild CRD
### D1: Rebuild Target Owner Controller
Status: implemented locally.
Add a namespaced `SwBlockReplicaRebuild` CRD with:
- spec identity:
- `volumeName`;
- `volumeID`;
- `pvcName`;
- `replicaID`;
- `sourceReplicaID`;
- status evidence:
- observed time/generation;
- executor;
- state/reason;
- durable and required frontier;
- frontend-fenced-before-rebuild;
- primary-unchanged;
- rebuild-traffic-started;
- no-frontend-publication;
- no-cross-volume-identity-change;
- conditions/evidence/non-claims.
### D2: Executor Planned-Status Write
Status: implemented locally.
When all of these are true:
- execution is explicitly requested;
- execution policy is explicitly enabled;
- allowed mutation class is `rebuild_traffic`;
- the volume has a disabled `authority.rebuild_returned_replica` contract;
- rebuild preflight is ready;
- the target `SwBlockReplicaRebuild` exists and matches volume + replica;
the executor writes:
The controller lists `SwBlockVolume` objects and existing
`SwBlockReplicaRebuild` targets. It creates one target only when a volume has a
ready disabled rebuild contract:
```text
SwBlockReplicaRebuild.status.state=planned
SwBlockReplicaRebuild.status.reasonCode=rebuild_progress_planned
SwBlockReplicaRebuild.status.rebuildTrafficStarted=false
SwBlockReplicaRebuild.status.noFrontendPublication=true
SwBlockReplicaRebuild.status.noCrossVolumeIdentityChange=true
actionType=authority.rebuild_returned_replica
decision=disabled
reason=executor_disabled
preflightDecision=ready
preflightReason=satisfied
allowedMutationClass contains rebuild_traffic
replicaID != ""
```
It does not write ACK eligibility, `SwBlockVolume.status`, Events, finalizers,
frontend state, or storage objects.
Existing targets are detected by volume identity plus replica ID and are not
duplicated.
### D3: RBAC Target Gate
### D2: CLI and Kubernetes Create Client
Status: implemented locally.
Added:
```text
sw-block ops rebuild-target-owner [--dry-run] [--namespace <ns>] [--interval 30s]
```
The command reports terminal evidence:
```text
rebuild_target_owner=target_mutation|dry_run
targets_planned=<n>
targets_existing=<n>
targets_created=<n>
invalid_contracts=<n>
storage_mutation_allowed=false
frontend_publication_allowed=false
failback_allowed=false
```
The Kubernetes client creates only the main `SwBlockReplicaRebuild` object with
`apiVersion`, `kind`, `metadata`, and `spec`; it does not include `status`.
### D3: Helm Packaging and RBAC
Status: implemented locally.
Added optional chart values:
```yaml
rebuildTargetOwner:
create: false
dryRun: true
interval: 30s
```
The packaged identity is intentionally separate from authority-executor:
- `rebuild-target-owner`: creates target CRs only;
- `authority-executor`: writes target `/status` only.
### D4: Runner RBAC Gate
Status: QA PASS.
Added:
- `scripts/run-phase57-authority-executor-rebuild-target-rbac-gate.sh`
- `testops/scenarios/authority-executor-rebuild-target-rbac-chain.yaml`
- `scripts/run-phase58-rebuild-target-owner-rbac-gate.sh`
- `testops/scenarios/rebuild-target-owner-rbac-chain.yaml`
The gate proves:
The live gate proves both `kubectl auth can-i` and runtime behavior:
- default authority-executor identity cannot patch
`swblockreplicarebuilds/status`;
- execution identity can get/list/watch `swblockreplicarebuilds`;
- execution identity can update/patch `swblockreplicarebuilds/status`;
- execution identity can actually patch a CRD-valid planned status payload;
- execution identity cannot patch main rebuild objects;
- execution identity cannot patch `SwBlockVolume.status`;
- execution identity cannot patch eligibility target status;
- execution identity cannot mutate events, pods, PVCs, or storage classes.
- default identity cannot create rebuild targets;
- owner identity can create one CRD-valid target;
- owner identity cannot patch the created target;
- created target has spec identity and empty status;
- owner identity cannot mutate status, Events, workloads, PVCs, or storage
classes.
## Verification
Current local checks:
Local checks:
```text
go test ./core/ops ./cmd/sw-block
go test ./core/ops ./cmd/sw-block ./scripts
helm lint charts/seaweed-block
swblock validate testops/scenarios/authority-executor-rebuild-target-rbac-chain.yaml
swblock validate testops/scenarios/rebuild-target-owner-rbac-chain.yaml
```
QA gate:
Live gate:
```text
swblock run testops/scenarios/authority-executor-rebuild-target-rbac-chain.yaml
swblock run testops/scenarios/rebuild-target-owner-rbac-chain.yaml
```
Expected terminal evidence:
```text
phase57_authority_executor_rebuild_target_rbac_status=ok
default_patch_swblockreplicarebuilds_status_denied=no
exec_patch_swblockreplicarebuilds_status_allowed=yes
exec_patch_swblockreplicarebuilds_main_denied=no
exec_patch_swblockvolumes_status_denied=no
exec_patch_swblockreplicaeligibilities_status_denied=no
exec_create_events_denied=no
default_rebuild_status_patch_runtime_denied=true
runtime_rebuild_status_state=planned
runtime_rebuild_status_reason=rebuild_progress_planned
runtime_rebuild_traffic_started=false
runtime_no_frontend_publication=true
phase58_rebuild_target_owner_rbac_status=ok
owner_create_swblockreplicarebuilds_allowed=yes
owner_create_rebuild_target_runtime_allowed=true
default_create_rebuild_target_runtime_denied=true
owner_patch_rebuild_target_runtime_denied=true
owner_patch_swblockreplicarebuilds_status_denied=no
owner_create_events_denied=no
runtime_rebuild_target_status_state=
```
## Exit
Phase 57 closes when the CRD/status writer/executor planned-status path is
locally verified and the runner proves the rebuild target RBAC boundary live.
The phase does not claim rebuild data movement.
Phase 58 closes when local tests pass and the runner proves the target owner can
create only rebuild target CRs, while all status, storage, frontend, workload,
and authority mutations remain denied.
Result:
```text
20260623-153515-68cf authority-executor-rebuild-target-rbac-chain PASS 26/26
20260623-164948-4735 rebuild-target-owner-rbac-chain PASS 18/18
```
Sign-off:
```text
internal/docs/qa-assignments/phase57-rebuild-progress-target-qa-signoff.md
internal/docs/qa-assignments/phase58-rebuild-target-owner-qa-signoff.md
```
@@ -0,0 +1,103 @@
# Phase 58 Finished Plan: Rebuild Target Owner
Status: complete.
Completed on: 2026-06-23.
Branch: `phase54-returned-replica-reintegration-executor`.
## What Changed
Phase 58 added the missing target-owner layer for returned-replica rebuild
planning:
```text
SwBlockVolume.status.executorContracts[]
|
v
rebuild-target-owner creates SwBlockReplicaRebuild.spec
|
v
authority-executor writes SwBlockReplicaRebuild.status
```
The owner creates a `SwBlockReplicaRebuild` target only when the existing
`SwBlockVolume.status.executorContracts[]` entry is a ready disabled
`authority.rebuild_returned_replica` contract with
`allowedMutationClass=rebuild_traffic`.
## Product Boundary
This phase intentionally claims only target creation.
Non-claims:
- no rebuild data movement;
- no WAL/block copy;
- no rebuild status write by the target owner;
- no frontend publication;
- no failback;
- no primary authority change;
- no cross-volume mutation.
## Deliverables
- `core/ops/rebuild_target_owner_controller.go`
- plans and creates rebuild target CRs;
- skips existing targets;
- rejects invalid contracts.
- `sw-block ops rebuild-target-owner`
- supports `--dry-run`, `--namespace`, and `--interval`;
- emits terminal evidence for planned/existing/created/invalid counts.
- `KubernetesStatusClient.CreateSwBlockReplicaRebuild`
- POSTs the target main object;
- sends only `apiVersion`, `kind`, `metadata`, and `spec`;
- never sends `status`.
- Helm packaging:
- optional `rebuildTargetOwner.create`;
- default disabled and dry-run;
- narrow ServiceAccount/RBAC.
- Runner gate:
- `scripts/run-phase58-rebuild-target-owner-rbac-gate.sh`;
- `testops/scenarios/rebuild-target-owner-rbac-chain.yaml`.
## Verification
Local:
```text
go test ./core/ops ./cmd/sw-block ./scripts
helm lint charts/seaweed-block
swblock validate testops/scenarios/rebuild-target-owner-rbac-chain.yaml
```
Live:
```text
20260623-164948-4735 rebuild-target-owner-rbac-chain PASS 18/18
```
Key terminal evidence:
```text
owner_create_swblockreplicarebuilds_allowed=yes
owner_create_rebuild_target_runtime_allowed=true
default_create_rebuild_target_runtime_denied=true
owner_patch_rebuild_target_runtime_denied=true
owner_patch_swblockreplicarebuilds_status_denied=no
owner_create_events_denied=no
runtime_rebuild_target_status_state=
```
## Result
Phase 58 closes the rebuild target lifecycle gap before real rebuild traffic.
The control-plane chain now has separate bounded identities:
- target owner: creates rebuild target CRs;
- authority executor: writes rebuild target status;
- no component in this phase starts data movement or changes authority.
Next logical step: decide whether to add a read-only rebuild progress surface
for user/operator visibility or move toward the first real rebuild data-path
primitive behind an explicit gate.
@@ -0,0 +1,91 @@
# Phase 58 Rebuild Target Owner QA Sign-off
Status: PASS.
Validated on: 2026-06-23.
Source: local Phase 58 tree on
`phase54-returned-replica-reintegration-executor`.
Runner evidence:
```text
20260623-164948-4735 rebuild-target-owner-rbac-chain PASS 18/18
```
## Scope
Phase 58 adds the bounded owner that creates `SwBlockReplicaRebuild` target
CRs for ready `authority.rebuild_returned_replica` executor contracts.
This phase does not start rebuild traffic, write rebuild status, publish a
frontend, fail back a replica, or change primary authority.
## Local Checks
```text
go test ./core/ops ./cmd/sw-block ./scripts
helm lint charts/seaweed-block
swblock validate testops/scenarios/rebuild-target-owner-rbac-chain.yaml
```
All passed.
## Live Gate
Scenario:
```text
testops/scenarios/rebuild-target-owner-rbac-chain.yaml
```
Result:
```text
=== rebuild-target-owner-rbac-chain === PASS (10.647s)
18 actions: 18 passed, 0 failed
```
Terminal evidence:
```text
phase58_rebuild_target_owner_rbac_status=ok
default_get_swblockvolumes_allowed=yes
default_create_swblockreplicarebuilds_denied=no
default_patch_swblockreplicarebuilds_status_denied=no
owner_get_swblockvolumes_allowed=yes
owner_get_swblockreplicarebuilds_allowed=yes
owner_create_swblockreplicarebuilds_allowed=yes
owner_patch_swblockreplicarebuilds_main_denied=no
owner_update_swblockreplicarebuilds_denied=no
owner_delete_swblockreplicarebuilds_denied=no
owner_patch_swblockreplicarebuilds_status_denied=no
owner_patch_swblockvolumes_denied=no
owner_patch_swblockvolumes_status_denied=no
owner_patch_swblockvolumes_finalizers_denied=no
owner_create_events_denied=no
owner_create_pods_denied=no
owner_patch_pvc_denied=no
owner_update_storageclass_denied=no
default_create_rebuild_target_runtime_denied=true
owner_create_rebuild_target_runtime_allowed=true
owner_patch_rebuild_target_runtime_denied=true
runtime_rebuild_target_volume_name=phase58-volume
runtime_rebuild_target_volume_id=pvc-phase58
runtime_rebuild_target_pvc_name=phase58-pvc
runtime_rebuild_target_replica_id=r2
runtime_rebuild_target_status_state=
```
## Verdict
PASS.
The rebuild target owner can create only `SwBlockReplicaRebuild` main objects
and cannot mutate target status, volume status/finalizers, events, pods, PVCs,
or storage classes. The created target carries only spec identity; status
remains empty until the authority executor writes planned progress in a
separate mutation class.
Lab residue check after the run showed no Phase 58 namespace, RBAC, or
temporary CRDs remaining.
@@ -0,0 +1,231 @@
#!/usr/bin/env bash
set -euo pipefail
PRODUCT_ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${PRODUCT_ROOT}/results/phase58-rebuild-target-owner-rbac-gate}"
KUBECTL="${KUBECTL:-kubectl}"
NAMESPACE="${SW_BLOCK_PHASE58_NAMESPACE:-sw-block-phase58-rebuild-target-owner}"
DEFAULT_SA="sw-block-rebuild-target-owner-default"
OWNER_SA="sw-block-rebuild-target-owner"
DEFAULT_USER="system:serviceaccount:${NAMESPACE}:${DEFAULT_SA}"
OWNER_USER="system:serviceaccount:${NAMESPACE}:${OWNER_SA}"
SUMMARY="${ARTIFACT_DIR}/phase58-rebuild-target-owner-rbac-summary.txt"
VOLUME_CRD="swblockvolumes.block.seaweedfs.com"
REBUILD_CRD="swblockreplicarebuilds.block.seaweedfs.com"
mkdir -p "${ARTIFACT_DIR}"
: >"${SUMMARY}"
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
run_capture() {
local name="$1"
shift
"$@" >"${ARTIFACT_DIR}/${name}.stdout.txt" 2>"${ARTIFACT_DIR}/${name}.stderr.txt"
}
run_expect_success() {
local name="$1"
shift
if run_capture "$name" "$@"; then
return 0
fi
echo "expected success for ${name}" >&2
cat "${ARTIFACT_DIR}/${name}.stderr.txt" >&2 || true
return 1
}
can_i_as() {
local user="$1"
local name="$2"
local expected="$3"
shift 3
run_capture "can-i-${name}" "${KUBECTL}" auth can-i "$@" --as "${user}" -n "${NAMESPACE}" || true
local actual
actual="$(tr -d '\r\n' <"${ARTIFACT_DIR}/can-i-${name}.stdout.txt")"
write_summary "${name}=${actual}"
if [ "${actual}" != "${expected}" ]; then
echo "unexpected can-i ${name}: got ${actual}, expected ${expected}" >&2
return 1
fi
}
crd_preexisting() {
local crd="$1"
if "${KUBECTL}" get crd "${crd}" >/dev/null 2>&1; then
echo "true"
else
echo "false"
fi
}
PREEXISTING_VOLUME_CRD="$(crd_preexisting "${VOLUME_CRD}")"
PREEXISTING_REBUILD_CRD="$(crd_preexisting "${REBUILD_CRD}")"
cleanup() {
set +e
"${KUBECTL}" delete clusterrolebinding sw-block-phase58-rebuild-target-owner-default sw-block-phase58-rebuild-target-owner --ignore-not-found >/dev/null 2>&1
"${KUBECTL}" delete clusterrole sw-block-phase58-rebuild-target-owner-default sw-block-phase58-rebuild-target-owner --ignore-not-found >/dev/null 2>&1
"${KUBECTL}" delete namespace "${NAMESPACE}" --ignore-not-found >/dev/null 2>&1
if [ "${PREEXISTING_REBUILD_CRD}" != "true" ]; then
"${KUBECTL}" delete crd "${REBUILD_CRD}" --ignore-not-found >/dev/null 2>&1
fi
if [ "${PREEXISTING_VOLUME_CRD}" != "true" ]; then
"${KUBECTL}" delete crd "${VOLUME_CRD}" --ignore-not-found >/dev/null 2>&1
fi
}
trap cleanup EXIT
write_summary "phase58_rebuild_target_owner_rbac_status=running"
write_summary "preexisting_volume_crd=${PREEXISTING_VOLUME_CRD}"
write_summary "preexisting_rebuild_crd=${PREEXISTING_REBUILD_CRD}"
run_expect_success kubectl-version "${KUBECTL}" version --client=true
run_expect_success apply-volume-crd "${KUBECTL}" apply -f "${PRODUCT_ROOT}/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml"
run_expect_success apply-rebuild-crd "${KUBECTL}" apply -f "${PRODUCT_ROOT}/charts/seaweed-block/crds/swblockreplicarebuilds.block.seaweedfs.com.yaml"
cat >"${ARTIFACT_DIR}/namespace.yaml" <<YAML
apiVersion: v1
kind: Namespace
metadata:
name: ${NAMESPACE}
labels:
block.seaweedfs.com/phase58-gate: "true"
YAML
run_expect_success apply-namespace "${KUBECTL}" apply -f "${ARTIFACT_DIR}/namespace.yaml"
cat >"${ARTIFACT_DIR}/rbac.yaml" <<YAML
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${DEFAULT_SA}
namespace: ${NAMESPACE}
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${OWNER_SA}
namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: sw-block-phase58-rebuild-target-owner-default
rules:
- apiGroups: ["block.seaweedfs.com"]
resources: ["swblockvolumes"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: sw-block-phase58-rebuild-target-owner
rules:
- apiGroups: ["block.seaweedfs.com"]
resources: ["swblockvolumes"]
verbs: ["get", "list", "watch"]
- apiGroups: ["block.seaweedfs.com"]
resources: ["swblockreplicarebuilds"]
verbs: ["get", "list", "watch", "create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: sw-block-phase58-rebuild-target-owner-default
subjects:
- kind: ServiceAccount
name: ${DEFAULT_SA}
namespace: ${NAMESPACE}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: sw-block-phase58-rebuild-target-owner-default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: sw-block-phase58-rebuild-target-owner
subjects:
- kind: ServiceAccount
name: ${OWNER_SA}
namespace: ${NAMESPACE}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: sw-block-phase58-rebuild-target-owner
YAML
run_expect_success apply-rbac "${KUBECTL}" apply -f "${ARTIFACT_DIR}/rbac.yaml"
cat >"${ARTIFACT_DIR}/rebuild-target.yaml" <<YAML
apiVersion: block.seaweedfs.com/v1alpha1
kind: SwBlockReplicaRebuild
metadata:
name: phase58-rebuild-r2
namespace: ${NAMESPACE}
spec:
volumeName: phase58-volume
volumeID: pvc-phase58
pvcName: phase58-pvc
replicaID: r2
YAML
can_i_as "${DEFAULT_USER}" "default_get_swblockvolumes_allowed" "yes" get swblockvolumes
can_i_as "${DEFAULT_USER}" "default_create_swblockreplicarebuilds_denied" "no" create swblockreplicarebuilds
can_i_as "${DEFAULT_USER}" "default_patch_swblockreplicarebuilds_status_denied" "no" patch swblockreplicarebuilds --subresource=status
can_i_as "${OWNER_USER}" "owner_get_swblockvolumes_allowed" "yes" get swblockvolumes
can_i_as "${OWNER_USER}" "owner_get_swblockreplicarebuilds_allowed" "yes" get swblockreplicarebuilds
can_i_as "${OWNER_USER}" "owner_create_swblockreplicarebuilds_allowed" "yes" create swblockreplicarebuilds
can_i_as "${OWNER_USER}" "owner_patch_swblockreplicarebuilds_main_denied" "no" patch swblockreplicarebuilds
can_i_as "${OWNER_USER}" "owner_update_swblockreplicarebuilds_denied" "no" update swblockreplicarebuilds
can_i_as "${OWNER_USER}" "owner_delete_swblockreplicarebuilds_denied" "no" delete swblockreplicarebuilds
can_i_as "${OWNER_USER}" "owner_patch_swblockreplicarebuilds_status_denied" "no" patch swblockreplicarebuilds --subresource=status
can_i_as "${OWNER_USER}" "owner_patch_swblockvolumes_denied" "no" patch swblockvolumes
can_i_as "${OWNER_USER}" "owner_patch_swblockvolumes_status_denied" "no" patch swblockvolumes --subresource=status
can_i_as "${OWNER_USER}" "owner_patch_swblockvolumes_finalizers_denied" "no" patch swblockvolumes --subresource=finalizers
can_i_as "${OWNER_USER}" "owner_create_events_denied" "no" create events
can_i_as "${OWNER_USER}" "owner_create_pods_denied" "no" create pods
can_i_as "${OWNER_USER}" "owner_patch_pvc_denied" "no" patch pvc
can_i_as "${OWNER_USER}" "owner_update_storageclass_denied" "no" update storageclasses
if run_capture "default-create-rebuild-target" "${KUBECTL}" create -f "${ARTIFACT_DIR}/rebuild-target.yaml" --as "${DEFAULT_USER}"; then
write_summary "default_create_rebuild_target_runtime_denied=false"
echo "default identity unexpectedly created rebuild target" >&2
exit 1
else
write_summary "default_create_rebuild_target_runtime_denied=true"
fi
run_expect_success owner-create-rebuild-target "${KUBECTL}" create -f "${ARTIFACT_DIR}/rebuild-target.yaml" --as "${OWNER_USER}"
write_summary "owner_create_rebuild_target_runtime_allowed=true"
if run_capture "owner-patch-rebuild-target" "${KUBECTL}" patch swblockreplicarebuilds phase58-rebuild-r2 -n "${NAMESPACE}" --type=merge --as "${OWNER_USER}" -p '{"spec":{"replicaID":"changed"}}'; then
write_summary "owner_patch_rebuild_target_runtime_denied=false"
echo "owner identity unexpectedly patched rebuild target" >&2
exit 1
else
write_summary "owner_patch_rebuild_target_runtime_denied=true"
fi
run_expect_success get-rebuild-target "${KUBECTL}" get swblockreplicarebuilds phase58-rebuild-r2 -n "${NAMESPACE}" -o jsonpath='{.spec.volumeName}{"\n"}{.spec.volumeID}{"\n"}{.spec.pvcName}{"\n"}{.spec.replicaID}{"\n"}{.status.state}{"\n"}'
mapfile -t target_lines <"${ARTIFACT_DIR}/get-rebuild-target.stdout.txt"
write_summary "runtime_rebuild_target_volume_name=${target_lines[0]:-}"
write_summary "runtime_rebuild_target_volume_id=${target_lines[1]:-}"
write_summary "runtime_rebuild_target_pvc_name=${target_lines[2]:-}"
write_summary "runtime_rebuild_target_replica_id=${target_lines[3]:-}"
write_summary "runtime_rebuild_target_status_state=${target_lines[4]:-}"
if [ "${target_lines[0]:-}" != "phase58-volume" ] ||
[ "${target_lines[1]:-}" != "pvc-phase58" ] ||
[ "${target_lines[2]:-}" != "phase58-pvc" ] ||
[ "${target_lines[3]:-}" != "r2" ] ||
[ "${target_lines[4]:-}" != "" ]; then
echo "unexpected rebuild target payload" >&2
cat "${ARTIFACT_DIR}/get-rebuild-target.stdout.txt" >&2 || true
exit 1
fi
write_summary "phase58_rebuild_target_owner_rbac_status=ok"
@@ -0,0 +1,96 @@
# Runner-native Phase 58 gate: rebuild-target-owner target-create RBAC boundary.
name: rebuild-target-owner-rbac-chain
timeout: 5m
env:
product_root: "/tmp/seaweed_block"
ssh_key: "C:\\work\\dev_server\\testdev_key"
topology:
nodes:
m02:
host: 192.168.1.184
user: testdev
key: "{{ ssh_key }}"
phases:
- name: rebuild_target_owner_rbac_gate
actions:
- action: exec
node: m02
timeout: 4m
cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac && cd {{ product_root }} && SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac bash scripts/run-phase58-rebuild-target-owner-rbac-gate.sh {{ product_root }}"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^phase58_rebuild_target_owner_rbac_status=ok$"
save_as: phase58_rbac_ok
- action: assert_greater
actual: "{{ phase58_rbac_ok }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^owner_create_swblockreplicarebuilds_allowed=yes$"
save_as: owner_create_allowed
- action: assert_greater
actual: "{{ owner_create_allowed }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^owner_create_rebuild_target_runtime_allowed=true$"
save_as: owner_runtime_create_allowed
- action: assert_greater
actual: "{{ owner_runtime_create_allowed }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^default_create_rebuild_target_runtime_denied=true$"
save_as: default_runtime_create_denied
- action: assert_greater
actual: "{{ default_runtime_create_denied }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^owner_patch_rebuild_target_runtime_denied=true$"
save_as: owner_runtime_patch_denied
- action: assert_greater
actual: "{{ owner_runtime_patch_denied }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^owner_patch_swblockreplicarebuilds_status_denied=no$"
save_as: owner_target_status_denied
- action: assert_greater
actual: "{{ owner_target_status_denied }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^owner_create_events_denied=no$"
save_as: owner_events_denied
- action: assert_greater
actual: "{{ owner_events_denied }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac/phase58-rebuild-target-owner-rbac-summary.txt"
pattern: "^runtime_rebuild_target_status_state=$"
save_as: target_status_empty
- action: assert_greater
actual: "{{ target_status_empty }}"
threshold: "0"
- name: collect
always: true
actions:
- action: collect_path
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase58-rebuild-target-owner-rbac"
name: "remote-phases"
ignore_error: true