Merge pull request #6475 from hashicorp/b-oh-godeps

godeps: fixup missing deps
This commit is contained in:
Paul Hinze 2016-05-04 11:06:21 -05:00
commit 8cf13d9582
80 changed files with 1906 additions and 7363 deletions

35
Godeps/Godeps.json generated
View File

@ -1,7 +1,7 @@
{
"ImportPath": "github.com/hashicorp/terraform",
"GoVersion": "go1.6",
"GodepVersion": "v62",
"GodepVersion": "v63",
"Packages": [
"./..."
],
@ -548,10 +548,6 @@
"Comment": "v2.3.0-alpha.0-652-ge552791",
"Rev": "e5527914aa42cae3063f52892e1ca4518da0e4ae"
},
{
"ImportPath": "github.com/crackcomm/cloudflare",
"Rev": "40f33bf6a6721e6d266a98d29e5a94afbe0169ed"
},
{
"ImportPath": "github.com/cyberdelia/heroku-go/v3",
"Rev": "81c5afa1abcf69cc18ccc24fa3716b5a455c9208"
@ -925,6 +921,31 @@
"ImportPath": "github.com/mattn/go-isatty",
"Rev": "56b76bdf51f7708750eac80fa38b952bb9f32639"
},
{
"ImportPath": "github.com/maximilien/softlayer-go/client",
"Comment": "v0.6.0",
"Rev": "85659debe44fab5792fc92cf755c04b115b9dc19"
},
{
"ImportPath": "github.com/maximilien/softlayer-go/common",
"Comment": "v0.6.0",
"Rev": "85659debe44fab5792fc92cf755c04b115b9dc19"
},
{
"ImportPath": "github.com/maximilien/softlayer-go/data_types",
"Comment": "v0.6.0",
"Rev": "85659debe44fab5792fc92cf755c04b115b9dc19"
},
{
"ImportPath": "github.com/maximilien/softlayer-go/services",
"Comment": "v0.6.0",
"Rev": "85659debe44fab5792fc92cf755c04b115b9dc19"
},
{
"ImportPath": "github.com/maximilien/softlayer-go/softlayer",
"Comment": "v0.6.0",
"Rev": "85659debe44fab5792fc92cf755c04b115b9dc19"
},
{
"ImportPath": "github.com/mitchellh/cli",
"Rev": "cb6853d606ea4a12a15ac83cc43503df99fd28fb"
@ -995,10 +1016,6 @@
"ImportPath": "github.com/pborman/uuid",
"Rev": "dee7705ef7b324f27ceb85a121c61f2c2e8ce988"
},
{
"ImportPath": "github.com/pearkes/cloudflare",
"Rev": "765ac1828a78ba49e6dc48309d56415c61806ac3"
},
{
"ImportPath": "github.com/pearkes/dnsimple",
"Rev": "78996265f576c7580ff75d0cb2c606a61883ceb8"

View File

@ -8,9 +8,9 @@ go:
- tip
- 1.3
# - 1.2
# Note: 1.2 is disabled because it seems to require that cover
# Note: 1.2 is disabled because it seems to require that cover
# be installed from code.google.com/p/go.tools/cmd/cover
before_install:
- go get -v golang.org/x/tools/cmd/cover
- go get -v golang.org/x/tools/cmd/vet

50
vendor/github.com/ajg/form/README.md generated vendored
View File

@ -34,13 +34,13 @@ Given a type like the following...
```go
type User struct {
Name string `form:"name"`
Email string `form:"email"`
Joined time.Time `form:"joined,omitempty"`
Posts []int `form:"posts"`
Preferences map[string]string `form:"prefs"`
Avatar []byte `form:"avatar"`
PasswordHash int64 `form:"-"`
Name string `form:"name"`
Email string `form:"email"`
Joined time.Time `form:"joined,omitempty"`
Posts []int `form:"posts"`
Preferences map[string]string `form:"prefs"`
Avatar []byte `form:"avatar"`
PasswordHash int64 `form:"-"`
}
```
@ -49,9 +49,9 @@ type User struct {
```go
func PostUser(url string, u User) error {
var c http.Client
_, err := c.PostForm(url, form.EncodeToValues(u))
return err
var c http.Client
_, err := c.PostForm(url, form.EncodeToValues(u))
return err
}
```
@ -60,15 +60,15 @@ func PostUser(url string, u User) error {
```go
func Handler(w http.ResponseWriter, r *http.Request) {
var u User
var u User
d := form.NewDecoder(r.Body)
if err := d.Decode(&u); err != nil {
http.Error(w, "Form could not be decoded", http.StatusBadRequest)
return
}
d := form.NewDecoder(r.Body)
if err := d.Decode(&u); err != nil {
http.Error(w, "Form could not be decoded", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Decoded: %#v", u)
fmt.Fprintf(w, "Decoded: %#v", u)
}
```
@ -149,20 +149,20 @@ import "encoding"
type Binary []byte
var (
_ encoding.TextMarshaler = &Binary{}
_ encoding.TextUnmarshaler = &Binary{}
_ encoding.TextMarshaler = &Binary{}
_ encoding.TextUnmarshaler = &Binary{}
)
func (b Binary) MarshalText() ([]byte, error) {
return []byte(base64.URLEncoding.EncodeToString([]byte(b))), nil
return []byte(base64.URLEncoding.EncodeToString([]byte(b))), nil
}
func (b *Binary) UnmarshalText(text []byte) error {
bs, err := base64.URLEncoding.DecodeString(string(text))
if err == nil {
*b = Binary(bs)
}
return err
bs, err := base64.URLEncoding.DecodeString(string(text))
if err == nil {
*b = Binary(bs)
}
return err
}
```

522
vendor/github.com/ajg/form/decode.go generated vendored
View File

@ -5,326 +5,326 @@
package form
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"reflect"
"strconv"
"time"
"fmt"
"io"
"io/ioutil"
"net/url"
"reflect"
"strconv"
"time"
)
// NewDecoder returns a new form decoder.
func NewDecoder(r io.Reader) *decoder {
return &decoder{r}
return &decoder{r}
}
// decoder decodes data from a form (application/x-www-form-urlencoded).
type decoder struct {
r io.Reader
r io.Reader
}
// Decode reads in and decodes form-encoded data into dst.
func (d decoder) Decode(dst interface{}) error {
bs, err := ioutil.ReadAll(d.r)
if err != nil {
return err
}
vs, err := url.ParseQuery(string(bs))
if err != nil {
return err
}
v := reflect.ValueOf(dst)
return decodeNode(v, parseValues(vs, canIndexOrdinally(v)))
bs, err := ioutil.ReadAll(d.r)
if err != nil {
return err
}
vs, err := url.ParseQuery(string(bs))
if err != nil {
return err
}
v := reflect.ValueOf(dst)
return decodeNode(v, parseValues(vs, canIndexOrdinally(v)))
}
// DecodeString decodes src into dst.
func DecodeString(dst interface{}, src string) error {
vs, err := url.ParseQuery(src)
if err != nil {
return err
}
v := reflect.ValueOf(dst)
return decodeNode(v, parseValues(vs, canIndexOrdinally(v)))
vs, err := url.ParseQuery(src)
if err != nil {
return err
}
v := reflect.ValueOf(dst)
return decodeNode(v, parseValues(vs, canIndexOrdinally(v)))
}
// DecodeValues decodes vs into dst.
func DecodeValues(dst interface{}, vs url.Values) error {
v := reflect.ValueOf(dst)
return decodeNode(v, parseValues(vs, canIndexOrdinally(v)))
v := reflect.ValueOf(dst)
return decodeNode(v, parseValues(vs, canIndexOrdinally(v)))
}
func decodeNode(v reflect.Value, n node) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
if v.Kind() == reflect.Slice {
return fmt.Errorf("could not decode directly into slice; use pointer to slice")
}
decodeValue(v, n)
return nil
if v.Kind() == reflect.Slice {
return fmt.Errorf("could not decode directly into slice; use pointer to slice")
}
decodeValue(v, n)
return nil
}
func decodeValue(v reflect.Value, x interface{}) {
t := v.Type()
k := v.Kind()
t := v.Type()
k := v.Kind()
if k == reflect.Ptr && v.IsNil() {
v.Set(reflect.New(t.Elem()))
}
if k == reflect.Ptr && v.IsNil() {
v.Set(reflect.New(t.Elem()))
}
if unmarshalValue(v, x) {
return
}
if unmarshalValue(v, x) {
return
}
empty := isEmpty(x)
empty := isEmpty(x)
switch k {
case reflect.Ptr:
decodeValue(v.Elem(), x)
return
case reflect.Interface:
if !v.IsNil() {
decodeValue(v.Elem(), x)
return
switch k {
case reflect.Ptr:
decodeValue(v.Elem(), x)
return
case reflect.Interface:
if !v.IsNil() {
decodeValue(v.Elem(), x)
return
} else if empty {
return // Allow nil interfaces only if empty.
} else {
panic("form: cannot decode non-empty value into into nil interface")
}
}
} else if empty {
return // Allow nil interfaces only if empty.
} else {
panic("form: cannot decode non-empty value into into nil interface")
}
}
if empty {
v.Set(reflect.Zero(t)) // Treat the empty string as the zero value.
return
}
if empty {
v.Set(reflect.Zero(t)) // Treat the empty string as the zero value.
return
}
switch k {
case reflect.Struct:
if t.ConvertibleTo(timeType) {
decodeTime(v, x)
} else if t.ConvertibleTo(urlType) {
decodeURL(v, x)
} else {
decodeStruct(v, x)
}
case reflect.Slice:
decodeSlice(v, x)
case reflect.Array:
decodeArray(v, x)
case reflect.Map:
decodeMap(v, x)
case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
panic(t.String() + " has unsupported kind " + k.String())
default:
decodeBasic(v, x)
}
switch k {
case reflect.Struct:
if t.ConvertibleTo(timeType) {
decodeTime(v, x)
} else if t.ConvertibleTo(urlType) {
decodeURL(v, x)
} else {
decodeStruct(v, x)
}
case reflect.Slice:
decodeSlice(v, x)
case reflect.Array:
decodeArray(v, x)
case reflect.Map:
decodeMap(v, x)
case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
panic(t.String() + " has unsupported kind " + k.String())
default:
decodeBasic(v, x)
}
}
func decodeStruct(v reflect.Value, x interface{}) {
t := v.Type()
for k, c := range getNode(x) {
if f, ok := findField(v, k); !ok && k == "" {
panic(getString(x) + " cannot be decoded as " + t.String())
} else if !ok {
panic(k + " doesn't exist in " + t.String())
} else if !f.CanSet() {
panic(k + " cannot be set in " + t.String())
} else {
decodeValue(f, c)
}
}
t := v.Type()
for k, c := range getNode(x) {
if f, ok := findField(v, k); !ok && k == "" {
panic(getString(x) + " cannot be decoded as " + t.String())
} else if !ok {
panic(k + " doesn't exist in " + t.String())
} else if !f.CanSet() {
panic(k + " cannot be set in " + t.String())
} else {
decodeValue(f, c)
}
}
}
func decodeMap(v reflect.Value, x interface{}) {
t := v.Type()
if v.IsNil() {
v.Set(reflect.MakeMap(t))
}
for k, c := range getNode(x) {
i := reflect.New(t.Key()).Elem()
decodeValue(i, k)
t := v.Type()
if v.IsNil() {
v.Set(reflect.MakeMap(t))
}
for k, c := range getNode(x) {
i := reflect.New(t.Key()).Elem()
decodeValue(i, k)
w := v.MapIndex(i)
if w.IsValid() { // We have an actual element value to decode into.
if w.Kind() == reflect.Interface {
w = w.Elem()
}
w = reflect.New(w.Type()).Elem()
} else if t.Elem().Kind() != reflect.Interface { // The map's element type is concrete.
w = reflect.New(t.Elem()).Elem()
} else {
// The best we can do here is to decode as either a string (for scalars) or a map[string]interface {} (for the rest).
// We could try to guess the type based on the string (e.g. true/false => bool) but that'll get ugly fast,
// especially if we have to guess the kind (slice vs. array vs. map) and index type (e.g. string, int, etc.)
switch c.(type) {
case node:
w = reflect.MakeMap(stringMapType)
case string:
w = reflect.New(stringType).Elem()
default:
panic("value is neither node nor string")
}
}
w := v.MapIndex(i)
if w.IsValid() { // We have an actual element value to decode into.
if w.Kind() == reflect.Interface {
w = w.Elem()
}
w = reflect.New(w.Type()).Elem()
} else if t.Elem().Kind() != reflect.Interface { // The map's element type is concrete.
w = reflect.New(t.Elem()).Elem()
} else {
// The best we can do here is to decode as either a string (for scalars) or a map[string]interface {} (for the rest).
// We could try to guess the type based on the string (e.g. true/false => bool) but that'll get ugly fast,
// especially if we have to guess the kind (slice vs. array vs. map) and index type (e.g. string, int, etc.)
switch c.(type) {
case node:
w = reflect.MakeMap(stringMapType)
case string:
w = reflect.New(stringType).Elem()
default:
panic("value is neither node nor string")
}
}
decodeValue(w, c)
v.SetMapIndex(i, w)
}
decodeValue(w, c)
v.SetMapIndex(i, w)
}
}
func decodeArray(v reflect.Value, x interface{}) {
t := v.Type()
for k, c := range getNode(x) {
i, err := strconv.Atoi(k)
if err != nil {
panic(k + " is not a valid index for type " + t.String())
}
if l := v.Len(); i >= l {
panic("index is above array size")
}
decodeValue(v.Index(i), c)
}
t := v.Type()
for k, c := range getNode(x) {
i, err := strconv.Atoi(k)
if err != nil {
panic(k + " is not a valid index for type " + t.String())
}
if l := v.Len(); i >= l {
panic("index is above array size")
}
decodeValue(v.Index(i), c)
}
}
func decodeSlice(v reflect.Value, x interface{}) {
t := v.Type()
if t.Elem().Kind() == reflect.Uint8 {
// Allow, but don't require, byte slices to be encoded as a single string.
if s, ok := x.(string); ok {
v.SetBytes([]byte(s))
return
}
}
t := v.Type()
if t.Elem().Kind() == reflect.Uint8 {
// Allow, but don't require, byte slices to be encoded as a single string.
if s, ok := x.(string); ok {
v.SetBytes([]byte(s))
return
}
}
// NOTE: Implicit indexing is currently done at the parseValues level,
// so if if an implicitKey reaches here it will always replace the last.
implicit := 0
for k, c := range getNode(x) {
var i int
if k == implicitKey {
i = implicit
implicit++
} else {
explicit, err := strconv.Atoi(k)
if err != nil {
panic(k + " is not a valid index for type " + t.String())
}
i = explicit
implicit = explicit + 1
}
// "Extend" the slice if it's too short.
if l := v.Len(); i >= l {
delta := i - l + 1
v.Set(reflect.AppendSlice(v, reflect.MakeSlice(t, delta, delta)))
}
decodeValue(v.Index(i), c)
}
// NOTE: Implicit indexing is currently done at the parseValues level,
// so if if an implicitKey reaches here it will always replace the last.
implicit := 0
for k, c := range getNode(x) {
var i int
if k == implicitKey {
i = implicit
implicit++
} else {
explicit, err := strconv.Atoi(k)
if err != nil {
panic(k + " is not a valid index for type " + t.String())
}
i = explicit
implicit = explicit + 1
}
// "Extend" the slice if it's too short.
if l := v.Len(); i >= l {
delta := i - l + 1
v.Set(reflect.AppendSlice(v, reflect.MakeSlice(t, delta, delta)))
}
decodeValue(v.Index(i), c)
}
}
func decodeBasic(v reflect.Value, x interface{}) {
t := v.Type()
switch k, s := t.Kind(), getString(x); k {
case reflect.Bool:
if b, e := strconv.ParseBool(s); e == nil {
v.SetBool(b)
} else {
panic("could not parse bool from " + strconv.Quote(s))
}
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
if i, e := strconv.ParseInt(s, 10, 64); e == nil {
v.SetInt(i)
} else {
panic("could not parse int from " + strconv.Quote(s))
}
case reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
if u, e := strconv.ParseUint(s, 10, 64); e == nil {
v.SetUint(u)
} else {
panic("could not parse uint from " + strconv.Quote(s))
}
case reflect.Float32,
reflect.Float64:
if f, e := strconv.ParseFloat(s, 64); e == nil {
v.SetFloat(f)
} else {
panic("could not parse float from " + strconv.Quote(s))
}
case reflect.Complex64,
reflect.Complex128:
var c complex128
if n, err := fmt.Sscanf(s, "%g", &c); n == 1 && err == nil {
v.SetComplex(c)
} else {
panic("could not parse complex from " + strconv.Quote(s))
}
case reflect.String:
v.SetString(s)
default:
panic(t.String() + " has unsupported kind " + k.String())
}
t := v.Type()
switch k, s := t.Kind(), getString(x); k {
case reflect.Bool:
if b, e := strconv.ParseBool(s); e == nil {
v.SetBool(b)
} else {
panic("could not parse bool from " + strconv.Quote(s))
}
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
if i, e := strconv.ParseInt(s, 10, 64); e == nil {
v.SetInt(i)
} else {
panic("could not parse int from " + strconv.Quote(s))
}
case reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
if u, e := strconv.ParseUint(s, 10, 64); e == nil {
v.SetUint(u)
} else {
panic("could not parse uint from " + strconv.Quote(s))
}
case reflect.Float32,
reflect.Float64:
if f, e := strconv.ParseFloat(s, 64); e == nil {
v.SetFloat(f)
} else {
panic("could not parse float from " + strconv.Quote(s))
}
case reflect.Complex64,
reflect.Complex128:
var c complex128
if n, err := fmt.Sscanf(s, "%g", &c); n == 1 && err == nil {
v.SetComplex(c)
} else {
panic("could not parse complex from " + strconv.Quote(s))
}
case reflect.String:
v.SetString(s)
default:
panic(t.String() + " has unsupported kind " + k.String())
}
}
func decodeTime(v reflect.Value, x interface{}) {
t := v.Type()
s := getString(x)
// TODO: Find a more efficient way to do this.
for _, f := range allowedTimeFormats {
if p, err := time.Parse(f, s); err == nil {
v.Set(reflect.ValueOf(p).Convert(v.Type()))
return
}
}
panic("cannot decode string `" + s + "` as " + t.String())
t := v.Type()
s := getString(x)
// TODO: Find a more efficient way to do this.
for _, f := range allowedTimeFormats {
if p, err := time.Parse(f, s); err == nil {
v.Set(reflect.ValueOf(p).Convert(v.Type()))
return
}
}
panic("cannot decode string `" + s + "` as " + t.String())
}
func decodeURL(v reflect.Value, x interface{}) {
t := v.Type()
s := getString(x)
if u, err := url.Parse(s); err == nil {
v.Set(reflect.ValueOf(*u).Convert(v.Type()))
return
}
panic("cannot decode string `" + s + "` as " + t.String())
t := v.Type()
s := getString(x)
if u, err := url.Parse(s); err == nil {
v.Set(reflect.ValueOf(*u).Convert(v.Type()))
return
}
panic("cannot decode string `" + s + "` as " + t.String())
}
var allowedTimeFormats = []string{
"2006-01-02T15:04:05.999999999Z07:00",
"2006-01-02T15:04:05.999999999Z07",
"2006-01-02T15:04:05.999999999Z",
"2006-01-02T15:04:05.999999999",
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05Z07",
"2006-01-02T15:04:05Z",
"2006-01-02T15:04:05",
"2006-01-02T15:04Z",
"2006-01-02T15:04",
"2006-01-02T15Z",
"2006-01-02T15",
"2006-01-02",
"2006-01",
"2006",
"15:04:05.999999999Z07:00",
"15:04:05.999999999Z07",
"15:04:05.999999999Z",
"15:04:05.999999999",
"15:04:05Z07:00",
"15:04:05Z07",
"15:04:05Z",
"15:04:05",
"15:04Z",
"15:04",
"15Z",
"15",
"2006-01-02T15:04:05.999999999Z07:00",
"2006-01-02T15:04:05.999999999Z07",
"2006-01-02T15:04:05.999999999Z",
"2006-01-02T15:04:05.999999999",
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05Z07",
"2006-01-02T15:04:05Z",
"2006-01-02T15:04:05",
"2006-01-02T15:04Z",
"2006-01-02T15:04",
"2006-01-02T15Z",
"2006-01-02T15",
"2006-01-02",
"2006-01",
"2006",
"15:04:05.999999999Z07:00",
"15:04:05.999999999Z07",
"15:04:05.999999999Z",
"15:04:05.999999999",
"15:04:05Z07:00",
"15:04:05Z07",
"15:04:05Z",
"15:04:05",
"15:04Z",
"15:04",
"15Z",
"15",
}

518
vendor/github.com/ajg/form/encode.go generated vendored
View File

@ -5,347 +5,347 @@
package form
import (
"encoding"
"errors"
"fmt"
"io"
"net/url"
"reflect"
"strconv"
"strings"
"time"
"encoding"
"errors"
"fmt"
"io"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
// NewEncoder returns a new form encoder.
func NewEncoder(w io.Writer) *encoder {
return &encoder{w}
return &encoder{w}
}
// encoder provides a way to encode to a Writer.
type encoder struct {
w io.Writer
w io.Writer
}
// Encode encodes dst as form and writes it out using the encoder's Writer.
func (e encoder) Encode(dst interface{}) error {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v)
if err != nil {
return err
}
s := n.Values().Encode()
l, err := io.WriteString(e.w, s)
switch {
case err != nil:
return err
case l != len(s):
return errors.New("could not write data completely")
}
return nil
v := reflect.ValueOf(dst)
n, err := encodeToNode(v)
if err != nil {
return err
}
s := n.Values().Encode()
l, err := io.WriteString(e.w, s)
switch {
case err != nil:
return err
case l != len(s):
return errors.New("could not write data completely")
}
return nil
}
// EncodeToString encodes dst as a form and returns it as a string.
func EncodeToString(dst interface{}) (string, error) {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v)
if err != nil {
return "", err
}
return n.Values().Encode(), nil
v := reflect.ValueOf(dst)
n, err := encodeToNode(v)
if err != nil {
return "", err
}
return n.Values().Encode(), nil
}
// EncodeToValues encodes dst as a form and returns it as Values.
func EncodeToValues(dst interface{}) (url.Values, error) {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v)
if err != nil {
return nil, err
}
return n.Values(), nil
v := reflect.ValueOf(dst)
n, err := encodeToNode(v)
if err != nil {
return nil, err
}
return n.Values(), nil
}
func encodeToNode(v reflect.Value) (n node, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
return getNode(encodeValue(v)), nil
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
return getNode(encodeValue(v)), nil
}
func encodeValue(v reflect.Value) interface{} {
t := v.Type()
k := v.Kind()
t := v.Type()
k := v.Kind()
if s, ok := marshalValue(v); ok {
return s
} else if isEmptyValue(v) {
return "" // Treat the zero value as the empty string.
}
if s, ok := marshalValue(v); ok {
return s
} else if isEmptyValue(v) {
return "" // Treat the zero value as the empty string.
}
switch k {
case reflect.Ptr, reflect.Interface:
return encodeValue(v.Elem())
case reflect.Struct:
if t.ConvertibleTo(timeType) {
return encodeTime(v)
} else if t.ConvertibleTo(urlType) {
return encodeURL(v)
}
return encodeStruct(v)
case reflect.Slice:
return encodeSlice(v)
case reflect.Array:
return encodeArray(v)
case reflect.Map:
return encodeMap(v)
case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
panic(t.String() + " has unsupported kind " + t.Kind().String())
default:
return encodeBasic(v)
}
switch k {
case reflect.Ptr, reflect.Interface:
return encodeValue(v.Elem())
case reflect.Struct:
if t.ConvertibleTo(timeType) {
return encodeTime(v)
} else if t.ConvertibleTo(urlType) {
return encodeURL(v)
}
return encodeStruct(v)
case reflect.Slice:
return encodeSlice(v)
case reflect.Array:
return encodeArray(v)
case reflect.Map:
return encodeMap(v)
case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
panic(t.String() + " has unsupported kind " + t.Kind().String())
default:
return encodeBasic(v)
}
}
func encodeStruct(v reflect.Value) interface{} {
t := v.Type()
n := node{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
k, oe := fieldInfo(f)
t := v.Type()
n := node{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
k, oe := fieldInfo(f)
if k == "-" {
continue
} else if fv := v.Field(i); oe && isEmptyValue(fv) {
delete(n, k)
} else {
n[k] = encodeValue(fv)
}
}
return n
if k == "-" {
continue
} else if fv := v.Field(i); oe && isEmptyValue(fv) {
delete(n, k)
} else {
n[k] = encodeValue(fv)
}
}
return n
}
func encodeMap(v reflect.Value) interface{} {
n := node{}
for _, i := range v.MapKeys() {
k := getString(encodeValue(i))
n[k] = encodeValue(v.MapIndex(i))
}
return n
n := node{}
for _, i := range v.MapKeys() {
k := getString(encodeValue(i))
n[k] = encodeValue(v.MapIndex(i))
}
return n
}
func encodeArray(v reflect.Value) interface{} {
n := node{}
for i := 0; i < v.Len(); i++ {
n[strconv.Itoa(i)] = encodeValue(v.Index(i))
}
return n
n := node{}
for i := 0; i < v.Len(); i++ {
n[strconv.Itoa(i)] = encodeValue(v.Index(i))
}
return n
}
func encodeSlice(v reflect.Value) interface{} {
t := v.Type()
if t.Elem().Kind() == reflect.Uint8 {
return string(v.Bytes()) // Encode byte slices as a single string by default.
}
n := node{}
for i := 0; i < v.Len(); i++ {
n[strconv.Itoa(i)] = encodeValue(v.Index(i))
}
return n
t := v.Type()
if t.Elem().Kind() == reflect.Uint8 {
return string(v.Bytes()) // Encode byte slices as a single string by default.
}
n := node{}
for i := 0; i < v.Len(); i++ {
n[strconv.Itoa(i)] = encodeValue(v.Index(i))
}
return n
}
func encodeTime(v reflect.Value) string {
t := v.Convert(timeType).Interface().(time.Time)
if t.Year() == 0 && (t.Month() == 0 || t.Month() == 1) && (t.Day() == 0 || t.Day() == 1) {
return t.Format("15:04:05.999999999Z07:00")
} else if t.Hour() == 0 && t.Minute() == 0 && t.Second() == 0 && t.Nanosecond() == 0 {
return t.Format("2006-01-02")
}
return t.Format("2006-01-02T15:04:05.999999999Z07:00")
t := v.Convert(timeType).Interface().(time.Time)
if t.Year() == 0 && (t.Month() == 0 || t.Month() == 1) && (t.Day() == 0 || t.Day() == 1) {
return t.Format("15:04:05.999999999Z07:00")
} else if t.Hour() == 0 && t.Minute() == 0 && t.Second() == 0 && t.Nanosecond() == 0 {
return t.Format("2006-01-02")
}
return t.Format("2006-01-02T15:04:05.999999999Z07:00")
}
func encodeURL(v reflect.Value) string {
u := v.Convert(urlType).Interface().(url.URL)
return u.String()
u := v.Convert(urlType).Interface().(url.URL)
return u.String()
}
func encodeBasic(v reflect.Value) string {
t := v.Type()
switch k := t.Kind(); k {
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
return strconv.FormatUint(v.Uint(), 10)
case reflect.Float32:
return strconv.FormatFloat(v.Float(), 'g', -1, 32)
case reflect.Float64:
return strconv.FormatFloat(v.Float(), 'g', -1, 64)
case reflect.Complex64, reflect.Complex128:
s := fmt.Sprintf("%g", v.Complex())
return strings.TrimSuffix(strings.TrimPrefix(s, "("), ")")
case reflect.String:
return v.String()
}
panic(t.String() + " has unsupported kind " + t.Kind().String())
t := v.Type()
switch k := t.Kind(); k {
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
return strconv.FormatUint(v.Uint(), 10)
case reflect.Float32:
return strconv.FormatFloat(v.Float(), 'g', -1, 32)
case reflect.Float64:
return strconv.FormatFloat(v.Float(), 'g', -1, 64)
case reflect.Complex64, reflect.Complex128:
s := fmt.Sprintf("%g", v.Complex())
return strings.TrimSuffix(strings.TrimPrefix(s, "("), ")")
case reflect.String:
return v.String()
}
panic(t.String() + " has unsupported kind " + t.Kind().String())
}
func isEmptyValue(v reflect.Value) bool {
switch t := v.Type(); v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Complex64, reflect.Complex128:
return v.Complex() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Struct:
if t.ConvertibleTo(timeType) {
return v.Convert(timeType).Interface().(time.Time).IsZero()
}
return reflect.DeepEqual(v, reflect.Zero(t))
}
return false
switch t := v.Type(); v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Complex64, reflect.Complex128:
return v.Complex() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Struct:
if t.ConvertibleTo(timeType) {
return v.Convert(timeType).Interface().(time.Time).IsZero()
}
return reflect.DeepEqual(v, reflect.Zero(t))
}
return false
}
// canIndexOrdinally returns whether a value contains an ordered sequence of elements.
func canIndexOrdinally(v reflect.Value) bool {
if !v.IsValid() {
return false
}
switch t := v.Type(); t.Kind() {
case reflect.Ptr, reflect.Interface:
return canIndexOrdinally(v.Elem())
case reflect.Slice, reflect.Array:
return true
}
return false
if !v.IsValid() {
return false
}
switch t := v.Type(); t.Kind() {
case reflect.Ptr, reflect.Interface:
return canIndexOrdinally(v.Elem())
case reflect.Slice, reflect.Array:
return true
}
return false
}
func fieldInfo(f reflect.StructField) (k string, oe bool) {
if f.PkgPath != "" { // Skip private fields.
return omittedKey, oe
}
if f.PkgPath != "" { // Skip private fields.
return omittedKey, oe
}
k = f.Name
tag := f.Tag.Get("form")
if tag == "" {
return k, oe
}
k = f.Name
tag := f.Tag.Get("form")
if tag == "" {
return k, oe
}
ps := strings.SplitN(tag, ",", 2)
if ps[0] != "" {
k = ps[0]
}
if len(ps) == 2 {
oe = ps[1] == "omitempty"
}
return k, oe
ps := strings.SplitN(tag, ",", 2)
if ps[0] != "" {
k = ps[0]
}
if len(ps) == 2 {
oe = ps[1] == "omitempty"
}
return k, oe
}
func findField(v reflect.Value, n string) (reflect.Value, bool) {
t := v.Type()
l := v.NumField()
// First try named fields.
for i := 0; i < l; i++ {
f := t.Field(i)
k, _ := fieldInfo(f)
if k == omittedKey {
continue
} else if n == k {
return v.Field(i), true
}
}
t := v.Type()
l := v.NumField()
// First try named fields.
for i := 0; i < l; i++ {
f := t.Field(i)
k, _ := fieldInfo(f)
if k == omittedKey {
continue
} else if n == k {
return v.Field(i), true
}
}
// Then try anonymous (embedded) fields.
for i := 0; i < l; i++ {
f := t.Field(i)
k, _ := fieldInfo(f)
if k == omittedKey || !f.Anonymous { // || k != "" ?
continue
}
fv := v.Field(i)
fk := fv.Kind()
for fk == reflect.Ptr || fk == reflect.Interface {
fv = fv.Elem()
fk = fv.Kind()
}
// Then try anonymous (embedded) fields.
for i := 0; i < l; i++ {
f := t.Field(i)
k, _ := fieldInfo(f)
if k == omittedKey || !f.Anonymous { // || k != "" ?
continue
}
fv := v.Field(i)
fk := fv.Kind()
for fk == reflect.Ptr || fk == reflect.Interface {
fv = fv.Elem()
fk = fv.Kind()
}
if fk != reflect.Struct {
continue
}
if ev, ok := findField(fv, n); ok {
return ev, true
}
}
if fk != reflect.Struct {
continue
}
if ev, ok := findField(fv, n); ok {
return ev, true
}
}
return reflect.Value{}, false
return reflect.Value{}, false
}
var (
stringType = reflect.TypeOf(string(""))
stringMapType = reflect.TypeOf(map[string]interface{}{})
timeType = reflect.TypeOf(time.Time{})
timePtrType = reflect.TypeOf(&time.Time{})
urlType = reflect.TypeOf(url.URL{})
stringType = reflect.TypeOf(string(""))
stringMapType = reflect.TypeOf(map[string]interface{}{})
timeType = reflect.TypeOf(time.Time{})
timePtrType = reflect.TypeOf(&time.Time{})
urlType = reflect.TypeOf(url.URL{})
)
func skipTextMarshalling(t reflect.Type) bool {
/*// Skip time.Time because its text unmarshaling is overly rigid:
return t == timeType || t == timePtrType*/
// Skip time.Time & convertibles because its text unmarshaling is overly rigid:
return t.ConvertibleTo(timeType) || t.ConvertibleTo(timePtrType)
/*// Skip time.Time because its text unmarshaling is overly rigid:
return t == timeType || t == timePtrType*/
// Skip time.Time & convertibles because its text unmarshaling is overly rigid:
return t.ConvertibleTo(timeType) || t.ConvertibleTo(timePtrType)
}
func unmarshalValue(v reflect.Value, x interface{}) bool {
if skipTextMarshalling(v.Type()) {
return false
}
if skipTextMarshalling(v.Type()) {
return false
}
tu, ok := v.Interface().(encoding.TextUnmarshaler)
if !ok && !v.CanAddr() {
return false
} else if !ok {
return unmarshalValue(v.Addr(), x)
}
tu, ok := v.Interface().(encoding.TextUnmarshaler)
if !ok && !v.CanAddr() {
return false
} else if !ok {
return unmarshalValue(v.Addr(), x)
}
s := getString(x)
if err := tu.UnmarshalText([]byte(s)); err != nil {
panic(err)
}
return true
s := getString(x)
if err := tu.UnmarshalText([]byte(s)); err != nil {
panic(err)
}
return true
}
func marshalValue(v reflect.Value) (string, bool) {
if skipTextMarshalling(v.Type()) {
return "", false
}
if skipTextMarshalling(v.Type()) {
return "", false
}
tm, ok := v.Interface().(encoding.TextMarshaler)
if !ok && !v.CanAddr() {
return "", false
} else if !ok {
return marshalValue(v.Addr())
}
tm, ok := v.Interface().(encoding.TextMarshaler)
if !ok && !v.CanAddr() {
return "", false
} else if !ok {
return marshalValue(v.Addr())
}
bs, err := tm.MarshalText()
if err != nil {
panic(err)
}
return string(bs), true
bs, err := tm.MarshalText()
if err != nil {
panic(err)
}
return string(bs), true
}

4
vendor/github.com/ajg/form/form.go generated vendored
View File

@ -6,6 +6,6 @@
package form
const (
implicitKey = "_"
omittedKey = "-"
implicitKey = "_"
omittedKey = "-"
)

194
vendor/github.com/ajg/form/node.go generated vendored
View File

@ -5,144 +5,144 @@
package form
import (
"net/url"
"strconv"
"strings"
"net/url"
"strconv"
"strings"
)
type node map[string]interface{}
func (n node) Values() url.Values {
vs := url.Values{}
n.merge("", &vs)
return vs
vs := url.Values{}
n.merge("", &vs)
return vs
}
func (n node) merge(p string, vs *url.Values) {
for k, x := range n {
switch y := x.(type) {
case string:
vs.Add(p+escape(k), y)
case node:
y.merge(p+escape(k)+".", vs)
default:
panic("value is neither string nor node")
}
}
for k, x := range n {
switch y := x.(type) {
case string:
vs.Add(p+escape(k), y)
case node:
y.merge(p+escape(k)+".", vs)
default:
panic("value is neither string nor node")
}
}
}
// TODO: Add tests for implicit indexing.
func parseValues(vs url.Values, canIndexFirstLevelOrdinally bool) node {
// NOTE: Because of the flattening of potentially multiple strings to one key, implicit indexing works:
// i. At the first level; e.g. Foo.Bar=A&Foo.Bar=B becomes 0.Foo.Bar=A&1.Foo.Bar=B
// ii. At the last level; e.g. Foo.Bar._=A&Foo.Bar._=B becomes Foo.Bar.0=A&Foo.Bar.1=B
// TODO: At in-between levels; e.g. Foo._.Bar=A&Foo._.Bar=B becomes Foo.0.Bar=A&Foo.1.Bar=B
// (This last one requires that there only be one placeholder in order for it to be unambiguous.)
// NOTE: Because of the flattening of potentially multiple strings to one key, implicit indexing works:
// i. At the first level; e.g. Foo.Bar=A&Foo.Bar=B becomes 0.Foo.Bar=A&1.Foo.Bar=B
// ii. At the last level; e.g. Foo.Bar._=A&Foo.Bar._=B becomes Foo.Bar.0=A&Foo.Bar.1=B
// TODO: At in-between levels; e.g. Foo._.Bar=A&Foo._.Bar=B becomes Foo.0.Bar=A&Foo.1.Bar=B
// (This last one requires that there only be one placeholder in order for it to be unambiguous.)
m := map[string]string{}
for k, ss := range vs {
indexLastLevelOrdinally := strings.HasSuffix(k, "."+implicitKey)
m := map[string]string{}
for k, ss := range vs {
indexLastLevelOrdinally := strings.HasSuffix(k, "."+implicitKey)
for i, s := range ss {
if canIndexFirstLevelOrdinally {
k = strconv.Itoa(i) + "." + k
} else if indexLastLevelOrdinally {
k = strings.TrimSuffix(k, implicitKey) + strconv.Itoa(i)
}
for i, s := range ss {
if canIndexFirstLevelOrdinally {
k = strconv.Itoa(i) + "." + k
} else if indexLastLevelOrdinally {
k = strings.TrimSuffix(k, implicitKey) + strconv.Itoa(i)
}
m[k] = s
}
}
m[k] = s
}
}
n := node{}
for k, s := range m {
n = n.split(k, s)
}
return n
n := node{}
for k, s := range m {
n = n.split(k, s)
}
return n
}
func splitPath(path string) (k, rest string) {
esc := false
for i, r := range path {
switch {
case !esc && r == '\\':
esc = true
case !esc && r == '.':
return unescape(path[:i]), path[i+1:]
default:
esc = false
}
}
return unescape(path), ""
esc := false
for i, r := range path {
switch {
case !esc && r == '\\':
esc = true
case !esc && r == '.':
return unescape(path[:i]), path[i+1:]
default:
esc = false
}
}
return unescape(path), ""
}
func (n node) split(path, s string) node {
k, rest := splitPath(path)
if rest == "" {
return add(n, k, s)
}
if _, ok := n[k]; !ok {
n[k] = node{}
}
k, rest := splitPath(path)
if rest == "" {
return add(n, k, s)
}
if _, ok := n[k]; !ok {
n[k] = node{}
}
c := getNode(n[k])
n[k] = c.split(rest, s)
return n
c := getNode(n[k])
n[k] = c.split(rest, s)
return n
}
func add(n node, k, s string) node {
if n == nil {
return node{k: s}
}
if n == nil {
return node{k: s}
}
if _, ok := n[k]; ok {
panic("key " + k + " already set")
}
if _, ok := n[k]; ok {
panic("key " + k + " already set")
}
n[k] = s
return n
n[k] = s
return n
}
func isEmpty(x interface{}) bool {
switch y := x.(type) {
case string:
return y == ""
case node:
if s, ok := y[""].(string); ok {
return s == ""
}
return false
}
panic("value is neither string nor node")
switch y := x.(type) {
case string:
return y == ""
case node:
if s, ok := y[""].(string); ok {
return s == ""
}
return false
}
panic("value is neither string nor node")
}
func getNode(x interface{}) node {
switch y := x.(type) {
case string:
return node{"": y}
case node:
return y
}
panic("value is neither string nor node")
switch y := x.(type) {
case string:
return node{"": y}
case node:
return y
}
panic("value is neither string nor node")
}
func getString(x interface{}) string {
switch y := x.(type) {
case string:
return y
case node:
if s, ok := y[""].(string); ok {
return s
}
return ""
}
panic("value is neither string nor node")
switch y := x.(type) {
case string:
return y
case node:
if s, ok := y[""].(string); ok {
return s
}
return ""
}
panic("value is neither string nor node")
}
func escape(s string) string {
return strings.Replace(strings.Replace(s, `\`, `\\`, -1), `.`, `\.`, -1)
return strings.Replace(strings.Replace(s, `\`, `\\`, -1), `.`, `\.`, -1)
}
func unescape(s string) string {
return strings.Replace(strings.Replace(s, `\.`, `.`, -1), `\\`, `\`, -1)
return strings.Replace(strings.Replace(s, `\.`, `.`, -1), `\\`, `\`, -1)
}

View File

@ -1,26 +0,0 @@
# 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
dist/

View File

@ -1,4 +0,0 @@
FROM busybox
MAINTAINER Łukasz Kurowski <crackcomm@gmail.com>
COPY ./dist/cf /cf
ENTRYPOINT ["/cf"]

View File

@ -1,15 +0,0 @@
save-godeps:
godep save github.com/crackcomm/cloudflare/cf
cloudflare-build:
mkdir -p dist
CGO_ENABLED=0 GOOS=linux go build -ldflags "-s" -a -installsuffix cgo -o ./dist/cf ./cf/main.go
install:
go install github.com/crackcomm/cloudflare/cf
dist: cloudflare-build
clean:
rm -rf dist

View File

@ -1,98 +0,0 @@
# Golang CloudFlare® API v4 client
[![GoDoc](https://godoc.org/github.com/crackcomm/cloudflare?status.svg)](https://godoc.org/github.com/crackcomm/cloudflare) [![Circle CI](https://img.shields.io/circleci/project/crackcomm/cloudflare.svg)](https://circleci.com/gh/crackcomm/cloudflare)
Golang API Client for CloudFlare® API v4.
## Command Line Tool
```sh
$ go install github.com/crackcomm/cloudflare/cf
$ cf
NAME:
cf - CloudFlare command line tool
USAGE:
cf [global options] command [command options] [arguments...]
VERSION:
1.0.0
COMMANDS:
zones zones management
records zone records management
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--email CloudFlare user email [$CLOUDFLARE_EMAIL]
--key CloudFlare user key [$CLOUDFLARE_KEY]
--help, -h show help
--version, -v print the version
$ cf zones list
+----------------------------------+-------------------+--------+---------+
| ID | NAME | PAUSED | STATUS |
+----------------------------------+-------------------+--------+---------+
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | pending |
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | pending |
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | active |
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | active |
+----------------------------------+-------------------+--------+---------+
$ cf records list 5xxxxxcxxxxxxxxxxxxxxxxxxxxxxxx2
+----------------------------------+------+------------------+-------------+-----------+---------+--------+-----+---------------------+---------------------+
| ID | TYPE | NAME | CONTENT | PROXIABLE | PROXIED | LOCKED | TTL | CREATED ON | MODIFIED ON |
+----------------------------------+------+------------------+-------------+-----------+---------+--------+-----+---------------------+---------------------+
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | A | xxxxxxxxx.pl | xx.xx.xx.xx | yes | yes | no | 1 | 2015/01/13 15:53:59 | 2015/01/13 15:53:59 |
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | A | www.xxxxxxxxx.pl | xx.xx.xx.xx | yes | yes | no | 1 | 2015/01/13 15:53:59 | 2015/01/13 15:53:59 |
+----------------------------------+------+------------------+-------------+-----------+---------+--------+-----+---------------------+---------------------+
```
## Usage
```go
package main
import (
"log"
"time"
"github.com/crackcomm/cloudflare"
"golang.org/x/net/context"
)
func main() {
client := cloudflare.New(&cloudflare.Options{
Email: "example@email.com",
Key: "example-key",
})
ctx := context.Background()
ctx, _ = context.WithTimeout(ctx, time.Second*30)
zones, err := client.Zones.List(ctx)
if err != nil {
log.Fatal(err)
} else if len(zones) == 0 {
log.Fatal("No zones were found")
}
records, err := client.Records.List(ctx, zones[0].ID)
if err != nil {
log.Fatal(err)
}
for _, record := range records {
log.Printf("%#v", record)
}
}
```
## CloudFlare®
CloudFlare is a registered trademark of [CloudFlare, Inc](https://cloudflare.com).
## License
Apache 2.0 License.

View File

@ -1,14 +0,0 @@
machine:
services:
- docker
deployment:
staging:
branch: master
commands:
- docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS
- make dist
- docker build -t crackcomm/cf:latest .
- docker push crackcomm/cf:latest
- make clean

View File

@ -1,24 +0,0 @@
package cloudflare
// Options - Cloudflare API Client Options.
type Options struct {
Email, Key string
}
// Client - Cloudflare API Client.
type Client struct {
*Zones
*Records
*Firewalls
opts *Options
}
// New - Creates a new Cloudflare client.
func New(opts *Options) *Client {
return &Client{
Zones: &Zones{opts: opts},
Records: &Records{opts: opts},
Firewalls: &Firewalls{opts: opts},
opts: opts,
}
}

View File

@ -1,61 +0,0 @@
package cloudflare
import (
"encoding/json"
"fmt"
"io"
"net/http"
"golang.org/x/net/context"
)
var baseURL = "https://api.cloudflare.com/client/v4"
func apiURL(format string, a ...interface{}) string {
return fmt.Sprintf("%s%s", baseURL, fmt.Sprintf(format, a...))
}
func readResponse(r io.Reader) (result *Response, err error) {
result = new(Response)
err = json.NewDecoder(r).Decode(result)
if err != nil {
return nil, err
} else if err := result.Err(); err != nil {
return nil, err
}
return
}
type httpResponse struct {
resp *http.Response
err error
}
func httpDo(ctx context.Context, opts *Options, method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Auth-Email", opts.Email)
req.Header.Set("X-Auth-Key", opts.Key)
transport := &http.Transport{}
client := &http.Client{Transport: transport}
respchan := make(chan *httpResponse, 1)
go func() {
resp, err := client.Do(req)
respchan <- &httpResponse{resp: resp, err: err}
}()
select {
case <-ctx.Done():
transport.CancelRequest(req)
<-respchan
return nil, ctx.Err()
case r := <-respchan:
return r.resp, r.err
}
}

View File

@ -1,75 +0,0 @@
package cloudflare
import (
"bytes"
"encoding/json"
"golang.org/x/net/context"
)
// Firewalls - Cloudflare Fireall Zones API Client.
type Firewalls struct {
opts *Options
}
// Create - Creates a firewall rule for zone.
func (firewalls *Firewalls) Create(ctx context.Context, id string, firewall *Firewall) (fw *Firewall, err error) {
buffer := new(bytes.Buffer)
err = json.NewEncoder(buffer).Encode(firewall)
if err != nil {
return
}
response, err := httpDo(ctx, firewalls.opts, "POST", apiURL("/zones/%s/firewall/access_rules/rules", id), buffer)
if err != nil {
return
}
defer response.Body.Close()
result, err := readResponse(response.Body)
if err != nil {
return
}
fw = new(Firewall)
err = json.Unmarshal(result.Result, &fw)
return
}
// List - Lists all firewall rules for zone.
func (firewalls *Firewalls) List(ctx context.Context, zone string) ([]*Firewall, error) {
return firewalls.listPages(ctx, zone, 1)
}
// Delete - Deletes firewall by id.
func (firewalls *Firewalls) Delete(ctx context.Context, zone, id string) (err error) {
response, err := httpDo(ctx, firewalls.opts, "DELETE", apiURL("/zones/%s/firewall/access_rules/rules/%s", zone, id), nil)
if err != nil {
return
}
defer response.Body.Close()
_, err = readResponse(response.Body)
return
}
// listPages - Gets all pages starting from `page`.
func (firewalls *Firewalls) listPages(ctx context.Context, zone string, page int) (list []*Firewall, err error) {
response, err := httpDo(ctx, firewalls.opts, "GET", apiURL("/zones/%s/firewall/access_rules/rules?page=%d&per_page=50", zone, page), nil)
if err != nil {
return
}
defer response.Body.Close()
result, err := readResponse(response.Body)
if err != nil {
return
}
err = json.Unmarshal(result.Result, &list)
if err != nil {
return
}
if result.ResultInfo == nil || page >= result.ResultInfo.TotalPages {
return
}
next, err := firewalls.listPages(ctx, zone, page+1)
if err != nil {
return
}
return append(list, next...), nil
}

View File

@ -1,104 +0,0 @@
package cloudflare
import (
"bytes"
"encoding/json"
"golang.org/x/net/context"
)
// Records - Cloudflare Records API Client.
type Records struct {
opts *Options
}
// Create - Creates a zone DNS record.
// Required parameters of a record are - `type`, `name` and `content`.
// Optional parameters of a record are - `ttl`.
func (records *Records) Create(ctx context.Context, record *Record) (err error) {
buffer := new(bytes.Buffer)
err = json.NewEncoder(buffer).Encode(record)
if err != nil {
return
}
response, err := httpDo(ctx, records.opts, "POST", apiURL("/zones/%s/dns_records", record.ZoneID), buffer)
if err != nil {
return
}
defer response.Body.Close()
_, err = readResponse(response.Body)
return
}
// List - Lists all zone DNS records.
func (records *Records) List(ctx context.Context, zoneID string) ([]*Record, error) {
return records.listPages(ctx, zoneID, 1)
}
// Details - Requests zone DNS record details by zone ID and record ID.
func (records *Records) Details(ctx context.Context, zoneID, recordID string) (record *Record, err error) {
response, err := httpDo(ctx, records.opts, "GET", apiURL("/zones/%s/dns_records/%s", zoneID, recordID), nil)
if err != nil {
return
}
defer response.Body.Close()
result, err := readResponse(response.Body)
if err != nil {
return
}
record = new(Record)
err = json.Unmarshal(result.Result, &record)
return
}
// Patch - Patches a zone DNS record.
func (records *Records) Patch(ctx context.Context, record *Record) (err error) {
buffer := new(bytes.Buffer)
err = json.NewEncoder(buffer).Encode(record)
if err != nil {
return
}
response, err := httpDo(ctx, records.opts, "PUT", apiURL("/zones/%s/dns_records/%s", record.ZoneID, record.ID), buffer)
if err != nil {
return
}
defer response.Body.Close()
_, err = readResponse(response.Body)
return
}
// Delete - Deletes zone DNS record by zone ID and record ID.
func (records *Records) Delete(ctx context.Context, zoneID, recordID string) (err error) {
response, err := httpDo(ctx, records.opts, "DELETE", apiURL("/zones/%s/dns_records/%s", zoneID, recordID), nil)
if err != nil {
return
}
defer response.Body.Close()
_, err = readResponse(response.Body)
return
}
// listPages - Gets all pages starting from `page`.
func (records *Records) listPages(ctx context.Context, zoneID string, page int) (list []*Record, err error) {
response, err := httpDo(ctx, records.opts, "GET", apiURL("/zones/%s/dns_records?page=%d&per_page=50", zoneID, page), nil)
if err != nil {
return
}
defer response.Body.Close()
result, err := readResponse(response.Body)
if err != nil {
return
}
err = json.Unmarshal(result.Result, &list)
if err != nil {
return
}
if result.ResultInfo == nil || page >= result.ResultInfo.TotalPages {
return
}
next, err := records.listPages(ctx, zoneID, page+1)
if err != nil {
return
}
return append(list, next...), nil
}

View File

@ -1,111 +0,0 @@
package cloudflare
import (
"bytes"
"encoding/json"
"golang.org/x/net/context"
)
// Zones - Cloudflare Zones API Client.
type Zones struct {
opts *Options
}
// Create - Creates a zone.
func (zones *Zones) Create(ctx context.Context, domain string) (zone *Zone, err error) {
buffer := new(bytes.Buffer)
err = json.NewEncoder(buffer).Encode(struct {
Name string `json:"name"`
}{
Name: domain,
})
if err != nil {
return
}
response, err := httpDo(ctx, zones.opts, "POST", apiURL("/zones"), buffer)
if err != nil {
return
}
defer response.Body.Close()
result, err := readResponse(response.Body)
if err != nil {
return
}
zone = new(Zone)
err = json.Unmarshal(result.Result, &zone)
return
}
// List - Lists all zones.
func (zones *Zones) List(ctx context.Context) ([]*Zone, error) {
return zones.listPages(ctx, 1)
}
// Details - Requests Zone details by ID.
func (zones *Zones) Details(ctx context.Context, id string) (zone *Zone, err error) {
response, err := httpDo(ctx, zones.opts, "GET", apiURL("/zones/%s", id), nil)
if err != nil {
return
}
defer response.Body.Close()
result, err := readResponse(response.Body)
if err != nil {
return
}
zone = new(Zone)
err = json.Unmarshal(result.Result, &zone)
return
}
// Patch - Patches a zone. It has a limited possibilities.
func (zones *Zones) Patch(ctx context.Context, id string, patch *ZonePatch) (err error) {
buffer := new(bytes.Buffer)
err = json.NewEncoder(buffer).Encode(patch)
if err != nil {
return
}
response, err := httpDo(ctx, zones.opts, "POST", apiURL("/zones/%s", id), buffer)
if err != nil {
return
}
defer response.Body.Close()
_, err = readResponse(response.Body)
return
}
// Delete - Deletes zone by id.
func (zones *Zones) Delete(ctx context.Context, id string) (err error) {
response, err := httpDo(ctx, zones.opts, "DELETE", apiURL("/zones/%s", id), nil)
if err != nil {
return
}
defer response.Body.Close()
_, err = readResponse(response.Body)
return
}
// listPages - Gets all pages starting from `page`.
func (zones *Zones) listPages(ctx context.Context, page int) (list []*Zone, err error) {
response, err := httpDo(ctx, zones.opts, "GET", apiURL("/zones?page=%d&per_page=50", page), nil)
if err != nil {
return
}
defer response.Body.Close()
result, err := readResponse(response.Body)
if err != nil {
return
}
err = json.Unmarshal(result.Result, &list)
if err != nil {
return
}
if result.ResultInfo == nil || page >= result.ResultInfo.TotalPages {
return
}
next, err := zones.listPages(ctx, page+1)
if err != nil {
return
}
return append(list, next...), nil
}

View File

@ -1,40 +0,0 @@
package cloudflare
import "encoding/json"
// Response - Cloudflare API Response.
type Response struct {
Result json.RawMessage `json:"result"`
ResultInfo *ResultInfo `json:"result_info"`
Errors []*ResponseError `json:"errors"`
Success bool `json:"success"`
}
// ResultInfo - Cloudflare API Response Result Info.
type ResultInfo struct {
Page int `json:"page,omitempty"`
PerPage int `json:"per_page,omitempty"`
TotalPages int `json:"total_pages,omitempty"`
Count int `json:"count,omitempty"`
TotalCount int `json:"total_count,omitempty"`
}
// ResponseError - Cloudflare API Response error.
type ResponseError struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
// Err - Gets response error if any.
func (response *Response) Err() error {
if len(response.Errors) > 0 {
return response.Errors[0]
}
return nil
}
// Error - Returns response error message.
func (err *ResponseError) Error() string {
return err.Message
}

View File

@ -1,25 +0,0 @@
package cloudflare
import (
"time"
)
type FirewallConfiguration struct {
Target string `json:"target,omitempty"`
Value string `json:"value,omitempty"`
}
// Firewall - Firewall for zone.
type Firewall struct {
ID string `json:"id,omitempty"`
Notes string `json:"notes,omitempty"`
AllowedModes []string `json:"allowed_modes,omitempty"`
Mode string `json:"mode,omitempty"`
Configuration *FirewallConfiguration `json:"configuration,omitempty"`
Scope *ZoneOwner `json:"scope,omitempty"`
CreatedOn time.Time `json:"created_on,omitempty"`
ModifiedOn time.Time `json:"modified_on,omitempty"`
}

View File

@ -1,24 +0,0 @@
package cloudflare
import "time"
// Record - Cloudflare DNS Record.
type Record struct {
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
Content string `json:"content,omitempty"`
Proxiable bool `json:"proxiable,omitempty"`
Proxied bool `json:"proxied,omitempty"`
Locked bool `json:"locked,omitempty"`
TTL int `json:"ttl,omitempty"`
Priority int `json:"priority,omitempty"`
CreatedOn time.Time `json:"created_on,omitempty"`
ModifiedOn time.Time `json:"modified_on,omitempty"`
ZoneID string `json:"zone_id,omitempty"`
ZoneName string `json:"zone_name,omitempty"`
}

View File

@ -1,104 +0,0 @@
package cloudflare
import (
"bytes"
"encoding/json"
"time"
)
// Zone - Cloudflare Zone.
type Zone struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Status string `json:"status,omitempty"`
Paused bool `json:"paused,omitempty"`
Type string `json:"type,omitempty"`
DevelopmentMode int `json:"development_mode,omitempty"`
NameServers []string `json:"name_servers,omitempty"`
OriginalNameServers []string `json:"original_name_servers,omitempty"`
ModifiedOn time.Time `json:"modified_on,omitempty"`
CreatedOn time.Time `json:"created_on,omitempty"`
CheckedOn time.Time `json:"checked_on,omitempty"`
Meta *ZoneMeta `json:"meta,omitempty"`
Owner *ZoneOwner `json:"owner,omitempty"`
Plan *ZonePlan `json:"plan,omitempty"`
Permissions []string `json:"permissions,omitempty"`
}
// ZoneOwner -
type ZoneOwner struct {
Type string `json:"type,omitempty"`
ID string `json:"id,omitempty"`
Email string `json:"email,omitempty"`
}
// ZoneMeta -
type ZoneMeta struct {
Step int `json:"step,omitempty"`
PageRuleQuota int `json:"page_rule_quota,omitempty"`
CustomCertificateQuota int `json:"custom_certificate_quota,omitempty"`
WildcardProxiable bool `json:"wildcard_proxiable,omitempty"`
PhishingDetected bool `json:"phishing_detected,omitempty"`
MultipleRailgunsAllowed bool `json:"multiple_railguns_allowed,omitempty"`
}
func (m *ZoneMeta) UnmarshalJSON(data []byte) error {
f := struct {
Step int `json:"step,omitempty"`
PageRuleQuota int `json:"page_rule_quota,omitempty"`
CustomCertificateQuota *maybeNumber `json:"custom_certificate_quota,omitempty"`
WildcardProxiable bool `json:"wildcard_proxiable,omitempty"`
PhishingDetected bool `json:"phishing_detected,omitempty"`
MultipleRailgunsAllowed bool `json:"multiple_railguns_allowed,omitempty"`
}{}
err := json.Unmarshal(data, &f)
if err != nil {
return err
}
m.CustomCertificateQuota = f.CustomCertificateQuota.value
m.MultipleRailgunsAllowed = f.MultipleRailgunsAllowed
m.PageRuleQuota = f.PageRuleQuota
m.PhishingDetected = f.PhishingDetected
m.Step = f.Step
m.WildcardProxiable = f.WildcardProxiable
return nil
}
// ZonePlan -
type ZonePlan struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Price int `json:"price,omitempty"`
Currency string `json:"currency,omitempty"`
Frequency string `json:"frequency,omitempty"`
LegacyID string `json:"legacy_id,omitempty"`
IsSubscribed bool `json:"is_subscribed,omitempty"`
CanSubscribe bool `json:"can_subscribe,omitempty"`
ExternallyManaged bool `json:"externally_managed,omitempty"`
}
// ZonePatch -
type ZonePatch struct {
Plan *ZonePlan `json:"plan,omitempty"`
Paused bool `json:"paused,omitempty"`
VanityNameServers []string `json:"vanity_name_servers,omitempty"`
}
// maybeNumber is an intermediate type to cope with the inconsistent responses
// for CustomCertificateQuota which can be a string or a number.
type maybeNumber struct {
value int
}
func (m *maybeNumber) UnmarshalJSON(data []byte) error {
data = bytes.Trim(data, `"`)
return json.Unmarshal(data, &m.value)
}

View File

@ -45,6 +45,7 @@ const (
apiFabricVLANs = "fabrics/default/vlans"
apiFabricNetworks = "networks"
apiNICs = "nics"
apiServices = "services"
// CloudAPI actions
actionExport = "export"

20
vendor/github.com/joyent/gosdc/cloudapi/services.go generated vendored Normal file
View File

@ -0,0 +1,20 @@
package cloudapi
import (
"github.com/joyent/gocommon/client"
"github.com/joyent/gocommon/errors"
)
// list available services
func (c *Client) ListServices() (map[string]string, error) {
var resp map[string]string
req := request{
method: client.GET,
url: apiServices,
resp: &resp,
}
if _, err := c.sendRequest(req); err != nil {
return nil, errors.Newf(err, "failed to get list of services")
}
return resp, nil
}

View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,165 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -1,4 +1,4 @@
Apache License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
@ -199,4 +199,3 @@
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,302 +0,0 @@
package client_fakes
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
services "github.com/maximilien/softlayer-go/services"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
const (
SOFTLAYER_API_URL = "api.softlayer.com/rest/v3"
TEMPLATE_ROOT_PATH = "templates"
)
type FakeSoftLayerClient struct {
Username string
ApiKey string
TemplatePath string
SoftLayerServices map[string]softlayer.Service
DoRawHttpRequestResponseCount int
DoRawHttpRequestResponse []byte
DoRawHttpRequestResponses [][]byte
DoRawHttpRequestResponsesIndex int
DoRawHttpRequestError error
DoRawHttpRequestPath string
DoRawHttpRequestRequestType string
GenerateRequestBodyBuffer *bytes.Buffer
GenerateRequestBodyError error
HasErrorsError, CheckForHttpResponseError error
}
func NewFakeSoftLayerClient(username, apiKey string) *FakeSoftLayerClient {
pwd, _ := os.Getwd()
fslc := &FakeSoftLayerClient{
Username: username,
ApiKey: apiKey,
TemplatePath: filepath.Join(pwd, TEMPLATE_ROOT_PATH),
SoftLayerServices: map[string]softlayer.Service{},
DoRawHttpRequestResponseCount: 0,
DoRawHttpRequestResponse: nil,
DoRawHttpRequestResponses: [][]byte{},
DoRawHttpRequestResponsesIndex: 0,
DoRawHttpRequestError: nil,
DoRawHttpRequestPath: "",
DoRawHttpRequestRequestType: "",
GenerateRequestBodyBuffer: new(bytes.Buffer),
GenerateRequestBodyError: nil,
HasErrorsError: nil,
CheckForHttpResponseError: nil,
}
fslc.initSoftLayerServices()
return fslc
}
//softlayer.Client interface methods
func (fslc *FakeSoftLayerClient) GetService(serviceName string) (softlayer.Service, error) {
slService, ok := fslc.SoftLayerServices[serviceName]
if !ok {
return nil, errors.New(fmt.Sprintf("softlayer-go does not support service '%s'", serviceName))
}
return slService, nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Account_Service() (softlayer.SoftLayer_Account_Service, error) {
slService, err := fslc.GetService("SoftLayer_Account")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Account_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Service() (softlayer.SoftLayer_Virtual_Guest_Service, error) {
slService, err := fslc.GetService("SoftLayer_Virtual_Guest")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Virtual_Guest_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Dns_Domain_Service() (softlayer.SoftLayer_Dns_Domain_Service, error) {
slService, err := fslc.GetService("SoftLayer_Dns_Domain")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Dns_Domain_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Disk_Image_Service() (softlayer.SoftLayer_Virtual_Disk_Image_Service, error) {
slService, err := fslc.GetService("SoftLayer_Virtual_Disk_Image")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Virtual_Disk_Image_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Security_Ssh_Key_Service() (softlayer.SoftLayer_Security_Ssh_Key_Service, error) {
slService, err := fslc.GetService("SoftLayer_Security_Ssh_Key")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Security_Ssh_Key_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Network_Storage_Service() (softlayer.SoftLayer_Network_Storage_Service, error) {
slService, err := fslc.GetService("SoftLayer_Network_Storage")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Network_Storage_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Network_Storage_Allowed_Host_Service() (softlayer.SoftLayer_Network_Storage_Allowed_Host_Service, error) {
slService, err := fslc.GetService("SoftLayer_Network_Storage_Allowed_Host")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Network_Storage_Allowed_Host_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Order_Service() (softlayer.SoftLayer_Product_Order_Service, error) {
slService, err := fslc.GetService("SoftLayer_Product_Order")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Product_Order_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Package_Service() (softlayer.SoftLayer_Product_Package_Service, error) {
slService, err := fslc.GetService("SoftLayer_Product_Package")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Product_Package_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Billing_Item_Cancellation_Request_Service() (softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service, error) {
slService, err := fslc.GetService("SoftLayer_Billing_Item_Cancellation_Request")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service() (softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service, error) {
slService, err := fslc.GetService("SoftLayer_Virtual_Guest_Block_Device_Template_Group")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Hardware_Service() (softlayer.SoftLayer_Hardware_Service, error) {
slService, err := fslc.GetService("SoftLayer_Hardware")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Hardware_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Dns_Domain_ResourceRecord_Service() (softlayer.SoftLayer_Dns_Domain_ResourceRecord_Service, error) {
slService, err := fslc.GetService("SoftLayer_Dns_Domain_ResourceRecord")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Dns_Domain_ResourceRecord_Service), nil
}
//Public methods
func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
fslc.DoRawHttpRequestPath = path
fslc.DoRawHttpRequestRequestType = requestType
fslc.DoRawHttpRequestResponseCount += 1
if fslc.DoRawHttpRequestError != nil {
return []byte{}, fslc.DoRawHttpRequestError
}
if fslc.DoRawHttpRequestResponse != nil && len(fslc.DoRawHttpRequestResponses) == 0 {
return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
} else {
fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
}
}
func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectFilter(path string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
fslc.DoRawHttpRequestPath = path
fslc.DoRawHttpRequestRequestType = requestType
fslc.DoRawHttpRequestResponseCount += 1
if fslc.DoRawHttpRequestError != nil {
return []byte{}, fslc.DoRawHttpRequestError
}
if fslc.DoRawHttpRequestResponse != nil && len(fslc.DoRawHttpRequestResponses) == 0 {
return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
} else {
fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
}
}
func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectFilterAndObjectMask(path string, masks []string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
fslc.DoRawHttpRequestPath = path
fslc.DoRawHttpRequestRequestType = requestType
fslc.DoRawHttpRequestResponseCount += 1
if fslc.DoRawHttpRequestError != nil {
return []byte{}, fslc.DoRawHttpRequestError
}
if fslc.DoRawHttpRequestResponse != nil && len(fslc.DoRawHttpRequestResponses) == 0 {
return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
} else {
fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
}
}
func (fslc *FakeSoftLayerClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
fslc.DoRawHttpRequestPath = path
fslc.DoRawHttpRequestRequestType = requestType
fslc.DoRawHttpRequestResponseCount += 1
if fslc.DoRawHttpRequestError != nil {
return []byte{}, fslc.DoRawHttpRequestError
}
if fslc.DoRawHttpRequestResponse != nil && len(fslc.DoRawHttpRequestResponses) == 0 {
return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
} else {
fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
}
}
func (fslc *FakeSoftLayerClient) GenerateRequestBody(templateData interface{}) (*bytes.Buffer, error) {
return fslc.GenerateRequestBodyBuffer, fslc.GenerateRequestBodyError
}
func (fslc *FakeSoftLayerClient) HasErrors(body map[string]interface{}) error {
return fslc.HasErrorsError
}
func (fslc *FakeSoftLayerClient) CheckForHttpResponseErrors(data []byte) error {
return fslc.CheckForHttpResponseError
}
//Private methods
func (fslc *FakeSoftLayerClient) initSoftLayerServices() {
fslc.SoftLayerServices["SoftLayer_Account"] = services.NewSoftLayer_Account_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Virtual_Guest"] = services.NewSoftLayer_Virtual_Guest_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Virtual_Disk_Image"] = services.NewSoftLayer_Virtual_Disk_Image_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Security_Ssh_Key"] = services.NewSoftLayer_Security_Ssh_Key_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Network_Storage"] = services.NewSoftLayer_Network_Storage_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Network_Storage_Allowed_Host"] = services.NewSoftLayer_Network_Storage_Allowed_Host_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Product_Order"] = services.NewSoftLayer_Product_Order_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Product_Package"] = services.NewSoftLayer_Product_Package_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Billing_Item_Cancellation_Request"] = services.NewSoftLayer_Billing_Item_Cancellation_Request_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Virtual_Guest_Block_Device_Template_Group"] = services.NewSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Hardware"] = services.NewSoftLayer_Hardware_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Dns_Domain"] = services.NewSoftLayer_Dns_Domain_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Dns_Domain_ResourceRecord"] = services.NewSoftLayer_Dns_Domain_ResourceRecord_Service(fslc)
}

View File

@ -0,0 +1,214 @@
package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"regexp"
"text/template"
)
const NON_VERBOSE = "NON_VERBOSE"
type HttpClient struct {
HTTPClient *http.Client
username string
password string
useHttps bool
apiUrl string
nonVerbose bool
templatePath string
}
func NewHttpsClient(username, password, apiUrl, templatePath string) *HttpClient {
return NewHttpClient(username, password, apiUrl, templatePath, true)
}
func NewHttpClient(username, password, apiUrl, templatePath string, useHttps bool) *HttpClient {
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
hClient := &HttpClient{
username: username,
password: password,
useHttps: useHttps,
apiUrl: apiUrl,
templatePath: filepath.Join(pwd, templatePath),
HTTPClient: http.DefaultClient,
nonVerbose: checkNonVerbose(),
}
return hClient
}
// Public methods
func (slc *HttpClient) DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error) {
url := fmt.Sprintf("%s://%s:%s@%s/%s", slc.scheme(), slc.username, slc.password, slc.apiUrl, path)
url += "?objectMask="
for i := 0; i < len(masks); i++ {
url += masks[i]
if i != len(masks)-1 {
url += ";"
}
}
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *HttpClient) DoRawHttpRequestWithObjectFilter(path string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error) {
url := fmt.Sprintf("%s://%s:%s@%s/%s", slc.scheme(), slc.username, slc.password, slc.apiUrl, path)
url += "?objectFilter=" + filters
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *HttpClient) DoRawHttpRequestWithObjectFilterAndObjectMask(path string, masks []string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error) {
url := fmt.Sprintf("%s://%s:%s@%s/%s", slc.scheme(), slc.username, slc.password, slc.apiUrl, path)
url += "?objectFilter=" + filters
url += "&objectMask=filteredMask["
for i := 0; i < len(masks); i++ {
url += masks[i]
if i != len(masks)-1 {
url += ";"
}
}
url += "]"
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *HttpClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error) {
url := fmt.Sprintf("%s://%s:%s@%s/%s", slc.scheme(), slc.username, slc.password, slc.apiUrl, path)
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *HttpClient) GenerateRequestBody(templateData interface{}) (*bytes.Buffer, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
bodyTemplate := template.Must(template.ParseFiles(filepath.Join(cwd, slc.templatePath)))
body := new(bytes.Buffer)
bodyTemplate.Execute(body, templateData)
return body, nil
}
func (slc *HttpClient) HasErrors(body map[string]interface{}) error {
if errString, ok := body["error"]; !ok {
return nil
} else {
return errors.New(errString.(string))
}
}
func (slc *HttpClient) CheckForHttpResponseErrors(data []byte) error {
var decodedResponse map[string]interface{}
err := json.Unmarshal(data, &decodedResponse)
if err != nil {
return err
}
if err := slc.HasErrors(decodedResponse); err != nil {
return err
}
return nil
}
// Private methods
func (slc *HttpClient) scheme() string {
if !slc.useHttps {
return "http"
}
return "https"
}
func (slc *HttpClient) makeHttpRequest(url string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error) {
req, err := http.NewRequest(requestType, url, requestBody)
if err != nil {
return nil, 0, err
}
bs, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, 0, err
}
if !slc.nonVerbose {
fmt.Fprintf(os.Stderr, "\n---\n[softlayer-go] Request:\n%s\n", hideCredentials(string(bs)))
}
resp, err := slc.HTTPClient.Do(req)
if err != nil {
return nil, 520, err
}
defer resp.Body.Close()
bs, err = httputil.DumpResponse(resp, true)
if err != nil {
return nil, resp.StatusCode, err
}
if !slc.nonVerbose {
fmt.Fprintf(os.Stderr, "[softlayer-go] Response:\n%s\n", hideCredentials(string(bs)))
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, resp.StatusCode, err
}
return responseBody, resp.StatusCode, nil
}
// Private functions
func hideCredentials(s string) string {
hiddenStr := "\"password\":\"******\""
r := regexp.MustCompile(`"password":"[^"]*"`)
return r.ReplaceAllString(s, hiddenStr)
}
func checkNonVerbose() bool {
slGoNonVerbose := os.Getenv(NON_VERBOSE)
switch slGoNonVerbose {
case "yes":
return true
case "YES":
return true
case "true":
return true
case "TRUE":
return true
}
return false
}

View File

@ -1,17 +1,8 @@
package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"regexp"
"text/template"
services "github.com/maximilien/softlayer-go/services"
softlayer "github.com/maximilien/softlayer-go/softlayer"
@ -20,36 +11,17 @@ import (
const (
SOFTLAYER_API_URL = "api.softlayer.com/rest/v3"
TEMPLATE_ROOT_PATH = "templates"
SL_GO_NON_VERBOSE = "SL_GO_NON_VERBOSE"
)
type SoftLayerClient struct {
username string
apiKey string
templatePath string
HTTPClient *http.Client
HttpClient softlayer.HttpClient
softLayerServices map[string]softlayer.Service
nonVerbose bool
}
func NewSoftLayerClient(username, apiKey string) *SoftLayerClient {
pwd, err := os.Getwd()
if err != nil {
panic(err) // this should be handled by the user
}
slc := &SoftLayerClient{
username: username,
apiKey: apiKey,
templatePath: filepath.Join(pwd, TEMPLATE_ROOT_PATH),
HTTPClient: http.DefaultClient,
nonVerbose: checkNonVerbose(),
HttpClient: NewHttpsClient(username, apiKey, SOFTLAYER_API_URL, TEMPLATE_ROOT_PATH),
softLayerServices: map[string]softlayer.Service{},
}
@ -61,6 +33,10 @@ func NewSoftLayerClient(username, apiKey string) *SoftLayerClient {
//softlayer.Client interface methods
func (slc *SoftLayerClient) GetHttpClient() softlayer.HttpClient {
return slc.HttpClient
}
func (slc *SoftLayerClient) GetService(serviceName string) (softlayer.Service, error) {
slService, ok := slc.softLayerServices[serviceName]
if !ok {
@ -169,6 +145,15 @@ func (slc *SoftLayerClient) GetSoftLayer_Billing_Item_Cancellation_Request_Servi
return slService.(softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service), nil
}
func (slc *SoftLayerClient) GetSoftLayer_Billing_Item_Service() (softlayer.SoftLayer_Billing_Item_Service, error) {
slService, err := slc.GetService("SoftLayer_Billing_Item")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Billing_Item_Service), nil
}
func (slc *SoftLayerClient) GetSoftLayer_Hardware_Service() (softlayer.SoftLayer_Hardware_Service, error) {
slService, err := slc.GetService("SoftLayer_Hardware")
if err != nil {
@ -187,86 +172,6 @@ func (slc *SoftLayerClient) GetSoftLayer_Dns_Domain_ResourceRecord_Service() (so
return slService.(softlayer.SoftLayer_Dns_Domain_ResourceRecord_Service), nil
}
//Public methods
func (slc *SoftLayerClient) DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
url := fmt.Sprintf("https://%s:%s@%s/%s", slc.username, slc.apiKey, SOFTLAYER_API_URL, path)
url += "?objectMask="
for i := 0; i < len(masks); i++ {
url += masks[i]
if i != len(masks)-1 {
url += ";"
}
}
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *SoftLayerClient) DoRawHttpRequestWithObjectFilter(path string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
url := fmt.Sprintf("https://%s:%s@%s/%s", slc.username, slc.apiKey, SOFTLAYER_API_URL, path)
url += "?objectFilter=" + filters
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *SoftLayerClient) DoRawHttpRequestWithObjectFilterAndObjectMask(path string, masks []string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
url := fmt.Sprintf("https://%s:%s@%s/%s", slc.username, slc.apiKey, SOFTLAYER_API_URL, path)
url += "?objectFilter=" + filters
url += "&objectMask=filteredMask["
for i := 0; i < len(masks); i++ {
url += masks[i]
if i != len(masks)-1 {
url += ";"
}
}
url += "]"
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *SoftLayerClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
url := fmt.Sprintf("https://%s:%s@%s/%s", slc.username, slc.apiKey, SOFTLAYER_API_URL, path)
return slc.makeHttpRequest(url, requestType, requestBody)
}
func (slc *SoftLayerClient) GenerateRequestBody(templateData interface{}) (*bytes.Buffer, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
bodyTemplate := template.Must(template.ParseFiles(filepath.Join(cwd, slc.templatePath)))
body := new(bytes.Buffer)
bodyTemplate.Execute(body, templateData)
return body, nil
}
func (slc *SoftLayerClient) HasErrors(body map[string]interface{}) error {
if errString, ok := body["error"]; !ok {
return nil
} else {
return errors.New(errString.(string))
}
}
func (slc *SoftLayerClient) CheckForHttpResponseErrors(data []byte) error {
var decodedResponse map[string]interface{}
err := json.Unmarshal(data, &decodedResponse)
if err != nil {
return err
}
if err := slc.HasErrors(decodedResponse); err != nil {
return err
}
return nil
}
//Private methods
func (slc *SoftLayerClient) initSoftLayerServices() {
@ -279,72 +184,9 @@ func (slc *SoftLayerClient) initSoftLayerServices() {
slc.softLayerServices["SoftLayer_Network_Storage_Allowed_Host"] = services.NewSoftLayer_Network_Storage_Allowed_Host_Service(slc)
slc.softLayerServices["SoftLayer_Product_Order"] = services.NewSoftLayer_Product_Order_Service(slc)
slc.softLayerServices["SoftLayer_Billing_Item_Cancellation_Request"] = services.NewSoftLayer_Billing_Item_Cancellation_Request_Service(slc)
slc.softLayerServices["SoftLayer_Billing_Item"] = services.NewSoftLayer_Billing_Item_Service(slc)
slc.softLayerServices["SoftLayer_Virtual_Guest_Block_Device_Template_Group"] = services.NewSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service(slc)
slc.softLayerServices["SoftLayer_Hardware"] = services.NewSoftLayer_Hardware_Service(slc)
slc.softLayerServices["SoftLayer_Dns_Domain"] = services.NewSoftLayer_Dns_Domain_Service(slc)
slc.softLayerServices["SoftLayer_Dns_Domain_ResourceRecord"] = services.NewSoftLayer_Dns_Domain_ResourceRecord_Service(slc)
}
func hideCredentials(s string) string {
hiddenStr := "\"password\":\"******\""
r := regexp.MustCompile(`"password":"[^"]*"`)
return r.ReplaceAllString(s, hiddenStr)
}
func (slc *SoftLayerClient) makeHttpRequest(url string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
req, err := http.NewRequest(requestType, url, requestBody)
if err != nil {
return nil, err
}
bs, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
if !slc.nonVerbose {
fmt.Fprintf(os.Stderr, "\n---\n[softlayer-go] Request:\n%s\n", hideCredentials(string(bs)))
}
resp, err := slc.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bs, err = httputil.DumpResponse(resp, true)
if err != nil {
return nil, err
}
if !slc.nonVerbose {
fmt.Fprintf(os.Stderr, "[softlayer-go] Response:\n%s\n", hideCredentials(string(bs)))
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return responseBody, nil
}
//Private helper methods
func checkNonVerbose() bool {
slGoNonVerbose := os.Getenv(SL_GO_NON_VERBOSE)
switch slGoNonVerbose {
case "yes":
return true
case "YES":
return true
case "true":
return true
case "TRUE":
return true
}
return false
}

View File

@ -1,13 +0,0 @@
package client_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestClient(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "SoftLayer Client Suite")
}

View File

@ -1,173 +0,0 @@
package client_test
import (
"bytes"
"errors"
"net"
"net/http"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclient "github.com/maximilien/softlayer-go/client"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
var _ = Describe("SoftLayerClient", func() {
var (
username string
apiKey string
client softlayer.Client
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
apiKey = os.Getenv("SL_API_KEY")
client = slclient.NewSoftLayerClient(username, apiKey)
})
Context("#NewSoftLayerClient", func() {
It("creates a new client with username and apiKey", func() {
Expect(username).ToNot(Equal(""), "username cannot be empty, set SL_USERNAME")
Expect(apiKey).ToNot(Equal(""), "apiKey cannot be empty, set SL_API_KEY")
client = slclient.NewSoftLayerClient(username, apiKey)
Expect(client).ToNot(BeNil())
})
})
Context("#NewSoftLayerClient_HTTPClient", func() {
It("creates a new client which should have an initialized default HTTP client", func() {
client = slclient.NewSoftLayerClient(username, apiKey)
if c, ok := client.(*slclient.SoftLayerClient); ok {
Expect(c.HTTPClient).ToNot(BeNil())
}
})
It("creates a new client with a custom HTTP client", func() {
client = slclient.NewSoftLayerClient(username, apiKey)
c, _ := client.(*slclient.SoftLayerClient)
// Assign a malformed dialer to test if the HTTP client really works
var errDialFailed = errors.New("dial failed")
c.HTTPClient = &http.Client{
Transport: &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return nil, errDialFailed
},
},
}
_, err := c.DoRawHttpRequest("/foo", "application/text", bytes.NewBufferString("random text"))
Expect(err).To(Equal(errDialFailed))
})
})
Context("#GetService", func() {
It("returns a service with name specified", func() {
accountService, err := client.GetService("SoftLayer_Account")
Expect(err).ToNot(HaveOccurred())
Expect(accountService).ToNot(BeNil())
})
It("fails when passed a bad service name", func() {
_, err := client.GetService("fake-service-name")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("softlayer-go does not support service 'fake-service-name'"))
})
})
Context("#GetSoftLayer_Account_Service", func() {
It("returns a instance implemementing the SoftLayer_Account_Service interface", func() {
var accountService softlayer.SoftLayer_Account_Service
accountService, err := client.GetSoftLayer_Account_Service()
Expect(err).ToNot(HaveOccurred())
Expect(accountService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Virtual_Guest_Service", func() {
It("returns a instance implemementing the SoftLayer_Virtual_Guest_Service interface", func() {
var virtualGuestService softlayer.SoftLayer_Virtual_Guest_Service
virtualGuestService, err := client.GetSoftLayer_Virtual_Guest_Service()
Expect(err).ToNot(HaveOccurred())
Expect(virtualGuestService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Ssh_Key_Service", func() {
It("returns a instance implemementing the SoftLayer_Ssh_Key_Service interface", func() {
var sshKeyService softlayer.SoftLayer_Security_Ssh_Key_Service
sshKeyService, err := client.GetSoftLayer_Security_Ssh_Key_Service()
Expect(err).ToNot(HaveOccurred())
Expect(sshKeyService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Product_Order_Service", func() {
It("returns a instance implemementing the SoftLayer_Product_Order_Service interface", func() {
var productOrderService softlayer.SoftLayer_Product_Order_Service
productOrderService, err := client.GetSoftLayer_Product_Order_Service()
Expect(err).ToNot(HaveOccurred())
Expect(productOrderService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Product_Package_Service", func() {
It("returns a instance implemementing the SoftLayer_Product_Package interface", func() {
var productPackageService softlayer.SoftLayer_Product_Package_Service
productPackageService, err := client.GetSoftLayer_Product_Package_Service()
Expect(err).ToNot(HaveOccurred())
Expect(productPackageService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Network_Storage_Service", func() {
It("returns a instance implemementing the GetSoftLayer_Network_Storage_Service interface", func() {
var networkStorageService softlayer.SoftLayer_Network_Storage_Service
networkStorageService, err := client.GetSoftLayer_Network_Storage_Service()
Expect(err).ToNot(HaveOccurred())
Expect(networkStorageService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Network_Storage_Allowed_Host_Service", func() {
It("returns a instance implemementing the GetSoftLayer_Network_Storage_Allowed_Host_Service interface", func() {
var networkStorageAllowedHostService softlayer.SoftLayer_Network_Storage_Allowed_Host_Service
networkStorageAllowedHostService, err := client.GetSoftLayer_Network_Storage_Allowed_Host_Service()
Expect(err).ToNot(HaveOccurred())
Expect(networkStorageAllowedHostService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Billing_Item_Cancellation_Request", func() {
It("returns a instance implemementing the SoftLayer_Billing_Item_Cancellation_Request interface", func() {
var billingItemCancellationRequestService softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service
billingItemCancellationRequestService, err := client.GetSoftLayer_Billing_Item_Cancellation_Request_Service()
Expect(err).ToNot(HaveOccurred())
Expect(billingItemCancellationRequestService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service", func() {
It("returns a instance implemementing the SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service interface", func() {
var vgbdtgService softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service
vgbdtgService, err := client.GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service()
Expect(err).ToNot(HaveOccurred())
Expect(vgbdtgService).ToNot(BeNil())
})
})
Context("#GetSoftLayer_Hardware_Service", func() {
It("returns an instance implemementing the SoftLayer_Hardware_Service interface", func() {
var hardwareService softlayer.SoftLayer_Hardware_Service
hardwareService, err := client.GetSoftLayer_Hardware_Service()
Expect(err).ToNot(HaveOccurred())
Expect(hardwareService).ToNot(BeNil())
})
})
})

View File

@ -1,13 +0,0 @@
package common_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestCommon(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Common Suite")
}

View File

@ -14,3 +14,11 @@ func ValidateJson(s string) (bool, error) {
return true, nil
}
func IsHttpErrorCode(errorCode int) bool {
if errorCode >= 400 {
return true
}
return false
}

View File

@ -1,29 +0,0 @@
package common_test
import (
. "github.com/maximilien/softlayer-go/common"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Utility", func() {
var (
result bool
err error
)
Context("#ValidateJson", func() {
It("returns true if the input string is valid Json format", func() {
result, err = ValidateJson(`{"correct_json":"whatever"}`)
Expect(result).To(Equal(true))
Expect(err).ToNot(HaveOccurred())
})
It("returns false if the input string is invalid Json format", func() {
result, err = ValidateJson(`{{"wrong_json":"whatever"}`)
Expect(result).To(Equal(false))
Expect(err).To(HaveOccurred())
})
})
})

View File

@ -15,3 +15,7 @@ type SoftLayer_Virtual_Guest_Block_Device_Template_Group_LocationsInitParameters
type SoftLayer_Virtual_Guest_Block_Device_Template_Group_LocationsInitParameter struct {
Locations []SoftLayer_Location `json:"locations"`
}
type SoftLayer_Virtual_Guest_Block_Device_Template_GroupInitParameters2 struct {
Parameters []interface{} `json:"parameters"`
}

View File

@ -0,0 +1,30 @@
package data_types
import (
"time"
)
type SoftLayer_Billing_Item struct {
Id int `json:"id"`
AllowCancellationFlag int `json:"allowCancellationFlag,omitempty"`
CancellationDate *time.Time `json:"cancellationDate,omitempty"`
CategoryCode string `json:"categoryCode,omitempty"`
CycleStartDate *time.Time `json:"cycleStartDate,omitempty"`
CreateDate *time.Time `json:"createDate,omitempty"`
Description string `json:"description,omitempty"`
LaborFee string `json:"laborFee,omitempty"`
LaborFeeTaxRate string `json:"laborFeeTaxRate,omitempty"`
LastBillDate *time.Time `json:"lastBillDate,omitempty"`
ModifyDate *time.Time `json:"modifyDate,omitempty"`
NextBillDate *time.Time `json:"nextBillDate,omitempty"`
OneTimeFee string `json:"oneTimeFee,omitempty"`
OneTimeFeeTaxRate string `json:"oneTimeFeeTaxRate,omitempty"`
OrderItemId int `json:"orderItemId,omitempty"`
ParentId int `json:"parentId,omitempty"`
RecurringFee string `json:"recurringFee,omitempty"`
RecurringFeeTaxRate string `json:"recurringFeeTaxRate,omitempty"`
RecurringMonths int `json:"recurringMonths,omitempty"`
ServiceProviderId int `json:"serviceProviderId,omitempty"`
SetupFee string `json:"setupFee,omitempty"`
SetupFeeTaxRate string `json:"setupFeeTaxRate,omitempty"`
}

View File

@ -0,0 +1,18 @@
package data_types
import "time"
type SoftLayer_Virtual_Guest_Block_Device struct {
BootableFlag int `json:"bootableFlag"`
CreateDate *time.Time `json:"createDate"`
Device string `json:"device"`
DiskImageId int `json:"diskImageId"`
GuestId int `json:"guestId"`
HotPlugFlag int `json:"hotPlugFlag"`
Id int `json:"id"`
ModifyDate *time.Time `json:"modifyDate"`
MountMode string `json:"mountMode"`
MountType string `json:"mountType"`
StatusId int `json:"statusId"`
Uuid string `json:"uuid"`
}

View File

@ -1,9 +1,13 @@
package data_types
type SoftLayer_Virtual_GuestInitParameters struct {
Parameters SoftLayer_Virtual_GuestInitParameter `json:"parameters"`
Parameters []interface{} `json:"parameters"`
}
type SoftLayer_Virtual_GuestInitParameter struct {
type SoftLayer_Virtual_GuestInit_ImageId_Parameters struct {
Parameters ImageId_Parameter `json:"parameters"`
}
type ImageId_Parameter struct {
ImageId int `json:"imageId"`
}

View File

@ -1,9 +0,0 @@
package main
import (
"fmt"
)
func main() {
fmt.Println("SoftLayer go client")
}

View File

@ -1,13 +0,0 @@
package services_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestServices(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Services Suite")
}

View File

@ -27,12 +27,17 @@ func (slas *softLayer_Account_Service) GetName() string {
func (slas *softLayer_Account_Service) GetAccountStatus() (datatypes.SoftLayer_Account_Status, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getAccountStatus.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getAccountStatus, error message '%s'", err.Error())
return datatypes.SoftLayer_Account_Status{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getAccountStatus, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Account_Status{}, errors.New(errorMessage)
}
accountStatus := datatypes.SoftLayer_Account_Status{}
err = json.Unmarshal(responseBytes, &accountStatus)
if err != nil {
@ -46,12 +51,87 @@ func (slas *softLayer_Account_Service) GetAccountStatus() (datatypes.SoftLayer_A
func (slas *softLayer_Account_Service) GetVirtualGuests() ([]datatypes.SoftLayer_Virtual_Guest, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getVirtualGuests.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getVirtualGuests, error message '%s'", err.Error())
return []datatypes.SoftLayer_Virtual_Guest{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getVirtualGuests, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Virtual_Guest{}, errors.New(errorMessage)
}
virtualGuests := []datatypes.SoftLayer_Virtual_Guest{}
err = json.Unmarshal(responseBytes, &virtualGuests)
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: failed to decode JSON response, err message '%s'", err.Error())
err := errors.New(errorMessage)
return []datatypes.SoftLayer_Virtual_Guest{}, err
}
return virtualGuests, nil
}
func (slas *softLayer_Account_Service) GetVirtualGuestsByFilter(filters string) ([]datatypes.SoftLayer_Virtual_Guest, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getVirtualGuests.json")
objectMasks := []string{
"accountId",
"createDate",
"dedicatedAccountHostOnlyFlag",
"domain",
"fullyQualifiedDomainName",
"hostname",
"hourlyBillingFlag",
"id",
"lastPowerStateId",
"lastVerifiedDate",
"maxCpu",
"maxCpuUnits",
"maxMemory",
"metricPollDate",
"modifyDate",
"notes",
"postInstallScriptUri",
"privateNetworkOnlyFlag",
"startCpus",
"statusId",
"uuid",
"userData.value",
"localDiskFlag",
"globalIdentifier",
"managedResourceFlag",
"primaryBackendIpAddress",
"primaryIpAddress",
"location.name",
"location.longName",
"location.id",
"datacenter.name",
"datacenter.longName",
"datacenter.id",
"networkComponents.maxSpeed",
"operatingSystem.passwords.password",
"operatingSystem.passwords.username",
"blockDeviceTemplateGroup.globalIdentifier",
"primaryNetworkComponent.networkVlan.id",
"primaryBackendNetworkComponent.networkVlan.id",
}
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequestWithObjectFilterAndObjectMask(path, objectMasks, filters, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getVirtualGuests, error message '%s'", err.Error())
return []datatypes.SoftLayer_Virtual_Guest{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getVirtualGuests, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Virtual_Guest{}, errors.New(errorMessage)
}
virtualGuests := []datatypes.SoftLayer_Virtual_Guest{}
err = json.Unmarshal(responseBytes, &virtualGuests)
if err != nil {
@ -65,12 +145,17 @@ func (slas *softLayer_Account_Service) GetVirtualGuests() ([]datatypes.SoftLayer
func (slas *softLayer_Account_Service) GetNetworkStorage() ([]datatypes.SoftLayer_Network_Storage, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getNetworkStorage.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getNetworkStorage, error message '%s'", err.Error())
return []datatypes.SoftLayer_Network_Storage{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getNetworkStorage, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Network_Storage{}, errors.New(errorMessage)
}
networkStorage := []datatypes.SoftLayer_Network_Storage{}
err = json.Unmarshal(responseBytes, &networkStorage)
if err != nil {
@ -94,12 +179,17 @@ func (slas *softLayer_Account_Service) GetIscsiNetworkStorage() ([]datatypes.Sof
"billingItem.orderItem.order.id",
}
responseBytes, err := slas.client.DoRawHttpRequestWithObjectMask(path, objectMasks, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequestWithObjectMask(path, objectMasks, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getIscsiNetworkStorage, error message '%s'", err.Error())
return []datatypes.SoftLayer_Network_Storage{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getIscsiNetworkStorage, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Network_Storage{}, errors.New(errorMessage)
}
networkStorage := []datatypes.SoftLayer_Network_Storage{}
err = json.Unmarshal(responseBytes, &networkStorage)
if err != nil {
@ -123,12 +213,17 @@ func (slas *softLayer_Account_Service) GetIscsiNetworkStorageWithFilter(filter s
"billingItem.orderItem.order.id",
}
responseBytes, err := slas.client.DoRawHttpRequestWithObjectFilterAndObjectMask(path, objectMasks, filter, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequestWithObjectFilterAndObjectMask(path, objectMasks, filter, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getIscsiNetworkStorage, error message '%s'", err.Error())
return []datatypes.SoftLayer_Network_Storage{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getIscsiNetworkStorage, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Network_Storage{}, errors.New(errorMessage)
}
networkStorage := []datatypes.SoftLayer_Network_Storage{}
err = json.Unmarshal(responseBytes, &networkStorage)
if err != nil {
@ -142,12 +237,17 @@ func (slas *softLayer_Account_Service) GetIscsiNetworkStorageWithFilter(filter s
func (slas *softLayer_Account_Service) GetVirtualDiskImages() ([]datatypes.SoftLayer_Virtual_Disk_Image, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getVirtualDiskImages.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could get SoftLayer_Account#getVirtualDiskImages, error message '%s'", err.Error())
return []datatypes.SoftLayer_Virtual_Disk_Image{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getVirtualDiskImages, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Virtual_Disk_Image{}, errors.New(errorMessage)
}
virtualDiskImages := []datatypes.SoftLayer_Virtual_Disk_Image{}
err = json.Unmarshal(responseBytes, &virtualDiskImages)
if err != nil {
@ -167,12 +267,17 @@ func (slas *softLayer_Account_Service) GetVirtualDiskImagesWithFilter(filters st
}
path := fmt.Sprintf("%s/%s", slas.GetName(), "getVirtualDiskImages.json")
responseBytes, err := slas.client.DoRawHttpRequestWithObjectFilter(path, filters, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequestWithObjectFilter(path, filters, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could get SoftLayer_Account#getVirtualDiskImages, error message '%s'", err.Error())
return []datatypes.SoftLayer_Virtual_Disk_Image{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getVirtualDiskImages, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Virtual_Disk_Image{}, errors.New(errorMessage)
}
virtualDiskImages := []datatypes.SoftLayer_Virtual_Disk_Image{}
err = json.Unmarshal(responseBytes, &virtualDiskImages)
if err != nil {
@ -186,12 +291,17 @@ func (slas *softLayer_Account_Service) GetVirtualDiskImagesWithFilter(filters st
func (slas *softLayer_Account_Service) GetSshKeys() ([]datatypes.SoftLayer_Security_Ssh_Key, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getSshKeys.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getSshKeys, error message '%s'", err.Error())
return []datatypes.SoftLayer_Security_Ssh_Key{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getSshKeys, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Security_Ssh_Key{}, errors.New(errorMessage)
}
sshKeys := []datatypes.SoftLayer_Security_Ssh_Key{}
err = json.Unmarshal(responseBytes, &sshKeys)
if err != nil {
@ -205,12 +315,17 @@ func (slas *softLayer_Account_Service) GetSshKeys() ([]datatypes.SoftLayer_Secur
func (slas *softLayer_Account_Service) GetBlockDeviceTemplateGroups() ([]datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getBlockDeviceTemplateGroups.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getBlockDeviceTemplateGroups, error message '%s'", err.Error())
return []datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getBlockDeviceTemplateGroups, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, errors.New(errorMessage)
}
vgbdtGroups := []datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}
err = json.Unmarshal(responseBytes, &vgbdtGroups)
if err != nil {
@ -230,12 +345,17 @@ func (slas *softLayer_Account_Service) GetBlockDeviceTemplateGroupsWithFilter(fi
}
path := fmt.Sprintf("%s/%s", slas.GetName(), "getBlockDeviceTemplateGroups.json")
responseBytes, err := slas.client.DoRawHttpRequestWithObjectFilter(path, filters, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequestWithObjectFilter(path, filters, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getBlockDeviceTemplateGroups, error message '%s'", err.Error())
return []datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getBlockDeviceTemplateGroups, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, errors.New(errorMessage)
}
vgbdtGroups := []datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}
err = json.Unmarshal(responseBytes, &vgbdtGroups)
if err != nil {
@ -247,18 +367,24 @@ func (slas *softLayer_Account_Service) GetBlockDeviceTemplateGroupsWithFilter(fi
return vgbdtGroups, nil
}
//TODO: why is this method empty? Remove?
func (slas *softLayer_Account_Service) GetDatacentersWithSubnetAllocations() ([]datatypes.SoftLayer_Location, error) {
return []datatypes.SoftLayer_Location{}, nil
}
func (slas *softLayer_Account_Service) GetHardware() ([]datatypes.SoftLayer_Hardware, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getHardware.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getHardware, error message '%s'", err.Error())
return []datatypes.SoftLayer_Hardware{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getHardware, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Hardware{}, errors.New(errorMessage)
}
hardwares := []datatypes.SoftLayer_Hardware{}
err = json.Unmarshal(responseBytes, &hardwares)
@ -273,12 +399,17 @@ func (slas *softLayer_Account_Service) GetHardware() ([]datatypes.SoftLayer_Hard
func (slas *softLayer_Account_Service) GetDnsDomains() ([]datatypes.SoftLayer_Dns_Domain, error) {
path := fmt.Sprintf("%s/%s", slas.GetName(), "getDomains.json")
responseBytes, err := slas.client.DoRawHttpRequest(path, "GET", &bytes.Buffer{})
responseBytes, errorCode, err := slas.client.GetHttpClient().DoRawHttpRequest(path, "GET", &bytes.Buffer{})
if err != nil {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getDomains, error message '%s'", err.Error())
return []datatypes.SoftLayer_Dns_Domain{}, errors.New(errorMessage)
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getDomains, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Dns_Domain{}, errors.New(errorMessage)
}
domains := []datatypes.SoftLayer_Dns_Domain{}
err = json.Unmarshal(responseBytes, &domains)
if err != nil {

View File

@ -5,7 +5,10 @@ import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -25,11 +28,16 @@ func (slvgs *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetNam
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetObject(id int) (datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getObject.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getObject.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, errors.New(errorMessage)
}
vgbdtGroup := datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}
err = json.Unmarshal(response, &vgbdtGroup)
if err != nil {
@ -40,11 +48,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Get
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) DeleteObject(id int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slvgbdtg.GetName(), id), "DELETE", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slvgbdtg.GetName(), id), "DELETE", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#deleteObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
transaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &transaction)
if err != nil {
@ -55,11 +68,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Del
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetDatacenters(id int) ([]datatypes.SoftLayer_Location, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getDatacenters.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getDatacenters.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Location{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getDatacenters, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Location{}, errors.New(errorMessage)
}
locations := []datatypes.SoftLayer_Location{}
err = json.Unmarshal(response, &locations)
if err != nil {
@ -70,11 +88,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Get
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetSshKeys(id int) ([]datatypes.SoftLayer_Security_Ssh_Key, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getSshKeys.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getSshKeys.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Security_Ssh_Key{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getSshKeys, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Security_Ssh_Key{}, errors.New(errorMessage)
}
sshKeys := []datatypes.SoftLayer_Security_Ssh_Key{}
err = json.Unmarshal(response, &sshKeys)
if err != nil {
@ -85,11 +108,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Get
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetStatus(id int) (datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Status, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getStatus.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getStatus.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Status{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getStatus, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Status{}, errors.New(errorMessage)
}
status := datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Status{}
err = json.Unmarshal(response, &status)
if err != nil {
@ -100,11 +128,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Get
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetImageType(id int) (datatypes.SoftLayer_Image_Type, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getImageType.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getImageType.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Image_Type{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getImageType, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Image_Type{}, errors.New(errorMessage)
}
imageType := datatypes.SoftLayer_Image_Type{}
err = json.Unmarshal(response, &imageType)
if err != nil {
@ -115,11 +148,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Get
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetStorageLocations(id int) ([]datatypes.SoftLayer_Location, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getStorageLocations.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getStorageLocations.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Location{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getStorageLocations, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Location{}, errors.New(errorMessage)
}
locations := []datatypes.SoftLayer_Location{}
err = json.Unmarshal(response, &locations)
if err != nil {
@ -139,11 +177,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Cre
return datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, err
}
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/createFromExternalSource.json", slvgbdtg.GetName()), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/createFromExternalSource.json", slvgbdtg.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#createFromExternalSource, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}, errors.New(errorMessage)
}
vgbdtGroup := datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}
err = json.Unmarshal(response, &vgbdtGroup)
if err != nil {
@ -163,11 +206,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Cop
return false, err
}
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/copyToExternalSource.json", slvgbdtg.GetName()), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/copyToExternalSource.json", slvgbdtg.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#copyToExternalSource, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to create virtual guest block device template group, got '%s' as response from the API.", res))
}
@ -176,17 +224,27 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Cop
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetImageTypeKeyName(id int) (string, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getImageTypeKeyName.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getImageTypeKeyName.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getImageTypeKeyName, HTTP error code: '%d'", errorCode)
return "", errors.New(errorMessage)
}
return string(response), err
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) GetTransaction(id int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getTransaction.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getTransaction.json", slvgbdtg.GetName(), id), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#getTransaction, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
transaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &transaction)
if err != nil {
@ -208,11 +266,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Den
return false, err
}
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/denySharingAccess.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/denySharingAccess.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#denySharingAccess, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to permit sharing access to VGDBTG with ID: %d to account ID: %d", id, accountId))
}
@ -232,11 +295,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Per
return false, err
}
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/permitSharingAccess.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/permitSharingAccess.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#permitSharingAccess, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to permit sharing access to VGDBTG with ID: %d to account ID: %d", id, accountId))
}
@ -256,11 +324,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Add
return false, err
}
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/addLocations.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/addLocations.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#addLocations, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to add locations access to VGDBTG with ID: %d", id))
}
@ -280,11 +353,16 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Rem
return false, err
}
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/removeLocations.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/removeLocations.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#removeLocations, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to remove locations access to VGDBTG with ID: %d", id))
}
@ -304,14 +382,56 @@ func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) Set
return false, err
}
response, err := slvgbdtg.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/setAvailableLocations.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/setAvailableLocations.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#setAvailableLocations, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to set available locations access to VGDBTG with ID: %d", id))
}
return true, nil
}
func (slvgbdtg *softLayer_Virtual_Guest_Block_Device_Template_Group_Service) CreatePublicArchiveTransaction(id int, groupName string, summary string, note string, locations []datatypes.SoftLayer_Location) (int, error) {
locationIdsArray := []int{}
for _, location := range locations {
locationIdsArray = append(locationIdsArray, location.Id)
}
groupName = url.QueryEscape(groupName)
summary = url.QueryEscape(summary)
note = url.QueryEscape(note)
parameters := datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_GroupInitParameters2{
Parameters: []interface{}{groupName, summary, note, locationIdsArray},
}
requestBody, err := json.Marshal(parameters)
if err != nil {
return 0, err
}
response, errorCode, err := slvgbdtg.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/createPublicArchiveTransaction.json", slvgbdtg.GetName(), id), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return 0, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest_Block_Device_Template_Group#createPublicArchiveTransaction, HTTP error code: '%d'", errorCode)
return 0, errors.New(errorMessage)
}
transactionId, err := strconv.Atoi(string(response[:]))
if err != nil {
return 0, errors.New(fmt.Sprintf("Failed to createPublicArchiveTransaction for ID: %d, error: %s", id, string(response[:])))
}
return transactionId, nil
}

View File

@ -1,386 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Virtual_Guest_Service", func() {
var (
username, apiKey string
err error
fakeClient *slclientfakes.FakeSoftLayerClient
vgbdtgService softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service
vgbdtGroup datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group
locations []datatypes.SoftLayer_Location
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
vgbdtgService, err = fakeClient.GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service()
Expect(err).ToNot(HaveOccurred())
Expect(vgbdtgService).ToNot(BeNil())
vgbdtGroup = datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group{}
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := vgbdtgService.GetName()
Expect(name).To(Equal("SoftLayer_Virtual_Guest_Block_Device_Template_Group"))
})
})
Context("#GetObject", func() {
BeforeEach(func() {
vgbdtGroup.Id = 200150
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_getObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Virtual_Guest_Block_Device_Template_Group instance", func() {
vgbdtg, err := vgbdtgService.GetObject(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(vgbdtg.AccountId).To(Equal(278444))
Expect(vgbdtg.CreateDate).ToNot(BeNil())
Expect(vgbdtg.Id).To(Equal(vgbdtGroup.Id))
Expect(vgbdtg.Name).To(Equal("BOSH-eCPI-packer-centos-2014-08-12T15:54:16Z"))
Expect(vgbdtg.Note).To(Equal("centos image created by packer at 2014-08-12T15:54:16Z"))
Expect(vgbdtg.ParentId).To(BeNil())
Expect(vgbdtg.PublicFlag).To(Equal(0))
Expect(vgbdtg.StatusId).To(Equal(1))
Expect(vgbdtg.Summary).To(Equal("centos image created by packer at 2014-08-12T15:54:16Z"))
Expect(vgbdtg.TransactionId).To(BeNil())
Expect(vgbdtg.UserRecordId).To(Equal(239954))
Expect(vgbdtg.GlobalIdentifier).To(Equal("8071601b-5ee1-483e-a9e8-6e5582dcb9f7"))
})
})
Context("#DeleteObject", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_deleteObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully deletes the SoftLayer_Virtual_Guest_Block_Device_Template_Group instance", func() {
transaction, err := vgbdtgService.DeleteObject(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(transaction.CreateDate).ToNot(BeNil())
Expect(transaction.ElapsedSeconds).To(Equal(1))
Expect(transaction.GuestId).To(Equal(1234567))
Expect(transaction.HardwareId).To(Equal(0))
Expect(transaction.Id).To(Equal(11878004))
Expect(transaction.ModifyDate).ToNot(BeNil())
Expect(transaction.StatusChangeDate).ToNot(BeNil())
Expect(transaction.TransactionGroup).To(Equal(datatypes.TransactionGroup{}))
Expect(transaction.TransactionStatus.AverageDuration).To(Equal(".42"))
Expect(transaction.TransactionStatus.FriendlyName).To(Equal("Cloud Reclaim Prep"))
Expect(transaction.TransactionStatus.Name).To(Equal("CLOUD_RECLAIM_PREP"))
})
})
Context("#GetDatacenters", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_getDatacenters.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves an array of SoftLayer_Location array for virtual guest device template group", func() {
locations, err := vgbdtgService.GetDatacenters(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(locations)).To(BeNumerically("==", 2))
Expect(locations[0].Id).To(Equal(265592))
Expect(locations[0].LongName).To(Equal("Amsterdam 1"))
Expect(locations[0].Name).To(Equal("ams01"))
Expect(locations[1].Id).To(Equal(154820))
Expect(locations[1].LongName).To(Equal("Dallas 6"))
Expect(locations[1].Name).To(Equal("dal06"))
})
})
Context("#GetSshKeys", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_getSshKeys.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves an array of SoftLayer_Security_Ssh_Key array for virtual guest device template group", func() {
sshKeys, err := vgbdtgService.GetSshKeys(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(sshKeys)).To(BeNumerically(">", 0))
for _, sshKey := range sshKeys {
Expect(sshKey.CreateDate).ToNot(BeNil())
Expect(sshKey.Fingerprint).To(Equal("f6:c2:9d:57:2f:74:be:a1:db:71:f2:e5:8e:0f:84:7e"))
Expect(sshKey.Id).To(Equal(84386))
Expect(sshKey.Key).ToNot(Equal(""))
Expect(sshKey.Label).To(Equal("TEST:softlayer-go"))
Expect(sshKey.ModifyDate).To(BeNil())
Expect(sshKey.Label).To(Equal("TEST:softlayer-go"))
}
})
})
Context("#GetStatus", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_getStatus.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Virtual_Guest_Block_Device_Template_Group instance status", func() {
status, err := vgbdtgService.GetStatus(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(status.Description).To(Equal("The Guest Block Device Template Group is available to all accounts"))
Expect(status.KeyName).To(Equal("ACTIVE"))
Expect(status.Name).To(Equal("Active"))
})
})
Context("#GetStorageLocations", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_getStorageLocations.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Locations for the Virtual_Guest_Block_Device_Template_Group instance", func() {
locations, err := vgbdtgService.GetStorageLocations(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(locations)).To(Equal(18))
found := false
for _, location := range locations {
if location.LongName == "Paris 1" {
Expect(location.Id).To(Equal(449500))
Expect(location.Name).To(Equal("par01"))
found = true
break
}
}
Expect(found).To(BeTrue())
})
})
Context("#GetImageType", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_getImageType.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves the image type for the instance", func() {
imageType, err := vgbdtgService.GetImageType(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(imageType.Description).To(Equal("a disk that may be replaced on upgrade"))
Expect(imageType.KeyName).To(Equal("SYSTEM"))
Expect(imageType.Name).To(Equal("System"))
})
})
Context("#GetImageTypeKeyName", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_getImageTypeKeyName.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves the image type key name for the instance", func() {
imageTypeKeyName, err := vgbdtgService.GetImageTypeKeyName(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(imageTypeKeyName).To(Equal("SYSTEM"))
})
})
Context("#CreateFromExternalSource", func() {
var configuration datatypes.SoftLayer_Container_Virtual_Guest_Block_Device_Template_Configuration
BeforeEach(func() {
configuration = datatypes.SoftLayer_Container_Virtual_Guest_Block_Device_Template_Configuration{
Name: "fake-configuration-name",
Note: "fake-configuration-note",
OperatingSystemReferenceCode: "fake-operating-system-reference-code",
Uri: "swift://FakeObjectStorageAccountName>@fake-clusterName/fake-containerName/fake-fileName.vhd",
}
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_createFromExternalSource.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully creates a virtual guest device templte group from a configuration from an external VHD image", func() {
vgbdtGroup, err := vgbdtgService.CreateFromExternalSource(configuration)
Expect(err).ToNot(HaveOccurred())
Expect(vgbdtGroup.AccountId).To(Equal(278444))
Expect(vgbdtGroup.CreateDate).ToNot(BeNil())
Expect(vgbdtGroup.Id).To(Equal(211582))
Expect(vgbdtGroup.Name).To(Equal(" ubuntu-10.04-bosh-2168-IEM-itcs104-dea-stemcell"))
Expect(vgbdtGroup.Note).To(Equal("fake-note"))
Expect(*vgbdtGroup.ParentId).To(Equal(211578))
Expect(vgbdtGroup.PublicFlag).To(Equal(0))
Expect(vgbdtGroup.StatusId).To(Equal(1))
Expect(vgbdtGroup.Summary).To(Equal("fake-summary"))
Expect(vgbdtGroup.TransactionId).To(BeNil())
Expect(vgbdtGroup.UserRecordId).To(Equal(180816))
Expect(vgbdtGroup.GlobalIdentifier).To(Equal("fake-global-identifier"))
})
})
Context("#CopyToExternalSource", func() {
var configuration datatypes.SoftLayer_Container_Virtual_Guest_Block_Device_Template_Configuration
BeforeEach(func() {
configuration = datatypes.SoftLayer_Container_Virtual_Guest_Block_Device_Template_Configuration{
Name: "fake-configuration-name",
Note: "fake-configuration-note",
OperatingSystemReferenceCode: "fake-operating-system-reference-code",
Uri: "swift://FakeObjectStorageAccountName>@fake-clusterName/fake-containerName/fake-fileName.vhd",
}
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_copyToExternalSource.json")
Expect(err).ToNot(HaveOccurred())
})
It("successfully copies the virtual guest device template group to an external source", func() {
copied, err := vgbdtgService.CopyToExternalSource(configuration)
Expect(err).ToNot(HaveOccurred())
Expect(copied).To(BeTrue())
})
})
Context("#GetTransaction", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_deleteObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Provisioning_Version1_Transaction for the Virtual_Guest_Block_Device_Template_Group instance", func() {
transaction, err := vgbdtgService.GetTransaction(vgbdtGroup.Id)
Expect(err).ToNot(HaveOccurred())
Expect(transaction.TransactionStatus).ToNot(BeNil())
})
})
Context("#DenySharingAccess", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_denySharingAccess.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully denies sharing access for VGBDTG instance", func() {
denySharing, err := vgbdtgService.DenySharingAccess(vgbdtGroup.Id, 1234567)
Expect(err).ToNot(HaveOccurred())
Expect(denySharing).To(BeTrue())
})
})
Context("#PermitSharingAccess", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_permitSharingAccess.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully permits sharing access for VGBDTG instance", func() {
permitSharing, err := vgbdtgService.PermitSharingAccess(vgbdtGroup.Id, 1234567)
Expect(err).ToNot(HaveOccurred())
Expect(permitSharing).To(BeTrue())
})
})
Context("#XyzLocations", func() {
BeforeEach(func() {
locations = []datatypes.SoftLayer_Location{
datatypes.SoftLayer_Location{
Id: 0,
Name: "0",
LongName: "Location 0",
},
datatypes.SoftLayer_Location{
Id: 1,
Name: "1",
LongName: "Location 1",
},
datatypes.SoftLayer_Location{
Id: 2,
Name: "2",
LongName: "Location 2",
},
}
})
Context("#AddLocations", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_addLocations.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully adds locations to VGBDTG instance", func() {
result, err := vgbdtgService.AddLocations(vgbdtGroup.Id, locations)
Expect(err).ToNot(HaveOccurred())
Expect(result).To(BeTrue())
})
})
Context("#RemoveLocations", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_removeLocations.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully removes locations to VGBDTG instance", func() {
result, err := vgbdtgService.RemoveLocations(vgbdtGroup.Id, locations)
Expect(err).ToNot(HaveOccurred())
Expect(result).To(BeTrue())
})
})
Context("#SetAvailableLocations", func() {
BeforeEach(func() {
vgbdtGroup.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service_setAvailableLocations.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully sets available locations to VGBDTG instance", func() {
result, err := vgbdtgService.SetAvailableLocations(vgbdtGroup.Id, locations)
Expect(err).ToNot(HaveOccurred())
Expect(result).To(BeTrue())
})
})
})
})

View File

@ -1,213 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Account_Service", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
accountService softlayer.SoftLayer_Account_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
accountService, err = fakeClient.GetSoftLayer_Account_Service()
Expect(err).ToNot(HaveOccurred())
Expect(accountService).ToNot(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := accountService.GetName()
Expect(name).To(Equal("SoftLayer_Account"))
})
})
Context("#GetAccountStatus", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getAccountStatus.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an instance of datatypes.SoftLayer_Account_Status that is Active", func() {
accountStatus, err := accountService.GetAccountStatus()
Expect(err).ToNot(HaveOccurred())
Expect(accountStatus.Id).ToNot(Equal(0))
Expect(accountStatus.Name).To(Equal("Active"))
})
})
Context("#GetVirtualGuests", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getVirtualGuests.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Virtual_Guest", func() {
virtualGuests, err := accountService.GetVirtualGuests()
Expect(err).ToNot(HaveOccurred())
Expect(virtualGuests).ToNot(BeNil())
})
})
Context("#GetNetworkStorage", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getNetworkStorage.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Network_Storage", func() {
networkStorage, err := accountService.GetNetworkStorage()
Expect(err).ToNot(HaveOccurred())
Expect(networkStorage).ToNot(BeNil())
})
})
Context("#GetIscsiNetworkStorage", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getNetworkStorage.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Network_Storage", func() {
iscsiNetworkStorage, err := accountService.GetIscsiNetworkStorage()
Expect(err).ToNot(HaveOccurred())
Expect(iscsiNetworkStorage).ToNot(BeNil())
})
})
Context("#GetIscsiNetworkStorageWithFilter", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getNetworkStorage.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Network_Storage", func() {
iscsiNetworkStorage, err := accountService.GetIscsiNetworkStorageWithFilter("fake-filter")
Expect(err).ToNot(HaveOccurred())
Expect(iscsiNetworkStorage).ToNot(BeNil())
})
})
Context("#GetVirtualDiskImages", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getVirtualDiskImages.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Virtual_Disk_Image", func() {
virtualDiskImages, err := accountService.GetVirtualDiskImages()
Expect(err).ToNot(HaveOccurred())
Expect(virtualDiskImages).ToNot(BeNil())
})
})
Context("#GetVirtualDiskImagesWithFilter", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getVirtualDiskImagesWithFilter.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Virtual_Disk_Image", func() {
virtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(`{"correct-filter":"whatever"}`)
Expect(err).ToNot(HaveOccurred())
Expect(virtualDiskImages).ToNot(BeNil())
})
It("returns an error due to failed Json validation", func() {
_, err := accountService.GetVirtualDiskImagesWithFilter(`{{"wrong-filter":"whatever"}`)
Expect(err).To(HaveOccurred())
})
})
Context("#GetSshKeys", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getSshKeys.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Ssh_Key", func() {
sshKeys, err := accountService.GetSshKeys()
Expect(err).ToNot(HaveOccurred())
Expect(sshKeys).ToNot(BeNil())
})
})
Context("#GetBlockDeviceTemplateGroups", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getBlockDeviceTemplateGroups.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group", func() {
groups, err := accountService.GetBlockDeviceTemplateGroups()
Expect(err).ToNot(HaveOccurred())
Expect(groups).ToNot(BeNil())
})
})
Context("#GetBlockDeviceTemplateGroupsWithFilter", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getBlockDeviceTemplateGroups.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group", func() {
groups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(`{"correct-filter":"whatever"}`)
Expect(err).ToNot(HaveOccurred())
Expect(groups).ToNot(BeNil())
})
It("returns an error due to failed Json validation", func() {
_, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(`{{"wrong-filter":"whatever"}`)
Expect(err).To(HaveOccurred())
})
})
Context("#GetDatacentersWithSubnetAllocations", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getDatacentersWithSubnetAllocations.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Virtual_Location", func() {
locations, err := accountService.GetBlockDeviceTemplateGroups()
Expect(err).ToNot(HaveOccurred())
Expect(locations).ToNot(BeNil())
Expect(len(locations)).To(BeNumerically(">", 0))
})
})
Context("#GetHardware", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Account_Service_getHardware.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Hardware", func() {
hardwares, err := accountService.GetHardware()
Expect(err).ToNot(HaveOccurred())
Expect(hardwares).ToNot(BeNil())
Expect(len(hardwares)).To(BeNumerically(">", 0))
})
})
})

