Skip to content

Commit ab58c71

Browse files
authored
feat(storage): retire the verified Longhorn V2 restore canary (#6680)
* feat(storage): retire the verified Longhorn V2 restore canary (cherry picked from commit 2e709f2db8c2af6bf5d001163e3b00c5cd8cc955) (cherry picked from commit e3ad4ee55e3aff6db49412001a5996805b796e0e) * test(storage): read the canary outcome outside reclaim authorization (cherry picked from commit fc1fb5bc358f7b3bb1d19fa4a408ba400b8f1bc3) (cherry picked from commit 63f3538c8a5b517c028178816b50eea3087c4fec) * fix(storage): bind canary retirement to all restore attempts (cherry picked from commit 0ec60f0b403cfa5757e0fa0c127157688e55f6c8) * fix(storage): recheck the serving fences and claims before canary retirement
1 parent 0ab30ce commit ab58c71

32 files changed

Lines changed: 1883 additions & 77 deletions

‎.github/workflows/prepare-longhorn-v2-node.yaml‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ name: Prepare Longhorn V2 Migration
3535
restore-native-v2-seed,
3636
resume-native-v2-seed-restore,
3737
resume-native-v2-reattach,
38+
reclaim-native-v2-seed,
3839
inventory-replicas,
3940
inventory-storage-root,
4041
inventory-storage-layout,
@@ -157,6 +158,9 @@ jobs:
157158
[[ -z "${LONGHORN_V2_NODE}" && -z "${LONGHORN_V2_DATABASE}" &&
158159
"${LONGHORN_V2_CONFIRM}" =~ ^resume-longhorn-native-v2-reattach:[1-9][0-9]{0,18}:[1-9][0-9]{0,18}$ ]]
159160
;;
161+
reclaim-native-v2-seed)
162+
[[ -z "${LONGHORN_V2_NODE}" && -z "${LONGHORN_V2_DATABASE}" && "${LONGHORN_V2_CONFIRM}" =~ ^reclaim-longhorn-native-v2-seed:[1-9][0-9]{0,18}$ ]]
163+
;;
160164
inventory-v1-runtime)
161165
[[ -z "${LONGHORN_V2_NODE}" && -z "${LONGHORN_V2_DATABASE}" && "${LONGHORN_V2_CONFIRM}" == inventory-v1-runtime ]]
162166
;;
@@ -282,7 +286,7 @@ jobs:
282286
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN }}
283287
run: ./scripts/use-prod-stable-api-endpoint.sh
284288
- name: Run the confirmed migration preparation
285-
if: ${{ inputs.operation != 'benchmark-v1' && inputs.operation != 'recover-bound-v1-benchmark' && inputs.operation != 'prepare-native-v1-seed' }}
289+
if: ${{ inputs.operation != 'benchmark-v1' && inputs.operation != 'recover-bound-v1-benchmark' && inputs.operation != 'prepare-native-v1-seed' && inputs.operation != 'reclaim-native-v2-seed' }}
286290
env:
287291
GH_TOKEN: ${{ github.token }}
288292
LONGHORN_RUNTIME_INVENTORY_SOURCE: ${{ steps.recovery-source.outputs.sha }}
@@ -299,6 +303,12 @@ jobs:
299303
GH_TOKEN: ${{ github.token }}
300304
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN }}
301305
run: go run ./scripts/migrate-longhorn-v2
306+
- name: Reclaim the verified disposable V2 restoration
307+
if: ${{ inputs.operation == 'reclaim-native-v2-seed' }}
308+
env:
309+
GH_TOKEN: ${{ github.token }}
310+
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN }}
311+
run: go run ./scripts/migrate-longhorn-v2
302312
- name: Remove runner credentials
303313
if: ${{ always() }}
304314
shell: bash

