Skip to content

Commit 283812a

Browse files
Add kubectl device maintenance commands
Add shortcuts for reboot, factory reset, reprovision, phase reset, skip provisioning, and firmware upgrades. Firmware upgrades accept a target URL and optional MD5 checksum. Commands require one device, reject cross-namespace selection, and avoid replacing an existing maintenance request. Signed-off-by: Felix Kästner <felix.kaestner@sap.com>
1 parent 33b9ef5 commit 283812a

6 files changed

Lines changed: 380 additions & 5 deletions

File tree

‎kubectl-net/README.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,23 @@ kubectl net unpause devices leaf1 --recursive
9191
kubectl net pause interfaces --device leaf1
9292
```
9393

94+
### Device maintenance
95+
96+
Maintenance commands annotate one Device and return after the request is accepted by the Kubernetes API. The controller performs the operation asynchronously.
97+
98+
```bash
99+
kubectl net reboot leaf1
100+
kubectl net factory-reset leaf1
101+
kubectl net reprovision leaf1
102+
kubectl net reset-phase leaf1
103+
kubectl net skip-provisioning leaf1
104+
kubectl net firmware-upgrade leaf1 \
105+
--url https://images.example.com/nxos.bin \
106+
--md5 0123456789abcdef
107+
```
108+
109+
All commands require exactly one Device. Firmware upgrades require `--url`; `--md5` is optional. Reboot, factory reset, reprovision, and firmware upgrade prompt for confirmation; use `--yes` in non-interactive workflows.
110+
94111
### Shell completion
95112

96113
```bash

‎kubectl-net/go.mod‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ module github.com/ironcore-dev/network-operator/kubectl-net
33
go 1.27.3
44