View File

@ -0,0 +1,41 @@
package services
import (
"bytes"
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
type softLayer_Billing_Item_Service struct {
client softlayer.Client
}
func NewSoftLayer_Billing_Item_Service(client softlayer.Client) *softLayer_Billing_Item_Service {
return &softLayer_Billing_Item_Service{
client: client,
}
}
func (slbi *softLayer_Billing_Item_Service) GetName() string {
return "SoftLayer_Billing_Item"
}
func (slbi *softLayer_Billing_Item_Service) CancelService(billingId int) (bool, error) {
response, errorCode, err := slbi.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/cancelService.json", slbi.GetName(), billingId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, nil
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Billing_Item#CancelService, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}

View File

@ -3,8 +3,10 @@ package services
import (
"bytes"
"encoding/json"
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -35,11 +37,16 @@ func (slbicr *softLayer_Billing_Item_Cancellation_Request_Service) CreateObject(
return datatypes.SoftLayer_Billing_Item_Cancellation_Request{}, err
}
responseBytes, err := slbicr.client.DoRawHttpRequest(fmt.Sprintf("%s/createObject.json", slbicr.GetName()), "POST", bytes.NewBuffer(requestBody))
responseBytes, errorCode, err := slbicr.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/createObject.json", slbicr.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Billing_Item_Cancellation_Request{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Billing_Item_Cancellation_Request#createObject TTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Billing_Item_Cancellation_Request{}, errors.New(errorMessage)
}
result := datatypes.SoftLayer_Billing_Item_Cancellation_Request{}
err = json.Unmarshal(responseBytes, &result)
if err != nil {

View File

@ -1,64 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Billing_Item_Cancellation_Request", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
billingItemCancellationRequestService softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
billingItemCancellationRequestService, err = fakeClient.GetSoftLayer_Billing_Item_Cancellation_Request_Service()
Expect(err).ToNot(HaveOccurred())
Expect(billingItemCancellationRequestService).ToNot(BeNil())
})
Context("#GetNam", func() {
It("returns the name for the service", func() {
name := billingItemCancellationRequestService.GetName()
Expect(name).To(Equal("SoftLayer_Billing_Item_Cancellation_Request"))
})
})
Context("#CreateObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Billing_Item_Cancellation_Request_Service_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an instance of datatypes.SoftLayer_Network_Storage", func() {
request := datatypes.SoftLayer_Billing_Item_Cancellation_Request{}
result, err := billingItemCancellationRequestService.CreateObject(request)
Expect(err).ToNot(HaveOccurred())
Expect(result.Id).To(Equal(123))
Expect(result.AccountId).To(Equal(456))
Expect(result.TicketId).To(Equal(789))
})
})
})

