Skip to content

Commit

Permalink
Migrate metal ports subcommand cli to metal-go from packngo
Browse files Browse the repository at this point in the history
Signed-off-by: Ayush Rangwala <[email protected]>
  • Loading branch information
aayushrangwala committed Oct 17, 2023
1 parent 230615a commit cd6fa31
Show file tree
Hide file tree
Showing 8 changed files with 552 additions and 75 deletions.
97 changes: 61 additions & 36 deletions internal/ports/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,21 @@
package ports

import (
"context"
"fmt"
"log"
"net/http"
"strconv"

metal "github.com/equinix-labs/metal-go/metal/v1"
"github.com/manifoldco/promptui"
"github.com/packethost/packngo"
"github.com/spf13/cobra"
)

func (c *Client) Convert() *cobra.Command {
var portID string
var bonded, layer2, bulk, force, ipv4, ipv6 bool
// retrievePortCmd represents the retrievePort command
retrievePortCmd := &cobra.Command{
convertPortCmd := &cobra.Command{
Use: `convert -i <port_UUID> [--bonded] [--bulk] --layer2 [--force] [--public-ipv4] [--public-ipv6]`,
Aliases: []string{},
Short: "Converts a list of ports or the details of the specified port.",
Expand All @@ -54,25 +55,11 @@ func (c *Client) Convert() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true

if f := cmd.Flag("bonded"); f.Changed {
_, _, err := map[bool]func(string, bool) (*packngo.Port, *packngo.Response, error){
true: c.PortService.Bond,
false: c.PortService.Disbond,
}[bonded](portID, bulk)
if err != nil {
return fmt.Errorf("failed to change port bonding: %w", err)
}
}
addrs := []packngo.AddressRequest{{AddressFamily: 4, Public: false}}

if f := cmd.Flag("public-ipv4"); f.Changed {
addrs = append(addrs, packngo.AddressRequest{AddressFamily: 4, Public: true})
}
if f := cmd.Flag("public-ipv6"); f.Changed {
addrs = append(addrs, packngo.AddressRequest{AddressFamily: 6, Public: true})
if err := portBondingHandler(cmd, c, portID); err != nil {
return fmt.Errorf("failed to change port bonding: %w", err)
}

convToL2 := func(portID string) (*packngo.Port, *packngo.Response, error) {
convToL2 := func(portID string) (*metal.Port, *http.Response, error) {
if !force {
prompt := promptui.Prompt{
Label: fmt.Sprintf("Are you sure you want to convert Port %s to Layer2 and remove assigned IP addresses: ", portID),
Expand All @@ -84,45 +71,83 @@ func (c *Client) Convert() *cobra.Command {
return nil, nil, nil
}
}
return c.PortService.ConvertToLayerTwo(portID)

return c.PortService.ConvertLayer2(context.Background(), portID).
PortAssignInput(*metal.NewPortAssignInput()).
Execute()
}
convToL3 := func(portID string) (*packngo.Port, *packngo.Response, error) {

addressFamily := int32(metal.IPADDRESSADDRESSFAMILY__4)
public := false
addrs := []metal.PortConvertLayer3InputRequestIpsInner{{AddressFamily: &addressFamily, Public: &public}}

if f := cmd.Flag("public-ipv4"); f.Changed {
addressFamily = int32(metal.IPADDRESSADDRESSFAMILY__4)
public = true
addrs = append(addrs, metal.PortConvertLayer3InputRequestIpsInner{AddressFamily: &addressFamily, Public: &public})
}
if f := cmd.Flag("public-ipv6"); f.Changed {
addressFamily = int32(metal.IPADDRESSADDRESSFAMILY__6)
public = true
addrs = append(addrs, metal.PortConvertLayer3InputRequestIpsInner{AddressFamily: &addressFamily, Public: &public})
}

convToL3 := func(portID string) (*metal.Port, *http.Response, error) {
log.Printf("Converting port %s to layer-3 with addresses %v", portID, addrs)
return c.PortService.ConvertToLayerThree(portID, addrs)
return c.PortService.
ConvertLayer3(context.Background(), portID).
PortConvertLayer3Input(metal.PortConvertLayer3Input{
RequestIps: addrs,
}).
Execute()
}
if f := cmd.Flag("layer2"); f.Changed {
_, _, err := map[bool]func(string) (*packngo.Port, *packngo.Response, error){
_, _, err := map[bool]func(string) (*metal.Port, *http.Response, error){
true: convToL2,
false: convToL3,
}[layer2](portID)
if err != nil {
return fmt.Errorf("failed to change port network mode: %w", err)
}
}
listOpts := c.Servicer.ListOptions(nil, nil)

getOpts := &packngo.GetOptions{Includes: listOpts.Includes, Excludes: listOpts.Excludes}
port, _, err := c.PortService.Get(portID, getOpts)
port, _, err := c.PortService.FindPortById(context.Background(), portID).
Include(c.Servicer.Includes(nil)).
Execute()
if err != nil {
return fmt.Errorf("Could not get Port: %w", err)
}

data := make([][]string, 1)

data[0] = []string{port.ID, port.Name, port.Type, port.NetworkType, port.Data.MAC, strconv.FormatBool(port.Data.Bonded)}
data[0] = []string{port.GetId(), port.GetName(), string(port.GetType()), string(port.GetNetworkType()), port.Data.GetMac(), strconv.FormatBool(port.Data.GetBonded())}
header := []string{"ID", "Name", "Type", "Network Type", "MAC", "Bonded"}

return c.Out.Output(port, header, &data)
},
}

retrievePortCmd.Flags().StringVarP(&portID, "port-id", "i", "", "The UUID of a port.")
retrievePortCmd.Flags().BoolVarP(&bonded, "bonded", "b", false, "Convert to layer-2 bonded.")
retrievePortCmd.Flags().BoolVarP(&bulk, "bulk", "", false, "Affect both ports in a bond.")
retrievePortCmd.Flags().BoolVarP(&layer2, "layer2", "2", false, "Convert to layer-2 unbonded.")
retrievePortCmd.Flags().BoolVarP(&force, "force", "f", false, "Force conversion to layer-2 bonded.")
retrievePortCmd.Flags().BoolVarP(&ipv4, "public-ipv4", "4", false, "Convert to layer-2 bonded with public IPv4.")
retrievePortCmd.Flags().BoolVarP(&ipv6, "public-ipv6", "6", false, "Convert to layer-2 bonded with public IPv6.")
convertPortCmd.Flags().StringVarP(&portID, "port-id", "i", "", "The UUID of a port.")
convertPortCmd.Flags().BoolVarP(&bonded, "bonded", "b", false, "Convert to layer-2 bonded.")
convertPortCmd.Flags().BoolVarP(&bulk, "bulk", "", false, "Affect both ports in a bond.")
convertPortCmd.Flags().BoolVarP(&layer2, "layer2", "2", false, "Convert to layer-2 unbonded.")
convertPortCmd.Flags().BoolVarP(&force, "force", "f", false, "Force conversion to layer-2 bonded.")
convertPortCmd.Flags().BoolVarP(&ipv4, "public-ipv4", "4", false, "Convert to layer-2 bonded with public IPv4.")
convertPortCmd.Flags().BoolVarP(&ipv6, "public-ipv6", "6", false, "Convert to layer-2 bonded with public IPv6.")

return convertPortCmd
}

func portBondingHandler(cmd *cobra.Command, c *Client, portId string) error {
if cmd.Flag("bonded").Changed {
_, _, err := c.PortService.BondPort(context.Background(), portId).
Include(c.Servicer.Includes(nil)).
Execute()
return err
}

return retrievePortCmd
_, _, err := c.PortService.DisbondPort(context.Background(), portId).
Include(c.Servicer.Includes(nil)).
Execute()
return err
}
15 changes: 8 additions & 7 deletions internal/ports/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
package ports

import (
metal "github.com/equinix-labs/metal-go/metal/v1"
"github.com/equinix/metal-cli/internal/outputs"
"github.com/packethost/packngo"
"github.com/spf13/cobra"
)

type Client struct {
Servicer Servicer
PortService packngo.PortService
VLANService packngo.VLANAssignmentService
PortService *metal.PortsApiService
VLANService *metal.VLANsApiService
Out outputs.Outputer
}

Expand All @@ -45,8 +45,8 @@ func (c *Client) NewCommand() *cobra.Command {
root.PersistentPreRun(cmd, args)
}
}
c.PortService = c.Servicer.API(cmd).Ports
c.VLANService = c.Servicer.API(cmd).VLANAssignments
c.PortService = c.Servicer.MetalAPI(cmd).PortsApi
c.VLANService = c.Servicer.MetalAPI(cmd).VLANsApi
},
}

Expand All @@ -59,8 +59,9 @@ func (c *Client) NewCommand() *cobra.Command {
}

type Servicer interface {
API(*cobra.Command) *packngo.Client
ListOptions(defaultIncludes, defaultExcludes []string) *packngo.ListOptions
MetalAPI(*cobra.Command) *metal.APIClient
Filters() map[string]string
Includes(defaultIncludes []string) (incl []string)
}

func NewClient(s Servicer, out outputs.Outputer) *Client {
Expand Down
11 changes: 5 additions & 6 deletions internal/ports/retrieve.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
package ports

import (
"context"
"fmt"
"strconv"

"github.com/packethost/packngo"
"github.com/spf13/cobra"
)

Expand All @@ -41,17 +41,16 @@ func (c *Client) Retrieve() *cobra.Command {

RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
listOpts := c.Servicer.ListOptions(nil, nil)

getOpts := &packngo.GetOptions{Includes: listOpts.Includes, Excludes: listOpts.Excludes}
port, _, err := c.PortService.Get(portID, getOpts)
port, _, err := c.PortService.FindPortById(context.Background(), portID).
Include(c.Servicer.Includes(nil)).
Execute()
if err != nil {
return fmt.Errorf("Could not get Port: %w", err)
}

data := make([][]string, 1)

data[0] = []string{port.ID, port.Name, port.Type, port.NetworkType, port.Data.MAC, strconv.FormatBool(port.Data.Bonded)}
data[0] = []string{port.GetId(), port.GetName(), string(port.GetType()), string(port.GetNetworkType()), port.Data.GetMac(), strconv.FormatBool(port.Data.GetBonded())}
header := []string{"ID", "Name", "Type", "Network Type", "MAC", "Bonded"}

return c.Out.Output(port, header, &data)
Expand Down
40 changes: 24 additions & 16 deletions internal/ports/vlans.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@
package ports

import (
"context"
"errors"
"fmt"
"strconv"

"github.com/packethost/packngo"
metal "github.com/equinix-labs/metal-go/metal/v1"
"github.com/spf13/cobra"
)

Expand All @@ -50,38 +51,45 @@ func (c *Client) Vlans() *cobra.Command {

RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
listOpts := c.Servicer.ListOptions([]string{"port"}, nil)
req := metal.NewPortVlanAssignmentBatchCreateInput()

getOpts := &packngo.GetOptions{Includes: listOpts.Includes, Excludes: listOpts.Excludes}
req := &packngo.VLANAssignmentBatchCreateRequest{}
f := false
t := true
for _, vlan := range assignments {
assignment := packngo.VLANAssignmentCreateRequest{VLAN: vlan, State: packngo.VLANAssignmentAssigned, Native: &f}
req.VLANAssignments = append(req.VLANAssignments, assignment)
CreateInputVlanAssignmentsInner := metal.PortVlanAssignmentBatchCreateInputVlanAssignmentsInner{}
CreateInputVlanAssignmentsInner.SetVlan(vlan)
CreateInputVlanAssignmentsInner.SetState(metal.PORTVLANASSIGNMENTBATCHVLANASSIGNMENTSINNERSTATE_ASSIGNED)
req.SetVlanAssignments(append(req.GetVlanAssignments(), CreateInputVlanAssignmentsInner))
}
for _, vlan := range unassignments {
assignment := packngo.VLANAssignmentCreateRequest{VLAN: vlan, State: packngo.VLANAssignmentUnassigned}
req.VLANAssignments = append(req.VLANAssignments, assignment)
CreateInputVlanAssignmentsInner := metal.PortVlanAssignmentBatchCreateInputVlanAssignmentsInner{}
CreateInputVlanAssignmentsInner.SetVlan(vlan)
CreateInputVlanAssignmentsInner.SetState(metal.PORTVLANASSIGNMENTBATCHVLANASSIGNMENTSINNERSTATE_UNASSIGNED)
req.SetVlanAssignments(append(req.GetVlanAssignments(), CreateInputVlanAssignmentsInner))
}
if native != "" {
assignment := packngo.VLANAssignmentCreateRequest{VLAN: native, State: packngo.VLANAssignmentAssigned, Native: &t}
req.VLANAssignments = append(req.VLANAssignments, assignment)
CreateInputVlanAssignmentsInner := metal.PortVlanAssignmentBatchCreateInputVlanAssignmentsInner{}
CreateInputVlanAssignmentsInner.SetVlan(native)
CreateInputVlanAssignmentsInner.SetState(metal.PORTVLANASSIGNMENTBATCHVLANASSIGNMENTSINNERSTATE_ASSIGNED)
CreateInputVlanAssignmentsInner.SetNative(true)
req.SetVlanAssignments(append(req.GetVlanAssignments(), CreateInputVlanAssignmentsInner))
}
if len(req.VLANAssignments) == 0 {

if len(req.GetVlanAssignments()) == 0 {
return errors.New("no VLAN assignments specified")
}
batch, _, err := c.VLANService.CreateBatch(portID, req, getOpts)
batch, _, err := c.PortService.CreatePortVlanAssignmentBatch(context.Background(), portID).
PortVlanAssignmentBatchCreateInput(*req).
Include(c.Servicer.Includes([]string{"port"})).
Execute()
if err != nil {
return fmt.Errorf("Could not update port VLAN assignments: %w", err)
}

// TODO: should we return the batch?
port := batch.Port
port := batch.GetPort()

data := make([][]string, 1)

data[0] = []string{port.ID, port.Name, port.Type, port.NetworkType, port.Data.MAC, strconv.FormatBool(port.Data.Bonded)}
data[0] = []string{port.GetId(), port.GetName(), string(port.GetType()), string(port.GetNetworkType()), port.Data.GetMac(), strconv.FormatBool(port.Data.GetBonded())}
header := []string{"ID", "Name", "Type", "Network Type", "MAC", "Bonded"}

return c.Out.Output(port, header, &data)
Expand Down
Loading

0 comments on commit cd6fa31

Please sign in to comment.