Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Subnet support #126

Merged
merged 9 commits into from
Oct 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type Instance struct {
SSHKey string `json:"ssh_key,omitempty"`
SSHKeyID string `json:"ssh_key_id,omitempty"`
Status string `json:"status,omitempty"`
Subnets []string `json:"subnets,omitempty"`
Notes string `json:"notes,omitempty"`
FirewallID string `json:"firewall_id,omitempty"`
Tags []string `json:"tags,omitempty"`
Expand Down Expand Up @@ -81,6 +82,7 @@ type InstanceConfig struct {
SourceType string `json:"source_type"`
SourceID string `json:"source_id"`
SnapshotID string `json:"snapshot_id"`
Subnets []string `json:"subnets,omitempty"`
InitialUser string `json:"initial_user"`
SSHKeyID string `json:"ssh_key_id"`
Script string `json:"script"`
Expand Down Expand Up @@ -224,12 +226,13 @@ func (c *Client) SetInstanceTags(i *Instance, tags string) (*SimpleResponse, err

// UpdateInstance updates an Instance's hostname, reverse DNS or notes
func (c *Client) UpdateInstance(i *Instance) (*SimpleResponse, error) {
params := map[string]string{
params := map[string]interface{}{
"hostname": i.Hostname,
"reverse_dns": i.ReverseDNS,
"notes": i.Notes,
"region": c.Region,
"public_ip": i.PublicIP,
"subnets": i.Subnets,
}

if i.Notes == "" {
Expand Down
2 changes: 1 addition & 1 deletion instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ func TestUpdateInstance(t *testing.T) {
Method: "PUT",
Value: []ValueAdvanceClientForTesting{
{
RequestBody: `{"hostname":"dummy.example.com","notes":"my notes","reverse_dns":"dummy-reverse.example.com"}`,
RequestBody: `{"hostname":"dummy.example.com","notes":"my notes","reverse_dns":"dummy-reverse.example.com", "subnets": ["test-subnet-1", "test-subnet-2"]}`,
URL: "/v2/instances/12345",
ResponseBody: `{"result": "success"}`,
},
Expand Down
164 changes: 153 additions & 11 deletions network.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,43 @@ import (

// Network represents a private network for instances to connect to
type Network struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Default bool `json:"default,omitempty"`
CIDR string `json:"cidr,omitempty"`
Label string `json:"label,omitempty"`
Status string `json:"status,omitempty"`
ID string `json:"id"`
Name string `json:"name,omitempty"`
Default bool `json:"default"`
CIDR string `json:"cidr,omitempty"`
CIDRV6 string `json:"cidr_v6,omitempty"`
Label string `json:"label,omitempty"`
Status string `json:"status,omitempty"`
IPv4Enabled bool `json:"ipv4_enabled,omitempty"`
IPv6Enabled bool `json:"ipv6_enabled,omitempty"`
NameserversV4 []string `json:"nameservers_v4,omitempty"`
NameserversV6 []string `json:"nameservers_v6,omitempty"`
}

type networkConfig struct {
Label string `json:"label"`
Region string `json:"region"`
// Subnet represents a subnet within a private network
type Subnet struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
NetworkID string `json:"network_id"`
SubnetSize string `json:"subnet_size,omitempty"`
Status string `json:"status,omitempty"`
}

// SubnetConfig contains incoming request parameters for the subnet object
type SubnetConfig struct {
Name string `json:"name" validate:"required" schema:"name"`
}

// NetworkConfig contains incoming request parameters for the network object
type NetworkConfig struct {
Label string `json:"label" validate:"required" schema:"label"`
Default string `json:"default" schema:"default"`
IPv4Enabled *bool `json:"ipv4_enabled"`
NameserversV4 []string `json:"nameservers_v4"`
CIDRv4 string `json:"cidr_v4"`
IPv6Enabled *bool `json:"ipv6_enabled"`
NameserversV6 []string `json:"nameservers_v6"`
Region string `json:"region"`
}

// NetworkResult represents the result from a network create/update call
Expand Down Expand Up @@ -62,7 +88,7 @@ func (c *Client) GetNetwork(id string) (*Network, error) {

// NewNetwork creates a new private network
func (c *Client) NewNetwork(label string) (*NetworkResult, error) {
nc := networkConfig{Label: label, Region: c.Region}
nc := NetworkConfig{Label: label, Region: c.Region}
body, err := c.SendPostRequest("/v2/networks", nc)
if err != nil {
return nil, decodeError(err)
Expand Down Expand Up @@ -127,7 +153,7 @@ func (c *Client) FindNetwork(search string) (*Network, error) {

// RenameNetwork renames an existing private network
func (c *Client) RenameNetwork(label, id string) (*NetworkResult, error) {
nc := networkConfig{Label: label, Region: c.Region}
nc := NetworkConfig{Label: label, Region: c.Region}
body, err := c.SendPutRequest("/v2/networks/"+id, nc)
if err != nil {
return nil, decodeError(err)
Expand All @@ -150,3 +176,119 @@ func (c *Client) DeleteNetwork(id string) (*SimpleResponse, error) {

return c.DecodeSimpleResponse(resp)
}

// GetSubnet gets a subnet with ID
func (c *Client) GetSubnet(networkID, subnetID string) (*Subnet, error) {
resp, err := c.SendGetRequest(fmt.Sprintf("/v2/networks/%s/subnets/", networkID) + subnetID)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can also do: fmt.Sprintf("/v2/networks/%s/subnets/%s", networkID, subnetID)

if err != nil {
return nil, decodeError(err)
}

subnet := Subnet{}
err = json.NewDecoder(bytes.NewReader(resp)).Decode(&subnet)
return &subnet, err
}

// ListSubnets list all subnets for a private network
func (c *Client) ListSubnets(networkID string) ([]Subnet, error) {
resp, err := c.SendGetRequest(fmt.Sprintf("/v2/networks/%s/subnets", networkID))
if err != nil {
return nil, decodeError(err)
}

subnets := make([]Subnet, 0)
if err := json.NewDecoder(bytes.NewReader(resp)).Decode(&subnets); err != nil {
return nil, err
}

return subnets, nil
}

// CreateSubnet creates a new subnet for a private network
func (c *Client) CreateSubnet(networkID string, subnet SubnetConfig) (*Subnet, error) {
body, err := c.SendPostRequest(fmt.Sprintf("/v2/networks/%s/subnets", networkID), subnet)
if err != nil {
return nil, decodeError(err)
}

var result = &Subnet{}
if err := json.NewDecoder(bytes.NewReader(body)).Decode(result); err != nil {
return nil, err
}

return result, nil
}

// FindSubnet finds a subnet by either part of the ID or part of the name
func (c *Client) FindSubnet(search, networkID string) (*Subnet, error) {
subnets, err := c.ListSubnets(networkID)
if err != nil {
return nil, decodeError(err)
}

exactMatch := false
partialMatchesCount := 0
result := Subnet{}

for _, value := range subnets {
if value.Name == search || value.ID == search {
exactMatch = true
result = value
} else if strings.Contains(value.Name, search) || strings.Contains(value.ID, search) {
if !exactMatch {
result = value
partialMatchesCount++
}
}
}

if exactMatch || partialMatchesCount == 1 {
return &result, nil
} else if partialMatchesCount > 1 {
err := fmt.Errorf("unable to find %s because there were multiple matches", search)
return nil, MultipleMatchesError.wrap(err)
} else {
err := fmt.Errorf("unable to find %s, zero matches", search)
return nil, ZeroMatchesError.wrap(err)
}
}

// DeleteSubnet deletes a subnet
func (c *Client) DeleteSubnet(networkID, subnetID string) (*SimpleResponse, error) {
resp, err := c.SendDeleteRequest(fmt.Sprintf("/v2/networks/%s/subnets/%s", networkID, subnetID))
if err != nil {
return nil, decodeError(err)
}

return c.DecodeSimpleResponse(resp)
}

// CreateNetwork creates a new network
func (c *Client) CreateNetwork(nc NetworkConfig) (*NetworkResult, error) {
body, err := c.SendPostRequest("/v2/networks", nc)
if err != nil {
return nil, decodeError(err)
}

var result = &NetworkResult{}
if err := json.NewDecoder(bytes.NewReader(body)).Decode(result); err != nil {
return nil, err
}

return result, nil
}

// UpdateNetwork updates an existing network
func (c *Client) UpdateNetwork(id string, nc NetworkConfig) (*NetworkResult, error) {
body, err := c.SendPutRequest("/v2/networks/"+id, nc)
if err != nil {
return nil, decodeError(err)
}

var result = &NetworkResult{}
if err := json.NewDecoder(bytes.NewReader(body)).Decode(result); err != nil {
return nil, err
}

return result, nil
}
112 changes: 112 additions & 0 deletions network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,115 @@ func TestDeleteNetwork(t *testing.T) {
t.Errorf("Expected %+v, got %+v", expected, got)
}
}

func TestGetSubnet(t *testing.T) {
client, server, _ := NewClientForTesting(map[string]string{
"/v2/networks/12345/subnets/6789": `{"network_id": "12345", "subnetID": "6789", "name": "test-subnet"}`,
})
defer server.Close()

got, err := client.GetSubnet("12345", "6789")
if err != nil {
t.Errorf("Request returned an error: %s", err)
return
}
if got.Name != "test-subnet" {
t.Errorf("Expected %s, got %s", "test-subnet", got.Name)
}
}

func TestFindSubnet(t *testing.T) {
client, server, _ := NewClientForTesting(map[string]string{
"/v2/networks/12345/subnets": `[
{
"id": "6789",
"name": "test-subnet",
"network_id": "12345"
},
{
"id": "67890",
"name": "test-subnet-2",
"network_id": "12345"
}
]`,
})
defer server.Close()

got, _ := client.FindSubnet("6789", "12345")
if got.ID != "6789" {
t.Errorf("Expected %s, got %s", "6789", got.ID)
}

got, _ = client.FindSubnet("test-subnet-2", "12345")
if got.ID != "67890" {
t.Errorf("Expected %s, got %s", "67890", got.ID)
}
}

func TestCreateSubnet(t *testing.T) {
client, server, _ := NewClientForTesting(map[string]string{
"/v2/networks/12345/subnets": `{"id": "76cc107f-fbef-4e2b-b97f-f5d34f4075d3","network_id": "12345","name": "test-subnet","status": "success"}`,
})
defer server.Close()

subnet := SubnetConfig{
Name: "test-subnet",
}

got, err := client.CreateSubnet("12345", subnet)
if err != nil {
t.Errorf("Request returned an error: %s", err)
return
}

expected := &Subnet{
ID: "76cc107f-fbef-4e2b-b97f-f5d34f4075d3",
Name: "test-subnet",
NetworkID: "12345",
Status: "success",
}

if !reflect.DeepEqual(got, expected) {
t.Errorf("Expected %+v, got %+v", expected, got)
}
}

func TestListSubnets(t *testing.T) {
client, server, _ := NewClientForTesting(map[string]string{
"/v2/networks/12345/subnets": `[{
"id": "6789",
"name": "test-subnet",
"network_id": "12345",
"label": "test-subnet"
}]`,
})
defer server.Close()
got, err := client.ListSubnets("12345")

if err != nil {
t.Errorf("Request returned an error: %s", err)
return
}
expected := []Subnet{{ID: "6789", Name: "test-subnet", NetworkID: "12345"}}
if !reflect.DeepEqual(got, expected) {
t.Errorf("Expected %+v, got %+v", expected, got)
}
}

func TestDeleteSubnet(t *testing.T) {
client, server, _ := NewClientForTesting(map[string]string{
"/v2/networks/12345/subnets/6789": `{"result": "success"}`,
})
defer server.Close()

got, err := client.DeleteSubnet("12345", "6789")
if err != nil {
t.Errorf("Request returned an error: %s", err)
return
}

expected := &SimpleResponse{Result: "success"}
if !reflect.DeepEqual(got, expected) {
t.Errorf("Expected %+v, got %+v", expected, got)
}
}