View File

@ -5,8 +5,10 @@ import (
"encoding/json"
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
"github.com/maximilien/softlayer-go/softlayer"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
type softLayer_Dns_Domain_Service struct {
@ -39,12 +41,17 @@ func (sldds *softLayer_Dns_Domain_Service) CreateObject(template datatypes.SoftL
return datatypes.SoftLayer_Dns_Domain{}, err
}
response, err := sldds.client.DoRawHttpRequest(fmt.Sprintf("%s.json", sldds.GetName()), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := sldds.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s.json", sldds.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Dns_Domain{}, err
}
err = sldds.client.CheckForHttpResponseErrors(response)
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Dns_Domain#createObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Dns_Domain{}, errors.New(errorMessage)
}
err = sldds.client.GetHttpClient().CheckForHttpResponseErrors(response)
if err != nil {
return datatypes.SoftLayer_Dns_Domain{}, err
}
@ -71,11 +78,16 @@ func (sldds *softLayer_Dns_Domain_Service) GetObject(dnsId int) (datatypes.SoftL
"secondary",
}
response, err := sldds.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", sldds.GetName(), dnsId), objectMask, "GET", new(bytes.Buffer))
response, errorCode, err := sldds.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", sldds.GetName(), dnsId), objectMask, "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Dns_Domain{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Dns_Domain#getObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Dns_Domain{}, errors.New(errorMessage)
}
dns_domain := datatypes.SoftLayer_Dns_Domain{}
err = json.Unmarshal(response, &dns_domain)
if err != nil {
@ -86,11 +98,16 @@ func (sldds *softLayer_Dns_Domain_Service) GetObject(dnsId int) (datatypes.SoftL
}
func (sldds *softLayer_Dns_Domain_Service) DeleteObject(dnsId int) (bool, error) {
response, err := sldds.client.DoRawHttpRequest(fmt.Sprintf("%s/%d.json", sldds.GetName(), dnsId), "DELETE", new(bytes.Buffer))
response, errorCode, err := sldds.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d.json", sldds.GetName(), dnsId), "DELETE", new(bytes.Buffer))
if response_value := string(response[:]); response_value != "true" {
return false, errors.New(fmt.Sprintf("Failed to delete dns domain with id '%d', got '%s' as response from the API", dnsId, response_value))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Dns_Domain#deleteObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}

View File

@ -6,6 +6,7 @@ import (
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -36,12 +37,17 @@ func (sldr *SoftLayer_Dns_Domain_ResourceRecord_Service) CreateObject(template d
return datatypes.SoftLayer_Dns_Domain_ResourceRecord{}, err
}
response, err := sldr.client.DoRawHttpRequest(fmt.Sprintf("%s/createObject", sldr.getNameByType(template.Type)), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := sldr.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/createObject", sldr.getNameByType(template.Type)), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Dns_Domain_ResourceRecord{}, err
}
err = sldr.client.CheckForHttpResponseErrors(response)
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Dns_Domain_ResourceRecord#createObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Dns_Domain_ResourceRecord{}, errors.New(errorMessage)
}
err = sldr.client.GetHttpClient().CheckForHttpResponseErrors(response)
if err != nil {
return datatypes.SoftLayer_Dns_Domain_ResourceRecord{}, err
}
@ -76,16 +82,21 @@ func (sldr *SoftLayer_Dns_Domain_ResourceRecord_Service) GetObject(id int) (data
"weight",
}
response, err := sldr.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", sldr.GetName(), id), objectMask, "GET", new(bytes.Buffer))
response, errorCode, err := sldr.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", sldr.GetName(), id), objectMask, "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Dns_Domain_ResourceRecord{}, err
}
err = sldr.client.CheckForHttpResponseErrors(response)
err = sldr.client.GetHttpClient().CheckForHttpResponseErrors(response)
if err != nil {
return datatypes.SoftLayer_Dns_Domain_ResourceRecord{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Dns_Domain_ResourceRecord#getObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Dns_Domain_ResourceRecord{}, errors.New(errorMessage)
}
dns_record := datatypes.SoftLayer_Dns_Domain_ResourceRecord{}
err = json.Unmarshal(response, &dns_record)
if err != nil {
@ -96,12 +107,17 @@ func (sldr *SoftLayer_Dns_Domain_ResourceRecord_Service) GetObject(id int) (data
}
func (sldr *SoftLayer_Dns_Domain_ResourceRecord_Service) DeleteObject(recordId int) (bool, error) {
response, err := sldr.client.DoRawHttpRequest(fmt.Sprintf("%s/%d.json", sldr.GetName(), recordId), "DELETE", new(bytes.Buffer))
response, errorCode, err := sldr.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d.json", sldr.GetName(), recordId), "DELETE", new(bytes.Buffer))
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to delete DNS Domain Record with id '%d', got '%s' as response from the API.", recordId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Dns_Domain_ResourceRecord#deleteObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
@ -117,12 +133,17 @@ func (sldr *SoftLayer_Dns_Domain_ResourceRecord_Service) EditObject(recordId int
return false, err
}
response, err := sldr.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/editObject.json", sldr.getNameByType(template.Type), recordId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := sldr.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/editObject.json", sldr.getNameByType(template.Type), recordId), "POST", bytes.NewBuffer(requestBody))
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to edit DNS Domain Record with id: %d, got '%s' as response from the API.", recordId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Dns_Domain_ResourceRecord#editObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}

View File

@ -1,144 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Dns_Domain_Record", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
dnsDomainResourceRecordService softlayer.SoftLayer_Dns_Domain_ResourceRecord_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
dnsDomainResourceRecordService, err = fakeClient.GetSoftLayer_Dns_Domain_ResourceRecord_Service()
Expect(err).ToNot(HaveOccurred())
Expect(dnsDomainResourceRecordService).ToNot(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := dnsDomainResourceRecordService.GetName()
Expect(name).To(Equal("SoftLayer_Dns_Domain_ResourceRecord"))
})
})
Context("#CreateObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Dns_Domain_ResourceRecord_Service_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("creates a new SoftLayer_Dns_Domain_Record", func() {
template := datatypes.SoftLayer_Dns_Domain_ResourceRecord_Template{
Data: "testData",
DomainId: 123,
Expire: 99999,
Host: "testHost.com",
Id: 111,
Minimum: 1,
MxPriority: 9,
Refresh: 100,
ResponsiblePerson: "someTestPerson",
Retry: 444,
Ttl: 222,
Type: "someTestType",
}
result, err := dnsDomainResourceRecordService.CreateObject(template)
Expect(err).ToNot(HaveOccurred())
Expect(result.Data).To(Equal("testData"))
Expect(result.DomainId).To(Equal(123))
Expect(result.Expire).To(Equal(99999))
Expect(result.Host).To(Equal("testHost.com"))
Expect(result.Id).To(Equal(111))
Expect(result.Minimum).To(Equal(1))
Expect(result.MxPriority).To(Equal(9))
Expect(result.Refresh).To(Equal(100))
Expect(result.ResponsiblePerson).To(Equal("someTestPerson"))
Expect(result.Retry).To(Equal(444))
Expect(result.Ttl).To(Equal(222))
Expect(result.Type).To(Equal("someTestType"))
})
It("fails to create a resource record without mandatory parameters", func() {
fakeClient.DoRawHttpRequestResponse = []byte("fake")
template := datatypes.SoftLayer_Dns_Domain_ResourceRecord_Template{
Data: "testData",
}
_, err := dnsDomainResourceRecordService.CreateObject(template)
Expect(err).To(HaveOccurred())
})
})
Context("#GetObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Dns_Domain_ResourceRecord_Service_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Dns_Domain_Record instance", func() {
result, err := dnsDomainResourceRecordService.GetObject(111)
Expect(err).ToNot(HaveOccurred())
Expect(result.Data).To(Equal("testData"))
Expect(result.DomainId).To(Equal(123))
Expect(result.Expire).To(Equal(99999))
Expect(result.Host).To(Equal("testHost.com"))
Expect(result.Id).To(Equal(111))
Expect(result.Minimum).To(Equal(1))
Expect(result.MxPriority).To(Equal(9))
Expect(result.Refresh).To(Equal(100))
Expect(result.ResponsiblePerson).To(Equal("someTestPerson"))
Expect(result.Retry).To(Equal(444))
Expect(result.Ttl).To(Equal(222))
Expect(result.Type).To(Equal("someTestType"))
})
})
Context("#EditObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Dns_Domain_ResourceRecord_Service_editObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("applies changes to the existing SoftLayer_Dns_Domain_Record instance", func() {
result, err := dnsDomainResourceRecordService.GetObject(112)
Expect(err).ToNot(HaveOccurred())
Expect(result.Data).To(Equal("changedData"))
Expect(result.DomainId).To(Equal(124))
Expect(result.Expire).To(Equal(99998))
Expect(result.Host).To(Equal("changedHost.com"))
Expect(result.Id).To(Equal(112))
Expect(result.Minimum).To(Equal(2))
Expect(result.MxPriority).To(Equal(8))
Expect(result.Refresh).To(Equal(101))
Expect(result.ResponsiblePerson).To(Equal("changedTestPerson"))
Expect(result.Retry).To(Equal(445))
Expect(result.Ttl).To(Equal(223))
Expect(result.Type).To(Equal("changedTestType"))
})
})
})

