From be0a55c0728e04006c83786e2fff246021463453 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Wed, 21 Oct 2026 17:36:24 +0200 Subject: [PATCH 01/18] feat(linstor): make Blockstor a selectable storage backend Blockstor is a control plane for DRBD-replicated volumes that serves LINSTOR's REST API and keeps its state in Kubernetes objects instead of a SQL database. Because it speaks LINSTOR's API, linstor-csi, piraeus-operator and the StorageClasses stay as they are, and the linstor package can deploy either control plane behind them. The platform chooses through storage.backend, linstor by default. The default leaves the linstor Package as it was, with no components, so existing clusters render exactly what they rendered before and roll no new revision. A value present but not one of the two strings fails the render, empty ones included: read as linstor, an empty override on a blockstor cluster would switch its control plane back. The linstor chart refuses an unknown backend on its own too, since a value can reach it without passing through the platform. Under blockstor the package renders blockstor's controller, apiserver and satellite, and its CRDs with helm.sh/resource-policy: keep, since those objects are blockstor's whole database and a switch back to linstor must not delete them. piraeus-operator runs in external mode against blockstor-apiserver's mutual-TLS port, and is pointed at a client certificate from the same CA for its own version probe, which otherwise fails and stops every LinstorCluster and LinstorSatellite reconcile. linstor-scheduler and linstor-gui read that endpoint and client Secret from the same LinstorCluster, rather than from objects rendered under piraeus's names, so the platform tells them only the backend and no package but this one names blockstor's Service. piraeus still runs a linstor-satellite pod on every node it selects for linstor-csi-node, and nothing in LinstorCluster stops that without also stopping the CSI node plugin. So cozystack's satellite configuration, its internal CA and the satellite scrape stay under both backends: what runs is pinned, uses TLS and host networking, and the address the operator registers each node at is the node's own rather than one on the pod network. The plunger stays with LINSTOR, as it drives DRBD resources that under blockstor are blockstor-satellite's alone, and the opt-in Talos graceful-shutdown hook is refused under blockstor for the same reason: it downs every idle Secondary resource in the shared kernel. The LinstorCluster is one document with the differing keys gated, so the CSI half, strict topology included, cannot drift between the two. The apiserver's plain-HTTP listener, which authenticates nobody, is bound to loopback. The controller runs without leader election, so its Deployment uses the Recreate strategy. Each workload is granted what it uses: the apiserver writes Secrets only in its namespace, the satellite reads its one Secret there and deletes nothing but the PhysicalDevices it discovers, and neither binary gets leases, since neither runs leader election. The roles name every blockstor kind they grant. The satellite's unauthenticated host-network ports are closed to the world the way drbd-reactor's are. Blockstor is for new clusters only. The pinned release cannot adopt a cluster that already holds LINSTOR volumes safely, and nothing here converts LINSTOR's database, so both values files say so, and the platform refuses to change the backend of a live cozystack.linstor Package unless storage.acknowledgeBackendChange names the new one, the way the networking variant guard does. `make update-blockstor-crds` refreshes the CRDs from the blockstor tag the images are pinned to. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- hack/promote-retag.sh | 2 + packages/core/platform/templates/_helpers.tpl | 69 ++ .../platform/templates/bundles/system.yaml | 18 +- .../bundles_storage_backend_guard_test.yaml | 98 +++ .../tests/bundles_storage_backend_test.yaml | 210 +++++ packages/core/platform/values.yaml | 18 + packages/system/linstor-gui/README.md | 1 + .../system/linstor-gui/templates/_helpers.tpl | 36 + .../templates/configmap-nginx.yaml | 11 +- .../linstor-gui/templates/deployment.yaml | 2 +- .../linstor-gui/tests/api_client_test.yaml | 118 +++ packages/system/linstor-gui/values.yaml | 2 + packages/system/linstor-scheduler/Makefile | 1 + .../linstor-scheduler/templates/_helpers.tpl | 10 +- .../patches/cozystack-api-client.patch | 37 + .../linstor-scheduler/templates/_helpers.tpl | 33 + .../tests/api_client_test.yaml | 111 +++ packages/system/linstor-scheduler/values.yaml | 5 + packages/system/linstor/Makefile | 15 + ...ckstor.cozystack.io_controllerconfigs.yaml | 337 ++++++++ .../blockstor.cozystack.io_nodes.yaml | 252 ++++++ ...lockstor.cozystack.io_physicaldevices.yaml | 229 ++++++ ...stor.cozystack.io_resourcedefinitions.yaml | 499 ++++++++++++ ...blockstor.cozystack.io_resourcegroups.yaml | 377 +++++++++ .../blockstor.cozystack.io_resources.yaml | 762 ++++++++++++++++++ .../blockstor.cozystack.io_snapshots.yaml | 315 ++++++++ .../blockstor.cozystack.io_storagepools.yaml | 210 +++++ .../linstor/templates/backend-guard.yaml | 9 + .../templates/blockstor-apiserver-tls.yaml | 110 +++ .../templates/blockstor-apiserver.yaml | 186 +++++ .../templates/blockstor-controller.yaml | 124 +++ .../templates/blockstor-satellite.yaml | 281 +++++++ .../system/linstor/templates/cluster.yaml | 36 + .../system/linstor/templates/crds/crds.yaml | 24 + .../linstor/templates/linstor-api-tls.yaml | 2 + .../templates/linstor-internal-tls.yaml | 2 + .../templates/plunger/configmap-scripts.yaml | 2 + .../system/linstor/templates/podscrape.yaml | 2 + .../linstor/templates/satellites-cozy.yaml | 9 + .../linstor/templates/satellites-plunger.yaml | 2 + .../linstor/templates/satellites-talos.yaml | 13 + .../linstor/tests/apiserver_tls_test.yaml | 58 ++ .../system/linstor/tests/backend_test.yaml | 178 ++++ .../linstor/tests/blockstor_cluster_test.yaml | 103 +++ .../blockstor_controller_events_test.yaml | 22 + .../linstor/tests/blockstor_images_test.yaml | 53 ++ .../linstor/tests/blockstor_names_test.yaml | 61 ++ .../linstor/tests/blockstor_rbac_test.yaml | 71 ++ .../tests/blockstor_workloads_test.yaml | 213 +++++ packages/system/linstor/tests/crds_test.yaml | 31 + .../linstor/tests/csi-topology_test.yaml | 15 + .../system/linstor/tests/talos_gate_test.yaml | 35 + .../linstor/tests/talos_shutdown_test.yaml | 19 + packages/system/linstor/values.yaml | 37 + 54 files changed, 5467 insertions(+), 9 deletions(-) create mode 100644 packages/core/platform/tests/bundles_storage_backend_guard_test.yaml create mode 100644 packages/core/platform/tests/bundles_storage_backend_test.yaml create mode 100644 packages/system/linstor-gui/tests/api_client_test.yaml create mode 100644 packages/system/linstor-scheduler/patches/cozystack-api-client.patch create mode 100644 packages/system/linstor-scheduler/templates/_helpers.tpl create mode 100644 packages/system/linstor-scheduler/tests/api_client_test.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_controllerconfigs.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_nodes.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_physicaldevices.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_resourcedefinitions.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_resourcegroups.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_resources.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_snapshots.yaml create mode 100644 packages/system/linstor/definitions/blockstor.cozystack.io_storagepools.yaml create mode 100644 packages/system/linstor/templates/backend-guard.yaml create mode 100644 packages/system/linstor/templates/blockstor-apiserver-tls.yaml create mode 100644 packages/system/linstor/templates/blockstor-apiserver.yaml create mode 100644 packages/system/linstor/templates/blockstor-controller.yaml create mode 100644 packages/system/linstor/templates/blockstor-satellite.yaml create mode 100644 packages/system/linstor/templates/crds/crds.yaml create mode 100644 packages/system/linstor/tests/apiserver_tls_test.yaml create mode 100644 packages/system/linstor/tests/backend_test.yaml create mode 100644 packages/system/linstor/tests/blockstor_cluster_test.yaml create mode 100644 packages/system/linstor/tests/blockstor_controller_events_test.yaml create mode 100644 packages/system/linstor/tests/blockstor_images_test.yaml create mode 100644 packages/system/linstor/tests/blockstor_names_test.yaml create mode 100644 packages/system/linstor/tests/blockstor_rbac_test.yaml create mode 100644 packages/system/linstor/tests/blockstor_workloads_test.yaml create mode 100644 packages/system/linstor/tests/crds_test.yaml create mode 100644 packages/system/linstor/tests/talos_gate_test.yaml diff --git a/hack/promote-retag.sh b/hack/promote-retag.sh index 16a212bce..c90376e40 100755 --- a/hack/promote-retag.sh +++ b/hack/promote-retag.sh @@ -150,6 +150,8 @@ for raw in $(collect_refs); do # ghcr.io/cozystack — see those packages' values.yaml) # - ghcr.io/cozystack/ingress-nginx-with-protobuf-exporter/*, which is a # cozystack-org repo but sits outside $REGISTRY's path + # - ghcr.io/cozystack/blockstor-*, released from the blockstor repository + # under its own version (see packages/system/linstor/values.yaml) # - non-ref scalars, e.g. a "--migrate-image=..." arg string # Note kilo, kube-ovn and keycloak-operator are NOT in that list: all three # are built and pushed to $REGISTRY, and are selected by shapes 3 and 4. An diff --git a/packages/core/platform/templates/_helpers.tpl b/packages/core/platform/templates/_helpers.tpl index 03ca23fb4..289cfbccb 100644 --- a/packages/core/platform/templates/_helpers.tpl +++ b/packages/core/platform/templates/_helpers.tpl @@ -11,6 +11,9 @@ {{- if eq $name "cozystack.networking" -}} {{- include "cozystack.platform.networking.variantGuard" (list $root $variant) -}} {{- end }} +{{- if eq $name "cozystack.linstor" -}} +{{- include "cozystack.platform.storage.backendGuard" $root -}} +{{- end }} --- apiVersion: cozystack.io/v1alpha1 kind: Package @@ -50,6 +53,31 @@ Call as (list $ ). {{- end -}} {{- end }} +{{/* +Refuses to change the storage backend of a live cozystack.linstor Package. +The two backends keep their state in different places, so a switch leaves +linstor-csi talking to a control plane that knows none of the existing +volumes, and blockstor-satellite's startup cleanup downs the DRBD resources it +does not consider healthy, whoever owns them. A live Package without a backend +value runs linstor, the chart default. As with the networking guard, the +acknowledgement names the target, and the guard is inert where lookup returns +nothing: helm template, client-side dry-run, first install. +*/}} +{{- define "cozystack.platform.storage.backendGuard" -}} +{{- $live := lookup "cozystack.io/v1alpha1" "Package" "" "cozystack.linstor" -}} +{{- if $live -}} +{{- $liveBackend := dig "spec" "components" "linstor" "values" "backend" "linstor" $live | toString -}} +{{- $backend := include "cozystack.platform.storage.backend" . -}} +{{- $ack := "" -}} +{{- if kindIs "map" .Values.storage -}} +{{- $ack = dig "acknowledgeBackendChange" "" .Values.storage | toString -}} +{{- end -}} +{{- if and (ne $liveBackend $backend) (ne $ack $backend) -}} +{{- fail (printf "the live cozystack.linstor Package runs the %q storage backend and this render would switch it to %q. The volumes this cluster already has are known only to the current backend: after the switch the CSI driver cannot attach, resize, snapshot or delete them. Restore storage.backend: %q, or, if the cluster holds no volumes, set storage.acknowledgeBackendChange: %q to confirm this exact switch." $liveBackend $backend $liveBackend $backend) -}} +{{- end -}} +{{- end -}} +{{- end }} + {{- define "cozystack.platform.package.default" -}} {{- $name := index . 0 -}} {{- $root := index . 1 -}} @@ -239,7 +267,21 @@ cozystack-scheduler (emitted with its own variant in both branches) {{include "cozystack.platform.package.optional.default" (list "cozystack.metallb-iad" $root) }} {{- end }} {{include "cozystack.platform.package.default" (list "cozystack.reloader" $root) }} +{{- /* linstor-scheduler and linstor-gui, the LINSTOR API consumers outside + the linstor package, are told only the backend. Under blockstor each + reads where the API is, and with which client certificate, from the + LinstorCluster the linstor package renders, the object that points + linstor-csi there too, so the names of blockstor's Service and Secret + stay in that package alone. Under linstor they get nothing and keep + their own defaults, linstor-controller and linstor-client-tls. The + backend is passed rather than left to the lookup alone so that a + switch changes their values and Helm renders them again. */ -}} +{{- if eq (include "cozystack.platform.storage.backend" $root) "blockstor" }} +{{- $schedulerComponents := dict "linstor-scheduler" (dict "values" (dict "linstor-scheduler" (dict "linstor" (dict "backend" "blockstor")))) -}} +{{include "cozystack.platform.package" (list "cozystack.linstor-scheduler" "default" $root $schedulerComponents) }} +{{- else }} {{include "cozystack.platform.package.default" (list "cozystack.linstor-scheduler" $root) }} +{{- end }} {{include "cozystack.platform.package.default" (list "cozystack.snapshot-controller" $root) }} {{- /* securitygroup-controller maintains membership labels for CiliumNetworkPolicy-backed SecurityGroups, so it only makes sense where Cilium runs. Keeping it here with the @@ -254,6 +296,33 @@ cozystack-scheduler (emitted with its own variant in both branches) {{- end }} {{- end }} +{{- /* +Resolve the storage backend for the linstor package. + +Defaults to `linstor`, which is what every existing cluster runs, and only +when the key is absent. `blockstor` is experimental and must be asked for +explicitly. Any value present but not one of the two strings fails the render, +empty ones included: `default` would map "", false or 0 to linstor, and on a +blockstor cluster that switches the control plane back. A null is the one +spelling the template cannot see, because Helm removes a key set to null +before rendering, so it reads as absent. +*/ -}} +{{- define "cozystack.platform.storage.backend" -}} +{{- $backend := "linstor" -}} +{{- if hasKey .Values "storage" -}} +{{- if not (kindIs "map" .Values.storage) -}} +{{- fail (printf "storage must be a map with a backend key, got %v" .Values.storage) -}} +{{- end -}} +{{- if hasKey .Values.storage "backend" -}} +{{- $backend = .Values.storage.backend -}} +{{- end -}} +{{- end -}} +{{- if not (and (kindIs "string" $backend) (has $backend (list "linstor" "blockstor"))) -}} +{{- fail (printf "storage.backend must be \"linstor\" or \"blockstor\", got %#v" $backend) -}} +{{- end -}} +{{- $backend -}} +{{- end -}} + {{/* The block Cilium takes its own addresses from on the kube-ovn variants, the last /21 of the pod CIDR, which kube-ovn is told to exclude. Called with the diff --git a/packages/core/platform/templates/bundles/system.yaml b/packages/core/platform/templates/bundles/system.yaml index f747210cc..8636368da 100644 --- a/packages/core/platform/templates/bundles/system.yaml +++ b/packages/core/platform/templates/bundles/system.yaml @@ -137,7 +137,12 @@ {{- $multusComponents := dict "multus" (dict "values" (include "cozystack.platform.multus.values" (list $ true) | fromYaml)) -}} {{include "cozystack.platform.package.full" (list "cozystack.multus" "default" $ $multusComponents) }} {{- end }} +{{- if eq (include "cozystack.platform.storage.backend" $) "blockstor" }} +{{- $linstorComponents := dict "linstor" (dict "values" (dict "backend" "blockstor")) -}} +{{include "cozystack.platform.package" (list "cozystack.linstor" "default" $ $linstorComponents) }} +{{- else }} {{include "cozystack.platform.package.default" (list "cozystack.linstor" $) }} +{{- end }} {{include "cozystack.platform.package" (list "cozystack.cozystack-scheduler" "linstor" $) }} {{- end }} @@ -230,7 +235,11 @@ {{- $multusComponents := dict "multus" (dict "values" (include "cozystack.platform.multus.values" (list $ true) | fromYaml)) -}} {{include "cozystack.platform.package.full" (list "cozystack.multus" "default" $ $multusComponents) }} {{- /* Pass talos.enabled: false to linstor for generic Linux */ -}} -{{- $linstorComponents := dict "linstor" (dict "values" (dict "talos" (dict "enabled" false))) -}} +{{- $linstorValues := dict "talos" (dict "enabled" false) -}} +{{- if eq (include "cozystack.platform.storage.backend" $) "blockstor" -}} +{{- $_ := set $linstorValues "backend" "blockstor" -}} +{{- end -}} +{{- $linstorComponents := dict "linstor" (dict "values" $linstorValues) -}} {{include "cozystack.platform.package" (list "cozystack.linstor" "default" $ $linstorComponents) }} {{include "cozystack.platform.package" (list "cozystack.cozystack-scheduler" "linstor" $) }} {{- end }} @@ -516,7 +525,14 @@ variants and opt-in on the slim ones. */}} {{include "cozystack.platform.package.optional.default" (list "cozystack.kuberture" $) }} {{include "cozystack.platform.package.optional.default" (list "cozystack.keda" $) }} {{include "cozystack.platform.package.optional.default" (list "cozystack.external-secrets-operator" $) }} +{{- /* Told only the backend, as linstor-scheduler is in the common-packages + helper: the linstor package's LinstorCluster says where the API is. */ -}} +{{- if eq (include "cozystack.platform.storage.backend" $) "blockstor" }} +{{- $guiComponents := dict "linstor-gui" (dict "values" (dict "linstor" (dict "backend" "blockstor"))) -}} +{{include "cozystack.platform.package.optional.default" (list "cozystack.linstor-gui" $ $guiComponents) }} +{{- else }} {{include "cozystack.platform.package.optional.default" (list "cozystack.linstor-gui" $) }} +{{- end }} {{- if has "cozystack.bootbox" (default (list) .Values.bundles.enabledPackages) }} {{include "cozystack.platform.package.default" (list "cozystack.bootbox-application" $) }} {{include "cozystack.platform.package.default" (list "cozystack.bootbox" $) }} diff --git a/packages/core/platform/tests/bundles_storage_backend_guard_test.yaml b/packages/core/platform/tests/bundles_storage_backend_guard_test.yaml new file mode 100644 index 000000000..77c17d3b0 --- /dev/null +++ b/packages/core/platform/tests/bundles_storage_backend_guard_test.yaml @@ -0,0 +1,98 @@ +suite: storage backend change guard (lookup of the live cozystack.linstor Package) + +# The backends keep their state apart, so switching one under a cluster that +# already has volumes strands them. The guard reads the live Package and is +# inert where lookup returns nothing (helm template, dry-run, fresh install). +templates: + - templates/bundles/system.yaml +release: + name: cozystack + namespace: cozy-system +set: + bundles: + system: + enabled: true + variant: isp-full +tests: + - it: refuses linstor -> blockstor on a live LINSTOR cluster and names the acknowledge value + set: + storage: + backend: blockstor + kubernetesProvider: + scheme: &scheme + "cozystack.io/v1alpha1/Package": + gvr: {group: "cozystack.io", version: "v1alpha1", resource: "packages"} + namespaced: false + objects: &liveLinstor + - kind: Package + apiVersion: cozystack.io/v1alpha1 + metadata: {name: cozystack.linstor} + spec: {variant: default} + asserts: + - failedTemplate: + errorPattern: 'runs the "linstor" storage backend and this render would switch it to "blockstor".*storage.acknowledgeBackendChange: "blockstor"' + + - it: refuses blockstor -> linstor on a live blockstor cluster + kubernetesProvider: + scheme: *scheme + objects: + - kind: Package + apiVersion: cozystack.io/v1alpha1 + metadata: {name: cozystack.linstor} + spec: + variant: default + components: + linstor: + values: {backend: blockstor} + asserts: + - failedTemplate: + errorPattern: 'runs the "blockstor" storage backend and this render would switch it to "linstor"' + + - it: renders the switch once it is acknowledged + set: + storage: + backend: blockstor + acknowledgeBackendChange: blockstor + kubernetesProvider: + scheme: *scheme + objects: *liveLinstor + asserts: + - equal: + path: spec.components.linstor.values.backend + value: blockstor + documentSelector: + path: metadata.name + value: cozystack.linstor + + # An acknowledgement left set from an earlier switch does not cover the + # opposite one. + - it: does not take an acknowledgement for another target + set: + storage: + backend: blockstor + acknowledgeBackendChange: linstor + kubernetesProvider: + scheme: *scheme + objects: *liveLinstor + asserts: + - failedTemplate: + errorPattern: 'would switch it to "blockstor"' + + - it: renders an unchanged backend on a live cluster + kubernetesProvider: + scheme: *scheme + objects: *liveLinstor + asserts: + - notFailedTemplate: {} + + - it: renders blockstor on a fresh install + set: + storage: + backend: blockstor + asserts: + - equal: + path: spec.components.linstor.values.backend + value: blockstor + documentSelector: + path: metadata.name + value: cozystack.linstor diff --git a/packages/core/platform/tests/bundles_storage_backend_test.yaml b/packages/core/platform/tests/bundles_storage_backend_test.yaml new file mode 100644 index 000000000..325a10c59 --- /dev/null +++ b/packages/core/platform/tests/bundles_storage_backend_test.yaml @@ -0,0 +1,210 @@ +suite: storage backend selection reaches the linstor package +templates: + - templates/bundles/system.yaml +release: + name: cozystack + namespace: cozy-system + +# The operator picks the storage control plane at install time. The choice has +# to arrive at the linstor package as a value, because that package renders one +# backend or the other from it — a choice that stayed in the platform chart +# would be inert. LINSTOR is the default: every existing cluster runs it, and a +# silent flip would swap the storage control plane under live data. +tests: + # The default leaves the linstor Package exactly as it was before the choice + # existed: no components, so the chart default (linstor) applies and an + # upgrade does not roll a new revision of the release for nothing. + - it: defaults to the linstor backend without restating it + set: + bundles: + system: + enabled: true + variant: isp-full + asserts: + - notExists: + path: spec.components + documentSelector: + path: metadata.name + value: cozystack.linstor + + - it: states nothing but the talos override on the generic variant by default + set: + bundles: + system: + enabled: true + variant: isp-full-generic + asserts: + - equal: + path: spec.components.linstor.values + value: + talos: + enabled: false + documentSelector: + path: metadata.name + value: cozystack.linstor + + - it: passes blockstor through when the operator asks for it + set: + storage: + backend: blockstor + bundles: + system: + enabled: true + variant: isp-full + asserts: + - equal: + path: spec.components.linstor.values.backend + value: blockstor + documentSelector: + path: metadata.name + value: cozystack.linstor + + - it: keeps the generic variant's talos override alongside the backend + set: + storage: + backend: blockstor + bundles: + system: + enabled: true + variant: isp-full-generic + asserts: + - equal: + path: spec.components.linstor.values.backend + value: blockstor + documentSelector: + path: metadata.name + value: cozystack.linstor + - equal: + path: spec.components.linstor.values.talos.enabled + value: false + documentSelector: + path: metadata.name + value: cozystack.linstor + + # A typo must not quietly deploy the wrong storage control plane. + - it: fails the render on an unrecognised backend + set: + storage: + backend: blockstore + bundles: + system: + enabled: true + variant: isp-full + asserts: + - failedTemplate: + errorMessage: 'storage.backend must be "linstor" or "blockstor", got "blockstore"' + + # Under linstor the API consumers keep their chart defaults, which name the + # objects piraeus-operator creates. Under blockstor they are told only the + # backend: where the API is comes from the LinstorCluster the linstor package + # renders, so the platform names neither blockstor's Service nor its Secret. + - it: leaves the linstor-scheduler on its defaults under linstor + set: + bundles: + system: + enabled: true + variant: isp-full + asserts: + - notExists: + path: spec.components + documentSelector: + path: metadata.name + value: cozystack.linstor-scheduler + + - it: tells the linstor-scheduler only the backend under blockstor + set: + storage: + backend: blockstor + bundles: + system: + enabled: true + variant: isp-full + asserts: + - equal: + path: spec.components.linstor-scheduler.values.linstor-scheduler.linstor + value: + backend: blockstor + documentSelector: + path: metadata.name + value: cozystack.linstor-scheduler + + - it: tells linstor-gui only the backend under blockstor + set: + storage: + backend: blockstor + bundles: + system: + enabled: true + variant: isp-full + enabledPackages: [cozystack.linstor-gui] + asserts: + - equal: + path: spec.components.linstor-gui.values.linstor + value: + backend: blockstor + documentSelector: + path: metadata.name + value: cozystack.linstor-gui + + - it: leaves linstor-gui on its defaults under linstor + set: + bundles: + system: + enabled: true + variant: isp-full + enabledPackages: [cozystack.linstor-gui] + asserts: + - notExists: + path: spec.components + documentSelector: + path: metadata.name + value: cozystack.linstor-gui + + # An empty value is not "unset". `default` would have read each of these as + # linstor, and on a blockstor cluster that is a switch of control plane. + - it: fails the render on an empty backend + set: + storage: + backend: "" + bundles: + system: + enabled: true + variant: isp-full + asserts: + - failedTemplate: + errorMessage: 'storage.backend must be "linstor" or "blockstor", got ""' + + - it: fails the render on a false backend + set: + storage: + backend: false + bundles: + system: + enabled: true + variant: isp-full + asserts: + - failedTemplate: + errorMessage: 'storage.backend must be "linstor" or "blockstor", got false' + + - it: fails the render on a numeric backend + set: + storage: + backend: 0 + bundles: + system: + enabled: true + variant: isp-full + asserts: + - failedTemplate: + errorMessage: 'storage.backend must be "linstor" or "blockstor", got 0' + + - it: fails the render on a storage key that is not a map + set: + storage: blockstor + bundles: + system: + enabled: true + variant: isp-full + asserts: + - failedTemplate: + errorMessage: 'storage must be a map with a backend key, got blockstor' diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index 4b7ae0e50..aa496eaf6 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -108,6 +108,24 @@ migrations: # Reset it to false once the upgrade is through, or the next platform upgrade # that adds an etcd migration will skip its snapshot too. etcdAdoptSkipBackup: false +# Which storage control plane the cluster runs. +# +# linstor — the default, and what every existing cluster runs. +# blockstor — EXPERIMENTAL, for new clusters only. A +# LINSTOR-API-compatible control plane serving the same +# CSI driver and StorageClasses. Do not switch a cluster +# that already holds LINSTOR volumes: the pinned blockstor +# release cannot adopt them safely, and nothing converts +# LINSTOR's database into blockstor's. +# +# Anything else fails the render rather than defaulting, so a typo +# cannot quietly deploy the wrong storage control plane. Changing the +# backend of a running cluster fails the render too; on a cluster that +# holds no volumes yet, set storage.acknowledgeBackendChange to the new +# backend to confirm the switch. +storage: + backend: linstor + # Bundle deployment configuration bundles: system: diff --git a/packages/system/linstor-gui/README.md b/packages/system/linstor-gui/README.md index 8f8053ab5..8f13f02e7 100644 --- a/packages/system/linstor-gui/README.md +++ b/packages/system/linstor-gui/README.md @@ -60,5 +60,6 @@ then open . | Name | Description | Value | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- | +| `linstor.backend` | Storage backend the platform runs, `linstor` or `blockstor`. Under `blockstor` the endpoint and client Secret are read from the LinstorCluster the `linstor` package renders, and the two values below apply only while it runs an in-cluster controller. | `linstor` | | `linstor.endpoint` | In-cluster URL of the LINSTOR controller REST API (HTTPS, mTLS) | `https://linstor-controller.cozy-linstor.svc:3371` | | `linstor.clientSecret` | Kubernetes Secret with `tls.crt`, `tls.key`, `ca.crt` used as the mTLS client certificate against the LINSTOR controller. Created by the `linstor` package. | `linstor-client-tls` | diff --git a/packages/system/linstor-gui/templates/_helpers.tpl b/packages/system/linstor-gui/templates/_helpers.tpl index 6cad99ee8..cfdc2b4bd 100644 --- a/packages/system/linstor-gui/templates/_helpers.tpl +++ b/packages/system/linstor-gui/templates/_helpers.tpl @@ -15,3 +15,39 @@ Selector labels app.kubernetes.io/name: linstor-gui app.kubernetes.io/instance: {{ .Release.Name }} {{- end }} + +{{/* +Where the LINSTOR API is and which client certificate it takes, as YAML with +endpoint and clientSecret keys. + +Under backend linstor that is linstor.endpoint and linstor.clientSecret, +which name the in-cluster controller and the Secret piraeus-operator issues +for it. Under backend blockstor the linstor package decides: it renders the +LinstorCluster that points piraeus-operator, and through it linstor-csi, at +the API, so this chart reads the same two fields and follows wherever they +point. A LinstorCluster still running an in-cluster controller leaves the +values in effect. The package depends on cozystack.linstor, so the +LinstorCluster exists before this chart renders; a render that finds none, or +more than one, fails rather than guess. +*/}} +{{- define "linstor-gui.apiClient" -}} +{{- $backend := .Values.linstor.backend | default "linstor" -}} +{{- if not (has $backend (list "linstor" "blockstor")) -}} +{{- fail (printf "linstor.backend must be \"linstor\" or \"blockstor\", got %#v" $backend) -}} +{{- end -}} +{{- $endpoint := .Values.linstor.endpoint -}} +{{- $clientSecret := .Values.linstor.clientSecret -}} +{{- if eq $backend "blockstor" -}} +{{- $clusters := (lookup "piraeus.io/v1" "LinstorCluster" "" "").items | default list -}} +{{- if ne (len $clusters) 1 -}} +{{- fail (printf "linstor.backend is blockstor, so the LINSTOR API endpoint is read from the LinstorCluster the linstor package renders, but the cluster has %d LinstorClusters" (len $clusters)) -}} +{{- end -}} +{{- $spec := (index $clusters 0).spec | default dict -}} +{{- with dig "externalController" "url" "" $spec -}} +{{- $endpoint = . -}} +{{- $clientSecret = dig "apiTLS" "clientSecretName" "linstor-client-tls" $spec -}} +{{- end -}} +{{- end -}} +endpoint: {{ $endpoint | quote }} +clientSecret: {{ $clientSecret | quote }} +{{- end }} diff --git a/packages/system/linstor-gui/templates/configmap-nginx.yaml b/packages/system/linstor-gui/templates/configmap-nginx.yaml index 86acd0f7a..58a6cfae0 100644 --- a/packages/system/linstor-gui/templates/configmap-nginx.yaml +++ b/packages/system/linstor-gui/templates/configmap-nginx.yaml @@ -3,10 +3,11 @@ Parse the LINSTOR endpoint so nginx can set `proxy_ssl_name` correctly. The endpoint must be an https:// URL — http:// would downgrade the mTLS-protected controller path. */}} -{{- if not (hasPrefix "https://" .Values.linstor.endpoint) -}} +{{- $api := include "linstor-gui.apiClient" . | fromYaml -}} +{{- if not (hasPrefix "https://" $api.endpoint) -}} {{- fail "linstor.endpoint must start with https:// to enforce mTLS to the LINSTOR controller" -}} {{- end -}} -{{- $endpoint := trimPrefix "https://" .Values.linstor.endpoint -}} +{{- $endpoint := trimPrefix "https://" $api.endpoint -}} {{- $endpointHost := (splitList ":" $endpoint) | first -}} apiVersion: v1 kind: ConfigMap @@ -89,16 +90,16 @@ data: if ($request_method !~ ^(GET|HEAD)$) { return 403 '{"ret_code":-1,"message":"linstor-gui in-app authentication is disabled by cozystack: authentication is enforced at the Ingress via Keycloak."}'; } - proxy_pass {{ .Values.linstor.endpoint }}; + proxy_pass {{ $api.endpoint }}; } # Proxy LINSTOR REST API over mTLS to the controller location /v1 { - proxy_pass {{ .Values.linstor.endpoint }}; + proxy_pass {{ $api.endpoint }}; } location /metrics { - proxy_pass {{ .Values.linstor.endpoint }}; + proxy_pass {{ $api.endpoint }}; } location = /healthz { diff --git a/packages/system/linstor-gui/templates/deployment.yaml b/packages/system/linstor-gui/templates/deployment.yaml index 92e2f7a66..2bc6a5c56 100644 --- a/packages/system/linstor-gui/templates/deployment.yaml +++ b/packages/system/linstor-gui/templates/deployment.yaml @@ -90,7 +90,7 @@ spec: name: linstor-gui-nginx - name: linstor-client-tls secret: - secretName: {{ .Values.linstor.clientSecret }} + secretName: {{ (include "linstor-gui.apiClient" . | fromYaml).clientSecret }} # 0444 so nginx (UID 101) can read the mTLS client keypair; # the secret volume is pod-local, not a broader disclosure. defaultMode: 0444 diff --git a/packages/system/linstor-gui/tests/api_client_test.yaml b/packages/system/linstor-gui/tests/api_client_test.yaml new file mode 100644 index 000000000..44b674449 --- /dev/null +++ b/packages/system/linstor-gui/tests/api_client_test.yaml @@ -0,0 +1,118 @@ +suite: the LINSTOR API endpoint follows the backend + +# Under blockstor the linstor package, not this chart or the platform, knows +# where the API is: it writes the URL and the client Secret into the +# LinstorCluster that points linstor-csi there. These cases feed that object +# through lookup. +templates: + - templates/configmap-nginx.yaml + - templates/deployment.yaml +release: + name: linstor-gui + namespace: cozy-linstor +tests: + - it: stays on the in-cluster controller under linstor + asserts: + - template: templates/configmap-nginx.yaml + matchRegex: + path: data["nginx.conf"] + pattern: "proxy_pass https://linstor-controller.cozy-linstor.svc:3371;" + - template: templates/deployment.yaml + contains: + path: spec.template.spec.volumes + content: + name: linstor-client-tls + secret: + secretName: linstor-client-tls + defaultMode: 0444 + + - it: follows the external controller of the LinstorCluster under blockstor + set: + linstor.backend: blockstor + kubernetesProvider: + scheme: &scheme + "piraeus.io/v1/LinstorCluster": + gvr: {group: "piraeus.io", version: "v1", resource: "linstorclusters"} + namespaced: false + objects: + - kind: LinstorCluster + apiVersion: piraeus.io/v1 + metadata: {name: linstorcluster} + spec: + externalController: + url: https://api.example.svc:3371 + apiTLS: + clientSecretName: example-client-tls + asserts: + - template: templates/configmap-nginx.yaml + matchRegex: + path: data["nginx.conf"] + pattern: "proxy_pass https://api.example.svc:3371;" + - template: templates/configmap-nginx.yaml + matchRegex: + path: data["nginx.conf"] + pattern: "proxy_ssl_name api.example.svc;" + - template: templates/deployment.yaml + contains: + path: spec.template.spec.volumes + content: + name: linstor-client-tls + secret: + secretName: example-client-tls + defaultMode: 0444 + + - it: takes piraeus's default client Secret when the LinstorCluster names none + set: + linstor.backend: blockstor + kubernetesProvider: + scheme: *scheme + objects: + - kind: LinstorCluster + apiVersion: piraeus.io/v1 + metadata: {name: linstorcluster} + spec: + externalController: + url: https://api.example.svc:3371 + template: templates/deployment.yaml + asserts: + - contains: + path: spec.template.spec.volumes + content: + name: linstor-client-tls + secret: + secretName: linstor-client-tls + defaultMode: 0444 + + # While a LinstorCluster still runs its own controller under blockstor, + # that controller is the API linstor-csi uses, so this chart stays on it. + - it: keeps the values while the LinstorCluster runs an in-cluster controller + set: + linstor.backend: blockstor + kubernetesProvider: + scheme: *scheme + objects: + - kind: LinstorCluster + apiVersion: piraeus.io/v1 + metadata: {name: linstorcluster} + spec: {} + template: templates/configmap-nginx.yaml + asserts: + - matchRegex: + path: data["nginx.conf"] + pattern: "proxy_pass https://linstor-controller.cozy-linstor.svc:3371;" + + - it: refuses blockstor when no LinstorCluster tells it where the API is + set: + linstor.backend: blockstor + template: templates/deployment.yaml + asserts: + - failedTemplate: + errorPattern: "linstor.backend is blockstor.*the cluster has 0 LinstorClusters" + + - it: refuses an unknown backend + set: + linstor.backend: blockstore + template: templates/deployment.yaml + asserts: + - failedTemplate: + errorMessage: 'linstor.backend must be "linstor" or "blockstor", got "blockstore"' diff --git a/packages/system/linstor-gui/values.yaml b/packages/system/linstor-gui/values.yaml index f35ddb8b3..48414c905 100644 --- a/packages/system/linstor-gui/values.yaml +++ b/packages/system/linstor-gui/values.yaml @@ -12,8 +12,10 @@ image: ## @param replicas Number of linstor-gui replicas replicas: 1 ## @section LINSTOR controller connection +## @param linstor.backend Storage backend the platform runs, `linstor` or `blockstor`. Under `blockstor` the endpoint and client Secret are read from the LinstorCluster the `linstor` package renders, and the two values below apply only while it runs an in-cluster controller. ## @param linstor.endpoint In-cluster URL of the LINSTOR controller REST API (HTTPS, mTLS) ## @param linstor.clientSecret Kubernetes Secret with `tls.crt`, `tls.key`, `ca.crt` used as the mTLS client certificate against the LINSTOR controller. Created by the `linstor` package. linstor: + backend: "linstor" endpoint: "https://linstor-controller.cozy-linstor.svc:3371" clientSecret: "linstor-client-tls" diff --git a/packages/system/linstor-scheduler/Makefile b/packages/system/linstor-scheduler/Makefile index 5961a1da9..e02f0f8d6 100644 --- a/packages/system/linstor-scheduler/Makefile +++ b/packages/system/linstor-scheduler/Makefile @@ -16,3 +16,4 @@ update: # tests/ are the source of truth (same policy as packages/system/coredns). rm -rf charts/linstor-scheduler/tests patch --no-backup-if-mismatch -p4 < patches/cozystack-scheduler-deployment.patch + patch --no-backup-if-mismatch -p4 < patches/cozystack-api-client.patch diff --git a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl index fd0487759..f13267bcd 100644 --- a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl +++ b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl @@ -133,7 +133,10 @@ Strips distribution suffixes like +k3s1, +rke2r1 from version string. Find the linstor client secret containing TLS certificates */}} {{- define "linstor-scheduler.linstorClientSecretName" -}} -{{- if .Values.linstor.clientSecret }} +{{- $cozystack := include "linstor-scheduler.cozystack.apiClient" . | fromYaml }} +{{- if $cozystack.clientSecret }} +{{- $cozystack.clientSecret }} +{{- else if .Values.linstor.clientSecret }} {{- .Values.linstor.clientSecret }} {{- else if .Capabilities.APIVersions.Has "piraeus.linbit.com/v1/LinstorController" }} {{- $crs := (lookup "piraeus.linbit.com/v1" "LinstorController" .Release.Namespace "").items }} @@ -189,7 +192,10 @@ Find the linstor URL by operator resources Find the linstor URL either by override or cluster resources */}} {{- define "linstor-scheduler.linstorEndpoint" -}} -{{- if .Values.linstor.endpoint }} +{{- $cozystack := include "linstor-scheduler.cozystack.apiClient" . | fromYaml }} +{{- if $cozystack.endpoint }} +{{- $cozystack.endpoint }} +{{- else if .Values.linstor.endpoint }} {{- .Values.linstor.endpoint }} {{- else }} {{- $piraeus := include "linstor-scheduler.linstorEndpointFromCRD" . }} diff --git a/packages/system/linstor-scheduler/patches/cozystack-api-client.patch b/packages/system/linstor-scheduler/patches/cozystack-api-client.patch new file mode 100644 index 000000000..478b9e619 --- /dev/null +++ b/packages/system/linstor-scheduler/patches/cozystack-api-client.patch @@ -0,0 +1,37 @@ +# Let the cozystack wrapper decide where the LINSTOR API is before the +# chart's own linstor.endpoint and linstor.clientSecret values do. +# +# Under the blockstor storage backend the API is wherever the linstor +# package points piraeus-operator, so the wrapper's +# templates/_helpers.tpl reads that from the LinstorCluster and both +# helpers below prefer its answer. It answers nothing under the linstor +# backend, which leaves the upstream order as it is. +# +# Chart source: https://piraeus.io/helm-charts (linstor-scheduler 0.3.1) +diff --git a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl +--- a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl ++++ b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/_helpers.tpl +@@ -133,7 +133,10 @@ Strips distribution suffixes like +k3s1, +rke2r1 from version string. + Find the linstor client secret containing TLS certificates + */}} + {{- define "linstor-scheduler.linstorClientSecretName" -}} +-{{- if .Values.linstor.clientSecret }} ++{{- $cozystack := include "linstor-scheduler.cozystack.apiClient" . | fromYaml }} ++{{- if $cozystack.clientSecret }} ++{{- $cozystack.clientSecret }} ++{{- else if .Values.linstor.clientSecret }} + {{- .Values.linstor.clientSecret }} + {{- else if .Capabilities.APIVersions.Has "piraeus.linbit.com/v1/LinstorController" }} + {{- $crs := (lookup "piraeus.linbit.com/v1" "LinstorController" .Release.Namespace "").items }} +@@ -189,7 +192,10 @@ Find the linstor URL by operator resources + Find the linstor URL either by override or cluster resources + */}} + {{- define "linstor-scheduler.linstorEndpoint" -}} +-{{- if .Values.linstor.endpoint }} ++{{- $cozystack := include "linstor-scheduler.cozystack.apiClient" . | fromYaml }} ++{{- if $cozystack.endpoint }} ++{{- $cozystack.endpoint }} ++{{- else if .Values.linstor.endpoint }} + {{- .Values.linstor.endpoint }} + {{- else }} + {{- $piraeus := include "linstor-scheduler.linstorEndpointFromCRD" . }} diff --git a/packages/system/linstor-scheduler/templates/_helpers.tpl b/packages/system/linstor-scheduler/templates/_helpers.tpl new file mode 100644 index 000000000..a15579251 --- /dev/null +++ b/packages/system/linstor-scheduler/templates/_helpers.tpl @@ -0,0 +1,33 @@ +{{/* +Where the LINSTOR API is and which client certificate it takes, as YAML with +endpoint and clientSecret keys, or nothing to leave the subchart on +linstor.endpoint and linstor.clientSecret. Called from the subchart's own +helpers (patches/cozystack-api-client.patch), so `.` is the subchart context. + +Under backend linstor it returns nothing: the values name the in-cluster +controller and the Secret piraeus-operator issues for it. Under backend +blockstor the linstor package decides: it renders the LinstorCluster that +points piraeus-operator, and through it linstor-csi, at the API, so the +scheduler reads the same two fields and follows wherever they point. A +LinstorCluster still running an in-cluster controller leaves the values in +effect. The package depends on cozystack.linstor, so the LinstorCluster +exists before this chart renders; a render that finds none, or more than +one, fails rather than guess. +*/}} +{{- define "linstor-scheduler.cozystack.apiClient" -}} +{{- $backend := .Values.linstor.backend | default "linstor" -}} +{{- if not (has $backend (list "linstor" "blockstor")) -}} +{{- fail (printf "linstor-scheduler.linstor.backend must be \"linstor\" or \"blockstor\", got %#v" $backend) -}} +{{- end -}} +{{- if eq $backend "blockstor" -}} +{{- $clusters := (lookup "piraeus.io/v1" "LinstorCluster" "" "").items | default list -}} +{{- if ne (len $clusters) 1 -}} +{{- fail (printf "linstor-scheduler.linstor.backend is blockstor, so the LINSTOR API endpoint is read from the LinstorCluster the linstor package renders, but the cluster has %d LinstorClusters" (len $clusters)) -}} +{{- end -}} +{{- $spec := (index $clusters 0).spec | default dict -}} +{{- with dig "externalController" "url" "" $spec }} +endpoint: {{ . | quote }} +clientSecret: {{ dig "apiTLS" "clientSecretName" "linstor-client-tls" $spec | quote }} +{{- end -}} +{{- end -}} +{{- end }} diff --git a/packages/system/linstor-scheduler/tests/api_client_test.yaml b/packages/system/linstor-scheduler/tests/api_client_test.yaml new file mode 100644 index 000000000..f0f2ad77c --- /dev/null +++ b/packages/system/linstor-scheduler/tests/api_client_test.yaml @@ -0,0 +1,111 @@ +suite: the LINSTOR API endpoint follows the backend + +# Under blockstor the linstor package, not this chart or the platform, knows +# where the API is: it writes the URL and the client Secret into the +# LinstorCluster that points linstor-csi there. These cases feed that object +# through lookup. +templates: + - charts/linstor-scheduler/templates/deployment.yaml +release: + name: linstor-scheduler + namespace: cozy-linstor +tests: + - it: stays on the in-cluster controller under linstor + asserts: + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_CONTROLLERS + value: https://linstor-controller.cozy-linstor.svc:3371 + - equal: + path: metadata.annotations["secret.reloader.stakater.com/reload"] + value: linstor-client-tls + + - it: follows the external controller of the LinstorCluster under blockstor + set: + linstor-scheduler.linstor.backend: blockstor + kubernetesProvider: + scheme: &scheme + "piraeus.io/v1/LinstorCluster": + gvr: {group: "piraeus.io", version: "v1", resource: "linstorclusters"} + namespaced: false + objects: + - kind: LinstorCluster + apiVersion: piraeus.io/v1 + metadata: {name: linstorcluster} + spec: + externalController: + url: https://api.example.svc:3371 + apiTLS: + clientSecretName: example-client-tls + asserts: + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_CONTROLLERS + value: https://api.example.svc:3371 + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_ROOT_CA + valueFrom: + secretKeyRef: + name: example-client-tls + key: ca.crt + - equal: + path: metadata.annotations["secret.reloader.stakater.com/reload"] + value: example-client-tls + + - it: takes piraeus's default client Secret when the LinstorCluster names none + set: + linstor-scheduler.linstor.backend: blockstor + linstor-scheduler.linstor.clientSecret: other-client-tls + kubernetesProvider: + scheme: *scheme + objects: + - kind: LinstorCluster + apiVersion: piraeus.io/v1 + metadata: {name: linstorcluster} + spec: + externalController: + url: https://api.example.svc:3371 + asserts: + - equal: + path: metadata.annotations["secret.reloader.stakater.com/reload"] + value: linstor-client-tls + + # While a LinstorCluster still runs its own controller under blockstor, + # that controller is the API linstor-csi uses, so the scheduler stays on it. + - it: keeps the values while the LinstorCluster runs an in-cluster controller + set: + linstor-scheduler.linstor.backend: blockstor + kubernetesProvider: + scheme: *scheme + objects: + - kind: LinstorCluster + apiVersion: piraeus.io/v1 + metadata: {name: linstorcluster} + spec: {} + asserts: + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_CONTROLLERS + value: https://linstor-controller.cozy-linstor.svc:3371 + - equal: + path: metadata.annotations["secret.reloader.stakater.com/reload"] + value: linstor-client-tls + + - it: refuses blockstor when no LinstorCluster tells it where the API is + set: + linstor-scheduler.linstor.backend: blockstor + asserts: + - failedTemplate: + errorPattern: "backend is blockstor.*the cluster has 0 LinstorClusters" + + - it: refuses an unknown backend + set: + linstor-scheduler.linstor.backend: blockstore + asserts: + - failedTemplate: + errorMessage: 'linstor-scheduler.linstor.backend must be "linstor" or "blockstor", got "blockstore"' diff --git a/packages/system/linstor-scheduler/values.yaml b/packages/system/linstor-scheduler/values.yaml index e181fc8f2..854ae5940 100644 --- a/packages/system/linstor-scheduler/values.yaml +++ b/packages/system/linstor-scheduler/values.yaml @@ -9,6 +9,11 @@ linstor-scheduler: # node: this buys drain safety, not node-failure HA. replicaCount: 2 linstor: + # The storage backend the platform runs, linstor or blockstor. Under + # blockstor the endpoint and client Secret come from the LinstorCluster + # the linstor package renders (templates/_helpers.tpl), and the two + # values below apply only while it runs an in-cluster controller. + backend: linstor endpoint: "https://linstor-controller.cozy-linstor.svc:3371" clientSecret: "linstor-client-tls" admission: diff --git a/packages/system/linstor/Makefile b/packages/system/linstor/Makefile index e58fc8578..bbc9f6da1 100644 --- a/packages/system/linstor/Makefile +++ b/packages/system/linstor/Makefile @@ -10,6 +10,21 @@ LINSTOR_VERSION ?= 1.35.3 # has to be re-checked against the new one. LINSTOR_CSI_VERSION ?= v1.13.2 +# blockstor's CRDs are copied unmodified from the release its images are pinned +# to, so the schema and the binaries that read it always come from one tag. +# Bump the three blockstor image tags in values.yaml first, then run this. +BLOCKSTOR_VERSION ?= $(shell yq e '.blockstorController.image.tag' values.yaml | cut -d@ -f1) + +update-blockstor-crds: + tmpdir=$$(mktemp -d) && \ + { curl --fail --silent --show-error --location -o "$$tmpdir/source.tar.gz" \ + "https://github.com/cozystack/blockstor/archive/refs/tags/v$(BLOCKSTOR_VERSION).tar.gz" && \ + mkdir "$$tmpdir/src" && tar -xzf "$$tmpdir/source.tar.gz" --strip-components=1 -C "$$tmpdir/src" && \ + ls "$$tmpdir"/src/config/crd/bases/blockstor.cozystack.io_*.yaml >/dev/null || { rm -rf "$$tmpdir"; exit 1; }; } && \ + rm -f definitions/blockstor.cozystack.io_*.yaml && \ + cp "$$tmpdir"/src/config/crd/bases/blockstor.cozystack.io_*.yaml definitions/ && \ + rm -rf "$$tmpdir" + test: helm unittest . python3 -m unittest discover -s tests -p 'test_*.py' -v diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_controllerconfigs.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_controllerconfigs.yaml new file mode 100644 index 000000000..93fdf34c5 --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_controllerconfigs.yaml @@ -0,0 +1,337 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: controllerconfigs.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: ControllerConfig + listKind: ControllerConfigList + plural: controllerconfigs + singular: controllerconfig + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ControllerConfig is the cluster-wide singleton config for the + blockstor controller. Exactly one instance with name=`default` + is recognised; any other instance is ignored. Phase 10.4. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of ControllerConfig + properties: + drbdOptions: + description: |- + drbdOptions is the cluster-wide DRBD configuration. Acts as + the controller-scope input to the typed hierarchy resolver + (`pkg/drbd.ResolveDRBDOptions`). + properties: + disk: + description: |- + disk configures the `disk { ... }` section (on-io-error, + activity-log size, resync hints). + properties: + alExtents: + description: |- + alExtents is the activity-log size (in extents). Larger values + reduce metadata write amplification at the cost of longer + resync windows. + format: int32 + type: integer + onIoError: + description: |- + onIOError is the action when the local backing device returns + an I/O error. `detach` is the production-safe default — the + satellite drops the local replica to Diskless and consumers + keep going via the network path. + enum: + - detach + - pass-on + - call-local-io-error + type: string + type: object + handlers: + additionalProperties: + type: string + description: |- + handlers maps event names to script paths (e.g. fence-peer, + before-resync-target). Free-form for now; the rendered .res + emits one line per pair under `handlers { }`. + type: object + net: + description: |- + net configures the `net { ... }` section of the rendered .res + file (replication protocol, secret, dual-primary, after-sb). + properties: + afterSb0Pri: + description: |- + afterSb0Pri is the recovery action when DRBD detects split- + brain and both sides were Secondary at the time. + enum: + - disconnect + - discard-younger-primary + - discard-older-primary + - discard-zero-changes + - discard-least-changes + - discard-local + - discard-remote + type: string + afterSb1Pri: + description: afterSb1Pri is the recovery action when one side + was Primary. + enum: + - disconnect + - consensus + - violently-as0p + - discard-secondary + - call-pri-lost-after-sb + type: string + afterSb2Pri: + description: |- + afterSb2Pri is the recovery action when both sides were Primary + (only possible if allow-two-primaries was enabled). + enum: + - disconnect + - violently-as0p + - call-pri-lost-after-sb + type: string + allowTwoPrimaries: + description: |- + allowTwoPrimaries enables dual-primary mode (live-migration, + shared-export NFS Ganesha). Must be paired with consumer-side + fencing — DRBD does NOT serialise concurrent writes from two + primaries. + type: boolean + maxBuffers: + description: maxBuffers is the maximum number of in-flight + network buffers. + format: int32 + type: integer + protocol: + description: |- + protocol picks the DRBD replication protocol. A=async (writer + returns once data hits local disk), B=memory-sync (returns on + peer ACK after kernel buffer), C=sync (returns on peer disk + fsync). DRBD-9 default is C. + enum: + - A + - B + - C + type: string + sharedSecretRef: + description: |- + sharedSecretRef references a Secret containing the DRBD network + authentication shared secret under the key `shared-secret`. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + type: object + peerDevice: + description: |- + peerDevice configures the `peer-device { ... }` block (per-peer + resync rate caps and similar). + properties: + cMaxRate: + description: |- + cMaxRate caps the per-peer resync transfer rate. Format + matches DRBD: integer + suffix (`100M`, `1G`). + type: string + type: object + resource: + description: |- + resource configures resource-level `options { ... }` (auto- + promote, quorum mode, on-no-quorum action). + properties: + autoPromote: + description: |- + autoPromote causes DRBD to promote the resource to Primary + automatically when a consumer opens the device, provided no + other peer is already Primary. Cluster-wide default true. + type: boolean + autoTieBreaker: + description: |- + autoTieBreaker gates auto-creation of a DISKLESS+TIE_BREAKER + witness when a parent RD has an even number of diskful + replicas and no operator-placed diskless replica. Replaces + `Props["DrbdOptions/AutoAddQuorumTiebreaker"]`. nil inherits + the cluster-wide default (true). Phase 10.3. + type: boolean + onNoQuorum: + description: |- + onNoQuorum is the action when quorum is lost. `io-error` + returns EIO to the consumer (drbd-reactor's typical trigger + for failover). `suspend-io` blocks I/O until quorum returns + (useful for deliberate maintenance windows). + enum: + - io-error + - suspend-io + - freeze-io + type: string + quorum: + description: |- + quorum picks the quorum policy. `majority` requires more than + half of all replicas (including diskless witnesses) to be + connected before allowing writes. `off` allows writes from any + replica regardless of partition state — split-brain risk. + `all` requires every replica to be reachable, useful only for + strict 2-replica configurations under deliberate operator + control. + enum: + - "off" + - majority + - all + type: string + type: object + type: object + extraProps: + additionalProperties: + type: string + description: |- + extraProps carries upstream-LINSTOR-shaped Props keys we have + not yet typed into structured fields. Forward-compat shim + populated only by the REST shim when golinstor sends an + unknown key. Drained as we type more fields here. + type: object + nodeConnections: + additionalProperties: + additionalProperties: + type: string + type: object + description: |- + nodeConnections is the per-(nodeA,nodeB) property bag exposed + at `/v1/node-connections/{nodeA}/{nodeB}` — backs upstream + LINSTOR's `linstor node-connection set-property / list` CLI + (Bug 101). Keys are the canonical pair-id `::` where + `` and `` are the lexicographically lower / higher of + the two node names — so a write against (A,B) and a read + against (B,A) hit the same record without the caller having + to remember any ordering convention. + + Stored on the cluster-wide ControllerConfig singleton rather + than a per-pair CRD: upstream LINSTOR persists these on a + flat in-memory matrix attached to the Controller, and the + cozystack node-connection use case is overwhelmingly empty + or one-off ("flag this pair as cross-site"). A dedicated CRD + per pair would add admission/RBAC surface for a feature that + in practice carries ≤ a handful of rows on any given cluster. + type: object + passphraseSecretRef: + description: |- + passphraseSecretRef points at the Secret carrying the + cluster-wide LUKS passphrase under the key `passphrase`. The + satellite reads it via the apiserver during reconcile; + passphrase never lands on Spec in plaintext. Replaces + `Props["DrbdOptions/Encryption/passphrase"]` on the legacy + ControllerProps instance. + properties: + name: + description: name is the Secret name. Required. + type: string + required: + - name + type: object + type: object + status: + description: status defines the observed state of ControllerConfig + properties: + conditions: + description: |- + conditions track the current state of the ControllerConfig + (e.g. PassphraseSecretFound, DRBDOptionsValid). + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_nodes.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_nodes.yaml new file mode 100644 index 000000000..c94128ed1 --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_nodes.yaml @@ -0,0 +1,252 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: nodes.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: Node + listKind: NodeList + plural: nodes + singular: node + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: Node is the Schema for the nodes API + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of Node + properties: + drbdMinorRange: + description: |- + drbdMinorRange is the inclusive [min, max] /dev/drbd minor + range the allocator picks from. Replaces + `Props["DrbdOptions/MinorNrRange"]`. nil inherits the + controller-wide default (20000–65535). Phase 10.3. + properties: + max: + description: max is the upper bound (inclusive). Must be ≥ Min. + format: int32 + minimum: 0 + type: integer + min: + description: min is the lower bound (inclusive). + format: int32 + minimum: 0 + type: integer + required: + - max + - min + type: object + drbdPortRange: + description: |- + drbdPortRange is the inclusive [min, max] TCP port range the + allocator picks DRBD listen ports from for replicas placed on + this node. Replaces `Props["DrbdOptions/TcpPortRange"]`. nil + inherits the controller-wide default (20000–20999). Phase 10.3. + properties: + max: + description: max is the upper bound (inclusive). Must be ≥ Min. + format: int32 + minimum: 0 + type: integer + min: + description: min is the lower bound (inclusive). + format: int32 + minimum: 0 + type: integer + required: + - max + - min + type: object + flags: + description: |- + flags is the desired set of LINSTOR flags. Most node flags are + observed (computed by the satellite); set via spec only those that + are user-controlled. + items: + type: string + type: array + netInterfaces: + description: |- + netInterfaces is the desired list of advertised network interfaces. + The first interface is treated as the satellite endpoint. + items: + description: NodeNetInterface is one advertised endpoint of a satellite. + properties: + address: + description: address is the IP address of the endpoint. + type: string + name: + description: name is the user-facing identifier ("default", + "drbd-net", etc.). + type: string + satelliteEncryptionType: + description: satelliteEncryptionType is "PLAIN" or "SSL". + enum: + - PLAIN + - SSL + type: string + satellitePort: + description: satellitePort is the port the satellite listens + on; 0 means default. + format: int32 + type: integer + required: + - address + - name + type: object + type: array + props: + additionalProperties: + type: string + description: |- + props is the LINSTOR property map for this node. Keys are LINSTOR + namespace paths (e.g. `Aux/foo`, `DrbdOptions/Net/...`). + type: object + satelliteEndpoint: + description: |- + satelliteEndpoint is the controller→satellite gRPC endpoint + (`host:port`). Phase 10.3: replaces `Props["SatelliteEndpoint"]` + — the dispatcher reads this typed field first, falling back to + the props bag for forward-compat with pre-migration data. The + field becomes irrelevant once Phase 10.6 lands and the gRPC + path is gone. + type: string + type: + description: |- + type is the LINSTOR node role. Common values: SATELLITE, COMBINED, + CONTROLLER, AUXILIARY. + enum: + - CONTROLLER + - SATELLITE + - COMBINED + - AUXILIARY + - REMOTE_SPDK + - OPENFLEX_TARGET + - EBS_TARGET + - EBS_INIT + type: string + required: + - type + type: object + status: + description: status defines the observed state of Node + properties: + conditions: + description: |- + conditions represents the current state of the Node resource. + The well-known `Ready` condition (status=True when the satellite + is healthy, Unknown when its heartbeat is stale, False when the + satellite reports a fatal state) is what consumers should look + at. Other conditions may follow as we surface more invariants. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + connectionStatus: + description: |- + connectionStatus is a coarse projection of the Ready condition + (ONLINE when Ready=True, OFFLINE when False/Unknown) kept for + kubectl-friendly columns + golinstor round-trip compatibility. + Written by the controller-side heartbeat watchdog; do not hand-set. + type: string + flags: + description: flags computed by the satellite (e.g. EVICTED, EVACUATING). + items: + type: string + type: array + lastHeartbeatTime: + description: |- + lastHeartbeatTime is when this node's satellite last stamped the + status (kubelet-style liveness). The controller-side watchdog + flips the Ready condition to Unknown when this is older than the + node-monitor grace period. Updated on every satellite reconcile + tick regardless of state changes — the "did we hear from this + satellite recently?" signal. + format: date-time + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_physicaldevices.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_physicaldevices.yaml new file mode 100644 index 000000000..3dfcef46e --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_physicaldevices.yaml @@ -0,0 +1,229 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: physicaldevices.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: PhysicalDevice + listKind: PhysicalDeviceList + plural: physicaldevices + singular: physicaldevice + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + PhysicalDevice is one raw block device discovered on a satellite. + Phase 10.7 — replaces the upstream `linstor physical-storage` + PropsContainers / gRPC pattern. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of PhysicalDevice + properties: + attachTo: + description: |- + attachTo is the controller-side request that this device be + added to the named pool. Empty/nil means "available". Phase + 10.7 step 2 wires the REST endpoint that flips this; until + then operators can edit the CRD directly. + properties: + directory: + description: |- + directory is the mount-point where a FILE / FILE_THIN + pool's backing files live. The satellite formats + mounts + the device on this path before flipping the pool to + available. + type: string + providerKind: + description: |- + providerKind picks the storage backend ("LVM", "LVM_THIN", + "ZFS", "ZFS_THIN", "FILE", "FILE_THIN"). + enum: + - LVM + - LVM_THIN + - ZFS + - ZFS_THIN + - FILE + - FILE_THIN + type: string + storagePoolName: + description: |- + storagePoolName is the target pool name (matches the + upstream LINSTOR pool name a Resource refers to). + type: string + thinPoolName: + description: |- + thinPoolName is the LVM thin pool to create on top of VG + (LVM_THIN only). Ignored otherwise. + type: string + vgName: + description: |- + vgName is the LVM volume group to create (LVM / LVM_THIN + kinds). Ignored otherwise. + type: string + wipe: + description: |- + wipe is the explicit consent flag the operator must set to + `true` to allow the satellite to overwrite existing on-disk + signatures (LVM/ZFS/MD/filesystems). Without it the attach + fails with `Status.Phase=Failed` rather than risk data loss. + type: boolean + zPoolName: + description: |- + zPoolName is the ZFS zpool to create (ZFS / ZFS_THIN + kinds). Ignored otherwise. + type: string + required: + - providerKind + - storagePoolName + type: object + type: object + status: + description: status defines the observed state of PhysicalDevice + properties: + conditions: + description: |- + conditions carry detailed state (e.g. `WipeRequired` when + the device has on-disk signatures and `Spec.AttachTo.Wipe` + is false). + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + currentDevPath: + description: |- + currentDevPath is the volatile `/dev/sdN` or `/dev/nvmeNnN` + path from the most recent discovery tick. Refreshed on + every discovery — operators MUST NOT rely on this being + stable across reboots. + type: string + devicePath: + description: |- + devicePath is the canonical /dev/disk/by-id symlink the + satellite uses internally. Stable across reboots (unless the + device is physically replaced). + type: string + model: + description: model carries the manufacturer model string (lsblk MODEL). + type: string + nodeName: + description: nodeName is the satellite that owns this device. + type: string + phase: + description: phase is the discovery + attach state. + enum: + - Available + - Attaching + - Failed + type: string + rotational: + description: |- + rotational reflects the kernel's view of the spindle — + false for SSD/NVMe, true for HDD. Used by the autoplacer + to bias placement when ResourceGroup says so. + type: boolean + serial: + description: |- + serial carries the device serial number when reported by + the firmware. Some virtualised setups (virtio without + serial passthrough) leave this empty. + type: string + sizeBytes: + description: sizeBytes is the device size as reported by `lsblk -o + SIZE`. + format: int64 + type: integer + stableID: + description: |- + stableID is the stable identifier the satellite picked from + `/dev/disk/by-id/...` (preferring `wwn-*` → `scsi-SATA_*` + → `nvme-*` → `by-path/*`). The CRD's metadata.name is + derived from this so it survives `/dev/sdN` re-lettering. + type: string + transport: + description: transport is the bus type ("sata", "nvme", "scsi", "virtio"). + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_resourcedefinitions.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_resourcedefinitions.yaml new file mode 100644 index 000000000..08e2b98d8 --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_resourcedefinitions.yaml @@ -0,0 +1,499 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: resourcedefinitions.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: ResourceDefinition + listKind: ResourceDefinitionList + plural: resourcedefinitions + singular: resourcedefinition + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: ResourceDefinition is the Schema for the resourcedefinitions + API + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of ResourceDefinition + properties: + drbdOptions: + description: |- + drbdOptions is the typed DRBD configuration applied to this + RD. Overrides the parent ResourceGroup's drbdOptions + field-by-field; in turn overridden by per-Resource drbdOptions + at the Resource scope. Phase 10.3. + properties: + disk: + description: |- + disk configures the `disk { ... }` section (on-io-error, + activity-log size, resync hints). + properties: + alExtents: + description: |- + alExtents is the activity-log size (in extents). Larger values + reduce metadata write amplification at the cost of longer + resync windows. + format: int32 + type: integer + onIoError: + description: |- + onIOError is the action when the local backing device returns + an I/O error. `detach` is the production-safe default — the + satellite drops the local replica to Diskless and consumers + keep going via the network path. + enum: + - detach + - pass-on + - call-local-io-error + type: string + type: object + handlers: + additionalProperties: + type: string + description: |- + handlers maps event names to script paths (e.g. fence-peer, + before-resync-target). Free-form for now; the rendered .res + emits one line per pair under `handlers { }`. + type: object + net: + description: |- + net configures the `net { ... }` section of the rendered .res + file (replication protocol, secret, dual-primary, after-sb). + properties: + afterSb0Pri: + description: |- + afterSb0Pri is the recovery action when DRBD detects split- + brain and both sides were Secondary at the time. + enum: + - disconnect + - discard-younger-primary + - discard-older-primary + - discard-zero-changes + - discard-least-changes + - discard-local + - discard-remote + type: string + afterSb1Pri: + description: afterSb1Pri is the recovery action when one side + was Primary. + enum: + - disconnect + - consensus + - violently-as0p + - discard-secondary + - call-pri-lost-after-sb + type: string + afterSb2Pri: + description: |- + afterSb2Pri is the recovery action when both sides were Primary + (only possible if allow-two-primaries was enabled). + enum: + - disconnect + - violently-as0p + - call-pri-lost-after-sb + type: string + allowTwoPrimaries: + description: |- + allowTwoPrimaries enables dual-primary mode (live-migration, + shared-export NFS Ganesha). Must be paired with consumer-side + fencing — DRBD does NOT serialise concurrent writes from two + primaries. + type: boolean + maxBuffers: + description: maxBuffers is the maximum number of in-flight + network buffers. + format: int32 + type: integer + protocol: + description: |- + protocol picks the DRBD replication protocol. A=async (writer + returns once data hits local disk), B=memory-sync (returns on + peer ACK after kernel buffer), C=sync (returns on peer disk + fsync). DRBD-9 default is C. + enum: + - A + - B + - C + type: string + sharedSecretRef: + description: |- + sharedSecretRef references a Secret containing the DRBD network + authentication shared secret under the key `shared-secret`. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + type: object + peerDevice: + description: |- + peerDevice configures the `peer-device { ... }` block (per-peer + resync rate caps and similar). + properties: + cMaxRate: + description: |- + cMaxRate caps the per-peer resync transfer rate. Format + matches DRBD: integer + suffix (`100M`, `1G`). + type: string + type: object + resource: + description: |- + resource configures resource-level `options { ... }` (auto- + promote, quorum mode, on-no-quorum action). + properties: + autoPromote: + description: |- + autoPromote causes DRBD to promote the resource to Primary + automatically when a consumer opens the device, provided no + other peer is already Primary. Cluster-wide default true. + type: boolean + autoTieBreaker: + description: |- + autoTieBreaker gates auto-creation of a DISKLESS+TIE_BREAKER + witness when a parent RD has an even number of diskful + replicas and no operator-placed diskless replica. Replaces + `Props["DrbdOptions/AutoAddQuorumTiebreaker"]`. nil inherits + the cluster-wide default (true). Phase 10.3. + type: boolean + onNoQuorum: + description: |- + onNoQuorum is the action when quorum is lost. `io-error` + returns EIO to the consumer (drbd-reactor's typical trigger + for failover). `suspend-io` blocks I/O until quorum returns + (useful for deliberate maintenance windows). + enum: + - io-error + - suspend-io + - freeze-io + type: string + quorum: + description: |- + quorum picks the quorum policy. `majority` requires more than + half of all replicas (including diskless witnesses) to be + connected before allowing writes. `off` allows writes from any + replica regardless of partition state — split-brain risk. + `all` requires every replica to be reachable, useful only for + strict 2-replica configurations under deliberate operator + control. + enum: + - "off" + - majority + - all + type: string + type: object + type: object + drbdPort: + description: |- + drbdPort is an OPTIONAL preferred TCP port seed for this RD, + mirroring upstream LINSTOR's `RscDfn.port` preferred value. The + per-node port allocator (Resource.Spec.DRBDPort) tries this + value first on each hosting node and falls back to a per-node + free port on collision. nil means "no preference — allocate + per-node freely". This is a seed, NOT the authoritative + listen-port: the authoritative per-replica value lives on + Resource.Spec.DRBDPort. clusterIP-style settable-once so an + accidental edit can't perturb the per-node allocation. + format: int32 + type: integer + x-kubernetes-validations: + - message: drbdPort is settable-once + optionalOldSelf: true + rule: '!oldSelf.hasValue() || self == oldSelf.value()' + encryption: + description: |- + encryption configures LUKS encryption for the volumes in this + RD. The passphrase is held in a referenced Secret rather than + inline in the spec. Phase 10.3. + properties: + passphraseSecretRef: + description: |- + passphraseSecretRef references the Secret carrying the LUKS + passphrase under the key `passphrase`. The satellite reads it + via the apiserver during reconcile; the passphrase never lands + on Spec in plaintext. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + type: object + externalName: + description: |- + externalName is the user-facing name surfaced by csi (CSI volume id). + Empty means the same as metadata.name. + type: string + extraProps: + additionalProperties: + type: string + description: |- + extraProps carries upstream-LINSTOR property keys we have not + yet typed into structured fields. Forward-compat shim populated + only by the REST shim when golinstor sends an unknown key. + Phase 10.3. + type: object + flags: + description: flags carries user-controlled RD flags (DELETE, INACTIVE, + ...). + items: + type: string + type: array + initialized: + description: |- + initialized is the durable "this RD has completed its initial + replica-set establishment and now holds (or has held) committed + data" latch. The controller flips it true ONCE, append-only, the + first time any diskful replica of the RD reports a real + data-bearing disk state that has advanced past the deterministic + day0 GI (a genuine write, or an adoption of pre-existing data) — + see ResourceReconciler.ensureRDInitialized. Once true it is NEVER + cleared or mutated. + + It is the OFFLINE-SAFE, BACKUP-SAFE source of truth for the + skip-initial-sync decision (replaces the live-kernel + AnyConnectedPeerHasData probe as the authoritative signal): + + - A Resource created while initialized is nil/false is part of + the genuinely-fresh initial set — every such replica is + stamped Spec.SkipInitialSync=true and skips the initial sync + (instant UpToDate, no SyncTarget). Invariant 1. + - A Resource created AFTER initialized latched true (relocate / + migrate-disk / extra replica) is stamped + Spec.SkipInitialSync=false and must SyncTarget the real data — + EVEN IF the sole data-holder is offline at seed time, because + this latch was set while the data was being written (holder + online) and PERSISTS in Spec across the holder going offline. + Invariant 2 + offline-safety. + + Lives in Spec (backed up by `kubectl get -o yaml`, restored by + `kubectl apply`), NOT Status — a restored, already-initialized RD + must keep forcing new replicas to sync rather than skip. Invariant + 3 (backup/restore-safe). + + clusterIP-style append-only: nil means "not yet initialized" (the + conservative pre-upgrade / fresh default → fresh replicas may skip, + the controller flips it on first real data). The controller writes + it only when transitioning nil/false→true and never otherwise, so + a user `kubectl apply` / golinstor REST that omits it never fights + the controller (3-way-merge-safe — invariant 4). + type: boolean + x-kubernetes-validations: + - message: 'initialized is append-only: it may go unset→value or false→true + but never back to false' + optionalOldSelf: true + rule: '!oldSelf.hasValue() || self == oldSelf.value() || (oldSelf.value() + == false && self == true)' + layerStack: + description: |- + layerStack is the LINSTOR layer composition for this RD's + satellite-side render — `["DRBD","STORAGE"]` (default) renders a + .res file and runs drbdadm; `["LUKS","STORAGE"]` layers + cryptsetup over the storage device with no DRBD; `["STORAGE"]` + is single-replica local mode (no replication, no encryption). + Order is top-down: the first layer's device is what the + consumer Pod mounts, the last is the raw block device the + storage provider creates. + Empty = inherits from the parent ResourceGroup; both empty = + `["DRBD","STORAGE"]`. + items: + type: string + type: array + props: + additionalProperties: + type: string + description: props is the LINSTOR property map. + type: object + resourceGroupName: + description: |- + resourceGroupName references the ResourceGroup template this RD was + spawned from (or empty if directly created). + type: string + volumeDefinitions: + description: volumeDefinitions are the volume slots inside this RD. + items: + description: ResourceDefinitionVolume is one volume slot inside + an RD. + properties: + drbdMinor: + description: |- + drbdMinor is the /dev/drbd device minor for THIS volume, + identical on every node that hosts a replica (the minor is the + device identity, not a per-replica value). Mirrors upstream + LINSTOR's per-volume-definition `VLM_MINOR_NR`. + + clusterIP-style allocation (Service.spec.clusterIP model): nil + means "controller, allocate one for me"; a non-nil value is + authoritative and is NEVER overwritten — that is what makes a + plain `kubectl get -o yaml` backup + `kubectl apply` restore + preserve the device identity with no resync/flap. The pointer + (rather than a plain int32) distinguishes "unset" from a valid + minor 0. + + Replaces the legacy single `RD.Status.DRBDMinor` base + + `base+volumeNumber` derivation: each volume carries its own + minor, so adoption can preserve arbitrary (possibly + non-contiguous) LINSTOR per-volume minors verbatim. + + NOTE: no CEL settable-once rule here. volumeDefinitions is a + plain (uncorrelatable) array — CEL `oldSelf` cannot track an + element across an update, so a transition rule on a nested + array field is rejected by the apiserver. Immutability is + instead enforced by the controller's allocate-if-nil / + respect-preset pass (it NEVER overwrites a non-nil minor) plus + the store-side VolumeDefinitions carry-across that preserves the + value through a REST modify. The settable-once CEL is retained + on the (correlatable scalar) Resource.Spec.DRBDPort / DRBDNodeID + and RD.Spec.DRBDPort fields. + format: int32 + type: integer + flags: + items: + type: string + type: array + props: + additionalProperties: + type: string + type: object + sizeKib: + format: int64 + type: integer + volumeNumber: + format: int32 + type: integer + required: + - sizeKib + - volumeNumber + type: object + type: array + type: object + status: + description: status defines the observed state of ResourceDefinition + properties: + conditions: + description: conditions represent the current state of the ResourceDefinition. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + drbdMinor: + description: |- + drbdMinor is a LEGACY read-only mirror of the (historically + cluster-scope, base+k) DRBD minor. DEPRECATED: the authoritative + per-volume minor now lives on + ResourceDefinition.Spec.VolumeDefinitions[].DRBDMinor. Retained + so the one-time status→spec backfill migration can read the + pre-upgrade base value (expanded base+k per volume). Not written + by the allocator any more. Bug 268. + format: int32 + type: integer + drbdPort: + description: |- + drbdPort is a LEGACY read-only mirror of the (historically + cluster-scope) DRBD port. DEPRECATED: the authoritative DRBD + listen-port now lives per-replica on Resource.Spec.DRBDPort, + and the optional preferred seed on RD.Spec.DRBDPort. Retained + so the one-time status→spec backfill migration can read the + pre-upgrade value, and so observers/REST that still read it + don't break in the same change. Not written by the allocator + any more. Bug 266. + format: int32 + type: integer + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_resourcegroups.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_resourcegroups.yaml new file mode 100644 index 000000000..8515b5aef --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_resourcegroups.yaml @@ -0,0 +1,377 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: resourcegroups.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: ResourceGroup + listKind: ResourceGroupList + plural: resourcegroups + singular: resourcegroup + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: ResourceGroup is the Schema for the resourcegroups API + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of ResourceGroup + properties: + description: + description: description is human-readable. + type: string + drbdOptions: + description: |- + drbdOptions is the typed DRBD configuration applied to every + ResourceDefinition spawned from this ResourceGroup. Lower scope + (RD, Resource) overrides this field-by-field. Phase 10.3. + properties: + disk: + description: |- + disk configures the `disk { ... }` section (on-io-error, + activity-log size, resync hints). + properties: + alExtents: + description: |- + alExtents is the activity-log size (in extents). Larger values + reduce metadata write amplification at the cost of longer + resync windows. + format: int32 + type: integer + onIoError: + description: |- + onIOError is the action when the local backing device returns + an I/O error. `detach` is the production-safe default — the + satellite drops the local replica to Diskless and consumers + keep going via the network path. + enum: + - detach + - pass-on + - call-local-io-error + type: string + type: object + handlers: + additionalProperties: + type: string + description: |- + handlers maps event names to script paths (e.g. fence-peer, + before-resync-target). Free-form for now; the rendered .res + emits one line per pair under `handlers { }`. + type: object + net: + description: |- + net configures the `net { ... }` section of the rendered .res + file (replication protocol, secret, dual-primary, after-sb). + properties: + afterSb0Pri: + description: |- + afterSb0Pri is the recovery action when DRBD detects split- + brain and both sides were Secondary at the time. + enum: + - disconnect + - discard-younger-primary + - discard-older-primary + - discard-zero-changes + - discard-least-changes + - discard-local + - discard-remote + type: string + afterSb1Pri: + description: afterSb1Pri is the recovery action when one side + was Primary. + enum: + - disconnect + - consensus + - violently-as0p + - discard-secondary + - call-pri-lost-after-sb + type: string + afterSb2Pri: + description: |- + afterSb2Pri is the recovery action when both sides were Primary + (only possible if allow-two-primaries was enabled). + enum: + - disconnect + - violently-as0p + - call-pri-lost-after-sb + type: string + allowTwoPrimaries: + description: |- + allowTwoPrimaries enables dual-primary mode (live-migration, + shared-export NFS Ganesha). Must be paired with consumer-side + fencing — DRBD does NOT serialise concurrent writes from two + primaries. + type: boolean + maxBuffers: + description: maxBuffers is the maximum number of in-flight + network buffers. + format: int32 + type: integer + protocol: + description: |- + protocol picks the DRBD replication protocol. A=async (writer + returns once data hits local disk), B=memory-sync (returns on + peer ACK after kernel buffer), C=sync (returns on peer disk + fsync). DRBD-9 default is C. + enum: + - A + - B + - C + type: string + sharedSecretRef: + description: |- + sharedSecretRef references a Secret containing the DRBD network + authentication shared secret under the key `shared-secret`. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + type: object + peerDevice: + description: |- + peerDevice configures the `peer-device { ... }` block (per-peer + resync rate caps and similar). + properties: + cMaxRate: + description: |- + cMaxRate caps the per-peer resync transfer rate. Format + matches DRBD: integer + suffix (`100M`, `1G`). + type: string + type: object + resource: + description: |- + resource configures resource-level `options { ... }` (auto- + promote, quorum mode, on-no-quorum action). + properties: + autoPromote: + description: |- + autoPromote causes DRBD to promote the resource to Primary + automatically when a consumer opens the device, provided no + other peer is already Primary. Cluster-wide default true. + type: boolean + autoTieBreaker: + description: |- + autoTieBreaker gates auto-creation of a DISKLESS+TIE_BREAKER + witness when a parent RD has an even number of diskful + replicas and no operator-placed diskless replica. Replaces + `Props["DrbdOptions/AutoAddQuorumTiebreaker"]`. nil inherits + the cluster-wide default (true). Phase 10.3. + type: boolean + onNoQuorum: + description: |- + onNoQuorum is the action when quorum is lost. `io-error` + returns EIO to the consumer (drbd-reactor's typical trigger + for failover). `suspend-io` blocks I/O until quorum returns + (useful for deliberate maintenance windows). + enum: + - io-error + - suspend-io + - freeze-io + type: string + quorum: + description: |- + quorum picks the quorum policy. `majority` requires more than + half of all replicas (including diskless witnesses) to be + connected before allowing writes. `off` allows writes from any + replica regardless of partition state — split-brain risk. + `all` requires every replica to be reachable, useful only for + strict 2-replica configurations under deliberate operator + control. + enum: + - "off" + - majority + - all + type: string + type: object + type: object + extraProps: + additionalProperties: + type: string + description: |- + extraProps carries upstream-LINSTOR property keys we have not + yet typed into structured fields. Populated only by the REST + compatibility shim when golinstor sends a key we don't + recognise. Operators editing via kubectl should prefer the + typed fields above. Phase 10.3. + type: object + peerSlots: + description: peerSlots is the DRBD peer-slot count baked into spawned + resources. + format: int32 + type: integer + props: + additionalProperties: + type: string + description: props is the LINSTOR property map for this resource group. + type: object + selectFilter: + description: |- + selectFilter constrains autoplacer when spawning resources from this + group. + properties: + disklessOnRemaining: + type: boolean + layerStack: + items: + type: string + type: array + nodeNameList: + items: + type: string + type: array + notPlaceWithRsc: + items: + type: string + type: array + notPlaceWithRscRegex: + type: string + placeCount: + format: int32 + type: integer + providerList: + items: + type: string + type: array + replicasOnDifferent: + items: + type: string + type: array + replicasOnSame: + items: + type: string + type: array + storagePool: + type: string + storagePoolDisklessList: + items: + type: string + type: array + storagePoolList: + items: + type: string + type: array + type: object + volumeGroups: + description: volumeGroups templates the per-volume props/flags for + spawned resources. + items: + description: ResourceGroupVolumeGroup is one volume's template inside + a ResourceGroup. + properties: + flags: + items: + type: string + type: array + props: + additionalProperties: + type: string + type: object + volumeNumber: + format: int32 + type: integer + required: + - volumeNumber + type: object + type: array + type: object + status: + description: status defines the observed state of ResourceGroup + properties: + conditions: + description: conditions represent the current state of the ResourceGroup. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_resources.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_resources.yaml new file mode 100644 index 000000000..a360db9f3 --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_resources.yaml @@ -0,0 +1,762 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: resources.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: Resource + listKind: ResourceList + plural: resources + singular: resource + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Resource is the Schema for the resources API. + + The CEL rule above enforces the cluster-wide naming convention every + node-bound CRD in the project follows: `metadata.name == .`. + Keeping the composite key encoded in the name lets operators grep for + `.` across kinds (Resource, Snapshot, StoragePool) and find every + resource bound to one satellite at once. + + BUG-047: the comparison is case-INSENSITIVE (.lowerAscii() on both + sides), mirroring StoragePool. LINSTOR identifiers are case-insensitive + and the k8s store's Name() helper lowercases metadata.name, while + spec.resourceDefinitionName preserves the caller's original case. With + an uppercase RD name (e.g. csi-sanity's `…BA880D4F…`) a case-SENSITIVE + rule rejected the Resource create with "must equal" even though the + names address the same object. lowerAscii() on both sides keeps the + `.` convention intact while tolerating case differences. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of Resource + properties: + drbdNodeID: + description: |- + drbdNodeID is the DRBD-9 node-id assigned to this replica. + Per-replica, allocated once and stable for the replica's life — + re-numbering a live replica re-maps its DRBD bitmaps and + corrupts peer-to-peer resync. Range 0..15 (drbd-9 max-peers). + + clusterIP-style allocation: nil means "controller, allocate"; + non-nil is authoritative and NEVER overwritten (restore-safe). + Pointer distinguishes "unset" from a valid node-id 0 + (LowestFreeNodeID hands out 0 for the first/freed slot). + format: int32 + type: integer + x-kubernetes-validations: + - message: 'drbdNodeID is settable-once: it may go from unset to a + value but not be changed once set' + optionalOldSelf: true + rule: '!oldSelf.hasValue() || self == oldSelf.value()' + drbdOptions: + description: |- + drbdOptions is the typed DRBD configuration applied to this + specific replica. Overrides the parent RD's drbdOptions + field-by-field. Rare — most config lives at RD or RG scope. + Phase 10.3. + properties: + disk: + description: |- + disk configures the `disk { ... }` section (on-io-error, + activity-log size, resync hints). + properties: + alExtents: + description: |- + alExtents is the activity-log size (in extents). Larger values + reduce metadata write amplification at the cost of longer + resync windows. + format: int32 + type: integer + onIoError: + description: |- + onIOError is the action when the local backing device returns + an I/O error. `detach` is the production-safe default — the + satellite drops the local replica to Diskless and consumers + keep going via the network path. + enum: + - detach + - pass-on + - call-local-io-error + type: string + type: object + handlers: + additionalProperties: + type: string + description: |- + handlers maps event names to script paths (e.g. fence-peer, + before-resync-target). Free-form for now; the rendered .res + emits one line per pair under `handlers { }`. + type: object + net: + description: |- + net configures the `net { ... }` section of the rendered .res + file (replication protocol, secret, dual-primary, after-sb). + properties: + afterSb0Pri: + description: |- + afterSb0Pri is the recovery action when DRBD detects split- + brain and both sides were Secondary at the time. + enum: + - disconnect + - discard-younger-primary + - discard-older-primary + - discard-zero-changes + - discard-least-changes + - discard-local + - discard-remote + type: string + afterSb1Pri: + description: afterSb1Pri is the recovery action when one side + was Primary. + enum: + - disconnect + - consensus + - violently-as0p + - discard-secondary + - call-pri-lost-after-sb + type: string + afterSb2Pri: + description: |- + afterSb2Pri is the recovery action when both sides were Primary + (only possible if allow-two-primaries was enabled). + enum: + - disconnect + - violently-as0p + - call-pri-lost-after-sb + type: string + allowTwoPrimaries: + description: |- + allowTwoPrimaries enables dual-primary mode (live-migration, + shared-export NFS Ganesha). Must be paired with consumer-side + fencing — DRBD does NOT serialise concurrent writes from two + primaries. + type: boolean + maxBuffers: + description: maxBuffers is the maximum number of in-flight + network buffers. + format: int32 + type: integer + protocol: + description: |- + protocol picks the DRBD replication protocol. A=async (writer + returns once data hits local disk), B=memory-sync (returns on + peer ACK after kernel buffer), C=sync (returns on peer disk + fsync). DRBD-9 default is C. + enum: + - A + - B + - C + type: string + sharedSecretRef: + description: |- + sharedSecretRef references a Secret containing the DRBD network + authentication shared secret under the key `shared-secret`. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + type: object + peerDevice: + description: |- + peerDevice configures the `peer-device { ... }` block (per-peer + resync rate caps and similar). + properties: + cMaxRate: + description: |- + cMaxRate caps the per-peer resync transfer rate. Format + matches DRBD: integer + suffix (`100M`, `1G`). + type: string + type: object + resource: + description: |- + resource configures resource-level `options { ... }` (auto- + promote, quorum mode, on-no-quorum action). + properties: + autoPromote: + description: |- + autoPromote causes DRBD to promote the resource to Primary + automatically when a consumer opens the device, provided no + other peer is already Primary. Cluster-wide default true. + type: boolean + autoTieBreaker: + description: |- + autoTieBreaker gates auto-creation of a DISKLESS+TIE_BREAKER + witness when a parent RD has an even number of diskful + replicas and no operator-placed diskless replica. Replaces + `Props["DrbdOptions/AutoAddQuorumTiebreaker"]`. nil inherits + the cluster-wide default (true). Phase 10.3. + type: boolean + onNoQuorum: + description: |- + onNoQuorum is the action when quorum is lost. `io-error` + returns EIO to the consumer (drbd-reactor's typical trigger + for failover). `suspend-io` blocks I/O until quorum returns + (useful for deliberate maintenance windows). + enum: + - io-error + - suspend-io + - freeze-io + type: string + quorum: + description: |- + quorum picks the quorum policy. `majority` requires more than + half of all replicas (including diskless witnesses) to be + connected before allowing writes. `off` allows writes from any + replica regardless of partition state — split-brain risk. + `all` requires every replica to be reachable, useful only for + strict 2-replica configurations under deliberate operator + control. + enum: + - "off" + - majority + - all + type: string + type: object + type: object + drbdPort: + description: |- + drbdPort is the TCP port THIS replica listens on for the RD's + DRBD replication mesh. PER-NODE (per-replica): the allocator's + taken-set is the ports already used by OTHER Resources ON THE + SAME NODE, so the same port number is freely reused across + different nodes — this scales to 1000+ resources per node + instead of exhausting a cluster-unique 20000-20999 window at + ~1000 resources cluster-wide. The optional RD.Spec.DRBDPort + preferred seed is tried first on each node. + + clusterIP-style allocation (Service.spec.clusterIP model): nil + means "controller, allocate one for me"; non-nil is + authoritative and is NEVER overwritten — that is what makes a + `kubectl get -o yaml` backup + `kubectl apply` restore preserve + the port with no flap. The pointer distinguishes "unset" from a + valid port 0 (never allocated, but kept for type symmetry). The + .res renderer puts each peer's own Spec.DRBDPort into that + peer's `on ` block. + format: int32 + type: integer + x-kubernetes-validations: + - message: 'drbdPort is settable-once: it may go from unset to a value + but not be changed once set' + optionalOldSelf: true + rule: '!oldSelf.hasValue() || self == oldSelf.value()' + extraProps: + additionalProperties: + type: string + description: |- + extraProps carries upstream-LINSTOR property keys we have not + yet typed into structured fields. Forward-compat shim populated + only by the REST shim when golinstor sends an unknown key. + Phase 10.3. + type: object + flags: + description: flags carries the user-controlled placement flags. + items: + type: string + type: array + nodeName: + description: nodeName is the satellite hosting this replica. + type: string + props: + additionalProperties: + type: string + description: props is the LINSTOR per-resource property map. + type: object + resourceDefinitionName: + description: resourceDefinitionName is the parent ResourceDefinition. + type: string + skipInitialSync: + description: |- + skipInitialSync is the controller-authoritative, persisted decision + of whether THIS replica may skip the DRBD initial sync (come up + instantly UpToDate via the day0 `set-gi` seed) or MUST run a real + SyncTarget from a data-bearing peer. Stamped ONCE at first reconcile + (append-only, set-if-nil, never mutated) as + `!ResourceDefinition.Spec.Initialized`: + + - true → the replica was created while its RD was still a + genuinely-fresh, never-written initial set (RD.Spec.Initialized + nil/false). It is safe to seed the day0 skip → instant UpToDate, + out_of_sync=0, no SyncTarget. The whole initial replica set is + stamped true together, so a fresh 2-/3-replica deployment skips + in lock-step (invariant 1). + - false → the replica joined an RD that had ALREADY held committed + data (RD.Spec.Initialized==true): relocate, migrate-disk, or an + extra replica. It MUST NOT skip — it comes up Inconsistent and + SyncTargets the real data from a peer (invariant 2). This holds + EVEN IF the sole data-holder is offline at seed time, because + the decision is read from the persisted RD latch, NOT from live + kernel/peer state (offline-safety + the core fix). + + This REPLACES the satellite's live-kernel AnyConnectedPeerHasData + probe as the authoritative skip decision (that probe is unsafe: it + only sees CONNECTED peers, so an offline data-holder made a fresh + replica skip → falsely UpToDate while EMPTY). The probe is retained + only as a defense-in-depth secondary veto. + + clusterIP-style: nil means "controller, decide and stamp me" + (conservative pre-upgrade / pre-stamp default in resolveVolumeSeed: + do NOT skip — full sync, invariant 5). A non-nil value is + authoritative and NEVER overwritten — restore-safe (invariant 3) + and 3-way-merge-safe (the user never sets it → it is never in their + last-applied → `kubectl apply` / golinstor REST that omit it never + strip it; invariant 4). + type: boolean + x-kubernetes-validations: + - message: 'skipInitialSync is settable-once: it may go from unset + to a value but not be changed once set' + optionalOldSelf: true + rule: '!oldSelf.hasValue() || self == oldSelf.value()' + storagePool: + description: |- + storagePool is the LINSTOR storage pool name this replica + allocates from. Replaces `Spec.Props["StorPoolName"]` (which + the dispatcher's buildVolumes already prefers when set). + Phase 10.3 step. + type: string + toggleDiskCancel: + description: |- + toggleDiskCancel asks the satellite reconciler to abort an + in-flight diskless→diskful conversion and roll back to the + pre-toggle Diskless state. Set by the REST shim when the + operator passes `?cancel=true` to PUT toggle-disk (upstream + LINSTOR's `linstor r td --cancel` shape). Bug 40. + + The reconciler observes this flag in conjunction with a + "partial diskful" state (storage carved, DRBD not yet Up or + not yet UpToDate) and unwinds by: + + 1. drbdadm down (idempotent if the kernel resource is + already gone), + 2. DeleteVolume on the storage provider, + 3. re-stamping the DISKLESS flag on Spec.Flags, + 4. clearing this flag and Status.ToggleDiskRetries. + + Once cleared the satellite resumes normal reconcile loops + against the (now diskless) Spec. A cancel issued against a + Resource that's already past the partial-state window (DRBD + is Up and Volumes report UpToDate) is a no-op — the operator + must issue a fresh toggle-disk to demote. + type: boolean + volumes: + description: |- + volumes carries per-volume seed configuration that the + satellite applies once on first activation of this replica. + Today the only field is SeedFromGI (Phase 8.1) — when set, + the satellite stamps the new replica's DRBD metadata with + this generation identifier before `drbdadm up` so the GI + handshake sees the new device as already-in-sync with that + peer, skipping the full initial-sync. + items: + description: |- + ResourceVolumeSpec is one volume's per-replica configuration knobs. + Distinct from ResourceVolumeStatus: this carries one-shot seeding + hints the satellite consumes during first activation, the Status + counterpart carries observed runtime state. + properties: + seedFromGI: + description: |- + seedFromGI pre-seeds the DRBD-9 generation identifier of this + replica's metadata block before the first `drbdadm up`. When + set to the CurrentGI of an existing UpToDate peer, DRBD's GI + handshake on first connect sees the match and skips the full + initial-sync — turning hours of resync on multi-TiB volumes + into instant. Phase 8.1. + + Consumed once on first activation; subsequent reconciles + ignore it (the satellite checks `drbdmeta show-gi` before + re-stamping). + type: string + volumeNumber: + description: |- + volumeNumber matches the corresponding ResourceDefinition + VolumeDefinition. +required when this struct is populated. + format: int32 + type: integer + required: + - volumeNumber + type: object + type: array + x-kubernetes-list-map-keys: + - volumeNumber + x-kubernetes-list-type: map + required: + - nodeName + - resourceDefinitionName + type: object + status: + description: status defines the observed state of Resource + properties: + conditions: + description: conditions represent the current state of the Resource. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + connections: + description: |- + connections is the per-peer DRBD connection state observed by the + satellite (from `drbdsetup events2` / `drbdsetup status`). The + Python `linstor r list --faulty` reads this through the REST + `layer_object.drbd.connections` map — without it, the CLI cannot + distinguish a healthy three-peer mesh from one with a broken + connection. Keyed by peer node name. + items: + description: |- + ResourceConnectionStatus is the state of one DRBD peer connection + from this replica's point of view. Maps 1:1 to upstream LINSTOR's + `DrbdConnection` REST shape — the Python CLI walks the `connected` + flag to color the Conns column red on `linstor r list`. + properties: + connected: + description: |- + connected is true iff DRBD reports the connection as + `Connected` (handshake complete, replication active). + type: boolean + message: + description: |- + message is the human-readable DRBD connection state + (`Connected`, `StandAlone`, `BrokenPipe`, `NetworkFailure`, + `Connecting`, `Timeout`, etc.) as reported by `drbdsetup + events2`. Populated even when Connected — useful for + surfacing transitional states. + type: string + peerDRBDNodeID: + description: |- + peerDrbdNodeId is the DRBD-9 node-id assigned to the peer in + this resource's connection table. Read from `drbdsetup + events2` connection-frame `peer-node-id` field. Six e2e + tests today parse this value out of `drbdsetup status + --verbose` adjacent to the peer-name — surfacing it on + Status lets them switch to a k8s-native read. The peer's + own Resource CRD also carries this number under + `Status.DRBDNodeID`, so callers with the atomic-view luxury + can cross-check; the field is retained here for ergonomics + when only the local Resource is in hand. + format: int32 + type: integer + peerNodeName: + description: |- + peerNodeName is the name of the peer Resource (and the node + it lives on — Resource names are RD.node). + type: string + peerVolumes: + description: |- + peerVolumes is the peer's view of each volume's disk state + on this connection — read from `drbdsetup events2 + --statistics` peer-device frames' `peer-disk:` token. + Important under network-partition: the local replica's + `Status.Volumes[i].DiskState` (UpToDate from this node's + kernel) and the peer's view of the same volume + (`DUnknown` from the peer's kernel) diverge. The + state-standalone-partition.sh and network-partition.sh + e2e tests assert against this divergence; without + peerVolumes they shell into the satellite and grep + drbdsetup. Keyed by volumeNumber. + items: + description: |- + PeerVolumeStatus is the per-volume slice of a peer's view of one + connection: what the peer's kernel reports its replica's disk_state + to be. Distinct from the local-side `ResourceVolumeStatus.DiskState` + because under network-partition the two views diverge (local says + UpToDate, peer says DUnknown / Outdated). 8 e2e partition tests + parse this token out of `drbdsetup status --verbose`; the field + gives them a kubectl-native substitute. + properties: + peerDiskState: + description: |- + peerDiskState is the peer's DRBD-9 disk_state for this volume + — `UpToDate`, `Outdated`, `Inconsistent`, `Diskless`, or + `DUnknown` (the local kernel cannot determine the peer's + disk state, typical under partition). Mirrors the + `peer-disk:` token in `drbdsetup events2 + --statistics` peer-device frames. + type: string + volumeNumber: + description: |- + volumeNumber is the DRBD-9 volume number this peer-view entry + describes. Matches the parent + `ResourceDefinition.Spec.VolumeDefinitions[].VolumeNumber`. + format: int32 + type: integer + required: + - volumeNumber + type: object + type: array + x-kubernetes-list-map-keys: + - volumeNumber + x-kubernetes-list-type: map + replicationState: + description: |- + replicationState is the DRBD-9 replication state for this + peer reported by `drbdsetup events2 --statistics` peer- + device frames: Established / SyncSource / SyncTarget / + PausedSync* / VerifyS / VerifyT / Ahead / Behind / Off / + WFBitMap* / WFSyncUUID / StartingSyncS / StartingSyncT. The + Python CLI's `linstor v l` Repl column reads this. + type: string + required: + - peerNodeName + type: object + type: array + x-kubernetes-list-map-keys: + - peerNodeName + x-kubernetes-list-type: map + drbdMinor: + description: |- + drbdMinor is a read-only mirror of the volume-0 minor now + living authoritatively on + ResourceDefinition.Spec.VolumeDefinitions[0].DRBDMinor. Kept so + the cluster-wide taken-set scan and observers that still read + Status keep working during the migration window. + format: int32 + type: integer + drbdNodeID: + description: |- + drbdNodeID is a read-only mirror of the authoritative + Spec.DRBDNodeID, kept so observers/REST/tests that still read + Status during the migration window don't break. The allocator + writes Spec.DRBDNodeID; the reconciler mirrors it here. nil + means not yet allocated. + format: int32 + type: integer + drbdPort: + description: |- + drbdPort is a read-only mirror of the authoritative + Spec.DRBDPort (per-node listen port), kept so the REST DTO + (drbdLayerFromStatus → TCPPorts) and observers that still read + Status keep working during the migration window. The allocator + writes Spec.DRBDPort; the reconciler mirrors it here. + format: int32 + type: integer + drbdState: + description: |- + drbdState is the current resource-level DRBD state reported by + `drbdsetup events2` — `UpToDate`, `Outdated`, `Connected`, + `Failed`, etc. Phase 10.2: written by the satellite via the + Status subresource so a concurrent Spec mutation + (auto-diskful, resize) can't clobber it. + type: string + inUse: + description: inUse is whether DRBD reports the resource as primary + anywhere. + type: boolean + role: + description: |- + role is the kernel-reported DRBD-9 role on this node, parsed + from the `role:` token in `drbdsetup events2` resource frames. + Values mirror the DRBD-9 enum: `Primary` (open for write), + `Secondary` (replication-only), `Unknown` (transient — kernel + just attached, has not yet picked a role). Per-replica, in + contrast to the cluster-wide `inUse` bool: a 3-replica RD has + up to one Primary and two Secondaries, all on different nodes. + ~15 e2e tests `grep role:` from `drbdsetup status`; surfacing + it on Status lets them switch to a k8s-native read. + type: string + suspended: + description: |- + suspended is the kernel-reported reason for I/O suspension on + this replica, parsed from the `suspended:` token in + `drbdsetup events2` resource frames. Values mirror the DRBD-9 + enum: `No` (I/O serves normally), `Quorum` (quorum lost, + `on-no-quorum=suspend-io` blocked the I/O queue), `User` + (`drbdadm suspend-io` issued by operator), `NoData` (no + UpToDate replica reachable, kernel is waiting for one), + `Fencing` (resource-and-stonith fencing handler running). + Paired with the per-volume `quorum` field for quorum-loss + recovery tests — 3 e2e tests need this to distinguish a + recoverable quorum suspend from a user/fencing suspend. + type: string + toggleDiskRetries: + description: |- + toggleDiskRetries counts how many times the satellite + reconciler has failed mid-conversion while running the + diskless→diskful chain (storage carve → drbdmeta create-md + → drbdadm up → initial-sync). Upstream LINSTOR exposes the + same counter under `Resource.toggle_disk_retries` so + operators can spot a permanently-stuck conversion via + `linstor r l`. Bug 39. + + Reset to 0 when the conversion succeeds (Resource reaches + the diskful steady-state) or when a cancel completes via + `Spec.ToggleDiskCancel`. The reconciler does NOT impose a + hard cap — the bound is policy that lives in the controller + layer (today the legacy backoff cap of 10 attempts) and is + surfaced via a `ToggleDiskFailed` condition once exceeded. + format: int32 + type: integer + volumes: + description: volumes is the per-volume runtime state reported by the + satellite. + items: + description: ResourceVolumeStatus is the runtime state of one volume + of a Resource. + properties: + allocatedKib: + format: int64 + type: integer + currentGI: + description: |- + currentGi is the DRBD-9 current generation identifier reported + by `drbdsetup events2` for this replica's local volume. The + controller reads it when adding a new replica to skip the full + initial-sync: pre-seeding the new metadata block with this GI + makes DRBD's GI handshake see the new peer as already-in-sync, + turning hours of resync on multi-TiB volumes into instant. + Updated by the satellite-side observer; never set in Spec. + type: string + devicePath: + type: string + diskState: + type: string + historyGI: + description: |- + historyGi carries the historical GI chain (DRBD keeps 3-4 + previous generations). Useful for split-brain forensics and + cluster-state UI; may be elided when we run tight on Status + budget. Order is newest-first. + items: + type: string + type: array + outOfSyncKib: + description: |- + outOfSyncKib is the worst-case "how many KiB this volume is + behind any peer" reported by `drbdsetup events2 --statistics` + peer-device frames. Combined with RD.Spec.VolumeDefinitions + SizeKib, callers compute a sync-progress percentage: + progress = (1 - outOfSyncKib / sizeKib) * 100 + + 0 means fully in sync; sizeKib (or close to it) means fresh + resync hasn't started yet. Surfaced via the REST view layer + so `linstor r l` / piraeus dashboards can render a CDI-style + progress bar without polling drbdsetup themselves. + format: int64 + type: integer + quorum: + description: |- + quorum reports the DRBD-9 kernel's per-volume quorum view + from the `quorum:yes|no` field in events2 `device` frames. + true means the local replica has quorum and may serve I/O; + false means the kernel has marked the volume quorum-lost + (writes block / fail-fast depending on `on-no-quorum` + policy). Per-volume is finer-grained than the node-wide + `drbd.linbit.com/lost-quorum` Kubernetes taint: a node with + quorum on one RD and no-quorum on another surfaces both + states correctly. The CSI plugin's quorum-aware mount path + (refusing to mount a no-quorum volume) reads this signal. + type: boolean + storagePool: + type: string + usableKib: + format: int64 + type: integer + volumeNumber: + format: int32 + type: integer + required: + - volumeNumber + type: object + type: array + x-kubernetes-list-map-keys: + - volumeNumber + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + x-kubernetes-validations: + - message: metadata.name must equal . + (case-insensitive) + optionalOldSelf: true + rule: oldSelf.hasValue() || self.metadata.name.lowerAscii() == (self.spec.resourceDefinitionName + + '.' + self.spec.nodeName).lowerAscii() + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_snapshots.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_snapshots.yaml new file mode 100644 index 000000000..7b669964c --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_snapshots.yaml @@ -0,0 +1,315 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: snapshots.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: Snapshot + listKind: SnapshotList + plural: snapshots + singular: snapshot + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Snapshot is the Schema for the snapshots API. + + The CEL rule above enforces the cluster-wide naming convention every + composite-keyed CRD in the project follows: `metadata.name == .`. + Keeping the composite key encoded in the name lets the store's + `snapshotCRDName` helper round-trip the (rd, snap) pair through k8s + metadata without a sidecar index, and lets operators grep for + `.` across kinds (Resource, Snapshot, StoragePool) to find every + object bound to one parent. The `optionalOldSelf` escape makes the + rule create-only — finalizer-strip on a stale-named Snapshot + (e.g. one created before this marker existed) is never blocked. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of Snapshot + properties: + groupID: + description: |- + groupID, when non-empty, marks this Snapshot as a member of a + transactional multi-RD batch — every Snapshot CRD stamped with + the same GroupID participates in a SINGLE suspend-io broadcast + across the UNION of every sibling's targeted nodes. Bug 353: + `linstor s create-multiple` (POST /v1/actions/snapshot/multi) + previously looped per-RD through the Bug-351 orchestrator and + each Snapshot ran its own independent 3-phase suspend/take/ + resume — so per-RD suspend windows did not overlap and the + cross-RD point-in-time consistency operators expect from a + "group snapshot" (DB + WAL on separate RDs) was lost. + + Lifecycle (driven by the controller-side SnapshotReconciler): + 1. apiserver stamps every batched Snapshot with the same + crypto/rand-generated GroupID + SuspendIO=true. + 2. Controller gates phase advancement on the FULL group: + Phase 2 only fires when every sibling's every targeted + node has acked the suspend. + 3. Phase 3 only fires when every sibling's every targeted + node is Ready — or any sibling node Failed=true, in + which case the abort cascade fires SuspendIO=false on + every sibling immediately. + + Empty GroupID is the single-snap path (Bug 351 behaviour + preserved verbatim — siblings denominator collapses to self). + type: string + groupSize: + description: |- + groupSize is the number of Snapshot CRDs the apiserver fanned + out for this transactional batch (len of the + `snapshot create-multiple` entry list). It is the denominator the + controller-side SnapshotReconciler uses to decide when the group + is fully ASSEMBLED before it opens the suspend-io barrier. + + Bug 046 / Bug-353 atomicity fix: the apiserver creates the + sibling CRDs SEQUENTIALLY (one Store.Create per entry, with + hydration + an offline pre-check between each), so on a busy + stand the last sibling's CRD can land ~15s after the first. If + each satellite started `drbdsetup suspend-io` the instant its + own sibling appeared (the old behaviour, with SuspendIO stamped + at Create time), the group's volumes would freeze ~15s APART — + well over the ≤5s consistency budget — so a DB's data volume and + WAL volume on separate RDs would be captured at different + instants and a group restore could be corrupt. + + With GroupSize the controller holds the WHOLE group at Phase 0 + (no SuspendIO) until it observes every member, then flips + SuspendIO=true on every sibling in a single reconcile pass so + they all enter suspend within one controller cycle (sub-second), + bounding the suspend-entry slip far under budget. + + Zero means "not a coordinated batch" (the single-snap Bug-351 + path, or a legacy grouped Snapshot created before this field + existed) — in that case the controller falls back to the + observed-siblings count so a GroupID with no GroupSize still + makes progress instead of hanging on a missing denominator. + format: int32 + type: integer + nodes: + description: |- + nodes are the satellites the snapshot should live on. Empty means + "every node currently hosting the parent resource". + items: + type: string + type: array + props: + additionalProperties: + type: string + description: props is the LINSTOR property map for the snapshot. + type: object + resourceDefinitionName: + description: resourceDefinitionName is the parent ResourceDefinition. + type: string + snapshotName: + description: snapshotName is the user-facing snapshot identifier. + type: string + suspendIO: + description: |- + suspendIO, when true, signals every satellite that hosts a + diskful replica of the parent ResourceDefinition to call + `drbdsetup suspend-io ` before taking the local backing + snapshot. Bug 351: two diskful replicas snapshotting + independently would otherwise capture divergent bytes while + the application writer's traffic is still streaming through + DRBD; suspending I/O on every peer first freezes the + replicated block stream at a single, common point so the + per-node LV / zvol snapshots all reflect the same + point-in-time bytes. + + Lifecycle (driven by the controller-side SnapshotReconciler): + 1. apiserver creates Snapshot CRD with SuspendIO=true, + TakeSnapshot=false. Satellites stamp + Status.NodeStatus[].SuspendIOAcked once their suspend-io + call returns. + 2. Once every targeted node has acked, the controller stamps + Spec.TakeSnapshot=true. Satellites then dispatch + provider.CreateSnapshot and stamp Status.NodeStatus[].Ready. + 3. Once every targeted node is Ready (or any has Failed=true), + the controller flips Spec.SuspendIO=false and satellites + issue `drbdsetup resume-io `. + + Resume-on-failure is mandatory — a partially-acked suspend + followed by an abort MUST still resume I/O on the nodes that + did ack, otherwise application I/O hangs forever. The + controller's abort path clears SuspendIO unconditionally. + type: boolean + takeSnapshot: + description: |- + takeSnapshot, when true, signals each satellite that has + already acked the suspend-io barrier (see SuspendIO above) to + dispatch the local provider.CreateSnapshot. The flag is + stamped by the controller-side SnapshotReconciler once every + targeted node's Status.NodeStatus[].SuspendIOAcked is true — + the two-step `suspend → take → resume` shape mirrors upstream + LINSTOR's CtrlSnapshotCrtApiCallHandler 3-phase flow so the + per-node backing snapshots all reflect the same point-in-time + bytes. + type: boolean + volumeDefinitions: + description: volumeDefinitions records the size of each volume captured. + items: + description: SnapshotVolumeRef is one volume slot inside a Snapshot. + properties: + sizeKib: + format: int64 + type: integer + volumeNumber: + format: int32 + type: integer + required: + - sizeKib + - volumeNumber + type: object + type: array + required: + - resourceDefinitionName + - snapshotName + type: object + status: + description: status defines the observed state of Snapshot + properties: + conditions: + description: conditions represent the current state of the Snapshot. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + flags: + description: |- + flags carries terminal-state markers. Currently only + "FAILED" is meaningful — stamped by the satellite when + CreateSnapshot returns a non-retryable error class. + items: + type: string + type: array + nodeStatus: + description: nodeStatus reports per-node readiness from the satellites. + items: + description: |- + SnapshotPerNodeStatus is the satellite-reported state of one + materialisation of the snapshot. + properties: + createTimestamp: + format: int64 + type: integer + failed: + description: |- + failed is stamped true when the local satellite hit a + terminal failure while either suspending I/O, taking the + per-node snapshot, or resuming I/O. The controller-side + SnapshotReconciler treats any Failed=true entry as an abort + signal: it flips Spec.SuspendIO=false immediately so the + already-suspended siblings resume rather than wait + indefinitely on the doomed node, and stamps the parent + Snapshot's Status.Flags with FAILED. Bug 351. + type: boolean + nodeName: + type: string + ready: + type: boolean + suspendIOAcked: + description: |- + suspendIOAcked is stamped true by the local satellite once + `drbdsetup suspend-io ` has returned for the parent + ResourceDefinition. The controller-side SnapshotReconciler + gates the Phase-2 `TakeSnapshot` transition on every targeted + node having acked. Cleared back to false when the controller + flips Spec.SuspendIO=false and the satellite issues + `drbdsetup resume-io `. Bug 351. + type: boolean + required: + - nodeName + type: object + type: array + type: object + required: + - spec + type: object + x-kubernetes-validations: + - message: metadata.name must equal . + (case-insensitive) + optionalOldSelf: true + rule: oldSelf.hasValue() || self.metadata.name.lowerAscii() == (self.spec.resourceDefinitionName + + '.' + self.spec.snapshotName).lowerAscii() + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_storagepools.yaml b/packages/system/linstor/definitions/blockstor.cozystack.io_storagepools.yaml new file mode 100644 index 000000000..2fa9911ed --- /dev/null +++ b/packages/system/linstor/definitions/blockstor.cozystack.io_storagepools.yaml @@ -0,0 +1,210 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.20.1 + name: storagepools.blockstor.cozystack.io +spec: + group: blockstor.cozystack.io + names: + kind: StoragePool + listKind: StoragePoolList + plural: storagepools + singular: storagepool + scope: Cluster + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + StoragePool is the Schema for the storagepools API. + + The CEL rule above enforces the cluster-wide naming convention every + node-bound CRD in the project follows: `metadata.name == .`. + Keeping the composite key encoded in the name lets operators grep for + `.` across kinds (Resource, Snapshot, StoragePool) and find every + resource bound to one satellite at once. + + The match is case-insensitive (`lowerAscii()` on both sides) because + k8s metadata.Name is RFC-1123 (lowercase only) while LINSTOR identifiers + preserve their CamelCase spelling on the wire. Upstream's well-known + `DfltDisklessStorPool` is the canonical example — we must be able to + store it under metadata.name `dfltdisklessstorpool.` while keeping + `spec.poolName == "DfltDisklessStorPool"` for byte-equal comparisons in + the satellite's provider registry (Bug 59). + + The rule fires on both Create and Update; the REST layer + (`pkg/rest/storage_pools.go`) also rejects non-canonical bodies with a + friendlier 400 message so callers don't have to parse the k8s 422 + Invalid envelope. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the desired state of StoragePool + properties: + nodeName: + description: |- + nodeName is the name of the satellite hosting this pool. Same as the + LINSTOR Node CRD's metadata.name. + type: string + poolName: + description: |- + poolName is the LINSTOR pool name (LVM VG, ZFS dataset, etc.). The + CRD-level CEL rule pins `metadata.name == poolName + "." + nodeName`, + so this field is required — without it the rule cannot evaluate. + type: string + props: + additionalProperties: + type: string + description: props is the LINSTOR property map for this pool. + type: object + providerKind: + description: providerKind is the storage backend. + enum: + - LVM + - LVM_THIN + - ZFS + - ZFS_THIN + - FILE + - FILE_THIN + - DISKLESS + type: string + sharedSpaceID: + description: |- + sharedSpaceId groups pools that physically share the same backing + LUN (e.g. an EXOS / NetApp / Ceph-RBD-as-shared-disk slice attached + to multiple satellites). Pools in the same group contribute their + free capacity once to cluster totals instead of summing, and the + autoplacer treats them as anti-affine for replica placement so a + 2-replica RD never lands twice on the same physical LUN. + Empty string = local pool (default). + type: string + required: + - nodeName + - poolName + - providerKind + type: object + status: + description: status defines the observed state of StoragePool + properties: + conditions: + description: conditions represent the current state of the StoragePool + resource. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + freeCapacity: + description: |- + freeCapacity is the free capacity in KiB reported by the satellite. + Matches the wire shape (gRPC SatellitePool.FreeCapacityKib, REST + `free_capacity_kib`) so /v1/view/storage-pools and the autoplacer + can read this field directly without a unit conversion. + format: int64 + type: integer + poolMissing: + description: |- + poolMissing indicates the satellite's last PoolStatus probe failed — + typically the backing pool (zpool / VG / FILE_THIN dir) was destroyed + out-of-band. While true, the placer skips this pool and the REST + wire view emits state="Faulty" instead of "Ok". + type: boolean + staticTraits: + additionalProperties: + type: string + description: staticTraits exposes provider-static attributes (kind, + etc.). + type: object + supportsSnapshots: + description: supportsSnapshots is whether the backing provider can + create snapshots. + type: boolean + totalCapacity: + description: totalCapacity is the total capacity in KiB reported by + the satellite. + format: int64 + type: integer + type: object + required: + - spec + type: object + x-kubernetes-validations: + - message: metadata.name must equal . (case-insensitive) + optionalOldSelf: true + rule: oldSelf.hasValue() || self.metadata.name.lowerAscii() == (self.spec.poolName + + '.' + self.spec.nodeName).lowerAscii() + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/linstor/templates/backend-guard.yaml b/packages/system/linstor/templates/backend-guard.yaml new file mode 100644 index 000000000..0089c96ae --- /dev/null +++ b/packages/system/linstor/templates/backend-guard.yaml @@ -0,0 +1,9 @@ +{{- /* +Every template here renders one backend or the other from this value, so +an unrecognised one renders some of each and exits 0. The platform chart +validates storage.backend before passing it on, but a value arriving here +any other way, a hand-set component value for one, is checked here too. +*/ -}} +{{- if not (has .Values.backend (list "linstor" "blockstor")) }} +{{- fail (printf "linstor: backend must be \"linstor\" or \"blockstor\", got %q" (toString .Values.backend)) }} +{{- end }} diff --git a/packages/system/linstor/templates/blockstor-apiserver-tls.yaml b/packages/system/linstor/templates/blockstor-apiserver-tls.yaml new file mode 100644 index 000000000..02803e23f --- /dev/null +++ b/packages/system/linstor/templates/blockstor-apiserver-tls.yaml @@ -0,0 +1,110 @@ +{{- if eq .Values.backend "blockstor" }} +--- +{{- /* + cert-manager PKI for the blockstor apiserver's mutual-TLS endpoint. + + Chain (the same shape as linstor-api-tls.yaml; chained from the + cozy-linstor ca-bootstrapper self-signed Issuer that the + piraeus-operator package creates in this namespace, so there is no + self-managed root here): + ca-bootstrapper (Issuer, from piraeus-operator package) + └─> blockstor-api-ca (CA Certificate, 10y) + └─> blockstor-api-ca (CA Issuer) + ├─> blockstor-apiserver-server (serving cert, Service DNS SANs) + └─> blockstor-apiserver-client (client cert for in-cluster consumers) + + The apiserver's TLS listener (RequireAndVerifyClientCert) verifies + every client cert against ca.crt of the server Secret, and serves + tls.crt/tls.key. cert-manager rotates these in place; the apiserver + hot-reloads them from disk WITHOUT a restart — there are intentionally + NO reloader.stakater.com annotations. LinstorCluster.spec.apiTLS + references the blockstor-api-ca Issuer so linstor-csi gets client + certs chained to the same CA. */}} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: blockstor-api-ca + namespace: {{ .Release.Namespace }} +spec: + commonName: blockstor-api-ca + secretName: blockstor-api-ca + duration: 87600h # 10 years + isCA: true + privateKey: + rotationPolicy: Never + usages: + - signing + - key encipherment + - cert sign + issuerRef: + name: ca-bootstrapper + kind: Issuer +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: blockstor-api-ca + namespace: {{ .Release.Namespace }} +spec: + ca: + secretName: blockstor-api-ca +--- +{{- /* + Serving certificate for the apiserver TLS listener. The dnsNames cover + the Service FQDN in-cluster clients dial: + blockstor-apiserver.cozy-linstor.svc(.cluster.local). MUST stay in + sync with LinstorCluster.spec.externalController.url in cluster.yaml. */}} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: blockstor-apiserver-server + namespace: {{ .Release.Namespace }} +spec: + secretName: blockstor-apiserver-server-tls + duration: 2160h # 90 days + renewBefore: 360h # 15 days + privateKey: + algorithm: ECDSA + size: 256 + rotationPolicy: Always + usages: + - server auth + - digital signature + - key encipherment + dnsNames: + - blockstor-apiserver + - blockstor-apiserver.cozy-linstor + - blockstor-apiserver.cozy-linstor.svc + - blockstor-apiserver.cozy-linstor.svc.cluster.local + issuerRef: + name: blockstor-api-ca + kind: Issuer +--- +{{- /* + Client certificate for in-cluster consumers: piraeus-operator's own + API probe, linstor-scheduler and linstor-gui (the platform points both + here under this backend), and the `linstor` CLI. Presented to the + apiserver's RequireAndVerifyClientCert listener. linstor-csi gets its + own client cert from the operator via LinstorCluster.spec.apiTLS. */}} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: blockstor-apiserver-client + namespace: {{ .Release.Namespace }} +spec: + secretName: blockstor-apiserver-client-tls + commonName: blockstor-apiserver-client + duration: 2160h # 90 days + renewBefore: 360h # 15 days + privateKey: + algorithm: ECDSA + size: 256 + rotationPolicy: Always + usages: + - client auth + - digital signature + - key encipherment + issuerRef: + name: blockstor-api-ca + kind: Issuer +{{- end }} diff --git a/packages/system/linstor/templates/blockstor-apiserver.yaml b/packages/system/linstor/templates/blockstor-apiserver.yaml new file mode 100644 index 000000000..4f714832c --- /dev/null +++ b/packages/system/linstor/templates/blockstor-apiserver.yaml @@ -0,0 +1,186 @@ +{{- if eq .Values.backend "blockstor" }} +--- +{{- /* + blockstor apiserver — the LINSTOR-compatible REST front end split out + of the controller binary. linstor-csi (external mode) and the + `linstor` CLI dial it. Three replicas behind a Service. */}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: blockstor-apiserver + namespace: {{ .Release.Namespace }} +--- +{{- /* + CRUD on the blockstor.cozystack.io CRDs, named rather than wildcarded so a kind + added to the group later is not granted by omission. No finalizers, + events or leases: the REST handlers do not write those. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: blockstor-apiserver +rules: + - apiGroups: [blockstor.cozystack.io] + resources: + - controllerconfigs + - controllerconfigs/status + - nodes + - nodes/status + - physicaldevices + - physicaldevices/status + - resourcedefinitions + - resourcedefinitions/status + - resourcegroups + - resourcegroups/status + - resources + - resources/status + - snapshots + - snapshots/status + - storagepools + - storagepools/status + verbs: [get, list, watch, create, update, patch, delete] + {{- /* + Read-only, and cluster-wide only because the apiserver reads the + passphrase Secret through controller-runtime's default cached client, + whose informer lists and watches Secrets at cluster scope. Narrowing + this needs the binary to scope its Secret cache to its own namespace; + until then a namespaced Role here would leave that informer forbidden + and every passphrase read hanging. */}} + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: blockstor-apiserver +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: blockstor-apiserver +subjects: + - kind: ServiceAccount + name: blockstor-apiserver + namespace: {{ .Release.Namespace }} +--- +{{- /* + Writes to Secrets stay in this namespace: the only Secret the apiserver + writes is the encryption passphrase, `encryption create-passphrase` and + `modify-passphrase`, and it always lives here. A cluster-wide write + grant would let this ServiceAccount rewrite any tenant's credentials. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: blockstor-apiserver-secrets + namespace: {{ .Release.Namespace }} +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [create, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: blockstor-apiserver-secrets + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: blockstor-apiserver-secrets +subjects: + - kind: ServiceAccount + name: blockstor-apiserver + namespace: {{ .Release.Namespace }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: blockstor-apiserver + namespace: {{ .Release.Namespace }} + labels: + app: blockstor-apiserver + app.kubernetes.io/component: blockstor-apiserver +spec: + replicas: 3 + selector: {matchLabels: {app: blockstor-apiserver}} + template: + metadata: + labels: + app: blockstor-apiserver + app.kubernetes.io/component: blockstor-apiserver + spec: + serviceAccountName: blockstor-apiserver + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: {app: blockstor-apiserver} + containers: + - name: apiserver + image: {{ .Values.blockstorApiserver.image.repository }}:{{ .Values.blockstorApiserver.image.tag }} + imagePullPolicy: IfNotPresent + args: + {{- /* + Plain-HTTP debug listener with no client authentication. + Bound to loopback so nothing on the pod network reaches it: + `kubectl port-forward` connects from inside the pod's network + namespace, so it still works. */}} + - --rest-bind-address=127.0.0.1:3370 + {{- /* + Mutual-TLS listener — the ONLY port the Service exposes. + Requires + verifies client certs against the mounted CA; + hot-reloads cert/key/CA on cert-manager rotation. */}} + - --tls-bind-address=:3371 + - --tls-cert-file=/etc/blockstor/tls/tls.crt + - --tls-key-file=/etc/blockstor/tls/tls.key + - --tls-client-ca-file=/etc/blockstor/tls/ca.crt + - --health-probe-bind-address=:8081 + - --metrics-bind-address=0 + env: + - name: POD_NAMESPACE + valueFrom: {fieldRef: {fieldPath: metadata.namespace}} + ports: + - {name: rest-tls, containerPort: 3371} + - {name: health, containerPort: 8081} + volumeMounts: + - name: api-tls + mountPath: /etc/blockstor/tls + readOnly: true + readinessProbe: + httpGet: {path: /readyz, port: health} + initialDelaySeconds: 5 + livenessProbe: + httpGet: {path: /healthz, port: health} + initialDelaySeconds: 15 + securityContext: + runAsNonRoot: true + runAsUser: 65532 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + seccompProfile: {type: RuntimeDefault} + resources: + requests: {cpu: 50m, memory: 128Mi} + limits: {cpu: 500m, memory: 512Mi} + volumes: + - name: api-tls + secret: + secretName: blockstor-apiserver-server-tls +--- +{{- /* + mTLS-only Service: exposes ONLY :3371. The plain-HTTP debug port + (3370) is deliberately NOT listed. Clients dial + https://blockstor-apiserver.cozy-linstor.svc:3371 presenting a client + cert. This DNS MUST match LinstorCluster.spec.externalController.url + and a serving-cert SAN. */}} +apiVersion: v1 +kind: Service +metadata: + name: blockstor-apiserver + namespace: {{ .Release.Namespace }} + labels: + app.kubernetes.io/component: blockstor-apiserver +spec: + selector: {app: blockstor-apiserver} + ports: + - {name: rest-tls, port: 3371, targetPort: 3371} +{{- end }} diff --git a/packages/system/linstor/templates/blockstor-controller.yaml b/packages/system/linstor/templates/blockstor-controller.yaml new file mode 100644 index 000000000..fd50b32d0 --- /dev/null +++ b/packages/system/linstor/templates/blockstor-controller.yaml @@ -0,0 +1,124 @@ +{{- if eq .Values.backend "blockstor" }} +--- +{{- /* + blockstor controller — runs the reconcilers for the blockstor.cozystack.io + CRDs (ResourceDefinitions / Resources / Snapshots / StoragePools / + Nodes). The REST API is split out into the separate apiserver + Deployment; the controller runs with --enable-rest-api=false. */}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: blockstor-controller + namespace: {{ .Release.Namespace }} +--- +{{- /* + Cluster-wide read on Kubernetes Nodes and the blockstor.cozystack.io kinds + the reconcilers manage, as blockstor's own config/rbac/role.yaml grants + them, kind by kind so a kind added to the group later is not granted by + omission. No leases: the controller runs without leader election. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: blockstor-controller +rules: + - apiGroups: [""] + resources: [events] + verbs: [create, patch] + - apiGroups: [events.k8s.io] + resources: [events] + verbs: [create, patch] + - apiGroups: [""] + resources: [nodes] + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: [controllerconfigs] + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: [nodes, resourcedefinitions, resourcegroups, resources, snapshots, storagepools] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [blockstor.cozystack.io] + resources: + - nodes/finalizers + - resourcedefinitions/finalizers + - resourcegroups/finalizers + - resources/finalizers + - snapshots/finalizers + - storagepools/finalizers + verbs: [update] + - apiGroups: [blockstor.cozystack.io] + resources: + - nodes/status + - resourcedefinitions/status + - resourcegroups/status + - resources/status + - snapshots/status + - storagepools/status + verbs: [get, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: blockstor-controller +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: blockstor-controller +subjects: + - kind: ServiceAccount + name: blockstor-controller + namespace: {{ .Release.Namespace }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: blockstor-controller + namespace: {{ .Release.Namespace }} + labels: + app: blockstor-controller + app.kubernetes.io/component: blockstor-controller +spec: + replicas: 1 + {{- /* + One reconciler at a time. The binary runs without leader election, so a + rolling update would run the old and the new pod side by side against the + same CRDs; Recreate stops the old one before the new one starts. */}} + strategy: + type: Recreate + selector: {matchLabels: {app: blockstor-controller}} + template: + metadata: + labels: + app: blockstor-controller + app.kubernetes.io/component: blockstor-controller + spec: + serviceAccountName: blockstor-controller + containers: + - name: manager + image: {{ .Values.blockstorController.image.repository }}:{{ .Values.blockstorController.image.tag }} + imagePullPolicy: IfNotPresent + args: + {{- /* + REST API lives in the separate apiserver Deployment — + controller only runs reconcilers. */}} + - --enable-rest-api=false + - --health-probe-bind-address=:8081 + - --metrics-bind-address=0 + - --leader-elect=false + ports: + - {name: health, containerPort: 8081} + readinessProbe: + httpGet: {path: /readyz, port: 8081} + initialDelaySeconds: 5 + livenessProbe: + httpGet: {path: /healthz, port: 8081} + initialDelaySeconds: 15 + securityContext: + runAsNonRoot: true + runAsUser: 65532 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + seccompProfile: {type: RuntimeDefault} + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {cpu: 500m, memory: 256Mi} +{{- end }} diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml new file mode 100644 index 000000000..297c0d984 --- /dev/null +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -0,0 +1,281 @@ +{{- define "blockstor.satellite.drbdGlobalConf" -}} +# blockstor satellite — global_common.conf. +# Kept minimal: per-resource tuning lives in the rendered .res +# files, not here. Mirrors the drbd-utils trixie default. +global { + usage-count no; + udev-always-use-vnr; +} +common { + handlers {} + startup {} + options {} + disk {} + net {} +} +{{- end }} +{{- if eq .Values.backend "blockstor" }} +--- +{{- /* + blockstor-satellite DaemonSet. Runs on every node, drives drbdadm + + ZFS/LVM reconcile, registers its StoragePools (declared via the + StoragePool CRDs) and writes node-scoped Status back to the apiserver. + + This DaemonSet loads no kernel module and mounts nothing from + /run/systemd, so it needs no Talos-specific patch. It expects DRBD to be + loaded already: on Talos by the siderolabs/drbd extension, on generic + Linux by the drbd-module-loader init container of piraeus's own + satellite pod on the same node, which nothing here orders this pod + after. */}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: blockstor-satellite + namespace: {{ .Release.Namespace }} +--- +{{- /* + /etc/drbd.d is a hostPath bind (below), which hides the + global_common.conf baked into the image. drbdadm reads that file on + every invocation, so it is mounted back on top of the bind by subPath. */}} +apiVersion: v1 +kind: ConfigMap +metadata: + name: blockstor-satellite-drbd-conf + namespace: {{ .Release.Namespace }} +data: + global_common.conf: | +{{ include "blockstor.satellite.drbdGlobalConf" . | indent 4 }} +--- +{{- /* + What the satellite writes, and no more. It creates and deletes only the + PhysicalDevices it discovers; on Nodes, Resources, Snapshots and + StoragePools it updates props and finalizers and server-side-applies the + SkipDisk prop, which is a patch; everything else it reads. Kubernetes + Nodes are read for their InternalIP. No leases: it runs no leader + election. Secrets are in the namespaced Role below. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: blockstor-satellite +rules: + - apiGroups: [""] + resources: [events] + verbs: [create, patch] + - apiGroups: [""] + resources: [nodes] + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: + - controllerconfigs + - nodes + - physicaldevices + - resourcedefinitions + - resourcegroups + - resources + - snapshots + - storagepools + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: [physicaldevices] + verbs: [create, update, patch, delete] + - apiGroups: [blockstor.cozystack.io] + resources: [nodes, resources, snapshots, storagepools] + verbs: [update, patch] + - apiGroups: [blockstor.cozystack.io] + resources: + - nodes/status + - physicaldevices/status + - resources/status + - snapshots/status + - storagepools/status + - nodes/finalizers + - physicaldevices/finalizers + - resources/finalizers + - snapshots/finalizers + - storagepools/finalizers + verbs: [get, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: blockstor-satellite +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: blockstor-satellite +subjects: + - kind: ServiceAccount + name: blockstor-satellite + namespace: {{ .Release.Namespace }} +--- +{{- /* + The satellite reads one Secret, the LUKS passphrase, in its own + namespace, with a direct GET rather than through a cache, so a + namespaced get is all it needs. A privileged pod on every node holding + a token that reads every Secret in the cluster would hand any node + compromise every tenant's credentials. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: blockstor-satellite-secrets + namespace: {{ .Release.Namespace }} +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: blockstor-satellite-secrets + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: blockstor-satellite-secrets +subjects: + - kind: ServiceAccount + name: blockstor-satellite + namespace: {{ .Release.Namespace }} +--- +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: blockstor-satellite + namespace: {{ .Release.Namespace }} + labels: + app: blockstor-satellite + app.kubernetes.io/component: blockstor-satellite +spec: + selector: {matchLabels: {app: blockstor-satellite}} + template: + metadata: + labels: + app: blockstor-satellite + app.kubernetes.io/component: blockstor-satellite + {{- /* The file is mounted by subPath, which Kubernetes never refreshes, + so a change to it has to roll the pods. */}} + annotations: + checksum/drbd-conf: {{ include "blockstor.satellite.drbdGlobalConf" . | sha256sum }} + spec: + serviceAccountName: blockstor-satellite + hostPID: true + {{- /* + hostNetwork so the container's hostname matches the node name + (drbdadm picks the `on ` block by hostname) and the + advertised endpoint equals the node IP. */}} + hostNetwork: true + hostIPC: true + dnsPolicy: ClusterFirstWithHostNet + tolerations: + - operator: Exists + {{- /* + Runs on every node, control-plane nodes included, which is what + the tolerations above are for: storage lives wherever the DRBD + module and a pool are, not on workers only. + Short grace and no preStop drain: DRBD state lives in the host + kernel and survives the pod. On startup the next satellite keeps + every resource it finds with a usable disk or a live peer, and + tears down the rest. */}} + terminationGracePeriodSeconds: 10 + containers: + - name: satellite + image: {{ .Values.blockstorSatellite.image.repository }}:{{ .Values.blockstorSatellite.image.tag }} + imagePullPolicy: IfNotPresent + args: + {{- /* + drbd's /etc/drbd.conf includes /etc/drbd.d/*.res; the + satellite writes rendered files there. The host backing + is /var/lib/blockstor-drbd.d (writable on Talos; /etc is + read-only). */}} + - --state-dir=/etc/drbd.d + {{- /* + Storage pools come from StoragePool objects, not flags. */}} + - --health-probe-bind-address=:9101 + env: + - name: NODE_NAME + valueFrom: {fieldRef: {fieldPath: spec.nodeName}} + - name: POD_IP + valueFrom: {fieldRef: {fieldPath: status.podIP}} + - name: POD_NAMESPACE + valueFrom: {fieldRef: {fieldPath: metadata.namespace}} + livenessProbe: + httpGet: {path: /healthz, port: 9101} + initialDelaySeconds: 15 + periodSeconds: 20 + timeoutSeconds: 3 + failureThreshold: 3 + readinessProbe: + httpGet: {path: /readyz, port: 9101} + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 3 + securityContext: + privileged: true + volumeMounts: + {{- /* + Plain bind of host /dev, no mountPropagation: the + partitions `zpool create` makes appear in the host's + devtmpfs, which is where libzfs opens them. */}} + - {name: dev, mountPath: /dev} + - {name: modules, mountPath: /lib/modules, readOnly: true} + - {name: lvm-run, mountPath: /run/lvm} + {{- /* + Host udev database, which libzfs and libblkid look devices up in. */}} + - {name: run-udev, mountPath: /run/udev, readOnly: true} + - {name: state, mountPath: /var/lib/blockstor-satellite} + - {name: pool, mountPath: /var/lib/blockstor-pool} + {{- /* + The satellite's own DRBD config dir on the host, + /var/lib/blockstor-drbd.d, so its .res files never mix with + another DRBD user's /etc/drbd.d. */}} + - {name: drbd-cfg, mountPath: /etc/drbd.d} + - name: drbd-global-conf + mountPath: /etc/drbd.d/global_common.conf + subPath: global_common.conf + readOnly: true + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {cpu: 500m, memory: 512Mi} + volumes: + - {name: dev, hostPath: {path: /dev, type: Directory}} + - {name: modules, hostPath: {path: /lib/modules}} + - {name: lvm-run, hostPath: {path: /run/lvm, type: DirectoryOrCreate}} + - {name: run-udev, hostPath: {path: /run/udev, type: Directory}} + - {name: state, hostPath: {path: /var/lib/blockstor-satellite, type: DirectoryOrCreate}} + - {name: pool, hostPath: {path: /var/lib/blockstor-pool, type: DirectoryOrCreate}} + - {name: drbd-cfg, hostPath: {path: /var/lib/blockstor-drbd.d, type: DirectoryOrCreate}} + - name: drbd-global-conf + configMap: + name: blockstor-satellite-drbd-conf + items: + - {key: global_common.conf, path: global_common.conf} +--- +{{- /* + blockstor-satellite runs on host networking and, in this release, listens + on every address without authentication: 9100 serves snapshot streams to + other satellites, 9101 its health probes, 8080 controller-runtime's + metrics. None of them is for anything outside the cluster, so they are + closed to the world the way restrict-drbd-reactor closes drbd-reactor's. */}} +apiVersion: cilium.io/v2 +kind: CiliumClusterwideNetworkPolicy +metadata: + name: restrict-blockstor-satellite +spec: + ingressDeny: + - fromEntities: + - world + toPorts: + - ports: + - port: "9100" + - port: "9101" + - port: "8080" + ingress: + - fromEntities: + - world + - host + - cluster + nodeSelector: + matchLabels: {} +{{- end }} diff --git a/packages/system/linstor/templates/cluster.yaml b/packages/system/linstor/templates/cluster.yaml index 4639e677b..271611b26 100644 --- a/packages/system/linstor/templates/cluster.yaml +++ b/packages/system/linstor/templates/cluster.yaml @@ -7,14 +7,46 @@ metadata: spec: #nodeSelector: # node-role.kubernetes.io/linstor: "" + {{- if eq .Values.backend "blockstor" }} + {{- /* External mode: piraeus-operator runs no linstor-controller of its + own. linstor-csi talks to blockstor-apiserver, which serves the + LINSTOR REST API on the mTLS port :3371 only. The URL has to match + the Service and a SAN of its serving certificate, both in + blockstor-apiserver*.yaml. linstor-scheduler and linstor-gui read + this URL and clientSecretName below from this object too, so no + other package names blockstor's Service or Secret. */}} + externalController: + url: https://blockstor-apiserver.cozy-linstor.svc:3371 + {{- else }} internalTLS: certManager: name: linstor-internal-ca kind: Issuer + {{- end }} apiTLS: certManager: + {{- if eq .Values.backend "blockstor" }} + {{- /* The operator issues linstor-csi-{controller,node}-tls from this + Issuer, so the CSI pods present a client certificate chained to + the CA blockstor-apiserver verifies. */}} + name: blockstor-api-ca + {{- else }} name: linstor-api-ca + {{- end }} kind: Issuer + {{- if eq .Values.backend "blockstor" }} + {{- /* The operator is a client of the API itself: it probes + /v1/controller/version before every LinstorCluster and + LinstorSatellite reconcile. In external mode it issues no + certificate for that client and only reads the Secret named here, + whose default, linstor-client-tls, either does not exist or, on a + cluster that ran the LINSTOR backend, still carries the old CA. + Either way the probe fails with "certificate signed by unknown + authority" and every reconcile stops before it starts, freezing the + satellite DaemonSets at their last spec. This is the client + certificate the chart issues from the same CA as the serving one. */}} + clientSecretName: blockstor-apiserver-client-tls + {{- end }} properties: {{- if .Values.linstor.autoDiskful.enabled }} - name: DrbdOptions/auto-diskful @@ -32,6 +64,7 @@ spec: value: "20" - name: DrbdOptions/Net/timeout value: "100" + {{- if eq .Values.backend "linstor" }} controller: enabled: true podTemplate: @@ -80,6 +113,7 @@ spec: configMap: name: linstor-plunger defaultMode: 0755 + {{- end }} csiController: podTemplate: spec: @@ -148,6 +182,7 @@ spec: - name: linstor-wait-node-online image: {{ .Values.linstorCSI.image.repository }}:{{ .Values.linstorCSI.image.tag }} patches: + {{- if eq .Values.backend "linstor" }} - target: kind: Deployment name: linstor-controller @@ -155,6 +190,7 @@ spec: - op: add path: /metadata/annotations/reloader.stakater.com~1auto value: "true" + {{- end }} - target: kind: Deployment name: linstor-csi-controller diff --git a/packages/system/linstor/templates/crds/crds.yaml b/packages/system/linstor/templates/crds/crds.yaml new file mode 100644 index 000000000..d50a07087 --- /dev/null +++ b/packages/system/linstor/templates/crds/crds.yaml @@ -0,0 +1,24 @@ +{{- /* +Blockstor's CRDs ship only with the blockstor backend. A LINSTOR +cluster has no use for them, and installing a component's schema +without the component that reconciles it invites objects nothing +serves. + +Every CRD is kept on an upgrade that stops rendering it. These live +under templates/, so they are ordinary release members: switching the +backend back to linstor would otherwise delete them, and the API server +deletes every object of a CRD before it removes the CRD. Those objects +are blockstor's whole database; it runs with no other datastore. The +annotation is added here rather than in definitions/, which is copied +verbatim from blockstor's generated manifests by `make update-blockstor-crds`. +*/}} +{{- if eq .Values.backend "blockstor" }} +{{- range $path, $_ := .Files.Glob "definitions/*" }} +{{- $crd := $.Files.Get $path | fromYaml }} +{{- $annotations := default dict $crd.metadata.annotations }} +{{- $_ := set $annotations "helm.sh/resource-policy" "keep" }} +{{- $_ := set $crd.metadata "annotations" $annotations }} +--- +{{ toYaml $crd }} +{{- end }} +{{- end }} diff --git a/packages/system/linstor/templates/linstor-api-tls.yaml b/packages/system/linstor/templates/linstor-api-tls.yaml index 055e6d082..c178b1a67 100644 --- a/packages/system/linstor/templates/linstor-api-tls.yaml +++ b/packages/system/linstor/templates/linstor-api-tls.yaml @@ -1,3 +1,4 @@ +{{- if eq .Values.backend "linstor" }} --- apiVersion: cert-manager.io/v1 kind: Certificate @@ -27,3 +28,4 @@ metadata: spec: ca: secretName: linstor-api-ca +{{- end }} diff --git a/packages/system/linstor/templates/linstor-internal-tls.yaml b/packages/system/linstor/templates/linstor-internal-tls.yaml index fe5ff4b1f..52913afde 100644 --- a/packages/system/linstor/templates/linstor-internal-tls.yaml +++ b/packages/system/linstor/templates/linstor-internal-tls.yaml @@ -1,3 +1,5 @@ +{{- /* Under both backends: the satellite configuration in + satellites-cozy.yaml takes its internalTLS certificates from this CA. */ -}} --- apiVersion: cert-manager.io/v1 kind: Certificate diff --git a/packages/system/linstor/templates/plunger/configmap-scripts.yaml b/packages/system/linstor/templates/plunger/configmap-scripts.yaml index 7dc72ef59..871a554d2 100644 --- a/packages/system/linstor/templates/plunger/configmap-scripts.yaml +++ b/packages/system/linstor/templates/plunger/configmap-scripts.yaml @@ -1,3 +1,4 @@ +{{- if eq .Values.backend "linstor" }} {{- $files := .Files.Glob "hack/plunger/*.sh" -}} {{/* TODO Add checksum of scripts to the pod selectors */}} --- @@ -7,3 +8,4 @@ metadata: name: linstor-plunger namespace: cozy-linstor data: {{- $files.AsConfig | nindent 2 }} +{{- end }} diff --git a/packages/system/linstor/templates/podscrape.yaml b/packages/system/linstor/templates/podscrape.yaml index 05b1483e1..2ed584d38 100644 --- a/packages/system/linstor/templates/podscrape.yaml +++ b/packages/system/linstor/templates/podscrape.yaml @@ -20,6 +20,7 @@ spec: selector: matchLabels: app.kubernetes.io/component: linstor-satellite +{{- if eq .Values.backend "linstor" }} --- apiVersion: operator.victoriametrics.com/v1beta1 kind: VMPodScrape @@ -44,3 +45,4 @@ spec: matchLabels: app.kubernetes.io/component: linstor-controller {{- end }} +{{- end }} diff --git a/packages/system/linstor/templates/satellites-cozy.yaml b/packages/system/linstor/templates/satellites-cozy.yaml index bb6240128..5f35e9088 100644 --- a/packages/system/linstor/templates/satellites-cozy.yaml +++ b/packages/system/linstor/templates/satellites-cozy.yaml @@ -1,3 +1,12 @@ +{{- /* Rendered under both backends. piraeus-operator creates a + linstor-satellite pod on every node it selects for linstor-csi-node, + external mode included, and LinstorCluster has no switch that keeps + the satellites and drops nothing else. Without this configuration the + pod falls back to the operator's default image by tag, without TLS, + limits or host networking. Host networking matters most under + blockstor: the operator registers each node at its satellite pod's + address, and on the pod network that address is one DRBD peers cannot + reach. */ -}} apiVersion: piraeus.io/v1 kind: LinstorSatelliteConfiguration metadata: diff --git a/packages/system/linstor/templates/satellites-plunger.yaml b/packages/system/linstor/templates/satellites-plunger.yaml index 78109e167..8a0fc603a 100644 --- a/packages/system/linstor/templates/satellites-plunger.yaml +++ b/packages/system/linstor/templates/satellites-plunger.yaml @@ -1,3 +1,4 @@ +{{- if eq .Values.backend "linstor" }} apiVersion: piraeus.io/v1 kind: LinstorSatelliteConfiguration metadata: @@ -94,3 +95,4 @@ spec: configMap: name: linstor-plunger defaultMode: 0755 +{{- end }} diff --git a/packages/system/linstor/templates/satellites-talos.yaml b/packages/system/linstor/templates/satellites-talos.yaml index 6a986c95e..ea3f5cfc6 100644 --- a/packages/system/linstor/templates/satellites-talos.yaml +++ b/packages/system/linstor/templates/satellites-talos.yaml @@ -1,10 +1,23 @@ {{- if .Values.talos.enabled }} +{{- /* Gated on the OS, never on .Values.backend: piraeus creates the + linstor-satellite. DaemonSets under blockstor too, and on Talos + they wedge at Init:0/3 on the run-systemd-system hostPath without + this patch. On generic Linux the patch must not apply at all: it + drops drbd-module-loader, the only thing that loads DRBD there. */ -}} {{- $shutdown := .Values.talos.gracefulShutdown | default dict }} {{- $enabled := dig "enabled" false $shutdown }} {{- if kindIs "invalid" $enabled }}{{- $enabled = false }}{{- end }} {{- if not (kindIs "bool" $enabled) }} {{- fail "linstor: talos.gracefulShutdown.enabled must be a boolean" }} {{- end }} +{{- /* The hook runs `drbdsetup down` on every idle Secondary resource in the + host kernel when the piraeus satellite stops. Under blockstor those + resources are blockstor-satellite's, so a rollout of the idle piraeus + pod would take healthy replicas down. Refused rather than dropped, so + the setting does not look like it took effect. */ -}} +{{- if and $enabled (eq .Values.backend "blockstor") }} +{{- fail "linstor: talos.gracefulShutdown.enabled is not supported with backend blockstor: its hook would tear down blockstor's DRBD resources" }} +{{- end }} apiVersion: piraeus.io/v1 kind: LinstorSatelliteConfiguration metadata: diff --git a/packages/system/linstor/tests/apiserver_tls_test.yaml b/packages/system/linstor/tests/apiserver_tls_test.yaml new file mode 100644 index 000000000..5e4fb7adb --- /dev/null +++ b/packages/system/linstor/tests/apiserver_tls_test.yaml @@ -0,0 +1,58 @@ +suite: blockstor apiserver PKI (blockstor backend) + +# The operator's own API client is wired by NAME, from +# LinstorCluster.spec.apiTLS.clientSecretName, and piraeus-operator does not +# create that secret in external mode — it only reads it. So the name has to +# match a Certificate this chart issues from the blockstor CA, and nothing in +# the cluster tells you when it stops matching: the operator falls back on +# whatever secret carries that name, validates against the ca.crt in it, and +# the probe fails at runtime with "certificate signed by unknown authority" +# while every HelmRelease still reports Ready. +# +# That is exactly how the bug shipped. The default name, linstor-client-tls, +# is a real secret on any cluster switched over from the LINSTOR backend — +# issued from linstor-api-ca, which cannot verify the blockstor serving cert. + +templates: + - templates/blockstor-apiserver-tls.yaml + +set: + backend: blockstor + +tests: + - it: "issues the client certificate the operator is pointed at, from the blockstor CA" + template: templates/blockstor-apiserver-tls.yaml + documentIndex: 3 + asserts: + - isKind: + of: Certificate + - equal: + path: metadata.name + value: blockstor-apiserver-client + # The name cluster.yaml hands the operator. A rename on either side + # leaves the operator reading some other secret's CA. + - equal: + path: spec.secretName + value: blockstor-apiserver-client-tls + - equal: + path: spec.issuerRef.name + value: blockstor-api-ca + # Without client auth the :3371 listener, which is + # RequireAndVerifyClientCert, rejects the operator's connection even + # once it trusts the CA. + - contains: + path: spec.usages + content: client auth + + - it: "serves from the same CA the client certificate validates against" + template: templates/blockstor-apiserver-tls.yaml + documentIndex: 2 + asserts: + - isKind: + of: Certificate + - equal: + path: metadata.name + value: blockstor-apiserver-server + - equal: + path: spec.issuerRef.name + value: blockstor-api-ca diff --git a/packages/system/linstor/tests/backend_test.yaml b/packages/system/linstor/tests/backend_test.yaml new file mode 100644 index 000000000..0b70e69f3 --- /dev/null +++ b/packages/system/linstor/tests/backend_test.yaml @@ -0,0 +1,178 @@ +suite: storage backend selection + +# The backend is opt-in and defaults to LINSTOR. That default is what every +# existing cluster runs, so a change that quietly flipped it would swap the +# storage control plane under live data on the next reconcile. These tests +# pin the default and prove each backend renders only its own control plane. + +release: + name: linstor + namespace: cozy-linstor + +tests: + - it: "defaults to the LINSTOR backend" + templates: + - templates/cluster.yaml + asserts: + - isKind: + of: LinstorCluster + # The operator runs its own in-cluster controller: no external URL. + - notExists: + path: spec.externalController + + - it: "renders no blockstor control plane by default" + templates: + - templates/blockstor-controller.yaml + - templates/blockstor-apiserver.yaml + - templates/blockstor-satellite.yaml + asserts: + - hasDocuments: + count: 0 + + - it: "renders no blockstor CRDs by default" + templates: + - templates/crds/crds.yaml + asserts: + - hasDocuments: + count: 0 + + # piraeus still runs a linstor-satellite pod per node in external mode, so + # what it runs is pinned the same way under either backend: cozystack's + # image, TLS, limits and host networking. + - it: "pins the piraeus satellite under the blockstor backend" + set: + backend: blockstor + piraeusServer.image.repository: example.org/piraeus-server + piraeusServer.image.tag: pinned + templates: + - templates/satellites-cozy.yaml + asserts: + - hasDocuments: + count: 1 + - equal: + path: spec.podTemplate.spec.hostNetwork + value: true + - equal: + path: spec.internalTLS.certManager.name + value: linstor-internal-ca + - equal: + path: spec.podTemplate.spec.containers[0].image + value: example.org/piraeus-server:pinned + + - it: "issues the satellite's internal CA under the blockstor backend" + set: + backend: blockstor + templates: + - templates/linstor-internal-tls.yaml + asserts: + - hasDocuments: + count: 2 + - equal: + path: kind + value: Issuer + documentIndex: 1 + + # The plunger runs drbdadm against the node's DRBD resources on its own + # schedule. Under blockstor those belong to blockstor-satellite alone, so the + # plunger stays with the LINSTOR backend. + - it: "renders no plunger on the blockstor backend" + set: + backend: blockstor + templates: + - templates/satellites-plunger.yaml + asserts: + - hasDocuments: + count: 0 + + # The Talos patch is NOT one of those. piraeus-operator still creates + # linstor-satellite. DaemonSets in external mode, and on Talos + # they wedge at Init:0/3 without it — the hostPath /run/systemd/system + # does not exist there — which then churns linstor-csi-node and blocks + # every PVC attach while every HelmRelease still reports Ready. + - it: "patches the satellite for Talos under both backends" + set: + backend: blockstor + templates: + - templates/satellites-talos.yaml + asserts: + - hasDocuments: + count: 1 + - isKind: + of: LinstorSatelliteConfiguration + - equal: + path: metadata.name + value: cozystack-talos + + - it: "patches the satellite for Talos on the LINSTOR backend too" + set: + backend: linstor + templates: + - templates/satellites-talos.yaml + asserts: + - hasDocuments: + count: 1 + - equal: + path: metadata.name + value: cozystack-talos + + - it: "ships the blockstor CRDs on the blockstor backend" + set: + backend: blockstor + templates: + - templates/crds/crds.yaml + asserts: + - hasDocuments: + count: 8 + - isKind: + of: CustomResourceDefinition + + # A value arriving outside the platform chart's own check, a hand-set + # component value for one, rendered some objects of each backend and + # exited 0. + - it: fails the render on an unrecognised backend + templates: + - templates/backend-guard.yaml + set: + backend: blokstor + asserts: + - failedTemplate: + errorMessage: 'linstor: backend must be "linstor" or "blockstor", got "blokstor"' + + - it: accepts the blockstor backend + templates: + - templates/backend-guard.yaml + set: + backend: blockstor + asserts: + - hasDocuments: + count: 0 + + # drbd-reactor in the piraeus satellite pod reads DRBD state from the kernel, + # which is the same under either control plane, so its metrics and the alerts + # built on them stay. The controller scrape targets the Java controller, which + # blockstor does not run. + - it: "keeps scraping the satellites under the blockstor backend" + set: + backend: blockstor + capabilities: + apiVersions: + - operator.victoriametrics.com/v1beta1 + templates: + - templates/podscrape.yaml + asserts: + - hasDocuments: + count: 1 + - equal: + path: metadata.name + value: linstor-satellite + + # The guard is the only check that reaches the default value through the + # whole chart; every other default test renders named templates. + - it: accepts the default backend + templates: + - templates/backend-guard.yaml + set: + backend: linstor + asserts: + - hasDocuments: + count: 0 diff --git a/packages/system/linstor/tests/blockstor_cluster_test.yaml b/packages/system/linstor/tests/blockstor_cluster_test.yaml new file mode 100644 index 000000000..47dcc6089 --- /dev/null +++ b/packages/system/linstor/tests/blockstor_cluster_test.yaml @@ -0,0 +1,103 @@ +suite: LinstorCluster external mode (blockstor backend) + +# Pins the LinstorCluster surface this package renders on the BLOCKSTOR +# backend. piraeus-operator runs in EXTERNAL mode there: it deploys no +# in-cluster linstor-controller and instead points linstor-csi at the blockstor +# apiserver (spec.externalController.url), issuing the CSI client certs from the +# blockstor-api-ca Issuer (spec.apiTLS). Controller-level DRBD tuning is carried +# in spec.properties, which the operator applies to the external controller over +# the LINSTOR REST API. There must be NO spec.controller block (no in-cluster +# controller / plunger sidecar) in this mode. + +templates: + - templates/cluster.yaml + +# Blockstor is opt-in. Without this the suite renders the LINSTOR backend, +# whose LinstorCluster is a different shape entirely. +set: + backend: blockstor + +tests: + - it: "renders a LinstorCluster pointed at the external blockstor apiserver" + asserts: + - isKind: + of: LinstorCluster + - equal: + path: spec.externalController.url + value: https://blockstor-apiserver.cozy-linstor.svc:3371 + - equal: + path: spec.apiTLS.certManager.name + value: blockstor-api-ca + - equal: + path: spec.apiTLS.certManager.kind + value: Issuer + # The operator's OWN client, the one that probes + # /v1/controller/version, is not provisioned by certManager in + # external mode — piraeus-operator emits no controller-side + # Certificate there. Left at its default it looks for + # linstor-client-tls, finds nothing, and cannot verify a serving + # cert signed by blockstor-api-ca; the probe fails and every + # satellite reconcile stops behind it. + - equal: + path: spec.apiTLS.clientSecretName + value: blockstor-apiserver-client-tls + + - it: "runs in external mode — no in-cluster linstor-controller / plunger" + asserts: + - notExists: + path: spec.controller + - notExists: + path: spec.internalTLS + + - it: "carries controller-level DRBD Net tuning as properties" + asserts: + - contains: + path: spec.properties + content: + name: DrbdOptions/Net/verify-alg + value: "crc32c" + - contains: + path: spec.properties + content: + name: DrbdOptions/Net/timeout + value: "100" + + - it: "auto-diskful properties are values-driven" + asserts: + - contains: + path: spec.properties + content: + name: DrbdOptions/auto-diskful + value: "30" + - contains: + path: spec.properties + content: + name: DrbdOptions/auto-diskful-allow-cleanup + value: "true" + + - it: "auto-diskful properties are dropped when disabled" + set: + linstor: + autoDiskful: + enabled: false + asserts: + - notContains: + path: spec.properties + content: + name: DrbdOptions/auto-diskful + value: "30" + # Net tuning is unconditional and stays regardless of auto-diskful. + - contains: + path: spec.properties + content: + name: DrbdOptions/Net/verify-alg + value: "crc32c" + + - it: "the reused linstor-csi image pin is preserved on the CSI podTemplates" + asserts: + - matchRegex: + path: spec.csiController.podTemplate.spec.containers[0].image + pattern: "^ghcr\\.io/cozystack/cozystack/linstor-csi:" + - matchRegex: + path: spec.csiNode.podTemplate.spec.containers[0].image + pattern: "^ghcr\\.io/cozystack/cozystack/linstor-csi:" diff --git a/packages/system/linstor/tests/blockstor_controller_events_test.yaml b/packages/system/linstor/tests/blockstor_controller_events_test.yaml new file mode 100644 index 000000000..560ce64f6 --- /dev/null +++ b/packages/system/linstor/tests/blockstor_controller_events_test.yaml @@ -0,0 +1,22 @@ +# The controller records events through events.k8s.io; without the grant +# its warnings (a definition short of its group's layer stack) are dropped. +suite: blockstor controller events +templates: + - templates/blockstor-controller.yaml +release: + name: linstor + namespace: cozy-linstor +set: + backend: blockstor +tests: + - it: lets the controller record events.k8s.io events + documentSelector: + path: kind + value: ClusterRole + asserts: + - contains: + path: rules + content: + apiGroups: [events.k8s.io] + resources: [events] + verbs: [create, patch] diff --git a/packages/system/linstor/tests/blockstor_images_test.yaml b/packages/system/linstor/tests/blockstor_images_test.yaml new file mode 100644 index 000000000..8e31355c3 --- /dev/null +++ b/packages/system/linstor/tests/blockstor_images_test.yaml @@ -0,0 +1,53 @@ +suite: cozy-linstor blockstor image pins +release: + name: linstor + namespace: cozy-linstor +# Blockstor is opt-in; without this the suite renders the LINSTOR backend +# and every blockstor template is empty. +set: + backend: blockstor + +# Every image this package ships must be pinned by digest (tag@sha256:...) so a +# moving upstream tag can never silently change what runs. blockstor-* are the +# published ghcr.io/cozystack/blockstor-* release images; linstor-csi is reused +# unchanged and pinned on the LinstorCluster CSI podTemplates. +tests: + - it: pins blockstor-apiserver by digest + template: templates/blockstor-apiserver.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - matchRegex: + path: spec.template.spec.containers[0].image + pattern: '^ghcr\.io/cozystack/blockstor-apiserver:[^@]+@sha256:[0-9a-f]{64}$' + + - it: pins blockstor-controller by digest + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - matchRegex: + path: spec.template.spec.containers[0].image + pattern: '^ghcr\.io/cozystack/blockstor-controller:[^@]+@sha256:[0-9a-f]{64}$' + + - it: pins blockstor-satellite by digest + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - matchRegex: + path: spec.template.spec.containers[0].image + pattern: '^ghcr\.io/cozystack/blockstor-satellite:[^@]+@sha256:[0-9a-f]{64}$' + + - it: pins the reused linstor-csi by digest on the LinstorCluster + template: templates/cluster.yaml + documentSelector: + path: kind + value: LinstorCluster + asserts: + - matchRegex: + path: spec.csiController.podTemplate.spec.containers[0].image + pattern: '^ghcr\.io/cozystack/cozystack/linstor-csi:[^@]+@sha256:[0-9a-f]{64}$' diff --git a/packages/system/linstor/tests/blockstor_names_test.yaml b/packages/system/linstor/tests/blockstor_names_test.yaml new file mode 100644 index 000000000..ad61cc823 --- /dev/null +++ b/packages/system/linstor/tests/blockstor_names_test.yaml @@ -0,0 +1,61 @@ +# piraeus-operator creates and owns Service/linstor-controller and +# Certificate/linstor-client-tls. Rendering either name from this chart puts +# it in Helm's create set on a switch to blockstor, Helm refuses to adopt an +# object it does not own, and the upgrade aborts before anything applies, the +# LinstorCluster change that would prune piraeus's copies included. +suite: the blockstor backend renders no name piraeus-operator owns +templates: + - templates/*.yaml +release: + name: linstor + namespace: cozy-linstor +set: + backend: blockstor +tests: + - it: renders no linstor-controller Service + documentSelector: + path: metadata.name + value: linstor-controller + skipEmptyTemplates: true + asserts: + - notEqual: + path: kind + value: Service + + - it: renders no linstor-client-tls Certificate + documentSelector: + path: metadata.name + value: linstor-client-tls + skipEmptyTemplates: true + asserts: + - notEqual: + path: kind + value: Certificate + + # The apiserver Service is the mTLS listener only. The plain-HTTP listener + # on :3370 is for kubectl port-forward to a pod and must not be reachable + # through the Service. + - it: exposes only the mutual-TLS port on the apiserver Service + template: templates/blockstor-apiserver.yaml + documentSelector: + path: kind + value: Service + asserts: + - equal: + path: spec.ports + value: + - {name: rest-tls, port: 3371, targetPort: 3371} + + - it: serves the apiserver certificate for its own Service only + template: templates/blockstor-apiserver-tls.yaml + documentSelector: + path: metadata.name + value: blockstor-apiserver-server + asserts: + - equal: + path: spec.dnsNames + value: + - blockstor-apiserver + - blockstor-apiserver.cozy-linstor + - blockstor-apiserver.cozy-linstor.svc + - blockstor-apiserver.cozy-linstor.svc.cluster.local diff --git a/packages/system/linstor/tests/blockstor_rbac_test.yaml b/packages/system/linstor/tests/blockstor_rbac_test.yaml new file mode 100644 index 000000000..8c21efa87 --- /dev/null +++ b/packages/system/linstor/tests/blockstor_rbac_test.yaml @@ -0,0 +1,71 @@ +# The apiserver writes exactly one Secret, the encryption passphrase, and +# always in its own namespace. A cluster-wide write grant would reach every +# tenant's admin kubeconfig and every managed-service credential. +suite: blockstor apiserver Secret access +templates: + - templates/blockstor-apiserver.yaml +release: + name: linstor + namespace: cozy-linstor +set: + backend: blockstor +tests: + - it: grants Secrets only read access cluster-wide + documentSelector: + path: kind + value: ClusterRole + asserts: + - contains: + path: rules + content: + apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch] + - notContains: + path: rules + content: + apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch, create, update, patch] + + - it: grants Secret writes in the release namespace only + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: metadata.namespace + value: cozy-linstor + - contains: + path: rules + content: + apiGroups: [""] + resources: [secrets] + verbs: [create, update, patch] + + - it: binds the namespaced Role to the apiserver ServiceAccount + documentSelector: + path: kind + value: RoleBinding + asserts: + - equal: + path: roleRef.name + value: blockstor-apiserver-secrets + - contains: + path: subjects + content: + kind: ServiceAccount + name: blockstor-apiserver + namespace: cozy-linstor + + - it: names the blockstor kinds instead of granting the whole group + documentSelector: + path: kind + value: ClusterRole + asserts: + - notContains: + path: rules + content: + apiGroups: [blockstor.cozystack.io] + resources: ["*"] + verbs: [get, list, watch, create, update, patch, delete] diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml new file mode 100644 index 000000000..2a97883e2 --- /dev/null +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -0,0 +1,213 @@ +suite: blockstor workloads +release: + name: linstor + namespace: cozy-linstor +set: + backend: blockstor +tests: + # The plain-HTTP listener authenticates nobody. On the pod network any pod + # that can route to the apiserver would get the whole LINSTOR API, deletes + # included, around the mTLS on :3371. + - it: binds the apiserver's plain-HTTP listener to loopback + template: templates/blockstor-apiserver.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - contains: + path: spec.template.spec.containers[0].args + content: --rest-bind-address=127.0.0.1:3370 + - notContains: + path: spec.template.spec.containers[0].ports + content: {name: rest-debug, containerPort: 3370} + + # The controller runs without leader election, so two pods side by side + # would both reconcile the same objects. + - it: never runs two controllers during a rollout + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - equal: + path: spec.strategy.type + value: Recreate + - equal: + path: spec.replicas + value: 1 + + - it: lets the satellite delete nothing but PhysicalDevices + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - contains: + path: rules + content: + apiGroups: [blockstor.cozystack.io] + resources: [physicaldevices] + verbs: [create, update, patch, delete] + - contains: + path: rules + content: + apiGroups: [blockstor.cozystack.io] + resources: [nodes, resources, snapshots, storagepools] + verbs: [update, patch] + - lengthEqual: + path: rules + count: 6 + + - it: gives the satellite no Secret or Lease access at cluster scope + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - notContains: + path: rules + content: + apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch] + - notContains: + path: rules + content: + apiGroups: [coordination.k8s.io] + resources: [leases] + verbs: [get, list, watch, create, update, patch, delete] + + - it: lets the satellite read Secrets in its own namespace only + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: metadata.namespace + value: cozy-linstor + - equal: + path: rules + value: + - apiGroups: [""] + resources: [secrets] + verbs: [get] + + - it: binds the satellite's Secret Role to its ServiceAccount + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: RoleBinding + asserts: + - equal: + path: roleRef.name + value: blockstor-satellite-secrets + - equal: + path: subjects[0].name + value: blockstor-satellite + + - it: gives the controller no Lease access + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - notContains: + path: rules + content: + apiGroups: [coordination.k8s.io] + resources: [leases] + verbs: [get, list, watch, create, update, patch, delete] + + - it: closes the satellite's unauthenticated ports to the world + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: CiliumClusterwideNetworkPolicy + asserts: + - equal: + path: spec.ingressDeny[0].fromEntities + value: [world] + - equal: + path: spec.ingressDeny[0].toPorts[0].ports + value: + - port: "9100" + - port: "9101" + - port: "8080" + + # A kind added to the group later must not be granted by omission, so the + # roles are pinned whole: a wildcard or a new kind shows up as a diff here. + - it: pins the controller ClusterRole rule by rule + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: rules + value: + - apiGroups: [''] + resources: [events] + verbs: [create, patch] + - apiGroups: [events.k8s.io] + resources: [events] + verbs: [create, patch] + - apiGroups: [''] + resources: [nodes] + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: [controllerconfigs] + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: [nodes, resourcedefinitions, resourcegroups, resources, snapshots, storagepools] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [blockstor.cozystack.io] + resources: [nodes/finalizers, resourcedefinitions/finalizers, resourcegroups/finalizers, + resources/finalizers, snapshots/finalizers, storagepools/finalizers] + verbs: [update] + - apiGroups: [blockstor.cozystack.io] + resources: [nodes/status, resourcedefinitions/status, resourcegroups/status, resources/status, + snapshots/status, storagepools/status] + verbs: [get, update, patch] + + - it: pins the satellite ClusterRole rule by rule + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: rules + value: + - apiGroups: [''] + resources: [events] + verbs: [create, patch] + - apiGroups: [''] + resources: [nodes] + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: [controllerconfigs, nodes, physicaldevices, resourcedefinitions, resourcegroups, + resources, snapshots, storagepools] + verbs: [get, list, watch] + - apiGroups: [blockstor.cozystack.io] + resources: [physicaldevices] + verbs: [create, update, patch, delete] + - apiGroups: [blockstor.cozystack.io] + resources: [nodes, resources, snapshots, storagepools] + verbs: [update, patch] + - apiGroups: [blockstor.cozystack.io] + resources: [nodes/status, physicaldevices/status, resources/status, snapshots/status, + storagepools/status, nodes/finalizers, physicaldevices/finalizers, resources/finalizers, + snapshots/finalizers, storagepools/finalizers] + verbs: [get, update, patch] + + # global_common.conf is a subPath mount, which is never refreshed in place. + - it: rolls the satellites when global_common.conf changes + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - matchRegex: + path: spec.template.metadata.annotations["checksum/drbd-conf"] + pattern: '^[0-9a-f]{64}$' diff --git a/packages/system/linstor/tests/crds_test.yaml b/packages/system/linstor/tests/crds_test.yaml new file mode 100644 index 000000000..22f727cd0 --- /dev/null +++ b/packages/system/linstor/tests/crds_test.yaml @@ -0,0 +1,31 @@ +# Blockstor keeps its entire control-plane state in objects of these CRDs. +# They render from templates/, so an upgrade that stops rendering them, a +# switch of the backend back to linstor, would delete them and every object +# with them. helm.sh/resource-policy: keep is what stops that. +# +# The kind assertion catches a non-CRD document carrying the annotation, +# which the annotation assertion alone would accept. +suite: blockstor CRDs survive a switch back to linstor +templates: + - templates/crds/crds.yaml +tests: + - it: annotates every CRD the blockstor backend renders + set: + backend: blockstor + asserts: + - hasDocuments: + count: 8 + - equal: + path: kind + value: CustomResourceDefinition + - equal: + path: metadata.annotations["helm.sh/resource-policy"] + value: keep + - equal: + path: metadata.annotations["controller-gen.kubebuilder.io/version"] + value: v0.20.1 + + - it: renders no CRD under the linstor backend + asserts: + - hasDocuments: + count: 0 diff --git a/packages/system/linstor/tests/csi-topology_test.yaml b/packages/system/linstor/tests/csi-topology_test.yaml index 1b346a93e..de357db97 100644 --- a/packages/system/linstor/tests/csi-topology_test.yaml +++ b/packages/system/linstor/tests/csi-topology_test.yaml @@ -62,3 +62,18 @@ tests: - equal: path: spec.csiController.podTemplate.spec.containers[1].name value: csi-snapshotter + + # The LinstorCluster is one document for both backends, so the CSI controller + # half is shared and blockstor gets the same constraint. linstor-csi issues the + # same CreateVolume either way; only the API behind it differs. + - it: the provisioner is constrained under the blockstor backend too + template: templates/cluster.yaml + set: + backend: blockstor + asserts: + - contains: + path: spec.csiController.podTemplate.spec.containers[?(@.name=="csi-provisioner")].args + content: --strict-topology + - lengthEqual: + path: spec.csiController.podTemplate.spec.containers[?(@.name=="csi-provisioner")].args + count: 12 diff --git a/packages/system/linstor/tests/talos_gate_test.yaml b/packages/system/linstor/tests/talos_gate_test.yaml new file mode 100644 index 000000000..69d24db31 --- /dev/null +++ b/packages/system/linstor/tests/talos_gate_test.yaml @@ -0,0 +1,35 @@ +suite: Talos satellite patch is gated on the OS, not the backend +templates: + - templates/satellites-talos.yaml + +# The patch drops drbd-module-loader, which is what loads DRBD on a node +# whose kernel does not ship it as a Talos extension. On generic Linux it +# must not render at all. On Talos it renders under both backends, since +# piraeus creates the linstor-satellite DaemonSets under blockstor too. +tests: + - it: renders nothing on generic Linux under the linstor backend + set: + talos.enabled: false + backend: linstor + asserts: + - hasDocuments: + count: 0 + + - it: renders nothing on generic Linux under the blockstor backend + set: + talos.enabled: false + backend: blockstor + asserts: + - hasDocuments: + count: 0 + + - it: renders on Talos under the blockstor backend + set: + talos.enabled: true + backend: blockstor + asserts: + - isKind: + of: LinstorSatelliteConfiguration + - equal: + path: metadata.name + value: cozystack-talos diff --git a/packages/system/linstor/tests/talos_shutdown_test.yaml b/packages/system/linstor/tests/talos_shutdown_test.yaml index a2de6ab2c..a454f3b7a 100644 --- a/packages/system/linstor/tests/talos_shutdown_test.yaml +++ b/packages/system/linstor/tests/talos_shutdown_test.yaml @@ -78,3 +78,22 @@ tests: - matchRegex: path: spec.patches[0].patch pattern: 'name: drbd-shutdown-guard' + + # The hook downs idle Secondary resources in the shared host kernel, which + # under blockstor belong to blockstor-satellite. + - it: refuses the hook under the blockstor backend + set: + backend: blockstor + talos.gracefulShutdown.enabled: true + asserts: + - failedTemplate: + errorMessage: "linstor: talos.gracefulShutdown.enabled is not supported with backend blockstor: its hook would tear down blockstor's DRBD resources" + + - it: keeps the Talos patch under blockstor when the hook is off + set: + backend: blockstor + asserts: + - notExists: + path: spec.podTemplate + - exists: + path: spec.patches diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index 4ee1429ec..a14daaa6c 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -1,7 +1,41 @@ +# Which storage control plane this package deploys. +# +# linstor — the Java linstor-controller driven by piraeus-operator +# (the default, and what every existing cluster runs). +# blockstor — blockstor's controller/apiserver/satellite, with +# piraeus-operator in EXTERNAL mode so it only drives +# linstor-csi. EXPERIMENTAL. +# +# Both backends serve the same CSI wire shape through the same +# linstor-csi build, so the StorageClasses (provisioner +# linstor.csi.linbit.com) are the same under either. +# +# blockstor is for new clusters only. Switching a cluster that already +# holds LINSTOR volumes is not supported: the pinned blockstor release +# cannot adopt existing DRBD resources safely, and this chart does not +# convert LINSTOR's database into blockstor's. +backend: linstor + piraeusServer: image: repository: ghcr.io/cozystack/cozystack/piraeus-server tag: v1.6.0@sha256:70ddd1a66fbc1ea58078f4645fc572ab8e2e189dbb4d9a5f9ca43d5663106483 + +# Blockstor images are component-versioned: they are released from the +# blockstor repository and carry ITS version, so a cozystack release +# must not retag them to the cozystack version. +blockstorController: + image: + repository: ghcr.io/cozystack/blockstor-controller + tag: 0.1.17@sha256:19b5733565e4bbe9510eecae8d47a181e72e07009b3d565848e8ccf1cd9393e8 +blockstorApiserver: + image: + repository: ghcr.io/cozystack/blockstor-apiserver + tag: 0.1.17@sha256:102cf8c8d431f3b6714bca53752327ae8bb793b2d5ebed3aae47d51a85805f26 +blockstorSatellite: + image: + repository: ghcr.io/cozystack/blockstor-satellite + tag: 0.1.17@sha256:8bd15bca47f33464eaf489884c33fd50ef2574a0ad856ab5ab9b921186a98bea # Talos-specific workarounds (disable for generic Linux like Ubuntu/Debian) talos: enabled: true @@ -59,6 +93,9 @@ linstor: enabled: true minutes: 30 allowCleanup: true +# linstor-csi is REUSED unchanged — blockstor serves the same CSI +# wire-shape, so the existing StorageClasses (provisioner +# linstor.csi.linbit.com) keep working. linstorCSI: ## Constrain provisioning to the node the scheduler actually picked. ## From cf7bd11eeb822a12ea9300b50410b1691e800e75 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Wed, 21 Oct 2026 17:36:24 +0200 Subject: [PATCH 02/18] test(e2e): prepare and check the backend the install deploys The e2e scripts assumed LINSTOR throughout: the prep created pools through linstor-controller and the replicated suite's pool guard read them from it. COZY_STORAGE_BACKEND is now set once by the install step and reaches the platform values, the prep and the Chainsaw suites alike. The prep refuses a missing or unknown value instead of guessing, which would race the install and fail open to linstor. Under blockstor the prep waits for blockstor's own Deployments and for every LinstorSatellite to apply, registers a Node per Kubernetes node at its InternalIP, creates the data zpool and its StoragePool on each satellite, and waits until every satellite has reported its pool, since placement does not count a pool before that. The pool guard reads StoragePool objects and lists datasets through blockstor-satellite. The backend is validated before the guard starts polling. Inside the loop every failed read is retried: the remote jq exits 2 on the output a restarting controller can print, so no read status can mean "give up". blockstor needs DRBD and the QEMU lane's private disk, so the pair with COZY_LINSTOR_DRBD_ENABLED=false is refused rather than installed into a prep that cannot finish. No CI lane sets the variable, so the default runs are unchanged. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- hack/e2e-chainsaw/_lib/run-kubernetes.sh | 115 ++++++++--- hack/e2e-install-cozystack.bats | 5 + hack/e2e-platform-packages.sh | 29 ++- hack/e2e-post-install-prep.sh | 231 +++++++++++++++++++++++ hack/linstor-storage-mode_test.bats | 184 ++++++++++++++++++ hack/platform-packages_test.bats | 41 ++++ hack/post-install-prep.bats | 194 +++++++++++++++++++ packages/core/testing/Makefile | 6 +- 8 files changed, 774 insertions(+), 31 deletions(-) diff --git a/hack/e2e-chainsaw/_lib/run-kubernetes.sh b/hack/e2e-chainsaw/_lib/run-kubernetes.sh index d13ec5a31..32ffc61f1 100644 --- a/hack/e2e-chainsaw/_lib/run-kubernetes.sh +++ b/hack/e2e-chainsaw/_lib/run-kubernetes.sh @@ -493,6 +493,52 @@ cozy_wait_schedulable_node() { done } +# The storage control plane the cluster under test runs, as the install was +# told (COZY_STORAGE_BACKEND, forwarded into the sandbox). Unset means linstor, +# the default every lane installs; anything else unknown is refused rather than +# read as linstor, which would poll a controller that does not exist. +_cozy_storage_backend() { + case "${COZY_STORAGE_BACKEND:-linstor}" in + linstor | blockstor) printf '%s\n' "${COZY_STORAGE_BACKEND:-linstor}" ;; + *) + echo "» ERROR: COZY_STORAGE_BACKEND must be linstor or blockstor, got '${COZY_STORAGE_BACKEND}'" >&2 + return 2 + ;; + esac +} + +# Print `:` for every ZFS pool that reports a free capacity. +# The LINSTOR path asks the controller, whose `sp l` serves one outer array of +# pool objects with free_capacity in KiB; OFFLINE satellites omit it, and the +# DISKLESS placeholder carries a Long.MAX_VALUE sentinel, so both are skipped. +# The blockstor path reads the StoragePool objects, whose status.freeCapacity +# is in KiB too; there is no controller pod to exec into. +_cozy_pool_free_rows() { + _backend=$(_cozy_storage_backend) || return 2 + if [ "$_backend" = blockstor ]; then + # Read first and filter second: piped, the read's status is jq's, and jq + # on empty input succeeds. + _pools_json=$(kubectl get storagepools.blockstor.cozystack.io --request-timeout=20s -o json) || return 1 + printf '%s\n' "$_pools_json" | + jq -r '.items[] | select((.spec.providerKind | test("^ZFS")) and .status.freeCapacity != null) | "\(.status.freeCapacity):\(.spec.nodeName)"' + return + fi + # jq lives inside the controller pod (Debian-bookworm base, `sh` is dash, + # so the script stays POSIX). + kubectl -n cozy-linstor exec deploy/linstor-controller -- sh -c ' + linstor --machine-readable sp l 2>/dev/null | + jq -r "first | .[] | select((.provider_kind | test(\"^ZFS\")) and .free_capacity != null) | \"\(.free_capacity):\(.node_name)\"" + ' +} + +_cozy_pool_diagnostics() { + if [ "$(_cozy_storage_backend 2>/dev/null)" = blockstor ]; then + kubectl get storagepools.blockstor.cozystack.io -o wide --request-timeout=20s 2>&1 + return + fi + kubectl -n cozy-linstor exec deploy/linstor-controller -- linstor --no-color sp l 2>&1 +} + # Block until every ZFS storage pool on every LINSTOR satellite reports at # least _min_free_gib of FreeCapacity. Motivation is proven from a # cozyreport artefact captured by hack/cozyreport.sh (see PR #3044 run @@ -524,36 +570,34 @@ cozy_wait_linstor_pool_free() { _timeout="${2:-300}" _min_free_kib=$(( _min_free_gib * 1024 * 1024 )) _deadline=$(( $(date +%s) + _timeout )) + # Settled once, before polling. Inside the loop every non-zero status is a + # read that failed and is retried: the remote jq exits 2 on the truncated or + # error output a restarting controller can print, so no status of the read + # can double as "give up". + _cozy_storage_backend >/dev/null || return 2 while :; do - # jq lives inside the controller pod (Debian-bookworm base, `sh` is - # dash — keep the heredoc POSIX-safe). LINSTOR's `--machine-readable` - # output for `sp l` on LINSTOR 1.33.x is a one-element outer array - # whose sole element is a flat array of storage-pool objects; each - # pool object exposes free_capacity at the top level in KiB. Filter - # to ZFS variants (both `ZFS` and `ZFS_THIN`) so DISKLESS - # placeholders (whose free_capacity is a Long.MAX_VALUE sentinel) - # and any future non-ZFS driver are skipped. Also guard against - # OFFLINE satellites, whose pool objects omit free_capacity entirely - # (StoragePool schema marks it optional) — without the null guard - # `sort -n` would rank the string "null" ahead of real numbers and - # the loop would silently poll to timeout. Emit - # `:` lines so a single sort yields the - # smallest pool and its owner in one round-trip. - _min_line=$(kubectl -n cozy-linstor exec deploy/linstor-controller -- sh -c ' - linstor --machine-readable sp l 2>/dev/null | - jq -r "first | .[] | select((.provider_kind | test(\"^ZFS\")) and .free_capacity != null) | \"\(.free_capacity):\(.node_name)\"" | - sort -n | head -n 1 - ' 2>/dev/null) || _min_line="" + # Filter to ZFS variants (both `ZFS` and `ZFS_THIN`) so DISKLESS + # placeholders and any future non-ZFS driver are skipped, and to pools + # that report a free capacity at all, or `sort -n` would rank a missing + # one ahead of real numbers. The read keeps its own status: piped + # straight into `head` it took head's, so a failed read, a 403 and a + # pool that is genuinely full all looked alike. + _rows_rc=0 + _rows=$(_cozy_pool_free_rows 2>/dev/null) || _rows_rc=$? + _min_line="" + if [ "$_rows_rc" -eq 0 ]; then + _min_line=$(printf '%s\n' "$_rows" | grep . | sort -n | head -n 1) + fi _min_kib="${_min_line%%:*}" _min_node="${_min_line#*:}" if [ -n "$_min_kib" ] && [ "$_min_kib" -ge "$_min_free_kib" ] 2>/dev/null; then - echo "» LINSTOR ZFS pool free: smallest satellite ${_min_node} has $(( _min_kib / 1024 / 1024 )) GiB (>= ${_min_free_gib} GiB threshold)" + echo "» ZFS pool free: smallest satellite ${_min_node} has $(( _min_kib / 1024 / 1024 )) GiB (>= ${_min_free_gib} GiB threshold)" return 0 fi if [ "$(date +%s)" -ge "$_deadline" ]; then - echo "» ERROR: LINSTOR ZFS pool free did not reach ${_min_free_gib} GiB on every satellite within ${_timeout}s (smallest observed: ${_min_kib:-unknown} KiB on ${_min_node:-unknown})" >&2 + echo "» ERROR: ZFS pool free did not reach ${_min_free_gib} GiB on every satellite within ${_timeout}s (smallest observed: ${_min_kib:-unknown} KiB on ${_min_node:-unknown}; last read exited ${_rows_rc})" >&2 _pool_diag_rc=0 - _pool_diag=$(kubectl -n cozy-linstor exec deploy/linstor-controller -- linstor --no-color sp l 2>&1) || _pool_diag_rc=$? + _pool_diag=$(_cozy_pool_diagnostics) || _pool_diag_rc=$? if [ "$_pool_diag_rc" -ne 0 ]; then echo " linstor-pool: diagnostic read failed with exit $_pool_diag_rc" >&2 fi @@ -582,19 +626,34 @@ _cozy_linstor_pool_baseline_file() { # `data-srvN` in container mode, where every node's pool is imported into one # shared kernel. Every read carries its own ceiling, so a wedged controller or # satellite fails the poll within 35s instead of holding the caller for good. +# +# On the blockstor backend the pools are StoragePool objects rather than +# controller rows, the zpool is whichever StorDriver property names it, and the +# satellite is blockstor's own DaemonSet. _cozy_linstor_pool_datasets() { - _pools=$(timeout -k 5 30 kubectl -n cozy-linstor exec deploy/linstor-controller -- sh -c ' - linstor --machine-readable sp l 2>/dev/null | - jq -r "first | .[] | select(.provider_kind | test(\"^ZFS\")) | \"\(.node_name) \(.props[\"StorDriver/StorPoolName\"] // \"\")\"" - ' 2>/dev/null) || return 1 + _backend=$(_cozy_storage_backend) || return 1 + if [ "$_backend" = blockstor ]; then + _pools_json=$(timeout -k 5 30 kubectl get storagepools.blockstor.cozystack.io --request-timeout=20s -o json 2>/dev/null) || return 1 + _pools=$(printf '%s\n' "$_pools_json" | + jq -r '.items[] | select(.spec.providerKind | test("^ZFS")) | "\(.spec.nodeName) \(.spec.props["StorDriver/StorPoolName"] // .spec.props["StorDriver/ZPoolThin"] // .spec.props["StorDriver/ZPool"] // "")"') || return 1 + _satellite_selector=app=blockstor-satellite + _satellite_container=satellite + else + _pools=$(timeout -k 5 30 kubectl -n cozy-linstor exec deploy/linstor-controller -- sh -c ' + linstor --machine-readable sp l 2>/dev/null | + jq -r "first | .[] | select(.provider_kind | test(\"^ZFS\")) | \"\(.node_name) \(.props[\"StorDriver/StorPoolName\"] // \"\")\"" + ' 2>/dev/null) || return 1 + _satellite_selector=app.kubernetes.io/component=linstor-satellite + _satellite_container=linstor-satellite + fi [ -n "$_pools" ] || return 1 - _satellites=$(timeout -k 5 30 kubectl -n cozy-linstor get pods -l app.kubernetes.io/component=linstor-satellite \ + _satellites=$(timeout -k 5 30 kubectl -n cozy-linstor get pods -l "$_satellite_selector" \ -o jsonpath='{range .items[*]}{.spec.nodeName} {.metadata.name}{"\n"}{end}' 2>/dev/null) || return 1 while read -r _node _zpool; do [ -n "$_node" ] && [ -n "$_zpool" ] || return 1 _pod=$(printf '%s\n' "$_satellites" | awk -v node="$_node" '$1 == node { print $2; exit }') [ -n "$_pod" ] || return 1 - _datasets=$(timeout -k 5 30 kubectl -n cozy-linstor exec "$_pod" --container=linstor-satellite -- \ + _datasets=$(timeout -k 5 30 kubectl -n cozy-linstor exec "$_pod" --container="$_satellite_container" -- \ zfs list -H -o name -t filesystem,volume,snapshot -r "$_zpool" /dev/null) || return 1 [ -n "$_datasets" ] || return 1 printf '%s\n' "$_datasets" | awk -v node="$_node" '{ print node " " $0 }' diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index f3724179b..e61feb786 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -181,6 +181,11 @@ # Wait for operator to create the platform PackageSource timeout 120 sh -ec 'until kubectl get packagesource cozystack.cozystack-platform >/dev/null 2>&1; do sleep 2; done' + # The storage control plane this install deploys. Set once here and read by + # both the generator, which passes it to the platform, and the prep, which + # needs it to take the matching branch and will not guess. + export COZY_STORAGE_BACKEND="${COZY_STORAGE_BACKEND:-linstor}" + # Stage the generated manifest instead of piping it into kubectl: cozytest # runs under /bin/sh without pipefail, so a generator failure in a pipeline # could be hidden by kubectl successfully applying empty input. diff --git a/hack/e2e-platform-packages.sh b/hack/e2e-platform-packages.sh index 5fe18739d..d232bdac2 100755 --- a/hack/e2e-platform-packages.sh +++ b/hack/e2e-platform-packages.sh @@ -3,6 +3,7 @@ set -eu api_server_endpoint=${COZY_APISERVER_ENDPOINT:-https://192.168.123.10:6443} linstor_drbd_enabled=${COZY_LINSTOR_DRBD_ENABLED:-true} +storage_backend=${COZY_STORAGE_BACKEND:-linstor} # Container-mode Talos shares the runner kernel and cannot load DRBD. Keep the # normal package graph for QEMU, and let that lane replace two Packages instead: @@ -24,6 +25,32 @@ case "$linstor_drbd_enabled" in ;; esac +# The storage control plane the cluster installs, passed to the platform as +# storage.backend. Blockstor creates its zpool on the QEMU lane's private +# /dev/vdc, which the container lane does not have, so the pair is refused +# rather than installed into a prep that cannot finish. +case "$storage_backend" in + linstor) ;; + blockstor) + if [ "$linstor_drbd_enabled" = false ]; then + echo "COZY_STORAGE_BACKEND=blockstor is not supported with COZY_LINSTOR_DRBD_ENABLED=false" >&2 + exit 2 + fi + ;; + *) + echo "COZY_STORAGE_BACKEND must be linstor or blockstor, got: $storage_backend" >&2 + exit 2 + ;; +esac + +# Only when asked: the linstor default renders the same Package it always has. +storage_values= +if [ "$storage_backend" = blockstor ]; then + storage_values=' storage: + backend: blockstor +' +fi + # Packages left out of this install. The container lane always drops the two it # replaces below; COZY_DISABLED_PACKAGES adds the complement computed by # hack/select-install.sh for the selected suites. Both land under one @@ -68,7 +95,7 @@ spec: publishing: host: "example.org" apiServerEndpoint: "$api_server_endpoint" - # Must match Tenant/root spec.monitoring, which the install sets to +${storage_values} # Must match Tenant/root spec.monitoring, which the install sets to # false. Left true, cozystack-basics renders Services into # cozy-monitoring, which a narrow suite selection never creates. monitoring: diff --git a/hack/e2e-post-install-prep.sh b/hack/e2e-post-install-prep.sh index 359f5cf75..52f79f437 100755 --- a/hack/e2e-post-install-prep.sh +++ b/hack/e2e-post-install-prep.sh @@ -57,6 +57,26 @@ validate_linstor_storage_mode() { esac } +# Which storage control plane the install deployed. The caller passes what it +# installed rather than this script guessing: a probe run here would race the +# install it runs alongside, since the namespace it would look in does not +# exist yet when the script starts, and it would fail open to linstor on any +# error. An unknown value is refused for the same reason the platform chart +# refuses one: it would otherwise take whichever branch is the fallback. +validate_storage_backend() { + case "${COZY_STORAGE_BACKEND:-}" in + linstor | blockstor) return 0 ;; + "") + echo "[post-install-prep] COZY_STORAGE_BACKEND must be set to linstor or blockstor" >&2 + return 1 + ;; + *) + echo "[post-install-prep] COZY_STORAGE_BACKEND must be linstor or blockstor, got '${COZY_STORAGE_BACKEND}'" >&2 + return 1 + ;; + esac +} + # KUBECTL_BOUND prefixes the cluster calls in the helpers below with a wall-clock # bound. The main body sets it; it stays empty when unit tests source the # helpers, because `timeout` execs a binary and would bypass the kubectl shell @@ -132,6 +152,45 @@ patch_local_cdi_storage_profile() { -p '{"spec":{"claimPropertySets":[{"accessModes":["ReadWriteOnce"],"volumeMode":"Block"}]}}' } +# count_true : how many lines of are exactly True. +count_true() { + printf '%s\n' "$1" | grep -c '^True$' || true +} + +# count_lines : how many non-empty lines has. +count_lines() { + printf '%s\n' "$1" | grep -c . || true +} + +render_blockstor_node() { + cat <.. +render_blockstor_storage_pool() { + cat </dev/null || exit 0 @@ -141,6 +200,17 @@ if ! validate_linstor_storage_mode; then exit 2 fi +if ! validate_storage_backend; then + exit 2 +fi + +# The blockstor branch creates its zpool on the QEMU lane's private /dev/vdc. +# The container lane has no such disk, and runs no DRBD for blockstor to drive. +if [ "$COZY_STORAGE_BACKEND" = blockstor ] && [ "${COZY_LINSTOR_DRBD_ENABLED:-true}" = false ]; then + echo "[post-install-prep] COZY_STORAGE_BACKEND=blockstor is not supported with COZY_LINSTOR_DRBD_ENABLED=false" >&2 + exit 2 +fi + # Every call that does work carries a bound, not only the waits: the caller # blocks in `wait` on this script, so one call that never returns holds the # install open until the job's own ceiling instead of failing the step. A @@ -281,6 +351,11 @@ wait_for_object() { wait_for_linstor "linstor HelmRelease to be Ready" \ helmrelease/linstor -n cozy-linstor --for=condition=Ready + +echo "[post-install-prep] storage backend: $COZY_STORAGE_BACKEND" + +if [ "$COZY_STORAGE_BACKEND" = linstor ]; then + wait_for_linstor "linstor-controller Deployment to be Available" \ deployment/linstor-controller -n cozy-linstor --for=condition=available @@ -331,6 +406,162 @@ for pid in $pids; do wait "$pid" done +else # COZY_STORAGE_BACKEND = blockstor + +# piraeus-operator runs in external mode here: there is no in-cluster +# linstor-controller to exec into. The zpool is made inside the +# blockstor-satellite pod, which carries the /dev, /run/udev and /lib/modules +# mounts libzfs needs, and the pool is then declared as a StoragePool. +wait_for_linstor "blockstor-apiserver Deployment to be Available" \ + deployment/blockstor-apiserver -n cozy-linstor --for=condition=available +wait_for_linstor "blockstor-controller Deployment to be Available" \ + deployment/blockstor-controller -n cozy-linstor --for=condition=available +wait_for_linstor "LinstorCluster to be Available" \ + linstorcluster/linstorcluster --for=condition=Available + +# Available says the operator reached the API once. It does not say a +# satellite reconcile finished, and the two came apart in the field: the +# operator probes /v1/controller/version before every LinstorSatellite +# reconcile, so a probe it cannot complete leaves each satellite at +# Applied=False with its DaemonSet frozen at a spec the chart no longer +# renders, while every HelmRelease reports Ready. That surfaces only when a pod +# is recreated, on a node that then loses its satellite for good, so the +# per-satellite condition is asserted here. +# +# Both reads are checked: a gate comparing two counts passes on no data when +# both reads fail and each count comes out zero. A cluster with no node is +# not a pass either. +echo "[post-install-prep] waiting for every LinstorSatellite to report Applied" +applied_deadline=$(( $(date +%s) + 300 )) +while :; do + sat_rc=0 + sat_applied=$(timeout -k 5 30 kubectl get linstorsatellite --request-timeout=10s \ + -o jsonpath='{range .items[*]}{.status.conditions[?(@.type=="Applied")].status}{"\n"}{end}' \ + 2>/dev/null) || sat_rc=$? + node_rc=0 + node_names=$(timeout -k 5 30 kubectl get nodes --request-timeout=10s \ + -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null) || node_rc=$? + if [ "$sat_rc" -eq 0 ] && [ "$node_rc" -eq 0 ]; then + node_count=$(count_lines "$node_names") + applied_count=$(count_true "$sat_applied") + if [ "$node_count" -gt 0 ] && [ "$applied_count" -eq "$node_count" ]; then + break + fi + applied_state="$applied_count of $node_count LinstorSatellite objects Applied" + else + applied_state="LinstorSatellite read exited $sat_rc, Node read exited $node_rc" + fi + if [ "$(date +%s)" -ge "$applied_deadline" ]; then + echo "[post-install-prep] timed out after 300s waiting for every LinstorSatellite to report Applied: $applied_state" >&2 + timeout -k 5 30 kubectl get linstorsatellite --request-timeout=10s \ + -o jsonpath='{range .items[*]}{.metadata.name}{": "}{.status.conditions[?(@.type=="Applied")].message}{"\n"}{end}' \ + 2>&1 | tail -n 30 >&2 + exit 1 + fi + sleep 5 +done + +echo "[post-install-prep] waiting for a Ready blockstor-satellite pod on each of $node_count nodes" +sat_deadline=$(( $(date +%s) + 300 )) +while :; do + ready_rc=0 + sat_ready=$(timeout -k 5 30 kubectl get pods -n cozy-linstor -l app=blockstor-satellite \ + --request-timeout=10s \ + -o jsonpath='{range .items[*]}{.status.conditions[?(@.type=="Ready")].status}{"\n"}{end}' \ + 2>/dev/null) || ready_rc=$? + if [ "$ready_rc" -eq 0 ] && [ "$(count_true "$sat_ready")" -eq "$node_count" ]; then + break + fi + if [ "$(date +%s)" -ge "$sat_deadline" ]; then + echo "[post-install-prep] timed out after 300s waiting for $node_count Ready blockstor-satellite pods (read exited $ready_rc)" >&2 + timeout -k 5 30 kubectl get pods -n cozy-linstor -l app=blockstor-satellite -o wide \ + --request-timeout=10s 2>&1 | tail -n 30 >&2 + exit 1 + fi + sleep 5 +done + +# Node CRs carrying each node's InternalIP must exist before replicated volumes +# can resolve their DRBD peers: the label-sync controller only patches Node CRs +# that already exist. The reads are assignments, not `for` lists, so a failed +# one stops the script under set -e instead of registering nothing and going on. +echo "[post-install-prep] registering blockstor Node CRs for DRBD peer resolution" +node_rows=$($KUBECTL_BOUND kubectl get nodes --request-timeout=60s \ + -o jsonpath='{range .items[*]}{.metadata.name} {.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}') +if [ "$(count_lines "$node_rows")" -ne "$node_count" ]; then + echo "[post-install-prep] expected $node_count nodes with an address, read: $node_rows" >&2 + exit 1 +fi +while read -r node ip; do + [ -n "$node" ] || continue + if [ -z "$ip" ]; then + echo "[post-install-prep] node $node has no InternalIP" >&2 + exit 1 + fi + render_blockstor_node "$node" "$ip" | $KUBECTL_BOUND kubectl apply --request-timeout=60s -f - +done <&2 + exit 1 +fi +pids="" +while read -r pod node; do + [ -n "$pod" ] || continue + ( + # Partition first and hand zpool the partition: a whole-disk create needs + # a GPT rescan that fails inside the container's devtmpfs view. + $KUBECTL_BOUND kubectl exec -n cozy-linstor "$pod" -- sh -ec ' + if zpool list data >/dev/null 2>&1; then + echo "zpool data already exists on '"$node"'" + exit 0 + fi + wipefs -af /dev/vdc* 2>/dev/null || true + sgdisk --zap-all /dev/vdc 2>/dev/null || true + sgdisk --new=1:0:0 -t 1:bf01 /dev/vdc + partprobe /dev/vdc 2>/dev/null || true + sleep 1 + zpool create -f -o cachefile=none data /dev/vdc1 + echo "zpool data created on '"$node"'" + ' + render_blockstor_storage_pool "$node" | $KUBECTL_BOUND kubectl apply --request-timeout=60s -f - + ) & + pids="$pids $!" +done <&2 + timeout -k 5 30 kubectl get storagepools.blockstor.cozystack.io -o yaml --request-timeout=20s 2>&1 | tail -n 80 >&2 + exit 1 + fi + sleep 5 +done + +fi # COZY_STORAGE_BACKEND + echo "[post-install-prep] applying StorageClasses" render_linstor_storageclasses | $KUBECTL_BOUND kubectl apply --request-timeout=60s -f - diff --git a/hack/linstor-storage-mode_test.bats b/hack/linstor-storage-mode_test.bats index a4eeb7e77..7ade7160f 100644 --- a/hack/linstor-storage-mode_test.bats +++ b/hack/linstor-storage-mode_test.bats @@ -704,3 +704,187 @@ idle_pool_datasets() { return 1 fi } + +# The blockstor backend has no controller pod to exec into: the pool guard +# reads StoragePool objects and lists datasets through blockstor's own +# satellite. These pin that it does, and that the LINSTOR path is not touched. +blockstor_storage_pools_json() { + printf '%s' '{"items":[ + {"spec":{"nodeName":"srv1","providerKind":"ZFS_THIN","props":{"StorDriver/ZPoolThin":"data"}},"status":{"freeCapacity":104857600}}, + {"spec":{"nodeName":"srv1","providerKind":"DISKLESS","props":{}},"status":{}}, + {"spec":{"nodeName":"srv2","providerKind":"ZFS_THIN","props":{"StorDriver/ZPoolThin":"data"}},"status":{"freeCapacity":'"${1:-104857600}"'}}, + {"spec":{"nodeName":"srv3","providerKind":"ZFS_THIN","props":{"StorDriver/ZPoolThin":"data"}},"status":{"freeCapacity":104857600}} + ]}' +} + +@test "the blockstor pool floor is read from StoragePool objects, not a controller" { + # shellcheck source=/dev/null + . "$HACK_DIR/e2e-chainsaw/_lib/run-kubernetes.sh" + COZY_STORAGE_BACKEND=blockstor + calls="_out/tmp/blockstor-calls-$$" + mkdir -p _out/tmp + : >"$calls" + kubectl() { + printf '%s\n' "$*" >>"$calls" + case "$*" in + 'get storagepools.blockstor.cozystack.io '*-o\ json*) blockstor_storage_pools_json ;; + *) return 1 ;; + esac + } + fake_linstor_clock + + rc=0 + output=$(cozy_wait_linstor_pool_free 90 300 2>&1) || rc=$? + rm -f "$clock_file" + unset COZY_STORAGE_BACKEND + + if [ "$rc" -ne 0 ]; then + echo "the blockstor floor failed on pools that all hold 100 GiB: $output" >&2 + return 1 + fi + if grep -q 'linstor-controller' "$calls"; then + echo "the blockstor floor reached for the LINSTOR controller" >&2 + return 1 + fi + rm -f "$calls" +} + +@test "a blockstor pool below the floor fails the guard and names the node" { + # shellcheck source=/dev/null + . "$HACK_DIR/e2e-chainsaw/_lib/run-kubernetes.sh" + COZY_STORAGE_BACKEND=blockstor + kubectl() { + case "$*" in + 'get storagepools.blockstor.cozystack.io '*-o\ json*) blockstor_storage_pools_json 87127923 ;; + *) printf 'STUB-POOL-TABLE\n' ;; + esac + } + fake_linstor_clock + + rc=0 + output=$(cozy_wait_linstor_pool_free 90 300 2>&1) || rc=$? + rm -f "$clock_file" + unset COZY_STORAGE_BACKEND + + if [ "$rc" -eq 0 ]; then + echo "the blockstor floor passed with srv2 at 83 GiB" >&2 + return 1 + fi + if ! printf '%s\n' "$output" | grep -q '87127923 KiB on srv2'; then + echo "the blockstor floor failure does not name the short node: $output" >&2 + return 1 + fi +} + +@test "a pool read that fails is told apart from a full pool" { + # shellcheck source=/dev/null + . "$HACK_DIR/e2e-chainsaw/_lib/run-kubernetes.sh" + COZY_STORAGE_BACKEND=blockstor + kubectl() { + case "$*" in + 'get storagepools.blockstor.cozystack.io '*-o\ json*) + echo 'Error from server (Forbidden): storagepools is forbidden' >&2 + return 1 ;; + esac + } + fake_linstor_clock + + rc=0 + output=$(cozy_wait_linstor_pool_free 90 300 2>&1) || rc=$? + rm -f "$clock_file" + unset COZY_STORAGE_BACKEND + + if [ "$rc" -eq 0 ]; then + echo "the floor passed on a read that failed" >&2 + return 1 + fi + if printf '%s\n' "$output" | grep -q 'last read exited 0'; then + echo "a failed read was reported as a successful one: $output" >&2 + return 1 + fi +} + +@test "the blockstor dataset listing goes through blockstor's satellite" { + # shellcheck source=/dev/null + . "$HACK_DIR/e2e-chainsaw/_lib/run-kubernetes.sh" + COZY_STORAGE_BACKEND=blockstor + calls="_out/tmp/blockstor-calls-$$" + mkdir -p _out/tmp + : >"$calls" + kubectl() { + printf '%s\n' "$*" >>"$calls" + case "$*" in + 'get storagepools.blockstor.cozystack.io '*) blockstor_storage_pools_json ;; + *'-l app=blockstor-satellite'*) + printf 'srv1 blockstor-satellite-a\nsrv2 blockstor-satellite-b\nsrv3 blockstor-satellite-c\n' ;; + *'--container=satellite -- zfs list'*) printf 'data\n' ;; + *) return 1 ;; + esac + } + timeout() { + [ "${1:-}" = -k ] && [ "${3:-0}" -gt 0 ] || return 97 + shift 3 + "$@" + } + + rc=0 + rows=$(_cozy_linstor_pool_datasets) || rc=$? + unset COZY_STORAGE_BACKEND + + if [ "$rc" -ne 0 ] || [ "$rows" != "$(printf 'srv1 data\nsrv2 data\nsrv3 data')" ]; then + echo "the blockstor dataset listing returned rc=$rc rows=$rows" >&2 + cat "$calls" >&2 + return 1 + fi + if grep -q 'linstor-controller\|linstor-satellite' "$calls"; then + echo "the blockstor listing reached for LINSTOR's own pods" >&2 + return 1 + fi + rm -f "$calls" +} + +@test "an unknown storage backend stops the pool guard before it reads anything" { + # shellcheck source=/dev/null + . "$HACK_DIR/e2e-chainsaw/_lib/run-kubernetes.sh" + COZY_STORAGE_BACKEND=blokstor + kubectl() { printf 'UNEXPECTED_READ\n'; } + fake_linstor_clock + + rc=0 + output=$(cozy_wait_linstor_pool_free 90 300 2>&1) || rc=$? + rm -f "$clock_file" + unset COZY_STORAGE_BACKEND + + if [ "$rc" -ne 2 ] || printf '%s\n' "$output" | grep -q UNEXPECTED_READ; then + echo "an unknown backend was read as some backend: rc=$rc $output" >&2 + return 1 + fi +} + +@test "a pool read that exits 2 keeps the guard polling instead of giving up" { + # shellcheck source=/dev/null + . "$HACK_DIR/e2e-chainsaw/_lib/run-kubernetes.sh" + reads="_out/tmp/linstor-reads-$$" + mkdir -p _out/tmp + : >"$reads" + # jq inside the controller pod exits 2 on the error banner a restarting + # controller prints, and kubectl exec passes that status through. + kubectl() { + printf 'read\n' >>"$reads" + case "$*" in + *'exec deploy/linstor-controller'*) return 2 ;; + esac + } + fake_linstor_clock + + rc=0 + output=$(cozy_wait_linstor_pool_free 90 300 2>&1) || rc=$? + rm -f "$clock_file" + count=$(grep -c read "$reads") + rm -f "$reads" + + if [ "$rc" -ne 1 ] || [ "$count" -lt 2 ]; then + echo "a read exiting 2 ended the guard: rc=$rc after $count read(s): $output" >&2 + return 1 + fi +} diff --git a/hack/platform-packages_test.bats b/hack/platform-packages_test.bats index 693f4d056..986b5f15f 100644 --- a/hack/platform-packages_test.bats +++ b/hack/platform-packages_test.bats @@ -201,3 +201,44 @@ load test_helper fi done } + +@test "the linstor default leaves the platform Package without a storage block" { + manifest=$(hack/e2e-platform-packages.sh) + if printf '%s\n' "$manifest" | grep -q '^ storage:'; then + echo "the default install names a storage backend it never used to" >&2 + return 1 + fi +} + +@test "blockstor reaches the platform as storage.backend" { + manifest=$(COZY_STORAGE_BACKEND=blockstor hack/e2e-platform-packages.sh) + backend=$(printf '%s\n' "$manifest" | yq 'select(.metadata.name == "cozystack.cozystack-platform") | .spec.components.platform.values.storage.backend') + if [ "$backend" != blockstor ]; then + echo "storage.backend is '$backend', want blockstor" >&2 + return 1 + fi + # The block sits in the values, not inside bundles. + bundles=$(printf '%s\n' "$manifest" | yq 'select(.metadata.name == "cozystack.cozystack-platform") | .spec.components.platform.values.bundles | keys | join(",")') + if [ "$bundles" != enabledPackages ]; then + echo "bundles carries '$bundles'" >&2 + return 1 + fi +} + +@test "an unknown storage backend fails before emitting YAML" { + if manifest=$(COZY_STORAGE_BACKEND=blokstor hack/e2e-platform-packages.sh); then + echo "an unknown backend unexpectedly succeeded" >&2 + return 1 + fi + if [ -n "$manifest" ]; then + echo "an unknown backend emitted a partial manifest" >&2 + return 1 + fi +} + +@test "blockstor on the container lane is refused" { + if manifest=$(COZY_STORAGE_BACKEND=blockstor COZY_LINSTOR_DRBD_ENABLED=false hack/e2e-platform-packages.sh); then + echo "blockstor without a block device unexpectedly succeeded" >&2 + return 1 + fi +} diff --git a/hack/post-install-prep.bats b/hack/post-install-prep.bats index cc34a4a6b..d0d6e3065 100644 --- a/hack/post-install-prep.bats +++ b/hack/post-install-prep.bats @@ -129,6 +129,39 @@ case "$*" in 'get hr -A '*) echo "cozy-linstor linstor False dependency 'cozy-system/piraeus-operator' is not ready" echo "STUB-HR cozy-kubeovn kubeovn False install retries exhausted" ;; + 'get linstorsatellite '*) + if [ -n "${STUB_SAT_READ_FAIL:-}" ]; then + echo 'Error from server (Forbidden): linstorsatellites is forbidden' >&2 + exit 1 + fi + printf '%s\n' "${STUB_SAT_APPLIED:-True True True}" | tr ' ' '\n' ;; + 'get nodes '*InternalIP*) + if [ -n "${STUB_NODE_ROWS_FAIL:-}" ]; then + echo 'Error from server (Forbidden): nodes is forbidden' >&2 + exit 1 + fi + for n in ${STUB_NODES:-srv1 srv2 srv3}; do echo "$n 192.0.2.$((${#n} + 10))"; done ;; + 'get nodes '*) + if [ -n "${STUB_NODES_READ_FAIL:-}" ]; then + echo 'Error from server (Forbidden): nodes is forbidden' >&2 + exit 1 + fi + for n in ${STUB_NODES:-srv1 srv2 srv3}; do echo "$n"; done ;; + 'get storagepools.blockstor.cozystack.io '*freeCapacity*) + # STUB_POOLS_UNREPORTED names nodes whose satellite has not reported its + # pool yet: the object exists, its free capacity does not. + for n in ${STUB_NODES:-srv1 srv2 srv3}; do + case " ${STUB_POOLS_UNREPORTED:-} " in + *" $n "*) echo "$n " ;; + *) echo "$n 104857600" ;; + esac + done ;; + 'get pods -n cozy-linstor -l app=blockstor-satellite '*spec.nodeName*) + for n in ${STUB_NODES:-srv1 srv2 srv3}; do echo "blockstor-satellite-$n $n"; done ;; + 'get pods -n cozy-linstor -l app=blockstor-satellite '*Ready*) + for n in ${STUB_NODES:-srv1 srv2 srv3}; do echo True; done ;; + 'apply '*) + cat >> "${STUB_APPLIED:-/dev/null}" ;; 'get pods '*) if [ -n "${STUB_PODS_FAIL:-}" ]; then echo "Error from server (Forbidden): pods is forbidden" >&2 @@ -187,6 +220,8 @@ run_prep() { STUB_CLOCK="$d/clock" STUB_CALLS="$d/calls" \ STUB_HR_READY_AT=$2 STUB_DEPLOY_READY_AT=$3 \ STUB_EVENTS_FAIL="${4:-}" STUB_PODS_FAIL="${5:-}" \ + STUB_APPLIED="$d/applied" \ + COZY_STORAGE_BACKEND="${STUB_BACKEND-linstor}" \ PATH="$d/bin:$PATH" \ "$SCRIPT" > "$d/out" 2> "$d/err" && echo 0 > "$d/rc" || echo $? > "$d/rc" } @@ -516,3 +551,162 @@ run_prep() { fi rm -rf "$tmp" } + +# run_prep_blockstor +# The blockstor branch. Every wait before the satellite gate is answered as +# ready, so what a test sees is the gate and what follows it. +run_prep_blockstor() { + STUB_BACKEND=blockstor run_prep "$1" 0 0 +} + +@test "the prep refuses to run without being told the storage backend" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + STUB_BACKEND="" run_prep "$tmp" 0 0 + + # A guess here races the install it runs alongside and fails open to linstor. + [ "$(cat "$tmp/rc")" -eq 2 ] + grep -q 'COZY_STORAGE_BACKEND must be set' "$tmp/err" + if grep -q '^wait ' "$tmp/calls"; then + echo "the prep waited on the cluster before it knew the backend" >&2 + return 1 + fi + rm -rf "$tmp" +} + +@test "the prep refuses a storage backend it does not know" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + STUB_BACKEND=blokstor run_prep "$tmp" 0 0 + + [ "$(cat "$tmp/rc")" -eq 2 ] + grep -q "got 'blokstor'" "$tmp/err" + rm -rf "$tmp" +} + +@test "the blockstor prep registers a Node CR and a StoragePool for every node" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + run_prep_blockstor "$tmp" + + cat "$tmp/err" >&2 + [ "$(cat "$tmp/rc")" -eq 0 ] + grep -q '\[post-install-prep\] done' "$tmp/out" + for n in srv1 srv2 srv3; do + # The durable outcome, not whether a wait returned: the objects applied. + grep -A8 '^kind: Node$' "$tmp/applied" | grep -q "^ name: $n$" + grep -A8 '^kind: StoragePool$' "$tmp/applied" | grep -q "^ name: data.$n$" + grep -A8 '^kind: StoragePool$' "$tmp/applied" | grep -q "^ nodeName: $n$" + grep -q "^exec -n cozy-linstor blockstor-satellite-$n -- sh -ec" "$tmp/calls" + done + if grep '^UNBOUNDED ' "$tmp/calls" >&2; then + echo "unbounded kubectl calls on the blockstor path" >&2 + return 1 + fi + # Never the LINSTOR path's own controller. + if grep -q 'linstor-controller' "$tmp/calls"; then + echo "the blockstor prep reached for the LINSTOR controller" >&2 + return 1 + fi + rm -rf "$tmp" +} + +@test "the blockstor prep fails when a satellite never reports Applied" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + export STUB_SAT_APPLIED="True False True" + run_prep_blockstor "$tmp" + unset STUB_SAT_APPLIED + + [ "$(cat "$tmp/rc")" -ne 0 ] + grep -q '2 of 3 LinstorSatellite objects Applied' "$tmp/err" + if grep -q '^kind: StoragePool$' "$tmp/applied" 2>/dev/null; then + echo "pools were created past a satellite that never applied" >&2 + return 1 + fi + rm -rf "$tmp" +} + +@test "the satellite gate does not pass when both of its reads fail" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + # Two failed reads each count zero, and zero equals zero. + export STUB_SAT_READ_FAIL=1 STUB_NODES_READ_FAIL=1 + run_prep_blockstor "$tmp" + unset STUB_SAT_READ_FAIL STUB_NODES_READ_FAIL + + [ "$(cat "$tmp/rc")" -ne 0 ] + grep -q 'LinstorSatellite read exited 1, Node read exited 1' "$tmp/err" + rm -rf "$tmp" +} + +@test "the satellite gate does not pass on a cluster with no node" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + export STUB_NODES=" " STUB_SAT_APPLIED=" " + run_prep_blockstor "$tmp" + unset STUB_NODES STUB_SAT_APPLIED + + [ "$(cat "$tmp/rc")" -ne 0 ] + grep -q '0 of 0 LinstorSatellite objects Applied' "$tmp/err" + rm -rf "$tmp" +} + +@test "a failed node read stops the blockstor prep before it registers anything" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + # A read used as a for-list is not covered by set -e: it registers nothing + # and the script reports done. + export STUB_NODE_ROWS_FAIL=1 + run_prep_blockstor "$tmp" + unset STUB_NODE_ROWS_FAIL + + [ "$(cat "$tmp/rc")" -ne 0 ] + if grep -q '\[post-install-prep\] done' "$tmp/out"; then + echo "the prep reported done after a failed node read" >&2 + return 1 + fi + if grep -q '^kind: \(Node\|StoragePool\)$' "$tmp/applied" 2>/dev/null; then + echo "objects were registered after the node read failed" >&2 + return 1 + fi + rm -rf "$tmp" +} + +@test "the blockstor prep waits for every satellite to report its pool" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + run_prep_blockstor "$tmp" + + [ "$(cat "$tmp/rc")" -eq 0 ] + grep -q "waiting for every satellite to report its 'data' pool" "$tmp/out" + grep -q '^get storagepools.blockstor.cozystack.io .*freeCapacity' "$tmp/calls" + rm -rf "$tmp" +} + +@test "the blockstor prep fails when a satellite never reports its pool" { + tmp=$(mktemp -d) + prep_sandbox "$tmp" + + # A declared pool no satellite has opened is one placement cannot use, so + # the first three-replica volume would fail on it. + export STUB_POOLS_UNREPORTED=srv2 + run_prep_blockstor "$tmp" + unset STUB_POOLS_UNREPORTED + + [ "$(cat "$tmp/rc")" -ne 0 ] + grep -q "timed out after 300s waiting for 3 reported 'data' pools" "$tmp/err" + if grep -q 'applying StorageClasses' "$tmp/out"; then + echo "StorageClasses were applied over a pool nobody reported" >&2 + return 1 + fi + rm -rf "$tmp" +} diff --git a/packages/core/testing/Makefile b/packages/core/testing/Makefile index 861af1e44..c45d1c530 100644 --- a/packages/core/testing/Makefile +++ b/packages/core/testing/Makefile @@ -159,7 +159,7 @@ delete-cluster-container: # COZY_DISABLED_PACKAGES is the space-separated output of # hack/select-install.sh --disabled; empty installs the whole platform. install-cozystack: - docker exec -e COZY_APISERVER_ENDPOINT="${COZY_APISERVER_ENDPOINT}" -e COZY_LINSTOR_DRBD_ENABLED="${COZY_LINSTOR_DRBD_ENABLED}" -e COZY_E2E_STORAGE_CLASS="${COZY_E2E_STORAGE_CLASS}" -e COZY_DISABLED_PACKAGES="${COZY_DISABLED_PACKAGES}" "${SANDBOX_NAME}" sh -c 'cd /workspace && hack/cozytest.sh hack/e2e-install-cozystack.bats' + docker exec -e COZY_APISERVER_ENDPOINT="${COZY_APISERVER_ENDPOINT}" -e COZY_LINSTOR_DRBD_ENABLED="${COZY_LINSTOR_DRBD_ENABLED}" -e COZY_STORAGE_BACKEND="${COZY_STORAGE_BACKEND}" -e COZY_E2E_STORAGE_CLASS="${COZY_E2E_STORAGE_CLASS}" -e COZY_DISABLED_PACKAGES="${COZY_DISABLED_PACKAGES}" "${SANDBOX_NAME}" sh -c 'cd /workspace && hack/cozytest.sh hack/e2e-install-cozystack.bats' test-openapi: docker exec "${SANDBOX_NAME}" sh -c 'cd /workspace && hack/cozytest.sh hack/e2e-test-openapi.bats' @@ -175,8 +175,10 @@ test-openapi: # reports into that same chainsaw-report.xml. # COZY_E2E_STORAGE_CLASS is passed both to script operations and as a Chainsaw # value for templated resource files; empty keeps the QEMU default, replicated. +# COZY_STORAGE_BACKEND reaches the install and the suite alike, so the pool +# guards read the backend the cluster was installed with; empty is linstor. test-chainsaw: - docker exec -e COZY_E2E_STORAGE_CLASS="${COZY_E2E_STORAGE_CLASS}" "${SANDBOX_NAME}" sh -c 'cd /workspace/hack/e2e-chainsaw && ../e2e-chainsaw-run.sh --set-string storageClass="$${COZY_E2E_STORAGE_CLASS:-replicated}" ${CHAINSAW_SUITES}' + docker exec -e COZY_E2E_STORAGE_CLASS="${COZY_E2E_STORAGE_CLASS}" -e COZY_STORAGE_BACKEND="${COZY_STORAGE_BACKEND}" "${SANDBOX_NAME}" sh -c 'cd /workspace/hack/e2e-chainsaw && ../e2e-chainsaw-run.sh --set-string storageClass="$${COZY_E2E_STORAGE_CLASS:-replicated}" ${CHAINSAW_SUITES}' collect-report: ## Collect the test report from the sandbox. docker exec "${SANDBOX_NAME}" sh -c 'cd /workspace && hack/cozyreport.sh cozyreport' From d617d52bfdc03594fd5b32fc89648edd7b839a19 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sat, 24 Oct 2026 12:33:11 +0200 Subject: [PATCH 03/18] refactor(linstor): follow blockstor's API group to blockstor.org blockstor moves its API group from blockstor.cozystack.io to blockstor.org before anything is deployed on it. The chart's CRD copies, the RBAC rules of the apiserver, controller and satellite, the chart tests and the e2e helpers that read the storage pools now use the new group. This needs the blockstor release that carries the rename, which the backend is pinned to before this PR merges. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- hack/e2e-chainsaw/_lib/run-kubernetes.sh | 6 +++--- hack/e2e-post-install-prep.sh | 8 ++++---- hack/linstor-storage-mode_test.bats | 8 ++++---- hack/post-install-prep.bats | 4 ++-- packages/system/linstor/Makefile | 6 +++--- ...l => blockstor.org_controllerconfigs.yaml} | 4 ++-- ...io_nodes.yaml => blockstor.org_nodes.yaml} | 4 ++-- ...aml => blockstor.org_physicaldevices.yaml} | 4 ++-- ...=> blockstor.org_resourcedefinitions.yaml} | 4 ++-- ...yaml => blockstor.org_resourcegroups.yaml} | 4 ++-- ...rces.yaml => blockstor.org_resources.yaml} | 4 ++-- ...hots.yaml => blockstor.org_snapshots.yaml} | 4 ++-- ...s.yaml => blockstor.org_storagepools.yaml} | 4 ++-- .../templates/blockstor-apiserver.yaml | 4 ++-- .../templates/blockstor-controller.yaml | 12 +++++------ .../templates/blockstor-satellite.yaml | 8 ++++---- .../linstor/tests/blockstor_rbac_test.yaml | 2 +- .../tests/blockstor_workloads_test.yaml | 20 +++++++++---------- 18 files changed, 55 insertions(+), 55 deletions(-) rename packages/system/linstor/definitions/{blockstor.cozystack.io_controllerconfigs.yaml => blockstor.org_controllerconfigs.yaml} (99%) rename packages/system/linstor/definitions/{blockstor.cozystack.io_nodes.yaml => blockstor.org_nodes.yaml} (99%) rename packages/system/linstor/definitions/{blockstor.cozystack.io_physicaldevices.yaml => blockstor.org_physicaldevices.yaml} (99%) rename packages/system/linstor/definitions/{blockstor.cozystack.io_resourcedefinitions.yaml => blockstor.org_resourcedefinitions.yaml} (99%) rename packages/system/linstor/definitions/{blockstor.cozystack.io_resourcegroups.yaml => blockstor.org_resourcegroups.yaml} (99%) rename packages/system/linstor/definitions/{blockstor.cozystack.io_resources.yaml => blockstor.org_resources.yaml} (99%) rename packages/system/linstor/definitions/{blockstor.cozystack.io_snapshots.yaml => blockstor.org_snapshots.yaml} (99%) rename packages/system/linstor/definitions/{blockstor.cozystack.io_storagepools.yaml => blockstor.org_storagepools.yaml} (99%) diff --git a/hack/e2e-chainsaw/_lib/run-kubernetes.sh b/hack/e2e-chainsaw/_lib/run-kubernetes.sh index 32ffc61f1..956632ada 100644 --- a/hack/e2e-chainsaw/_lib/run-kubernetes.sh +++ b/hack/e2e-chainsaw/_lib/run-kubernetes.sh @@ -518,7 +518,7 @@ _cozy_pool_free_rows() { if [ "$_backend" = blockstor ]; then # Read first and filter second: piped, the read's status is jq's, and jq # on empty input succeeds. - _pools_json=$(kubectl get storagepools.blockstor.cozystack.io --request-timeout=20s -o json) || return 1 + _pools_json=$(kubectl get storagepools.blockstor.org --request-timeout=20s -o json) || return 1 printf '%s\n' "$_pools_json" | jq -r '.items[] | select((.spec.providerKind | test("^ZFS")) and .status.freeCapacity != null) | "\(.status.freeCapacity):\(.spec.nodeName)"' return @@ -533,7 +533,7 @@ _cozy_pool_free_rows() { _cozy_pool_diagnostics() { if [ "$(_cozy_storage_backend 2>/dev/null)" = blockstor ]; then - kubectl get storagepools.blockstor.cozystack.io -o wide --request-timeout=20s 2>&1 + kubectl get storagepools.blockstor.org -o wide --request-timeout=20s 2>&1 return fi kubectl -n cozy-linstor exec deploy/linstor-controller -- linstor --no-color sp l 2>&1 @@ -633,7 +633,7 @@ _cozy_linstor_pool_baseline_file() { _cozy_linstor_pool_datasets() { _backend=$(_cozy_storage_backend) || return 1 if [ "$_backend" = blockstor ]; then - _pools_json=$(timeout -k 5 30 kubectl get storagepools.blockstor.cozystack.io --request-timeout=20s -o json 2>/dev/null) || return 1 + _pools_json=$(timeout -k 5 30 kubectl get storagepools.blockstor.org --request-timeout=20s -o json 2>/dev/null) || return 1 _pools=$(printf '%s\n' "$_pools_json" | jq -r '.items[] | select(.spec.providerKind | test("^ZFS")) | "\(.spec.nodeName) \(.spec.props["StorDriver/StorPoolName"] // .spec.props["StorDriver/ZPoolThin"] // .spec.props["StorDriver/ZPool"] // "")"') || return 1 _satellite_selector=app=blockstor-satellite diff --git a/hack/e2e-post-install-prep.sh b/hack/e2e-post-install-prep.sh index 52f79f437..fa202a405 100755 --- a/hack/e2e-post-install-prep.sh +++ b/hack/e2e-post-install-prep.sh @@ -164,7 +164,7 @@ count_lines() { render_blockstor_node() { cat <.. render_blockstor_storage_pool() { cat <&2 - timeout -k 5 30 kubectl get storagepools.blockstor.cozystack.io -o yaml --request-timeout=20s 2>&1 | tail -n 80 >&2 + timeout -k 5 30 kubectl get storagepools.blockstor.org -o yaml --request-timeout=20s 2>&1 | tail -n 80 >&2 exit 1 fi sleep 5 diff --git a/hack/linstor-storage-mode_test.bats b/hack/linstor-storage-mode_test.bats index 7ade7160f..9f65ecaaf 100644 --- a/hack/linstor-storage-mode_test.bats +++ b/hack/linstor-storage-mode_test.bats @@ -727,7 +727,7 @@ blockstor_storage_pools_json() { kubectl() { printf '%s\n' "$*" >>"$calls" case "$*" in - 'get storagepools.blockstor.cozystack.io '*-o\ json*) blockstor_storage_pools_json ;; + 'get storagepools.blockstor.org '*-o\ json*) blockstor_storage_pools_json ;; *) return 1 ;; esac } @@ -755,7 +755,7 @@ blockstor_storage_pools_json() { COZY_STORAGE_BACKEND=blockstor kubectl() { case "$*" in - 'get storagepools.blockstor.cozystack.io '*-o\ json*) blockstor_storage_pools_json 87127923 ;; + 'get storagepools.blockstor.org '*-o\ json*) blockstor_storage_pools_json 87127923 ;; *) printf 'STUB-POOL-TABLE\n' ;; esac } @@ -782,7 +782,7 @@ blockstor_storage_pools_json() { COZY_STORAGE_BACKEND=blockstor kubectl() { case "$*" in - 'get storagepools.blockstor.cozystack.io '*-o\ json*) + 'get storagepools.blockstor.org '*-o\ json*) echo 'Error from server (Forbidden): storagepools is forbidden' >&2 return 1 ;; esac @@ -814,7 +814,7 @@ blockstor_storage_pools_json() { kubectl() { printf '%s\n' "$*" >>"$calls" case "$*" in - 'get storagepools.blockstor.cozystack.io '*) blockstor_storage_pools_json ;; + 'get storagepools.blockstor.org '*) blockstor_storage_pools_json ;; *'-l app=blockstor-satellite'*) printf 'srv1 blockstor-satellite-a\nsrv2 blockstor-satellite-b\nsrv3 blockstor-satellite-c\n' ;; *'--container=satellite -- zfs list'*) printf 'data\n' ;; diff --git a/hack/post-install-prep.bats b/hack/post-install-prep.bats index d0d6e3065..939297fb8 100644 --- a/hack/post-install-prep.bats +++ b/hack/post-install-prep.bats @@ -147,7 +147,7 @@ case "$*" in exit 1 fi for n in ${STUB_NODES:-srv1 srv2 srv3}; do echo "$n"; done ;; - 'get storagepools.blockstor.cozystack.io '*freeCapacity*) + 'get storagepools.blockstor.org '*freeCapacity*) # STUB_POOLS_UNREPORTED names nodes whose satellite has not reported its # pool yet: the object exists, its free capacity does not. for n in ${STUB_NODES:-srv1 srv2 srv3}; do @@ -688,7 +688,7 @@ run_prep_blockstor() { [ "$(cat "$tmp/rc")" -eq 0 ] grep -q "waiting for every satellite to report its 'data' pool" "$tmp/out" - grep -q '^get storagepools.blockstor.cozystack.io .*freeCapacity' "$tmp/calls" + grep -q '^get storagepools.blockstor.org .*freeCapacity' "$tmp/calls" rm -rf "$tmp" } diff --git a/packages/system/linstor/Makefile b/packages/system/linstor/Makefile index bbc9f6da1..d32e6089d 100644 --- a/packages/system/linstor/Makefile +++ b/packages/system/linstor/Makefile @@ -20,9 +20,9 @@ update-blockstor-crds: { curl --fail --silent --show-error --location -o "$$tmpdir/source.tar.gz" \ "https://github.com/cozystack/blockstor/archive/refs/tags/v$(BLOCKSTOR_VERSION).tar.gz" && \ mkdir "$$tmpdir/src" && tar -xzf "$$tmpdir/source.tar.gz" --strip-components=1 -C "$$tmpdir/src" && \ - ls "$$tmpdir"/src/config/crd/bases/blockstor.cozystack.io_*.yaml >/dev/null || { rm -rf "$$tmpdir"; exit 1; }; } && \ - rm -f definitions/blockstor.cozystack.io_*.yaml && \ - cp "$$tmpdir"/src/config/crd/bases/blockstor.cozystack.io_*.yaml definitions/ && \ + ls "$$tmpdir"/src/config/crd/bases/blockstor.org_*.yaml >/dev/null || { rm -rf "$$tmpdir"; exit 1; }; } && \ + rm -f definitions/blockstor.org_*.yaml && \ + cp "$$tmpdir"/src/config/crd/bases/blockstor.org_*.yaml definitions/ && \ rm -rf "$$tmpdir" test: diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_controllerconfigs.yaml b/packages/system/linstor/definitions/blockstor.org_controllerconfigs.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_controllerconfigs.yaml rename to packages/system/linstor/definitions/blockstor.org_controllerconfigs.yaml index 93fdf34c5..f296c08a6 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_controllerconfigs.yaml +++ b/packages/system/linstor/definitions/blockstor.org_controllerconfigs.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: controllerconfigs.blockstor.cozystack.io + name: controllerconfigs.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: ControllerConfig listKind: ControllerConfigList diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_nodes.yaml b/packages/system/linstor/definitions/blockstor.org_nodes.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_nodes.yaml rename to packages/system/linstor/definitions/blockstor.org_nodes.yaml index c94128ed1..9f8730129 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_nodes.yaml +++ b/packages/system/linstor/definitions/blockstor.org_nodes.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: nodes.blockstor.cozystack.io + name: nodes.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: Node listKind: NodeList diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_physicaldevices.yaml b/packages/system/linstor/definitions/blockstor.org_physicaldevices.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_physicaldevices.yaml rename to packages/system/linstor/definitions/blockstor.org_physicaldevices.yaml index 3dfcef46e..5d4faf6a0 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_physicaldevices.yaml +++ b/packages/system/linstor/definitions/blockstor.org_physicaldevices.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: physicaldevices.blockstor.cozystack.io + name: physicaldevices.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: PhysicalDevice listKind: PhysicalDeviceList diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_resourcedefinitions.yaml b/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_resourcedefinitions.yaml rename to packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml index 08e2b98d8..641df9589 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_resourcedefinitions.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: resourcedefinitions.blockstor.cozystack.io + name: resourcedefinitions.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: ResourceDefinition listKind: ResourceDefinitionList diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_resourcegroups.yaml b/packages/system/linstor/definitions/blockstor.org_resourcegroups.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_resourcegroups.yaml rename to packages/system/linstor/definitions/blockstor.org_resourcegroups.yaml index 8515b5aef..141079b35 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_resourcegroups.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resourcegroups.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: resourcegroups.blockstor.cozystack.io + name: resourcegroups.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: ResourceGroup listKind: ResourceGroupList diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_resources.yaml b/packages/system/linstor/definitions/blockstor.org_resources.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_resources.yaml rename to packages/system/linstor/definitions/blockstor.org_resources.yaml index a360db9f3..96e0e94db 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_resources.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resources.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: resources.blockstor.cozystack.io + name: resources.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: Resource listKind: ResourceList diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_snapshots.yaml b/packages/system/linstor/definitions/blockstor.org_snapshots.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_snapshots.yaml rename to packages/system/linstor/definitions/blockstor.org_snapshots.yaml index 7b669964c..f041385c7 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_snapshots.yaml +++ b/packages/system/linstor/definitions/blockstor.org_snapshots.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: snapshots.blockstor.cozystack.io + name: snapshots.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: Snapshot listKind: SnapshotList diff --git a/packages/system/linstor/definitions/blockstor.cozystack.io_storagepools.yaml b/packages/system/linstor/definitions/blockstor.org_storagepools.yaml similarity index 99% rename from packages/system/linstor/definitions/blockstor.cozystack.io_storagepools.yaml rename to packages/system/linstor/definitions/blockstor.org_storagepools.yaml index 2fa9911ed..8afe147c6 100644 --- a/packages/system/linstor/definitions/blockstor.cozystack.io_storagepools.yaml +++ b/packages/system/linstor/definitions/blockstor.org_storagepools.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.20.1 - name: storagepools.blockstor.cozystack.io + name: storagepools.blockstor.org spec: - group: blockstor.cozystack.io + group: blockstor.org names: kind: StoragePool listKind: StoragePoolList diff --git a/packages/system/linstor/templates/blockstor-apiserver.yaml b/packages/system/linstor/templates/blockstor-apiserver.yaml index 4f714832c..781f0cd5b 100644 --- a/packages/system/linstor/templates/blockstor-apiserver.yaml +++ b/packages/system/linstor/templates/blockstor-apiserver.yaml @@ -11,7 +11,7 @@ metadata: namespace: {{ .Release.Namespace }} --- {{- /* - CRUD on the blockstor.cozystack.io CRDs, named rather than wildcarded so a kind + CRUD on the blockstor.org CRDs, named rather than wildcarded so a kind added to the group later is not granted by omission. No finalizers, events or leases: the REST handlers do not write those. */}} apiVersion: rbac.authorization.k8s.io/v1 @@ -19,7 +19,7 @@ kind: ClusterRole metadata: name: blockstor-apiserver rules: - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: - controllerconfigs - controllerconfigs/status diff --git a/packages/system/linstor/templates/blockstor-controller.yaml b/packages/system/linstor/templates/blockstor-controller.yaml index fd50b32d0..faca527ef 100644 --- a/packages/system/linstor/templates/blockstor-controller.yaml +++ b/packages/system/linstor/templates/blockstor-controller.yaml @@ -1,7 +1,7 @@ {{- if eq .Values.backend "blockstor" }} --- {{- /* - blockstor controller — runs the reconcilers for the blockstor.cozystack.io + blockstor controller — runs the reconcilers for the blockstor.org CRDs (ResourceDefinitions / Resources / Snapshots / StoragePools / Nodes). The REST API is split out into the separate apiserver Deployment; the controller runs with --enable-rest-api=false. */}} @@ -12,7 +12,7 @@ metadata: namespace: {{ .Release.Namespace }} --- {{- /* - Cluster-wide read on Kubernetes Nodes and the blockstor.cozystack.io kinds + Cluster-wide read on Kubernetes Nodes and the blockstor.org kinds the reconcilers manage, as blockstor's own config/rbac/role.yaml grants them, kind by kind so a kind added to the group later is not granted by omission. No leases: the controller runs without leader election. */}} @@ -30,13 +30,13 @@ rules: - apiGroups: [""] resources: [nodes] verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [controllerconfigs] verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [nodes, resourcedefinitions, resourcegroups, resources, snapshots, storagepools] verbs: [get, list, watch, create, update, patch, delete] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: - nodes/finalizers - resourcedefinitions/finalizers @@ -45,7 +45,7 @@ rules: - snapshots/finalizers - storagepools/finalizers verbs: [update] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: - nodes/status - resourcedefinitions/status diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml index 297c0d984..28aae4ac1 100644 --- a/packages/system/linstor/templates/blockstor-satellite.yaml +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -64,7 +64,7 @@ rules: - apiGroups: [""] resources: [nodes] verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: - controllerconfigs - nodes @@ -75,13 +75,13 @@ rules: - snapshots - storagepools verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [physicaldevices] verbs: [create, update, patch, delete] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [nodes, resources, snapshots, storagepools] verbs: [update, patch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: - nodes/status - physicaldevices/status diff --git a/packages/system/linstor/tests/blockstor_rbac_test.yaml b/packages/system/linstor/tests/blockstor_rbac_test.yaml index 8c21efa87..52e2fbc0d 100644 --- a/packages/system/linstor/tests/blockstor_rbac_test.yaml +++ b/packages/system/linstor/tests/blockstor_rbac_test.yaml @@ -66,6 +66,6 @@ tests: - notContains: path: rules content: - apiGroups: [blockstor.cozystack.io] + apiGroups: [blockstor.org] resources: ["*"] verbs: [get, list, watch, create, update, patch, delete] diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index 2a97883e2..aa63d1c4d 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -45,13 +45,13 @@ tests: - contains: path: rules content: - apiGroups: [blockstor.cozystack.io] + apiGroups: [blockstor.org] resources: [physicaldevices] verbs: [create, update, patch, delete] - contains: path: rules content: - apiGroups: [blockstor.cozystack.io] + apiGroups: [blockstor.org] resources: [nodes, resources, snapshots, storagepools] verbs: [update, patch] - lengthEqual: @@ -155,17 +155,17 @@ tests: - apiGroups: [''] resources: [nodes] verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [controllerconfigs] verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [nodes, resourcedefinitions, resourcegroups, resources, snapshots, storagepools] verbs: [get, list, watch, create, update, patch, delete] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [nodes/finalizers, resourcedefinitions/finalizers, resourcegroups/finalizers, resources/finalizers, snapshots/finalizers, storagepools/finalizers] verbs: [update] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [nodes/status, resourcedefinitions/status, resourcegroups/status, resources/status, snapshots/status, storagepools/status] verbs: [get, update, patch] @@ -185,17 +185,17 @@ tests: - apiGroups: [''] resources: [nodes] verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [controllerconfigs, nodes, physicaldevices, resourcedefinitions, resourcegroups, resources, snapshots, storagepools] verbs: [get, list, watch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [physicaldevices] verbs: [create, update, patch, delete] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [nodes, resources, snapshots, storagepools] verbs: [update, patch] - - apiGroups: [blockstor.cozystack.io] + - apiGroups: [blockstor.org] resources: [nodes/status, physicaldevices/status, resources/status, snapshots/status, storagepools/status, nodes/finalizers, physicaldevices/finalizers, resources/finalizers, snapshots/finalizers, storagepools/finalizers] From 87e6f99c722ec27e214abf66faefca7935505ccf Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Thu, 12 Nov 2026 10:23:28 -0500 Subject: [PATCH 04/18] feat(linstor): run blockstor v0.3.0 Bump the three blockstor images to 0.3.0 and take its CRDs from the release. v0.3.0 activates an LVM thin pool a reboot left inactive; before it, a rebooted node reported no capacity on such a pool and volume creation failed across the cluster. It gives every LUKS volume its own password, wrapped under a master key that several passphrases can open, so changing a passphrase no longer touches a volume and losing one is no longer losing the data. It also keeps each replica's own DRBD port when converting a LINSTOR cluster. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../blockstor.org_controllerconfigs.yaml | 18 ++-- .../definitions/blockstor.org_nodes.yaml | 15 +++- .../blockstor.org_resourcedefinitions.yaml | 84 ++++++++++++++++++- .../blockstor.org_resourcegroups.yaml | 15 +++- .../definitions/blockstor.org_resources.yaml | 65 +++++++++++++- .../definitions/blockstor.org_snapshots.yaml | 68 ++++++++++++++- .../blockstor.org_storagepools.yaml | 23 ++++- packages/system/linstor/values.yaml | 6 +- 8 files changed, 276 insertions(+), 18 deletions(-) diff --git a/packages/system/linstor/definitions/blockstor.org_controllerconfigs.yaml b/packages/system/linstor/definitions/blockstor.org_controllerconfigs.yaml index f296c08a6..c5dae2102 100644 --- a/packages/system/linstor/definitions/blockstor.org_controllerconfigs.yaml +++ b/packages/system/linstor/definitions/blockstor.org_controllerconfigs.yaml @@ -248,13 +248,19 @@ spec: type: object passphraseSecretRef: description: |- - passphraseSecretRef points at the Secret carrying the - cluster-wide LUKS passphrase under the key `passphrase`. The - satellite reads it via the apiserver during reconcile; - passphrase never lands on Spec in plaintext. Replaces - `Props["DrbdOptions/Encryption/passphrase"]` on the legacy - ControllerProps instance. + passphraseSecretRef points at the Secret, in blockstor's own + namespace, whose value unlocks the cluster master key: the shape + piraeus gives LINSTOR (`MASTER_PASSPHRASE`). blockstor only reads + it; every component reads it through the API server, so a changed + Secret takes effect without a restart. Unset, blockstor unlocks + from a passphrase Secret it generates and owns. properties: + key: + default: MASTER_PASSPHRASE + description: |- + key is the data key holding the passphrase. Its bytes are the + passphrase verbatim, a trailing newline included. + type: string name: description: name is the Secret name. Required. type: string diff --git a/packages/system/linstor/definitions/blockstor.org_nodes.yaml b/packages/system/linstor/definitions/blockstor.org_nodes.yaml index 9f8730129..839c05931 100644 --- a/packages/system/linstor/definitions/blockstor.org_nodes.yaml +++ b/packages/system/linstor/definitions/blockstor.org_nodes.yaml @@ -14,7 +14,20 @@ spec: singular: node scope: Cluster versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .spec.type + name: Type + type: string + - jsonPath: .spec.netInterfaces[0].address + name: Address + type: string + - jsonPath: .status.connectionStatus + name: Status + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: Node is the Schema for the nodes API diff --git a/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml b/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml index 641df9589..b301767f7 100644 --- a/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml @@ -14,7 +14,20 @@ spec: singular: resourcedefinition scope: Cluster versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .spec.resourceGroupName + name: Group + type: string + - jsonPath: .spec.drbdPort + name: Port + type: integer + - jsonPath: .spec.layerStack + name: Layers + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: ResourceDefinition is the Schema for the resourcedefinitions @@ -330,8 +343,10 @@ spec: Order is top-down: the first layer's device is what the consumer Pod mounts, the last is the raw block device the storage provider creates. - Empty = inherits from the parent ResourceGroup; both empty = - `["DRBD","STORAGE"]`. + Empty means not decided yet: the controller fixes it once, from + the parent ResourceGroup's stack for a definition that holds no + data, and the satellite builds nothing until it is set. Once set it + is never emptied. See docs/layer-stack.md. items: type: string type: array @@ -346,7 +361,22 @@ spec: spawned from (or empty if directly created). type: string volumeDefinitions: - description: volumeDefinitions are the volume slots inside this RD. + description: |- + volumeDefinitions are the volume slots inside this RD. + + Keyed on volumeNumber rather than atomic, because that is what makes + the size bound below enforceable. Kubernetes ratcheting correlates + per field, and an atomic list is compared whole: any update touching + it re-validates every element, so one volume written before the bound + existed would reject every later write to this definition — the + controller's own included, since it rewrites this list to stamp + drbdMinor. With the list keyed, an untouched element is not + re-validated and the bound applies to what is actually being written. + + The change was accepted by a running apiserver on the existing CRD, so + it needs no new API version. One shape does become unwritable: an + object carrying two entries with the same volumeNumber, which the + atomic list allowed. Neither writer produces it. items: description: ResourceDefinitionVolume is one volume slot inside an RD. @@ -392,7 +422,45 @@ spec: type: string type: object sizeKib: + description: |- + sizeKib is the volume size. The bounds are enforced HERE, by the API + server, as well as in pkg/validate: the CLI writes these CRDs + directly and REST has its own path, so a check living in one client + is not a check the data is subject to. The writers give an operator a + readable message; the schema is what holds for kubectl apply, a + GitOps controller, and blockstor's own controller rewriting this + list. + + The floor is DRBD's own per-device minimum once metadata is + reserved. Below it the satellite does not fail — it loops on + `drbdadm create-md` forever, which is why zero is the one value that + must never reach it, and why an overflowing size parse that lands on + zero has to be refused before it is stored. + + The ceiling is DRBD 9's documented per-device limit. It was 16 TiB, + which is below what DRBD 9 and upstream LINSTOR handle: linstormigrate + copies sizes verbatim, so a cluster holding a larger volume failed + part-way through its own migration. + + A bound on an existing field validates on UPDATE as well as on + create, which on an atomic list makes an out-of-range element poison + every later write to the whole object — including writes that never + touch the size, and including the controller's own, since it rewrites + this list to stamp drbdMinor. That is reachable on an in-place + upgrade: the REST spawn handler accepted any positive size until the + gate was added, so a cluster upgrading into this can hold a definition + sized 1..4095 KiB. + + The answer is the list-type marker on VolumeDefinitions rather than + dropping the bound. Keyed on volumeNumber, the API server correlates + elements across an update and ratcheting applies per element: a + grandfathered volume stays writable, and the bound holds for what is + actually being written. Verified against a running apiserver — an + update appending a second, in-range volume is accepted while volume 0 + stays at 1024 KiB, and a fresh definition at 1024 KiB is refused. format: int64 + maximum: 1099511627776 + minimum: 4096 type: integer volumeNumber: format: int32 @@ -402,7 +470,15 @@ spec: - volumeNumber type: object type: array + x-kubernetes-list-map-keys: + - volumeNumber + x-kubernetes-list-type: map type: object + x-kubernetes-validations: + - message: 'layerStack is decided once: it may be set or replaced, never + emptied' + rule: '!has(oldSelf.layerStack) || size(oldSelf.layerStack) == 0 || + (has(self.layerStack) && size(self.layerStack) > 0)' status: description: status defines the observed state of ResourceDefinition properties: diff --git a/packages/system/linstor/definitions/blockstor.org_resourcegroups.yaml b/packages/system/linstor/definitions/blockstor.org_resourcegroups.yaml index 141079b35..cfb9ac6f9 100644 --- a/packages/system/linstor/definitions/blockstor.org_resourcegroups.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resourcegroups.yaml @@ -14,7 +14,20 @@ spec: singular: resourcegroup scope: Cluster versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .spec.selectFilter.placeCount + name: Place-Count + type: integer + - jsonPath: .spec.selectFilter.storagePool + name: Storage-Pool + type: string + - jsonPath: .spec.selectFilter.layerStack + name: Layers + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: ResourceGroup is the Schema for the resourcegroups API diff --git a/packages/system/linstor/definitions/blockstor.org_resources.yaml b/packages/system/linstor/definitions/blockstor.org_resources.yaml index 96e0e94db..8cb1a6737 100644 --- a/packages/system/linstor/definitions/blockstor.org_resources.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resources.yaml @@ -14,7 +14,32 @@ spec: singular: resource scope: Cluster versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .spec.resourceDefinitionName + name: Definition + type: string + - jsonPath: .spec.nodeName + name: Node + type: string + - jsonPath: .spec.storagePool + name: Pool + type: string + - jsonPath: .spec.drbdNodeID + name: Node-ID + type: integer + - jsonPath: .spec.drbdPort + name: Port + type: integer + - jsonPath: .status.drbdState + name: State + type: string + - jsonPath: .status.inUse + name: In-Use + type: boolean + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: |- @@ -386,6 +411,35 @@ spec: hints the satellite consumes during first activation, the Status counterpart carries observed runtime state. properties: + luksKey: + description: |- + luksKey is this replica's LUKS password, wrapped under the cluster + master key. It is the only key in the volume's LUKS header, so it + lives in spec, where backups restore it, and it is set once. + properties: + keyID: + description: |- + keyID is the public ID of the master key the password is wrapped + under. + pattern: ^[0-9a-f]{16}$ + type: string + origin: + description: origin says where the password came from. + enum: + - Generated + - LinstorImport + type: string + wrapped: + description: wrapped is nonce || AES-256-GCM ciphertext + || tag. + minLength: 1 + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + required: + - keyID + - origin + - wrapped + type: object seedFromGI: description: |- seedFromGI pre-seeds the DRBD-9 generation identifier of this @@ -408,6 +462,12 @@ spec: required: - volumeNumber type: object + x-kubernetes-validations: + - message: 'luksKey is set once: it may go from unset to a value + but not be changed or removed, the replica''s data is readable + only with it' + rule: '!has(oldSelf.luksKey) || (has(self.luksKey) && self.luksKey + == oldSelf.luksKey)' type: array x-kubernetes-list-map-keys: - volumeNumber @@ -756,6 +816,9 @@ spec: optionalOldSelf: true rule: oldSelf.hasValue() || self.metadata.name.lowerAscii() == (self.spec.resourceDefinitionName + '.' + self.spec.nodeName).lowerAscii() + selectableFields: + - jsonPath: .spec.nodeName + - jsonPath: .spec.resourceDefinitionName served: true storage: true subresources: diff --git a/packages/system/linstor/definitions/blockstor.org_snapshots.yaml b/packages/system/linstor/definitions/blockstor.org_snapshots.yaml index f041385c7..f7f1f0cbd 100644 --- a/packages/system/linstor/definitions/blockstor.org_snapshots.yaml +++ b/packages/system/linstor/definitions/blockstor.org_snapshots.yaml @@ -14,7 +14,20 @@ spec: singular: snapshot scope: Cluster versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .spec.resourceDefinitionName + name: Definition + type: string + - jsonPath: .spec.snapshotName + name: Snapshot + type: string + - jsonPath: .spec.nodes + name: Nodes + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: |- @@ -109,6 +122,53 @@ spec: makes progress instead of hanging on a missing denominator. format: int32 type: integer + luksKeys: + description: |- + luksKeys are the wrapped LUKS passwords of the source replicas, + copied when the snapshot is created: a snapshot's bytes are + encrypted under the password of the replica they were taken from, + and that replica may be gone by the time the snapshot is restored. + items: + description: SnapshotLUKSKey is the wrapped password of one source + replica's volume. + properties: + keyID: + description: |- + keyID is the public ID of the master key the password is wrapped + under. + pattern: ^[0-9a-f]{16}$ + type: string + nodeName: + description: nodeName is the CR name of the node the replica + is on. + type: string + origin: + description: origin says where the password came from. + enum: + - Generated + - LinstorImport + type: string + volumeNumber: + description: volumeNumber is the volume within the replica. + format: int32 + type: integer + wrapped: + description: wrapped is nonce || AES-256-GCM ciphertext || tag. + minLength: 1 + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + required: + - keyID + - nodeName + - origin + - volumeNumber + - wrapped + type: object + type: array + x-kubernetes-list-map-keys: + - nodeName + - volumeNumber + x-kubernetes-list-type: map nodes: description: |- nodes are the satellites the snapshot should live on. Empty means @@ -189,6 +249,10 @@ spec: - resourceDefinitionName - snapshotName type: object + x-kubernetes-validations: + - message: luksKeys is set once, when the snapshot is created + rule: '!has(oldSelf.luksKeys) || (has(self.luksKeys) && self.luksKeys + == oldSelf.luksKeys)' status: description: status defines the observed state of Snapshot properties: @@ -309,6 +373,8 @@ spec: optionalOldSelf: true rule: oldSelf.hasValue() || self.metadata.name.lowerAscii() == (self.spec.resourceDefinitionName + '.' + self.spec.snapshotName).lowerAscii() + selectableFields: + - jsonPath: .spec.resourceDefinitionName served: true storage: true subresources: diff --git a/packages/system/linstor/definitions/blockstor.org_storagepools.yaml b/packages/system/linstor/definitions/blockstor.org_storagepools.yaml index 8afe147c6..195295ab2 100644 --- a/packages/system/linstor/definitions/blockstor.org_storagepools.yaml +++ b/packages/system/linstor/definitions/blockstor.org_storagepools.yaml @@ -14,7 +14,26 @@ spec: singular: storagepool scope: Cluster versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .spec.nodeName + name: Node + type: string + - jsonPath: .spec.poolName + name: Pool + type: string + - jsonPath: .spec.providerKind + name: Provider + type: string + - jsonPath: .status.freeCapacity + name: Free-KiB + type: integer + - jsonPath: .status.totalCapacity + name: Total-KiB + type: integer + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: |- @@ -204,6 +223,8 @@ spec: optionalOldSelf: true rule: oldSelf.hasValue() || self.metadata.name.lowerAscii() == (self.spec.poolName + '.' + self.spec.nodeName).lowerAscii() + selectableFields: + - jsonPath: .spec.nodeName served: true storage: true subresources: diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index a14daaa6c..d004abce5 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -27,15 +27,15 @@ piraeusServer: blockstorController: image: repository: ghcr.io/cozystack/blockstor-controller - tag: 0.1.17@sha256:19b5733565e4bbe9510eecae8d47a181e72e07009b3d565848e8ccf1cd9393e8 + tag: 0.3.0@sha256:ca5fc964265a1fd9e1153077f0565a9f07532c593bea1182d3b97a38430822ea blockstorApiserver: image: repository: ghcr.io/cozystack/blockstor-apiserver - tag: 0.1.17@sha256:102cf8c8d431f3b6714bca53752327ae8bb793b2d5ebed3aae47d51a85805f26 + tag: 0.3.0@sha256:20cf599f8d0ae85a44b237b9d8ad2ca631a1feff3fd387194ef84636b538dd0b blockstorSatellite: image: repository: ghcr.io/cozystack/blockstor-satellite - tag: 0.1.17@sha256:8bd15bca47f33464eaf489884c33fd50ef2574a0ad856ab5ab9b921186a98bea + tag: 0.3.0@sha256:abff381da5425fdf7a6abc0d52006727cf7fe13c438acc79aaea192fc8681cb4 # Talos-specific workarounds (disable for generic Linux like Ubuntu/Debian) talos: enabled: true From bd64d7672da35bc1874ae8088c4a95f51a65965f Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Thu, 12 Nov 2026 10:24:30 -0500 Subject: [PATCH 05/18] feat(linstor): run blockstor's snapshot stream on 3372 over mutual TLS blockstor v0.2.0 moved the stream between satellites from port 9100 to 3372 and runs it over mutual TLS with a CA of its own. The chart issues the stream CA and the satellites' certificate, mounts it into the satellite, and closes 3372 to the world instead of 9100. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../templates/blockstor-apiserver-tls.yaml | 67 +++++++++++++++++ .../templates/blockstor-satellite.yaml | 25 +++++-- .../tests/blockstor_workloads_test.yaml | 71 ++++++++++++++++++- 3 files changed, 156 insertions(+), 7 deletions(-) diff --git a/packages/system/linstor/templates/blockstor-apiserver-tls.yaml b/packages/system/linstor/templates/blockstor-apiserver-tls.yaml index 02803e23f..b6af39104 100644 --- a/packages/system/linstor/templates/blockstor-apiserver-tls.yaml +++ b/packages/system/linstor/templates/blockstor-apiserver-tls.yaml @@ -12,6 +12,9 @@ └─> blockstor-api-ca (CA Issuer) ├─> blockstor-apiserver-server (serving cert, Service DNS SANs) └─> blockstor-apiserver-client (client cert for in-cluster consumers) + └─> blockstor-stream-ca (CA Certificate, 10y, kept apart from the API CA) + └─> blockstor-stream-ca (CA Issuer) + └─> blockstor-satellite-stream (one cert for every satellite's snapshot stream) The apiserver's TLS listener (RequireAndVerifyClientCert) verifies every client cert against ca.crt of the server Secret, and serves @@ -107,4 +110,68 @@ spec: issuerRef: name: blockstor-api-ca kind: Issuer +--- +{{- /* + The snapshot stream between satellites has a CA of its own. A stream + certificate is a client certificate, and one from blockstor-api-ca would + also be accepted by the apiserver's mutual-TLS listener; keeping the CAs + apart keeps a satellite's stream identity off the REST API. */}} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: blockstor-stream-ca + namespace: {{ .Release.Namespace }} +spec: + commonName: blockstor-stream-ca + secretName: blockstor-stream-ca + duration: 87600h # 10 years + isCA: true + privateKey: + rotationPolicy: Never + usages: + - signing + - key encipherment + - cert sign + issuerRef: + name: ca-bootstrapper + kind: Issuer +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: blockstor-stream-ca + namespace: {{ .Release.Namespace }} +spec: + ca: + secretName: blockstor-stream-ca +--- +{{- /* + One certificate for every satellite, for both ends of a stream: the + satellites dial each other by node address, so the name checked is the + fixed blockstor-satellite, not an address. A satellite pod does not + start until cert-manager has issued blockstor-satellite-stream-tls. */}} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: blockstor-satellite-stream + namespace: {{ .Release.Namespace }} +spec: + secretName: blockstor-satellite-stream-tls + commonName: blockstor-satellite + duration: 2160h # 90 days + renewBefore: 360h # 15 days + privateKey: + algorithm: ECDSA + size: 256 + rotationPolicy: Always + usages: + - server auth + - client auth + - digital signature + - key encipherment + dnsNames: + - blockstor-satellite + issuerRef: + name: blockstor-stream-ca + kind: Issuer {{- end }} diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml index 28aae4ac1..8edd86ba6 100644 --- a/packages/system/linstor/templates/blockstor-satellite.yaml +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -192,6 +192,14 @@ spec: {{- /* Storage pools come from StoragePool objects, not flags. */}} - --health-probe-bind-address=:9101 + {{- /* + Mutual TLS of the snapshot stream between satellites (port + 3372). Every satellite presents the same certificate, issued + by the stream CA in blockstor-apiserver-tls.yaml, and accepts + only peers that present one from that CA. */}} + - --stream-tls-cert-file=/etc/blockstor/stream-tls/tls.crt + - --stream-tls-key-file=/etc/blockstor/stream-tls/tls.key + - --stream-tls-ca-file=/etc/blockstor/stream-tls/ca.crt env: - name: NODE_NAME valueFrom: {fieldRef: {fieldPath: spec.nodeName}} @@ -235,6 +243,7 @@ spec: mountPath: /etc/drbd.d/global_common.conf subPath: global_common.conf readOnly: true + - {name: stream-tls, mountPath: /etc/blockstor/stream-tls, readOnly: true} resources: requests: {cpu: 50m, memory: 64Mi} limits: {cpu: 500m, memory: 512Mi} @@ -251,12 +260,18 @@ spec: name: blockstor-satellite-drbd-conf items: - {key: global_common.conf, path: global_common.conf} + {{- /* + Read on every stream handshake, so a certificate cert-manager + rotates is picked up without a restart. */}} + - name: stream-tls + secret: + secretName: blockstor-satellite-stream-tls --- {{- /* - blockstor-satellite runs on host networking and, in this release, listens - on every address without authentication: 9100 serves snapshot streams to - other satellites, 9101 its health probes, 8080 controller-runtime's - metrics. None of them is for anything outside the cluster, so they are + blockstor-satellite runs on host networking and listens on every address: + 3372 serves snapshot streams to other satellites over mutual TLS, 9101 its + health probes and 8080 controller-runtime's metrics, both without + authentication. None of them is for anything outside the cluster, so they are closed to the world the way restrict-drbd-reactor closes drbd-reactor's. */}} apiVersion: cilium.io/v2 kind: CiliumClusterwideNetworkPolicy @@ -268,7 +283,7 @@ spec: - world toPorts: - ports: - - port: "9100" + - port: "3372" - port: "9101" - port: "8080" ingress: diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index aa63d1c4d..1818838a6 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -119,7 +119,7 @@ tests: resources: [leases] verbs: [get, list, watch, create, update, patch, delete] - - it: closes the satellite's unauthenticated ports to the world + - it: closes the satellite's ports to the world template: templates/blockstor-satellite.yaml documentSelector: path: kind @@ -131,10 +131,77 @@ tests: - equal: path: spec.ingressDeny[0].toPorts[0].ports value: - - port: "9100" + - port: "3372" - port: "9101" - port: "8080" + # The snapshot stream runs over mutual TLS: without the Secret mounted and + # the three flags the satellite serves no stream at all. + - it: gives the satellite the snapshot stream's TLS + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - contains: + path: spec.template.spec.containers[0].args + content: --stream-tls-cert-file=/etc/blockstor/stream-tls/tls.crt + - contains: + path: spec.template.spec.containers[0].args + content: --stream-tls-key-file=/etc/blockstor/stream-tls/tls.key + - contains: + path: spec.template.spec.containers[0].args + content: --stream-tls-ca-file=/etc/blockstor/stream-tls/ca.crt + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: {name: stream-tls, mountPath: /etc/blockstor/stream-tls, readOnly: true} + - contains: + path: spec.template.spec.volumes + content: + name: stream-tls + secret: + secretName: blockstor-satellite-stream-tls + + # The stream CA stays apart from the API CA: a stream certificate is a + # client certificate the apiserver's mutual-TLS listener would otherwise + # accept. + - it: issues the satellite stream certificate from its own CA + template: templates/blockstor-apiserver-tls.yaml + documentSelector: + path: metadata.name + value: blockstor-satellite-stream + asserts: + - equal: + path: spec.secretName + value: blockstor-satellite-stream-tls + - equal: + path: spec.issuerRef.name + value: blockstor-stream-ca + - equal: + path: spec.dnsNames + value: [blockstor-satellite] + - contains: + path: spec.usages + content: server auth + - contains: + path: spec.usages + content: client auth + + - it: roots the stream CA in the bootstrapper, not in the API CA + template: templates/blockstor-apiserver-tls.yaml + documentSelector: + path: spec.commonName + value: blockstor-stream-ca + asserts: + - isKind: + of: Certificate + - equal: + path: spec.isCA + value: true + - equal: + path: spec.issuerRef.name + value: ca-bootstrapper + # A kind added to the group later must not be granted by omission, so the # roles are pinned whole: a wildcard or a new kind shows up as a diff here. - it: pins the controller ClusterRole rule by rule From b9526ebfd26c164cf657a3ab9e87509ef694b9fe Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Thu, 12 Nov 2026 10:25:24 -0500 Subject: [PATCH 06/18] fix(linstor): grant blockstor its Secrets by name only blockstor reads the passphrase Secret past controller-runtime's cache, keeps the master key in its own keyring Secret and unlocks it from piraeus's linstor-passphrase. Its own RBAC grants the satellite, and the controller and apiserver, access only to those Secrets and the generated unlock Secret. cozy-linstor is shared with piraeus, so unnamed or cluster-wide grants would let any blockstor pod read piraeus's TLS keys; the satellite runs privileged on every node, which makes that one compromised node away. The apiserver reads and writes Secrets through a namespaced Role only. The controller creates the keyring itself, so it gets its own namespaced Role, and the namespace it looks the Secrets up in, which otherwise defaults to blockstor-system. create cannot be limited by name and is granted on its own. The passphrase Secret's name is a value so a cluster that names another Secret keeps the Roles in step. The named rules also allow list and watch: newer blockstor releases read these Secrets from one watch per Secret selected by metadata.name, and without the verbs fall back to a GET per read. A list or watch restricted by resourceNames is authorized only when its fieldSelector names one of them, so the rule still exposes nothing else in the namespace. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../linstor/templates/_blockstor-secrets.tpl | 14 +++++ .../templates/blockstor-apiserver.yaml | 33 +++++----- .../templates/blockstor-controller.yaml | 46 ++++++++++++++ .../templates/blockstor-satellite.yaml | 13 ++-- .../linstor/tests/blockstor_rbac_test.yaml | 55 +++++++++++------ .../tests/blockstor_workloads_test.yaml | 61 ++++++++++++++++++- packages/system/linstor/values.yaml | 7 +++ 7 files changed, 191 insertions(+), 38 deletions(-) create mode 100644 packages/system/linstor/templates/_blockstor-secrets.tpl diff --git a/packages/system/linstor/templates/_blockstor-secrets.tpl b/packages/system/linstor/templates/_blockstor-secrets.tpl new file mode 100644 index 000000000..4cebc2b32 --- /dev/null +++ b/packages/system/linstor/templates/_blockstor-secrets.tpl @@ -0,0 +1,14 @@ +{{- /* +The only Secrets blockstor touches, as a YAML flow list: its keyring, the +unlock Secret it generates when no passphrase Secret is named, and the +passphrase Secret named by blockstorPassphraseSecret. Every Role that grants +blockstor Secret access names exactly these, because cozy-linstor is shared +with piraeus and its TLS keys must stay unreadable. +*/ -}} +{{- define "blockstor.secretNames" -}} +{{- $name := .Values.blockstorPassphraseSecret | toString }} +{{- if not (regexMatch "^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$" $name) }} +{{- fail (printf "linstor: blockstorPassphraseSecret must be a Secret name, got %q" $name) }} +{{- end }} +{{- list "blockstor-master-key" "blockstor-unlock" $name | uniq | toJson }} +{{- end }} diff --git a/packages/system/linstor/templates/blockstor-apiserver.yaml b/packages/system/linstor/templates/blockstor-apiserver.yaml index 781f0cd5b..ae873432f 100644 --- a/packages/system/linstor/templates/blockstor-apiserver.yaml +++ b/packages/system/linstor/templates/blockstor-apiserver.yaml @@ -38,16 +38,6 @@ rules: - storagepools - storagepools/status verbs: [get, list, watch, create, update, patch, delete] - {{- /* - Read-only, and cluster-wide only because the apiserver reads the - passphrase Secret through controller-runtime's default cached client, - whose informer lists and watches Secrets at cluster scope. Narrowing - this needs the binary to scope its Secret cache to its own namespace; - until then a namespaced Role here would leave that informer forbidden - and every passphrase read hanging. */}} - - apiGroups: [""] - resources: [secrets] - verbs: [get, list, watch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding @@ -63,10 +53,19 @@ subjects: namespace: {{ .Release.Namespace }} --- {{- /* - Writes to Secrets stay in this namespace: the only Secret the apiserver - writes is the encryption passphrase, `encryption create-passphrase` and - `modify-passphrase`, and it always lives here. A cluster-wide write - grant would let this ServiceAccount rewrite any tenant's credentials. */}} + The encryption endpoints read and rewrite the keyring (add-, modify-, + remove-passphrase), create it and the generated unlock Secret when no + passphrase Secret is named, and read the passphrase Secret to unlock. + All of it is in this namespace and none of it goes through + controller-runtime's cache, which would watch every Secret: the verbs + read by name, and the encryption state of the resource view comes from + one watch per Secret, selected by metadata.name. get, list, watch and + update name the three Secrets, because this namespace is shared with + piraeus, whose TLS keys stay unreadable; a list or watch is allowed only + when it selects one of them by name. create cannot be limited by name, + so it is granted on its own; the ValidatingAdmissionPolicy in + blockstor-secrets-policy.yaml holds it to the two Secrets blockstor + creates. */}} apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: @@ -75,7 +74,11 @@ metadata: rules: - apiGroups: [""] resources: [secrets] - verbs: [create, update, patch] + resourceNames: {{ include "blockstor.secretNames" . }} + verbs: [get, list, watch, update] + - apiGroups: [""] + resources: [secrets] + verbs: [create] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/packages/system/linstor/templates/blockstor-controller.yaml b/packages/system/linstor/templates/blockstor-controller.yaml index faca527ef..6c77ee912 100644 --- a/packages/system/linstor/templates/blockstor-controller.yaml +++ b/packages/system/linstor/templates/blockstor-controller.yaml @@ -68,6 +68,45 @@ subjects: name: blockstor-controller namespace: {{ .Release.Namespace }} --- +{{- /* + On its first pass the controller creates the keyring from the passphrase + Secret, and later drops superseded slots from it, so it reads both and + writes the keyring, by name or through one watch per Secret, never + through the manager's cache. get, list, watch and update name the three + Secrets blockstor uses, because this namespace is shared with piraeus, + whose TLS keys stay unreadable; a list or watch is allowed only when it + selects one of them by name. create cannot be limited by name, so it is + granted on its own; the ValidatingAdmissionPolicy in + blockstor-secrets-policy.yaml holds it to the two Secrets blockstor + creates. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: blockstor-controller-secrets + namespace: {{ .Release.Namespace }} +rules: + - apiGroups: [""] + resources: [secrets] + resourceNames: {{ include "blockstor.secretNames" . }} + verbs: [get, list, watch, update] + - apiGroups: [""] + resources: [secrets] + verbs: [create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: blockstor-controller-secrets + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: blockstor-controller-secrets +subjects: + - kind: ServiceAccount + name: blockstor-controller + namespace: {{ .Release.Namespace }} +--- apiVersion: apps/v1 kind: Deployment metadata: @@ -104,6 +143,13 @@ spec: - --health-probe-bind-address=:8081 - --metrics-bind-address=0 - --leader-elect=false + {{- /* + The keyring and the passphrase Secret are looked up in the + controller's namespace, which otherwise defaults to + blockstor-system. */}} + env: + - name: POD_NAMESPACE + valueFrom: {fieldRef: {fieldPath: metadata.namespace}} ports: - {name: health, containerPort: 8081} readinessProbe: diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml index 8edd86ba6..de1a522e2 100644 --- a/packages/system/linstor/templates/blockstor-satellite.yaml +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -109,11 +109,13 @@ subjects: namespace: {{ .Release.Namespace }} --- {{- /* - The satellite reads one Secret, the LUKS passphrase, in its own - namespace, with a direct GET rather than through a cache, so a - namespaced get is all it needs. A privileged pod on every node holding - a token that reads every Secret in the cluster would hand any node - compromise every tenant's credentials. */}} + The satellite unlocks the master key itself, from the passphrase Secret + and the keyring, to unwrap the password of each LUKS volume it opens. It + reads them with a direct GET rather than through a cache, so a get by + name is all it needs. Named, because this namespace is shared with + piraeus: a privileged pod on every node holding a token that reads + piraeus's TLS keys, or every Secret in the cluster, would turn any node + compromise into far more than this node's volumes. */}} apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: @@ -122,6 +124,7 @@ metadata: rules: - apiGroups: [""] resources: [secrets] + resourceNames: {{ include "blockstor.secretNames" . }} verbs: [get] --- apiVersion: rbac.authorization.k8s.io/v1 diff --git a/packages/system/linstor/tests/blockstor_rbac_test.yaml b/packages/system/linstor/tests/blockstor_rbac_test.yaml index 52e2fbc0d..5af37586b 100644 --- a/packages/system/linstor/tests/blockstor_rbac_test.yaml +++ b/packages/system/linstor/tests/blockstor_rbac_test.yaml @@ -1,6 +1,7 @@ -# The apiserver writes exactly one Secret, the encryption passphrase, and -# always in its own namespace. A cluster-wide write grant would reach every -# tenant's admin kubeconfig and every managed-service credential. +# The apiserver reads and writes the keyring and the generated unlock Secret +# and reads the passphrase Secret, always in its own namespace, which it +# shares with piraeus. A cluster-wide grant would reach every tenant's admin +# kubeconfig; an unnamed one in the namespace would reach piraeus's TLS keys. suite: blockstor apiserver Secret access templates: - templates/blockstor-apiserver.yaml @@ -10,25 +11,23 @@ release: set: backend: blockstor tests: - - it: grants Secrets only read access cluster-wide + - it: grants no Secret access cluster-wide documentSelector: path: kind value: ClusterRole asserts: - - contains: - path: rules - content: - apiGroups: [""] - resources: [secrets] - verbs: [get, list, watch] - notContains: path: rules content: apiGroups: [""] resources: [secrets] - verbs: [get, list, watch, create, update, patch] + verbs: [get, list, watch] + any: true + - lengthEqual: + path: rules + count: 1 - - it: grants Secret writes in the release namespace only + - it: grants Secret reads and writes in the release namespace by name only documentSelector: path: kind value: Role @@ -36,12 +35,34 @@ tests: - equal: path: metadata.namespace value: cozy-linstor - - contains: + - equal: path: rules - content: - apiGroups: [""] - resources: [secrets] - verbs: [create, update, patch] + value: + - apiGroups: [""] + resources: [secrets] + resourceNames: [blockstor-master-key, blockstor-unlock, linstor-passphrase] + verbs: [get, list, watch, update] + - apiGroups: [""] + resources: [secrets] + verbs: [create] + + - it: names the passphrase Secret the chart is told to use + set: + blockstorPassphraseSecret: my-passphrase + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: rules[0].resourceNames + value: [blockstor-master-key, blockstor-unlock, my-passphrase] + + - it: refuses a passphrase Secret name that is not a Secret name + set: + blockstorPassphraseSecret: "" + asserts: + - failedTemplate: + errorPattern: blockstorPassphraseSecret must be a Secret name - it: binds the namespaced Role to the apiserver ServiceAccount documentSelector: diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index 1818838a6..98ed86e40 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -77,7 +77,7 @@ tests: resources: [leases] verbs: [get, list, watch, create, update, patch, delete] - - it: lets the satellite read Secrets in its own namespace only + - it: lets the satellite read only blockstor's Secrets in its own namespace template: templates/blockstor-satellite.yaml documentSelector: path: kind @@ -91,8 +91,67 @@ tests: value: - apiGroups: [""] resources: [secrets] + resourceNames: [blockstor-master-key, blockstor-unlock, linstor-passphrase] verbs: [get] + - it: gives the controller no Secret access at cluster scope + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - notContains: + path: rules + content: + apiGroups: [""] + resources: [secrets] + any: true + + - it: lets the controller read and write only blockstor's Secrets in its own namespace + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: metadata.namespace + value: cozy-linstor + - equal: + path: rules + value: + - apiGroups: [""] + resources: [secrets] + resourceNames: [blockstor-master-key, blockstor-unlock, linstor-passphrase] + verbs: [get, list, watch, update] + - apiGroups: [""] + resources: [secrets] + verbs: [create] + + - it: binds the controller's Secret Role to its ServiceAccount + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: RoleBinding + asserts: + - equal: + path: roleRef.name + value: blockstor-controller-secrets + - equal: + path: subjects[0].name + value: blockstor-controller + + - it: tells the controller its namespace, where the keyring lives + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: POD_NAMESPACE + valueFrom: {fieldRef: {fieldPath: metadata.namespace}} + - it: binds the satellite's Secret Role to its ServiceAccount template: templates/blockstor-satellite.yaml documentSelector: diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index d004abce5..9c3c424c6 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -36,6 +36,13 @@ blockstorSatellite: image: repository: ghcr.io/cozystack/blockstor-satellite tag: 0.3.0@sha256:abff381da5425fdf7a6abc0d52006727cf7fe13c438acc79aaea192fc8681cb4 +# The Secret, in this namespace, whose MASTER_PASSPHRASE key unlocks the +# blockstor master key that wraps every LUKS volume password. It is the +# Secret piraeus reads for LINSTOR, so a cluster migrated from LINSTOR keeps +# its passphrase. blockstor only reads it; the operator creates it. The +# chart renders it into ControllerConfig.spec.passphraseSecretRef and into +# the Secret names the blockstor Roles grant. +blockstorPassphraseSecret: linstor-passphrase # Talos-specific workarounds (disable for generic Linux like Ubuntu/Debian) talos: enabled: true From b4865ae574c74cc4f2fe764d730abee6281f815e Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Thu, 12 Nov 2026 10:25:24 -0500 Subject: [PATCH 07/18] fix(linstor): let the blockstor satellite record events.k8s.io events The satellite's recorder writes events through events.k8s.io, for a LUKS format refused over data, and the role granted only core events. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- packages/system/linstor/templates/blockstor-satellite.yaml | 6 ++++++ packages/system/linstor/tests/blockstor_workloads_test.yaml | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml index de1a522e2..2e2f07503 100644 --- a/packages/system/linstor/templates/blockstor-satellite.yaml +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -61,6 +61,12 @@ rules: - apiGroups: [""] resources: [events] verbs: [create, patch] + {{- /* + The same events through events.k8s.io, which the satellite's recorder + writes (a LUKS format refused over data). */}} + - apiGroups: [events.k8s.io] + resources: [events] + verbs: [create, patch] - apiGroups: [""] resources: [nodes] verbs: [get, list, watch] diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index 98ed86e40..5395afeec 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -56,7 +56,7 @@ tests: verbs: [update, patch] - lengthEqual: path: rules - count: 6 + count: 7 - it: gives the satellite no Secret or Lease access at cluster scope template: templates/blockstor-satellite.yaml @@ -308,6 +308,9 @@ tests: - apiGroups: [''] resources: [events] verbs: [create, patch] + - apiGroups: [events.k8s.io] + resources: [events] + verbs: [create, patch] - apiGroups: [''] resources: [nodes] verbs: [get, list, watch] From 112aa1ca16adb20934fde4385a5a601ef8033c61 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Thu, 12 Nov 2026 10:25:42 -0500 Subject: [PATCH 08/18] fix(linstor): give the blockstor controller and apiserver 21s to stop Their REST servers hold a shutdown window derived from the detached rollback budget, and blockstor v0.2.0 sets the pods' grace to 21s so a SIGTERM does not kill a compensation mid-cascade. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../templates/blockstor-apiserver.yaml | 5 +++++ .../templates/blockstor-controller.yaml | 5 +++++ .../tests/blockstor_workloads_test.yaml | 22 +++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/packages/system/linstor/templates/blockstor-apiserver.yaml b/packages/system/linstor/templates/blockstor-apiserver.yaml index ae873432f..db908d8ea 100644 --- a/packages/system/linstor/templates/blockstor-apiserver.yaml +++ b/packages/system/linstor/templates/blockstor-apiserver.yaml @@ -112,6 +112,11 @@ spec: app.kubernetes.io/component: blockstor-apiserver spec: serviceAccountName: blockstor-apiserver + {{- /* + The REST server's graceful-shutdown window is derived from its + detached rollback budget; this has to outlive it, or a SIGTERM kills + a compensation mid-cascade. */}} + terminationGracePeriodSeconds: 21 topologySpreadConstraints: - maxSkew: 1 topologyKey: kubernetes.io/hostname diff --git a/packages/system/linstor/templates/blockstor-controller.yaml b/packages/system/linstor/templates/blockstor-controller.yaml index 6c77ee912..2f8871d26 100644 --- a/packages/system/linstor/templates/blockstor-controller.yaml +++ b/packages/system/linstor/templates/blockstor-controller.yaml @@ -131,6 +131,11 @@ spec: app.kubernetes.io/component: blockstor-controller spec: serviceAccountName: blockstor-controller + {{- /* + The REST server's graceful-shutdown window is derived from its + detached rollback budget; this has to outlive it, or a SIGTERM kills + a compensation mid-cascade. */}} + terminationGracePeriodSeconds: 21 containers: - name: manager image: {{ .Values.blockstorController.image.repository }}:{{ .Values.blockstorController.image.tag }} diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index 5395afeec..c4dafa2ba 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -340,3 +340,25 @@ tests: - matchRegex: path: spec.template.metadata.annotations["checksum/drbd-conf"] pattern: '^[0-9a-f]{64}$' + + # A SIGTERM must not cut a detached rollback short: the pod outlives the + # REST server's shutdown window. + - it: gives the controller time to finish a rollback on shutdown + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - equal: + path: spec.template.spec.terminationGracePeriodSeconds + value: 21 + + - it: gives the apiserver time to finish a rollback on shutdown + template: templates/blockstor-apiserver.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - equal: + path: spec.template.spec.terminationGracePeriodSeconds + value: 21 From 5c1f4c532e09bab0a0ddce3b919e947a5972d680 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Thu, 12 Nov 2026 12:35:49 -0500 Subject: [PATCH 09/18] docs(linstor): point a cluster with LINSTOR volumes at blockstor's runbook The values files said nothing converts LINSTOR's database into blockstor's. blockstor v0.2.0 ships linstor-migrate and a runbook for adopting such a cluster in place; the platform still does not run it, so the backend value stays for new clusters and names the runbook. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- packages/core/platform/values.yaml | 11 ++++++----- packages/system/linstor/values.yaml | 8 ++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index aa496eaf6..61cb90fca 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -111,12 +111,13 @@ migrations: # Which storage control plane the cluster runs. # # linstor — the default, and what every existing cluster runs. -# blockstor — EXPERIMENTAL, for new clusters only. A +# blockstor — EXPERIMENTAL, for new clusters. A # LINSTOR-API-compatible control plane serving the same -# CSI driver and StorageClasses. Do not switch a cluster -# that already holds LINSTOR volumes: the pinned blockstor -# release cannot adopt them safely, and nothing converts -# LINSTOR's database into blockstor's. +# CSI driver and StorageClasses. This value does not move +# a cluster that already holds LINSTOR volumes: blockstor +# adopts them with its own linstor-migrate runbook, which +# this platform does not run: +# https://blockstor.org/docs/migration/ # # Anything else fails the render rather than defaulting, so a typo # cannot quietly deploy the wrong storage control plane. Changing the diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index 9c3c424c6..e376866ff 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -10,10 +10,10 @@ # linstor-csi build, so the StorageClasses (provisioner # linstor.csi.linbit.com) are the same under either. # -# blockstor is for new clusters only. Switching a cluster that already -# holds LINSTOR volumes is not supported: the pinned blockstor release -# cannot adopt existing DRBD resources safely, and this chart does not -# convert LINSTOR's database into blockstor's. +# blockstor is for new clusters. This chart does not move a cluster that +# already holds LINSTOR volumes: blockstor adopts them with its own +# linstor-migrate runbook, which the chart does not run: +# https://blockstor.org/docs/migration/ backend: linstor piraeusServer: From 6ba465d40af63c98ec018eef06f9f44b37692664 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 16 Nov 2026 11:46:30 -0500 Subject: [PATCH 10/18] fix(linstor): admit only blockstor's own Secret creates RBAC cannot limit create by name, and the blockstor controller and apiserver need create for the keyring and the generated unlock Secret. With the name-limited get they also hold, a compromised pod could create a service-account-token Secret for one of piraeus's ServiceAccounts in cozy-linstor under a covered name that does not exist yet, linstor-passphrase on a cluster that never set one, and read the token back. blockstor's design leaves closing this to the chart. The policy matches only Secret creates in the release namespace by the blockstor ServiceAccounts, so it cannot reach piraeus or cert-manager, and admits the keyring and the unlock Secret with the types blockstor gives them. The passphrase Secret is not admitted: blockstor never writes it. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../templates/blockstor-secrets-policy.yaml | 61 +++++++++++++ .../tests/blockstor_secrets_policy_test.yaml | 90 +++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 packages/system/linstor/templates/blockstor-secrets-policy.yaml create mode 100644 packages/system/linstor/tests/blockstor_secrets_policy_test.yaml diff --git a/packages/system/linstor/templates/blockstor-secrets-policy.yaml b/packages/system/linstor/templates/blockstor-secrets-policy.yaml new file mode 100644 index 000000000..d1726aa90 --- /dev/null +++ b/packages/system/linstor/templates/blockstor-secrets-policy.yaml @@ -0,0 +1,61 @@ +{{- if and (eq .Values.backend "blockstor") (.Capabilities.APIVersions.Has "admissionregistration.k8s.io/v1/ValidatingAdmissionPolicy") }} +{{- $sa := printf "system:serviceaccount:%s:" .Release.Namespace }} +--- +{{- /* + RBAC cannot limit create by name, and the blockstor controller and + apiserver need it for the keyring and the generated unlock Secret. A + compromised pod could otherwise create a Secret under a name its + name-limited get already covers but that does not exist yet, such as + linstor-passphrase on a cluster that never set one, typed + kubernetes.io/service-account-token for one of piraeus's ServiceAccounts + in this namespace, and read the token back. This admits a Secret create + by a blockstor ServiceAccount only for the two Secrets blockstor creates, + each with the type blockstor gives it; the passphrase Secret is input + that blockstor never writes. + + It matches nothing but CREATE of Secrets in this namespace by these + ServiceAccounts, so piraeus, cert-manager and everyone else are outside + it, as are updates, which RBAC already limits by name. The satellite + holds no create; it is listed so a later grant does not reopen the gap. */}} +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: blockstor-secret-create +spec: + failurePolicy: Fail + matchConstraints: + namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ .Release.Namespace }} + resourceRules: + - apiGroups: [""] + apiVersions: [v1] + operations: [CREATE] + resources: [secrets] + matchConditions: + - name: blockstor-service-account + expression: >- + request.userInfo.username in [ + '{{ $sa }}blockstor-apiserver', + '{{ $sa }}blockstor-controller', + '{{ $sa }}blockstor-satellite' + ] + validations: + - expression: >- + (object.metadata.name == 'blockstor-master-key' && + has(object.type) && object.type == 'blockstor.org/master-key') || + (object.metadata.name == 'blockstor-unlock' && + (!has(object.type) || object.type == 'Opaque')) + message: >- + blockstor may create only the Secrets blockstor-master-key (type + blockstor.org/master-key) and blockstor-unlock (type Opaque) + reason: Forbidden +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: blockstor-secret-create +spec: + policyName: blockstor-secret-create + validationActions: [Deny] +{{- end }} diff --git a/packages/system/linstor/tests/blockstor_secrets_policy_test.yaml b/packages/system/linstor/tests/blockstor_secrets_policy_test.yaml new file mode 100644 index 000000000..2b77ec989 --- /dev/null +++ b/packages/system/linstor/tests/blockstor_secrets_policy_test.yaml @@ -0,0 +1,90 @@ +# RBAC cannot limit a Secret create by name, so this policy is what keeps a +# compromised blockstor pod from minting a token Secret for one of piraeus's +# ServiceAccounts under a name its get already covers. It must reach nothing +# but blockstor's own creates in its own namespace. +suite: blockstor Secret create policy +templates: + - templates/blockstor-secrets-policy.yaml +release: + name: linstor + namespace: cozy-linstor +# helm unittest's default API versions do not include it, and the template +# renders only where the cluster serves it. +capabilities: + apiVersions: + - admissionregistration.k8s.io/v1/ValidatingAdmissionPolicy +set: + backend: blockstor +tests: + - it: renders nothing under the LINSTOR backend + set: + backend: linstor + asserts: + - hasDocuments: + count: 0 + + - it: matches only Secret creates in the release namespace + documentSelector: + path: kind + value: ValidatingAdmissionPolicy + asserts: + - equal: + path: spec.matchConstraints + value: + namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: cozy-linstor + resourceRules: + - apiGroups: [""] + apiVersions: [v1] + operations: [CREATE] + resources: [secrets] + - equal: + path: spec.failurePolicy + value: Fail + + - it: applies only to the blockstor ServiceAccounts of the release namespace + documentSelector: + path: kind + value: ValidatingAdmissionPolicy + asserts: + - lengthEqual: + path: spec.matchConditions + count: 1 + - equal: + path: spec.matchConditions[0].expression + value: >- + request.userInfo.username in [ + 'system:serviceaccount:cozy-linstor:blockstor-apiserver', + 'system:serviceaccount:cozy-linstor:blockstor-controller', + 'system:serviceaccount:cozy-linstor:blockstor-satellite' + ] + + - it: admits only the keyring and the unlock Secret, each with its type + documentSelector: + path: kind + value: ValidatingAdmissionPolicy + asserts: + - lengthEqual: + path: spec.validations + count: 1 + - matchRegex: + path: spec.validations[0].expression + pattern: "object.metadata.name == 'blockstor-master-key' &&\\s+has\\(object.type\\) && object.type == 'blockstor.org/master-key'" + - matchRegex: + path: spec.validations[0].expression + pattern: "object.metadata.name == 'blockstor-unlock' &&\\s+\\(!has\\(object.type\\) \\|\\| object.type == 'Opaque'\\)" + - notMatchRegex: + path: spec.validations[0].expression + pattern: linstor-passphrase + + - it: denies through a binding without its own selector + documentSelector: + path: kind + value: ValidatingAdmissionPolicyBinding + asserts: + - equal: + path: spec + value: + policyName: blockstor-secret-create + validationActions: [Deny] From 26435fc0fd75e5592b8b6926c5beda64afe4ab00 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 16 Nov 2026 11:48:15 -0500 Subject: [PATCH 11/18] feat(linstor): unlock blockstor from piraeus's passphrase Secret From v0.3.0 every blockstor component finds the Secret that unlocks the master key through ControllerConfig/default, in the piraeus shape: linstor-passphrase, key MASTER_PASSPHRASE. Naming it is what lets a cluster migrated from LINSTOR keep its passphrase, and what blockstor's runbook assumes under Cozystack. The field is set by a post-install/post-upgrade Job rather than by a ControllerConfig in the release. Helm resolves every kind of a release before applying any, and the CRD is a template of this release, so the object would fail the first install of the backend. blockstor also creates and writes the same object at runtime, so the Job server-side applies only passphraseSecretRef under its own field manager and leaves the rest to blockstor. The controller does nothing with the keyring until the reference is there, so starting first is harmless. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../templates/blockstor-controllerconfig.yaml | 115 ++++++++++++++++++ .../blockstor_controllerconfig_test.yaml | 92 ++++++++++++++ packages/system/linstor/values.yaml | 6 + 3 files changed, 213 insertions(+) create mode 100644 packages/system/linstor/templates/blockstor-controllerconfig.yaml create mode 100644 packages/system/linstor/tests/blockstor_controllerconfig_test.yaml diff --git a/packages/system/linstor/templates/blockstor-controllerconfig.yaml b/packages/system/linstor/templates/blockstor-controllerconfig.yaml new file mode 100644 index 000000000..b098bed1c --- /dev/null +++ b/packages/system/linstor/templates/blockstor-controllerconfig.yaml @@ -0,0 +1,115 @@ +{{- if eq .Values.backend "blockstor" }} +{{- $_ := include "blockstor.secretNames" . }} +{{- $hook := dict "helm.sh/hook" "post-install,post-upgrade" "helm.sh/hook-delete-policy" "before-hook-creation,hook-succeeded" }} +{{- /* + Points ControllerConfig/default at the passphrase Secret, which is how + every blockstor component finds the Secret that unlocks the master key. + + A Job rather than a ControllerConfig in the release, for two reasons. + The CRD is a template of this same release, and Helm resolves every + kind in a release before it applies any, so a ControllerConfig here + fails the first install of the blockstor backend on a kind that does not + exist yet. And blockstor writes the same object at runtime (controller + properties, node connections) and creates it on first use, so the chart + owns one field, not the object: a server-side apply under its own field + manager sets passphraseSecretRef and leaves the rest alone, on a + ControllerConfig blockstor or linstor-migrate created as well as on a + missing one. --force-conflicts makes the value authoritative over a ref + set by hand. + + The controller may start before this runs. That costs nothing: with no + ref it unlocks nothing and creates no keyring, and it picks the ref up + when it changes. */}} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: blockstor-controllerconfig + namespace: {{ .Release.Namespace }} + annotations: + {{- toYaml $hook | nindent 4 }} + helm.sh/hook-weight: "-1" +--- +{{- /* + An apply that finds no object creates it, which needs create, and create + cannot be limited by name. ControllerConfig is a singleton named + default; blockstor reads no other. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: blockstor-controllerconfig + annotations: + {{- toYaml $hook | nindent 4 }} + helm.sh/hook-weight: "-1" +rules: + - apiGroups: [blockstor.org] + resources: [controllerconfigs] + resourceNames: [default] + verbs: [get, patch] + - apiGroups: [blockstor.org] + resources: [controllerconfigs] + verbs: [create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: blockstor-controllerconfig + annotations: + {{- toYaml $hook | nindent 4 }} + helm.sh/hook-weight: "-1" +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: blockstor-controllerconfig +subjects: + - kind: ServiceAccount + name: blockstor-controllerconfig + namespace: {{ .Release.Namespace }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: blockstor-controllerconfig + namespace: {{ .Release.Namespace }} + annotations: + {{- toYaml $hook | nindent 4 }} +spec: + {{- /* The CRD can take a moment to be served after a first install. */}} + backoffLimit: 6 + activeDeadlineSeconds: 300 + template: + spec: + serviceAccountName: blockstor-controllerconfig + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 65534 + runAsGroup: 65534 + seccompProfile: {type: RuntimeDefault} + containers: + - name: apply + image: {{ .Values.kubectl.image.repository }}:{{ .Values.kubectl.image.tag }} + imagePullPolicy: IfNotPresent + command: [sh, -ec, 'printf "%s\n" "$MANIFEST" | kubectl apply --server-side --field-manager=cozystack-linstor --force-conflicts -f -'] + env: + - name: HOME + value: /tmp + - name: MANIFEST + value: | + apiVersion: blockstor.org/v1alpha1 + kind: ControllerConfig + metadata: + name: default + spec: + passphraseSecretRef: + name: {{ .Values.blockstorPassphraseSecret }} + key: MASTER_PASSPHRASE + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + volumeMounts: + - {name: tmp, mountPath: /tmp} + volumes: + - {name: tmp, emptyDir: {}} +{{- end }} diff --git a/packages/system/linstor/tests/blockstor_controllerconfig_test.yaml b/packages/system/linstor/tests/blockstor_controllerconfig_test.yaml new file mode 100644 index 000000000..d708e887e --- /dev/null +++ b/packages/system/linstor/tests/blockstor_controllerconfig_test.yaml @@ -0,0 +1,92 @@ +# Every blockstor component finds the Secret that unlocks the master key +# through ControllerConfig/default. The chart sets that one field from a hook, +# because the CRD ships in this same release and blockstor writes the rest of +# the object at runtime. +suite: blockstor ControllerConfig passphrase reference +templates: + - templates/blockstor-controllerconfig.yaml +release: + name: linstor + namespace: cozy-linstor +set: + backend: blockstor +tests: + - it: renders nothing under the LINSTOR backend + set: + backend: linstor + asserts: + - hasDocuments: + count: 0 + + - it: runs after every install and upgrade, and cleans up after itself + asserts: + - equal: + path: metadata.annotations["helm.sh/hook"] + value: post-install,post-upgrade + - equal: + path: metadata.annotations["helm.sh/hook-delete-policy"] + value: before-hook-creation,hook-succeeded + + - it: points passphraseSecretRef at piraeus's Secret, key MASTER_PASSPHRASE + documentSelector: + path: kind + value: Job + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: MANIFEST + value: | + apiVersion: blockstor.org/v1alpha1 + kind: ControllerConfig + metadata: + name: default + spec: + passphraseSecretRef: + name: linstor-passphrase + key: MASTER_PASSPHRASE + + - it: follows the passphrase Secret value + set: + blockstorPassphraseSecret: my-passphrase + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: spec.template.spec.containers[0].env[1].value + pattern: '(?m)^ name: my-passphrase$' + + - it: owns only the fields it applies, and wins over a ref set by hand + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'kubectl apply --server-side --field-manager=cozystack-linstor --force-conflicts -f -' + + - it: pins its image by digest + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: spec.template.spec.containers[0].image + pattern: '^[^@]+:[^@]+@sha256:[0-9a-f]{64}$' + + - it: may touch no ControllerConfig but default, and nothing else + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: rules + value: + - apiGroups: [blockstor.org] + resources: [controllerconfigs] + resourceNames: [default] + verbs: [get, patch] + - apiGroups: [blockstor.org] + resources: [controllerconfigs] + verbs: [create] diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index e376866ff..527fdfd73 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -43,6 +43,12 @@ blockstorSatellite: # chart renders it into ControllerConfig.spec.passphraseSecretRef and into # the Secret names the blockstor Roles grant. blockstorPassphraseSecret: linstor-passphrase +# Runs the hook Job that writes blockstorPassphraseSecret into +# ControllerConfig/default. The same pin the other cozystack hook Jobs use. +kubectl: + image: + repository: docker.io/alpine/k8s + tag: 1.33.4@sha256:b0523f0a244ddc4c8e055aa335c040d3d78b3ead5528f4544395f7f9f69c7b68 # Talos-specific workarounds (disable for generic Linux like Ubuntu/Debian) talos: enabled: true From 194201d643c7d530fb83aecc705ace9c5ee7191a Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 16 Nov 2026 12:33:14 -0500 Subject: [PATCH 12/18] test(linstor): select TLS documents by name, not by position Both templates render several cert-manager objects, so a positional index silently retargets an assertion whenever a document is added or reordered above it. main now rejects new documentIndex selectors on multi-document templates for exactly that reason. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- packages/system/linstor/tests/apiserver_tls_test.yaml | 8 ++++++-- packages/system/linstor/tests/backend_test.yaml | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/system/linstor/tests/apiserver_tls_test.yaml b/packages/system/linstor/tests/apiserver_tls_test.yaml index 5e4fb7adb..734608e35 100644 --- a/packages/system/linstor/tests/apiserver_tls_test.yaml +++ b/packages/system/linstor/tests/apiserver_tls_test.yaml @@ -22,7 +22,9 @@ set: tests: - it: "issues the client certificate the operator is pointed at, from the blockstor CA" template: templates/blockstor-apiserver-tls.yaml - documentIndex: 3 + documentSelector: + path: metadata.name + value: blockstor-apiserver-client asserts: - isKind: of: Certificate @@ -46,7 +48,9 @@ tests: - it: "serves from the same CA the client certificate validates against" template: templates/blockstor-apiserver-tls.yaml - documentIndex: 2 + documentSelector: + path: metadata.name + value: blockstor-apiserver-server asserts: - isKind: of: Certificate diff --git a/packages/system/linstor/tests/backend_test.yaml b/packages/system/linstor/tests/backend_test.yaml index 0b70e69f3..b535edd81 100644 --- a/packages/system/linstor/tests/backend_test.yaml +++ b/packages/system/linstor/tests/backend_test.yaml @@ -68,9 +68,11 @@ tests: - hasDocuments: count: 2 - equal: + path: spec.ca.secretName + value: linstor-internal-ca + documentSelector: path: kind value: Issuer - documentIndex: 1 # The plunger runs drbdadm against the node's DRBD resources on its own # schedule. Under blockstor those belong to blockstor-satellite alone, so the From 49725a376d9fc36d9c85002e7caa0d7d1bd00f5f Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 16 Nov 2026 12:34:24 -0500 Subject: [PATCH 13/18] fix(linstor): refuse blockstor images from different releases The controller, apiserver and satellite speak one wire protocol and share the CRDs fetched for the controller's tag. Pinning one of them to another release rendered and passed every test, and broke only on a cluster, so the chart now fails the render instead. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../linstor/templates/backend-guard.yaml | 15 ++++++++ .../system/linstor/tests/backend_test.yaml | 34 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/packages/system/linstor/templates/backend-guard.yaml b/packages/system/linstor/templates/backend-guard.yaml index 0089c96ae..75f1dc98e 100644 --- a/packages/system/linstor/templates/backend-guard.yaml +++ b/packages/system/linstor/templates/backend-guard.yaml @@ -7,3 +7,18 @@ any other way, a hand-set component value for one, is checked here too. {{- if not (has .Values.backend (list "linstor" "blockstor")) }} {{- fail (printf "linstor: backend must be \"linstor\" or \"blockstor\", got %q" (toString .Values.backend)) }} {{- end }} +{{- /* +blockstor's three images are one release: the controller, apiserver and +satellite share a wire protocol and the CRDs under definitions/, which +`make update-blockstor-crds` fetches for the controller's tag. Pinning one +of them to another release still renders, and only fails on a cluster. +*/ -}} +{{- if eq .Values.backend "blockstor" }} +{{- $versions := dict }} +{{- range $component := list "blockstorController" "blockstorApiserver" "blockstorSatellite" }} +{{- $_ := set $versions $component (index $.Values $component "image" "tag" | toString | splitList "@" | first) }} +{{- end }} +{{- if ne 1 (values $versions | uniq | len) }} +{{- fail (printf "linstor: the blockstor images must share one release, got controller %q, apiserver %q, satellite %q" $versions.blockstorController $versions.blockstorApiserver $versions.blockstorSatellite) }} +{{- end }} +{{- end }} diff --git a/packages/system/linstor/tests/backend_test.yaml b/packages/system/linstor/tests/backend_test.yaml index b535edd81..0377aa544 100644 --- a/packages/system/linstor/tests/backend_test.yaml +++ b/packages/system/linstor/tests/backend_test.yaml @@ -149,6 +149,40 @@ tests: - hasDocuments: count: 0 + - it: fails the render when one blockstor image is pinned to another release + templates: + - templates/backend-guard.yaml + set: + backend: blockstor + blockstorController.image.tag: 0.2.1@sha256:0000000000000000000000000000000000000000000000000000000000000000 + blockstorApiserver.image.tag: 9.9.9@sha256:0000000000000000000000000000000000000000000000000000000000000000 + blockstorSatellite.image.tag: 9.9.9@sha256:0000000000000000000000000000000000000000000000000000000000000000 + asserts: + - failedTemplate: + errorMessage: 'linstor: the blockstor images must share one release, got controller "0.2.1", apiserver "9.9.9", satellite "9.9.9"' + + # Each component image has its own digest; only the release tag is shared. + - it: accepts blockstor images of one release with distinct digests + templates: + - templates/backend-guard.yaml + set: + backend: blockstor + blockstorController.image.tag: 0.3.0@sha256:1111111111111111111111111111111111111111111111111111111111111111 + asserts: + - hasDocuments: + count: 0 + + # The LINSTOR backend renders none of these images. + - it: does not check the blockstor image release under the LINSTOR backend + templates: + - templates/backend-guard.yaml + set: + backend: linstor + blockstorController.image.tag: 0.2.1 + asserts: + - hasDocuments: + count: 0 + # drbd-reactor in the piraeus satellite pod reads DRBD state from the kernel, # which is the same under either control plane, so its metrics and the alerts # built on them stay. The controller scrape targets the Java controller, which From ced338f4f1b9b2700baa6069c5aa28870b657b54 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Fri, 27 Nov 2026 01:30:49 +0100 Subject: [PATCH 14/18] fix(linstor): pause the satellite rollout until the first adjust The blockstor-satellite DaemonSet took the Kubernetes default update strategy. The satellite reports Ready once its caches have synced, seconds after start, while re-rendering and adjusting every DRBD resource on the node takes minutes: on a test cluster a satellite finished about 110 resources 1.5 to 2.7 minutes after it turned Ready. An image bump therefore rolled every node seconds apart. Hold each node for minReadySeconds, 180 by default, after Ready, one node at a time, and let an operator choose OnDelete to check every node by hand. maxUnavailable takes only 1 or 0 and a surge is refused, because two satellites on one node would both drive its DRBD resources and a wider rollout runs several first passes at once. Readiness never drops after the cache sync, so the pause stops only a satellite that exits or restarts; OnDelete with the per-node checks is the gate for a change in how resources render. The README describes the node-by-node upgrade, what waits for the rollout (the linstor HelmRelease past the upgrade timeout and HelmReleaseNotReady, and the dependent scheduler and gui releases), and that rolling back means reverting the change that brought the version. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- packages/system/linstor/README.md | 21 +++ .../templates/blockstor-satellite.yaml | 42 ++++++ .../tests/blockstor_workloads_test.yaml | 135 ++++++++++++++++++ packages/system/linstor/values.yaml | 24 ++++ 4 files changed, 222 insertions(+) diff --git a/packages/system/linstor/README.md b/packages/system/linstor/README.md index ab5e4f1aa..8f6785bb9 100644 --- a/packages/system/linstor/README.md +++ b/packages/system/linstor/README.md @@ -25,3 +25,24 @@ Drain workloads before a planned node shutdown. The hook has a 60-second work bu Related upstream discussion: [Piraeus orderly shutdown on Talos](https://github.com/piraeusdatastore/piraeus-operator/issues/860). Run `make test` in this directory with Helm, helm-unittest and Python 3.11 or later. The tests cover rendering with each feature flag, resource selection and rechecks, bounded errors and timeouts, dry-run behavior, and logging in the shared pod PID namespace. + +## Upgrading the blockstor satellites + +The `blockstor-satellite` DaemonSet replaces its pods one node at a time and holds the rollout on each node for `blockstorSatellite.minReadySeconds` (180 by default) after the new pod turns Ready. Ready only means the satellite's caches have synced, which takes seconds; its first pass, which re-renders and adjusts every DRBD resource on the node, ended 1.5 to 2.7 minutes after Ready on a test cluster with about 110 resources per node. The default covers that, so first passes on two nodes do not overlap; a node with more resources needs a longer pause. `maxUnavailable` is always 1 and `maxSurge` always 0, and the chart refuses other values: a wider rollout would run several first passes at once, and a second satellite on the node would drive the same DRBD resources. + +The pause stops the rollout only if the satellite exits or restarts within it. Readiness does not drop when resources fail to adjust: a satellite that renders a bad `.res`, or whose `drbdadm adjust` fails, keeps running and stays Ready, and the next node follows once the pause is over. For an upgrade that changes how the satellite renders DRBD resources, the per-node procedure below is the only check that catches that. + +The `linstor` HelmRelease waits for the whole rollout, and every node adds its pause to it: about 3.5 minutes per node at the default. cozystack-operator gives a package upgrade 10 minutes (`--helmrelease-upgrade-timeout`), which covers two nodes with room and three only just. On a larger cluster the first upgrade attempt times out while the DaemonSet keeps rolling; the release retries the upgrade, becomes Ready once the last node is done, and runs its post-upgrade hooks with the attempt that succeeds. Lower `minReadySeconds`, or raise the operator's timeout, if that is not acceptable. Changing either value does not restart the satellites. While the rollout runs: + +- the HelmRelease is not Ready, and `HelmReleaseNotReady` fires once that has lasted 5 minutes, so on a satellite image change for any cluster of two nodes or more; +- `cozystack.linstor-scheduler` and `cozystack.linstor-gui` depend on `cozystack.linstor`, and their own upgrades wait for it. + +For an upgrade that changes how the satellite renders DRBD resources, check each node before the next one goes. Set `blockstorSatellite.updateStrategy.type: OnDelete` in `spec.components.linstor.values` of the `cozystack.linstor` Package before the upgrade, so that nothing moves until a pod is deleted. Run every command below in the `satellite` container of that node's pod, `kubectl -n cozy-linstor exec -c satellite -- `: it holds the rendered `/etc/drbd.d`, and `drbdadm` on the host or in another container reads a different configuration. + +1. Before the upgrade, save `drbdsetup show` and `drbdsetup status --verbose` from every node. +2. Upgrade. The controller and the apiserver roll; the satellites stay on the old version. +3. Delete the satellite pod on one node and wait for the new one to be Ready and for its first pass to finish. Nothing reports the end of the pass yet. Every `.res` file whose rendering the release changes gets a new modification time in `/etc/drbd.d` (`ls -l --time-style=full-iso /etc/drbd.d`), and step 4 shows whether anything is still pending; wait at least 3 minutes after Ready on a node with about a hundred resources. +4. On that node, `drbdadm -d adjust all` prints nothing, `drbdsetup show` differs from the saved copy only where the release notes say it does, and `drbdsetup status` shows every resource in the role, disk and connection state it had before, none of them suspended. If `drbdadm -d adjust all` still prints something, the pass has not finished or has failed: wait and run it again, and read the satellite's log before going on. +5. Repeat steps 3 and 4 for the next node, then set the strategy back to `RollingUpdate`. + +Under `OnDelete` the HelmRelease cannot become Ready until every satellite has been replaced by hand: the upgrade attempt times out and retries, as above, and everything listed above lasts until the last pod, which may be hours. To roll back, first revert the change that brought the new version, the platform version or the `cozystack.linstor` Package values, rather than running `helm rollback`, which helm-controller undoes; then replace the satellites one node at a time the same way. diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml index 2e2f07503..d92b61362 100644 --- a/packages/system/linstor/templates/blockstor-satellite.yaml +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -157,6 +157,48 @@ metadata: app.kubernetes.io/component: blockstor-satellite spec: selector: {matchLabels: {app: blockstor-satellite}} + {{- /* + Without these the DaemonSet takes the Kubernetes default, which moves + to the next node as soon as the new pod is Ready: seconds after start, + long before the satellite has adjusted the node's DRBD resources. + The pause stops the rollout only if the satellite exits or restarts + within it: readiness never drops on an adjust error, so a satellite + that keeps running with failed resources does not stop it. + One node at a time and no surge are not values: a wider rollout runs + several first passes at once, a surge pod would run a second + satellite against the same host DRBD state, and maxUnavailable 0 + with maxSurge 0 is refused by the apiserver. */}} + {{- $strategy := .Values.blockstorSatellite.updateStrategy | default dict }} + {{- $minReady := .Values.blockstorSatellite.minReadySeconds }} + {{- $minReadyErr := printf "linstor: blockstorSatellite.minReadySeconds must be a whole number of seconds, 0 or more, got %s" (toJson $minReady) }} + {{- if not (or (kindIs "float64" $minReady) (kindIs "int64" $minReady) (kindIs "int" $minReady)) }} + {{- fail $minReadyErr }} + {{- end }} + {{- if or (lt (float64 $minReady) 0.0) (ne (float64 $minReady) (float64 (int64 $minReady))) }} + {{- fail $minReadyErr }} + {{- end }} + minReadySeconds: {{ int64 $minReady }} + updateStrategy: + {{- if eq (toString $strategy.type) "RollingUpdate" }} + {{- $rolling := $strategy.rollingUpdate | default dict }} + {{- if not (kindIs "map" $rolling) }} + {{- fail (printf "linstor: blockstorSatellite.updateStrategy.rollingUpdate must be a map, got %s" (toJson $rolling)) }} + {{- end }} + {{- if and (hasKey $rolling "maxUnavailable") (ne (toJson $rolling.maxUnavailable) "1") }} + {{- fail (printf "linstor: blockstorSatellite.updateStrategy.rollingUpdate.maxUnavailable can only be 1, got %s" (toJson $rolling.maxUnavailable)) }} + {{- end }} + {{- if and (hasKey $rolling "maxSurge") (ne (toJson $rolling.maxSurge) "0") }} + {{- fail (printf "linstor: blockstorSatellite.updateStrategy.rollingUpdate.maxSurge can only be 0, got %s" (toJson $rolling.maxSurge)) }} + {{- end }} + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 + maxSurge: 0 + {{- else if eq (toString $strategy.type) "OnDelete" }} + type: OnDelete + {{- else }} + {{- fail (printf "linstor: blockstorSatellite.updateStrategy.type must be \"RollingUpdate\" or \"OnDelete\", got %q" (toString $strategy.type)) }} + {{- end }} template: metadata: labels: diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index c4dafa2ba..50b11cd4d 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -341,6 +341,141 @@ tests: path: spec.template.metadata.annotations["checksum/drbd-conf"] pattern: '^[0-9a-f]{64}$' + # The satellite is Ready once its caches sync, minutes before its first + # adjust pass is done; the Kubernetes default would move to the next node + # right then. The pause covers the pass measured on a test cluster, up + # to 160s after Ready for about 110 resources. + - it: rolls the satellites one node at a time with a pause after Ready + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - equal: + path: spec.minReadySeconds + value: 180 + - equal: + path: spec.updateStrategy + value: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 + maxSurge: 0 + + # Two satellites on one node would both drive its DRBD resources. + - it: never surges a second satellite onto a node + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + set: + blockstorSatellite: + minReadySeconds: 0 + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 + maxSurge: 0 + asserts: + - equal: + path: spec.minReadySeconds + value: 0 + - equal: + path: spec.updateStrategy.rollingUpdate + value: + maxUnavailable: 1 + maxSurge: 0 + + - it: refuses a surge pod + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.updateStrategy.rollingUpdate.maxSurge: 1 + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.updateStrategy.rollingUpdate.maxSurge can only be 0, got 1' + + # Several nodes at once run their first adjust passes together. + - it: refuses a rollout wider than one node + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.updateStrategy.rollingUpdate.maxUnavailable: 5 + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.updateStrategy.rollingUpdate.maxUnavailable can only be 1, got 5' + + - it: refuses a percentage rollout + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.updateStrategy.rollingUpdate.maxUnavailable: 50% + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.updateStrategy.rollingUpdate.maxUnavailable can only be 1, got "50%"' + + # With maxSurge 0 the apiserver refuses it, after the chart's own checks. + - it: refuses a rollout that replaces no node + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.updateStrategy.rollingUpdate.maxUnavailable: 0 + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.updateStrategy.rollingUpdate.maxUnavailable can only be 1, got 0' + + # OnDelete alone: the API keeps a rollingUpdate block it would ignore. + - it: replaces a satellite only when its pod is deleted under OnDelete + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + set: + blockstorSatellite.updateStrategy.type: OnDelete + asserts: + - equal: + path: spec.updateStrategy + value: + type: OnDelete + + - it: refuses an update strategy the DaemonSet does not have + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.updateStrategy.type: Recreate + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.updateStrategy.type must be "RollingUpdate" or "OnDelete", got "Recreate"' + + - it: refuses a negative minReadySeconds + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.minReadySeconds: -1 + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.minReadySeconds must be a whole number of seconds, 0 or more, got -1' + + - it: refuses a minReadySeconds that is not a number + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.minReadySeconds: 2m + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.minReadySeconds must be a whole number of seconds, 0 or more, got "2m"' + + # --set hands a decimal over as a string; the message must still say + # what is wrong with it. + - it: refuses a decimal minReadySeconds given as a string + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.minReadySeconds: "1.5" + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.minReadySeconds must be a whole number of seconds, 0 or more, got "1.5"' + + - it: refuses a decimal minReadySeconds + template: templates/blockstor-satellite.yaml + set: + blockstorSatellite.minReadySeconds: 1.5 + asserts: + - failedTemplate: + errorMessage: 'linstor: blockstorSatellite.minReadySeconds must be a whole number of seconds, 0 or more, got 1.5' + # A SIGTERM must not cut a detached rollback short: the pod outlives the # REST server's shutdown window. - it: gives the controller time to finish a rollback on shutdown diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index 527fdfd73..e85eac749 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -36,6 +36,30 @@ blockstorSatellite: image: repository: ghcr.io/cozystack/blockstor-satellite tag: 0.3.0@sha256:abff381da5425fdf7a6abc0d52006727cf7fe13c438acc79aaea192fc8681cb4 + # How a change to the satellite pod template reaches the nodes. The + # satellite turns Ready once its caches have synced, seconds after + # start; its first pass over the node's DRBD resources ends later and + # does not show in readiness. minReadySeconds holds the rollout on each + # node for that long after Ready, so that first passes on two nodes do + # not overlap. 180 covers the passes measured on a test cluster, 1.5 to + # 2.7 minutes after Ready for about 110 resources per node; a node with + # more resources needs longer. + # The pause stops the rollout only if the satellite exits or restarts + # within it. A satellite that keeps running while resources fail to + # adjust stays Ready, and the next node follows. For an upgrade that + # changes how resources are rendered, use OnDelete and the per-node + # checks in "Upgrading the blockstor satellites" in README.md. + # Every node adds the pause to the rollout, and the HelmRelease upgrade + # waits for the whole rollout: see the same section before raising it. + minReadySeconds: 180 + updateStrategy: + # RollingUpdate replaces one node at a time; OnDelete replaces a pod + # only when it is deleted, for an upgrade checked node by node. + # rollingUpdate may be left out: maxUnavailable can only be 1, since + # several nodes would run their first passes at once, and maxSurge + # only 0, since two satellites on one node would both drive its DRBD + # resources. The chart refuses other values. + type: RollingUpdate # The Secret, in this namespace, whose MASTER_PASSPHRASE key unlocks the # blockstor master key that wraps every LUKS volume password. It is the # Secret piraeus reads for LINSTOR, so a cluster migrated from LINSTOR keeps From 7ebbbd18a0b4e8ec383feccc4cb69f9d07a86b24 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sat, 21 Nov 2026 23:36:32 +0100 Subject: [PATCH 15/18] fix(linstor): drop the CPU limit of the blockstor components With a 500m CPU limit the blockstor controller and every satellite sat at the limit through a burst of volume creates, and idle satellites were throttled in most CPU periods, so each reconcile pass and each create stretched to tens of seconds. The LINSTOR components blockstor replaces run without a CPU limit; the satellite now takes the LINSTOR satellite's requests and memory limit, and the controller and apiserver keep their memory limits. The resources become values so a cluster can size them without patching the chart. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../templates/blockstor-apiserver.yaml | 6 +- .../templates/blockstor-controller.yaml | 6 +- .../templates/blockstor-satellite.yaml | 6 +- .../tests/blockstor_workloads_test.yaml | 80 +++++++++++++++++++ packages/system/linstor/values.yaml | 18 +++++ 5 files changed, 107 insertions(+), 9 deletions(-) diff --git a/packages/system/linstor/templates/blockstor-apiserver.yaml b/packages/system/linstor/templates/blockstor-apiserver.yaml index db908d8ea..51c9b960c 100644 --- a/packages/system/linstor/templates/blockstor-apiserver.yaml +++ b/packages/system/linstor/templates/blockstor-apiserver.yaml @@ -166,9 +166,9 @@ spec: allowPrivilegeEscalation: false capabilities: {drop: [ALL]} seccompProfile: {type: RuntimeDefault} - resources: - requests: {cpu: 50m, memory: 128Mi} - limits: {cpu: 500m, memory: 512Mi} + {{- with .Values.blockstorApiserver.resources }} + resources: {{- toYaml . | nindent 12 }} + {{- end }} volumes: - name: api-tls secret: diff --git a/packages/system/linstor/templates/blockstor-controller.yaml b/packages/system/linstor/templates/blockstor-controller.yaml index 2f8871d26..e4a9b1383 100644 --- a/packages/system/linstor/templates/blockstor-controller.yaml +++ b/packages/system/linstor/templates/blockstor-controller.yaml @@ -169,7 +169,7 @@ spec: allowPrivilegeEscalation: false capabilities: {drop: [ALL]} seccompProfile: {type: RuntimeDefault} - resources: - requests: {cpu: 50m, memory: 64Mi} - limits: {cpu: 500m, memory: 256Mi} + {{- with .Values.blockstorController.resources }} + resources: {{- toYaml . | nindent 12 }} + {{- end }} {{- end }} diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml index d92b61362..7715f9a3c 100644 --- a/packages/system/linstor/templates/blockstor-satellite.yaml +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -295,9 +295,9 @@ spec: subPath: global_common.conf readOnly: true - {name: stream-tls, mountPath: /etc/blockstor/stream-tls, readOnly: true} - resources: - requests: {cpu: 50m, memory: 64Mi} - limits: {cpu: 500m, memory: 512Mi} + {{- with .Values.blockstorSatellite.resources }} + resources: {{- toYaml . | nindent 12 }} + {{- end }} volumes: - {name: dev, hostPath: {path: /dev, type: Directory}} - {name: modules, hostPath: {path: /lib/modules}} diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index 50b11cd4d..64e7db822 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -497,3 +497,83 @@ tests: - equal: path: spec.template.spec.terminationGracePeriodSeconds value: 21 + + # A CPU limit throttles the reconcile passes; the LINSTOR components this + # backend replaces run without one. + - it: sets the controller no CPU limit + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: {cpu: 100m, memory: 64Mi} + limits: {memory: 256Mi} + + - it: sets the apiserver no CPU limit + template: templates/blockstor-apiserver.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: {cpu: 50m, memory: 128Mi} + limits: {memory: 512Mi} + + - it: sizes the satellite as the LINSTOR satellite, without a CPU limit + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: {cpu: 100m, memory: 128Mi} + limits: {memory: 2Gi} + + - it: merges a satellite resources override over the defaults + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + set: + blockstorSatellite.resources.limits.cpu: "2" + blockstorSatellite.resources.requests.cpu: 250m + asserts: + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: {cpu: 250m, memory: 128Mi} + limits: {cpu: "2", memory: 2Gi} + + - it: merges a controller resources override over the defaults + template: templates/blockstor-controller.yaml + documentSelector: + path: kind + value: Deployment + set: + blockstorController.resources.limits.memory: 1Gi + asserts: + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: {cpu: 100m, memory: 64Mi} + limits: {memory: 1Gi} + + - it: drops a default the apiserver override sets to null + template: templates/blockstor-apiserver.yaml + documentSelector: + path: kind + value: Deployment + set: + blockstorApiserver.resources.limits: null + asserts: + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: {cpu: 50m, memory: 128Mi} diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index e85eac749..55b2a9fa0 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -24,18 +24,36 @@ piraeusServer: # Blockstor images are component-versioned: they are released from the # blockstor repository and carry ITS version, so a cozystack release # must not retag them to the cozystack version. +# +# None of the three sets a CPU limit, as the LINSTOR controller and +# satellite do not. CFS throttling under a limit stretches every +# reconcile pass: with 500m the controller and the satellites sat at the +# limit through a burst of volume creates, idle satellites were throttled +# in most CPU periods, and each create took tens of seconds. Memory stays +# limited. A key set here is merged over the default; set it to null to +# drop a default. blockstorController: image: repository: ghcr.io/cozystack/blockstor-controller tag: 0.3.0@sha256:ca5fc964265a1fd9e1153077f0565a9f07532c593bea1182d3b97a38430822ea + resources: + requests: {cpu: 100m, memory: 64Mi} + limits: {memory: 256Mi} blockstorApiserver: image: repository: ghcr.io/cozystack/blockstor-apiserver tag: 0.3.0@sha256:20cf599f8d0ae85a44b237b9d8ad2ca631a1feff3fd387194ef84636b538dd0b + resources: + requests: {cpu: 50m, memory: 128Mi} + limits: {memory: 512Mi} blockstorSatellite: image: repository: ghcr.io/cozystack/blockstor-satellite tag: 0.3.0@sha256:abff381da5425fdf7a6abc0d52006727cf7fe13c438acc79aaea192fc8681cb4 + # The LINSTOR satellite's requests and memory limit. + resources: + requests: {cpu: 100m, memory: 128Mi} + limits: {memory: 2Gi} # How a change to the satellite pod template reaches the nodes. The # satellite turns Ready once its caches have synced, seconds after # start; its first pass over the node's DRBD resources ends later and From b33e3863f161fd9979fae214ec5ef732aa021aee Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Fri, 27 Nov 2026 17:48:00 +0100 Subject: [PATCH 16/18] feat(linstor): pin blockstor v0.4.0 v0.4.0 serves linstor-csi v1.13 at REST API 1.29, deletes storage only when asked to, and carries the DRBD workarounds of the LINSTOR plunger. The CRDs are refreshed from the same tag, so the schema and the binaries that read it stay one release. The DrbdOptions keys the chart and the e2e StorageClasses set all pass the whitelist v0.4.0 enforces, so no parameter has to change. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../definitions/blockstor.org_nodes.yaml | 8 + .../blockstor.org_resourcedefinitions.yaml | 63 +++++- .../definitions/blockstor.org_resources.yaml | 200 +++++++++++++++++- .../definitions/blockstor.org_snapshots.yaml | 63 +++++- .../system/linstor/tests/backend_test.yaml | 2 +- packages/system/linstor/values.yaml | 6 +- 6 files changed, 321 insertions(+), 21 deletions(-) diff --git a/packages/system/linstor/definitions/blockstor.org_nodes.yaml b/packages/system/linstor/definitions/blockstor.org_nodes.yaml index 839c05931..fd3b6357c 100644 --- a/packages/system/linstor/definitions/blockstor.org_nodes.yaml +++ b/packages/system/linstor/definitions/blockstor.org_nodes.yaml @@ -255,6 +255,14 @@ spec: satellite recently?" signal. format: date-time type: string + satelliteIncarnation: + description: |- + satelliteIncarnation identifies the satellite process now running + on this node; every satellite start picks a new one. A Resource + whose status.satelliteIncarnation differs was last reported by an + earlier process, so its state predates the restart and is not + shown. Written by the satellite heartbeat; do not hand-set. + type: string type: object required: - spec diff --git a/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml b/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml index b301767f7..f932e1ad5 100644 --- a/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resourcedefinitions.yaml @@ -251,10 +251,21 @@ spec: properties: passphraseSecretRef: description: |- - passphraseSecretRef references the Secret carrying the LUKS - passphrase under the key `passphrase`. The satellite reads it - via the apiserver during reconcile; the passphrase never lands - on Spec in plaintext. + passphraseSecretRef names a Secret carrying a LUKS passphrase + under the key `passphrase`. + + NOT IMPLEMENTED: setting this does NOT encrypt the volume with + the referenced Secret. A resource definition that sets it gets + per-replica passwords wrapped under the CLUSTER master key, like + every other one, and the referenced Secret opens nothing. + + The field is kept, rather than removed, because it is reserved + as the selector of a non-default key (docs/encryption-keys.md, + stage 2) and removing it would prune the reference out of stored + objects. + While it does nothing, a LUKS-layered resource definition that + sets it gets an `EncryptionKeyIgnored` Condition on each of its + Resources saying so. properties: name: default: "" @@ -350,6 +361,30 @@ spec: items: type: string type: array + peerSlots: + description: |- + peerSlots is the DRBD peer-slot count new replicas of this + definition get, LINSTOR's DrbdRscDfnData.peerSlots. A replica + keeps one bitmap per slot and a peer with a disk takes one, so a + definition holds one replica with a disk more than its slots. + + Resolved once when the definition is created, as LINSTOR resolves + it when the definition's DRBD layer is created: the count the + request names, else the group's peerSlots, else the + PeerSlotsNewResource property of the definition, its group or the + controller, else 7. `rd modify --peer-slots` changes it for + replicas created afterwards. + + Unset means a definition created before blockstor recorded a + count: by blockstor, whose replicas have 15, or by LINSTOR before + an older linstor-migrate adopted it, whose replicas have + LINSTOR's count. The controller records the least count the + superblocks of its replicas with a disk hold once all of them + have told it; until then it is read as 15. + format: int32 + maximum: 31 + minimum: 1 + type: integer props: additionalProperties: type: string @@ -381,6 +416,16 @@ spec: description: ResourceDefinitionVolume is one volume slot inside an RD. properties: + deleteID: + description: |- + deleteID tells this delete of the volume apart from an earlier one of + a volume with the same number. It is written together with the + DELETE flag, and a replica's confirmation in Status.DeletedVolumes + counts only when it carries the same value: a confirmation left over + from the earlier volume must not stand for this one, whose storage + would then never be deleted. + maxLength: 64 + type: string drbdMinor: description: |- drbdMinor is the /dev/drbd device minor for THIS volume, @@ -414,8 +459,13 @@ spec: format: int32 type: integer flags: + description: |- + flags carries LINSTOR's volume definition flags; DELETE is the one + blockstor acts on, see VolumeDefinitionFlagDelete. items: + maxLength: 64 type: string + maxItems: 16 type: array props: additionalProperties: @@ -469,6 +519,11 @@ spec: - sizeKib - volumeNumber type: object + x-kubernetes-validations: + - message: 'the DELETE flag of a volume definition is never cleared: + a replica may already have deleted its volume' + rule: '!has(oldSelf.flags) || !(''DELETE'' in oldSelf.flags) || + (has(self.flags) && ''DELETE'' in self.flags)' type: array x-kubernetes-list-map-keys: - volumeNumber diff --git a/packages/system/linstor/definitions/blockstor.org_resources.yaml b/packages/system/linstor/definitions/blockstor.org_resources.yaml index 8cb1a6737..b72065ef3 100644 --- a/packages/system/linstor/definitions/blockstor.org_resources.yaml +++ b/packages/system/linstor/definitions/blockstor.org_resources.yaml @@ -85,7 +85,7 @@ spec: drbdNodeID is the DRBD-9 node-id assigned to this replica. Per-replica, allocated once and stable for the replica's life — re-numbering a live replica re-maps its DRBD bitmaps and - corrupts peer-to-peer resync. Range 0..15 (drbd-9 max-peers). + corrupts peer-to-peer resync. Range 0..31 (DRBD 9 node ids). clusterIP-style allocation: nil means "controller, allocate"; non-nil is authoritative and NEVER overwritten (restore-safe). @@ -314,6 +314,29 @@ spec: nodeName: description: nodeName is the satellite hosting this replica. type: string + peerSlots: + description: |- + peerSlots is the DRBD peer-slot count this replica's metadata is + created with (`create-md --max-peers`) and its lower disk is sized + for. The controller copies it from the definition when it + allocates the replica's identities, as LINSTOR copies the + definition's count to each replica it creates, so changing the + definition's count later leaves the replicas already there alone. + + Unset means a replica created before blockstor recorded a count: + by blockstor with 15, or by LINSTOR, whose count only the + superblock tells (status.metadataPeerSlots). The controller + records it from there. Settable once: the metadata on disk does + not change with it. + format: int32 + maximum: 31 + minimum: 1 + type: integer + x-kubernetes-validations: + - message: 'peerSlots is settable-once: the replica''s metadata was + created with it' + optionalOldSelf: true + rule: '!oldSelf.hasValue() || self == oldSelf.value()' props: additionalProperties: type: string @@ -479,6 +502,45 @@ spec: status: description: status defines the observed state of Resource properties: + applyFailure: + description: |- + applyFailure is the error of the satellite's last apply pass on + this replica, with the volume sizes that pass was applying. The + satellite sets it when a pass fails and removes it when one + succeeds. A resize that waits for this replica to grow ends with + this error instead of waiting for a pass that keeps failing, as + LINSTOR returns its satellite's error. + properties: + message: + description: message is the error the pass failed with. + type: string + volumes: + description: |- + volumes lists the definition size of each volume the failed pass + was applying. + items: + description: ResourceApplyFailureVolume is the size one volume + had in a failed pass. + properties: + sizeKib: + description: sizeKib is the volume definition size the pass + was applying. + format: int64 + type: integer + volumeNumber: + description: volumeNumber is the volume's number in the + definition. + format: int32 + type: integer + required: + - sizeKib + - volumeNumber + type: object + type: array + required: + - message + type: object + x-kubernetes-map-type: atomic conditions: description: conditions represent the current state of the Resource. items: @@ -609,6 +671,16 @@ spec: parse this token out of `drbdsetup status --verbose`; the field gives them a kubectl-native substitute. properties: + done: + description: |- + done is the progress of the resync running with this peer, as + the `done:` token of the peer-device frame carries it + ("50.31"). DRBD measures it against that resync's own total, + not the volume size, and prints it only while a resync with + this peer runs; empty otherwise. It is what LINSTOR reports as + the peer's `done_percentage` and renders in `SyncTarget(NN%)`. + A string because a CRD has no portable float type. + type: string peerDiskState: description: |- peerDiskState is the peer's DRBD-9 disk_state for this volume @@ -618,6 +690,17 @@ spec: `peer-disk:` token in `drbdsetup events2 --statistics` peer-device frames. type: string + replicationState: + description: |- + replicationState is this volume's DRBD-9 replication state with + this peer, the `replication:` token of the volume's own + peer-device frame. DRBD keeps it per peer and per volume, and + so does LINSTOR (DrbdVolume.volReplState); the connection-level + `replicationState` is whichever volume's frame came last. It is + what `done` belongs to: a two-volume resource can have one + volume in SyncTarget and the other Established or PausedSyncT + on the same connection. + type: string volumeNumber: description: |- volumeNumber is the DRBD-9 volume number this peer-view entry @@ -648,6 +731,39 @@ spec: x-kubernetes-list-map-keys: - peerNodeName x-kubernetes-list-type: map + deletedVolumes: + description: |- + deletedVolumes is this replica's confirmation of volume definition + deletes: the satellite lists a volume here once it has removed the + volume from DRBD and deleted its storage, because its volume + definition is flagged DELETE. The controller removes the volume + definition once every replica of the definition lists it with the + same deleteID. The satellite drops an entry once its volume + definition is gone. Empty on a satellite that predates volume + definition deletes, which therefore holds the definition until it is + upgraded rather than having its volume skipped. + items: + description: |- + DeletedVolumeStatus is one replica's confirmation that it deleted the + volume of a volume definition flagged DELETE. + properties: + deleteID: + description: |- + deleteID is the deleteID of the volume definition the satellite + acted on. + maxLength: 64 + type: string + volumeNumber: + description: volumeNumber is the deleted volume's number. + format: int32 + type: integer + required: + - volumeNumber + type: object + type: array + x-kubernetes-list-map-keys: + - volumeNumber + x-kubernetes-list-type: map drbdMinor: description: |- drbdMinor is a read-only mirror of the volume-0 minor now @@ -687,6 +803,35 @@ spec: description: inUse is whether DRBD reports the resource as primary anywhere. type: boolean + mayPromote: + description: |- + mayPromote is the kernel-reported DRBD-9 `may_promote:` flag + from the same frames, published upstream as + `layer_object.drbd.may_promote`. Unset until observed. + type: boolean + metadataPeerSlots: + description: |- + metadataPeerSlots is the peer-slot count the replica's DRBD + metadata holds, read once from its superblock by the satellite. + A grow sizes the metadata for it, so the device stays at the + definition. A replica created before blockstor recorded counts, + by blockstor with 15 or by LINSTOR with its definition's count, + 7 by default, when it was adopted, gets it as spec.peerSlots + from the controller, never a guess. + format: int32 + maximum: 31 + minimum: 1 + type: integer + promotionScore: + description: |- + promotionScore is the kernel-reported DRBD-9 promotion score of + this replica, parsed from the `promotion_score:` token in + `drbdsetup events2` resource frames. Upstream LINSTOR publishes + it as `layer_object.drbd.promotion_score`, and linstor-csi + reports a volume abnormal on every node whose score is 0 or + missing. Unset until the satellite has observed the resource. + format: int32 + type: integer role: description: |- role is the kernel-reported DRBD-9 role on this node, parsed @@ -699,6 +844,12 @@ spec: ~15 e2e tests `grep role:` from `drbdsetup status`; surfacing it on Status lets them switch to a k8s-native read. type: string + satelliteIncarnation: + description: |- + satelliteIncarnation is the node's status.satelliteIncarnation of + the satellite process that wrote the runtime state above. Written + by the satellite observer with that state; do not hand-set. + type: string suspended: description: |- suspended is the kernel-reported reason for I/O suspension on @@ -741,6 +892,23 @@ spec: allocatedKib: format: int64 type: integer + appliedSizeKib: + description: |- + appliedSizeKib is the volume definition size this replica has + finished applying: the satellite writes it after a pass in which + every layer, the backing volume, LUKS and `drbdadm resize`, + succeeded at that size and the device the consumer sees reads at + least that size. A grow is complete once every diskful replica + reports the new size here. The last replica to grow its + backing runs its `drbdadm resize` after all the others have + grown theirs, and DRBD commits a resize on every connected peer + before the command returns, so at that point the device has the + new size wherever it is attached. The REST API answers a resize + only then, as LINSTOR does, and the satellite reruns + `drbdadm resize` while this lags the definition. Unset until + the first such pass. + format: int64 + type: integer currentGI: description: |- currentGi is the DRBD-9 current generation identifier reported @@ -753,6 +921,18 @@ spec: type: string devicePath: type: string + deviceSizeKib: + description: |- + deviceSizeKib is the size of this replica's DRBD device in KiB, + the `size:` token of `drbdsetup events2 --statistics --full` + device frames. A diskless replica reports the size its peers + agreed on. The controller hands the largest size any replica + reports to a replica that is getting a new lower disk, which + must hold at least that much: the kernel refuses to attach a + disk smaller than the device, and a volume adopted from LINSTOR + can be a few KiB larger than its definition. + format: int64 + type: integer diskState: type: string historyGI: @@ -766,16 +946,16 @@ spec: type: array outOfSyncKib: description: |- - outOfSyncKib is the worst-case "how many KiB this volume is - behind any peer" reported by `drbdsetup events2 --statistics` - peer-device frames. Combined with RD.Spec.VolumeDefinitions - SizeKib, callers compute a sync-progress percentage: - progress = (1 - outOfSyncKib / sizeKib) * 100 + outOfSyncKib is the largest out-of-sync count over this + volume's peers, as `drbdsetup events2 --statistics` peer-device + frames report it. 0 means in sync with every peer. It is not a + resync progress once the replica has more than one peer: the + progress is connections[].peerVolumes[].done. - 0 means fully in sync; sizeKib (or close to it) means fresh - resync hasn't started yet. Surfaced via the REST view layer - so `linstor r l` / piraeus dashboards can render a CDI-style - progress bar without polling drbdsetup themselves. + While the volume is UpToDate and no peer resyncs with this + replica, a change that keeps the count non-zero can reach the + status up to 5 minutes late. A change to or from 0, and any + change during a resync, is written at once. format: int64 type: integer quorum: diff --git a/packages/system/linstor/definitions/blockstor.org_snapshots.yaml b/packages/system/linstor/definitions/blockstor.org_snapshots.yaml index f7f1f0cbd..c34d4383c 100644 --- a/packages/system/linstor/definitions/blockstor.org_snapshots.yaml +++ b/packages/system/linstor/definitions/blockstor.org_snapshots.yaml @@ -63,6 +63,16 @@ spec: spec: description: spec defines the desired state of Snapshot properties: + abortReason: + description: |- + abortReason, once set, records that the controller aborted the + take, and why. It is written in the same update that clears + suspendIO and takeSnapshot, so the abort is on record before any + satellite resumes and holds even if the status write that + follows never lands. An aborted take is over: suspendIO is never + set again and the snapshot is never marked SUCCESSFUL, as LINSTOR + keeps an aborted snapshot definition failed for good. + type: string groupID: description: |- groupID, when non-empty, marks this Snapshot as a member of a @@ -234,6 +244,20 @@ spec: items: description: SnapshotVolumeRef is one volume slot inside a Snapshot. properties: + props: + additionalProperties: + type: string + description: |- + props is the volume definition's property map as it was when the + snapshot was taken, which a restore copies onto the volume it + creates, as LINSTOR does. The block size LINSTOR keeps there is + the one the snapshot's data was written at. A snapshot recorded + before this field existed has none, and its volume definition's + current props stand in. Serialised without omitempty so a volume + definition that had no props is recorded as {} and stays told + apart from a snapshot that recorded nothing. + nullable: true + type: object sizeKib: format: int64 type: integer @@ -316,11 +340,36 @@ spec: x-kubernetes-list-map-keys: - type x-kubernetes-list-type: map + deleteFailures: + description: |- + deleteFailures records, per node, why the satellite's last + attempt to delete its copy of a deleting snapshot failed. The + delete call answers with it at once, as LINSTOR answers with the + error its satellite returned, instead of waiting on a node that + is alive but keeps failing. + items: + description: |- + SnapshotDeleteFailure is the error one satellite hit deleting its + copy of the snapshot. + properties: + message: + type: string + nodeName: + type: string + required: + - message + - nodeName + type: object + type: array + x-kubernetes-list-map-keys: + - nodeName + x-kubernetes-list-type: map flags: description: |- - flags carries terminal-state markers. Currently only - "FAILED" is meaningful — stamped by the satellite when - CreateSnapshot returns a non-retryable error class. + flags carries terminal-state markers: "SUCCESSFUL" once the + take completed on every targeted node, "FAILED" when a + satellite's CreateSnapshot returned a non-retryable error, and + "FAILED_DISCONNECT" when the controller aborted a take that hung. items: type: string type: array @@ -349,6 +398,14 @@ spec: type: string ready: type: boolean + storagePool: + description: |- + storagePool is the pool that holds this node's copy: the pool of + the replica it was taken from. The local satellite records it once + its copy exists, because the copy outlives the replica and a + restore has to be placed in the same pool, the way LINSTOR keeps + the pool on each snapshot volume. + type: string suspendIOAcked: description: |- suspendIOAcked is stamped true by the local satellite once diff --git a/packages/system/linstor/tests/backend_test.yaml b/packages/system/linstor/tests/backend_test.yaml index 0377aa544..24e45ddfd 100644 --- a/packages/system/linstor/tests/backend_test.yaml +++ b/packages/system/linstor/tests/backend_test.yaml @@ -167,7 +167,7 @@ tests: - templates/backend-guard.yaml set: backend: blockstor - blockstorController.image.tag: 0.3.0@sha256:1111111111111111111111111111111111111111111111111111111111111111 + blockstorController.image.tag: 0.4.0@sha256:1111111111111111111111111111111111111111111111111111111111111111 asserts: - hasDocuments: count: 0 diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index 55b2a9fa0..9a4d94d37 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -35,21 +35,21 @@ piraeusServer: blockstorController: image: repository: ghcr.io/cozystack/blockstor-controller - tag: 0.3.0@sha256:ca5fc964265a1fd9e1153077f0565a9f07532c593bea1182d3b97a38430822ea + tag: 0.4.0@sha256:b7526472c26475abba333b2f6d3a6a2b5c51b90ef878752490c8de85a0799075 resources: requests: {cpu: 100m, memory: 64Mi} limits: {memory: 256Mi} blockstorApiserver: image: repository: ghcr.io/cozystack/blockstor-apiserver - tag: 0.3.0@sha256:20cf599f8d0ae85a44b237b9d8ad2ca631a1feff3fd387194ef84636b538dd0b + tag: 0.4.0@sha256:7b869c114cee4fea9092be03758749df2e19096d99791336f0ee94d5d3de16d0 resources: requests: {cpu: 50m, memory: 128Mi} limits: {memory: 512Mi} blockstorSatellite: image: repository: ghcr.io/cozystack/blockstor-satellite - tag: 0.3.0@sha256:abff381da5425fdf7a6abc0d52006727cf7fe13c438acc79aaea192fc8681cb4 + tag: 0.4.0@sha256:36670bf2e50a845bcb40dc3f2dd2fb64f4fe6e3671a07865a423a169b3da190e # The LINSTOR satellite's requests and memory limit. resources: requests: {cpu: 100m, memory: 128Mi} From eed86349a834f88eb2189a3394ddf00f839ae9ef Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Fri, 27 Nov 2026 17:48:34 +0100 Subject: [PATCH 17/18] feat(linstor): let the satellite act on a stalled resync Without its act flag the satellite only reports a stalled resync (LINBIT/drbd#149) as an Event, and the replica stays Inconsistent until someone runs the drbdadm commands by hand. Production clusters should recover on their own, so blockstorSatellite.stalledResyncAct turns the action on and defaults to true. The flag arrived in blockstor 0.4.0, the release the chart pins, and the backend guard keeps the three images on one release, so the chart passes it without checking the satellite's version. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../templates/blockstor-satellite.yaml | 3 +++ .../tests/blockstor_workloads_test.yaml | 24 +++++++++++++++++++ packages/system/linstor/values.yaml | 10 ++++++++ 3 files changed, 37 insertions(+) diff --git a/packages/system/linstor/templates/blockstor-satellite.yaml b/packages/system/linstor/templates/blockstor-satellite.yaml index 7715f9a3c..a4c47daef 100644 --- a/packages/system/linstor/templates/blockstor-satellite.yaml +++ b/packages/system/linstor/templates/blockstor-satellite.yaml @@ -251,6 +251,9 @@ spec: - --stream-tls-cert-file=/etc/blockstor/stream-tls/tls.crt - --stream-tls-key-file=/etc/blockstor/stream-tls/tls.key - --stream-tls-ca-file=/etc/blockstor/stream-tls/ca.crt + {{- if .Values.blockstorSatellite.stalledResyncAct }} + - --drbd-workaround-stalled-resync-act + {{- end }} env: - name: NODE_NAME valueFrom: {fieldRef: {fieldPath: spec.nodeName}} diff --git a/packages/system/linstor/tests/blockstor_workloads_test.yaml b/packages/system/linstor/tests/blockstor_workloads_test.yaml index 64e7db822..2533a7b6e 100644 --- a/packages/system/linstor/tests/blockstor_workloads_test.yaml +++ b/packages/system/linstor/tests/blockstor_workloads_test.yaml @@ -577,3 +577,27 @@ tests: path: spec.template.spec.containers[0].resources value: requests: {cpu: 50m, memory: 128Mi} + + # Without the act flag the satellite only reports a stalled resync, and a + # replica caught in LINBIT/drbd#149 stays Inconsistent for good. + - it: lets the satellite act on a stalled resync by default + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - contains: + path: spec.template.spec.containers[0].args + content: --drbd-workaround-stalled-resync-act + + - it: keeps the stalled-resync check report-only when turned off + template: templates/blockstor-satellite.yaml + documentSelector: + path: kind + value: DaemonSet + set: + blockstorSatellite.stalledResyncAct: false + asserts: + - notContains: + path: spec.template.spec.containers[0].args + content: --drbd-workaround-stalled-resync-act diff --git a/packages/system/linstor/values.yaml b/packages/system/linstor/values.yaml index 9a4d94d37..c893de51d 100644 --- a/packages/system/linstor/values.yaml +++ b/packages/system/linstor/values.yaml @@ -54,6 +54,16 @@ blockstorSatellite: resources: requests: {cpu: 100m, memory: 128Mi} limits: {memory: 2Gi} + # Lets the satellite act on a stalled resync (LINBIT/drbd#149) instead + # of only reporting it as a Warning Event: after the stall has lasted + # several passes it disconnects the peer whose resync waits on the + # stalled one, on a replica that is an Inconsistent SyncTarget. With a + # Primary in sight it never reconnects a peer to break the stall, since + # such a reconnect left two Secondaries with different data while DRBD + # reported both UpToDate. On by default: a replica stuck Inconsistent + # does not recover without it. The flag exists from blockstor 0.4.0 on; + # an older satellite exits on it. + stalledResyncAct: true # How a change to the satellite pod template reaches the nodes. The # satellite turns Ready once its caches have synced, seconds after # start; its first pass over the node's DRBD resources ends later and From 71ab2602391826aedc5cce158ac8fe865b2836aa Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Fri, 27 Nov 2026 21:00:42 +0100 Subject: [PATCH 18/18] fix(linstor): keep scheduler and GUI off a stale endpoint on a switch Under backend blockstor linstor-scheduler and linstor-gui read the API endpoint from the LinstorCluster the linstor release renders. The backend reaches both charts in one platform render, and dependsOn holds them back only while the linstor release is not Ready, so on a switch they can upgrade before the linstor release has written externalController. They then fell back to the values, linstor-controller, a Service piraeus-operator removes in external mode, and nothing rendered them again: the scheduler stayed pointed at a deleted controller. Fail the render instead while the LinstorCluster names no external controller. The platform's HelmReleases use the RetryOnFailure strategy, and a failed render stores no release, so helm-controller retries after the retry interval without counting a failure until the linstor release has written the endpoint. Under backend linstor nothing changes. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- packages/system/linstor-gui/README.md | 2 +- .../system/linstor-gui/templates/_helpers.tpl | 19 ++++++++----- .../linstor-gui/tests/api_client_test.yaml | 14 +++++----- packages/system/linstor-gui/values.yaml | 2 +- .../linstor-scheduler/templates/_helpers.tpl | 27 +++++++++++++------ .../tests/api_client_test.yaml | 17 +++++------- packages/system/linstor-scheduler/values.yaml | 5 ++-- 7 files changed, 49 insertions(+), 37 deletions(-) diff --git a/packages/system/linstor-gui/README.md b/packages/system/linstor-gui/README.md index 8f13f02e7..4ce6829d4 100644 --- a/packages/system/linstor-gui/README.md +++ b/packages/system/linstor-gui/README.md @@ -60,6 +60,6 @@ then open . | Name | Description | Value | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- | -| `linstor.backend` | Storage backend the platform runs, `linstor` or `blockstor`. Under `blockstor` the endpoint and client Secret are read from the LinstorCluster the `linstor` package renders, and the two values below apply only while it runs an in-cluster controller. | `linstor` | +| `linstor.backend` | Storage backend the platform runs, `linstor` or `blockstor`. Under `blockstor` the endpoint and client Secret are read from the LinstorCluster the `linstor` package renders, the render fails until that object names an external controller, and the two values below apply only under `linstor`. | `linstor` | | `linstor.endpoint` | In-cluster URL of the LINSTOR controller REST API (HTTPS, mTLS) | `https://linstor-controller.cozy-linstor.svc:3371` | | `linstor.clientSecret` | Kubernetes Secret with `tls.crt`, `tls.key`, `ca.crt` used as the mTLS client certificate against the LINSTOR controller. Created by the `linstor` package. | `linstor-client-tls` | diff --git a/packages/system/linstor-gui/templates/_helpers.tpl b/packages/system/linstor-gui/templates/_helpers.tpl index cfdc2b4bd..699df70bb 100644 --- a/packages/system/linstor-gui/templates/_helpers.tpl +++ b/packages/system/linstor-gui/templates/_helpers.tpl @@ -25,10 +25,14 @@ which name the in-cluster controller and the Secret piraeus-operator issues for it. Under backend blockstor the linstor package decides: it renders the LinstorCluster that points piraeus-operator, and through it linstor-csi, at the API, so this chart reads the same two fields and follows wherever they -point. A LinstorCluster still running an in-cluster controller leaves the -values in effect. The package depends on cozystack.linstor, so the -LinstorCluster exists before this chart renders; a render that finds none, or -more than one, fails rather than guess. +point. The package depends on cozystack.linstor, so the LinstorCluster +exists before this chart renders; a render that finds none, or more than one, +fails rather than guess. One without externalController fails as well: on a +backend switch this release can upgrade before the linstor release has +rewritten the LinstorCluster, and falling back to the values would leave the +GUI on linstor-controller, which piraeus-operator removes, with nothing to +render it again. Failing keeps the HelmRelease retrying until the endpoint is +there. */}} {{- define "linstor-gui.apiClient" -}} {{- $backend := .Values.linstor.backend | default "linstor" -}} @@ -43,10 +47,11 @@ more than one, fails rather than guess. {{- fail (printf "linstor.backend is blockstor, so the LINSTOR API endpoint is read from the LinstorCluster the linstor package renders, but the cluster has %d LinstorClusters" (len $clusters)) -}} {{- end -}} {{- $spec := (index $clusters 0).spec | default dict -}} -{{- with dig "externalController" "url" "" $spec -}} -{{- $endpoint = . -}} -{{- $clientSecret = dig "apiTLS" "clientSecretName" "linstor-client-tls" $spec -}} +{{- $endpoint = dig "externalController" "url" "" $spec -}} +{{- if not $endpoint -}} +{{- fail "linstor.backend is blockstor, but the LinstorCluster has no spec.externalController.url yet: the linstor release has not switched it to blockstor-apiserver. This release is retried until it has" -}} {{- end -}} +{{- $clientSecret = dig "apiTLS" "clientSecretName" "linstor-client-tls" $spec -}} {{- end -}} endpoint: {{ $endpoint | quote }} clientSecret: {{ $clientSecret | quote }} diff --git a/packages/system/linstor-gui/tests/api_client_test.yaml b/packages/system/linstor-gui/tests/api_client_test.yaml index 44b674449..db96411aa 100644 --- a/packages/system/linstor-gui/tests/api_client_test.yaml +++ b/packages/system/linstor-gui/tests/api_client_test.yaml @@ -83,9 +83,10 @@ tests: secretName: linstor-client-tls defaultMode: 0444 - # While a LinstorCluster still runs its own controller under blockstor, - # that controller is the API linstor-csi uses, so this chart stays on it. - - it: keeps the values while the LinstorCluster runs an in-cluster controller + # On a backend switch this release can upgrade before the linstor release + # has written externalController. Falling back to the values would leave + # the GUI on linstor-controller for good; failing has Flux retry it. + - it: refuses blockstor while the LinstorCluster has no external controller yet set: linstor.backend: blockstor kubernetesProvider: @@ -95,11 +96,10 @@ tests: apiVersion: piraeus.io/v1 metadata: {name: linstorcluster} spec: {} - template: templates/configmap-nginx.yaml + template: templates/deployment.yaml asserts: - - matchRegex: - path: data["nginx.conf"] - pattern: "proxy_pass https://linstor-controller.cozy-linstor.svc:3371;" + - failedTemplate: + errorPattern: "linstor.backend is blockstor, but the LinstorCluster has no spec.externalController.url yet" - it: refuses blockstor when no LinstorCluster tells it where the API is set: diff --git a/packages/system/linstor-gui/values.yaml b/packages/system/linstor-gui/values.yaml index 48414c905..efc91e535 100644 --- a/packages/system/linstor-gui/values.yaml +++ b/packages/system/linstor-gui/values.yaml @@ -12,7 +12,7 @@ image: ## @param replicas Number of linstor-gui replicas replicas: 1 ## @section LINSTOR controller connection -## @param linstor.backend Storage backend the platform runs, `linstor` or `blockstor`. Under `blockstor` the endpoint and client Secret are read from the LinstorCluster the `linstor` package renders, and the two values below apply only while it runs an in-cluster controller. +## @param linstor.backend Storage backend the platform runs, `linstor` or `blockstor`. Under `blockstor` the endpoint and client Secret are read from the LinstorCluster the `linstor` package renders, the render fails until that object names an external controller, and the two values below apply only under `linstor`. ## @param linstor.endpoint In-cluster URL of the LINSTOR controller REST API (HTTPS, mTLS) ## @param linstor.clientSecret Kubernetes Secret with `tls.crt`, `tls.key`, `ca.crt` used as the mTLS client certificate against the LINSTOR controller. Created by the `linstor` package. linstor: diff --git a/packages/system/linstor-scheduler/templates/_helpers.tpl b/packages/system/linstor-scheduler/templates/_helpers.tpl index a15579251..3dea1ece5 100644 --- a/packages/system/linstor-scheduler/templates/_helpers.tpl +++ b/packages/system/linstor-scheduler/templates/_helpers.tpl @@ -8,11 +8,20 @@ Under backend linstor it returns nothing: the values name the in-cluster controller and the Secret piraeus-operator issues for it. Under backend blockstor the linstor package decides: it renders the LinstorCluster that points piraeus-operator, and through it linstor-csi, at the API, so the -scheduler reads the same two fields and follows wherever they point. A -LinstorCluster still running an in-cluster controller leaves the values in -effect. The package depends on cozystack.linstor, so the LinstorCluster -exists before this chart renders; a render that finds none, or more than -one, fails rather than guess. +scheduler reads the same two fields and follows wherever they point. The +package depends on cozystack.linstor, so the LinstorCluster exists before +this chart renders; a render that finds none, or more than one, fails rather +than guess. + +A LinstorCluster without externalController fails the render too. The +backend reaches this chart and the linstor chart in the same platform +render, and dependsOn holds this release back only while the linstor release +is not Ready, so on a switch it can upgrade first, against the LinstorCluster +the linstor release has not rewritten yet. Falling back to the values there +would leave the scheduler on linstor-controller, a Service piraeus-operator +removes once it sees externalController, and nothing would render this +release again. Failing keeps the HelmRelease retrying until the linstor +release has written the endpoint. */}} {{- define "linstor-scheduler.cozystack.apiClient" -}} {{- $backend := .Values.linstor.backend | default "linstor" -}} @@ -25,9 +34,11 @@ one, fails rather than guess. {{- fail (printf "linstor-scheduler.linstor.backend is blockstor, so the LINSTOR API endpoint is read from the LinstorCluster the linstor package renders, but the cluster has %d LinstorClusters" (len $clusters)) -}} {{- end -}} {{- $spec := (index $clusters 0).spec | default dict -}} -{{- with dig "externalController" "url" "" $spec }} -endpoint: {{ . | quote }} +{{- $endpoint := dig "externalController" "url" "" $spec -}} +{{- if not $endpoint -}} +{{- fail "linstor-scheduler.linstor.backend is blockstor, but the LinstorCluster has no spec.externalController.url yet: the linstor release has not switched it to blockstor-apiserver. This release is retried until it has" -}} +{{- end }} +endpoint: {{ $endpoint | quote }} clientSecret: {{ dig "apiTLS" "clientSecretName" "linstor-client-tls" $spec | quote }} {{- end -}} -{{- end -}} {{- end }} diff --git a/packages/system/linstor-scheduler/tests/api_client_test.yaml b/packages/system/linstor-scheduler/tests/api_client_test.yaml index f0f2ad77c..deed4eac2 100644 --- a/packages/system/linstor-scheduler/tests/api_client_test.yaml +++ b/packages/system/linstor-scheduler/tests/api_client_test.yaml @@ -74,9 +74,10 @@ tests: path: metadata.annotations["secret.reloader.stakater.com/reload"] value: linstor-client-tls - # While a LinstorCluster still runs its own controller under blockstor, - # that controller is the API linstor-csi uses, so the scheduler stays on it. - - it: keeps the values while the LinstorCluster runs an in-cluster controller + # On a backend switch this release can upgrade before the linstor release + # has written externalController. Falling back to the values would leave + # the scheduler on linstor-controller for good; failing has Flux retry it. + - it: refuses blockstor while the LinstorCluster has no external controller yet set: linstor-scheduler.linstor.backend: blockstor kubernetesProvider: @@ -87,14 +88,8 @@ tests: metadata: {name: linstorcluster} spec: {} asserts: - - contains: - path: spec.template.spec.containers[1].env - content: - name: LS_CONTROLLERS - value: https://linstor-controller.cozy-linstor.svc:3371 - - equal: - path: metadata.annotations["secret.reloader.stakater.com/reload"] - value: linstor-client-tls + - failedTemplate: + errorPattern: "backend is blockstor, but the LinstorCluster has no spec.externalController.url yet" - it: refuses blockstor when no LinstorCluster tells it where the API is set: diff --git a/packages/system/linstor-scheduler/values.yaml b/packages/system/linstor-scheduler/values.yaml index 854ae5940..981c3ad6e 100644 --- a/packages/system/linstor-scheduler/values.yaml +++ b/packages/system/linstor-scheduler/values.yaml @@ -11,8 +11,9 @@ linstor-scheduler: linstor: # The storage backend the platform runs, linstor or blockstor. Under # blockstor the endpoint and client Secret come from the LinstorCluster - # the linstor package renders (templates/_helpers.tpl), and the two - # values below apply only while it runs an in-cluster controller. + # the linstor package renders (templates/_helpers.tpl), the render + # fails until that object names an external controller, and the two + # values below apply only under linstor. backend: linstor endpoint: "https://linstor-controller.cozy-linstor.svc:3371" clientSecret: "linstor-client-tls"