vlans.go raw

   1  package linodego
   2  
   3  import (
   4  	"context"
   5  	"encoding/json"
   6  	"fmt"
   7  	"time"
   8  
   9  	"github.com/linode/linodego/internal/parseabletime"
  10  )
  11  
  12  type VLAN struct {
  13  	Label   string     `json:"label"`
  14  	Linodes []int      `json:"linodes"`
  15  	Region  string     `json:"region"`
  16  	Created *time.Time `json:"-"`
  17  }
  18  
  19  // UnmarshalJSON for VLAN responses
  20  func (v *VLAN) UnmarshalJSON(b []byte) error {
  21  	type Mask VLAN
  22  
  23  	p := struct {
  24  		*Mask
  25  
  26  		Created *parseabletime.ParseableTime `json:"created"`
  27  	}{
  28  		Mask: (*Mask)(v),
  29  	}
  30  
  31  	if err := json.Unmarshal(b, &p); err != nil {
  32  		return err
  33  	}
  34  
  35  	v.Created = (*time.Time)(p.Created)
  36  
  37  	return nil
  38  }
  39  
  40  // ListVLANs returns a paginated list of VLANs
  41  func (c *Client) ListVLANs(ctx context.Context, opts *ListOptions) ([]VLAN, error) {
  42  	return getPaginatedResults[VLAN](ctx, c, "networking/vlans", opts)
  43  }
  44  
  45  // GetVLANIPAMAddress returns the IPAM Address for a given VLAN Label as a string (10.0.0.1/24)
  46  func (c *Client) GetVLANIPAMAddress(ctx context.Context, linodeID int, vlanLabel string) (string, error) {
  47  	f := Filter{}
  48  	f.AddField(Eq, "interfaces", vlanLabel)
  49  
  50  	vlanFilter, err := f.MarshalJSON()
  51  	if err != nil {
  52  		return "", fmt.Errorf("Unable to convert VLAN label: %s to a filterable object: %w", vlanLabel, err)
  53  	}
  54  
  55  	cfgs, err := c.ListInstanceConfigs(ctx, linodeID, &ListOptions{Filter: string(vlanFilter)})
  56  	if err != nil {
  57  		return "", fmt.Errorf("Fetching configs for instance %v failed: %w", linodeID, err)
  58  	}
  59  
  60  	interfaces := cfgs[0].Interfaces
  61  	for _, face := range interfaces {
  62  		if face.Label == vlanLabel {
  63  			return face.IPAMAddress, nil
  64  		}
  65  	}
  66  
  67  	return "", fmt.Errorf("Failed to find IPAMAddress for VLAN: %s", vlanLabel)
  68  }
  69