View File

@ -1,63 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Dns_Domain", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
dnsDomainService softlayer.SoftLayer_Dns_Domain_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).NotTo(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).NotTo(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).NotTo(BeNil())
dnsDomainService, err = fakeClient.GetSoftLayer_Dns_Domain_Service()
Expect(err).ToNot(HaveOccurred())
Expect(dnsDomainService).NotTo(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := dnsDomainService.GetName()
Expect(name).To(Equal("SoftLayer_Dns_Domain"))
})
})
Context("#CreateDns", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Dns_Domain_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an instance of datatypes.SoftLayer_Dns_Domain", func() {
dns, err := dnsDomainService.CreateObject(datatypes.SoftLayer_Dns_Domain_Template{})
Expect(err).ToNot(HaveOccurred())
Expect(dns).NotTo(BeNil())
Expect(dns.Id).NotTo(BeNil())
Expect(dns.Serial).NotTo(BeNil())
Expect(dns.UpdateDate).NotTo(BeNil())
Expect(dns.Name).To(Equal("qwerty123ff.com"))
})
})
})

View File

@ -3,8 +3,10 @@ package services
import (
"bytes"
"encoding/json"
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -35,12 +37,17 @@ func (slhs *softLayer_Hardware_Service) CreateObject(template datatypes.SoftLaye
return datatypes.SoftLayer_Hardware{}, err
}
response, err := slhs.client.DoRawHttpRequest(fmt.Sprintf("%s.json", slhs.GetName()), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slhs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s.json", slhs.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Hardware{}, err
}
err = slhs.client.CheckForHttpResponseErrors(response)
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Hardware#createObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Hardware{}, errors.New(errorMessage)
}
err = slhs.client.GetHttpClient().CheckForHttpResponseErrors(response)
if err != nil {
return datatypes.SoftLayer_Hardware{}, err
}
@ -69,12 +76,17 @@ func (slhs *softLayer_Hardware_Service) GetObject(id string) (datatypes.SoftLaye
"operatingSystem.passwords.username",
}
response, err := slhs.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%s.json", slhs.GetName(), id), objectMask, "GET", new(bytes.Buffer))
response, errorCode, err := slhs.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%s.json", slhs.GetName(), id), objectMask, "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Hardware{}, err
}
err = slhs.client.CheckForHttpResponseErrors(response)
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Hardware#getObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Hardware{}, errors.New(errorMessage)
}
err = slhs.client.GetHttpClient().CheckForHttpResponseErrors(response)
if err != nil {
return datatypes.SoftLayer_Hardware{}, err
}