‎internal/namespaceinventory/benchmark_recovery_credentials_test.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,19 @@ func TestBenchmarkAdmissionCredentialsRequireTheConfirmedOriginalRun(t *testing.
2929
t.Fatalf("ordinary benchmark did not reach the private credential check: %v", err)
3030
}
3131
})
32+
t.Run("native restore reclaim", func(t *testing.T) {
33+
values := maps.Clone(env)
34+
values["LONGHORN_V2_OPERATION"] = "reclaim-native-v2-seed"
35+
values["LONGHORN_V2_CONFIRM"] = "reclaim-longhorn-native-v2-seed:1234"
36+
getenv := func(key string) string { return values[key] }
37+
if _, _, err := LoadBenchmarkAdmissionClient(getenv, peer, "1234"); err == nil || err.Error() != "credential directory is not private" {
38+
t.Fatalf("confirmed reclaim did not reach the private credential check: %v", err)
39+
}
40+
values["LONGHORN_V2_CONFIRM"] = env["LONGHORN_V2_CONFIRM"]
41+
if _, _, err := LoadBenchmarkAdmissionClient(getenv, peer, "1234"); err == nil || err.Error() != "protected benchmark admission dispatch is unverified" {
42+
t.Fatalf("borrowed V1 confirmation reached reclaim credentials: %v", err)
43+
}
44+
})
3245
for _, tc := range []struct {
3346
name, original, key, value, want string
3447
}{

‎internal/namespaceinventory/credentials.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ func LoadBenchmarkAdmissionClient(getenv func(string) string, directIP netip.Add
7777
return nil, nil, errors.New("protected benchmark admission dispatch is unverified")
7878
}
7979
operation, confirmation = "recover-bound-v1-benchmark", "recover-bound-longhorn-v1-benchmark:"+originalRun
80+
if getenv("LONGHORN_V2_OPERATION") == "reclaim-native-v2-seed" {
81+
operation, confirmation = "reclaim-native-v2-seed", "reclaim-longhorn-native-v2-seed:"+originalRun
82+
}
8083
case getenv("LONGHORN_V2_OPERATION") == "prepare-native-v1-seed":
8184
operation, confirmation = "prepare-native-v1-seed", "prepare-longhorn-native-v1-seed"
8285
}

