|
| 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