1
0
mirror of https://github.com/rancher/os.git synced 2025-07-06 11:36:15 +00:00

Vendor changes, github.com/packethost/packngo v0.1.0

This commit is contained in:
niusmallnan 2017-12-19 08:30:37 +00:00 committed by niusmallnan
parent 60909e435f
commit 543f106689
19 changed files with 201 additions and 1294 deletions

View File

@ -32,7 +32,7 @@ github.com/mattn/go-shellwords v1.0.0
github.com/opencontainers/runc edc34c4a8c1e261b5ce926ff557ecde1aff19ce3 https://github.com/ibuildthecloud/runc.git
github.com/opencontainers/runtime-spec f955d90e70a98ddfb886bd930ffd076da9b67998
github.com/opencontainers/specs f955d90e70a98ddfb886bd930ffd076da9b67998
github.com/packethost/packngo 7b3a781a3c8c45b0e55390fa3c4d24981402b99f https://github.com/joshwget/packngo.git
github.com/packethost/packngo v0.1.0
github.com/pkg/errors d62207b3dc916c342cd6a7180fa861d898cf42ee
github.com/pmezard/go-difflib d8ed2627bdf02c080bf22230dbb337003b7aba2d
github.com/rancher/cniglue b56bd68e5df113ad3fcc59c58034c22afaede877

28
vendor/github.com/packethost/packngo/.drone.yml generated vendored Normal file
View File

@ -0,0 +1,28 @@
workspace:
base: /go
path: src/github.com/packethost/packngo
pipeline:
lint:
image: golang:1.8
commands:
- go get -v -u github.com/alecthomas/gometalinter
- gometalinter --install
- go get -v ./...
- |
gometalinter --disable=gas ./... || :
- |
gometalinter --disable-all --enable=gas ./... || :
- |
gofmt -d . | (! grep '.') || ok=false
- if ! $ok; then exit 1; fi
build:
image: golang:1.8
commands:
- go build -i -v ./...
test:
image: golang:1.8
commands:
- go test ./...

28
vendor/github.com/packethost/packngo/.gitignore generated vendored Normal file
View File

