1
0
Fork 0

Vendor main dependencies.

This commit is contained in:
Timo Reimann 2017-02-07 22:33:23 +01:00
parent 49a09ab7dd
commit dd5e3fba01
2738 changed files with 1045689 additions and 0 deletions

59
vendor/github.com/JamesClonk/vultr/lib/account_info.go generated vendored Normal file
View file

@ -0,0 +1,59 @@
package lib
import (
"encoding/json"
"fmt"
"strconv"
)
// AccountInfo of Vultr account
type AccountInfo struct {
Balance float64 `json:"balance"`
PendingCharges float64 `json:"pending_charges"`
LastPaymentDate string `json:"last_payment_date"`
LastPaymentAmount float64 `json:"last_payment_amount"`
}
// GetAccountInfo retrieves the Vultr account information about current balance, pending charges, etc..
func (c *Client) GetAccountInfo() (info AccountInfo, err error) {
if err := c.get(`account/info`, &info); err != nil {
return AccountInfo{}, err
}
return
}
// UnmarshalJSON implements json.Unmarshaller on AccountInfo.
// This is needed because the Vultr API is inconsistent in it's JSON responses for account info.
// Some fields can change type, from JSON number to JSON string and vice-versa.
func (a *AccountInfo) UnmarshalJSON(data []byte) (err error) {
if a == nil {
*a = AccountInfo{}
}
var fields map[string]interface{}
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
b, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["balance"]), 64)
if err != nil {
return err
}
a.Balance = b
pc, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["pending_charges"]), 64)
if err != nil {
return err
}
a.PendingCharges = pc
lpa, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["last_payment_amount"]), 64)
if err != nil {
return err
}
a.LastPaymentAmount = lpa
a.LastPaymentDate = fmt.Sprintf("%v", fields["last_payment_date"])
return
}

188
vendor/github.com/JamesClonk/vultr/lib/block_storage.go generated vendored Normal file
View file

