/
switch.go
389 lines (332 loc) · 13.8 KB
/
switch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package cmd
import (
"fmt"
"os"
"os/exec"
"strings"
"github.com/metal-stack/metal-go/api/client/machine"
"github.com/metal-stack/metal-go/api/client/switch_operations"
"github.com/metal-stack/metal-go/api/models"
"github.com/metal-stack/metal-lib/pkg/genericcli"
"github.com/metal-stack/metal-lib/pkg/genericcli/printers"
"github.com/metal-stack/metalctl/cmd/sorters"
"github.com/metal-stack/metalctl/cmd/tableprinters"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type switchCmd struct {
*config
}
func newSwitchCmd(c *config) *cobra.Command {
w := switchCmd{
config: c,
}
cmdsConfig := &genericcli.CmdsConfig[any, *models.V1SwitchUpdateRequest, *models.V1SwitchResponse]{
BinaryName: binaryName,
GenericCLI: genericcli.NewGenericCLI[any, *models.V1SwitchUpdateRequest, *models.V1SwitchResponse](w).WithFS(c.fs),
OnlyCmds: genericcli.OnlyCmds(
genericcli.ListCmd,
genericcli.DescribeCmd,
genericcli.UpdateCmd,
genericcli.DeleteCmd,
genericcli.EditCmd,
),
Aliases: []string{"sw"},
Singular: "switch",
Plural: "switches",
Description: "switch are the leaf switches in the data center that are controlled by metal-stack.",
Sorter: sorters.SwitchSorter(),
ValidArgsFn: c.comp.SwitchListCompletion,
DescribePrinter: func() printers.Printer { return c.describePrinter },
ListPrinter: func() printers.Printer { return c.listPrinter },
ListCmdMutateFn: func(cmd *cobra.Command) {
cmd.Flags().String("id", "", "ID of the switch.")
cmd.Flags().String("name", "", "Name of the switch.")
cmd.Flags().String("os-vendor", "", "OS vendor of this switch.")
cmd.Flags().String("os-version", "", "OS version of this switch.")
cmd.Flags().String("partition", "", "Partition of this switch.")
cmd.Flags().String("rack", "", "Rack of this switch.")
must(cmd.RegisterFlagCompletionFunc("id", c.comp.SwitchListCompletion))
must(cmd.RegisterFlagCompletionFunc("name", c.comp.SwitchNameListCompletion))
must(cmd.RegisterFlagCompletionFunc("partition", c.comp.PartitionListCompletion))
must(cmd.RegisterFlagCompletionFunc("rack", c.comp.SwitchRackListCompletion))
must(cmd.RegisterFlagCompletionFunc("os-vendor", c.comp.SwitchOSVendorListCompletion))
must(cmd.RegisterFlagCompletionFunc("os-version", c.comp.SwitchOSVersionListCompletion))
},
}
switchDetailCmd := &cobra.Command{
Use: "detail",
Short: "switch details",
RunE: func(cmd *cobra.Command, args []string) error {
return w.switchDetail()
},
ValidArgsFunction: c.comp.SwitchListCompletion,
}
switchDetailCmd.Flags().String("id", "", "ID of the switch.")
switchDetailCmd.Flags().String("name", "", "Name of the switch.")
switchDetailCmd.Flags().String("os-vendor", "", "OS vendor of this switch.")
switchDetailCmd.Flags().String("os-version", "", "OS version of this switch.")
switchDetailCmd.Flags().String("partition", "", "Partition of this switch.")
switchDetailCmd.Flags().String("rack", "", "Rack of this switch.")
must(switchDetailCmd.RegisterFlagCompletionFunc("id", c.comp.SwitchListCompletion))
must(switchDetailCmd.RegisterFlagCompletionFunc("name", c.comp.SwitchNameListCompletion))
must(switchDetailCmd.RegisterFlagCompletionFunc("partition", c.comp.PartitionListCompletion))
must(switchDetailCmd.RegisterFlagCompletionFunc("rack", c.comp.SwitchRackListCompletion))
switchMachinesCmd := &cobra.Command{
Use: "connected-machines",
Short: "shows switches with their connected machines",
RunE: func(cmd *cobra.Command, args []string) error {
return w.switchMachines()
},
Example: `The command will show the machines connected to the switch ports.
Can also be used with -o template in order to generate CSV-style output:
$ metalctl switch connected-machines -o template --template '{{ $machines := .machines }}{{ range .switches }}{{ $switch := . }}{{ range .connections }}{{ $switch.id }},{{ $switch.rack_id }},{{ .nic.name }},{{ .machine_id }},{{ (index $machines .machine_id).ipmi.fru.product_serial }}{{ printf "\n" }}{{ end }}{{ end }}'
r01leaf01,swp1,f78cc340-e5e8-48ed-8fe7-2336c1e2ded2,<a-serial>
r01leaf01,swp2,44e3a522-5f48-4f3c-9188-41025f9e401e,<b-serial>
...
`,
}
switchMachinesCmd.Flags().String("id", "", "ID of the switch.")
switchMachinesCmd.Flags().String("name", "", "Name of the switch.")
switchMachinesCmd.Flags().String("os-vendor", "", "OS vendor of this switch.")
switchMachinesCmd.Flags().String("os-version", "", "OS version of this switch.")
switchMachinesCmd.Flags().String("partition", "", "Partition of this switch.")
switchMachinesCmd.Flags().String("rack", "", "Rack of this switch.")
switchMachinesCmd.Flags().String("size", "", "Size of the connected machines.")
switchMachinesCmd.Flags().String("machine-id", "", "The id of the connected machine, ignores size flag if set.")
must(switchMachinesCmd.RegisterFlagCompletionFunc("id", c.comp.SwitchListCompletion))
must(switchMachinesCmd.RegisterFlagCompletionFunc("name", c.comp.SwitchNameListCompletion))
must(switchMachinesCmd.RegisterFlagCompletionFunc("partition", c.comp.PartitionListCompletion))
must(switchMachinesCmd.RegisterFlagCompletionFunc("rack", c.comp.SwitchRackListCompletion))
must(switchMachinesCmd.RegisterFlagCompletionFunc("size", c.comp.SizeListCompletion))
must(switchMachinesCmd.RegisterFlagCompletionFunc("machine-id", c.comp.MachineListCompletion))
switchReplaceCmd := &cobra.Command{
Use: "replace <switchID>",
Short: "put a leaf switch into replace mode in preparation for physical replacement. For a description of the steps involved see the long help.",
Long: `Put a leaf switch into replace mode in preparation for physical replacement
Operational steps to replace a switch:
- Put the switch that needs to be replaced in replace mode with this command
- Replace the switch MAC address in the metal-stack deployment configuration
- Make sure that interfaces on the new switch do not get connected to the PXE-bridge immediately by setting the interfaces list of the respective leaf switch to [] in the metal-stack deployment configuration
- Deploy the management servers so that the dhcp servers will serve the right address and DHCP options to the new switch
- Replace the switch physically. Be careful to ensure that the cabling mirrors the remaining leaf exactly because the new switch information will be cloned from the remaining switch! Also make sure to have console access to the switch so you can start and monitor the install process
- If the switch is not in onie install mode but already has an operating system installed, put it into install mode with "sudo onie-select -i -f -v" and reboot it. Now the switch should be provisioned with a management IP from a management server, install itself with the right software image and receive license and ssh keys through ZTP. You can check whether that process has completed successfully with the command "sudo ztp -s". The ZTP state should be disabled and the result should be success.
- Deploy the switch plane and metal-core through metal-stack deployment CI job
- The switch will now register with its metal-api, and the metal-core service will receive the cloned interface and routing information. You can verify successful switch replacement by checking the interface and BGP configuration, and checking the switch status with "metalctl switch ls -o wide"; it should now be operational again`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.switchReplace(args)
},
ValidArgsFunction: c.comp.SwitchListCompletion,
}
switchSSHCmd := &cobra.Command{
Use: "ssh <switchID>",
Short: "connect to the switch via ssh",
Long: "this requires a network connectivity to the management ip address of the switch.",
RunE: func(cmd *cobra.Command, args []string) error {
return w.switchSSH(args)
},
ValidArgsFunction: c.comp.SwitchListCompletion,
}
switchConsoleCmd := &cobra.Command{
Use: "console <switchID>",
Short: "connect to the switch console",
Long: "this requires a network connectivity to the ip address of the console server this switch is connected to.",
RunE: func(cmd *cobra.Command, args []string) error {
return w.switchConsole(args)
},
ValidArgsFunction: c.comp.SwitchListCompletion,
}
return genericcli.NewCmds(cmdsConfig, switchDetailCmd, switchMachinesCmd, switchReplaceCmd, switchSSHCmd, switchConsoleCmd)
}
func (c switchCmd) Get(id string) (*models.V1SwitchResponse, error) {
resp, err := c.client.SwitchOperations().FindSwitch(switch_operations.NewFindSwitchParams().WithID(id), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c switchCmd) List() ([]*models.V1SwitchResponse, error) {
resp, err := c.client.SwitchOperations().FindSwitches(switch_operations.NewFindSwitchesParams().WithBody(&models.V1SwitchFindRequest{
ID: viper.GetString("id"),
Name: viper.GetString("name"),
Osvendor: viper.GetString("os-vendor"),
Osversion: viper.GetString("os-version"),
Partitionid: viper.GetString("partition"),
Rackid: viper.GetString("rack"),
}), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c switchCmd) Delete(id string) (*models.V1SwitchResponse, error) {
resp, err := c.client.SwitchOperations().DeleteSwitch(switch_operations.NewDeleteSwitchParams().WithID(id), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c switchCmd) Create(rq any) (*models.V1SwitchResponse, error) {
return nil, fmt.Errorf("switch entity does not support create operation")
}
func (c switchCmd) Update(rq *models.V1SwitchUpdateRequest) (*models.V1SwitchResponse, error) {
resp, err := c.client.SwitchOperations().UpdateSwitch(switch_operations.NewUpdateSwitchParams().WithBody(rq), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c switchCmd) Convert(r *models.V1SwitchResponse) (string, any, *models.V1SwitchUpdateRequest, error) {
if r.ID == nil {
return "", nil, nil, fmt.Errorf("id is nil")
}
return *r.ID, nil, switchResponseToUpdate(r), nil
}
func switchResponseToUpdate(r *models.V1SwitchResponse) *models.V1SwitchUpdateRequest {
switchOS := &models.V1SwitchOS{}
if r.Os != nil {
switchOS.Vendor = r.Os.Vendor
switchOS.Vendor = r.Os.Version
}
return &models.V1SwitchUpdateRequest{
ConsoleCommand: r.ConsoleCommand,
Description: r.Description,
ID: r.ID,
ManagementIP: "",
ManagementUser: "",
Mode: r.Mode,
Name: r.Name,
Os: switchOS,
RackID: r.RackID,
}
}
// non-generic command handling
func (c *switchCmd) switchDetail() error {
resp, err := c.List()
if err != nil {
return err
}
var result []*tableprinters.SwitchDetail
for _, s := range resp {
result = append(result, &tableprinters.SwitchDetail{V1SwitchResponse: s})
}
return c.listPrinter.Print(result)
}
func (c *switchCmd) switchMachines() error {
switches, err := c.List()
if err != nil {
return err
}
err = sorters.SwitchSorter().SortBy(switches)
if err != nil {
return err
}
var machines []*models.V1MachineIPMIResponse
if viper.IsSet("machine-id") {
resp, err := c.client.Machine().FindIPMIMachine(machine.NewFindIPMIMachineParams().WithID(viper.GetString("machine-id")), nil)
if err != nil {
return err
}
machines = append(machines, resp.Payload)
} else {
resp, err := c.client.Machine().FindIPMIMachines(machine.NewFindIPMIMachinesParams().WithBody(&models.V1MachineFindRequest{
ID: viper.GetString("machine-id"),
PartitionID: viper.GetString("partition"),
Rackid: viper.GetString("rack"),
Sizeid: viper.GetString("size"),
}), nil)
if err != nil {
return err
}
machines = append(machines, resp.Payload...)
}
ms := map[string]*models.V1MachineIPMIResponse{}
for _, m := range machines {
m := m
if m.ID == nil {
continue
}
ms[*m.ID] = m
}
return c.listPrinter.Print(&tableprinters.SwitchesWithMachines{
SS: switches,
MS: ms,
})
}
func (c *switchCmd) switchReplace(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.Get(id)
if err != nil {
return err
}
switchOS := &models.V1SwitchOS{}
if resp.Os != nil {
switchOS.Vendor = resp.Os.Vendor
switchOS.Vendor = resp.Os.Version
}
uresp, err := c.Update(&models.V1SwitchUpdateRequest{
ConsoleCommand: "",
Description: resp.Description,
ID: resp.ID,
ManagementIP: "",
ManagementUser: "",
Mode: "replace",
Name: resp.Name,
Os: switchOS,
RackID: resp.RackID,
})
if err != nil {
return err
}
return c.describePrinter.Print(uresp)
}
func (c *switchCmd) switchSSH(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.Get(id)
if err != nil {
return err
}
if resp.ManagementIP == "" || resp.ManagementUser == "" {
return fmt.Errorf("unable to connect to switch by ssh because no ip and user was stored for this switch, please restart metal-core on this switch")
}
// nolint: gosec
cmd := exec.Command("ssh", fmt.Sprintf("%s@%s", resp.ManagementUser, resp.ManagementIP))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
return cmd.Run()
}
func (c *switchCmd) switchConsole(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.Get(id)
if err != nil {
return err
}
if resp.ConsoleCommand == "" {
return fmt.Errorf(`
unable to connect to console because no console_command was specified for this switch
You can add a working console_command to every switch with metalctl switch edit
A sample would look like:
telnet console-server 7008`)
}
parts := strings.Fields(resp.ConsoleCommand)
// nolint: gosec
cmd := exec.Command(parts[0])
if len(parts) > 1 {
// nolint: gosec
cmd = exec.Command(parts[0], parts[1:]...)
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
return cmd.Run()
}