View File

@ -1,92 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Hardware", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
hardwareService softlayer.SoftLayer_Hardware_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
hardwareService, err = fakeClient.GetSoftLayer_Hardware_Service()
Expect(err).ToNot(HaveOccurred())
Expect(hardwareService).ToNot(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := hardwareService.GetName()
Expect(name).To(Equal("SoftLayer_Hardware"))
})
})
Context("#CreateObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Hardware_Service_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("creates a new SoftLayer_Virtual_Guest instance", func() {
template := datatypes.SoftLayer_Hardware_Template{
Hostname: "softlayer",
Domain: "testing.com",
ProcessorCoreAmount: 2,
MemoryCapacity: 2,
HourlyBillingFlag: true,
OperatingSystemReferenceCode: "UBUNTU_LATEST",
Datacenter: &datatypes.Datacenter{
Name: "ams01",
},
}
hardware, err := hardwareService.CreateObject(template)
Expect(err).ToNot(HaveOccurred())
Expect(hardware.Id).To(Equal(123))
Expect(hardware.Hostname).To(Equal("softlayer"))
Expect(hardware.Domain).To(Equal("testing.com"))
Expect(hardware.BareMetalInstanceFlag).To(Equal(1))
Expect(hardware.GlobalIdentifier).To(Equal("abcdefg"))
})
})
Context("#GetObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Hardware_Service_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Virtual_Guest instance", func() {
hardware, err := hardwareService.GetObject("abcdefg")
Expect(err).ToNot(HaveOccurred())
Expect(hardware.Id).To(Equal(123))
Expect(hardware.Hostname).To(Equal("softlayer"))
Expect(hardware.Domain).To(Equal("testing.com"))
Expect(hardware.BareMetalInstanceFlag).To(Equal(1))
Expect(hardware.GlobalIdentifier).To(Equal("abcdefg"))
})
})
})

View File

@ -5,10 +5,10 @@ import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"time"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -95,72 +95,50 @@ func (slns *softLayer_Network_Storage_Service) CreateIscsiVolume(size int, locat
}
func (slvgs *softLayer_Network_Storage_Service) DeleteObject(volumeId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slvgs.GetName(), volumeId), "DELETE", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slvgs.GetName(), volumeId), "DELETE", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to delete volume with id '%d', got '%s' as response from the API.", volumeId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Network_Storage#deleteObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slns *softLayer_Network_Storage_Service) DeleteIscsiVolume(volumeId int, immediateCancellationFlag bool) error {
ObjectFilter := string(`{"iscsiNetworkStorage":{"id":{"operation":` + strconv.Itoa(volumeId) + `}}}`)
accountService, err := slns.client.GetSoftLayer_Account_Service()
billingItem, err := slns.GetBillingItem(volumeId)
if err != nil {
return err
}
iscsiStorages, err := accountService.GetIscsiNetworkStorageWithFilter(ObjectFilter)
if err != nil {
return err
}
if billingItem.Id > 0 {
billingItemService, err := slns.client.GetSoftLayer_Billing_Item_Service()
if err != nil {
return err
}
var accountId, billingItemId int
deleted, err := billingItemService.CancelService(billingItem.Id)
if err != nil {
return err
}
for i := 0; i < len(iscsiStorages); i++ {
if iscsiStorages[i].Id == volumeId {
accountId = iscsiStorages[i].AccountId
if reflect.ValueOf(iscsiStorages[i].BillingItem).IsNil() {
deleted, err := slns.DeleteObject(volumeId)
if err != nil {
return err
}
if deleted {
return nil
} else {
return errors.New(fmt.Sprintf("Cannot delete volume %d from client at present", volumeId))
}
} else {
billingItemId = iscsiStorages[i].BillingItem.Id
break
}
if deleted {
return nil
}
}
billingItemCancellationRequest := datatypes.SoftLayer_Billing_Item_Cancellation_Request{
ComplexType: "SoftLayer_Billing_Item_Cancellation_Request",
AccountId: accountId,
Items: []datatypes.SoftLayer_Billing_Item_Cancellation_Request_Item{
{
BillingItemId: billingItemId,
ImmediateCancellationFlag: immediateCancellationFlag,
},
},
}
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Network_Storage_Service#deleteIscsiVolume with id: '%d'", volumeId)
billingItemCancellationRequestService, err := slns.client.GetSoftLayer_Billing_Item_Cancellation_Request_Service()
if err != nil {
return err
}
_, err = billingItemCancellationRequestService.CreateObject(billingItemCancellationRequest)
if err != nil {
return err
}
return nil
return errors.New(errorMessage)
}
func (slns *softLayer_Network_Storage_Service) GetIscsiVolume(volumeId int) (datatypes.SoftLayer_Network_Storage, error) {
@ -184,12 +162,17 @@ func (slns *softLayer_Network_Storage_Service) GetIscsiVolume(volumeId int) (dat
"serviceResourceBackendIpAddress",
}
response, err := slns.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", slns.GetName(), volumeId), objectMask, "GET", new(bytes.Buffer))
response, errorCode, err := slns.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", slns.GetName(), volumeId), objectMask, "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Network_Storage{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getAccountStatus, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Network_Storage{}, errors.New(errorMessage)
}
volume := datatypes.SoftLayer_Network_Storage{}
err = json.Unmarshal(response, &volume)
if err != nil {
@ -199,14 +182,40 @@ func (slns *softLayer_Network_Storage_Service) GetIscsiVolume(volumeId int) (dat
return volume, nil
}
func (slns *softLayer_Network_Storage_Service) GetBillingItem(volumeId int) (datatypes.SoftLayer_Billing_Item, error) {
response, errorCode, err := slns.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getBillingItem.json", slns.GetName(), volumeId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Billing_Item{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_NetWork_Storage#getBillingItem, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Billing_Item{}, errors.New(errorMessage)
}
billingItem := datatypes.SoftLayer_Billing_Item{}
err = json.Unmarshal(response, &billingItem)
if err != nil {
return datatypes.SoftLayer_Billing_Item{}, err
}
return billingItem, nil
}
func (slns *softLayer_Network_Storage_Service) HasAllowedVirtualGuest(volumeId int, vmId int) (bool, error) {
filter := string(`{"allowedVirtualGuests":{"id":{"operation":"` + strconv.Itoa(vmId) + `"}}}`)
response, err := slns.client.DoRawHttpRequestWithObjectFilterAndObjectMask(fmt.Sprintf("%s/%d/getAllowedVirtualGuests.json", slns.GetName(), volumeId), []string{"id"}, fmt.Sprintf(string(filter)), "GET", new(bytes.Buffer))
response, errorCode, err := slns.client.GetHttpClient().DoRawHttpRequestWithObjectFilterAndObjectMask(fmt.Sprintf("%s/%d/getAllowedVirtualGuests.json", slns.GetName(), volumeId), []string{"id"}, fmt.Sprintf(string(filter)), "GET", new(bytes.Buffer))
if err != nil {
return false, errors.New(fmt.Sprintf("Cannot check authentication for volume %d in vm %d", volumeId, vmId))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Network_Storage#hasAllowedVirtualGuest, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
virtualGuest := []datatypes.SoftLayer_Virtual_Guest{}
err = json.Unmarshal(response, &virtualGuest)
if err != nil {
@ -231,7 +240,16 @@ func (slns *softLayer_Network_Storage_Service) AttachIscsiVolume(virtualGuest da
return false, err
}
resp, err := slns.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/allowAccessFromVirtualGuest.json", slns.GetName(), volumeId), "PUT", bytes.NewBuffer(requestBody))
resp, errorCode, err := slns.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/allowAccessFromVirtualGuest.json", slns.GetName(), volumeId), "PUT", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Network_Storage#attachIscsiVolume, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
allowable, err := strconv.ParseBool(string(resp[:]))
if err != nil {
@ -252,11 +270,16 @@ func (slns *softLayer_Network_Storage_Service) DetachIscsiVolume(virtualGuest da
return err
}
_, err = slns.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/removeAccessFromVirtualGuest.json", slns.GetName(), volumeId), "PUT", bytes.NewBuffer(requestBody))
_, errorCode, err := slns.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/removeAccessFromVirtualGuest.json", slns.GetName(), volumeId), "PUT", bytes.NewBuffer(requestBody))
if err != nil {
return err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getAccountStatus, HTTP error code: '%d'", errorCode)
return errors.New(errorMessage)
}
return nil
}

View File

@ -3,8 +3,10 @@ package services
import (
"bytes"
"encoding/json"
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -24,12 +26,16 @@ func (slns *softLayer_Network_Storage_Allowed_Host_Service) GetName() string {
}
func (slns *softLayer_Network_Storage_Allowed_Host_Service) GetCredential(allowedHostId int) (datatypes.SoftLayer_Network_Storage_Credential, error) {
response, err := slns.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getCredential.json", slns.GetName(), allowedHostId), "GET", new(bytes.Buffer))
response, errorCode, err := slns.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getCredential.json", slns.GetName(), allowedHostId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Network_Storage_Credential{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Network_Storage_Allowed_Host#getCredential, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Network_Storage_Credential{}, errors.New(errorMessage)
}
credential := datatypes.SoftLayer_Network_Storage_Credential{}
err = json.Unmarshal(response, &credential)
if err != nil {

View File

@ -1,60 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Network_Storage_Allowed_Host", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
networkStorageAllowedHostService softlayer.SoftLayer_Network_Storage_Allowed_Host_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
networkStorageAllowedHostService, err = fakeClient.GetSoftLayer_Network_Storage_Allowed_Host_Service()
Expect(err).ToNot(HaveOccurred())
Expect(networkStorageAllowedHostService).ToNot(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := networkStorageAllowedHostService.GetName()
Expect(name).To(Equal("SoftLayer_Network_Storage_Allowed_Host"))
})
})
Context("#GetCredential", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Network_Storage_Allowed_Host_Service_getCredential.json")
Expect(err).ToNot(HaveOccurred())
})
It("return the credential with allowed host id", func() {
credential, err := networkStorageAllowedHostService.GetCredential(123456)
Expect(err).NotTo(HaveOccurred())
Expect(credential).ToNot(BeNil())
Expect(credential.Username).To(Equal("fake-username"))
Expect(credential.Password).To(Equal("fake-password"))
})
})
})

View File

@ -1,159 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Network_Storage", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
volume datatypes.SoftLayer_Network_Storage
networkStorageService softlayer.SoftLayer_Network_Storage_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
networkStorageService, err = fakeClient.GetSoftLayer_Network_Storage_Service()
Expect(err).ToNot(HaveOccurred())
Expect(networkStorageService).ToNot(BeNil())
volume = datatypes.SoftLayer_Network_Storage{}
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := networkStorageService.GetName()
Expect(name).To(Equal("SoftLayer_Network_Storage"))
})
})
Context("#CreateIscsiVolume", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Network_Storage_Service_getIscsiVolume.json")
Expect(err).ToNot(HaveOccurred())
})
It("fails with error if the volume size is negative", func() {
volume, err = networkStorageService.CreateIscsiVolume(-1, "fake-location")
Expect(err).To(HaveOccurred())
})
})
Context("#GetIscsiVolume", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Network_Storage_Service_getIscsiVolume.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns the iSCSI volume object based on volume id", func() {
volume, err = networkStorageService.GetIscsiVolume(1)
Expect(err).ToNot(HaveOccurred())
Expect(volume.Id).To(Equal(1))
Expect(volume.Username).To(Equal("test_username"))
Expect(volume.Password).To(Equal("test_password"))
Expect(volume.CapacityGb).To(Equal(20))
Expect(volume.ServiceResourceBackendIpAddress).To(Equal("1.1.1.1"))
})
})
Context("#HasAllowedVirtualGuest", func() {
It("virtual guest allows to access volume", func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Network_Storage_Service_getAllowedVirtualGuests.json")
Expect(err).ToNot(HaveOccurred())
_, err := networkStorageService.HasAllowedVirtualGuest(123, 456)
Expect(err).ToNot(HaveOccurred())
})
})
Context("#AttachIscsiVolume", func() {
It("Allow access to storage from virutal guest", func() {
virtualGuest := datatypes.SoftLayer_Virtual_Guest{
AccountId: 123456,
DedicatedAccountHostOnlyFlag: false,
Domain: "softlayer.com",
FullyQualifiedDomainName: "fake.softlayer.com",
Hostname: "fake-hostname",
Id: 1234567,
MaxCpu: 2,
MaxCpuUnits: "CORE",
MaxMemory: 1024,
StartCpus: 2,
StatusId: 1001,
Uuid: "fake-uuid",
GlobalIdentifier: "fake-globalIdentifier",
PrimaryBackendIpAddress: "fake-primary-backend-ip",
PrimaryIpAddress: "fake-primary-ip",
}
fakeClient.DoRawHttpRequestResponse = []byte("true")
resp, err := networkStorageService.AttachIscsiVolume(virtualGuest, 123)
Expect(err).ToNot(HaveOccurred())
Expect(resp).To(Equal(true))
})
})
Context("#DetachIscsiVolume", func() {
It("Revoke access to storage from virtual guest", func() {
virtualGuest := datatypes.SoftLayer_Virtual_Guest{
AccountId: 123456,
DedicatedAccountHostOnlyFlag: false,
Domain: "softlayer.com",
FullyQualifiedDomainName: "fake.softlayer.com",
Hostname: "fake-hostname",
Id: 1234567,
MaxCpu: 2,
MaxCpuUnits: "CORE",
MaxMemory: 1024,
StartCpus: 2,
StatusId: 1001,
Uuid: "fake-uuid",
GlobalIdentifier: "fake-globalIdentifier",
PrimaryBackendIpAddress: "fake-primary-backend-ip",
PrimaryIpAddress: "fake-primary-ip",
}
volume.Id = 1234567
fakeClient.DoRawHttpRequestResponse = []byte("true")
err = networkStorageService.DetachIscsiVolume(virtualGuest, volume.Id)
Expect(err).ToNot(HaveOccurred())
})
})
Context("#DeleteObject", func() {
BeforeEach(func() {
volume.Id = 1234567
})
It("sucessfully deletes the SoftLayer_Network_Storage volume", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
deleted, err := networkStorageService.DeleteObject(volume.Id)
Expect(err).ToNot(HaveOccurred())
Expect(deleted).To(BeTrue())
})
It("fails to delete the SoftLayer_Network_Storage volume", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
deleted, err := networkStorageService.DeleteObject(volume.Id)
Expect(err).To(HaveOccurred())
Expect(deleted).To(BeFalse())
})
})
})

View File

@ -3,8 +3,10 @@ package services
import (
"bytes"
"encoding/json"
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -35,11 +37,16 @@ func (slpo *softLayer_Product_Order_Service) PlaceOrder(order datatypes.SoftLaye
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, err
}
responseBytes, err := slpo.client.DoRawHttpRequest(fmt.Sprintf("%s/placeOrder.json", slpo.GetName()), "POST", bytes.NewBuffer(requestBody))
responseBytes, errorCode, err := slpo.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/placeOrder.json", slpo.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Account#getAccountStatus, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, errors.New(errorMessage)
}
receipt := datatypes.SoftLayer_Container_Product_Order_Receipt{}
err = json.Unmarshal(responseBytes, &receipt)
if err != nil {
@ -61,11 +68,16 @@ func (slpo *softLayer_Product_Order_Service) PlaceContainerOrderNetworkPerforman
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, err
}
responseBytes, err := slpo.client.DoRawHttpRequest(fmt.Sprintf("%s/placeOrder.json", slpo.GetName()), "POST", bytes.NewBuffer(requestBody))
responseBytes, errorCode, err := slpo.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/placeOrder.json", slpo.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Product_Order#placeContainerOrderNetworkPerformanceStorageIscsi, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, errors.New(errorMessage)
}
receipt := datatypes.SoftLayer_Container_Product_Order_Receipt{}
err = json.Unmarshal(responseBytes, &receipt)
if err != nil {
@ -87,11 +99,16 @@ func (slpo *softLayer_Product_Order_Service) PlaceContainerOrderVirtualGuestUpgr
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, err
}
responseBytes, err := slpo.client.DoRawHttpRequest(fmt.Sprintf("%s/placeOrder.json", slpo.GetName()), "POST", bytes.NewBuffer(requestBody))
responseBytes, errorCode, err := slpo.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/placeOrder.json", slpo.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Product_Order#placeOrder, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Container_Product_Order_Receipt{}, errors.New(errorMessage)
}
receipt := datatypes.SoftLayer_Container_Product_Order_Receipt{}
err = json.Unmarshal(responseBytes, &receipt)
if err != nil {

View File

@ -1,88 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Product_Order", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
productOrderService softlayer.SoftLayer_Product_Order_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
productOrderService, err = fakeClient.GetSoftLayer_Product_Order_Service()
Expect(err).ToNot(HaveOccurred())
Expect(productOrderService).ToNot(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := productOrderService.GetName()
Expect(name).To(Equal("SoftLayer_Product_Order"))
})
})
Context("#PlaceOrder", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Order_placeOrder.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an instance of datatypes.SoftLayer_Container_Product_Order_Receipt", func() {
receipt, err := productOrderService.PlaceOrder(datatypes.SoftLayer_Container_Product_Order{})
Expect(err).ToNot(HaveOccurred())
Expect(receipt).ToNot(BeNil())
Expect(receipt.OrderId).To(Equal(123))
})
})
Context("#PlaceContainerOrderNetworkPerformanceStorageIscsi", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Order_placeOrder.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an instance of datatypes.SoftLayer_Container_Product_Order_Receipt", func() {
receipt, err := productOrderService.PlaceContainerOrderNetworkPerformanceStorageIscsi(datatypes.SoftLayer_Container_Product_Order_Network_PerformanceStorage_Iscsi{})
Expect(err).ToNot(HaveOccurred())
Expect(receipt).ToNot(BeNil())
Expect(receipt.OrderId).To(Equal(123))
})
})
Context("#PlaceContainerOrderVirtualGuestUpgrade", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Order_placeOrder.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an instance of datatypes.SoftLayer_Container_Product_Order_Receipt", func() {
receipt, err := productOrderService.PlaceContainerOrderVirtualGuestUpgrade(datatypes.SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade{})
Expect(err).ToNot(HaveOccurred())
Expect(receipt).ToNot(BeNil())
Expect(receipt.OrderId).To(Equal(123))
})
})
})

View File