@ -0,0 +1,188 @@
package lib
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
)
// BlockStorage on Vultr account
type BlockStorage struct {
ID string `json:"SUBID,string"`
Name string `json:"label"`
RegionID int `json:"DCID,string"`
SizeGB int `json:"size_gb,string"`
Created string `json:"date_created"`
Cost string `json:"cost_per_month"`
Status string `json:"status"`
AttachedTo string `json:"attached_to_SUBID"`
}
// UnmarshalJSON implements json.Unmarshaller on BlockStorage.
// This is needed because the Vultr API is inconsistent in it's JSON responses.
// Some fields can change type, from JSON number to JSON string and vice-versa.
func (b *BlockStorage) UnmarshalJSON(data []byte) (err error) {
if b == nil {
*b = BlockStorage{}
}
var fields map[string]interface{}
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
value := fmt.Sprintf("%v", fields["SUBID"])
if len(value) == 0 || value == "<nil>" || value == "0" {
b.ID = ""
} else {
id, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
b.ID = strconv.FormatFloat(id, 'f', -1, 64)
}
value = fmt.Sprintf("%v", fields["DCID"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
region, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
b.RegionID = int(region)
value = fmt.Sprintf("%v", fields["size_gb"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
size, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
b.SizeGB = int(size)
value = fmt.Sprintf("%v", fields["attached_to_SUBID"])
if len(value) == 0 || value == "<nil>" || value == "0" {
b.AttachedTo = ""
} else {
attached, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
b.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64)
}
b.Name = fmt.Sprintf("%v", fields["label"])
b.Created = fmt.Sprintf("%v", fields["date_created"])
b.Status = fmt.Sprintf("%v", fields["status"])
b.Cost = fmt.Sprintf("%v", fields["cost_per_month"])
return
}
// GetBlockStorages returns a list of all active block storages on Vultr account
func (c *Client) GetBlockStorages() (storages []BlockStorage, err error) {
if err := c.get(`block/list`, &storages); err != nil {
return nil, err
}
return storages, nil
}
// GetBlockStorage returns block storage with given ID
func (c *Client) GetBlockStorage(id string) (BlockStorage, error) {
storages, err := c.GetBlockStorages()
if err != nil {
return BlockStorage{}, err
}
for _, s := range storages {
if s.ID == id {
return s, nil
}
}
return BlockStorage{}, fmt.Errorf("BlockStorage with ID %v not found", id)
}
// CreateBlockStorage creates a new block storage on Vultr account
func (c *Client) CreateBlockStorage(name string, regionID, size int) (BlockStorage, error) {
values := url.Values{
"label": {name},
"DCID": {fmt.Sprintf("%v", regionID)},
"size_gb": {fmt.Sprintf("%v", size)},
}
var storage BlockStorage
if err := c.post(`block/create`, values, &storage); err != nil {
return BlockStorage{}, err
}
storage.RegionID = regionID
storage.Name = name
storage.SizeGB = size
return storage, nil
}
// ResizeBlockStorage resizes an existing block storage
func (c *Client) ResizeBlockStorage(id string, size int) error {
values := url.Values{
"SUBID": {id},
"size_gb": {fmt.Sprintf("%v", size)},
}
if err := c.post(`block/resize`, values, nil); err != nil {
return err
}
return nil
}
// LabelBlockStorage changes the label on an existing block storage
func (c *Client) LabelBlockStorage(id, name string) error {
values := url.Values{
"SUBID": {id},
"label": {name},
}
if err := c.post(`block/label_set`, values, nil); err != nil {
return err
}
return nil
}
// AttachBlockStorage attaches block storage to an existing virtual machine
func (c *Client) AttachBlockStorage(id, serverID string) error {
values := url.Values{
"SUBID": {id},
"attach_to_SUBID": {serverID},
}
if err := c.post(`block/attach`, values, nil); err != nil {
return err
}
return nil
}
// DetachBlockStorage detaches block storage from virtual machine
func (c *Client) DetachBlockStorage(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`block/detach`, values, nil); err != nil {
return err
}
return nil
}
// DeleteBlockStorage deletes an existing block storage
func (c *Client) DeleteBlockStorage(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`block/delete`, values, nil); err != nil {
return err
}
return nil
}

231
vendor/github.com/JamesClonk/vultr/lib/client.go generated vendored Normal file
View file

@ -0,0 +1,231 @@
package lib
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
"github.com/juju/ratelimit"
)
const (
// Version of this libary
Version = "1.12.0"
// APIVersion of Vultr
APIVersion = "v1"
// DefaultEndpoint to be used
DefaultEndpoint = "https://api.vultr.com/"
mediaType = "application/json"
)
// retryableStatusCodes are API response status codes that indicate that
// the failed request can be retried without further actions.
var retryableStatusCodes = map[int]struct{}{
503: {}, // Rate limit hit
500: {}, // Internal server error. Try again at a later time.
}
// Client represents the Vultr API client
type Client struct {
// HTTP client for communication with the Vultr API
client *http.Client
// User agent for HTTP client
UserAgent string
// Endpoint URL for API requests
Endpoint *url.URL
// API key for accessing the Vultr API
APIKey string
// Max. number of request attempts
MaxAttempts int
// Throttling struct
bucket *ratelimit.Bucket
}
// Options represents optional settings and flags that can be passed to NewClient
type Options struct {
// HTTP client for communication with the Vultr API
HTTPClient *http.Client
// User agent for HTTP client
UserAgent string
// Endpoint URL for API requests
Endpoint string
// API rate limitation, calls per duration
RateLimitation time.Duration
// Max. number of times to retry API calls
MaxRetries int
}
// NewClient creates new Vultr API client. Options are optional and can be nil.
func NewClient(apiKey string, options *Options) *Client {
userAgent := "vultr-go/" + Version
transport := &http.Transport{
TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper),
}
client := http.DefaultClient
client.Transport = transport
endpoint, _ := url.Parse(DefaultEndpoint)
rate := 505 * time.Millisecond
attempts := 1
if options != nil {
if options.HTTPClient != nil {
client = options.HTTPClient
}
if options.UserAgent != "" {
userAgent = options.UserAgent
}
if options.Endpoint != "" {
endpoint, _ = url.Parse(options.Endpoint)
}
if options.RateLimitation != 0 {
rate = options.RateLimitation
}
if options.MaxRetries != 0 {
attempts = options.MaxRetries + 1
}
}
return &Client{
UserAgent: userAgent,
client: client,
Endpoint: endpoint,
APIKey: apiKey,
MaxAttempts: attempts,
bucket: ratelimit.NewBucket(rate, 1),
}
}
func apiPath(path string) string {
return fmt.Sprintf("/%s/%s", APIVersion, path)
}
func apiKeyPath(path, apiKey string) string {
if strings.Contains(path, "?") {
return path + "&api_key=" + apiKey
}
return path + "?api_key=" + apiKey
}
func (c *Client) get(path string, data interface{}) error {
req, err := c.newRequest("GET", apiPath(path), nil)
if err != nil {
return err
}
return c.do(req, data)
}
func (c *Client) post(path string, values url.Values, data interface{}) error {
req, err := c.newRequest("POST", apiPath(path), strings.NewReader(values.Encode()))
if err != nil {
return err
}
return c.do(req, data)
}
func (c *Client) newRequest(method string, path string, body io.Reader) (*http.Request, error) {
relPath, err := url.Parse(apiKeyPath(path, c.APIKey))
if err != nil {
return nil, err
}
url := c.Endpoint.ResolveReference(relPath)
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("Accept", mediaType)
if req.Method == "POST" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
return req, nil
}
func (c *Client) do(req *http.Request, data interface{}) error {
// Throttle http requests to avoid hitting Vultr's API rate-limit
c.bucket.Wait(1)
var apiError error
for tryCount := 1; tryCount <= c.MaxAttempts; tryCount++ {
resp, err := c.client.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode == http.StatusOK {
if data != nil {
// avoid unmarshalling problem because Vultr API returns
// empty array instead of empty map when it shouldn't!
if string(body) == `[]` {
data = nil
} else {
if err := json.Unmarshal(body, data); err != nil {
return err
}
}
}
return nil
}
apiError = errors.New(string(body))
if !isCodeRetryable(resp.StatusCode) {
break
}
delay := backoffDuration(tryCount)
time.Sleep(delay)
}
return apiError
}
// backoffDuration returns the duration to wait before retrying the request.
// Duration is an exponential function of the retry count with a jitter of ~0-30%.
func backoffDuration(retryCount int) time.Duration {
// Upper limit of delay at ~1 minute
if retryCount > 7 {
retryCount = 7
}
rand.Seed(time.Now().UnixNano())
delay := (1 << uint(retryCount)) * (rand.Intn(150) + 500)
return time.Duration(delay) * time.Millisecond
}
// isCodeRetryable returns true if the given status code means that we should retry.
func isCodeRetryable(statusCode int) bool {
if _, ok := retryableStatusCodes[statusCode]; ok {
return true
}
return false
}

