Skip to content

Commit

Permalink
Updated metal-go client for sub-command devices
Browse files Browse the repository at this point in the history
  • Loading branch information
codinja1188 committed Jun 14, 2023
1 parent 0db7e0e commit 6ad1f80
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 60 deletions.
2 changes: 1 addition & 1 deletion docs/metal_device_create.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ metal device create -p <project_id> (-m <metro> | -f <facility>) -P <plan> -H <h
-p, --project-id string The project's UUID. This flag is required, unless specified in the config created by metal init or set as METAL_PROJECT_ID environment variable.
-S, --public-ipv4-subnet-size int Size of the public IPv4 subnet.
-s, --spot-instance Provisions the device as a spot instance.
--spot-price-max float Sets the maximum spot market price for the device: --spot-price-max=1.2
--spot-price-max float32 Sets the maximum spot market price for the device: --spot-price-max=1.2
-t, --tags strings Tag or list of tags for the device: --tags="tag1,tag2".
-T, --termination-time string Device termination time: --termination-time="15:04:05"
-u, --userdata string Userdata for device initialization. Can not be used with --userdata-file.
Expand Down
67 changes: 42 additions & 25 deletions internal/devices/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@
package devices

import (
"context"
"fmt"
"os"
"time"

"github.com/packethost/packngo"
metal "github.com/equinix-labs/metal-go/metal/v1"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand All @@ -49,7 +50,7 @@ func (c *Client) Create() *cobra.Command {
alwaysPXE bool
hardwareReservationID string
spotInstance bool
spotPriceMax float64
spotPriceMax float32
terminationTime string
)

Expand All @@ -64,7 +65,6 @@ func (c *Client) Create() *cobra.Command {
metal device create -p $METAL_PROJECT_ID -P c3.medium.x86 -m sv -H test-rocky -O rocky_8 -r 47161704-1715-4b45-8549-fb3f4b2c32c7`,

RunE: func(cmd *cobra.Command, args []string) error {
var endDt *packngo.Timestamp

if userdata != "" && userdataFile != "" {
return fmt.Errorf("either userdata or userdata-file should be set")
Expand All @@ -78,48 +78,65 @@ func (c *Client) Create() *cobra.Command {
}
userdata = string(userdataRaw)
}
var endDt time.Time

if terminationTime != "" {
parsedTime, err := time.Parse(time.RFC3339, terminationTime)
if err != nil {
return fmt.Errorf("Could not parse time %q: %w", terminationTime, err)
}
endDt = &packngo.Timestamp{Time: parsedTime}
endDt = parsedTime
}

var facilityArgs []string
var request metal.CreateDeviceRequest

if facility != "" {
facilityArgs = append(facilityArgs, facility)

deviceCreateInFacilityInput := &metal.DeviceCreateInFacilityInput{
Plan: plan,
OperatingSystem: operatingSystem,
Hostname: &hostname,
BillingCycle: &billingCycle,
Userdata: &userdata,
IpxeScriptUrl: &ipxescripturl,
AlwaysPxe: &alwaysPXE,
HardwareReservationId: &hardwareReservationID,
SpotInstance: &spotInstance,
SpotPriceMax: &spotPriceMax,
TerminationTime: &endDt,
Facility: facilityArgs,
}
request = metal.CreateDeviceRequest{DeviceCreateInFacilityInput: deviceCreateInFacilityInput, DeviceCreateInMetroInput: nil}
}

request := &packngo.DeviceCreateRequest{
Hostname: hostname,
Plan: plan,
Facility: facilityArgs,
Metro: metro,
OS: operatingSystem,
BillingCycle: billingCycle,
ProjectID: projectID,
UserData: userdata,
CustomData: customdata,
IPXEScriptURL: ipxescripturl,
Tags: tags,
PublicIPv4SubnetSize: publicIPv4SubnetSize,
AlwaysPXE: alwaysPXE,
HardwareReservationID: hardwareReservationID,
SpotInstance: spotInstance,
SpotPriceMax: spotPriceMax,
TerminationTime: endDt,
if metro != "" {
deviceCreateInMetroInput := &metal.DeviceCreateInMetroInput{
Metro: metro,
Plan: plan,
OperatingSystem: operatingSystem,
Hostname: &hostname,
BillingCycle: &billingCycle,
Userdata: &userdata,
IpxeScriptUrl: &ipxescripturl,
AlwaysPxe: &alwaysPXE,
HardwareReservationId: &hardwareReservationID,
SpotInstance: &spotInstance,
SpotPriceMax: &spotPriceMax,
TerminationTime: &endDt,
}
request = metal.CreateDeviceRequest{DeviceCreateInFacilityInput: nil, DeviceCreateInMetroInput: deviceCreateInMetroInput}
}

device, _, err := c.Service.Create(request)
device, _, err := c.Service.CreateDevice(context.Background(), projectID).CreateDeviceRequest(request).Execute()
if err != nil {
return fmt.Errorf("Could not create Device: %w", err)
}

header := []string{"ID", "Hostname", "OS", "State", "Created"}
data := make([][]string, 1)
data[0] = []string{device.ID, device.Hostname, device.OS.Name, device.State, device.Created}
data[0] = []string{device.GetId(), device.GetHostname(), *device.GetOperatingSystem().Name, device.GetState(), device.GetCreatedAt().String()}

return c.Out.Output(device, header, &data)
},
Expand Down Expand Up @@ -147,7 +164,7 @@ func (c *Client) Create() *cobra.Command {
createDeviceCmd.Flags().StringVarP(&billingCycle, "billing-cycle", "b", "hourly", "Billing cycle")
createDeviceCmd.Flags().BoolVarP(&alwaysPXE, "always-pxe", "a", false, "Sets whether the device always PXE boots on reboot.")
createDeviceCmd.Flags().BoolVarP(&spotInstance, "spot-instance", "s", false, "Provisions the device as a spot instance.")
createDeviceCmd.Flags().Float64VarP(&spotPriceMax, "spot-price-max", "", 0, `Sets the maximum spot market price for the device: --spot-price-max=1.2`)
createDeviceCmd.Flags().Float32VarP(&spotPriceMax, "spot-price-max", "", 0, `Sets the maximum spot market price for the device: --spot-price-max=1.2`)
createDeviceCmd.Flags().StringVarP(&terminationTime, "termination-time", "T", "", `Device termination time: --termination-time="15:04:05"`)

return createDeviceCmd
Expand Down
3 changes: 2 additions & 1 deletion internal/devices/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package devices

import (
"context"
"fmt"

"github.com/manifoldco/promptui"
Expand All @@ -31,7 +32,7 @@ func (c *Client) Delete() *cobra.Command {
var deviceID string
var force bool
deleteDevice := func(id string) error {
_, err := c.Service.Delete(id, force)
_, err := c.Service.DeleteDevice(context.Background(), id).ForceDelete(force).Execute()
if err != nil {
return err
}
Expand Down
9 changes: 4 additions & 5 deletions internal/devices/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
package devices

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"
"github.com/spf13/viper"
)

type Client struct {
Servicer Servicer
Service packngo.DeviceService
Service metal.DevicesApiService
Out outputs.Outputer
}

Expand All @@ -47,7 +47,7 @@ func (c *Client) NewCommand() *cobra.Command {
}
}

c.Service = c.Servicer.API(cmd).Devices
c.Service = *c.Servicer.MetalAPI(cmd).DevicesApi
},
}

Expand All @@ -65,8 +65,7 @@ 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
Config(cmd *cobra.Command) *viper.Viper
}

Expand Down
5 changes: 4 additions & 1 deletion internal/devices/reboot.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
package devices

import (
"context"
"fmt"

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

Expand All @@ -38,7 +40,8 @@ func (c *Client) Reboot() *cobra.Command {

RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
_, err := c.Service.Reboot(deviceID)
DeviceAction := metal.NewDeviceActionInput("reboot")
_, err := c.Service.PerformAction(context.Background(), deviceID).DeviceActionInput(*DeviceAction).Execute()
if err != nil {
return fmt.Errorf("Could not reboot Device: %w", err)
}
Expand Down
29 changes: 23 additions & 6 deletions internal/devices/reinstall.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
package devices

import (
"context"
"fmt"

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

Expand All @@ -47,14 +48,30 @@ func (c *Client) Reinstall() *cobra.Command {
metal device reinstall -d 50382f72-02b7-4b40-ac8d-253713e1e174 -O ubuntu_22_04 --preserve-data`,
RunE: func(cmd *cobra.Command, args []string) error {

request := packngo.DeviceReinstallFields{
OperatingSystem: operatingSystem,
PreserveData: preserveData,
DeprovisionFast: deprovisionFast,
DeviceAction := metal.NewDeviceActionInput("reinstall")

if preserveData {
DeviceAction.PreserveData = &preserveData
}
if deprovisionFast {
DeviceAction.DeprovisionFast = &deprovisionFast
}
device, _, Err := c.Service.FindDeviceById(context.Background(), id).Execute()
if Err != nil {
fmt.Printf("Error when calling `DevicesApiService.FindDeviceByID``: %v\n", Err)
Err = fmt.Errorf("Could not reinstall Device: %w", Err)
return Err
}

if operatingSystem == "" || operatingSystem == "null" {
DeviceAction.SetOperatingSystem(device.OperatingSystem.GetSlug())
} else {
DeviceAction.OperatingSystem = &operatingSystem
}

_, err := c.Service.Reinstall(id, &request)
_, err := c.Service.PerformAction(context.Background(), id).DeviceActionInput(*DeviceAction).Execute()
if err != nil {
fmt.Printf("Error when calling `DevicesApiService.PerformAction``: %v\n", err)
err = fmt.Errorf("Could not reinstall Device: %w", err)
}

Expand Down
16 changes: 10 additions & 6 deletions internal/devices/retrieve.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package devices

import (
"context"
"fmt"

"github.com/spf13/cobra"
Expand All @@ -47,27 +48,30 @@ func (c *Client) Retrieve() *cobra.Command {
}
cmd.SilenceUsage = true

include := []string{"Inner_example"}
exclude := []string{"Inner_example"}

if deviceID != "" {
device, _, err := c.Service.Get(deviceID, nil)
device, _, err := c.Service.FindDeviceById(context.Background(), deviceID).Include(include).Exclude(exclude).Execute()
if err != nil {
return fmt.Errorf("Could not get Devices: %w", err)
}
header := []string{"ID", "Hostname", "OS", "State", "Created"}

data := make([][]string, 1)
data[0] = []string{device.ID, device.Hostname, device.OS.Name, device.State, device.Created}
data[0] = []string{device.GetId(), device.GetHostname(), *device.GetOperatingSystem().Name, device.GetState(), device.GetCreatedAt().String()}

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

devices, _, err := c.Service.List(projectID, c.Servicer.ListOptions(nil, nil))
devices, _, err := c.Service.FindProjectDevices(context.Background(), projectID).Execute()
if err != nil {
return fmt.Errorf("Could not list Devices: %w", err)
}
data := make([][]string, len(devices))
data := make([][]string, len(devices.GetDevices()))

for i, dc := range devices {
data[i] = []string{dc.ID, dc.Hostname, dc.OS.Name, dc.State, dc.Created}
for i, dc := range devices.GetDevices() {
data[i] = []string{dc.GetId(), dc.GetHostname(), *dc.GetOperatingSystem().Name, dc.GetState(), dc.GetCreatedAt().String()}
}
header := []string{"ID", "Hostname", "OS", "State", "Created"}

Expand Down
5 changes: 4 additions & 1 deletion internal/devices/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
package devices

import (
"context"
"fmt"

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

Expand All @@ -38,7 +40,8 @@ func (c *Client) Start() *cobra.Command {

RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
_, err := c.Service.PowerOn(deviceID)
DeviceAction := metal.NewDeviceActionInput("power_on")
_, err := c.Service.PerformAction(context.Background(), deviceID).DeviceActionInput(*DeviceAction).Execute()
if err != nil {
return fmt.Errorf("Could not start Device: %w", err)
}
Expand Down
5 changes: 4 additions & 1 deletion internal/devices/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
package devices

import (
"context"
"fmt"

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

Expand All @@ -37,7 +39,8 @@ func (c *Client) Stop() *cobra.Command {

RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
_, err := c.Service.PowerOff(deviceID)
DeviceAction := metal.NewDeviceActionInput("power_off")
_, err := c.Service.PerformAction(context.Background(), deviceID).DeviceActionInput(*DeviceAction).Execute()
if err != nil {
return fmt.Errorf("Could not stop Device: %w", err)
}
Expand Down
Loading

0 comments on commit 6ad1f80

Please sign in to comment.