@ -8,6 +8,7 @@ import (
"strconv"
"strings"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -31,11 +32,16 @@ func (slpp *softLayer_Product_Package_Service) GetName() string {
}
func (slpp *softLayer_Product_Package_Service) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {
response, err := slpp.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getItemPrices.json", slpp.GetName(), packageId), []string{"id", "item.id", "item.description", "item.capacity"}, "GET", new(bytes.Buffer))
response, errorCode, err := slpp.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getItemPrices.json", slpp.GetName(), packageId), []string{"id", "item.id", "item.description", "item.capacity"}, "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Product_Item_Price{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Product_Package#getItemPrices, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Product_Item_Price{}, errors.New(errorMessage)
}
itemPrices := []datatypes.SoftLayer_Product_Item_Price{}
err = json.Unmarshal(response, &itemPrices)
if err != nil {
@ -49,11 +55,16 @@ func (slpp *softLayer_Product_Package_Service) GetItemPricesBySize(packageId int
keyName := strconv.Itoa(size) + "_GB_PERFORMANCE_STORAGE_SPACE"
filter := string(`{"itemPrices":{"item":{"keyName":{"operation":"` + keyName + `"}}}}`)
response, err := slpp.client.DoRawHttpRequestWithObjectFilterAndObjectMask(fmt.Sprintf("%s/%d/getItemPrices.json", slpp.GetName(), packageId), []string{"id", "locationGroupId", "item.id", "item.keyName", "item.units", "item.description", "item.capacity"}, fmt.Sprintf(string(filter)), "GET", new(bytes.Buffer))
response, errorCode, err := slpp.client.GetHttpClient().DoRawHttpRequestWithObjectFilterAndObjectMask(fmt.Sprintf("%s/%d/getItemPrices.json", slpp.GetName(), packageId), []string{"id", "locationGroupId", "item.id", "item.keyName", "item.units", "item.description", "item.capacity"}, fmt.Sprintf(string(filter)), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Product_Item_Price{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Product_Package#getItemsPricesBySize, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Product_Item_Price{}, errors.New(errorMessage)
}
itemPrices := []datatypes.SoftLayer_Product_Item_Price{}
err = json.Unmarshal(response, &itemPrices)
if err != nil {
@ -82,11 +93,16 @@ func (slpp *softLayer_Product_Package_Service) GetItems(packageId int) ([]dataty
"prices.categories.name",
}
response, err := slpp.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getItems.json", slpp.GetName(), packageId), objectMasks, "GET", new(bytes.Buffer))
response, errorCode, err := slpp.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getItems.json", slpp.GetName(), packageId), objectMasks, "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Product_Item{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Product_Package#getItems, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Product_Item{}, errors.New(errorMessage)
}
productItems := []datatypes.SoftLayer_Product_Item{}
err = json.Unmarshal(response, &productItems)
if err != nil {
@ -120,11 +136,16 @@ func (slpp *softLayer_Product_Package_Service) GetPackagesByType(packageType str
filterObject := string(`{"type":{"keyName":{"operation":"` + packageType + `"}}}`)
response, err := slpp.client.DoRawHttpRequestWithObjectFilterAndObjectMask(fmt.Sprintf("%s/getAllObjects.json", slpp.GetName()), objectMasks, filterObject, "GET", new(bytes.Buffer))
response, errorCode, err := slpp.client.GetHttpClient().DoRawHttpRequestWithObjectFilterAndObjectMask(fmt.Sprintf("%s/getAllObjects.json", slpp.GetName()), objectMasks, filterObject, "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.Softlayer_Product_Package{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Product_Package#getPackagesByType, HTTP error code: '%d'", errorCode)
return []datatypes.Softlayer_Product_Package{}, errors.New(errorMessage)
}
productPackages := []*datatypes.Softlayer_Product_Package{}
err = json.Unmarshal(response, &productPackages)
if err != nil {

View File

@ -1,161 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Product_Package", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
productPackageService softlayer.SoftLayer_Product_Package_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
productPackageService, err = fakeClient.GetSoftLayer_Product_Package_Service()
Expect(err).ToNot(HaveOccurred())
Expect(productPackageService).ToNot(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := productPackageService.GetName()
Expect(name).To(Equal("SoftLayer_Product_Package"))
})
})
Context("#GetItemPrices", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getItemPrices.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Product_Item_Price", func() {
itemPrices, err := productPackageService.GetItemPrices(0)
Expect(err).ToNot(HaveOccurred())
Expect(len(itemPrices)).To(Equal(1))
Expect(itemPrices[0].Id).To(Equal(123))
Expect(itemPrices[0].Item.Id).To(Equal(456))
})
})
Context("#GetItemPricesBySize", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getItemPrices.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Product_Item_Price", func() {
itemPrices, err := productPackageService.GetItemPricesBySize(222, 20)
Expect(err).ToNot(HaveOccurred())
Expect(len(itemPrices)).To(Equal(1))
Expect(itemPrices[0].Id).To(Equal(123))
Expect(itemPrices[0].Item.Id).To(Equal(456))
})
})
Context("#GetItems", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getItems.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Product_Item", func() {
productItems, err := productPackageService.GetItems(222)
Expect(err).ToNot(HaveOccurred())
Expect(len(productItems)).To(Equal(2))
Expect(productItems[0].Id).To(Equal(123))
Expect(productItems[0].Prices[0].Id).To(Equal(456))
})
})
Context("#GetItemsByType", func() {
BeforeEach(func() {
response, err := testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getAllObjects_virtual_server.json")
fakeClient.DoRawHttpRequestResponses = append(fakeClient.DoRawHttpRequestResponses, response)
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.SoftLayer_Product_Item", func() {
response, err := testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getItems.json")
fakeClient.DoRawHttpRequestResponses = append(fakeClient.DoRawHttpRequestResponses, response)
productItems, err := productPackageService.GetItemsByType("VIRTUAL_SERVER_INSTANCE")
Expect(err).ToNot(HaveOccurred())
Expect(len(productItems)).To(Equal(2))
Expect(productItems[0].Id).To(Equal(123))
Expect(productItems[0].Prices[0].Id).To(Equal(456))
})
})
Context("#GetPackagesByType", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getAllObjects_virtual_server.json")
Expect(err).ToNot(HaveOccurred())
})
It("returns an array of datatypes.Softlayer_Product_Package", func() {
productPackages, err := productPackageService.GetPackagesByType("VIRTUAL_SERVER_INSTANCE")
Expect(err).ToNot(HaveOccurred())
Expect(len(productPackages)).To(Equal(4))
Expect(productPackages[0].Id).To(Equal(200))
Expect(productPackages[0].Name).To(Equal("Cloud Server 1"))
})
It("skips packaged marked OUTLET", func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getAllObjects_virtual_server_with_OUTLET.json")
productPackages, err := productPackageService.GetPackagesByType("VIRTUAL_SERVER_INSTANCE")
Expect(err).ToNot(HaveOccurred())
Expect(len(productPackages)).To(Equal(3)) // OUTLET should be skipped
Expect(productPackages[0].Id).To(Equal(202))
Expect(productPackages[0].Name).To(Equal("Cloud Server 2"))
})
})
Context("#GetOnePackageByType", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getAllObjects_virtual_server.json")
Expect(err).ToNot(HaveOccurred())
})
It("reports error when NO product packages are found", func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getAllObjects_virtual_server_empty.json")
GinkgoWriter.Write(fakeClient.DoRawHttpRequestResponse)
_, err := productPackageService.GetOnePackageByType("SOME_TYPE")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("No packages available for type 'SOME_TYPE'."))
})
It("returns datatypes.Softlayer_Product_Package", func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getAllObjects_virtual_server.json")
productPackage, err := productPackageService.GetOnePackageByType("VIRTUAL_SERVER_INSTANCE")
Expect(err).ToNot(HaveOccurred())
Expect(productPackage.Id).To(Equal(200))
Expect(productPackage.Name).To(Equal("Cloud Server 1"))
})
})
})

View File

@ -6,6 +6,7 @@ import (
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -36,12 +37,17 @@ func (slssks *softLayer_Security_Ssh_Key_Service) CreateObject(template datatype
return datatypes.SoftLayer_Security_Ssh_Key{}, err
}
data, err := slssks.client.DoRawHttpRequest(fmt.Sprintf("%s/createObject", slssks.GetName()), "POST", bytes.NewBuffer(requestBody))
data, errorCode, err := slssks.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/createObject", slssks.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Security_Ssh_Key{}, err
}
err = slssks.client.CheckForHttpResponseErrors(data)
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Security_Ssh_Key#createObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Security_Ssh_Key{}, errors.New(errorMessage)
}
err = slssks.client.GetHttpClient().CheckForHttpResponseErrors(data)
if err != nil {
return datatypes.SoftLayer_Security_Ssh_Key{}, err
}
@ -66,11 +72,16 @@ func (slssks *softLayer_Security_Ssh_Key_Service) GetObject(sshKeyId int) (datat
"notes",
}
response, err := slssks.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", slssks.GetName(), sshKeyId), objectMask, "GET", new(bytes.Buffer))
response, errorCode, err := slssks.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", slssks.GetName(), sshKeyId), objectMask, "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Security_Ssh_Key{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Security_Ssh_Key#getObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Security_Ssh_Key{}, errors.New(errorMessage)
}
sshKey := datatypes.SoftLayer_Security_Ssh_Key{}
err = json.Unmarshal(response, &sshKey)
if err != nil {
@ -92,31 +103,52 @@ func (slssks *softLayer_Security_Ssh_Key_Service) EditObject(sshKeyId int, templ
return false, err
}
response, err := slssks.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/editObject.json", slssks.GetName(), sshKeyId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slssks.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/editObject.json", slssks.GetName(), sshKeyId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to edit SSH key with id: %d, got '%s' as response from the API.", sshKeyId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Security_Ssh_Key#editObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slssks *softLayer_Security_Ssh_Key_Service) DeleteObject(sshKeyId int) (bool, error) {
response, err := slssks.client.DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slssks.GetName(), sshKeyId), "DELETE", new(bytes.Buffer))
response, errorCode, err := slssks.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slssks.GetName(), sshKeyId), "DELETE", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to destroy ssh key with id '%d', got '%s' as response from the API.", sshKeyId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Security_Ssh_Key#deleteObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slssks *softLayer_Security_Ssh_Key_Service) GetSoftwarePasswords(sshKeyId int) ([]datatypes.SoftLayer_Software_Component_Password, error) {
response, err := slssks.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getSoftwarePasswords.json", slssks.GetName(), sshKeyId), "GET", new(bytes.Buffer))
response, errorCode, err := slssks.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getSoftwarePasswords.json", slssks.GetName(), sshKeyId), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Software_Component_Password{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Security_Ssh_Key#getSoftwarePasswords, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Software_Component_Password{}, errors.New(errorMessage)
}
passwords := []datatypes.SoftLayer_Software_Component_Password{}
err = json.Unmarshal(response, &passwords)
if err != nil {

View File

@ -1,158 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Ssh_Key_Service", func() {
var (
username, apiKey string
err error
fakeClient *slclientfakes.FakeSoftLayerClient
sshKeyService softlayer.SoftLayer_Security_Ssh_Key_Service
sshKey datatypes.SoftLayer_Security_Ssh_Key
sshKeyTemplate datatypes.SoftLayer_Security_Ssh_Key
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
sshKeyService, err = fakeClient.GetSoftLayer_Security_Ssh_Key_Service()
Expect(err).ToNot(HaveOccurred())
Expect(sshKeyService).ToNot(BeNil())
sshKey = datatypes.SoftLayer_Security_Ssh_Key{}
sshKeyTemplate = datatypes.SoftLayer_Security_Ssh_Key{}
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := sshKeyService.GetName()
Expect(name).To(Equal("SoftLayer_Security_Ssh_Key"))
})
})
Context("#CreateObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Security_Ssh_Key_Service_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("creates a new SoftLayer_Ssh_Key instance", func() {
sshKeyTemplate = datatypes.SoftLayer_Security_Ssh_Key{
Fingerprint: "fake-fingerprint",
Key: "fake-key",
Label: "fake-label",
Notes: "fake-notes",
}
sshKey, err = sshKeyService.CreateObject(sshKeyTemplate)
Expect(err).ToNot(HaveOccurred())
Expect(sshKey.Fingerprint).To(Equal("fake-fingerprint"))
Expect(sshKey.Key).To(Equal("fake-key"))
Expect(sshKey.Label).To(Equal("fake-label"))
Expect(sshKey.Notes).To(Equal("fake-notes"))
})
})
Context("#GetObject", func() {
BeforeEach(func() {
sshKey.Id = 1337
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Security_Ssh_Key_Service_getObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("gets an SSH key", func() {
key, err := sshKeyService.GetObject(sshKey.Id)
Expect(err).ToNot(HaveOccurred())
Expect(key.Id).To(Equal(1337))
Expect(key.Fingerprint).To(Equal("e9:56:6d:b1:f3:8b:f1:2a:dd:a3:24:73:4f:d3:1b:3c"))
Expect(key.Key).To(Equal("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAA/DczU7Wj4hgAgy14LfjOvVKtDBOfwFgHFwsXQ7Efp0pQRBOIwWoQfQ3hHMWw1X5Q7Mhwl9Gbat9V7tu985Hf5h9BOrq9D/ZIFQ1yhsvt6klZYoHHbM5kHFUegx9lgn3mHcfLNcvahDHpQAFXCPknc1VNpn0VP0RPhqZ8pubP7r9/Uczmit1ipy43SGzlxM46cyyqNPgDDRJepDla6coJJGuWVZMZaTXc3fNNFTSIi1ODDQgXxaYWcz5ThcQ1CT/MLSzAz7IDNNjAr5W40ZUmxxHzA5nPmLcKKqqXrxbnCyw+SrVjhIsKSoz41caYdSz2Bpw00ZxzVO9dCnHsEw=="))
Expect(key.Label).To(Equal("packer-53ead4c1-df11-9023-1173-eef40a291b7e"))
Expect(key.Notes).To(Equal("My test key"))
})
})
Context("#EditObject", func() {
BeforeEach(func() {
sshKey.Id = 1338
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Security_Ssh_Key_Service_editObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("edits an existing SSH key", func() {
edited := datatypes.SoftLayer_Security_Ssh_Key{
Label: "edited-label",
}
result, err := sshKeyService.EditObject(sshKey.Id, edited)
Expect(err).ToNot(HaveOccurred())
Expect(result).To(BeTrue())
})
})
Context("#DeleteObject", func() {
BeforeEach(func() {
sshKey.Id = 1234567
})
It("sucessfully deletes the SoftLayer_Ssh_Key instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
deleted, err := sshKeyService.DeleteObject(sshKey.Id)
Expect(err).ToNot(HaveOccurred())
Expect(deleted).To(BeTrue())
})
It("fails to delete the SoftLayer_Ssh_Key instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
deleted, err := sshKeyService.DeleteObject(sshKey.Id)
Expect(err).To(HaveOccurred())
Expect(deleted).To(BeFalse())
})
})
Context("#GetSoftwarePasswords", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Security_Ssh_Key_Service_getSoftwarePasswords.json")
Expect(err).ToNot(HaveOccurred())
sshKey.Id = 1234567
})
It("retrieves the software passwords associated with this virtual guest", func() {
passwords, err := sshKeyService.GetSoftwarePasswords(sshKey.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(passwords)).To(Equal(1))
password := passwords[0]
Expect(password.CreateDate).ToNot(BeNil())
Expect(password.Id).To(Equal(4244148))
Expect(password.ModifyDate).ToNot(BeNil())
Expect(password.Notes).To(Equal(""))
Expect(password.Password).To(Equal("QJ95Gznz"))
Expect(password.Port).To(Equal(0))
Expect(password.SoftwareId).To(Equal(4181746))
Expect(password.Username).To(Equal("root"))
Expect(password.Software.HardwareId).To(Equal(0))
Expect(password.Software.Id).To(Equal(4181746))
Expect(password.Software.ManufacturerLicenseInstance).To(Equal(""))
})
})
})

View File

@ -3,8 +3,10 @@ package services
import (
"bytes"
"encoding/json"
"errors"
"fmt"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -24,11 +26,16 @@ func (slvdi *softLayer_Virtual_Disk_Image_Service) GetName() string {
}
func (slvdi *softLayer_Virtual_Disk_Image_Service) GetObject(vdImageId int) (datatypes.SoftLayer_Virtual_Disk_Image, error) {
response, err := slvdi.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getObject.json", slvdi.GetName(), vdImageId), "GET", new(bytes.Buffer))
response, errorCode, err := slvdi.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getObject.json", slvdi.GetName(), vdImageId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Virtual_Disk_Image{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Disk_Image#getObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Virtual_Disk_Image{}, errors.New(errorMessage)
}
vdImage := datatypes.SoftLayer_Virtual_Disk_Image{}
err = json.Unmarshal(response, &vdImage)
if err != nil {

View File

@ -1,73 +0,0 @@
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Virtual_Disk_Image_Service", func() {
var (
username, apiKey string
err error
fakeClient *slclientfakes.FakeSoftLayerClient
virtualDiskImageService softlayer.SoftLayer_Virtual_Disk_Image_Service
virtualDiskImage datatypes.SoftLayer_Virtual_Disk_Image
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
virtualDiskImageService, err = fakeClient.GetSoftLayer_Virtual_Disk_Image_Service()
Expect(err).ToNot(HaveOccurred())
Expect(virtualDiskImageService).ToNot(BeNil())
virtualDiskImage = datatypes.SoftLayer_Virtual_Disk_Image{}
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := virtualDiskImageService.GetName()
Expect(name).To(Equal("SoftLayer_Virtual_Disk_Image"))
})
})
Context("#GetObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Disk_Image_Service_getObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("gets the SoftLayer_Virtual_Disk_Image instance", func() {
virtualDiskImage, err = virtualDiskImageService.GetObject(4868344)
Expect(err).ToNot(HaveOccurred())
Expect(virtualDiskImage.Capacity).To(Equal(25))
Expect(virtualDiskImage.CreateDate).ToNot(BeNil())
Expect(virtualDiskImage.Description).To(Equal("yz-fabric-node-20140407-133340-856.softlayer.com"))
Expect(virtualDiskImage.Id).To(Equal(4868344))
Expect(virtualDiskImage.ModifyDate).To(BeNil())
Expect(virtualDiskImage.Name).To(Equal("yz-fabric-node-20140407-133340-856.softlayer.com"))
Expect(virtualDiskImage.ParentId).To(Equal(0))
Expect(virtualDiskImage.StorageRepositoryId).To(Equal(1105002))
Expect(virtualDiskImage.TypeId).To(Equal(241))
Expect(virtualDiskImage.Units).To(Equal("GB"))
Expect(virtualDiskImage.Uuid).To(Equal("8c7a8358-d9a9-4e4d-9345-6f637e10ccb7"))
})
})
})

View File