119
vendor/github.com/JamesClonk/vultr/lib/dns.go generated vendored Normal file
View file

@ -0,0 +1,119 @@
package lib
import (
"fmt"
"net/url"
)
// DNSDomain represents a DNS domain on Vultr
type DNSDomain struct {
Domain string `json:"domain"`
Created string `json:"date_created"`
}
// DNSRecord represents a DNS record on Vultr
type DNSRecord struct {
RecordID int `json:"RECORDID"`
Type string `json:"type"`
Name string `json:"name"`
Data string `json:"data"`
Priority int `json:"priority"`
TTL int `json:"ttl"`
}
// GetDNSDomains returns a list of available domains on Vultr account
func (c *Client) GetDNSDomains() (dnsdomains []DNSDomain, err error) {
if err := c.get(`dns/list`, &dnsdomains); err != nil {
return nil, err
}
return dnsdomains, nil
}
// GetDNSRecords returns a list of all DNS records of a particular domain
func (c *Client) GetDNSRecords(domain string) (dnsrecords []DNSRecord, err error) {
if err := c.get(`dns/records?domain=`+domain, &dnsrecords); err != nil {
return nil, err
}
return dnsrecords, nil
}
// CreateDNSDomain creates a new DNS domain name on Vultr
func (c *Client) CreateDNSDomain(domain, serverIP string) error {
values := url.Values{
"domain": {domain},
"serverIP": {serverIP},
}
if err := c.post(`dns/create_domain`, values, nil); err != nil {
return err
}
return nil
}
// DeleteDNSDomain deletes an existing DNS domain name
func (c *Client) DeleteDNSDomain(domain string) error {
values := url.Values{
"domain": {domain},
}
if err := c.post(`dns/delete_domain`, values, nil); err != nil {
return err
}
return nil
}
// CreateDNSRecord creates a new DNS record
func (c *Client) CreateDNSRecord(domain, name, rtype, data string, priority, ttl int) error {
values := url.Values{
"domain": {domain},
"name": {name},
"type": {rtype},
"data": {data},
"priority": {fmt.Sprintf("%v", priority)},
"ttl": {fmt.Sprintf("%v", ttl)},
}
if err := c.post(`dns/create_record`, values, nil); err != nil {
return err
}
return nil
}
// UpdateDNSRecord updates an existing DNS record
func (c *Client) UpdateDNSRecord(domain string, dnsrecord DNSRecord) error {
values := url.Values{
"domain": {domain},
"RECORDID": {fmt.Sprintf("%v", dnsrecord.RecordID)},
}
if dnsrecord.Name != "" {
values.Add("name", dnsrecord.Name)
}
if dnsrecord.Data != "" {
values.Add("data", dnsrecord.Data)
}
if dnsrecord.Priority != 0 {
values.Add("priority", fmt.Sprintf("%v", dnsrecord.Priority))
}
if dnsrecord.TTL != 0 {
values.Add("ttl", fmt.Sprintf("%v", dnsrecord.TTL))
}
if err := c.post(`dns/update_record`, values, nil); err != nil {
return err
}
return nil
}
// DeleteDNSRecord deletes an existing DNS record
func (c *Client) DeleteDNSRecord(domain string, recordID int) error {
values := url.Values{
"domain": {domain},
"RECORDID": {fmt.Sprintf("%v", recordID)},
}
if err := c.post(`dns/delete_record`, values, nil); err != nil {
return err
}
return nil
}

125
vendor/github.com/JamesClonk/vultr/lib/ip.go generated vendored Normal file
View file

