// SPDX-License-Identifier: Apache-2.0 /* Copyright 2026 Cozystack contributors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cli import ( "context" "fmt" "github.com/cockroachdb/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/naming" "github.com/cozystack/blockstor/pkg/store" "github.com/cozystack/blockstor/internal/cli/command" "github.com/cozystack/blockstor/internal/cli/output" "github.com/cozystack/blockstor/internal/cli/table" "github.com/cozystack/blockstor/internal/cli/view" ) // handlers maps a canonical command to its implementation. A command // present in the grammar but absent here is reported as // not-implemented rather than failing obscurely, and // App.UnimplementedCommands lists the gap. // //nolint:gochecknoglobals // static dispatch table var handlers = map[string]handler{ "node list": listing("nodes", func(ctx context.Context, st store.Store) ([]apiv1.Node, error) { return st.Nodes().List(ctx) }, func(node *apiv1.Node, flags *flagSet) bool { return matches(flags.Nodes, node.Name) }, func(nodes []apiv1.Node, _ *runContext) *metav1.Table { return view.NodeList(nodes) }, "State", ), "storage-pool list": listing("storage pools", func(ctx context.Context, st store.Store) ([]apiv1.StoragePool, error) { return st.StoragePools().List(ctx) }, func(pool *apiv1.StoragePool, flags *flagSet) bool { return matches(flags.Nodes, pool.NodeName) && matches(splitList(flags.Values["storage-pools"]), pool.StoragePoolName) }, func(pools []apiv1.StoragePool, _ *runContext) *metav1.Table { return view.StoragePoolList(pools) }, "State", ), "resource-definition list": listing("resource definitions", fetchDefinitions, func(def *apiv1.ResourceDefinition, flags *flagSet) bool { return matches(flags.Resources, def.Name) }, func(defs []apiv1.ResourceDefinition, _ *runContext) *metav1.Table { return view.ResourceDefinitionList(defs) }, "State", ), "resource list": resourceList, "volume list": volumeList, "snapshot list": listing("snapshots", func(ctx context.Context, st store.Store) ([]apiv1.Snapshot, error) { return st.Snapshots().List(ctx) }, func(snap *apiv1.Snapshot, flags *flagSet) bool { return matches(flags.Resources, snap.ResourceName) }, func(snaps []apiv1.Snapshot, _ *runContext) *metav1.Table { return view.SnapshotList(snaps) }, "State", ), "resource-group list": listing("resource groups", func(ctx context.Context, st store.Store) ([]apiv1.ResourceGroup, error) { return st.ResourceGroups().List(ctx) }, func(*apiv1.ResourceGroup, *flagSet) bool { return true }, func(groups []apiv1.ResourceGroup, _ *runContext) *metav1.Table { return view.ResourceGroupList(groups) }, ), "volume-definition list": volumeDefinitionList, "resource-definition create": resourceDefinitionCreate, "resource-definition delete": resourceDefinitionDelete, "node create": nodeCreate, "node delete": nodeDelete, "node evacuate": nodeEvacuate, "node evict": nodeEvacuate, "node restore": nodeRestore, "node lost": nodeLost, "node info": nodeInfo, "volume-definition create": volumeDefinitionCreate, "volume-definition delete": volumeDefinitionDelete, "volume-definition set-size": volumeDefinitionSetSize, "resource create": resourceCreate, "resource delete": resourceDelete, "snapshot create": snapshotCreate, "snapshot delete": snapshotDelete, "resource-definition auto-place": resourceDefinitionAutoPlace, "resource-group spawn-resources": resourceGroupSpawn, "resource-group adjust": resourceGroupAdjust, "resource-group create": resourceGroupCreate, "resource-group modify": resourceGroupModify, "resource-group delete": resourceGroupDelete, "resource toggle-disk": resourceToggleDisk, "resource activate": resourceActivate, "resource deactivate": resourceDeactivate, "resource list-volumes": volumeList, "storage-pool create": storagePoolCreate, "storage-pool delete": storagePoolDelete, "volume-group create": volumeGroupCreate, "volume-group list": volumeGroupList, "encryption create-passphrase": encryptionCreatePassphrase, "encryption enter-passphrase": encryptionEnterPassphrase, "encryption modify-passphrase": encryptionModifyPassphrase, "encryption add-passphrase": encryptionAddPassphrase, "encryption remove-passphrase": encryptionRemovePassphrase, "encryption list-passphrases": encryptionListPassphrases, "resource-definition modify": resourceDefinitionModify, "resource-definition clone": resourceDefinitionClone, "resource-group query-size-info": resourceGroupQuerySizeInfo, "resource-group query-max-volume-size": resourceGroupQuerySizeInfo, "snapshot create-multiple": snapshotCreateMultiple, "snapshot rollback": snapshotRollback, "snapshot resource restore": snapshotRestoreResource, "snapshot resource-definition restore": snapshotRestoreResource, "snapshot volume-definition restore": snapshotRestoreVolumeDefinition, "physical-storage create-device-pool": physicalStorageCreateDevicePool, "physical-storage list": listing("physical devices", func(ctx context.Context, st store.Store) ([]apiv1.PhysicalDevice, error) { return st.PhysicalDevices().List(ctx) }, func(device *apiv1.PhysicalDevice, flags *flagSet) bool { return matches(flags.Nodes, device.NodeName) }, func(devices []apiv1.PhysicalDevice, _ *runContext) *metav1.Table { return view.PhysicalDeviceList(devices) }, ), cmdControllerVersion: controllerVersion, } // propertyNouns maps every noun that carries a property bag to its // accessor. The three property verbs are registered from this one // table so a noun cannot end up with, say, set-property but no // delete-property — a gap an operator would only discover mid-runbook. // //nolint:gochecknoglobals // static dispatch table var propertyNouns = map[string]propertyAccessor{ "resource-definition": rdProps, "node": nodeProps, "controller": controllerProps, "resource": resourceProps, "storage-pool": storagePoolProps, "resource-group": resourceGroupProps, "volume-definition": volumeDefinitionProps, "volume-group": volumeGroupProps, } //nolint:gochecknoinits // wires one static table into another func init() { for noun, accessor := range propertyNouns { handlers[noun+" set-property"] = setProperty(accessor) handlers[noun+" list-properties"] = listProperties(accessor) handlers[noun+" delete-property"] = deleteProperty(accessor) if command.Has(noun, "drbd-options") { handlers[noun+" drbd-options"] = drbdOptions(accessor) } } } // listing builds a handler for the shared list shape: fetch, filter, // then either the machine envelope or a rendered table. Keeping that // shape in one place means a new listing cannot accidentally skip the // `-m` branch or the filters. func listing[T any]( label string, fetch func(context.Context, store.Store) ([]T, error), keep func(*T, *flagSet) bool, build func([]T, *runContext) *metav1.Table, stateColumns ...string, ) handler { return func(ctx context.Context, run *runContext) error { items, err := fetch(ctx, run.Store) if err != nil { return fmt.Errorf("list %s: %w", label, err) } kept := make([]T, 0, len(items)) for i := range items { if keep(&items[i], run.Flags) { kept = append(kept, items[i]) } } kept = applyLimit(kept, run.Flags) if run.Flags.Machine { return machineOut(run, kept) } return run.render(build(kept, run), stateColumns...) } } func fetchResources(ctx context.Context, st store.Store) ([]apiv1.Resource, error) { return st.Resources().List(ctx) //nolint:wrapcheck // listing() adds the context } func fetchDefinitions(ctx context.Context, st store.Store) ([]apiv1.ResourceDefinition, error) { return st.ResourceDefinitions().List(ctx) //nolint:wrapcheck // listing() adds the context } func keepResource(res *apiv1.Resource, flags *flagSet) bool { return matches(flags.Nodes, res.NodeName) && matches(flags.Resources, res.Name) } // keepFaulty applies --faulty as part of the FILTER, not as a rendering // decision. Filtering during render would leave `-m` — which skips the // renderer — returning every replica for a command whose whole point is // to narrow to the broken ones. func keepFaulty(resources []apiv1.Resource, defProps map[string]map[string]string, flags *flagSet) []apiv1.Resource { if !flags.Faulty { return resources } kept := resources[:0] for i := range resources { if view.IsFaulty(&resources[i], defProps[naming.Key(resources[i].Name)]) { kept = append(kept, resources[i]) } } return kept } // explainSkipDisk prints what a SkipDisk marker in the table means, on // stderr so the table on stdout stays the contract `awk -F'|'` parses. func explainSkipDisk(run *runContext, resources []apiv1.Resource, defProps map[string]map[string]string) { if run.Err == nil { return } for i := range resources { if view.SkipDisk(&resources[i], defProps[naming.Key(resources[i].Name)]) { fmt.Fprint(run.Err, view.SkipDiskHelp) return } } } // volumeList implements `volume list` and `resource list-volumes`: the // shared listing shape, with the replicas stamped with their layer // stacks before either output reads them. func volumeList(ctx context.Context, run *runContext) error { resources, err := fetchResources(ctx, run.Store) if err != nil { return fmt.Errorf("list resources: %w", err) } kept := make([]apiv1.Resource, 0, len(resources)) for i := range resources { if keepResource(&resources[i], run.Flags) { kept = append(kept, resources[i]) } } kept = applyLimit(kept, run.Flags) defProps := withLayerStacks(ctx, run, kept) if run.Flags.Machine { return machineOut(run, kept) } err = run.render(view.VolumeList(kept, defProps), "State") if err == nil { explainSkipDisk(run, kept, defProps) } return err } // volumeDefinitionList implements `volume-definition list` (`vd l`). // // Volume definitions are keyed by their parent definition, so an // unfiltered listing walks every definition rather than silently // showing none. func volumeDefinitionList(ctx context.Context, run *runContext) error { names := run.Flags.Resources if len(names) == 0 { defs, err := fetchDefinitions(ctx, run.Store) if err != nil { return fmt.Errorf("list resource definitions: %w", err) } for i := range defs { names = append(names, defs[i].Name) } } tbl := view.VolumeDefinitionList("", nil) collected := make([]apiv1.VolumeDefinition, 0) for _, name := range names { vds, err := run.Store.VolumeDefinitions().List(ctx, name) if err != nil { return fmt.Errorf("list volume definitions of %s: %w", name, err) } collected = append(collected, vds...) tbl.Rows = append(tbl.Rows, view.VolumeDefinitionList(name, vds).Rows...) } if run.Flags.Machine { return machineOut(run, collected) } return run.render(tbl, "State") } // resourceList implements `resource list`. // // It fetches the volume sizes as well as the replicas, because the // State column renders `SyncTarget(NN%)` from them. Without the sizes // the percentage silently disappeared during exactly the resync an // operator is watching, while the design doc promised it and the // colour classifier went to the trouble of stripping it. // // The replicas are read whole and filtered in process, `-n` and `-r` // included. The filter compares names as the store addresses them // (naming.Same), and a replica's spec keeps whatever case its writer used: // an adoption run or linstor-csi can store `NODE-1` for a node the operator // types as `node-1`. The node- and definition-scoped reads compare the stored // spelling verbatim, as a field selector does (pkg/store/k8s/spellings.go), // so answering a narrowed listing with them returned fewer rows than this // filter finds, with exit status zero; the listing stays whole. func resourceList(ctx context.Context, run *runContext) error { resources, err := fetchResources(ctx, run.Store) if err != nil { return fmt.Errorf("list resources: %w", err) } kept := make([]apiv1.Resource, 0, len(resources)) for i := range resources { if keepResource(&resources[i], run.Flags) { kept = append(kept, resources[i]) } } // Stamped before --faulty reads them: whether a replica is faulty // depends on which layers it has. defProps := withLayerStacks(ctx, run, kept) // Counted before --faulty narrows the rows: a faulty primary whose // second primary is healthy is still one of two. primaries := view.PrimariesByDefinition(kept) kept = keepFaulty(kept, defProps, run.Flags) kept = applyLimit(kept, run.Flags) if run.Flags.Machine { return machineOut(run, kept) } err = run.render(view.ResourceList(view.ResourceListInput{ Resources: kept, VolumeSizesKib: volumeSizesFor(ctx, run, kept), DefinitionProps: defProps, Primaries: primaries, FaultyOnly: run.Flags.Faulty, }), "State", "Conns") if err == nil { explainSkipDisk(run, kept, defProps) } return err } // volumeSizesBulkCutoff is where reading the definitions one at a time stops // being the cheaper of the two reads. Below it a listing narrowed by `-r`, // `-n` or `--limit` pays that many GETs; above it, one request for the lot. // // It counts the definitions the rendered rows cover, not the definitions in // the cluster. The replica read behind those rows is whole whatever the // filter (see resourceList), so this is the one read a narrowing makes // cheaper, and the choice is between two costs rather than a guess about // the cluster: up to the cutoff, that many sequential GETs; past it, one // LIST that carries every definition, those without a replica included. // So `-n` on a node holding more definitions than the cutoff takes the // LIST to render its rows. That is the trade, not an oversight, and // removing it means making the per-definition read concurrent rather than // moving this number. const volumeSizesBulkCutoff = 16 // volumeSizesFor builds the per-volume sizes the sync-percentage column needs. // // Two reads, chosen on how much of the cluster the listing actually covers. // Reading them one definition at a time is what this used to do // unconditionally, and on the Kubernetes store each of those is a GET of one // ResourceDefinition against an uncached client — so `resource list` on a // cluster with a thousand definitions was one LIST plus a thousand sequential // round trips, in the command an operator runs while watching a resync. // Reading them all in one request fixes that and breaks the opposite case: // `resource list -r one-volume` asked about one definition and would pull // every definition in the cluster back to answer it. // // So the listing picks. Either side of the cutoff the answer is identical; // only the number of requests and the size of them differ. // // A read that fails leaves that definition out rather than failing the // listing: the column degrades to a bare state, which is what the // per-definition version did when one of its reads failed. A missing // percentage is a cosmetic loss; an unreadable `resource list` during an // incident is not. func volumeSizesFor(ctx context.Context, run *runContext, resources []apiv1.Resource) map[string]map[int32]int64 { names := distinctDefinitionNames(resources) if len(names) <= volumeSizesBulkCutoff { return volumeSizesPerDefinition(ctx, run, names) } sizes, err := volumeSizesInOneRequest(ctx, run, names) if err == nil { return sizes } if !perDefinitionCanAnswer(ctx, err) { warnSyncColumnUnavailable(run, err) return nil } return volumeSizesPerDefinition(ctx, run, names) } // perDefinitionCanAnswer says whether reading the definitions one at a time // can answer what the single read could not. // // SelectorUnsupported (pkg/store/k8s) draws the same line one layer down, and // for the same reason: a fallback is worth taking when the first read failed // on its shape, not when it ran out of the budget the second read spends // again. A cancelled context and a refusal aimed at the caller rather than at // the request repeat identically once per definition, so the retry buys the // same answer at N times the cost, in the command an operator is running // because something is already wrong. // // A server that asked the caller to slow down is the same case as a refusal, // by the same rule: 429 and 503 say the budget is the problem, and answering // them with one narrow request per definition sends N requests to the server // that just asked for fewer. // // A timeout is deliberately on the other side. One request covering every // definition in the cluster is the read most likely to exceed a deadline, and // the narrow ones after it are each small enough to land. func perDefinitionCanAnswer(ctx context.Context, err error) bool { if ctx.Err() != nil { return false } if apierrors.IsTooManyRequests(err) || apierrors.IsServiceUnavailable(err) { return false } return !apierrors.IsForbidden(err) && !apierrors.IsUnauthorized(err) } // warnSyncColumnUnavailable tells the operator why the percentages are gone. // // The listing still prints: an unreadable `resource list` during an incident // is worse than one without a percentage. But a column that emptied because // every read was refused looks exactly like a cluster with nothing to sync, // and that is the one reading an operator must not take away from it. Stderr, // so the table on stdout stays the contract `awk -F'|'` parses. func warnSyncColumnUnavailable(run *runContext, err error) { if run.Err == nil { return } fmt.Fprintf(run.Err, "warning: sync percentages unavailable: %v\n", err) } // distinctDefinitionNames is the set of definitions a listing covers, in // first-seen order — every replica of one definition asks the same question. func distinctDefinitionNames(resources []apiv1.Resource) []string { seen := make(map[string]struct{}, len(resources)) names := make([]string, 0, len(resources)) for i := range resources { name := resources[i].Name if _, dup := seen[name]; dup { continue } seen[name] = struct{}{} names = append(names, name) } return names } func volumeSizesPerDefinition(ctx context.Context, run *runContext, names []string) map[string]map[int32]int64 { sizes := make(map[string]map[int32]int64, len(names)) var firstErr error for _, name := range names { vds, err := run.Store.VolumeDefinitions().List(ctx, name) if err != nil { if firstErr == nil { firstErr = err } continue } sizes[name] = perVolumeSizes(vds) } // One definition that could not be read is the degradation this path is // documented to accept. None of them read is not a degradation, it is a // failure that reached the operator as an empty column. if len(sizes) == 0 && firstErr != nil { warnSyncColumnUnavailable(run, firstErr) } return sizes } func volumeSizesInOneRequest( ctx context.Context, run *runContext, names []string, ) (map[string]map[int32]int64, error) { all, err := run.Store.VolumeDefinitions().ListAll(ctx) if err != nil { // One read, so one failure costs every row its percentage — where // the per-definition path loses only the definition it could not // read. The caller decides whether that path can do better, since // it cannot for a failure that was never about the read's shape. return nil, errors.Wrap(err, "read every definition's volumes") } sizes := make(map[string]map[int32]int64, len(names)) for _, name := range names { vds, ok := all[naming.Key(name)] if !ok { continue } sizes[name] = perVolumeSizes(vds) } return sizes, nil } // perVolumeSizes keys one definition's volumes the way the view reads them. func perVolumeSizes(vds []apiv1.VolumeDefinition) map[int32]int64 { out := make(map[int32]int64, len(vds)) for i := range vds { out[vds[i].VolumeNumber] = vds[i].SizeKib } return out } // machineOut writes the machine-readable envelope. func machineOut[T any](run *runContext, items []T) error { err := output.MachineList(run.Out, items) if err != nil { return fmt.Errorf("write machine-readable output: %w", err) } return nil } // applyLimit caps a listing at --limit rows; zero is unlimited. The // value was validated at parse time, so a malformed one never reaches // here. func applyLimit[T any](items []T, flags *flagSet) []T { if flags.Limit <= 0 || flags.Limit >= len(items) { return items } return items[:flags.Limit] } // render writes a table, painting the named state columns. func (run *runContext) render(tbl *metav1.Table, stateColumns ...string) error { err := table.Render(run.Out, tbl, table.Options{ Color: run.Color, StateColumns: stateColumns, Pastable: run.Flags.Pastable, }) if err != nil { return fmt.Errorf("render table: %w", err) } return nil }