‎internal/namespaceinventory/credentials_test.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ func TestAdmissionLoaderBuildsConfirmedClientsFromPrivateMemoryCredentials(t *te
274274
{operation: "benchmark-v1", confirmation: "benchmark-longhorn-storage"},
275275
{operation: "prepare-native-v1-seed", confirmation: "prepare-longhorn-native-v1-seed"},
276276
{operation: "recover-bound-v1-benchmark", confirmation: "recover-bound-longhorn-v1-benchmark:99", originalRun: "99"},
277+
{operation: "reclaim-native-v2-seed", confirmation: "reclaim-longhorn-native-v2-seed:99", originalRun: "99"},
277278
} {
278279
valid := nativeSeedAdmissionDispatch()
279280
valid["LONGHORN_V2_OPERATION"], valid["LONGHORN_V2_CONFIRM"] = dispatch.operation, dispatch.confirmation

‎scripts/migrate-longhorn-v2/README.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,23 @@ Leave `node` and `database` empty. The protected operation verifies the failed
516516
executor and the never-started Pod, replaces that test Pod and checks the
517517
original payload and previously written marker on the remaining qualified worker.
518518

519+
After independently verifying the successful restore and reattachment, select
520+
`reclaim-native-v2-seed` and confirm it with
521+
`reclaim-longhorn-native-v2-seed:<original restore run ID>`. Leave the node and
522+
database fields empty. The operation binds the original off-cluster seed and
523+
the successful first attempt of the restore or its recorded continuation. It
524+
waits for the canary consumer to leave and for the backend to detach. It verifies
525+
admission on every serving API before changing the bound disposable PV's reclaim
526+
policy.
527+
528+
The original claim is removed only after the CSI provisioner has installed its
529+
deletion finalizer. Verify the PV, backend, replicas and attachment references
530+
have retired. The operation removes the canary's policies, class and workload
531+
tags and verifies the seed backup again. The restore and reclaim journals and
532+
the object-store restore logs provide the audit record. If any action cannot be
533+
confirmed, inspect the reclaim journal and the exact recorded resources before
534+
recovering it.
535+
519536
## Prepare a permanent worker
520537

521538
`prepare-worker` rebuilds one permanent worker's local disk so it can hold V2 replicas. It wipes

‎scripts/migrate-longhorn-v2/benchmark_admission_probe.go‎

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -49,45 +49,63 @@ func proveBenchmarkReferenceFenceOnServingAPIs(ctx context.Context, c client, re
4949
}
5050

5151
func proveBenchmarkFenceOnServingAPIs(ctx context.Context, c client, record benchmarkRecord, policy object, receipt benchmarkFenceReceipt, probe func(context.Context, *http.Client, *url.URL) error) error {
52-
source := record.mutationSource()
52+
originalRun := ""
53+
if record.Recovery != nil {
54+
originalRun = record.Run
55+
}
56+
return proveReferenceFenceOnServingAPIs(ctx, c, record.mutationSource(), originalRun, policy, receipt, probe)
57+
}
58+
59+
func proveReferenceFenceOnServingAPIs(ctx context.Context, c client, source, originalRun string, policy object, receipt benchmarkFenceReceipt, probe func(context.Context, *http.Client, *url.URL) error) error {
60+
_, err := proveReferenceFenceForRoster(ctx, c, source, originalRun, policy, receipt, nil, probe)
61+
return err
62+
}
63+
64+
func proveReferenceFenceForRoster(ctx context.Context, c client, source, originalRun string, policy object, receipt benchmarkFenceReceipt, expected []benchmarkAPIServer, probe func(context.Context, *http.Client, *url.URL) error) (benchmarkAdmissionEpoch, error) {
5365
if err := sourceCurrent(ctx, c.run, source); err != nil {
54-
return err
66+
return benchmarkAdmissionEpoch{}, err
5567
}
5668
before, err := observeBenchmarkReferenceFence(ctx, c, policy, receipt)
5769
if err != nil {
58-
return err
70+
return benchmarkAdmissionEpoch{}, err
5971
}
6072
roster, err := observeBenchmarkAPIServers(ctx, c)
6173
if err != nil {
62-
return err
74+
return benchmarkAdmissionEpoch{}, err
6375
}
64-
if err := verifyBenchmarkProviderEndpoints(ctx, os.Getenv("HCLOUD_TOKEN"), roster); err != nil {
65-
return err
76+
if expected != nil && !slices.Equal(expected, roster) {
77+
return benchmarkAdmissionEpoch{}, errors.New("serving API processes changed between admission proofs")
6678
}
67-
originalRun := ""
68-
if record.Recovery != nil {
69-
originalRun = record.Run
79+
if err := verifyBenchmarkProviderEndpoints(ctx, os.Getenv("HCLOUD_TOKEN"), roster); err != nil {
80+
return benchmarkAdmissionEpoch{}, err
7081
}
7182
for _, endpoint := range roster {
7283
direct, address, err := namespaceinventory.LoadBenchmarkAdmissionClient(os.Getenv, endpoint.ExternalIP, originalRun)
7384
if err != nil {
74-
return err
85+
return benchmarkAdmissionEpoch{}, err
7586
}
7687
proof := probe(ctx, direct, address)
7788
direct.CloseIdleConnections()
7889
if proof != nil {
79-
return proof
90+
return benchmarkAdmissionEpoch{}, proof
8091
}
8192
}
82-
after, err := observeBenchmarkAPIServers(ctx, c)
83-
if err != nil || !slices.Equal(roster, after) {
84-
return errors.New("serving API processes changed during benchmark admission proof")
93+
if err := rebindBenchmarkAPIServers(ctx, c, roster); err != nil {
94+
return benchmarkAdmissionEpoch{}, err
8595
}
8696
bound, err := observeBenchmarkReferenceFence(ctx, c, policy, receipt)
8797
if err != nil || before != bound {
88-
return errors.New("the benchmark reference fence changed during native admission proof")
98+
return benchmarkAdmissionEpoch{}, errors.New("the benchmark reference fence changed during native admission proof")
99+
}
100+
return before, sourceCurrent(ctx, c.run, source)
101+
}
102+
103+
func rebindBenchmarkAPIServers(ctx context.Context, c client, expected []benchmarkAPIServer) error {
104+
actual, err := observeBenchmarkAPIServers(ctx, c)
105+
if err != nil || len(expected) != benchmarkControlPlaneCount || !slices.Equal(expected, actual) {
106+
return errors.New("serving API processes changed during benchmark admission proof")
89107
}
90-
return sourceCurrent(ctx, c.run, source)
108+
return nil
91109
}
92110

93111
func observeBenchmarkReferenceFence(ctx context.Context, c client, desired object, receipt benchmarkFenceReceipt) (benchmarkAdmissionEpoch, error) {
@@ -182,22 +200,26 @@ func probeBenchmarkDetachedBackendAdmission(ctx context.Context, client *http.Cl
182200
// Keep the native response in bounded memory. The caller accepts only its
183201
// fixed object or admission-policy status and never emits the response.
184202
func benchmarkAdmissionDryRun(ctx context.Context, client *http.Client, endpoint *url.URL, path string, operations []object) (int, []byte, error) {
203+
return benchmarkAdmissionRequest(ctx, client, endpoint, path, http.MethodPatch, "application/json-patch+json", operations)
204+
}
205+
206+
func benchmarkAdmissionRequest(ctx context.Context, client *http.Client, endpoint *url.URL, path, method, contentType string, body any) (int, []byte, error) {
185207
const limit = 2 << 20
186208
unverified := errors.New("native admission dry-run did not return a bounded response")
187209
if client == nil || endpoint == nil || endpoint.Scheme != "https" || endpoint.Host == "" || endpoint.User != nil {
188210
return 0, nil, unverified
189211
}
190212
destination := url.URL{Scheme: "https", Host: endpoint.Host, Path: path, RawQuery: "dryRun=All"}
191-
payload, err := json.Marshal(operations)
213+
payload, err := json.Marshal(body)
192214
if err != nil {
193215
return 0, nil, unverified
194216
}
195-
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, destination.String(), bytes.NewReader(payload))
217+
req, err := http.NewRequestWithContext(ctx, method, destination.String(), bytes.NewReader(payload))
196218
if err != nil {
197219
return 0, nil, unverified
198220
}
199221
req.Header.Set("Accept", "application/json")
200-
req.Header.Set("Content-Type", "application/json-patch+json")
222+
req.Header.Set("Content-Type", contentType)
201223
res, err := client.Do(req)
202224
if err != nil {
203225
return 0, nil, unverified

‎scripts/migrate-longhorn-v2/benchmark_admission_roster_test.go‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,35 @@ func TestBenchmarkAdmissionRequiresEveryServingAPIServer(t *testing.T) {
9494
}
9595
}
9696

97+
func TestBenchmarkAdmissionRebindRejectsAReplacedServingProcess(t *testing.T) {
98+
nodes, pods, endpoints := benchmarkAdmissionFixture()
99+
expected, err := qualifyBenchmarkAPIServers(nodes, pods, endpoints)
100+
if err != nil {
101+
t.Fatal(err)
102+
}
103+
for _, changed := range []bool{false, true} {
104+
nodes, pods, endpoints := benchmarkAdmissionFixture()
105+
if changed {
106+
status := value(pods[0], "status", "containerStatuses").([]any)[0].(object)
107+
status["containerID"] = "containerd://" + strings.Repeat("a", 64)
108+
}
109+
calls := 0
110+
c := client{context: "admin@prod", run: func(_ context.Context, input []byte, binary string, args ...string) ([]byte, error) {
111+
if input != nil || binary != "kubectl" || len(args) != 4 || args[2] != "get" || calls >= 3 {
112+
t.Fatal("the serving roster check left its read-only scope")
113+
}
114+
api := []string{"v1", "v1", "discovery.k8s.io/v1"}[calls]
115+
kind := []string{"NodeList", "PodList", "EndpointSliceList"}[calls]
116+
items := [][]object{nodes, pods, endpoints}[calls]
117+
calls++
118+
return json.Marshal(object{"apiVersion": api, "kind": kind, "metadata": object{"resourceVersion": "150"}, "items": items})
119+
}}
120+
if err := rebindBenchmarkAPIServers(t.Context(), c, expected); (err != nil) != changed || calls != 3 {
121+
t.Fatalf("serving API rebind with changed process=%t returned %v after %d reads", changed, err, calls)
122+
}
123+
}
124+
}
125+
97126
func benchmarkAdmissionFixture() (nodes, pods, slices []object) {
98127
endpoints := make([]any, 0, 3)
99128
for i := 1; i <= 3; i++ {

‎scripts/migrate-longhorn-v2/benchmark_cleanup.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,18 @@ import (
99
// Native kubectl raw DELETE accepts DeleteOptions. Unlike name-only deletion,
1010
// the API atomically refuses changed or replaced objects through preconditions.
1111
func (c client) deleteObserved(ctx context.Context, source, path string, o object) error {
12+
return c.deleteObservedWithPropagation(ctx, source, path, o, "Foreground")
13+
}
14+
15+
func (c client) deleteObservedWithPropagation(ctx context.Context, source, path string, o object, propagation string) error {
1216
uid, version := text(o, "metadata", "uid"), text(o, "metadata", "resourceVersion")
1317
if uid == "" || version == "" {
1418
return errors.New("deletion requires the observed resource identity")
1519
}
1620
if err := sourceCurrent(ctx, c.run, source); err != nil {
1721
return err
1822
}
19-
body, err := json.Marshal(object{"apiVersion": "v1", "kind": "DeleteOptions", "propagationPolicy": "Foreground",
23+
body, err := json.Marshal(object{"apiVersion": "v1", "kind": "DeleteOptions", "propagationPolicy": propagation,
2024
"preconditions": object{"uid": uid, "resourceVersion": version}})
2125
if err != nil {
2226
return err

‎scripts/migrate-longhorn-v2/benchmark_recovery_fence.go‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -74,23 +74,25 @@ func benchmarkRetirementFences(record benchmarkRecord) ([]object, error) {
7474
empty("object.status.kubernetesStatus.pvName"),
7575
"("+empty("object.status.kubernetesStatus.pvcName")+" || (has(object.status.kubernetesStatus.lastPVCRefAt) && object.status.kubernetesStatus.lastPVCRefAt != \"\"))",
7676
)
77-
policy := func(name, group, version, scope string, resources []any, match, invariant string) object {
78-
return object{
79-
"apiVersion": "admissionregistration.k8s.io/v1", "kind": "ValidatingAdmissionPolicy",
80-
"metadata": object{"name": name + "-" + record.Phase + "-" + record.Run},
81-
"spec": object{
82-
"failurePolicy": "Fail",
83-
"matchConstraints": object{
84-
"matchPolicy": "Equivalent", "namespaceSelector": object{}, "objectSelector": object{},
85-
"resourceRules": []any{object{"apiGroups": []any{group}, "apiVersions": []any{version}, "resources": resources, "operations": []any{"CREATE", "UPDATE"}, "scope": scope}},
86-
},
87-
"matchConditions": []any{object{"name": "references-original-benchmark", "expression": match}},
88-
"validations": []any{object{"expression": invariant, "reason": "Forbidden", "message": benchmarkReferenceFenceMessage}},
89-
},
90-
}
91-
}
77+
suffix := "-" + record.Phase + "-" + record.Run
9278
return []object{
93-
policy("lh-benchmark-retire-pv", "", "v1", "Cluster", []any{"persistentvolumes", "persistentvolumes/status"}, pvMatch, pvInvariant),
94-
policy("lh-benchmark-retire-backend", "longhorn.io", "v1beta2", "Namespaced", []any{"volumes", "volumes/status"}, backendMatch, strings.Join(backendTerms, " && ")),
79+
benchmarkReferencePolicy("lh-benchmark-retire-pv"+suffix, "", "v1", "Cluster", []any{"persistentvolumes", "persistentvolumes/status"}, pvMatch, pvInvariant),
80+
benchmarkReferencePolicy("lh-benchmark-retire-backend"+suffix, "longhorn.io", "v1beta2", "Namespaced", []any{"volumes", "volumes/status"}, backendMatch, strings.Join(backendTerms, " && ")),
9581
}, nil
9682
}
83+
84+
func benchmarkReferencePolicy(name, group, version, scope string, resources []any, match, invariant string) object {
85+
return object{
86+
"apiVersion": benchmarkAdmissionAPI, "kind": "ValidatingAdmissionPolicy",
87+
"metadata": object{"name": name},
88+
"spec": object{
89+
"failurePolicy": "Fail",
90+
"matchConstraints": object{
91+
"matchPolicy": "Equivalent", "namespaceSelector": object{}, "objectSelector": object{},
92+
"resourceRules": []any{object{"apiGroups": []any{group}, "apiVersions": []any{version}, "resources": resources, "operations": []any{"CREATE", "UPDATE"}, "scope": scope}},
93+
},
94+
"matchConditions": []any{object{"name": "references-original-benchmark", "expression": match}},
95+
"validations": []any{object{"expression": invariant, "reason": "Forbidden", "message": benchmarkReferenceFenceMessage}},
96+
},
97+
}
98+
}

‎scripts/migrate-longhorn-v2/main.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ func main() {
5151
_, authorization = nativeRestoreResumeRun(os.Getenv)
5252
case nativeReattachmentOperation:
5353
_, _, authorization = authorizeNativeReattachment(os.Getenv)
54+
case nativeRestoreReclaimOperation:
55+
_, authorization = authorizedNativeRestoreReclaimRun(os.Getenv)
5456
case "inventory-replicas":
5557
authorization = authorizeInventory(os.Getenv, target)
5658
case "inspect-host-memory":
@@ -234,6 +236,15 @@ func main() {
234236
fmt.Println("LONGHORN_NATIVE_RESTORE=VERIFIED transfer=KOPIA engine=v2 reattachment=VERIFIED migration=UNVERIFIED")
235237
return
236238
}
239+
if operation == nativeRestoreReclaimOperation {
240+
if err := runNativeRestoreReclaim(ctx, client{run: execute, context: "admin@prod"}, config); err != nil {
241+
fmt.Fprintln(os.Stderr, "Disposable V2 reclaim held:", err)
242+
fmt.Fprintln(os.Stderr, "Preserve the reclaim journal and any confirmed admission policies for explicit recovery.")
243+
os.Exit(1)
244+
}
245+
fmt.Println("LONGHORN_NATIVE_RESTORE_RECLAIM=COMPLETE engine=v2 sourceBackup=RETAINED")
246+
return
247+
}
237248
pools, err := configuredMigrationPools(config)
238249
if err != nil {
239250
fmt.Fprintln(os.Stderr, err)

0 commit comments

Comments
 (0)