@ -0,0 +1,125 @@
package lib
import "net/url"
// IPv4 information of a virtual machine
type IPv4 struct {
IP string `json:"ip"`
Netmask string `json:"netmask"`
Gateway string `json:"gateway"`
Type string `json:"type"`
ReverseDNS string `json:"reverse"`
}
// IPv6 information of a virtual machine
type IPv6 struct {
IP string `json:"ip"`
Network string `json:"network"`
NetworkSize string `json:"network_size"`
Type string `json:"type"`
}
// ReverseDNSIPv6 information of a virtual machine
type ReverseDNSIPv6 struct {
IP string `json:"ip"`
ReverseDNS string `json:"reverse"`
}
// ListIPv4 lists the IPv4 information of a virtual machine
func (c *Client) ListIPv4(id string) (list []IPv4, err error) {
var ipMap map[string][]IPv4
if err := c.get(`server/list_ipv4?SUBID=`+id, &ipMap); err != nil {
return nil, err
}
for _, iplist := range ipMap {
for _, ip := range iplist {
list = append(list, ip)
}
}
return list, nil
}
// ListIPv6 lists the IPv4 information of a virtual machine
func (c *Client) ListIPv6(id string) (list []IPv6, err error) {
var ipMap map[string][]IPv6
if err := c.get(`server/list_ipv6?SUBID=`+id, &ipMap); err != nil {
return nil, err
}
for _, iplist := range ipMap {
for _, ip := range iplist {
list = append(list, ip)
}
}
return list, nil
}
// ListIPv6ReverseDNS lists the IPv6 reverse DNS entries of a virtual machine
func (c *Client) ListIPv6ReverseDNS(id string) (list []ReverseDNSIPv6, err error) {
var ipMap map[string][]ReverseDNSIPv6
if err := c.get(`server/reverse_list_ipv6?SUBID=`+id, &ipMap); err != nil {
return nil, err
}
for _, iplist := range ipMap {
for _, ip := range iplist {
list = append(list, ip)
}
}
return list, nil
}
// DeleteIPv6ReverseDNS removes a reverse DNS entry for an IPv6 address of a virtual machine
func (c *Client) DeleteIPv6ReverseDNS(id string, ip string) error {
values := url.Values{
"SUBID": {id},
"ip": {ip},
}
if err := c.post(`server/reverse_delete_ipv6`, values, nil); err != nil {
return err
}
return nil
}
// SetIPv6ReverseDNS sets a reverse DNS entry for an IPv6 address of a virtual machine
func (c *Client) SetIPv6ReverseDNS(id, ip, entry string) error {
values := url.Values{
"SUBID": {id},
"ip": {ip},
"entry": {entry},
}
if err := c.post(`server/reverse_set_ipv6`, values, nil); err != nil {
return err
}
return nil
}
// DefaultIPv4ReverseDNS sets a reverse DNS entry for an IPv4 address of a virtual machine to the original setting
func (c *Client) DefaultIPv4ReverseDNS(id, ip string) error {
values := url.Values{
"SUBID": {id},
"ip": {ip},
}
if err := c.post(`server/reverse_default_ipv4`, values, nil); err != nil {
return err
}
return nil
}
// SetIPv4ReverseDNS sets a reverse DNS entry for an IPv4 address of a virtual machine
func (c *Client) SetIPv4ReverseDNS(id, ip, entry string) error {
values := url.Values{
"SUBID": {id},
"ip": {ip},
"entry": {entry},
}
if err := c.post(`server/reverse_set_ipv4`, values, nil); err != nil {
return err
}
return nil
}

24
vendor/github.com/JamesClonk/vultr/lib/iso.go generated vendored Normal file
View file

@ -0,0 +1,24 @@
package lib
// ISO image on Vultr
type ISO struct {
ID int `json:"ISOID"`
Created string `json:"date_created"`
Filename string `json:"filename"`
Size int `json:"size"`
MD5sum string `json:"md5sum"`
}
// GetISO returns a list of all ISO images on Vultr account
func (c *Client) GetISO() ([]ISO, error) {
var isoMap map[string]ISO
if err := c.get(`iso/list`, &isoMap); err != nil {
return nil, err
}
var isoList []ISO
for _, iso := range isoMap {
isoList = append(isoList, iso)
}
return isoList, nil
}

25
vendor/github.com/JamesClonk/vultr/lib/os.go generated vendored Normal file
View file

@ -0,0 +1,25 @@
package lib
// OS image on Vultr
type OS struct {
ID int `json:"OSID"`
Name string `json:"name"`
Arch string `json:"arch"`
Family string `json:"family"`
Windows bool `json:"windows"`
Surcharge string `json:"surcharge"`
}
// GetOS returns a list of all available operating systems on Vultr
func (c *Client) GetOS() ([]OS, error) {
var osMap map[string]OS
if err := c.get(`os/list`, &osMap); err != nil {
return nil, err
}
var osList []OS
for _, os := range osMap {
osList = append(osList, os)
}
return osList, nil
}

37
vendor/github.com/JamesClonk/vultr/lib/plans.go generated vendored Normal file
View file

@ -0,0 +1,37 @@
package lib
import "fmt"
// Plan on Vultr
type Plan struct {
ID int `json:"VPSPLANID,string"`
Name string `json:"name"`
VCpus int `json:"vcpu_count,string"`
RAM string `json:"ram"`
Disk string `json:"disk"`
Bandwidth string `json:"bandwidth"`
Price string `json:"price_per_month"`
Regions []int `json:"available_locations"`
}
// GetPlans returns a list of all available plans on Vultr account
func (c *Client) GetPlans() ([]Plan, error) {
var planMap map[string]Plan
if err := c.get(`plans/list`, &planMap); err != nil {
return nil, err
}
var planList []Plan
for _, plan := range planMap {
planList = append(planList, plan)
}
return planList, nil
}
// GetAvailablePlansForRegion returns available plans for specified region
func (c *Client) GetAvailablePlansForRegion(id int) (planIDs []int, err error) {
if err := c.get(fmt.Sprintf(`regions/availability?DCID=%v`, id), &planIDs); err != nil {
return nil, err
}
return
}

27
vendor/github.com/JamesClonk/vultr/lib/regions.go generated vendored Normal file
View file

@ -0,0 +1,27 @@
package lib
// Region on Vultr
type Region struct {
ID int `json:"DCID,string"`
Name string `json:"name"`
Country string `json:"country"`
Continent string `json:"continent"`
State string `json:"state"`
Ddos bool `json:"ddos_protection"`
BlockStorage bool `json:"block_storage"`
Code string `json:"regioncode"`
}
// GetRegions returns a list of all available Vultr regions
func (c *Client) GetRegions() ([]Region, error) {
var regionMap map[string]Region
if err := c.get(`regions/list`, &regionMap); err != nil {
return nil, err
}
var regionList []Region
for _, os := range regionMap {
regionList = append(regionList, os)
}
return regionList, nil
}

170
vendor/github.com/JamesClonk/vultr/lib/reservedip.go generated vendored Normal file
View file