@ -0,0 +1,28 @@
### Go template
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
# idea
.idea**/**

9
vendor/github.com/packethost/packngo/README.md generated vendored Normal file
View File

@ -0,0 +1,9 @@
# packngo
Packet Go Api Client
![](https://www.packet.net/media/labs/images/1679091c5a880faf6fb5e6087eb1b2dc/ULY7-hero.png)
Committing
----------
Before committing, it's a good idea to run `gofmt -w *.go`. ([gofmt](https://golang.org/cmd/gofmt/))

View File

@ -1,236 +0,0 @@
package packngo
import "fmt"
const deviceBasePath = "/devices"
// DeviceService interface defines available device methods
type DeviceService interface {
List(ProjectID string) ([]Device, *Response, error)
Get(string) (*Device, *Response, error)
Create(*DeviceCreateRequest) (*Device, *Response, error)
Delete(string) (*Response, error)
Reboot(string) (*Response, error)
PowerOff(string) (*Response, error)
PowerOn(string) (*Response, error)
Lock(string) (*Response, error)
Unlock(string) (*Response, error)
}
type devicesRoot struct {
Devices []Device `json:"devices"`
}
// Device represents a Packet device
type Device struct {
ID string `json:"id"`
Href string `json:"href,omitempty"`
Hostname string `json:"hostname,omitempty"`
State string `json:"state,omitempty"`
Created string `json:"created_at,omitempty"`
Updated string `json:"updated_at,omitempty"`
Locked bool `json:"locked,omitempty"`
BillingCycle string `json:"billing_cycle,omitempty"`
Tags []string `json:"tags,omitempty"`
Network []*IPAddress `json:"ip_addresses"`
OS *OS `json:"operating_system,omitempty"`
Plan *Plan `json:"plan,omitempty"`
Facility *Facility `json:"facility,omitempty"`
Project *Project `json:"project,omitempty"`
ProvisionPer float32 `json:"provisioning_percentage,omitempty"`
}
func (d Device) String() string {
return Stringify(d)
}
// DeviceCreateRequest type used to create a Packet device
type DeviceCreateRequest struct {
HostName string `json:"hostname"`
Plan string `json:"plan"`
Facility string `json:"facility"`
OS string `json:"operating_system"`
BillingCycle string `json:"billing_cycle"`
ProjectID string `json:"project_id"`
UserData string `json:"userdata"`
Tags []string `json:"tags"`
}
func (d DeviceCreateRequest) String() string {
return Stringify(d)
}
// DeviceActionRequest type used to execute actions on devices
type DeviceActionRequest struct {
Type string `json:"type"`
}
func (d DeviceActionRequest) String() string {
return Stringify(d)
}
// IPAddress used to execute actions on devices
type IPAddress struct {
Family int `json:"address_family"`
Cidr int `json:"cidr"`
Address string `json:"address"`
Gateway string `json:"gateway"`
Public bool `json:"public"`
}
func (n IPAddress) String() string {
return Stringify(n)
}
// DeviceServiceOp implements DeviceService
type DeviceServiceOp struct {
client *Client
}
// List returns devices on a project
func (s *DeviceServiceOp) List(projectID string) ([]Device, *Response, error) {
path := fmt.Sprintf("%s/%s/devices?include=facility", projectBasePath, projectID)
req, err := s.client.NewRequest("GET", path, nil)
if err != nil {
return nil, nil, err
}
root := new(devicesRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.Devices, resp, err
}
// Get returns a device by id
func (s *DeviceServiceOp) Get(deviceID string) (*Device, *Response, error) {
path := fmt.Sprintf("%s/%s?include=facility", deviceBasePath, deviceID)
req, err := s.client.NewRequest("GET", path, nil)
if err != nil {
return nil, nil, err
}
device := new(Device)
resp, err := s.client.Do(req, device)
if err != nil {
return nil, resp, err
}
return device, resp, err
}
// Create creates a new device
func (s *DeviceServiceOp) Create(createRequest *DeviceCreateRequest) (*Device, *Response, error) {
path := fmt.Sprintf("%s/%s/devices", projectBasePath, createRequest.ProjectID)
req, err := s.client.NewRequest("POST", path, createRequest)
if err != nil {
return nil, nil, err
}
device := new(Device)
resp, err := s.client.Do(req, device)
if err != nil {
return nil, resp, err
}
return device, resp, err
}
// Delete deletes a device
func (s *DeviceServiceOp) Delete(deviceID string) (*Response, error) {
path := fmt.Sprintf("%s/%s", deviceBasePath, deviceID)
req, err := s.client.NewRequest("DELETE", path, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}
// Reboot reboots on a device
func (s *DeviceServiceOp) Reboot(deviceID string) (*Response, error) {
path := fmt.Sprintf("%s/%s/actions", deviceBasePath, deviceID)
action := &DeviceActionRequest{Type: "reboot"}
req, err := s.client.NewRequest("POST", path, action)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}
// PowerOff powers on a device
func (s *DeviceServiceOp) PowerOff(deviceID string) (*Response, error) {
path := fmt.Sprintf("%s/%s/actions", deviceBasePath, deviceID)
action := &DeviceActionRequest{Type: "power_off"}
req, err := s.client.NewRequest("POST", path, action)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}
// PowerOn powers on a device
func (s *DeviceServiceOp) PowerOn(deviceID string) (*Response, error) {
path := fmt.Sprintf("%s/%s/actions", deviceBasePath, deviceID)
action := &DeviceActionRequest{Type: "power_on"}
req, err := s.client.NewRequest("POST", path, action)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}
type lockDeviceType struct {
Locked bool `json:"locked"`
}
// Lock sets a device to "locked"
func (s *DeviceServiceOp) Lock(deviceID string) (*Response, error) {
path := fmt.Sprintf("%s/%s", deviceBasePath, deviceID)
action := lockDeviceType{Locked: true}
req, err := s.client.NewRequest("PATCH", path, action)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}
// Unlock sets a device to "locked"
func (s *DeviceServiceOp) Unlock(deviceID string) (*Response, error) {
path := fmt.Sprintf("%s/%s", deviceBasePath, deviceID)
action := lockDeviceType{Locked: false}
req, err := s.client.NewRequest("PATCH", path, action)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}

View File

@ -1,40 +0,0 @@
package packngo
const emailBasePath = "/emails"
// EmailService interface defines available email methods
type EmailService interface {
Get(string) (*Email, *Response, error)
}
// Email represents a user's email address
type Email struct {
ID string `json:"id"`
Address string `json:"address"`
Default bool `json:"default,omitempty"`
URL string `json:"href,omitempty"`
}
func (e Email) String() string {
return Stringify(e)
}
// EmailServiceOp implements EmailService
type EmailServiceOp struct {
client *Client
}
// Get retrieves an email by id
func (s *EmailServiceOp) Get(emailID string) (*Email, *Response, error) {
req, err := s.client.NewRequest("GET", emailBasePath, nil)
if err != nil {
return nil, nil, err
}
email := new(Email)
resp, err := s.client.Do(req, email)
if err != nil {
return nil, resp, err
}
return email, resp, err
}

View File

@ -1,55 +0,0 @@
package packngo
const facilityBasePath = "/facilities"
// FacilityService interface defines available facility methods
type FacilityService interface {
List() ([]Facility, *Response, error)
}
type facilityRoot struct {
Facilities []Facility `json:"facilities"`
}
// Facility represents a Packet facility
type Facility struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Code string `json:"code,omitempty"`
Features []string `json:"features,omitempty"`
Address *Address `json:"address,omitempty"`
URL string `json:"href,omitempty"`
}
func (f Facility) String() string {
return Stringify(f)
}
// Address - the physical address of the facility
type Address struct {
ID string `json:"id,omitempty"`
}
func (a Address) String() string {
return Stringify(a)
}
// FacilityServiceOp implements FacilityService
type FacilityServiceOp struct {
client *Client
}
// List returns all available Packet facilities
func (s *FacilityServiceOp) List() ([]Facility, *Response, error) {
req, err := s.client.NewRequest("GET", facilityBasePath, nil)
if err != nil {
return nil, nil, err
}
root := new(facilityRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.Facilities, resp, err
}

View File

@ -1,37 +0,0 @@
package metadata
import (
"net/http"
"net/url"
"github.com/packethost/packngo"
)
const (
baseUrl = "https://metadata.packet.net"
)
type Client struct {
client *packngo.Client
Metadata MetadataService
Userdata UserdataService
}
type MetadataService interface {
Get() (Metadata, error)
}
type UserdataService interface {
Get() (string, error)
}
func NewClient(httpClient *http.Client) *Client {
c := packngo.NewClient("", "", httpClient)
c.BaseURL, _ = url.Parse(baseUrl)
return &Client{
client: c,
Metadata: &MetadataServiceOp{client: c},
Userdata: &UserdataServiceOp{client: c},
}
}

View File

@ -1,73 +1,156 @@
package metadata
import (
"github.com/packethost/packngo"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
)
const BaseURL = "https://metadata.packet.net"
func GetMetadata() (*CurrentDevice, error) {
res, err := http.Get(BaseURL + "/metadata")
if err != nil {
return nil, err
}
b, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return nil, err
}
var result struct {
Error string `json:"error"`
*CurrentDevice
}
if err := json.Unmarshal(b, &result); err != nil {
if res.StatusCode >= 400 {
return nil, errors.New(res.Status)
}
return nil, err
}
if result.Error != "" {
return nil, errors.New(result.Error)
}
return result.CurrentDevice, nil
}
func GetUserData() ([]byte, error) {
res, err := http.Get(BaseURL + "/userdata")
if err != nil {
return nil, err
}
b, err := ioutil.ReadAll(res.Body)
res.Body.Close()
return b, err
}
type AddressFamily int
const (
metadataBasePath = "/metadata"
IPv4 = AddressFamily(4)
IPv6 = AddressFamily(6)
)
type Metadata struct {
PhoneHomeURL string `json:"phone_home_url"`
ApiUrl string `json:"api_url"`
Id string `json:"id"`
Hostname string `json:"hostname"`
Iqn string `json:"iqn"`
OperatingSystem OperatingSystem `json:"operating_system"`
Plan string `json:"plan"`
Facility string `json:"facility"`
SshKeys []string `json:"ssh_keys"`
Network Network `json:"network"`
type AddressInfo struct {
ID string `json:"id"`
Family AddressFamily `json:"address_family"`
Public bool `json:"public"`
Management bool `json:"management"`
Address net.IP `json:"address"`
NetworkMask net.IP `json:"netmask"`
Gateway net.IP `json:"gateway"`
NetworkBits int `json:"cidr"`
// These are available, but not really needed:
// Network net.IP `json:"network"`
}
type Network struct {
Addresses []Address `json:"addresses"`
Interfaces []Interface `json:"interfaces"`
type BondingMode int
const (
BondingBalanceRR = BondingMode(0)
BondingActiveBackup = BondingMode(1)
BondingBalanceXOR = BondingMode(2)
BondingBroadcast = BondingMode(3)
BondingLACP = BondingMode(4)
BondingBalanceTLB = BondingMode(5)
BondingBalanceALB = BondingMode(6)
)
var bondingModeStrings = map[BondingMode]string{
BondingBalanceRR: "balance-rr",
BondingActiveBackup: "active-backup",
BondingBalanceXOR: "balance-xor",
BondingBroadcast: "broadcast",
BondingLACP: "802.3ad",
BondingBalanceTLB: "balance-tlb",
BondingBalanceALB: "balance-alb",
}
type Address struct {
Href string `json:"href"`
Gateway string `json:"gateway"`
Address string `json:"address"`
Network string `json:"network"`
Id string `json:"id"`
AddressFamily int `json:"address_family"`
Netmask string `json:"netmask"`
Public bool `json:"public"`
Cidr int `json:"cidr"`
Management bool `json:"management"`
Manageable bool `json:"manageable"`
AssignedTo Reference `json:"assigned_to"`
func (m BondingMode) String() string {
if str, ok := bondingModeStrings[m]; ok {
return str
}
return fmt.Sprintf("%d", m)
}
type Reference struct {
Href string `json:"href"`
type CurrentDevice struct {
ID string `json:"id"`
Hostname string `json:"hostname"`
IQN string `json:"iqn"`
Plan string `json:"plan"`
Facility string `json:"facility"`
Tags []string `json:"tags"`
SSHKeys []string `json:"ssh_keys"`
OS OperatingSystem `json:"operating_system"`
Network NetworkInfo `json:"network"`
Volumes []VolumeInfo `json:"volume"`
// This is available, but is actually inaccurate, currently:
// APIBaseURL string `json:"api_url"`
}
type InterfaceInfo struct {
Name string `json:"name"`
MAC string `json:"mac"`
}
func (i *InterfaceInfo) ParseMAC() (net.HardwareAddr, error) {
return net.ParseMAC(i.MAC)
}
type NetworkInfo struct {
Interfaces []InterfaceInfo `json:"interfaces"`
Addresses []AddressInfo `json:"addresses"`
Bonding struct {
Mode BondingMode `json:"mode"`
} `json:"bonding"`
}
func (n *NetworkInfo) BondingMode() BondingMode {
return n.Bonding.Mode
}
type OperatingSystem struct {
Version string `json:"version"`
Distro string `json:"distro"`
Slug string `json:"slug"`
Distro string `json:"distro"`
Version string `json:"version"`
}
type Interface struct {
Mac string `json:"mac"`
Name string `json:"name"`
}
type MetadataServiceOp struct {
client *packngo.Client
}
func (s *MetadataServiceOp) Get() (Metadata, error) {
metadata := Metadata{}
req, err := s.client.NewRequest("GET", metadataBasePath, nil)
if err != nil {
return metadata, err
}
_, err = s.client.Do(req, &metadata)
return metadata, err
type VolumeInfo struct {
Name string `json:"name"`
IQN string `json:"iqn"`
IPs []net.IP `json:"ips"`
Capacity struct {
Size int `json:"size,string"`
Unit string `json:"unit"`
} `json:"capacity"`
}

View File

@ -1,26 +0,0 @@
package metadata
import (
"bytes"
"github.com/packethost/packngo"
)
const (
userdataBasePath = "/userdata"
)
type UserdataServiceOp struct {
client *packngo.Client
}
func (s *UserdataServiceOp) Get() (string, error) {
req, err := s.client.NewRequest("GET", userdataBasePath, nil)
if err != nil {
return "", err
}
buffer := &bytes.Buffer{}
_, err = s.client.Do(req, buffer)
return buffer.String(), err
}

View File

@ -1,44 +0,0 @@
package packngo
const osBasePath = "/operating-systems"
// OSService interface defines available operating_systems methods
type OSService interface {
List() ([]OS, *Response, error)
}
type osRoot struct {
OperatingSystems []OS `json:"operating_systems"`
}
// OS represents a Packet operating system
type OS struct {
Name string `json:"name"`
Slug string `json:"slug"`
Distro string `json:"distro"`
Version string `json:"version"`
}
func (o OS) String() string {
return Stringify(o)
}
// OSServiceOp implements OSService
type OSServiceOp struct {
client *Client
}
// List returns all available operating systems
func (s *OSServiceOp) List() ([]OS, *Response, error) {
req, err := s.client.NewRequest("GET", osBasePath, nil)
if err != nil {
return nil, nil, err
}
root := new(osRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.OperatingSystems, resp, err
}

View File

@ -1,205 +0,0 @@
package packngo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
libraryVersion = "0.1.0"
baseURL = "https://api.packet.net/"
userAgent = "packngo/" + libraryVersion
mediaType = "application/json"
headerRateLimit = "X-RateLimit-Limit"
headerRateRemaining = "X-RateLimit-Remaining"
headerRateReset = "X-RateLimit-Reset"
)
// ListOptions specifies optional global API parameters
type ListOptions struct {
// for paginated result sets, page of results to retrieve
Page int `url:"page,omitempty"`
// for paginated result sets, the number of results to return per page
PerPage int `url:"per_page,omitempty"`
// specify which resources you want to return as collections instead of references
Includes string
}
// Response is the http response from api calls
type Response struct {
*http.Response
Rate
}
func (r *Response) populateRate() {
// parse the rate limit headers and populate Response.Rate
if limit := r.Header.Get(headerRateLimit); limit != "" {
r.Rate.RequestLimit, _ = strconv.Atoi(limit)
}
if remaining := r.Header.Get(headerRateRemaining); remaining != "" {
r.Rate.RequestsRemaining, _ = strconv.Atoi(remaining)
}
if reset := r.Header.Get(headerRateReset); reset != "" {
if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 {
r.Rate.Reset = Timestamp{time.Unix(v, 0)}
}
}
}
// ErrorResponse is the http response used on errrors
type ErrorResponse struct {
Response *http.Response
Errors []string `json:"errors"`
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %v",
r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, strings.Join(r.Errors, ", "))
}
// Client is the base API Client
type Client struct {
client *http.Client
BaseURL *url.URL
UserAgent string
ConsumerToken string
APIKey string
RateLimit Rate
// Packet Api Objects
Plans PlanService
Users UserService
Emails EmailService
SSHKeys SSHKeyService
Devices DeviceService
Projects ProjectService
Facilities FacilityService
OperatingSystems OSService
}
// NewRequest inits a new http request with the proper headers
func (c *Client) NewRequest(method, path string, body interface{}) (*http.Request, error) {
// relative path to append to the endpoint url, no leading slash please
rel, err := url.Parse(path)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
// json encode the request body, if any
buf := new(bytes.Buffer)
if body != nil {
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Close = true
req.Header.Add("X-Auth-Token", c.APIKey)
req.Header.Add("X-Consumer-Token", c.ConsumerToken)
req.Header.Add("Content-Type", mediaType)
req.Header.Add("Accept", mediaType)
req.Header.Add("User-Agent", userAgent)
return req, nil
}
// Do executes the http request
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
response := Response{Response: resp}
response.populateRate()
c.RateLimit = response.Rate
err = checkResponse(resp)
// if the response is an error, return the ErrorResponse
if err != nil {
return &response, err
}
if v != nil {
// if v implements the io.Writer interface, return the raw response
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
return &response, err
}
}
}
return &response, err
}
// NewClient initializes and returns a Client, use this to get an API Client to operate on
// N.B.: Packet's API certificate requires Go 1.5+ to successfully parse. If you are using
// an older version of Go, pass in a custom http.Client with a custom TLS configuration
// that sets "InsecureSkipVerify" to "true"
func NewClient(consumerToken string, apiKey string, httpClient *http.Client) *Client {
if httpClient == nil {
// Don't fall back on http.DefaultClient as it's not nice to adjust state
// implicitly. If the client wants to use http.DefaultClient, they can
// pass it in explicitly.
httpClient = &http.Client{}
}
BaseURL, _ := url.Parse(baseURL)
c := &Client{client: httpClient, BaseURL: BaseURL, UserAgent: userAgent, ConsumerToken: consumerToken, APIKey: apiKey}
c.Plans = &PlanServiceOp{client: c}
c.Users = &UserServiceOp{client: c}
c.Emails = &EmailServiceOp{client: c}
c.SSHKeys = &SSHKeyServiceOp{client: c}
c.Devices = &DeviceServiceOp{client: c}
c.Projects = &ProjectServiceOp{client: c}
c.Facilities = &FacilityServiceOp{client: c}
c.OperatingSystems = &OSServiceOp{client: c}
return c
}
func checkResponse(r *http.Response) error {
// return if http status code is within 200 range
if c := r.StatusCode; c >= 200 && c <= 299 {
// response is good, return
return nil
}
errorResponse := &ErrorResponse{Response: r}
data, err := ioutil.ReadAll(r.Body)
// if the response has a body, populate the message in errorResponse
if err == nil && len(data) > 0 {
json.Unmarshal(data, errorResponse)
}
return errorResponse
}

View File

@ -1,114 +0,0 @@
package packngo
const planBasePath = "/plans"
// PlanService interface defines available plan methods
type PlanService interface {
List() ([]Plan, *Response, error)
}
type planRoot struct {
Plans []Plan `json:"plans"`
}
// Plan represents a Packet service plan
type Plan struct {
ID string `json:"id"`
Slug string `json:"slug,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Line string `json:"line,omitempty"`
Specs *Specs `json:"specs,omitempty"`
Pricing *Pricing `json:"pricing,omitempty"`
}
func (p Plan) String() string {
return Stringify(p)
}
// Specs - the server specs for a plan
type Specs struct {
Cpus []*Cpus `json:"cpus,omitempty"`
Memory *Memory `json:"memory,omitempty"`
Drives []*Drives `json:"drives,omitempty"`
Nics []*Nics `json:"nics,omitempty"`
Features *Features `json:"features,omitempty"`
}
func (s Specs) String() string {
return Stringify(s)
}
// Cpus - the CPU config details for specs on a plan
type Cpus struct {
Count int `json:"count,omitempty"`
Type string `json:"type,omitempty"`
}
func (c Cpus) String() string {
return Stringify(c)
}
// Memory - the RAM config details for specs on a plan
type Memory struct {
Total string `json:"total,omitempty"`
}
func (m Memory) String() string {
return Stringify(m)
}
// Drives - the storage config details for specs on a plan
type Drives struct {
Count int `json:"count,omitempty"`
Size string `json:"size,omitempty"`
Type string `json:"type,omitempty"`
}
func (d Drives) String() string {
return Stringify(d)
}
// Nics - the network hardware details for specs on a plan
type Nics struct {
Count int `json:"count,omitempty"`
Type string `json:"type,omitempty"`
}
func (n Nics) String() string {
return Stringify(n)
}
// Features - other features in the specs for a plan
type Features struct {
Raid bool `json:"raid,omitempty"`
Txt bool `json:"txt,omitempty"`
}
func (f Features) String() string {
return Stringify(f)
}
// Pricing - the pricing options on a plan
type Pricing struct {
Hourly float32 `json:"hourly,omitempty"`
Monthly float32 `json:"monthly,omitempty"`
}
func (p Pricing) String() string {
return Stringify(p)
}
// PlanServiceOp implements PlanService
type PlanServiceOp struct {
client *Client
}
// List method returns all available plans
func (s *PlanServiceOp) List() ([]Plan, *Response, error) {
req, err := s.client.NewRequest("GET", planBasePath, nil)
if err != nil {
return nil, nil, err
}
root := new(planRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.Plans, resp, err
}

View File

@ -1,136 +0,0 @@
package packngo
import "fmt"
const projectBasePath = "/projects"
// ProjectService interface defines available project methods
type ProjectService interface {
List() ([]Project, *Response, error)
Get(string) (*Project, *Response, error)
Create(*ProjectCreateRequest) (*Project, *Response, error)
Update(*ProjectUpdateRequest) (*Project, *Response, error)
Delete(string) (*Response, error)
}
type projectsRoot struct {
Projects []Project `json:"projects"`
}
// Project represents a Packet project
type Project struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Created string `json:"created_at,omitempty"`
Updated string `json:"updated_at,omitempty"`
Users []User `json:"members,omitempty"`
Devices []Device `json:"devices,omitempty"`
SSHKeys []SSHKey `json:"ssh_keys,omitempty"`
URL string `json:"href,omitempty"`
}
func (p Project) String() string {
return Stringify(p)
}
// ProjectCreateRequest type used to create a Packet project
type ProjectCreateRequest struct {
Name string `json:"name"`
PaymentMethod string `json:"payment_method,omitempty"`
}
func (p ProjectCreateRequest) String() string {
return Stringify(p)
}
// ProjectUpdateRequest type used to update a Packet project
type ProjectUpdateRequest struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
PaymentMethod string `json:"payment_method,omitempty"`
}
func (p ProjectUpdateRequest) String() string {
return Stringify(p)
}
// ProjectServiceOp implements ProjectService
type ProjectServiceOp struct {
client *Client
}
// List returns the user's projects
func (s *ProjectServiceOp) List() ([]Project, *Response, error) {
req, err := s.client.NewRequest("GET", projectBasePath, nil)
if err != nil {
return nil, nil, err
}
root := new(projectsRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.Projects, resp, err
}
// Get returns a project by id
func (s *ProjectServiceOp) Get(projectID string) (*Project, *Response, error) {
path := fmt.Sprintf("%s/%s", projectBasePath, projectID)
req, err := s.client.NewRequest("GET", path, nil)
if err != nil {
return nil, nil, err
}
project := new(Project)
resp, err := s.client.Do(req, project)
if err != nil {
return nil, resp, err
}
return project, resp, err
}
// Create creates a new project
func (s *ProjectServiceOp) Create(createRequest *ProjectCreateRequest) (*Project, *Response, error) {
req, err := s.client.NewRequest("POST", projectBasePath, createRequest)
if err != nil {
return nil, nil, err
}
project := new(Project)
resp, err := s.client.Do(req, project)
if err != nil {
return nil, resp, err
}
return project, resp, err
}
// Update updates a project
func (s *ProjectServiceOp) Update(updateRequest *ProjectUpdateRequest) (*Project, *Response, error) {
path := fmt.Sprintf("%s/%s", projectBasePath, updateRequest.ID)
req, err := s.client.NewRequest("PATCH", path, updateRequest)
if err != nil {
return nil, nil, err
}
project := new(Project)
resp, err := s.client.Do(req, project)
if err != nil {
return nil, resp, err
}
return project, resp, err
}
// Delete deletes a project
func (s *ProjectServiceOp) Delete(projectID string) (*Response, error) {
path := fmt.Sprintf("%s/%s", projectBasePath, projectID)
req, err := s.client.NewRequest("DELETE", path, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}

View File

@ -1,11 +0,0 @@
package packngo
// Rate provides the API request rate limit details
type Rate struct {
RequestLimit int `json:"request_limit"`
RequestsRemaining int `json:"requests_remaining"`
Reset Timestamp `json:"rate_reset"`
}
func (r Rate) String() string {
return Stringify(r)
}

View File

@ -1,138 +0,0 @@
package packngo
import "fmt"
const sshKeyBasePath = "/ssh-keys"
// SSHKeyService interface defines available device methods
type SSHKeyService interface {
List() ([]SSHKey, *Response, error)
Get(string) (*SSHKey, *Response, error)
Create(*SSHKeyCreateRequest) (*SSHKey, *Response, error)
Update(*SSHKeyUpdateRequest) (*SSHKey, *Response, error)
Delete(string) (*Response, error)
}
type sshKeyRoot struct {
SSHKeys []SSHKey `json:"ssh_keys"`
}
// SSHKey represents a user's ssh key
type SSHKey struct {
ID string `json:"id"`
Label string `json:"label"`
Key string `json:"key"`
FingerPrint string `json:"fingerprint"`
Created string `json:"created_at"`
Updated string `json:"updated_at"`
User User `json:"user,omitempty"`
URL string `json:"href,omitempty"`
}
func (s SSHKey) String() string {
return Stringify(s)
}
// SSHKeyCreateRequest type used to create an ssh key
type SSHKeyCreateRequest struct {
Label string `json:"label"`
Key string `json:"key"`
}
func (s SSHKeyCreateRequest) String() string {
return Stringify(s)
}
// SSHKeyUpdateRequest type used to update an ssh key
type SSHKeyUpdateRequest struct {
ID string `json:"id"`
Label string `json:"label"`
Key string `json:"key"`
}
func (s SSHKeyUpdateRequest) String() string {
return Stringify(s)
}
// SSHKeyServiceOp implements SSHKeyService
type SSHKeyServiceOp struct {
client *Client
}
// List returns a user's ssh keys
func (s *SSHKeyServiceOp) List() ([]SSHKey, *Response, error) {
req, err := s.client.NewRequest("GET", sshKeyBasePath, nil)
if err != nil {
return nil, nil, err
}
root := new(sshKeyRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.SSHKeys, resp, err
}
// Get returns an ssh key by id
func (s *SSHKeyServiceOp) Get(sshKeyID string) (*SSHKey, *Response, error) {
path := fmt.Sprintf("%s/%s", sshKeyBasePath, sshKeyID)
req, err := s.client.NewRequest("GET", path, nil)
if err != nil {
return nil, nil, err
}
sshKey := new(SSHKey)
resp, err := s.client.Do(req, sshKey)
if err != nil {
return nil, resp, err
}
return sshKey, resp, err
}
// Create creates a new ssh key
func (s *SSHKeyServiceOp) Create(createRequest *SSHKeyCreateRequest) (*SSHKey, *Response, error) {
req, err := s.client.NewRequest("POST", sshKeyBasePath, createRequest)
if err != nil {
return nil, nil, err
}
sshKey := new(SSHKey)
resp, err := s.client.Do(req, sshKey)
if err != nil {
return nil, resp, err
}
return sshKey, resp, err
}
// Update updates an ssh key
func (s *SSHKeyServiceOp) Update(updateRequest *SSHKeyUpdateRequest) (*SSHKey, *Response, error) {
path := fmt.Sprintf("%s/%s", sshKeyBasePath, updateRequest.ID)
req, err := s.client.NewRequest("PATCH", path, updateRequest)
if err != nil {
return nil, nil, err
}
sshKey := new(SSHKey)
resp, err := s.client.Do(req, sshKey)
if err != nil {
return nil, resp, err
}
return sshKey, resp, err
}
// Delete deletes an ssh key
func (s *SSHKeyServiceOp) Delete(sshKeyID string) (*Response, error) {
path := fmt.Sprintf("%s/%s", sshKeyBasePath, sshKeyID)
req, err := s.client.NewRequest("DELETE", path, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
return resp, err
}

View File

@ -1,35 +0,0 @@
package packngo
import (
"strconv"
"time"
)
// Timestamp represents a time that can be unmarshalled from a JSON string
// formatted as either an RFC3339 or Unix timestamp. All
// exported methods of time.Time can be called on Timestamp.
type Timestamp struct {
time.Time
}
func (t Timestamp) String() string {
return t.Time.String()
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// Time is expected in RFC3339 or Unix format.
func (t *Timestamp) UnmarshalJSON(data []byte) (err error) {
str := string(data)
i, err := strconv.ParseInt(str, 10, 64)
if err == nil {
t.Time = time.Unix(i, 0)
} else {
t.Time, err = time.Parse(`"`+time.RFC3339+`"`, str)
}
return
}
// Equal reports whether t and u are equal based on time.Equal
func (t Timestamp) Equal(u Timestamp) bool {
return t.Time.Equal(u.Time)
}

View File

@ -1,52 +0,0 @@
package packngo
const userBasePath = "/users"
// UserService interface defines available user methods
type UserService interface {
Get(string) (*User, *Response, error)
}
// User represents a Packet user
type User struct {
ID string `json:"id"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
FullName string `json:"full_name,omitempty"`
Email string `json:"email,omitempty"`
TwoFactor string `json:"two_factor_auth,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
Facebook string `json:"twitter,omitempty"`
Twitter string `json:"facebook,omitempty"`
LinkedIn string `json:"linkedin,omitempty"`
Created string `json:"created_at,omitempty"`
Updated string `json:"updated_at,omitempty"`
TimeZone string `json:"timezone,omitempty"`
Emails []Email `json:"email,omitempty"`
PhoneNumber string `json:"phone_number,omitempty"`
URL string `json:"href,omitempty"`
}
func (u User) String() string {
return Stringify(u)
}
// UserServiceOp implements UserService
type UserServiceOp struct {
client *Client
}
// Get method gets a user by userID
func (s *UserServiceOp) Get(userID string) (*User, *Response, error) {
req, err := s.client.NewRequest("GET", userBasePath, nil)
if err != nil {
return nil, nil, err
}
user := new(User)
resp, err := s.client.Do(req, user)
if err != nil {
return nil, resp, err
}
return user, resp, err
}

View File

@ -1,112 +0,0 @@
package packngo
import (
"bytes"
"fmt"
"io"
"reflect"
)
var timestampType = reflect.TypeOf(Timestamp{})
// Stringify creates a string representation of the provided message
func Stringify(message interface{}) string {
var buf bytes.Buffer
v := reflect.ValueOf(message)
stringifyValue(&buf, v)
return buf.String()
}
// String allocates a new string value to store v and returns a pointer to it
func String(v string) *string {
p := new(string)
*p = v
return p
}
// Int allocates a new int32 value to store v and returns a pointer to it, but unlike Int32 its argument value is an int.
func Int(v int) *int {
p := new(int)
*p = v
return p
}
// Bool allocates a new bool value to store v and returns a pointer to it.
func Bool(v bool) *bool {
p := new(bool)
*p = v
return p
}
// StreamToString converts a reader to a string
func StreamToString(stream io.Reader) string {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.String()
}
// stringifyValue was graciously cargoculted from the goprotubuf library
func stringifyValue(w io.Writer, val reflect.Value) {
if val.Kind() == reflect.Ptr && val.IsNil() {
w.Write([]byte("<nil>"))
return
}
v := reflect.Indirect(val)
switch v.Kind() {
case reflect.String:
fmt.Fprintf(w, `"%s"`, v)
case reflect.Slice:
w.Write([]byte{'['})
for i := 0; i < v.Len(); i++ {
if i > 0 {
w.Write([]byte{' '})
}
stringifyValue(w, v.Index(i))
}
w.Write([]byte{']'})
return
case reflect.Struct:
if v.Type().Name() != "" {
w.Write([]byte(v.Type().String()))
}
// special handling of Timestamp values
if v.Type() == timestampType {
fmt.Fprintf(w, "{%s}", v.Interface())
return
}
w.Write([]byte{'{'})
var sep bool
for i := 0; i < v.NumField(); i++ {
fv := v.Field(i)
if fv.Kind() == reflect.Ptr && fv.IsNil() {
continue
}
if fv.Kind() == reflect.Slice && fv.IsNil() {
continue
}
if sep {
w.Write([]byte(", "))
} else {
sep = true
}
w.Write([]byte(v.Type().Field(i).Name))
w.Write([]byte{':'})
stringifyValue(w, fv)
}
w.Write([]byte{'}'})
default:
if v.CanInterface() {
fmt.Fprint(w, v.Interface())
}
}
}