@ -6,10 +6,12 @@ import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"time"
common "github.com/maximilien/softlayer-go/common"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
@ -54,12 +56,17 @@ func (slvgs *softLayer_Virtual_Guest_Service) CreateObject(template datatypes.So
return datatypes.SoftLayer_Virtual_Guest{}, err
}
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s.json", slvgs.GetName()), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s.json", slvgs.GetName()), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Virtual_Guest{}, err
}
err = slvgs.client.CheckForHttpResponseErrors(response)
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#createObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Virtual_Guest{}, errors.New(errorMessage)
}
err = slvgs.client.GetHttpClient().CheckForHttpResponseErrors(response)
if err != nil {
return datatypes.SoftLayer_Virtual_Guest{}, err
}
@ -84,11 +91,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) ReloadOperatingSystem(instanceId i
return err
}
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/reloadOperatingSystem.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/reloadOperatingSystem.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#reloadOperatingSystem, HTTP error code: '%d'", errorCode)
return errors.New(errorMessage)
}
if res := string(response[:]); res != `"1"` {
return errors.New(fmt.Sprintf("Failed to reload OS on instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
@ -143,11 +155,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetObject(instanceId int) (datatyp
"primaryBackendNetworkComponent.networkVlan.id",
}
response, err := slvgs.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", slvgs.GetName(), instanceId), objectMask, "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getObject.json", slvgs.GetName(), instanceId), objectMask, "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Virtual_Guest{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getObject, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Virtual_Guest{}, errors.New(errorMessage)
}
virtualGuest := datatypes.SoftLayer_Virtual_Guest{}
err = json.Unmarshal(response, &virtualGuest)
if err != nil {
@ -157,6 +174,48 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetObject(instanceId int) (datatyp
return virtualGuest, nil
}
func (slvgs *softLayer_Virtual_Guest_Service) GetObjectByPrimaryIpAddress(ipAddress string) (datatypes.SoftLayer_Virtual_Guest, error) {
ObjectFilter := string(`{"virtualGuests":{"primaryIpAddress":{"operation":"` + ipAddress + `"}}}`)
accountService, err := slvgs.client.GetSoftLayer_Account_Service()
if err != nil {
return datatypes.SoftLayer_Virtual_Guest{}, err
}
virtualGuests, err := accountService.GetVirtualGuestsByFilter(ObjectFilter)
if err != nil {
return datatypes.SoftLayer_Virtual_Guest{}, err
}
if len(virtualGuests) == 1 {
return virtualGuests[0], nil
}
return datatypes.SoftLayer_Virtual_Guest{}, errors.New(fmt.Sprintf("Cannot find virtual guest with primary ip: %s", ipAddress))
}
func (slvgs *softLayer_Virtual_Guest_Service) GetObjectByPrimaryBackendIpAddress(ipAddress string) (datatypes.SoftLayer_Virtual_Guest, error) {
ObjectFilter := string(`{"virtualGuests":{"primaryBackendIpAddress":{"operation":` + ipAddress + `}}}`)
accountService, err := slvgs.client.GetSoftLayer_Account_Service()
if err != nil {
return datatypes.SoftLayer_Virtual_Guest{}, err
}
virtualGuests, err := accountService.GetVirtualGuestsByFilter(ObjectFilter)
if err != nil {
return datatypes.SoftLayer_Virtual_Guest{}, err
}
if len(virtualGuests) == 1 {
return virtualGuests[0], nil
}
return datatypes.SoftLayer_Virtual_Guest{}, errors.New(fmt.Sprintf("Cannot find virtual guest with primary backend ip: %s", ipAddress))
}
func (slvgs *softLayer_Virtual_Guest_Service) EditObject(instanceId int, template datatypes.SoftLayer_Virtual_Guest) (bool, error) {
parameters := datatypes.SoftLayer_Virtual_Guest_Parameters{
Parameters: []datatypes.SoftLayer_Virtual_Guest{template},
@ -167,31 +226,52 @@ func (slvgs *softLayer_Virtual_Guest_Service) EditObject(instanceId int, templat
return false, err
}
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/editObject.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/editObject.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to edit virtual guest with id: %d, got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#editObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) DeleteObject(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slvgs.GetName(), instanceId), "DELETE", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d.json", slvgs.GetName(), instanceId), "DELETE", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to delete instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#deleteObject, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) GetPowerState(instanceId int) (datatypes.SoftLayer_Virtual_Guest_Power_State, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getPowerState.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getPowerState.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Virtual_Guest_Power_State{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getPowerState, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Virtual_Guest_Power_State{}, errors.New(errorMessage)
}
vgPowerState := datatypes.SoftLayer_Virtual_Guest_Power_State{}
err = json.Unmarshal(response, &vgPowerState)
if err != nil {
@ -202,11 +282,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetPowerState(instanceId int) (dat
}
func (slvgs *softLayer_Virtual_Guest_Service) GetPrimaryIpAddress(instanceId int) (string, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getPrimaryIpAddress.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getPrimaryIpAddress.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return "", err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getPrimaryIpAddress, HTTP error code: '%d'", errorCode)
return "", errors.New(errorMessage)
}
vgPrimaryIpAddress := strings.TrimSpace(string(response))
if vgPrimaryIpAddress == "" {
return "", errors.New(fmt.Sprintf("Failed to get primary IP address for instance with id '%d', got '%s' as response from the API.", instanceId, response))
@ -216,11 +301,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetPrimaryIpAddress(instanceId int
}
func (slvgs *softLayer_Virtual_Guest_Service) GetActiveTransaction(instanceId int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getActiveTransaction.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getActiveTransaction.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getActiveTransaction, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
activeTransaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &activeTransaction)
if err != nil {
@ -234,11 +324,17 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetLastTransaction(instanceId int)
objectMask := []string{
"transactionGroup",
}
response, err := slvgs.client.DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getLastTransaction.json", slvgs.GetName(), instanceId), objectMask, "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequestWithObjectMask(fmt.Sprintf("%s/%d/getLastTransaction.json", slvgs.GetName(), instanceId), objectMask, "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getLastTransaction, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
lastTransaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &lastTransaction)
if err != nil {
@ -249,11 +345,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetLastTransaction(instanceId int)
}
func (slvgs *softLayer_Virtual_Guest_Service) GetActiveTransactions(instanceId int) ([]datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getActiveTransactions.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getActiveTransactions.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getActiveTransactions, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
activeTransactions := []datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &activeTransactions)
if err != nil {
@ -264,11 +365,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetActiveTransactions(instanceId i
}
func (slvgs *softLayer_Virtual_Guest_Service) GetSshKeys(instanceId int) ([]datatypes.SoftLayer_Security_Ssh_Key, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getSshKeys.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getSshKeys.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Security_Ssh_Key{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getSshKeys, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Security_Ssh_Key{}, errors.New(errorMessage)
}
sshKeys := []datatypes.SoftLayer_Security_Ssh_Key{}
err = json.Unmarshal(response, &sshKeys)
if err != nil {
@ -279,72 +385,128 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetSshKeys(instanceId int) ([]data
}
func (slvgs *softLayer_Virtual_Guest_Service) PowerCycle(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/powerCycle.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/powerCycle.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to power cycle instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#powerCycle, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) PowerOff(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/powerOff.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/powerOff.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to power off instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#powerOff, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) PowerOffSoft(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/powerOffSoft.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/powerOffSoft.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to power off soft instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#powerOffSoft, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) PowerOn(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/powerOn.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/powerOn.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to power on instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#powerOn, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) RebootDefault(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/rebootDefault.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/rebootDefault.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to default reboot instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#rebootDefault, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) RebootSoft(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/rebootSoft.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/rebootSoft.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to soft reboot instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#rebootSoft, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) RebootHard(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/rebootHard.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/rebootHard.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to hard reboot instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Security_Ssh_Key#rebootHard, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
@ -363,21 +525,34 @@ func (slvgs *softLayer_Virtual_Guest_Service) SetMetadata(instanceId int, metada
return false, err
}
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/setUserMetadata.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/setUserMetadata.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to setUserMetadata for instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#setUserMetadata, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
return true, err
}
func (slvgs *softLayer_Virtual_Guest_Service) ConfigureMetadataDisk(instanceId int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/configureMetadataDisk.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/configureMetadataDisk.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#setUserMetadata, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
transaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &transaction)
if err != nil {
@ -388,11 +563,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) ConfigureMetadataDisk(instanceId i
}
func (slvgs *softLayer_Virtual_Guest_Service) GetUserData(instanceId int) ([]datatypes.SoftLayer_Virtual_Guest_Attribute, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getUserData.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getUserData.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Virtual_Guest_Attribute{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getUserData, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Virtual_Guest_Attribute{}, errors.New(errorMessage)
}
attributes := []datatypes.SoftLayer_Virtual_Guest_Attribute{}
err = json.Unmarshal(response, &attributes)
if err != nil {
@ -403,11 +583,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetUserData(instanceId int) ([]dat
}
func (slvgs *softLayer_Virtual_Guest_Service) IsPingable(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/isPingable.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/isPingable.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#isPingable, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
res := string(response)
if res == "true" {
@ -422,11 +607,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) IsPingable(instanceId int) (bool,
}
func (slvgs *softLayer_Virtual_Guest_Service) IsBackendPingable(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/isBackendPingable.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/isBackendPingable.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#isBackendPingable, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
res := string(response)
if res == "true" {
@ -488,7 +678,6 @@ func (slvgs *softLayer_Virtual_Guest_Service) AttachEphemeralDisk(instanceId int
}
func (slvgs *softLayer_Virtual_Guest_Service) UpgradeObject(instanceId int, options *softlayer.UpgradeOptions) (bool, error) {
prices, err := slvgs.GetAvailableUpgradeItemPrices(options)
if err != nil {
return false, err
@ -529,7 +718,6 @@ func (slvgs *softLayer_Virtual_Guest_Service) UpgradeObject(instanceId int, opti
}
func (slvgs *softLayer_Virtual_Guest_Service) GetAvailableUpgradeItemPrices(upgradeOptions *softlayer.UpgradeOptions) ([]datatypes.SoftLayer_Product_Item_Price, error) {
itemsCapacity := make(map[string]int)
if upgradeOptions.Cpus > 0 {
itemsCapacity["cpus"] = upgradeOptions.Cpus
@ -561,11 +749,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetAvailableUpgradeItemPrices(upgr
}
func (slvgs *softLayer_Virtual_Guest_Service) GetUpgradeItemPrices(instanceId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getUpgradeItemPrices.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getUpgradeItemPrices.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Product_Item_Price{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getUpgradeItemPrices, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Product_Item_Price{}, errors.New(errorMessage)
}
itemPrices := []datatypes.SoftLayer_Product_Item_Price{}
err = json.Unmarshal(response, &itemPrices)
if err != nil {
@ -593,11 +786,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) SetTags(instanceId int, tags []str
return false, err
}
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/setTags.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/setTags.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#setTags, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
if res := string(response[:]); res != "true" {
return false, errors.New(fmt.Sprintf("Failed to setTags for instance with id '%d', got '%s' as response from the API.", instanceId, res))
}
@ -606,11 +804,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) SetTags(instanceId int, tags []str
}
func (slvgs *softLayer_Virtual_Guest_Service) GetTagReferences(instanceId int) ([]datatypes.SoftLayer_Tag_Reference, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getTagReferences.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getTagReferences.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Tag_Reference{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getTagReferences, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Tag_Reference{}, errors.New(errorMessage)
}
tagReferences := []datatypes.SoftLayer_Tag_Reference{}
err = json.Unmarshal(response, &tagReferences)
if err != nil {
@ -621,8 +824,8 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetTagReferences(instanceId int) (
}
func (slvgs *softLayer_Virtual_Guest_Service) AttachDiskImage(instanceId int, imageId int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
parameters := datatypes.SoftLayer_Virtual_GuestInitParameters{
Parameters: datatypes.SoftLayer_Virtual_GuestInitParameter{
parameters := datatypes.SoftLayer_Virtual_GuestInit_ImageId_Parameters{
Parameters: datatypes.ImageId_Parameter{
ImageId: imageId,
},
}
@ -632,11 +835,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) AttachDiskImage(instanceId int, im
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/attachDiskImage.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/attachDiskImage.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#attachDiskImage, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
transaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &transaction)
if err != nil {
@ -647,8 +855,8 @@ func (slvgs *softLayer_Virtual_Guest_Service) AttachDiskImage(instanceId int, im
}
func (slvgs *softLayer_Virtual_Guest_Service) DetachDiskImage(instanceId int, imageId int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
parameters := datatypes.SoftLayer_Virtual_GuestInitParameters{
Parameters: datatypes.SoftLayer_Virtual_GuestInitParameter{
parameters := datatypes.SoftLayer_Virtual_GuestInit_ImageId_Parameters{
Parameters: datatypes.ImageId_Parameter{
ImageId: imageId,
},
}
@ -658,11 +866,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) DetachDiskImage(instanceId int, im
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/detachDiskImage.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/detachDiskImage.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#detachDiskImage, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
transaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &transaction)
if err != nil {
@ -673,11 +886,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) DetachDiskImage(instanceId int, im
}
func (slvgs *softLayer_Virtual_Guest_Service) ActivatePrivatePort(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/activatePrivatePort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/activatePrivatePort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#activatePrivatePort, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
res := string(response)
if res == "true" {
@ -692,11 +910,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) ActivatePrivatePort(instanceId int
}
func (slvgs *softLayer_Virtual_Guest_Service) ActivatePublicPort(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/activatePublicPort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/activatePublicPort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#activatePublicPort, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
res := string(response)
if res == "true" {
@ -711,11 +934,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) ActivatePublicPort(instanceId int)
}
func (slvgs *softLayer_Virtual_Guest_Service) ShutdownPrivatePort(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/shutdownPrivatePort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/shutdownPrivatePort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#shutdownPrivatePort, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
res := string(response)
if res == "true" {
@ -730,11 +958,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) ShutdownPrivatePort(instanceId int
}
func (slvgs *softLayer_Virtual_Guest_Service) ShutdownPublicPort(instanceId int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/shutdownPublicPort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/shutdownPublicPort.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#shutdownPublicPort, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
res := string(response)
if res == "true" {
@ -749,11 +982,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) ShutdownPublicPort(instanceId int)
}
func (slvgs *softLayer_Virtual_Guest_Service) GetAllowedHost(instanceId int) (datatypes.SoftLayer_Network_Storage_Allowed_Host, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getAllowedHost.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getAllowedHost.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Network_Storage_Allowed_Host{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getAllowedHost, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Network_Storage_Allowed_Host{}, errors.New(errorMessage)
}
allowedHost := datatypes.SoftLayer_Network_Storage_Allowed_Host{}
err = json.Unmarshal(response, &allowedHost)
if err != nil {
@ -764,11 +1002,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetAllowedHost(instanceId int) (da
}
func (slvgs *softLayer_Virtual_Guest_Service) GetNetworkVlans(instanceId int) ([]datatypes.SoftLayer_Network_Vlan, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/getNetworkVlans.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/getNetworkVlans.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return []datatypes.SoftLayer_Network_Vlan{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#getNetworkVlans, HTTP error code: '%d'", errorCode)
return []datatypes.SoftLayer_Network_Vlan{}, errors.New(errorMessage)
}
networkVlans := []datatypes.SoftLayer_Network_Vlan{}
err = json.Unmarshal(response, &networkVlans)
if err != nil {
@ -779,11 +1022,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) GetNetworkVlans(instanceId int) ([
}
func (slvgs *softLayer_Virtual_Guest_Service) CheckHostDiskAvailability(instanceId int, diskCapacity int) (bool, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/checkHostDiskAvailability/%d", slvgs.GetName(), instanceId, diskCapacity), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/checkHostDiskAvailability/%d", slvgs.GetName(), instanceId, diskCapacity), "GET", new(bytes.Buffer))
if err != nil {
return false, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#checkHostDiskAvailability, HTTP error code: '%d'", errorCode)
return false, errors.New(errorMessage)
}
res := string(response)
if res == "true" {
@ -798,11 +1046,16 @@ func (slvgs *softLayer_Virtual_Guest_Service) CheckHostDiskAvailability(instance
}
func (slvgs *softLayer_Virtual_Guest_Service) CaptureImage(instanceId int) (datatypes.SoftLayer_Container_Disk_Image_Capture_Template, error) {
response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/captureImage.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/captureImage.json", slvgs.GetName(), instanceId), "GET", new(bytes.Buffer))
if err != nil {
return datatypes.SoftLayer_Container_Disk_Image_Capture_Template{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#captureImage, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Container_Disk_Image_Capture_Template{}, errors.New(errorMessage)
}
diskImageTemplate := datatypes.SoftLayer_Container_Disk_Image_Capture_Template{}
err = json.Unmarshal(response, &diskImageTemplate)
if err != nil {
@ -812,6 +1065,38 @@ func (slvgs *softLayer_Virtual_Guest_Service) CaptureImage(instanceId int) (data
return diskImageTemplate, nil
}
func (slvgs *softLayer_Virtual_Guest_Service) CreateArchiveTransaction(instanceId int, groupName string, blockDevices []datatypes.SoftLayer_Virtual_Guest_Block_Device, note string) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
groupName = url.QueryEscape(groupName)
note = url.QueryEscape(note)
parameters := datatypes.SoftLayer_Virtual_GuestInitParameters{
Parameters: []interface{}{groupName, blockDevices, note},
}
requestBody, err := json.Marshal(parameters)
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/createArchiveTransaction.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
if common.IsHttpErrorCode(errorCode) {
errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#createArchiveTransaction, HTTP error code: '%d'", errorCode)
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
}
transaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
err = json.Unmarshal(response, &transaction)
if err != nil {
return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
}
return transaction, nil
}
//Private methods
func (slvgs *softLayer_Virtual_Guest_Service) getVirtualServerItems() ([]datatypes.SoftLayer_Product_Item, error) {

View File

@ -1,982 +0,0 @@
package services_test
import (
"errors"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Virtual_Guest_Service", func() {
var (
username, apiKey string
err error
fakeClient *slclientfakes.FakeSoftLayerClient
virtualGuestService softlayer.SoftLayer_Virtual_Guest_Service
virtualGuest datatypes.SoftLayer_Virtual_Guest
virtualGuestTemplate datatypes.SoftLayer_Virtual_Guest_Template
reload_OS_Config datatypes.Image_Template_Config
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
fakeClient.SoftLayerServices["SoftLayer_Product_Package"] = &testhelpers.MockProductPackageService{}
virtualGuestService, err = fakeClient.GetSoftLayer_Virtual_Guest_Service()
Expect(err).ToNot(HaveOccurred())
Expect(virtualGuestService).ToNot(BeNil())
virtualGuest = datatypes.SoftLayer_Virtual_Guest{}
virtualGuestTemplate = datatypes.SoftLayer_Virtual_Guest_Template{}
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := virtualGuestService.GetName()
Expect(name).To(Equal("SoftLayer_Virtual_Guest"))
})
})
Context("#CreateObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_createObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("creates a new SoftLayer_Virtual_Guest instance", func() {
virtualGuestTemplate = datatypes.SoftLayer_Virtual_Guest_Template{
Hostname: "fake-hostname",
Domain: "fake.domain.com",
StartCpus: 2,
MaxMemory: 1024,
Datacenter: datatypes.Datacenter{
Name: "fake-datacenter-name",
},
HourlyBillingFlag: true,
LocalDiskFlag: false,
DedicatedAccountHostOnlyFlag: false,
NetworkComponents: []datatypes.NetworkComponents{datatypes.NetworkComponents{
MaxSpeed: 10,
}},
UserData: []datatypes.UserData{
datatypes.UserData{
Value: "some user data $_/<| with special characters",
},
},
}
virtualGuest, err = virtualGuestService.CreateObject(virtualGuestTemplate)
Expect(err).ToNot(HaveOccurred())
Expect(virtualGuest.Hostname).To(Equal("fake-hostname"))
Expect(virtualGuest.Domain).To(Equal("fake.domain.com"))
Expect(virtualGuest.StartCpus).To(Equal(2))
Expect(virtualGuest.MaxMemory).To(Equal(1024))
Expect(virtualGuest.DedicatedAccountHostOnlyFlag).To(BeFalse())
})
It("flags all missing required parameters for SoftLayer_Virtual_Guest/createObject.json POST call", func() {
virtualGuestTemplate = datatypes.SoftLayer_Virtual_Guest_Template{}
_, err := virtualGuestService.CreateObject(virtualGuestTemplate)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Hostname"))
Expect(err.Error()).To(ContainSubstring("Domain"))
Expect(err.Error()).To(ContainSubstring("StartCpus"))
Expect(err.Error()).To(ContainSubstring("MaxMemory"))
Expect(err.Error()).To(ContainSubstring("Datacenter"))
})
})
Context("#GetObject", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Virtual_Guest instance", func() {
vg, err := virtualGuestService.GetObject(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(vg.Id).To(Equal(virtualGuest.Id))
Expect(vg.AccountId).To(Equal(278444))
Expect(vg.CreateDate).ToNot(BeNil())
Expect(vg.DedicatedAccountHostOnlyFlag).To(BeFalse())
Expect(vg.Domain).To(Equal("softlayer.com"))
Expect(vg.FullyQualifiedDomainName).To(Equal("bosh-ecpi1.softlayer.com"))
Expect(vg.Hostname).To(Equal("bosh-ecpi1"))
Expect(vg.Id).To(Equal(1234567))
Expect(vg.LastPowerStateId).To(Equal(0))
Expect(vg.LastVerifiedDate).To(BeNil())
Expect(vg.MaxCpu).To(Equal(1))
Expect(vg.MaxCpuUnits).To(Equal("CORE"))
Expect(vg.MaxMemory).To(Equal(1024))
Expect(vg.MetricPollDate).To(BeNil())
Expect(vg.ModifyDate).ToNot(BeNil())
Expect(vg.StartCpus).To(Equal(1))
Expect(vg.StatusId).To(Equal(1001))
Expect(vg.Uuid).To(Equal("85d444ce-55a0-39c0-e17a-f697f223cd8a"))
Expect(vg.GlobalIdentifier).To(Equal("52145e01-97b6-4312-9c15-dac7f24b6c2a"))
Expect(vg.UserData[0].Value).To(Equal("some user data $_/<| with special characters"))
Expect(vg.PrimaryBackendIpAddress).To(Equal("10.106.192.42"))
Expect(vg.PrimaryIpAddress).To(Equal("23.246.234.32"))
Expect(vg.Location.Id).To(Equal(1234567))
Expect(vg.Location.Name).To(Equal("R5"))
Expect(vg.Location.LongName).To(Equal("Room 5"))
Expect(vg.Datacenter.Id).To(Equal(456))
Expect(vg.Datacenter.Name).To(Equal("bej2"))
Expect(vg.Datacenter.LongName).To(Equal("Beijing 2"))
Expect(vg.NetworkComponents[0].MaxSpeed).To(Equal(100))
Expect(len(vg.OperatingSystem.Passwords)).To(BeNumerically(">=", 1))
Expect(vg.OperatingSystem.Passwords[0].Password).To(Equal("test_password"))
Expect(vg.OperatingSystem.Passwords[0].Username).To(Equal("test_username"))
})
})
Context("#EditObject", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_editObject.json")
Expect(err).ToNot(HaveOccurred())
})
It("edits an existing SoftLayer_Virtual_Guest instance", func() {
virtualGuest := datatypes.SoftLayer_Virtual_Guest{
Notes: "fake-notes",
}
edited, err := virtualGuestService.EditObject(virtualGuest.Id, virtualGuest)
Expect(err).ToNot(HaveOccurred())
Expect(edited).To(BeTrue())
})
})
Context("#ReloadOperatingSystem", func() {
BeforeEach(func() {
reload_OS_Config = datatypes.Image_Template_Config{
ImageTemplateId: "5b7bc66a-72c6-447a-94a1-967803fcd76b",
}
virtualGuest.Id = 1234567
})
It("sucessfully reload OS on the virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte(`"1"`)
err = virtualGuestService.ReloadOperatingSystem(virtualGuest.Id, reload_OS_Config)
Expect(err).ToNot(HaveOccurred())
})
It("fails to reload OS on the virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte(`"99"`)
err = virtualGuestService.ReloadOperatingSystem(virtualGuest.Id, reload_OS_Config)
Expect(err).To(HaveOccurred())
})
})
Context("#DeleteObject", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully deletes the SoftLayer_Virtual_Guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
deleted, err := virtualGuestService.DeleteObject(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(deleted).To(BeTrue())
})
It("fails to delete the SoftLayer_Virtual_Guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
deleted, err := virtualGuestService.DeleteObject(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(deleted).To(BeFalse())
})
})
Context("#AttachEphemeralDisk", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Order_placeOrder.json")
Expect(err).ToNot(HaveOccurred())
})
It("reports error when providing a wrong disk size", func() {
_, err := virtualGuestService.AttachEphemeralDisk(123, -1)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Ephemeral disk size can not be negative: -1"))
})
It("can attach a local disk without error", func() {
receipt, err := virtualGuestService.AttachEphemeralDisk(123, 25)
Expect(err).ToNot(HaveOccurred())
Expect(receipt.OrderId).NotTo(Equal(0))
})
})
Context("#UpgradeObject", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Order_placeOrder.json")
Expect(err).ToNot(HaveOccurred())
})
It("can upgrade object without any error", func() {
_, err := virtualGuestService.UpgradeObject(123, &softlayer.UpgradeOptions{
Cpus: 2,
MemoryInGB: 2,
NicSpeed: 1000,
})
Expect(err).ToNot(HaveOccurred())
})
})
Context("#GetAvailableUpgradeItemPrices", func() {
BeforeEach(func() {
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Product_Order_placeOrder.json")
Expect(err).ToNot(HaveOccurred())
})
It("reports error when pricing item for provided CPUs is not available", func() {
_, err := virtualGuestService.GetAvailableUpgradeItemPrices(&softlayer.UpgradeOptions{Cpus: 3})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Failed to find price for 'cpus' (of size 3)"))
})
It("reports error when pricing item for provided RAM is not available", func() {
_, err := virtualGuestService.GetAvailableUpgradeItemPrices(&softlayer.UpgradeOptions{MemoryInGB: 1500})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Failed to find price for 'memory' (of size 1500)"))
})
It("reports error when pricing item for provided network speed is not available", func() {
_, err := virtualGuestService.GetAvailableUpgradeItemPrices(&softlayer.UpgradeOptions{NicSpeed: 999})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Failed to find price for 'nic_speed' (of size 999)"))
})
})
Context("#GetPowerState", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getPowerState.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Virtual_Guest_State for RUNNING instance", func() {
vgPowerState, err := virtualGuestService.GetPowerState(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(vgPowerState.KeyName).To(Equal("RUNNING"))
})
})
Context("#GetPrimaryIpAddress", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse = []byte("159.99.99.99")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer virtual guest's primary IP address instance", func() {
vgPrimaryIpAddress, err := virtualGuestService.GetPrimaryIpAddress(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(vgPrimaryIpAddress).To(Equal("159.99.99.99"))
})
})
Context("#GetActiveTransaction", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getActiveTransaction.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves SoftLayer_Provisioning_Version1_Transaction for virtual guest", func() {
activeTransaction, err := virtualGuestService.GetActiveTransaction(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(activeTransaction.CreateDate).ToNot(BeNil())
Expect(activeTransaction.ElapsedSeconds).To(BeNumerically(">", 0))
Expect(activeTransaction.GuestId).To(Equal(virtualGuest.Id))
Expect(activeTransaction.Id).To(BeNumerically(">", 0))
})
})
Context("#GetLastTransaction", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getLastTransaction.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves last SoftLayer_Provisioning_Version1_Transaction for virtual guest", func() {
lastTransaction, err := virtualGuestService.GetLastTransaction(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(lastTransaction.CreateDate).ToNot(BeNil())
Expect(lastTransaction.ElapsedSeconds).To(BeNumerically(">", 0))
Expect(lastTransaction.GuestId).To(Equal(virtualGuest.Id))
Expect(lastTransaction.Id).To(BeNumerically(">", 0))
})
})
Context("#GetActiveTransactions", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getActiveTransactions.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves an array of SoftLayer_Provisioning_Version1_Transaction for virtual guest", func() {
activeTransactions, err := virtualGuestService.GetActiveTransactions(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(activeTransactions)).To(BeNumerically(">", 0))
for _, activeTransaction := range activeTransactions {
Expect(activeTransaction.CreateDate).ToNot(BeNil())
Expect(activeTransaction.ElapsedSeconds).To(BeNumerically(">", 0))
Expect(activeTransaction.GuestId).To(Equal(virtualGuest.Id))
Expect(activeTransaction.Id).To(BeNumerically(">", 0))
}
})
})
Context("#GetSshKeys", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getSshKeys.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully retrieves an array of SoftLayer_Security_Ssh_Key for virtual guest", func() {
sshKeys, err := virtualGuestService.GetSshKeys(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(sshKeys)).To(BeNumerically(">", 0))
for _, sshKey := range sshKeys {
Expect(sshKey.CreateDate).ToNot(BeNil())
Expect(sshKey.Fingerprint).To(Equal("f6:c2:9d:57:2f:74:be:a1:db:71:f2:e5:8e:0f:84:7e"))
Expect(sshKey.Id).To(Equal(84386))
Expect(sshKey.Key).ToNot(Equal(""))
Expect(sshKey.Label).To(Equal("TEST:softlayer-go"))
Expect(sshKey.ModifyDate).To(BeNil())
Expect(sshKey.Label).To(Equal("TEST:softlayer-go"))
}
})
})
Context("#PowerCycle", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully power cycle virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
rebooted, err := virtualGuestService.PowerCycle(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(rebooted).To(BeTrue())
})
It("fails to power cycle virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
rebooted, err := virtualGuestService.PowerCycle(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(rebooted).To(BeFalse())
})
})
Context("#PowerOff", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully power off virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
rebooted, err := virtualGuestService.PowerOff(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(rebooted).To(BeTrue())
})
It("fails to power off virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
rebooted, err := virtualGuestService.PowerOff(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(rebooted).To(BeFalse())
})
})
Context("#PowerOffSoft", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully power off soft virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
rebooted, err := virtualGuestService.PowerOffSoft(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(rebooted).To(BeTrue())
})
It("fails to power off soft virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
rebooted, err := virtualGuestService.PowerOffSoft(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(rebooted).To(BeFalse())
})
})
Context("#PowerOn", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully power on virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
rebooted, err := virtualGuestService.PowerOn(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(rebooted).To(BeTrue())
})
It("fails to power on virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
rebooted, err := virtualGuestService.PowerOn(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(rebooted).To(BeFalse())
})
})
Context("#RebootDefault", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully default reboots virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
rebooted, err := virtualGuestService.RebootDefault(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(rebooted).To(BeTrue())
})
It("fails to default reboot virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
rebooted, err := virtualGuestService.RebootDefault(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(rebooted).To(BeFalse())
})
})
Context("#RebootSoft", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully soft reboots virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
rebooted, err := virtualGuestService.RebootSoft(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(rebooted).To(BeTrue())
})
It("fails to soft reboot virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
rebooted, err := virtualGuestService.RebootSoft(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(rebooted).To(BeFalse())
})
})
Context("#RebootHard", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
It("sucessfully hard reboot virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
rebooted, err := virtualGuestService.RebootHard(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(rebooted).To(BeTrue())
})
It("fails to hard reboot virtual guest instance", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
rebooted, err := virtualGuestService.RebootHard(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(rebooted).To(BeFalse())
})
})
Context("#SetUserMetadata", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_setMetadata.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully adds metadata strings as a dile to virtual guest's metadata disk", func() {
retBool, err := virtualGuestService.SetMetadata(virtualGuest.Id, "fake-metadata")
Expect(err).ToNot(HaveOccurred())
Expect(retBool).To(BeTrue())
})
})
Context("#GetUserData", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getUserData.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully returns user data for the virtual guest", func() {
attributes, err := virtualGuestService.GetUserData(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(attributes)).To(BeNumerically("==", 2))
Expect(attributes[0].Value).To(Equal("V2hvJ3Mgc21hcnRlcj8gRG1pdHJ5aSBvciBkci5tYXguLi4gIHRoZSBkb2MsIGFueSBkYXkgOik="))
Expect(attributes[0].Type.Name).To(Equal("User Data"))
Expect(attributes[0].Type.Keyname).To(Equal("USER_DATA"))
Expect(attributes[1].Value).To(Equal("ZmFrZS1iYXNlNjQtZGF0YQo="))
Expect(attributes[1].Type.Name).To(Equal("Fake Data"))
Expect(attributes[1].Type.Keyname).To(Equal("FAKE_DATA"))
})
})
Context("#IsPingable", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
Context("when there are no API errors", func() {
It("checks that the virtual guest instance is pigable", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
pingable, err := virtualGuestService.IsPingable(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(pingable).To(BeTrue())
})
It("checks that the virtual guest instance is NOT pigable", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
pingable, err := virtualGuestService.IsPingable(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(pingable).To(BeFalse())
})
})
Context("when there are API errors", func() {
It("returns false and error", func() {
fakeClient.DoRawHttpRequestError = errors.New("fake-error")
pingable, err := virtualGuestService.IsPingable(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(pingable).To(BeFalse())
})
})
Context("when the API returns invalid or empty result", func() {
It("returns false and error", func() {
fakeClient.DoRawHttpRequestResponse = []byte("fake")
pingable, err := virtualGuestService.IsPingable(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Failed to checking that virtual guest is pingable"))
Expect(pingable).To(BeFalse())
})
})
})
Context("#IsBackendPingeable", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
})
Context("when there are no API errors", func() {
It("checks that the virtual guest instance backend is pigable", func() {
fakeClient.DoRawHttpRequestResponse = []byte("true")
pingable, err := virtualGuestService.IsBackendPingable(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(pingable).To(BeTrue())
})
It("checks that the virtual guest instance backend is NOT pigable", func() {
fakeClient.DoRawHttpRequestResponse = []byte("false")
pingable, err := virtualGuestService.IsBackendPingable(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(pingable).To(BeFalse())
})
})
Context("when there are API errors", func() {
It("returns false and error", func() {
fakeClient.DoRawHttpRequestError = errors.New("fake-error")
pingable, err := virtualGuestService.IsBackendPingable(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(pingable).To(BeFalse())
})
})
Context("when the API returns invalid or empty result", func() {
It("returns false and error", func() {
fakeClient.DoRawHttpRequestResponse = []byte("fake")
pingable, err := virtualGuestService.IsBackendPingable(virtualGuest.Id)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Failed to checking that virtual guest backend is pingable"))
Expect(pingable).To(BeFalse())
})
})
})
Context("#ConfigureMetadataDisk", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_configureMetadataDisk.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully configures a metadata disk for a virtual guest", func() {
transaction, err := virtualGuestService.ConfigureMetadataDisk(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(transaction.CreateDate).ToNot(BeNil())
Expect(transaction.ElapsedSeconds).To(Equal(0))
Expect(transaction.GuestId).To(Equal(virtualGuest.Id))
Expect(transaction.HardwareId).To(Equal(0))
Expect(transaction.Id).To(Equal(12476326))
Expect(transaction.ModifyDate).ToNot(BeNil())
Expect(transaction.StatusChangeDate).ToNot(BeNil())
Expect(transaction.TransactionGroup.AverageTimeToComplete).To(Equal("1.62"))
Expect(transaction.TransactionGroup.Name).To(Equal("Configure Cloud Metadata Disk"))
Expect(transaction.TransactionStatus.AverageDuration).To(Equal(".32"))
Expect(transaction.TransactionStatus.FriendlyName).To(Equal("Configure Cloud Metadata Disk"))
Expect(transaction.TransactionStatus.Name).To(Equal("CLOUD_CONFIGURE_METADATA_DISK"))
})
})
Context("#GetUpgradeItemPrices", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getUpgradeItemPrices.json")
Expect(err).ToNot(HaveOccurred())
})
It("sucessfully get the upgrade item prices for a virtual guest", func() {
itemPrices, err := virtualGuestService.GetUpgradeItemPrices(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(itemPrices)).To(Equal(1))
Expect(itemPrices[0].Id).To(Equal(12345))
Expect(itemPrices[0].Categories[0].CategoryCode).To(Equal("guest_disk1"))
})
})
Context("#SetTags", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_setTags.json")
Expect(err).ToNot(HaveOccurred())
})
It("sets tags: tag0, tag1, tag2 to virtual guest instance", func() {
tags := []string{"tag0", "tag1", "tag2"}
tagsWasSet, err := virtualGuestService.SetTags(virtualGuest.Id, tags)
Expect(err).ToNot(HaveOccurred())
Expect(tagsWasSet).To(BeTrue())
})
})
Context("#GetReferenceTags", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getReferenceTags.json")
Expect(err).ToNot(HaveOccurred())
})
itVerifiesATagReference := func(tagReference1 datatypes.SoftLayer_Tag_Reference, tagReference2 datatypes.SoftLayer_Tag_Reference) {
Expect(tagReference1.EmpRecordId).To(Equal(tagReference2.EmpRecordId))
Expect(tagReference1.Id).To(Equal(tagReference2.Id))
Expect(tagReference1.ResourceTableId).To(Equal(tagReference2.ResourceTableId))
Expect(tagReference1.Tag.AccountId).To(Equal(tagReference2.Tag.AccountId))
Expect(tagReference1.Tag.Id).To(Equal(tagReference2.Tag.Id))
Expect(tagReference1.Tag.Internal).To(Equal(tagReference2.Tag.Internal))
Expect(tagReference1.Tag.Name).To(Equal(tagReference2.Tag.Name))
Expect(tagReference1.TagId).To(Equal(tagReference2.TagId))
Expect(tagReference1.TagType.Description).To(Equal(tagReference2.TagType.Description))
Expect(tagReference1.TagType.KeyName).To(Equal(tagReference2.TagType.KeyName))
Expect(tagReference1.TagTypeId).To(Equal(tagReference2.TagTypeId))
Expect(tagReference1.UsrRecordId).To(Equal(tagReference2.UsrRecordId))
}
It("gets the reference tags: tag0, tag1, tag2 from the virtual guest instance", func() {
tagReferences, err := virtualGuestService.GetTagReferences(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(tagReferences)).To(Equal(3))
expectedTagReferences := []datatypes.SoftLayer_Tag_Reference{
datatypes.SoftLayer_Tag_Reference{
EmpRecordId: nil,
Id: 1855150,
ResourceTableId: 7967498,
Tag: datatypes.TagReference{
AccountId: 278444,
Id: 91128,
Internal: 0,
Name: "tag1",
},
TagId: 91128,
TagType: datatypes.TagType{
Description: "CCI",
KeyName: "GUEST",
},
TagTypeId: 2,
UsrRecordId: 239954,
},
datatypes.SoftLayer_Tag_Reference{
EmpRecordId: nil,
Id: 1855152,
ResourceTableId: 7967498,
Tag: datatypes.TagReference{
AccountId: 278444,
Id: 91130,
Internal: 0,
Name: "tag2",
},
TagId: 91130,
TagType: datatypes.TagType{
Description: "CCI",
KeyName: "GUEST",
},
TagTypeId: 2,
UsrRecordId: 239954,
},
datatypes.SoftLayer_Tag_Reference{
EmpRecordId: nil,
Id: 1855154,
ResourceTableId: 7967498,
Tag: datatypes.TagReference{
AccountId: 278444,
Id: 91132,
Internal: 0,
Name: "tag3",
},
TagId: 91132,
TagType: datatypes.TagType{
Description: "CCI",
KeyName: "GUEST",
},
TagTypeId: 2,
UsrRecordId: 239954,
},
}
for i, expectedTagReference := range expectedTagReferences {
itVerifiesATagReference(tagReferences[i], expectedTagReference)
}
})
})
Context("#AttachDiskImage", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_attachDiskImage.json")
Expect(err).ToNot(HaveOccurred())
})
It("attaches disk image with ID `1234567` to virtual guest instance", func() {
imageId := 1234567
transaction, err := virtualGuestService.AttachDiskImage(virtualGuest.Id, imageId)
Expect(err).ToNot(HaveOccurred())
Expect(transaction).ToNot(Equal(datatypes.SoftLayer_Provisioning_Version1_Transaction{}))
})
})
Context("#DetachDiskImage", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_detachDiskImage.json")
Expect(err).ToNot(HaveOccurred())
})
It("detaches disk image with ID `1234567` to virtual guest instance", func() {
imageId := 1234567
transaction, err := virtualGuestService.DetachDiskImage(virtualGuest.Id, imageId)
Expect(err).ToNot(HaveOccurred())
Expect(transaction).ToNot(Equal(datatypes.SoftLayer_Provisioning_Version1_Transaction{}))
})
})
Context("#ActivatePrivatePort", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_activatePrivatePort.json")
Expect(err).ToNot(HaveOccurred())
})
It("activates private port for virtual guest instance", func() {
activated, err := virtualGuestService.ActivatePrivatePort(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(activated).To(BeTrue())
})
})
Context("#ActivatePublicPort", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_activatePublicPort.json")
Expect(err).ToNot(HaveOccurred())
})
It("activates public port for virtual guest instance", func() {
activated, err := virtualGuestService.ActivatePublicPort(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(activated).To(BeTrue())
})
})
Context("#ShutdownPrivatePort", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_shutdownPrivatePort.json")
Expect(err).ToNot(HaveOccurred())
})
It("shutdown private port for virtual guest instance", func() {
shutdowned, err := virtualGuestService.ShutdownPrivatePort(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(shutdowned).To(BeTrue())
})
})
Context("#ShutdownPublicPort", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_shutdownPublicPort.json")
Expect(err).ToNot(HaveOccurred())
})
It("shuts down public port for virtual guest instance", func() {
shutdowned, err := virtualGuestService.ShutdownPublicPort(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(shutdowned).To(BeTrue())
})
})
Context("#GetAllowedHost", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getAllowedHost.json")
Expect(err).ToNot(HaveOccurred())
})
It("gets allowed host for virtual guest", func() {
allowedHost, err := virtualGuestService.GetAllowedHost(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(allowedHost).NotTo(BeNil())
Expect(allowedHost.Name).To(Equal("fake-iqn"))
})
})
Context("#GetNetworkVlans", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_getNetworkVlans.json")
Expect(err).ToNot(HaveOccurred())
})
It("gets network vlans for virtual guest", func() {
networkVlans, err := virtualGuestService.GetNetworkVlans(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(len(networkVlans)).To(Equal(2))
Expect(networkVlans[0].AccountId).To(Equal(278444))
Expect(networkVlans[0].Id).To(Equal(293731))
Expect(networkVlans[0].ModifyDate).ToNot(BeNil())
Expect(networkVlans[0].Name).To(Equal("AMS CLMS Pub"))
Expect(networkVlans[0].NetworkVrfId).To(Equal(0))
Expect(networkVlans[0].Note).To(Equal(""))
Expect(networkVlans[0].PrimarySubnetId).To(Equal(517311))
Expect(networkVlans[0].VlanNumber).To(Equal(809))
})
})
Context("#CheckHostDiskAvailability", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_checkHostDiskAvailability.json")
Expect(err).ToNot(HaveOccurred())
})
It("checks for host disk availability", func() {
available, err := virtualGuestService.CheckHostDiskAvailability(virtualGuest.Id, 10*1024)
Expect(err).ToNot(HaveOccurred())
Expect(available).To(BeTrue())
})
})
Context("#CaptureImage", func() {
BeforeEach(func() {
virtualGuest.Id = 1234567
fakeClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Virtual_Guest_Service_captureImage.json")
Expect(err).ToNot(HaveOccurred())
})
It("captures the virtual guest as a container disk image template", func() {
diskImageTemplate, err := virtualGuestService.CaptureImage(virtualGuest.Id)
Expect(err).ToNot(HaveOccurred())
Expect(diskImageTemplate.Description).To(Equal("fake-description"))
Expect(diskImageTemplate.Name).To(Equal("fake-name"))
Expect(diskImageTemplate.Summary).To(Equal("fake-summary"))
Expect(len(diskImageTemplate.Volumes)).To(BeNumerically(">=", 1))
Expect(diskImageTemplate.Volumes[0].Name).To(Equal("fake-volume-name"))
Expect(len(diskImageTemplate.Volumes[0].Partitions)).To(BeNumerically(">=", 1))
Expect(diskImageTemplate.Volumes[0].Partitions[0].Name).To(Equal("fake-partition-name"))
})
})
})