@ -0,0 +1,170 @@
package lib
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
)
// IP on Vultr
type IP struct {
ID string `json:"SUBID,string"`
RegionID int `json:"DCID,string"`
IPType string `json:"ip_type"`
Subnet string `json:"subnet"`
SubnetSize int `json:"subnet_size"`
Label string `json:"label"`
AttachedTo string `json:"attached_SUBID,string"`
}
// UnmarshalJSON implements json.Unmarshaller on IP.
// This is needed because the Vultr API is inconsistent in it's JSON responses.
// Some fields can change type, from JSON number to JSON string and vice-versa.
func (i *IP) UnmarshalJSON(data []byte) (err error) {
if i == nil {
*i = IP{}
}
var fields map[string]interface{}
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
value := fmt.Sprintf("%v", fields["SUBID"])
if len(value) == 0 || value == "<nil>" || value == "0" {
i.ID = ""
} else {
id, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
i.ID = strconv.FormatFloat(id, 'f', -1, 64)
}
value = fmt.Sprintf("%v", fields["DCID"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
region, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
i.RegionID = int(region)
value = fmt.Sprintf("%v", fields["attached_SUBID"])
if len(value) == 0 || value == "<nil>" || value == "0" || value == "false" {
i.AttachedTo = ""
} else {
attached, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
i.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64)
}
value = fmt.Sprintf("%v", fields["subnet_size"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
size, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
i.SubnetSize = int(size)
i.IPType = fmt.Sprintf("%v", fields["ip_type"])
i.Subnet = fmt.Sprintf("%v", fields["subnet"])
i.Label = fmt.Sprintf("%v", fields["label"])
return
}
// ListReservedIP returns a list of all available reserved IPs on Vultr account
func (c *Client) ListReservedIP() ([]IP, error) {
var ipMap map[string]IP
err := c.get(`reservedip/list`, &ipMap)
if err != nil {
return nil, err
}
ips := make([]IP, 0)
for _, ip := range ipMap {
ips = append(ips, ip)
}
return ips, nil
}
// GetReservedIP returns reserved IP with given ID
func (c *Client) GetReservedIP(id string) (IP, error) {
var ipMap map[string]IP
err := c.get(`reservedip/list`, &ipMap)
if err != nil {
return IP{}, err
}
if ip, ok := ipMap[id]; ok {
return ip, nil
}
return IP{}, fmt.Errorf("IP with ID %v not found", id)
}
// CreateReservedIP creates a new reserved IP on Vultr account
func (c *Client) CreateReservedIP(regionID int, ipType string, label string) (string, error) {
values := url.Values{
"DCID": {fmt.Sprintf("%v", regionID)},
"ip_type": {ipType},
}
if len(label) > 0 {
values.Add("label", label)
}
result := IP{}
err := c.post(`reservedip/create`, values, &result)
if err != nil {
return "", err
}
return result.ID, nil
}
// DestroyReservedIP deletes an existing reserved IP
func (c *Client) DestroyReservedIP(id string) error {
values := url.Values{
"SUBID": {id},
}
return c.post(`reservedip/destroy`, values, nil)
}
// AttachReservedIP attaches a reserved IP to a virtual machine
func (c *Client) AttachReservedIP(ip string, serverID string) error {
values := url.Values{
"ip_address": {ip},
"attach_SUBID": {serverID},
}
return c.post(`reservedip/attach`, values, nil)
}
// DetachReservedIP detaches a reserved IP from an existing virtual machine
func (c *Client) DetachReservedIP(serverID string, ip string) error {
values := url.Values{
"ip_address": {ip},
"detach_SUBID": {serverID},
}
return c.post(`reservedip/detach`, values, nil)
}
// ConvertReservedIP converts an existing virtual machines IP to a reserved IP
func (c *Client) ConvertReservedIP(serverID string, ip string) (string, error) {
values := url.Values{
"SUBID": {serverID},
"ip_address": {ip},
}
result := IP{}
err := c.post(`reservedip/convert`, values, &result)
if err != nil {
return "", err
}
return result.ID, err
}

115
vendor/github.com/JamesClonk/vultr/lib/scripts.go generated vendored Normal file
View file

@ -0,0 +1,115 @@
package lib
import (
"encoding/json"
"fmt"
"net/url"
)
// StartupScript on Vultr account
type StartupScript struct {
ID string `json:"SCRIPTID"`
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"script"`
}
// UnmarshalJSON implements json.Unmarshaller on StartupScript.
// Necessary because the SCRIPTID field has inconsistent types.
func (s *StartupScript) UnmarshalJSON(data []byte) (err error) {
if s == nil {
*s = StartupScript{}
}
var fields map[string]interface{}
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
s.ID = fmt.Sprintf("%v", fields["SCRIPTID"])
s.Name = fmt.Sprintf("%v", fields["name"])
s.Type = fmt.Sprintf("%v", fields["type"])
s.Content = fmt.Sprintf("%v", fields["script"])
return
}
// GetStartupScripts returns a list of all startup scripts on the current Vultr account
func (c *Client) GetStartupScripts() (scripts []StartupScript, err error) {
var scriptMap map[string]StartupScript
if err := c.get(`startupscript/list`, &scriptMap); err != nil {
return nil, err
}
for _, script := range scriptMap {
if script.Type == "" {
script.Type = "boot" // set default script type
}
scripts = append(scripts, script)
}
return scripts, nil
}
// GetStartupScript returns the startup script with the given ID
func (c *Client) GetStartupScript(id string) (StartupScript, error) {
scripts, err := c.GetStartupScripts()
if err != nil {
return StartupScript{}, err
}
for _, s := range scripts {
if s.ID == id {
return s, nil
}
}
return StartupScript{}, nil
}
// CreateStartupScript creates a new startup script
func (c *Client) CreateStartupScript(name, content, scriptType string) (StartupScript, error) {
values := url.Values{
"name": {name},
"script": {content},
"type": {scriptType},
}
var script StartupScript
if err := c.post(`startupscript/create`, values, &script); err != nil {
return StartupScript{}, err
}
script.Name = name
script.Content = content
script.Type = scriptType
return script, nil
}
// UpdateStartupScript updates an existing startup script
func (c *Client) UpdateStartupScript(script StartupScript) error {
values := url.Values{
"SCRIPTID": {script.ID},
}
if script.Name != "" {
values.Add("name", script.Name)
}
if script.Content != "" {
values.Add("script", script.Content)
}
if err := c.post(`startupscript/update`, values, nil); err != nil {
return err
}
return nil
}
// DeleteStartupScript deletes an existing startup script from Vultr account
func (c *Client) DeleteStartupScript(id string) error {
values := url.Values{
"SCRIPTID": {id},
}
if err := c.post(`startupscript/destroy`, values, nil); err != nil {
return err
}
return nil
}

448
vendor/github.com/JamesClonk/vultr/lib/servers.go generated vendored Normal file
View file

@ -0,0 +1,448 @@
package lib
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strconv"
)
// Server (virtual machine) on Vultr account
type Server struct {
ID string `json:"SUBID"`
Name string `json:"label"`
OS string `json:"os"`
RAM string `json:"ram"`
Disk string `json:"disk"`
MainIP string `json:"main_ip"`
VCpus int `json:"vcpu_count,string"`
Location string `json:"location"`
RegionID int `json:"DCID,string"`
DefaultPassword string `json:"default_password"`
Created string `json:"date_created"`
PendingCharges float64 `json:"pending_charges"`
Status string `json:"status"`
Cost string `json:"cost_per_month"`
CurrentBandwidth float64 `json:"current_bandwidth_gb"`
AllowedBandwidth float64 `json:"allowed_bandwidth_gb,string"`
NetmaskV4 string `json:"netmask_v4"`
GatewayV4 string `json:"gateway_v4"`
PowerStatus string `json:"power_status"`
ServerState string `json:"server_state"`
PlanID int `json:"VPSPLANID,string"`
V6Networks []V6Network `json:"v6_networks"`
InternalIP string `json:"internal_ip"`
KVMUrl string `json:"kvm_url"`
AutoBackups string `json:"auto_backups"`
Tag string `json:"tag"`
}
// ServerOptions are optional parameters to be used during server creation
type ServerOptions struct {
IPXEChainURL string
ISO int
Script int
UserData string
Snapshot string
SSHKey string
IPV6 bool
PrivateNetworking bool
AutoBackups bool
DontNotifyOnActivate bool
Hostname string
Tag string
}
// V6Network represents a IPv6 network of a Vultr server
type V6Network struct {
Network string `json:"v6_network"`
MainIP string `json:"v6_main_ip"`
NetworkSize string `json:"v6_network_size"`
}
// ISOStatus represents an ISO image attached to a Vultr server
type ISOStatus struct {
State string `json:"state"`
ISOID string `json:"ISOID"`
}
// UnmarshalJSON implements json.Unmarshaller on Server.
// This is needed because the Vultr API is inconsistent in it's JSON responses for servers.
// Some fields can change type, from JSON number to JSON string and vice-versa.
func (s *Server) UnmarshalJSON(data []byte) (err error) {
if s == nil {
*s = Server{}
}
var fields map[string]interface{}
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
value := fmt.Sprintf("%v", fields["vcpu_count"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
vcpu, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
s.VCpus = int(vcpu)
value = fmt.Sprintf("%v", fields["DCID"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
region, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
s.RegionID = int(region)
value = fmt.Sprintf("%v", fields["VPSPLANID"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
plan, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
s.PlanID = int(plan)
value = fmt.Sprintf("%v", fields["pending_charges"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
pc, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
s.PendingCharges = pc
value = fmt.Sprintf("%v", fields["current_bandwidth_gb"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
cb, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
s.CurrentBandwidth = cb
value = fmt.Sprintf("%v", fields["allowed_bandwidth_gb"])
if len(value) == 0 || value == "<nil>" {
value = "0"
}
ab, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
s.AllowedBandwidth = ab
s.ID = fmt.Sprintf("%v", fields["SUBID"])
s.Name = fmt.Sprintf("%v", fields["label"])
s.OS = fmt.Sprintf("%v", fields["os"])
s.RAM = fmt.Sprintf("%v", fields["ram"])
s.Disk = fmt.Sprintf("%v", fields["disk"])
s.MainIP = fmt.Sprintf("%v", fields["main_ip"])
s.Location = fmt.Sprintf("%v", fields["location"])
s.DefaultPassword = fmt.Sprintf("%v", fields["default_password"])
s.Created = fmt.Sprintf("%v", fields["date_created"])
s.Status = fmt.Sprintf("%v", fields["status"])
s.Cost = fmt.Sprintf("%v", fields["cost_per_month"])
s.NetmaskV4 = fmt.Sprintf("%v", fields["netmask_v4"])
s.GatewayV4 = fmt.Sprintf("%v", fields["gateway_v4"])
s.PowerStatus = fmt.Sprintf("%v", fields["power_status"])
s.ServerState = fmt.Sprintf("%v", fields["server_state"])
v6networks := make([]V6Network, 0)
if networks, ok := fields["v6_networks"].([]interface{}); ok {
for _, network := range networks {
if network, ok := network.(map[string]interface{}); ok {
v6network := V6Network{
Network: fmt.Sprintf("%v", network["v6_network"]),
MainIP: fmt.Sprintf("%v", network["v6_main_ip"]),
NetworkSize: fmt.Sprintf("%v", network["v6_network_size"]),
}
v6networks = append(v6networks, v6network)
}
}
s.V6Networks = v6networks
}
s.InternalIP = fmt.Sprintf("%v", fields["internal_ip"])
s.KVMUrl = fmt.Sprintf("%v", fields["kvm_url"])
s.AutoBackups = fmt.Sprintf("%v", fields["auto_backups"])
s.Tag = fmt.Sprintf("%v", fields["tag"])
return
}
// GetServers returns a list of current virtual machines on Vultr account
func (c *Client) GetServers() (servers []Server, err error) {
var serverMap map[string]Server
if err := c.get(`server/list`, &serverMap); err != nil {
return nil, err
}
for _, server := range serverMap {
servers = append(servers, server)
}
return servers, nil
}
// GetServersByTag returns a list of all virtual machines matching by tag
func (c *Client) GetServersByTag(tag string) (servers []Server, err error) {
var serverMap map[string]Server
if err := c.get(`server/list?tag=`+tag, &serverMap); err != nil {
return nil, err
}
for _, server := range serverMap {
servers = append(servers, server)
}
return servers, nil
}
// GetServer returns the virtual machine with the given ID
func (c *Client) GetServer(id string) (server Server, err error) {
if err := c.get(`server/list?SUBID=`+id, &server); err != nil {
return Server{}, err
}
return server, nil
}
// CreateServer creates a new virtual machine on Vultr. ServerOptions are optional settings.
func (c *Client) CreateServer(name string, regionID, planID, osID int, options *ServerOptions) (Server, error) {
values := url.Values{
"label": {name},
"DCID": {fmt.Sprintf("%v", regionID)},
"VPSPLANID": {fmt.Sprintf("%v", planID)},
"OSID": {fmt.Sprintf("%v", osID)},
}
if options != nil {
if options.IPXEChainURL != "" {
values.Add("ipxe_chain_url", options.IPXEChainURL)
}
if options.ISO != 0 {
values.Add("ISOID", fmt.Sprintf("%v", options.ISO))
}
if options.Script != 0 {
values.Add("SCRIPTID", fmt.Sprintf("%v", options.Script))
}
if options.UserData != "" {
values.Add("userdata", base64.StdEncoding.EncodeToString([]byte(options.UserData)))
}
if options.Snapshot != "" {
values.Add("SNAPSHOTID", options.Snapshot)
}
if options.SSHKey != "" {
values.Add("SSHKEYID", options.SSHKey)
}
values.Add("enable_ipv6", "no")
if options.IPV6 {
values.Set("enable_ipv6", "yes")
}
values.Add("enable_private_network", "no")
if options.PrivateNetworking {
values.Set("enable_private_network", "yes")
}
values.Add("auto_backups", "no")
if options.AutoBackups {
values.Set("auto_backups", "yes")
}
values.Add("notify_activate", "yes")
if options.DontNotifyOnActivate {
values.Set("notify_activate", "no")
}
if options.Hostname != "" {
values.Add("hostname", options.Hostname)
}
if options.Tag != "" {
values.Add("tag", options.Tag)
}
}
var server Server
if err := c.post(`server/create`, values, &server); err != nil {
return Server{}, err
}
server.Name = name
server.RegionID = regionID
server.PlanID = planID
return server, nil
}
// RenameServer renames an existing virtual machine
func (c *Client) RenameServer(id, name string) error {
values := url.Values{
"SUBID": {id},
"label": {name},
}
if err := c.post(`server/label_set`, values, nil); err != nil {
return err
}
return nil
}
// StartServer starts an existing virtual machine
func (c *Client) StartServer(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`server/start`, values, nil); err != nil {
return err
}
return nil
}
// HaltServer stops an existing virtual machine
func (c *Client) HaltServer(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`server/halt`, values, nil); err != nil {
return err
}
return nil
}
// RebootServer reboots an existing virtual machine
func (c *Client) RebootServer(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`server/reboot`, values, nil); err != nil {
return err
}
return nil
}
// ReinstallServer reinstalls the operating system on an existing virtual machine
func (c *Client) ReinstallServer(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`server/reinstall`, values, nil); err != nil {
return err
}
return nil
}
// ChangeOSofServer changes the virtual machine to a different operating system
func (c *Client) ChangeOSofServer(id string, osID int) error {
values := url.Values{
"SUBID": {id},
"OSID": {fmt.Sprintf("%v", osID)},
}
if err := c.post(`server/os_change`, values, nil); err != nil {
return err
}
return nil
}
// ListOSforServer lists all available operating systems to which an existing virtual machine can be changed
func (c *Client) ListOSforServer(id string) (os []OS, err error) {
var osMap map[string]OS
if err := c.get(`server/os_change_list?SUBID=`+id, &osMap); err != nil {
return nil, err
}
for _, o := range osMap {
os = append(os, o)
}
return os, nil
}
// AttachISOtoServer attaches an ISO image to an existing virtual machine and reboots it
func (c *Client) AttachISOtoServer(id string, isoID int) error {
values := url.Values{
"SUBID": {id},
"ISOID": {fmt.Sprintf("%v", isoID)},
}
if err := c.post(`server/iso_attach`, values, nil); err != nil {
return err
}
return nil
}
// DetachISOfromServer detaches the currently mounted ISO image from the virtual machine and reboots it
func (c *Client) DetachISOfromServer(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`server/iso_detach`, values, nil); err != nil {
return err
}
return nil
}
// GetISOStatusofServer retrieves the current ISO image state of an existing virtual machine
func (c *Client) GetISOStatusofServer(id string) (isoStatus ISOStatus, err error) {
if err := c.get(`server/iso_status?SUBID=`+id, &isoStatus); err != nil {
return ISOStatus{}, err
}
return isoStatus, nil
}
// DeleteServer deletes an existing virtual machine
func (c *Client) DeleteServer(id string) error {
values := url.Values{
"SUBID": {id},
}
if err := c.post(`server/destroy`, values, nil); err != nil {
return err
}
return nil
}
// BandwidthOfServer retrieves the bandwidth used by a virtual machine
func (c *Client) BandwidthOfServer(id string) (bandwidth []map[string]string, err error) {
var bandwidthMap map[string][][]string
if err := c.get(`server/bandwidth?SUBID=`+id, &bandwidthMap); err != nil {
return nil, err
}
// parse incoming bytes
for _, b := range bandwidthMap["incoming_bytes"] {
bMap := make(map[string]string)
bMap["date"] = b[0]
bMap["incoming"] = b[1]
bandwidth = append(bandwidth, bMap)
}
// parse outgoing bytes (we'll assume that incoming and outgoing dates are always a match)
for _, b := range bandwidthMap["outgoing_bytes"] {
for i := range bandwidth {
if bandwidth[i]["date"] == b[0] {
bandwidth[i]["outgoing"] = b[1]
break
}
}
}
return bandwidth, nil
}

53
vendor/github.com/JamesClonk/vultr/lib/snapshots.go generated vendored Normal file
View file

@ -0,0 +1,53 @@
package lib
import "net/url"
// Snapshot of a virtual machine on Vultr account
type Snapshot struct {
ID string `json:"SNAPSHOTID"`
Description string `json:"description"`
Size string `json:"size"`
Status string `json:"status"`
Created string `json:"date_created"`
}
// GetSnapshots retrieves a list of all snapshots on Vultr account
func (c *Client) GetSnapshots() (snapshots []Snapshot, err error) {
var snapshotMap map[string]Snapshot
if err := c.get(`snapshot/list`, &snapshotMap); err != nil {
return nil, err
}
for _, snapshot := range snapshotMap {
snapshots = append(snapshots, snapshot)
}
return snapshots, nil
}
// CreateSnapshot creates a new virtual machine snapshot
func (c *Client) CreateSnapshot(id, description string) (Snapshot, error) {
values := url.Values{
"SUBID": {id},
"description": {description},
}
var snapshot Snapshot
if err := c.post(`snapshot/create`, values, &snapshot); err != nil {
return Snapshot{}, err
}
snapshot.Description = description
return snapshot, nil
}
// DeleteSnapshot deletes an existing virtual machine snapshot
func (c *Client) DeleteSnapshot(id string) error {
values := url.Values{
"SNAPSHOTID": {id},
}
if err := c.post(`snapshot/destroy`, values, nil); err != nil {
return err
}
return nil
}

71
vendor/github.com/JamesClonk/vultr/lib/sshkeys.go generated vendored Normal file
View file

@ -0,0 +1,71 @@
package lib
import "net/url"
// SSHKey on Vultr account
type SSHKey struct {
ID string `json:"SSHKEYID"`
Name string `json:"name"`
Key string `json:"ssh_key"`
Created string `json:"date_created"`
}
// GetSSHKeys returns a list of SSHKeys from Vultr account
func (c *Client) GetSSHKeys() (keys []SSHKey, err error) {
var keyMap map[string]SSHKey
if err := c.get(`sshkey/list`, &keyMap); err != nil {
return nil, err
}
for _, key := range keyMap {
keys = append(keys, key)
}
return keys, nil
}
// CreateSSHKey creates new SSHKey on Vultr
func (c *Client) CreateSSHKey(name, key string) (SSHKey, error) {
values := url.Values{
"name": {name},
"ssh_key": {key},
}
var sshKey SSHKey
if err := c.post(`sshkey/create`, values, &sshKey); err != nil {
return SSHKey{}, err
}
sshKey.Name = name
sshKey.Key = key
return sshKey, nil
}
// UpdateSSHKey updates an existing SSHKey entry
func (c *Client) UpdateSSHKey(key SSHKey) error {
values := url.Values{
"SSHKEYID": {key.ID},
}
if key.Name != "" {
values.Add("name", key.Name)
}
if key.Key != "" {
values.Add("ssh_key", key.Key)
}
if err := c.post(`sshkey/update`, values, nil); err != nil {
return err
}
return nil
}
// DeleteSSHKey deletes an existing SSHKey from Vultr account
func (c *Client) DeleteSSHKey(id string) error {
values := url.Values{
"SSHKEYID": {id},
}
if err := c.post(`sshkey/destroy`, values, nil); err != nil {
return err
}
return nil
}