55
require (
6-
github.com/ironcore-dev/network-operator v0.0.0-20260827134819-b03d7ae72c7e
6+
github.com/ironcore-dev/network-operator v0.0.0-20260917125130-19eb933a2f91
77
github.com/spf13/cobra v1.10.2
88
github.com/spf13/pflag v1.0.10
99
k8s.io/apimachinery v0.36.2

‎kubectl-net/go.sum‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎kubectl-net/pkg/cmd/maintenance.go‎

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
// SPDX-FileCopyrightText: SAP SE or an SAP affiliate company and IronCore contributors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package cmd
5+
6+
import (
7+
"bufio"
8+
"context"
9+
"encoding/json"
10+
"errors"
11+
"fmt"
12+
"io"
13+
"os"
14+
"strings"
15+
16+
"github.com/spf13/cobra"
17+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
18+
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
19+
"k8s.io/apimachinery/pkg/types"
20+
"k8s.io/cli-runtime/pkg/genericclioptions"
21+
"k8s.io/client-go/dynamic"
22+
23+
"github.com/ironcore-dev/network-operator/api/core/v1alpha1"
24+
)
25+
26+
// MaintenanceOptions holds the configuration for a Device maintenance command.
27+
type MaintenanceOptions struct {
28+
Root *RootOptions
29+
Action string
30+
PrintFlags *genericclioptions.PrintFlags
31+
32+
FirmwareURL string
33+
FirmwareMD5 string
34+
Yes bool
35+
ResourceVersion string
36+
Namespace string
37+
}
38+
39+
// NewCmdMaintenance returns the Device maintenance commands.
40+
func NewCmdMaintenance(root *RootOptions) []*cobra.Command {
41+
actions := []struct {
42+
name string
43+
short string
44+
}{
45+
{v1alpha1.DeviceMaintenanceReboot, "Reboot a Device"},
46+
{v1alpha1.DeviceMaintenanceFactoryReset, "Factory reset a Device"},
47+
{v1alpha1.DeviceMaintenanceReprovision, "Reprovision a Device"},
48+
{v1alpha1.DeviceMaintenanceResetPhase, "Reset a Device phase"},
49+
{v1alpha1.DeviceMaintenanceSkipProvisioning, "Skip provisioning a Device"},
50+
{v1alpha1.DeviceMaintenanceFirmwareUpgrade, "Upgrade Device firmware"},
51+
}
52+
53+
commands := make([]*cobra.Command, 0, len(actions))
54+
for _, action := range actions {
55+
o := &MaintenanceOptions{
56+
Root: root,
57+
Action: action.name,
58+
PrintFlags: genericclioptions.NewPrintFlags(action.name),
59+
}
60+
cmd := &cobra.Command{
61+
Use: action.name + " DEVICE",
62+
Short: action.short,
63+
Args: cobra.ExactArgs(1),
64+
RunE: func(c *cobra.Command, args []string) error {
65+
if err := o.Complete(); err != nil {
66+
return err
67+
}
68+
return o.Run(args[0])
69+
},
70+
}
71+
if maintenanceActionRequiresConfirmation(action.name) {
72+
cmd.Flags().BoolVarP(&o.Yes, "yes", "y", false, "Skip confirmation")
73+
}
74+
if action.name == v1alpha1.DeviceMaintenanceFirmwareUpgrade {
75+
cmd.Flags().StringVar(&o.FirmwareURL, "url", "", "Firmware image URL")
76+
cmd.Flags().StringVar(&o.FirmwareMD5, "md5", "", "Firmware image MD5 checksum")
77+
_ = cmd.MarkFlagRequired("url")
78+
}
79+
o.PrintFlags.AddFlags(cmd)
80+
commands = append(commands, cmd)
81+
}
82+
return commands
83+
}
84+
85+
// Complete resolves the target namespace from the kubeconfig.
86+
func (o *MaintenanceOptions) Complete() error {
87+
if o.Root.AllNamespaces {
88+
return errors.New("a maintenance operation cannot be performed across all namespaces")
89+
}
90+
namespace, _, err := o.Root.ConfigFlags.ToRawKubeConfigLoader().Namespace()
91+
if err != nil {
92+
return err
93+
}
94+
o.Namespace = namespace
95+
return nil
96+
}
97+
98+
// Run annotates a Device to request a maintenance operation.
99+
func (o *MaintenanceOptions) Run(name string) error {
100+
resourceName := "devices." + v1alpha1.GroupVersion.Group
101+
result, err := buildResourceResult(o.Root.ConfigFlags, o.Namespace, false, resourceName, []string{name}, "")
102+
if err != nil {
103+
return err
104+
}
105+
infos, err := result.Infos()
106+
if err != nil {
107+
return err
108+
}
109+
if len(infos) != 1 {
110+
return fmt.Errorf("expected one Device, found %d", len(infos))
111+
}
112+
device := infos[0].Object.(*unstructured.Unstructured)
113+
if _, ok := device.GetAnnotations()[v1alpha1.DeviceMaintenanceAnnotation]; ok {
114+
return fmt.Errorf("device %q already has a maintenance operation", name)
115+
}
116+
o.ResourceVersion = device.GetResourceVersion()
117+
if err := o.confirm(name); err != nil {
118+
return err
119+
}
120+
121+
restConfig, err := o.Root.ConfigFlags.ToRESTConfig()
122+
if err != nil {
123+
return err
124+
}
125+
dyn, err := dynamic.NewForConfig(restConfig)
126+
if err != nil {
127+
return err
128+
}
129+
patch, err := o.buildPatch()
130+
if err != nil {
131+
return err
132+
}
133+
obj, err := dyn.Resource(infos[0].Mapping.Resource).Namespace(infos[0].Namespace).Patch(context.Background(), name, types.MergePatchType, patch, metav1.PatchOptions{})
134+
if err != nil {
135+
return err
136+
}
137+
printer, err := o.PrintFlags.ToPrinter()
138+
if err != nil {
139+
return err
140+
}
141+
return printer.PrintObj(obj, o.Root.IOStreams.Out)
142+
}
143+
144+
func (o *MaintenanceOptions) confirm(name string) error {
145+
if o.Yes || !maintenanceActionRequiresConfirmation(o.Action) {
146+
return nil
147+
}
148+
149+
input, ok := o.Root.IOStreams.In.(*os.File)
150+
if !ok {
151+
return errors.New("maintenance confirmation requires a terminal; use --yes to skip confirmation")
152+
}
153+
info, err := input.Stat()
154+
if err != nil {
155+
return fmt.Errorf("failed to inspect maintenance confirmation input: %w", err)
156+
}
157+
if info.Mode()&os.ModeCharDevice == 0 {
158+
return errors.New("maintenance confirmation requires a terminal; use --yes to skip confirmation")
159+
}
160+
return confirmMaintenanceOperation(input, o.Root.IOStreams.Out, o.Action, name)
161+
}
162+
163+
func maintenanceActionRequiresConfirmation(action string) bool {
164+
switch action {
165+
case v1alpha1.DeviceMaintenanceReboot,
166+
v1alpha1.DeviceMaintenanceFactoryReset,
167+
v1alpha1.DeviceMaintenanceReprovision,
168+
v1alpha1.DeviceMaintenanceFirmwareUpgrade:
169+
return true
170+
default:
171+
return false
172+
}
173+
}
174+
175+
func confirmMaintenanceOperation(in io.Reader, out io.Writer, action, name string) error {
176+
description := strings.ReplaceAll(action, "-", " ")
177+
description = strings.ToUpper(description[:1]) + description[1:]
178+
fmt.Fprintf(out, "%s Device %q? [y/N]: ", description, name)
179+
180+
response, err := bufio.NewReader(in).ReadString('\n')
181+
if err != nil && !errors.Is(err, io.EOF) {
182+
return fmt.Errorf("failed to read maintenance confirmation: %w", err)
183+
}
184+
if strings.TrimSpace(response) != "y" && strings.TrimSpace(response) != "Y" {
185+
return errors.New("maintenance operation cancelled")
186+
}
187+
return nil
188+
}
189+
190+
// buildPatch returns the JSON merge-patch payload for the maintenance annotations.
191+
func (o *MaintenanceOptions) buildPatch() ([]byte, error) {
192+
annotations := map[string]any{v1alpha1.DeviceMaintenanceAnnotation: o.Action}
193+
if o.Action == v1alpha1.DeviceMaintenanceFirmwareUpgrade {
194+
target, err := json.Marshal(struct {
195+
URL string `json:"url"`
196+
MD5 string `json:"md5,omitempty"`
197+
}{o.FirmwareURL, o.FirmwareMD5})
198+
if err != nil {
199+
return nil, err
200+
}
201+
annotations[v1alpha1.DeviceMaintenanceFirmwareTargetAnnotation] = string(target)
202+
}
203+
return json.Marshal(map[string]any{
204+
"metadata": map[string]any{
205+
"resourceVersion": o.ResourceVersion,
206+
"annotations": annotations,
207+
},
208+
})
209+
}

0 commit comments

Comments
 (0)