View File

@ -16,15 +16,20 @@ type Client interface {
GetSoftLayer_Network_Storage_Service() (SoftLayer_Network_Storage_Service, error)
GetSoftLayer_Network_Storage_Allowed_Host_Service() (SoftLayer_Network_Storage_Allowed_Host_Service, error)
GetSoftLayer_Billing_Item_Cancellation_Request_Service() (SoftLayer_Billing_Item_Cancellation_Request_Service, error)
GetSoftLayer_Billing_Item_Service() (SoftLayer_Billing_Item_Service, error)
GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service() (SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service, error)
GetSoftLayer_Hardware_Service() (SoftLayer_Hardware_Service, error)
GetSoftLayer_Dns_Domain_Service() (SoftLayer_Dns_Domain_Service, error)
GetSoftLayer_Dns_Domain_ResourceRecord_Service() (SoftLayer_Dns_Domain_ResourceRecord_Service, error)
DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, error)
DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, error)
DoRawHttpRequestWithObjectFilter(path string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error)
DoRawHttpRequestWithObjectFilterAndObjectMask(path string, masks []string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error)
GetHttpClient() HttpClient
}
type HttpClient interface {
DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error)
DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error)
DoRawHttpRequestWithObjectFilter(path string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error)
DoRawHttpRequestWithObjectFilterAndObjectMask(path string, masks []string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error)
GenerateRequestBody(templateData interface{}) (*bytes.Buffer, error)
HasErrors(body map[string]interface{}) error

View File

@ -9,6 +9,7 @@ type SoftLayer_Account_Service interface {
GetAccountStatus() (datatypes.SoftLayer_Account_Status, error)
GetVirtualGuests() ([]datatypes.SoftLayer_Virtual_Guest, error)
GetVirtualGuestsByFilter(filters string) ([]datatypes.SoftLayer_Virtual_Guest, error)
GetNetworkStorage() ([]datatypes.SoftLayer_Network_Storage, error)
GetIscsiNetworkStorage() ([]datatypes.SoftLayer_Network_Storage, error)
GetIscsiNetworkStorageWithFilter(filter string) ([]datatypes.SoftLayer_Network_Storage, error)

View File

@ -0,0 +1,7 @@
package softlayer
type SoftLayer_Billing_Item_Service interface {
Service
CancelService(billingId int) (bool, error)
}

View File

@ -12,6 +12,7 @@ type SoftLayer_Network_Storage_Service interface {
CreateIscsiVolume(size int, location string) (datatypes.SoftLayer_Network_Storage, error)
DeleteIscsiVolume(volumeId int, immediateCancellationFlag bool) error
GetIscsiVolume(volumeId int) (datatypes.SoftLayer_Network_Storage, error)
GetBillingItem(volumeId int) (datatypes.SoftLayer_Billing_Item, error)
HasAllowedVirtualGuest(volumeId int, vmId int) (bool, error)
AttachIscsiVolume(virtualGuest datatypes.SoftLayer_Virtual_Guest, volumeId int) (bool, error)
DetachIscsiVolume(virtualGuest datatypes.SoftLayer_Virtual_Guest, volumeId int) error

View File

@ -10,6 +10,7 @@ type SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service interface {
AddLocations(id int, locations []datatypes.SoftLayer_Location) (bool, error)
CreateFromExternalSource(configuration datatypes.SoftLayer_Container_Virtual_Guest_Block_Device_Template_Configuration) (datatypes.SoftLayer_Virtual_Guest_Block_Device_Template_Group, error)
CreatePublicArchiveTransaction(id int, groupName string, summary string, note string, locations []datatypes.SoftLayer_Location) (int, error)
CopyToExternalSource(configuration datatypes.SoftLayer_Container_Virtual_Guest_Block_Device_Template_Configuration) (bool, error)
DeleteObject(id int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error)

View File

@ -21,6 +21,7 @@ type SoftLayer_Virtual_Guest_Service interface {
CaptureImage(instanceId int) (datatypes.SoftLayer_Container_Disk_Image_Capture_Template, error)
CheckHostDiskAvailability(instanceId int, diskCapacity int) (bool, error)
ConfigureMetadataDisk(instanceId int) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error)
CreateArchiveTransaction(instanceId int, groupName string, blockDevices []datatypes.SoftLayer_Virtual_Guest_Block_Device, note string) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error)
CreateObject(template datatypes.SoftLayer_Virtual_Guest_Template) (datatypes.SoftLayer_Virtual_Guest, error)
DeleteObject(instanceId int) (bool, error)
@ -37,6 +38,8 @@ type SoftLayer_Virtual_Guest_Service interface {
GetAllowedHost(instanceId int) (datatypes.SoftLayer_Network_Storage_Allowed_Host, error)
GetNetworkVlans(instanceId int) ([]datatypes.SoftLayer_Network_Vlan, error)
GetObject(instanceId int) (datatypes.SoftLayer_Virtual_Guest, error)
GetObjectByPrimaryIpAddress(ipAddress string) (datatypes.SoftLayer_Virtual_Guest, error)
GetObjectByPrimaryBackendIpAddress(ipAddress string) (datatypes.SoftLayer_Virtual_Guest, error)
GetPrimaryIpAddress(instanceId int) (string, error)
GetPowerState(instanceId int) (datatypes.SoftLayer_Virtual_Guest_Power_State, error)
GetSshKeys(instanceId int) ([]datatypes.SoftLayer_Security_Ssh_Key, error)

View File

@ -1,34 +0,0 @@
# flarectl
A CLI application for interacting with a CloudFlare account.
# Usage
You must set your API key and account email address in the environment variables `CF_API_KEY` and `CF_API_EMAIL`.
```
$ export CF_API_KEY=abcdef1234567890
$ export CF_API_EMAIL=someone@example.com
$ flarectl
NAME:
flarectl - CloudFlare CLI
USAGE:
flarectl [global options] command [command options] [arguments...]
VERSION:
2015.12.0
COMMANDS:
user, u User information
zone, z Zone information
dns, d DNS records
railgun, r Railgun information
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--help, -h show help
--version, -v print the version
```

View File

@ -1,726 +0,0 @@
package main
import (
"errors"
"fmt"
"os"
"reflect"
"strings"
"github.com/cloudflare/cloudflare-go"
"github.com/codegangsta/cli"
)
var api *cloudflare.API
// Map type used for printing a table
type table map[string]string
// Print a nicely-formatted table
func makeTable(zones []table, cols ...string) {
// Store the maximum length of all columns
// The default is the length of the title
lens := make(map[string]int)
for _, col := range cols {
lens[col] = len(col)
}
// Increase the size of the column if it is larger than the current value
for _, z := range zones {
for col, val := range z {
if _, ok := lens[col]; ok && len(val) > lens[col] {
lens[col] = len(val)
}
}
}
// Print the headings and an underline for each heading
for _, col := range cols {
fmt.Printf("%s%s ", strings.Title(col), strings.Repeat(" ", lens[col]-len(col)))
}
fmt.Println()
for _, col := range cols {
fmt.Printf("%s ", strings.Repeat("-", lens[col]))
}
fmt.Println()
// And finally print the table data
for _, z := range zones {
for _, col := range cols {
fmt.Printf("%s%s ", z[col], strings.Repeat(" ", lens[col]-len(z[col])))
}
fmt.Println()
}
}
func checkEnv() error {
if api.APIKey == "" {
return errors.New("API key not defined")
}
if api.APIEmail == "" {
return errors.New("API email not defined")
}
return nil
}
// Utility function to check if CLI flags were given.
func checkFlags(c *cli.Context, flags ...string) error {
for _, flag := range flags {
if c.String(flag) == "" {
cli.ShowSubcommandHelp(c)
return fmt.Errorf("%s not specified", flag)
}
}
return nil
}
func ips(*cli.Context) {
ips, _ := cloudflare.IPs()
fmt.Println("IPv4 ranges:")
for _, r := range ips.IPv4CIDRs {
fmt.Println(" ", r)
}
fmt.Println()
fmt.Println("IPv6 ranges:")
for _, r := range ips.IPv6CIDRs {
fmt.Println(" ", r)
}
}
func userInfo(*cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
user, err := api.UserDetails()
if err != nil {
fmt.Println(err)
return
}
var output []table
output = append(output, table{
"ID": user.ID,
"Email": user.Email,
"Username": user.Username,
"Name": user.FirstName + " " + user.LastName,
"2FA": fmt.Sprintf("%t", user.TwoFA),
})
makeTable(output, "ID", "Email", "Username", "Name", "2FA")
}
func userUpdate(*cli.Context) {
}
func zoneList(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
zones, err := api.ListZones()
if err != nil {
fmt.Println(err)
return
}
var output []table
for _, z := range zones {
output = append(output, table{
"ID": z.ID,
"Name": z.Name,
"Plan": z.Plan.LegacyID,
"Status": z.Status,
})
}
makeTable(output, "ID", "Name", "Plan", "Status")
}
func zoneInfo(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
var zone string
if len(c.Args()) > 0 {
zone = c.Args()[0]
} else if c.String("zone") != "" {
zone = c.String("zone")
} else {
cli.ShowSubcommandHelp(c)
return
}
zones, err := api.ListZones(zone)
if err != nil {
fmt.Println(err)
return
}
var output []table
for _, z := range zones {
output = append(output, table{
"ID": z.ID,
"Zone": z.Name,
"Plan": z.Plan.LegacyID,
"Status": z.Status,
"Name Servers": strings.Join(z.NameServers, ", "),
"Paused": fmt.Sprintf("%t", z.Paused),
"Type": z.Type,
})
}
makeTable(output, "ID", "Zone", "Plan", "Status", "Name Servers", "Paused", "Type")
}
func zonePlan(*cli.Context) {
}
func zoneSettings(*cli.Context) {
}
func zoneRecords(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
var zone string
if len(c.Args()) > 0 {
zone = c.Args()[0]
} else if c.String("zone") != "" {
zone = c.String("zone")
} else {
cli.ShowSubcommandHelp(c)
return
}
zoneID, err := api.ZoneIDByName(zone)
if err != nil {
fmt.Println(err)
return
}
// Create a an empty record for searching for records
rr := cloudflare.DNSRecord{}
var records []cloudflare.DNSRecord
if c.String("id") != "" {
rec, err := api.DNSRecord(zoneID, c.String("id"))
if err != nil {
fmt.Println(err)
return
}
records = append(records, rec)
} else {
if c.String("name") != "" {
rr.Name = c.String("name")
}
if c.String("content") != "" {
rr.Name = c.String("content")
}
var err error
records, err = api.DNSRecords(zoneID, rr)
if err != nil {
fmt.Println(err)
return
}
}
var output []table
for _, r := range records {
switch r.Type {
case "MX":
r.Content = fmt.Sprintf("%d %s", r.Priority, r.Content)
case "SRV":
dp := reflect.ValueOf(r.Data).Interface().(map[string]interface{})
r.Content = fmt.Sprintf("%.f %s", dp["priority"], r.Content)
// CloudFlare's API, annoyingly, automatically prepends the weight
// and port into content, separated by tabs.
// XXX: File this as a bug. LOC doesn't do this.
r.Content = strings.Replace(r.Content, "\t", " ", -1)
}
output = append(output, table{
"ID": r.ID,
"Type": r.Type,
"Name": r.Name,
"Content": r.Content,
"Proxied": fmt.Sprintf("%t", r.Proxied),
"TTL": fmt.Sprintf("%d", r.TTL),
})
}
makeTable(output, "ID", "Type", "Name", "Content", "Proxied", "TTL")
}
func dnsCreate(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
if err := checkFlags(c, "zone", "name", "type", "content"); err != nil {
return
}
zone := c.String("zone")
name := c.String("name")
rtype := c.String("type")
content := c.String("content")
ttl := c.Int("ttl")
proxy := c.Bool("proxy")
zoneID, err := api.ZoneIDByName(zone)
if err != nil {
fmt.Println(err)
return
}
record := cloudflare.DNSRecord{
Name: name,
Type: strings.ToUpper(rtype),
Content: content,
TTL: ttl,
Proxied: proxy,
}
err = api.CreateDNSRecord(zoneID, record)
if err != nil {
fmt.Println("Error creating DNS record:", err)
}
}
func dnsCreateOrUpdate(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
if err := checkFlags(c, "zone", "name", "type", "content"); err != nil {
return
}
zone := c.String("zone")
name := c.String("name")
rtype := strings.ToUpper(c.String("type"))
content := c.String("content")
ttl := c.Int("ttl")
proxy := c.Bool("proxy")
zoneID, err := api.ZoneIDByName(zone)
if err != nil {
fmt.Println(err)
return
}
// Look for an existing record
rr := cloudflare.DNSRecord{
Name: name + "." + zone,
}
records, err := api.DNSRecords(zoneID, rr)
if err != nil {
fmt.Println(err)
return
}
if len(records) > 0 {
// Record exists - find the ID and update it.
// This is imprecise without knowing the original content; if a label
// has multiple RRs we'll just update the first one.
for _, r := range records {
if r.Type == rtype {
rr.ID = r.ID
rr.Type = r.Type
rr.Content = content
rr.TTL = ttl
rr.Proxied = proxy
err := api.UpdateDNSRecord(zoneID, r.ID, rr)
if err != nil {
fmt.Println("Error updating DNS record:", err)
}
}
}
} else {
// Record doesn't exist - create it
rr.Type = rtype
rr.Content = content
rr.TTL = ttl
rr.Proxied = proxy
err := api.CreateDNSRecord(zoneID, rr)
if err != nil {
fmt.Println("Error creating DNS record:", err)
}
}
}
func dnsUpdate(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
if err := checkFlags(c, "zone", "id"); err != nil {
return
}
zone := c.String("zone")
recordID := c.String("id")
content := c.String("content")
ttl := c.Int("ttl")
proxy := c.Bool("proxy")
zoneID, err := api.ZoneIDByName(zone)
if err != nil {
fmt.Println(err)
return
}
record := cloudflare.DNSRecord{
ID: recordID,
Content: content,
TTL: ttl,
Proxied: proxy,
}
err = api.UpdateDNSRecord(zoneID, recordID, record)
if err != nil {
fmt.Println("Error updating DNS record:", err)
}
}
func dnsDelete(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
if err := checkFlags(c, "zone", "id"); err != nil {
return
}
zone := c.String("zone")
recordID := c.String("id")
zoneID, err := api.ZoneIDByName(zone)
if err != nil {
fmt.Println(err)
return
}
err = api.DeleteDNSRecord(zoneID, recordID)
if err != nil {
fmt.Println("Error deleting DNS record:", err)
}
}
func zoneCerts(*cli.Context) {
}
func zoneKeyless(*cli.Context) {
}
func zoneRailgun(*cli.Context) {
}
func pageRules(c *cli.Context) {
if err := checkEnv(); err != nil {
fmt.Println(err)
return
}
if err := checkFlags(c, "zone"); err != nil {
return
}
zone := c.String("zone")
zoneID, err := api.ZoneIDByName(zone)
if err != nil {
fmt.Println(err)
return
}
rules, err := api.ListPageRules(zoneID)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%3s %-32s %-8s %s\n", "Pri", "ID", "Status", "URL")
for _, r := range rules {
var settings []string
fmt.Printf("%3d %s %-8s %s\n", r.Priority, r.ID, r.Status, r.Targets[0].Constraint.Value)
for _, a := range r.Actions {
v := reflect.ValueOf(a.Value)
var s string
switch a.Value.(type) {
case int:
s = fmt.Sprintf("%s: %d", cloudflare.PageRuleActions[a.ID], v.Int())
case float64:
s = fmt.Sprintf("%s: %.f", cloudflare.PageRuleActions[a.ID], v.Float())
case map[string]interface{}:
vmap := a.Value.(map[string]interface{})
s = fmt.Sprintf("%s: %.f - %s", cloudflare.PageRuleActions[a.ID], vmap["status_code"], vmap["url"])
case nil:
s = fmt.Sprintf("%s", cloudflare.PageRuleActions[a.ID])
default:
s = fmt.Sprintf("%s: %s", cloudflare.PageRuleActions[a.ID], strings.Title(strings.Replace(v.String(), "_", " ", -1)))
}
settings = append(settings, s)
}
fmt.Println(" ", strings.Join(settings, ", "))
}
}
func railgun(*cli.Context) {
}
func main() {
api = cloudflare.New(os.Getenv("CF_API_KEY"), os.Getenv("CF_API_EMAIL"))
app := cli.NewApp()
app.Name = "flarectl"
app.Usage = "CloudFlare CLI"
app.Version = "2016.4.0"
app.Commands = []cli.Command{
{
Name: "ips",
Aliases: []string{"i"},
Action: ips,
Usage: "Print CloudFlare IP ranges",
},
{
Name: "user",
Aliases: []string{"u"},
Usage: "User information",
Subcommands: []cli.Command{
{
Name: "info",
Aliases: []string{"i"},
Action: userInfo,
Usage: "User details",
},
{
Name: "update",
Aliases: []string{"u"},
Action: userUpdate,
Usage: "Update user details",
},
},
},
{
Name: "zone",
Aliases: []string{"z"},
Usage: "Zone information",
Subcommands: []cli.Command{
{
Name: "list",
Aliases: []string{"l"},
Action: zoneList,
Usage: "List all zones on an account",
},
{
Name: "info",
Aliases: []string{"i"},
Action: zoneInfo,
Usage: "Information on one zone",
Flags: []cli.Flag{
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
},
},
{
Name: "plan",
Aliases: []string{"p"},
Action: zonePlan,
Usage: "Plan information for one zone",
},
{
Name: "settings",
Aliases: []string{"s"},
Action: zoneSettings,
Usage: "Settings for one zone",
},
{
Name: "dns",
Aliases: []string{"d"},
Action: zoneRecords,
Usage: "DNS records for a zone",
Flags: []cli.Flag{
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
},
},
{
Name: "railgun",
Aliases: []string{"r"},
Action: zoneRailgun,
Usage: "Railguns for a zone",
},
{
Name: "certs",
Aliases: []string{"c"},
Action: zoneCerts,
Usage: "Custom SSL certificates for a zone",
},
{
Name: "keyless",
Aliases: []string{"k"},
Action: zoneKeyless,
Usage: "Keyless SSL for a zone",
},
},
},
{
Name: "dns",
Aliases: []string{"d"},
Usage: "DNS records",
Subcommands: []cli.Command{
{
Name: "list",
Aliases: []string{"l"},
Action: zoneRecords,
Usage: "List DNS records for a zone",
Flags: []cli.Flag{
cli.StringFlag{
Name: "id",
Usage: "record id",
},
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
cli.StringFlag{
Name: "name",
Usage: "record name",
},
cli.StringFlag{
Name: "content",
Usage: "record content",
},
},
},
{
Name: "create",
Aliases: []string{"c"},
Action: dnsCreate,
Usage: "Create a DNS record",
Flags: []cli.Flag{
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
cli.StringFlag{
Name: "name",
Usage: "record name",
},
cli.StringFlag{
Name: "type",
Usage: "record type",
},
cli.StringFlag{
Name: "content",
Usage: "record content",
},
cli.IntFlag{
Name: "ttl",
Usage: "TTL (1 = automatic)",
Value: 1,
},
cli.BoolFlag{
Name: "proxy",
Usage: "proxy through CloudFlare (orange cloud)",
},
},
},
{
Name: "update",
Aliases: []string{"u"},
Action: dnsUpdate,
Usage: "Update a DNS record",
Flags: []cli.Flag{
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
cli.StringFlag{
Name: "id",
Usage: "record id",
},
cli.StringFlag{
Name: "content",
Usage: "record content",
},
cli.IntFlag{
Name: "ttl",
Usage: "TTL (1 = automatic)",
Value: 1,
},
cli.BoolFlag{
Name: "proxy",
Usage: "proxy through CloudFlare (orange cloud)",
},
},
},
{
Name: "create-or-update",
Aliases: []string{"o"},
Action: dnsCreateOrUpdate,
Usage: "Create a DNS record, or update if it exists",
Flags: []cli.Flag{
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
cli.StringFlag{
Name: "name",
Usage: "record name",
},
cli.StringFlag{
Name: "content",
Usage: "record content",
},
cli.StringFlag{
Name: "type",
Usage: "record type",
},
cli.IntFlag{
Name: "ttl",
Usage: "TTL (1 = automatic)",
Value: 1,
},
cli.BoolFlag{
Name: "proxy",
Usage: "proxy through CloudFlare (orange cloud)",
},
},
},
{
Name: "delete",
Aliases: []string{"d"},
Action: dnsDelete,
Usage: "Delete a DNS record",
Flags: []cli.Flag{
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
cli.StringFlag{
Name: "id",
Usage: "record id",
},
},
},
},
},
{
Name: "pagerules",
Aliases: []string{"p"},
Usage: "Page Rules",
Subcommands: []cli.Command{
{
Name: "list",
Aliases: []string{"l"},
Action: pageRules,
Usage: "List Page Rules for a zone",
Flags: []cli.Flag{
cli.StringFlag{
Name: "zone",
Usage: "zone name",
},
},
},
},
},
{
Name: "railgun",
Aliases: []string{"r"},
Usage: "Railgun information",
Action: railgun,
},
}
app.Run(os.Args)
}

View File

@ -1,23 +0,0 @@
# 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

View File

@ -1,362 +0,0 @@
Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0.

View File

@ -1,15 +0,0 @@
## cloudflare
This package provides the `cloudflare` package which offers
an interface to the CloudFlare gAPI.
It's intentionally designed to make heavy use of built-ins and strings
in place of custom data structures and proper types. It also only implements
specific endpoints, and doesn't have full API coverage.
**For those reasons, I recommend looking elsewhere if you just need
a standard CloudFlare API client.**
### Documentation
The full documentation is available on [Godoc](http://godoc.org/github.com/pearkes/cloudflare)

View File

@ -1,119 +0,0 @@
package cloudflare
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"github.com/hashicorp/go-cleanhttp"
)
// Client provides a client to the CloudflAre API
type Client struct {
// Access Token
Token string
// User Email
Email string
// URL to the DO API to use
URL string
// HttpClient is the client to use. Default will be
// used if not provided.
Http *http.Client
}
// NewClient returns a new cloudflare client,
// requires an authorization token. You can generate
// an OAuth token by visiting the Apps & API section
// of the CloudflAre control panel for your account.
func NewClient(email string, token string) (*Client, error) {
// If it exists, grab teh token from the environment
if token == "" {
token = os.Getenv("CLOUDFLARE_TOKEN")
}
if email == "" {
email = os.Getenv("CLOUDFLARE_EMAIL")
}
client := Client{
Token: token,
Email: email,
URL: "https://www.cloudflare.com/api_json.html",
Http: cleanhttp.DefaultClient(),
}
return &client, nil
}
// Creates a new request with the params
func (c *Client) NewRequest(params map[string]string, method string, action string) (*http.Request, error) {
p := url.Values{}
u, err := url.Parse(c.URL)
if err != nil {
return nil, fmt.Errorf("Error parsing base URL: %s", err)
}
// Build up our request parameters
for k, v := range params {
p.Add(k, v)
}
// Add authentication details
p.Add("tkn", c.Token)
p.Add("email", c.Email)
// The "action" to take against the API
p.Add("a", action)
// Add the params to our URL
u.RawQuery = p.Encode()
// Build the request
req, err := http.NewRequest(method, u.String(), nil)
if err != nil {
return nil, fmt.Errorf("Error creating request: %s", err)
}
return req, nil
}
// decodeBody is used to JSON decode a body
func decodeBody(resp *http.Response, out interface{}) error {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err = json.Unmarshal(body, &out); err != nil {
return err
}
return nil
}
// checkResp wraps http.Client.Do() and verifies that the
// request was successful. A non-200 request returns an error
// formatted to included any validation problems or otherwise
func checkResp(resp *http.Response, err error) (*http.Response, error) {
// If the err is already there, there was an error higher
// up the chain, so just return that
if err != nil {
return resp, err
}
switch i := resp.StatusCode; {
case i == 200:
return resp, nil
default:
return nil, fmt.Errorf("API Error: %s", resp.Status)
}
}

View File

@ -1,334 +0,0 @@
package cloudflare
import (
"errors"
"fmt"
"strings"
)
type RecordsResponse struct {
Response struct {
Recs struct {
Records []Record `json:"objs"`
} `json:"recs"`
} `json:"response"`
Result string `json:"result"`
Message string `json:"msg"`
}
func (r *RecordsResponse) FindRecord(id string) (*Record, error) {
if r.Result == "error" {
return nil, fmt.Errorf("API Error: %s", r.Message)
}
objs := r.Response.Recs.Records
notFoundErr := errors.New("Record not found")
// No objects, return nil
if len(objs) < 0 {
return nil, notFoundErr
}
for _, v := range objs {
// We have a match, return that
if v.Id == id {
return &v, nil
}
}
return nil, notFoundErr
}
func (r *RecordsResponse) FindRecordByName(name string, wildcard bool) ([]Record, error) {
if r.Result == "error" {
return nil, fmt.Errorf("API Error: %s", r.Message)
}
objs := r.Response.Recs.Records
notFoundErr := errors.New("Record not found")
// No objects, return nil
if len(objs) < 0 {
return nil, notFoundErr
}
var recs []Record
suffix := "." + name
for _, v := range objs {
if v.Name == name {
recs = append(recs, v)
} else if wildcard && strings.HasSuffix(v.Name, suffix) {
recs = append(recs, v)
}
}
return recs, nil
}
type RecordResponse struct {
Response struct {
Rec struct {
Record Record `json:"obj"`
} `json:"rec"`
} `json:"response"`
Result string `json:"result"`
Message string `json:"msg"`
}
func (r *RecordResponse) GetRecord() (*Record, error) {
if r.Result == "error" {
return nil, fmt.Errorf("API Error: %s", r.Message)
}
return &r.Response.Rec.Record, nil
}
// Record is used to represent a retrieved Record. All properties
// are set as strings.
type Record struct {
Id string `json:"rec_id"`
Domain string `json:"zone_name"`
Name string `json:"display_name"`
FullName string `json:"name"`
Value string `json:"content"`
Type string `json:"type"`
Priority string `json:"prio"`
Ttl string `json:"ttl"`
}
// CreateRecord contains the request parameters to create a new
// record.
type CreateRecord struct {
Type string
Name string
Content string
Ttl string
Priority string
}
// CreateRecord creates a record from the parameters specified and
// returns an error if it fails. If no error and the name is returned,
// the Record was succesfully created.
func (c *Client) CreateRecord(domain string, opts *CreateRecord) (*Record, error) {
// Make the request parameters
params := make(map[string]string)
params["z"] = domain
params["type"] = opts.Type
if opts.Name != "" {
params["name"] = opts.Name
}
if opts.Content != "" {
params["content"] = opts.Content
}
if opts.Priority != "" {
params["prio"] = opts.Priority
}
if opts.Ttl != "" {
params["ttl"] = opts.Ttl
} else {
params["ttl"] = "1"
}
req, err := c.NewRequest(params, "POST", "rec_new")
if err != nil {
return nil, err
}
resp, err := checkResp(c.Http.Do(req))
if err != nil {
return nil, fmt.Errorf("Error creating record: %s", err)
}
recordResp := new(RecordResponse)
err = decodeBody(resp, &recordResp)
if err != nil {
return nil, fmt.Errorf("Error parsing record response: %s", err)
}
record, err := recordResp.GetRecord()
if err != nil {
return nil, err
}
// The request was successful
return record, nil
}
// DestroyRecord destroys a record by the ID specified and
// returns an error if it fails. If no error is returned,
// the Record was succesfully destroyed.
func (c *Client) DestroyRecord(domain string, id string) error {
params := make(map[string]string)
params["z"] = domain
params["id"] = id
req, err := c.NewRequest(params, "POST", "rec_delete")
if err != nil {
return err
}
resp, err := checkResp(c.Http.Do(req))
if err != nil {
return fmt.Errorf("Error deleting record: %s", err)
}
recordResp := new(RecordResponse)
err = decodeBody(resp, &recordResp)
if err != nil {
return fmt.Errorf("Error parsing record response: %s", err)
}
_, err = recordResp.GetRecord()
if err != nil {
return err
}
// The request was successful
return nil
}
// UpdateRecord contains the request parameters to update a
// record.
type UpdateRecord struct {
Type string
Name string
Content string
Ttl string
Priority string
}
// UpdateRecord destroys a record by the ID specified and
// returns an error if it fails. If no error is returned,
// the Record was succesfully updated.
func (c *Client) UpdateRecord(domain string, id string, opts *UpdateRecord) error {
params := make(map[string]string)
params["z"] = domain
params["id"] = id
params["type"] = opts.Type
if opts.Name != "" {
params["name"] = opts.Name
}
if opts.Content != "" {
params["content"] = opts.Content
}
if opts.Priority != "" {
params["prio"] = opts.Priority
}
if opts.Ttl != "" {
params["ttl"] = opts.Ttl
} else {
params["ttl"] = "1"
}
req, err := c.NewRequest(params, "POST", "rec_edit")
if err != nil {
return err
}
resp, err := checkResp(c.Http.Do(req))
if err != nil {
return fmt.Errorf("Error updating record: %s", err)
}
recordResp := new(RecordResponse)
err = decodeBody(resp, &recordResp)
if err != nil {
return fmt.Errorf("Error parsing record response: %s", err)
}
_, err = recordResp.GetRecord()
if err != nil {
return err
}
// The request was successful
return nil
}
func (c *Client) RetrieveRecordsByName(domain string, name string, wildcard bool) ([]Record, error) {
params := make(map[string]string)
// The zone we want
params["z"] = domain
req, err := c.NewRequest(params, "GET", "rec_load_all")
if err != nil {
return nil, err
}
resp, err := checkResp(c.Http.Do(req))
if err != nil {
return nil, fmt.Errorf("Error retrieving record: %s", err)
}
records := new(RecordsResponse)
err = decodeBody(resp, records)
if err != nil {
return nil, fmt.Errorf("Error decoding record response: %s", err)
}
record, err := records.FindRecordByName(name, wildcard)
if err != nil {
return nil, err
}
// The request was successful
return record, nil
}
// RetrieveRecord gets a record by the ID specified and
// returns a Record and an error. An error will be returned for failed
// requests with a nil Record.
func (c *Client) RetrieveRecord(domain string, id string) (*Record, error) {
params := make(map[string]string)
// The zone we want
params["z"] = domain
params["id"] = id
req, err := c.NewRequest(params, "GET", "rec_load_all")
if err != nil {
return nil, err
}
resp, err := checkResp(c.Http.Do(req))
if err != nil {
return nil, fmt.Errorf("Error retrieving record: %s", err)
}
records := new(RecordsResponse)
err = decodeBody(resp, records)
if err != nil {
return nil, fmt.Errorf("Error decoding record response: %s", err)
}
record, err := records.FindRecord(id)
if err != nil {
return nil, err
}
// The request was successful
return record, nil
}