diff --git a/state/remote/swift.go b/state/remote/swift.go index 3f9c88d69..6fc4597f6 100644 --- a/state/remote/swift.go +++ b/state/remote/swift.go @@ -3,14 +3,17 @@ package remote import ( "bytes" "crypto/md5" + "crypto/tls" "fmt" + "log" + "net/http" "os" - "strings" + "strconv" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" - "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers" - "github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects" + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack" + "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/containers" + "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects" ) const TFSTATE_NAME = "tfstate.tf" @@ -49,13 +52,38 @@ func (c *SwiftClient) validateConfig(conf map[string]string) (err error) { return fmt.Errorf("missing 'path' configuration") } - provider, err := openstack.AuthenticatedClient(gophercloud.AuthOptions{ + ao := gophercloud.AuthOptions{ IdentityEndpoint: os.Getenv("OS_AUTH_URL"), Username: os.Getenv("OS_USERNAME"), TenantName: os.Getenv("OS_TENANT_NAME"), Password: os.Getenv("OS_PASSWORD"), - }) + DomainName: os.Getenv("OS_DOMAIN_NAME"), + DomainID: os.Getenv("OS_DOMAIN_ID"), + } + provider, err := openstack.NewClient(ao.IdentityEndpoint) + if err != nil { + return err + } + + config := &tls.Config{} + insecure := false + if insecure_env := os.Getenv("OS_INSECURE"); insecure_env != "" { + insecure, err = strconv.ParseBool(insecure_env) + if err != nil { + return err + } + } + + if insecure { + log.Printf("[DEBUG] Insecure mode set") + config.InsecureSkipVerify = true + } + + transport := &http.Transport{Proxy: http.ProxyFromEnvironment, TLSClientConfig: config} + provider.HTTPClient.Transport = transport + + err = openstack.Authenticate(provider, ao) if err != nil { return err } @@ -70,12 +98,18 @@ func (c *SwiftClient) validateConfig(conf map[string]string) (err error) { func (c *SwiftClient) Get() (*Payload, error) { result := objects.Download(c.client, c.path, TFSTATE_NAME, nil) - bytes, err := result.ExtractContent() + // Extract any errors from result + _, err := result.Extract() + + // 404 response is to be expected if the object doesn't already exist! + if _, ok := err.(gophercloud.ErrDefault404); ok { + log.Printf("[DEBUG] Container doesn't exist to download.") + return nil, nil + } + + bytes, err := result.ExtractContent() if err != nil { - if strings.Contains(err.Error(), "but got 404 instead") { - return nil, nil - } return nil, err } @@ -94,7 +128,10 @@ func (c *SwiftClient) Put(data []byte) error { } reader := bytes.NewReader(data) - result := objects.Create(c.client, c.path, TFSTATE_NAME, reader, nil) + createOpts := objects.CreateOpts{ + Content: reader, + } + result := objects.Create(c.client, c.path, TFSTATE_NAME, createOpts) return result.Err } diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/doc.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/doc.go similarity index 100% rename from vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/doc.go rename to vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/doc.go diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/requests.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/requests.go similarity index 83% rename from vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/requests.go rename to vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/requests.go index 79eff609e..b5beef28b 100644 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/requests.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/requests.go @@ -1,6 +1,6 @@ package accounts -import "github.com/rackspace/gophercloud" +import "github.com/gophercloud/gophercloud" // GetOptsBuilder allows extensions to add additional headers to the Get // request. @@ -23,31 +23,27 @@ func (opts GetOpts) ToAccountGetMap() (map[string]string, error) { // custom metadata, call the ExtractMetadata method on the GetResult. To extract // all the headers that are returned (including the metadata), call the // ExtractHeader method on the GetResult. -func Get(c *gophercloud.ServiceClient, opts GetOptsBuilder) GetResult { - var res GetResult +func Get(c *gophercloud.ServiceClient, opts GetOptsBuilder) (r GetResult) { h := make(map[string]string) - if opts != nil { headers, err := opts.ToAccountGetMap() if err != nil { - res.Err = err - return res + r.Err = err + return } - for k, v := range headers { h[k] = v } } - - resp, err := c.Request("HEAD", getURL(c), gophercloud.RequestOpts{ + resp, err := c.Request("HEAD", getURL(c), &gophercloud.RequestOpts{ MoreHeaders: h, OkCodes: []int{204}, }) if resp != nil { - res.Header = resp.Header + r.Header = resp.Header } - res.Err = err - return res + r.Err = err + return } // UpdateOptsBuilder allows extensions to add additional headers to the Update @@ -80,28 +76,25 @@ func (opts UpdateOpts) ToAccountUpdateMap() (map[string]string, error) { // Update is a function that creates, updates, or deletes an account's metadata. // To extract the headers returned, call the Extract method on the UpdateResult. -func Update(c *gophercloud.ServiceClient, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult +func Update(c *gophercloud.ServiceClient, opts UpdateOptsBuilder) (r UpdateResult) { h := make(map[string]string) - if opts != nil { headers, err := opts.ToAccountUpdateMap() if err != nil { - res.Err = err - return res + r.Err = err + return } for k, v := range headers { h[k] = v } } - - resp, err := c.Request("POST", updateURL(c), gophercloud.RequestOpts{ + resp, err := c.Request("POST", updateURL(c), &gophercloud.RequestOpts{ MoreHeaders: h, OkCodes: []int{201, 202, 204}, }) if resp != nil { - res.Header = resp.Header + r.Header = resp.Header } - res.Err = err - return res + r.Err = err + return } diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/results.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/results.go new file mode 100644 index 000000000..216414b74 --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/results.go @@ -0,0 +1,160 @@ +package accounts + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + + "github.com/gophercloud/gophercloud" +) + +// UpdateResult is returned from a call to the Update function. +type UpdateResult struct { + gophercloud.HeaderResult +} + +// UpdateHeader represents the headers returned in the response from an Update request. +type UpdateHeader struct { + ContentLength int64 `json:"-"` + ContentType string `json:"Content-Type"` + TransID string `json:"X-Trans-Id"` + Date gophercloud.JSONRFC1123 `json:"Date"` +} + +func (h *UpdateHeader) UnmarshalJSON(b []byte) error { + type tmp UpdateHeader + var updateHeader *struct { + tmp + ContentLength string `json:"Content-Length"` + } + err := json.Unmarshal(b, &updateHeader) + if err != nil { + return err + } + + *h = UpdateHeader(updateHeader.tmp) + + switch updateHeader.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(updateHeader.ContentLength, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// Extract will return a struct of headers returned from a call to Get. To obtain +// a map of headers, call the ExtractHeader method on the GetResult. +func (ur UpdateResult) Extract() (*UpdateHeader, error) { + var uh *UpdateHeader + err := ur.ExtractInto(&uh) + return uh, err +} + +// GetHeader represents the headers returned in the response from a Get request. +type GetHeader struct { + BytesUsed int64 `json:"-"` + ContainerCount int64 `json:"-"` + ContentLength int64 `json:"-"` + ObjectCount int64 `json:"-"` + ContentType string `json:"Content-Type"` + TransID string `json:"X-Trans-Id"` + TempURLKey string `json:"X-Account-Meta-Temp-URL-Key"` + TempURLKey2 string `json:"X-Account-Meta-Temp-URL-Key-2"` + Date gophercloud.JSONRFC1123 `json:"Date"` +} + +func (h *GetHeader) UnmarshalJSON(b []byte) error { + type tmp GetHeader + var getHeader *struct { + tmp + BytesUsed string `json:"X-Account-Bytes-Used"` + ContentLength string `json:"Content-Length"` + ContainerCount string `json:"X-Account-Container-Count"` + ObjectCount string `json:"X-Account-Object-Count"` + } + err := json.Unmarshal(b, &getHeader) + if err != nil { + return err + } + + *h = GetHeader(getHeader.tmp) + + switch getHeader.BytesUsed { + case "": + h.BytesUsed = 0 + default: + h.BytesUsed, err = strconv.ParseInt(getHeader.BytesUsed, 10, 64) + if err != nil { + return err + } + } + + fmt.Println("getHeader: ", getHeader.ContentLength) + switch getHeader.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(getHeader.ContentLength, 10, 64) + if err != nil { + return err + } + } + + switch getHeader.ObjectCount { + case "": + h.ObjectCount = 0 + default: + h.ObjectCount, err = strconv.ParseInt(getHeader.ObjectCount, 10, 64) + if err != nil { + return err + } + } + + switch getHeader.ContainerCount { + case "": + h.ContainerCount = 0 + default: + h.ContainerCount, err = strconv.ParseInt(getHeader.ContainerCount, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// GetResult is returned from a call to the Get function. +type GetResult struct { + gophercloud.HeaderResult +} + +// Extract will return a struct of headers returned from a call to Get. To obtain +// a map of headers, call the ExtractHeader method on the GetResult. +func (r GetResult) Extract() (*GetHeader, error) { + var s *GetHeader + err := r.ExtractInto(&s) + return s, err +} + +// ExtractMetadata is a function that takes a GetResult (of type *http.Response) +// and returns the custom metatdata associated with the account. +func (r GetResult) ExtractMetadata() (map[string]string, error) { + if r.Err != nil { + return nil, r.Err + } + + metadata := make(map[string]string) + for k, v := range r.Header { + if strings.HasPrefix(k, "X-Account-Meta-") { + key := strings.TrimPrefix(k, "X-Account-Meta-") + metadata[key] = v[0] + } + } + return metadata, nil +} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/urls.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/urls.go similarity index 79% rename from vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/urls.go rename to vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/urls.go index 9952fe434..71540b1da 100644 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/urls.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts/urls.go @@ -1,6 +1,6 @@ package accounts -import "github.com/rackspace/gophercloud" +import "github.com/gophercloud/gophercloud" func getURL(c *gophercloud.ServiceClient) string { return c.Endpoint diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/doc.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/doc.go similarity index 100% rename from vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/doc.go rename to vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/doc.go diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/errors.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/errors.go new file mode 100644 index 000000000..5c4ae44d3 --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/errors.go @@ -0,0 +1,13 @@ +package objects + +import "github.com/gophercloud/gophercloud" + +// ErrWrongChecksum is the error when the checksum generated for an object +// doesn't match the ETAG header. +type ErrWrongChecksum struct { + gophercloud.BaseError +} + +func (e ErrWrongChecksum) Error() string { + return "Local checksum does not match API ETag header" +} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/requests.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/requests.go similarity index 81% rename from vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/requests.go rename to vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/requests.go index a2b96eda2..0ab5e1711 100644 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/requests.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/requests.go @@ -1,19 +1,18 @@ package objects import ( - "bufio" + "bytes" "crypto/hmac" "crypto/md5" "crypto/sha1" "fmt" "io" - "io/ioutil" "strings" "time" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts" - "github.com/rackspace/gophercloud/pagination" + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts" + "github.com/gophercloud/gophercloud/pagination" ) // ListOptsBuilder allows extensions to add additional parameters to the List @@ -42,10 +41,7 @@ type ListOpts struct { // representing whether to list complete information for each object. func (opts ListOpts) ToObjectListParams() (bool, string, error) { q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return false, "", err - } - return opts.Full, q.String(), nil + return opts.Full, q.String(), err } // List is a function that retrieves all objects in a container. It also returns the details @@ -67,13 +63,11 @@ func List(c *gophercloud.ServiceClient, containerName string, opts ListOptsBuild } } - createPage := func(r pagination.PageResult) pagination.Page { + pager := pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { p := ObjectPage{pagination.MarkerPageBase{PageResult: r}} p.MarkerPageBase.Owner = p return p - } - - pager := pagination.NewPager(c, url, createPage) + }) pager.Headers = headers return pager } @@ -113,47 +107,42 @@ func (opts DownloadOpts) ToObjectDownloadParams() (map[string]string, string, er // Download is a function that retrieves the content and metadata for an object. // To extract just the content, pass the DownloadResult response to the // ExtractContent function. -func Download(c *gophercloud.ServiceClient, containerName, objectName string, opts DownloadOptsBuilder) DownloadResult { - var res DownloadResult - +func Download(c *gophercloud.ServiceClient, containerName, objectName string, opts DownloadOptsBuilder) (r DownloadResult) { url := downloadURL(c, containerName, objectName) h := make(map[string]string) - if opts != nil { headers, query, err := opts.ToObjectDownloadParams() if err != nil { - res.Err = err - return res + r.Err = err + return } - for k, v := range headers { h[k] = v } - url += query } - resp, err := c.Request("GET", url, gophercloud.RequestOpts{ + resp, err := c.Get(url, nil, &gophercloud.RequestOpts{ MoreHeaders: h, OkCodes: []int{200, 304}, }) if resp != nil { - res.Header = resp.Header - res.Body = resp.Body + r.Header = resp.Header + r.Body = resp.Body } - res.Err = err - - return res + r.Err = err + return } // CreateOptsBuilder allows extensions to add additional parameters to the // Create request. type CreateOptsBuilder interface { - ToObjectCreateParams() (map[string]string, string, error) + ToObjectCreateParams() (io.Reader, map[string]string, string, error) } // CreateOpts is a structure that holds parameters for creating an object. type CreateOpts struct { + Content io.Reader Metadata map[string]string CacheControl string `h:"Cache-Control"` ContentDisposition string `h:"Content-Disposition"` @@ -175,78 +164,60 @@ type CreateOpts struct { // ToObjectCreateParams formats a CreateOpts into a query string and map of // headers. -func (opts CreateOpts) ToObjectCreateParams() (map[string]string, string, error) { +func (opts CreateOpts) ToObjectCreateParams() (io.Reader, map[string]string, string, error) { q, err := gophercloud.BuildQueryString(opts) if err != nil { - return nil, "", err + return nil, nil, "", err } h, err := gophercloud.BuildHeaders(opts) if err != nil { - return nil, q.String(), err + return nil, nil, "", err } for k, v := range opts.Metadata { h["X-Object-Meta-"+k] = v } - return h, q.String(), nil + hash := md5.New() + buf := bytes.NewBuffer([]byte{}) + _, err = io.Copy(io.MultiWriter(hash, buf), opts.Content) + if err != nil { + return nil, nil, "", err + } + localChecksum := fmt.Sprintf("%x", hash.Sum(nil)) + h["ETag"] = localChecksum + + return buf, h, q.String(), nil } // Create is a function that creates a new object or replaces an existing object. If the returned response's ETag // header fails to match the local checksum, the failed request will automatically be retried up to a maximum of 3 times. -func Create(c *gophercloud.ServiceClient, containerName, objectName string, content io.ReadSeeker, opts CreateOptsBuilder) CreateResult { - var res CreateResult - +func Create(c *gophercloud.ServiceClient, containerName, objectName string, opts CreateOptsBuilder) (r CreateResult) { url := createURL(c, containerName, objectName) h := make(map[string]string) - + var b io.Reader if opts != nil { - headers, query, err := opts.ToObjectCreateParams() + tmpB, headers, query, err := opts.ToObjectCreateParams() if err != nil { - res.Err = err - return res + r.Err = err + return } - for k, v := range headers { h[k] = v } - url += query + b = tmpB } - hash := md5.New() - bufioReader := bufio.NewReader(io.TeeReader(content, hash)) - io.Copy(ioutil.Discard, bufioReader) - localChecksum := hash.Sum(nil) - - h["ETag"] = fmt.Sprintf("%x", localChecksum) - - _, err := content.Seek(0, 0) - if err != nil { - res.Err = err - return res - } - - ropts := gophercloud.RequestOpts{ - RawBody: content, + resp, err := c.Put(url, nil, nil, &gophercloud.RequestOpts{ + RawBody: b, MoreHeaders: h, - } - - resp, err := c.Request("PUT", url, ropts) - if err != nil { - res.Err = err - return res - } + }) + r.Err = err if resp != nil { - res.Header = resp.Header - if resp.Header.Get("ETag") == fmt.Sprintf("%x", localChecksum) { - res.Err = err - return res - } - res.Err = fmt.Errorf("Local checksum does not match API ETag header") + r.Header = resp.Header } - - return res + return } // CopyOptsBuilder allows extensions to add additional parameters to the @@ -262,14 +233,11 @@ type CopyOpts struct { ContentDisposition string `h:"Content-Disposition"` ContentEncoding string `h:"Content-Encoding"` ContentType string `h:"Content-Type"` - Destination string `h:"Destination,required"` + Destination string `h:"Destination" required:"true"` } // ToObjectCopyMap formats a CopyOpts into a map of headers. func (opts CopyOpts) ToObjectCopyMap() (map[string]string, error) { - if opts.Destination == "" { - return nil, fmt.Errorf("Required CopyOpts field 'Destination' not set.") - } h, err := gophercloud.BuildHeaders(opts) if err != nil { return nil, err @@ -281,14 +249,12 @@ func (opts CopyOpts) ToObjectCopyMap() (map[string]string, error) { } // Copy is a function that copies one object to another. -func Copy(c *gophercloud.ServiceClient, containerName, objectName string, opts CopyOptsBuilder) CopyResult { - var res CopyResult +func Copy(c *gophercloud.ServiceClient, containerName, objectName string, opts CopyOptsBuilder) (r CopyResult) { h := make(map[string]string) - headers, err := opts.ToObjectCopyMap() if err != nil { - res.Err = err - return res + r.Err = err + return } for k, v := range headers { @@ -296,15 +262,15 @@ func Copy(c *gophercloud.ServiceClient, containerName, objectName string, opts C } url := copyURL(c, containerName, objectName) - resp, err := c.Request("COPY", url, gophercloud.RequestOpts{ + resp, err := c.Request("COPY", url, &gophercloud.RequestOpts{ MoreHeaders: h, OkCodes: []int{201}, }) if resp != nil { - res.Header = resp.Header + r.Header = resp.Header } - res.Err = err - return res + r.Err = err + return } // DeleteOptsBuilder allows extensions to add additional parameters to the @@ -321,32 +287,26 @@ type DeleteOpts struct { // ToObjectDeleteQuery formats a DeleteOpts into a query string. func (opts DeleteOpts) ToObjectDeleteQuery() (string, error) { q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil + return q.String(), err } // Delete is a function that deletes an object. -func Delete(c *gophercloud.ServiceClient, containerName, objectName string, opts DeleteOptsBuilder) DeleteResult { - var res DeleteResult +func Delete(c *gophercloud.ServiceClient, containerName, objectName string, opts DeleteOptsBuilder) (r DeleteResult) { url := deleteURL(c, containerName, objectName) - if opts != nil { query, err := opts.ToObjectDeleteQuery() if err != nil { - res.Err = err - return res + r.Err = err + return } url += query } - resp, err := c.Delete(url, nil) if resp != nil { - res.Header = resp.Header + r.Header = resp.Header } - res.Err = err - return res + r.Err = err + return } // GetOptsBuilder allows extensions to add additional parameters to the @@ -364,35 +324,29 @@ type GetOpts struct { // ToObjectGetQuery formats a GetOpts into a query string. func (opts GetOpts) ToObjectGetQuery() (string, error) { q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil + return q.String(), err } // Get is a function that retrieves the metadata of an object. To extract just the custom // metadata, pass the GetResult response to the ExtractMetadata function. -func Get(c *gophercloud.ServiceClient, containerName, objectName string, opts GetOptsBuilder) GetResult { - var res GetResult +func Get(c *gophercloud.ServiceClient, containerName, objectName string, opts GetOptsBuilder) (r GetResult) { url := getURL(c, containerName, objectName) - if opts != nil { query, err := opts.ToObjectGetQuery() if err != nil { - res.Err = err - return res + r.Err = err + return } url += query } - - resp, err := c.Request("HEAD", url, gophercloud.RequestOpts{ + resp, err := c.Request("HEAD", url, &gophercloud.RequestOpts{ OkCodes: []int{200, 204}, }) if resp != nil { - res.Header = resp.Header + r.Header = resp.Header } - res.Err = err - return res + r.Err = err + return } // UpdateOptsBuilder allows extensions to add additional parameters to the @@ -426,31 +380,28 @@ func (opts UpdateOpts) ToObjectUpdateMap() (map[string]string, error) { } // Update is a function that creates, updates, or deletes an object's metadata. -func Update(c *gophercloud.ServiceClient, containerName, objectName string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult +func Update(c *gophercloud.ServiceClient, containerName, objectName string, opts UpdateOptsBuilder) (r UpdateResult) { h := make(map[string]string) - if opts != nil { headers, err := opts.ToObjectUpdateMap() if err != nil { - res.Err = err - return res + r.Err = err + return } for k, v := range headers { h[k] = v } } - url := updateURL(c, containerName, objectName) - resp, err := c.Request("POST", url, gophercloud.RequestOpts{ + resp, err := c.Post(url, nil, nil, &gophercloud.RequestOpts{ MoreHeaders: h, }) if resp != nil { - res.Header = resp.Header + r.Header = resp.Header } - res.Err = err - return res + r.Err = err + return } // HTTPMethod represents an HTTP method string (e.g. "GET"). diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/results.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/results.go new file mode 100644 index 000000000..4f7020cfd --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/results.go @@ -0,0 +1,441 @@ +package objects + +import ( + "encoding/json" + "fmt" + "io" + "io/ioutil" + "strconv" + "strings" + + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/pagination" +) + +// Object is a structure that holds information related to a storage object. +type Object struct { + // Bytes is the total number of bytes that comprise the object. + Bytes int64 `json:"bytes"` + + // ContentType is the content type of the object. + ContentType string `json:"content_type"` + + // Hash represents the MD5 checksum value of the object's content. + Hash string `json:"hash"` + + // LastModified is the RFC3339Milli time the object was last modified, represented + // as a string. For any given object (obj), this value may be parsed to a time.Time: + // lastModified, err := time.Parse(gophercloud.RFC3339Milli, obj.LastModified) + LastModified gophercloud.JSONRFC3339MilliNoZ `json:"last_modified"` + + // Name is the unique name for the object. + Name string `json:"name"` +} + +// ObjectPage is a single page of objects that is returned from a call to the +// List function. +type ObjectPage struct { + pagination.MarkerPageBase +} + +// IsEmpty returns true if a ListResult contains no object names. +func (r ObjectPage) IsEmpty() (bool, error) { + names, err := ExtractNames(r) + return len(names) == 0, err +} + +// LastMarker returns the last object name in a ListResult. +func (r ObjectPage) LastMarker() (string, error) { + names, err := ExtractNames(r) + if err != nil { + return "", err + } + if len(names) == 0 { + return "", nil + } + return names[len(names)-1], nil +} + +// ExtractInfo is a function that takes a page of objects and returns their full information. +func ExtractInfo(r pagination.Page) ([]Object, error) { + var s []Object + err := (r.(ObjectPage)).ExtractInto(&s) + return s, err +} + +// ExtractNames is a function that takes a page of objects and returns only their names. +func ExtractNames(r pagination.Page) ([]string, error) { + casted := r.(ObjectPage) + ct := casted.Header.Get("Content-Type") + switch { + case strings.HasPrefix(ct, "application/json"): + parsed, err := ExtractInfo(r) + if err != nil { + return nil, err + } + + names := make([]string, 0, len(parsed)) + for _, object := range parsed { + names = append(names, object.Name) + } + + return names, nil + case strings.HasPrefix(ct, "text/plain"): + names := make([]string, 0, 50) + + body := string(r.(ObjectPage).Body.([]uint8)) + for _, name := range strings.Split(body, "\n") { + if len(name) > 0 { + names = append(names, name) + } + } + + return names, nil + case strings.HasPrefix(ct, "text/html"): + return []string{}, nil + default: + return nil, fmt.Errorf("Cannot extract names from response with content-type: [%s]", ct) + } +} + +// DownloadHeader represents the headers returned in the response from a Download request. +type DownloadHeader struct { + AcceptRanges string `json:"Accept-Ranges"` + ContentDisposition string `json:"Content-Disposition"` + ContentEncoding string `json:"Content-Encoding"` + ContentLength int64 `json:"-"` + ContentType string `json:"Content-Type"` + Date gophercloud.JSONRFC1123 `json:"Date"` + DeleteAt gophercloud.JSONUnix `json:"X-Delete-At"` + ETag string `json:"Etag"` + LastModified gophercloud.JSONRFC1123 `json:"Last-Modified"` + ObjectManifest string `json:"X-Object-Manifest"` + StaticLargeObject bool `json:"X-Static-Large-Object"` + TransID string `json:"X-Trans-Id"` +} + +func (h *DownloadHeader) UnmarshalJSON(b []byte) error { + type tmp DownloadHeader + var hTmp *struct { + tmp + ContentLength string `json:"Content-Length"` + } + err := json.Unmarshal(b, &hTmp) + if err != nil { + return err + } + + *h = DownloadHeader(hTmp.tmp) + + switch hTmp.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(hTmp.ContentLength, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// DownloadResult is a *http.Response that is returned from a call to the Download function. +type DownloadResult struct { + gophercloud.HeaderResult + Body io.ReadCloser +} + +// Extract will return a struct of headers returned from a call to Download. To obtain +// a map of headers, call the ExtractHeader method on the DownloadResult. +func (r DownloadResult) Extract() (*DownloadHeader, error) { + var s *DownloadHeader + err := r.ExtractInto(&s) + return s, err +} + +// ExtractContent is a function that takes a DownloadResult's io.Reader body +// and reads all available data into a slice of bytes. Please be aware that due +// the nature of io.Reader is forward-only - meaning that it can only be read +// once and not rewound. You can recreate a reader from the output of this +// function by using bytes.NewReader(downloadBytes) +func (r *DownloadResult) ExtractContent() ([]byte, error) { + if r.Err != nil { + return nil, r.Err + } + defer r.Body.Close() + body, err := ioutil.ReadAll(r.Body) + if err != nil { + return nil, err + } + r.Body.Close() + return body, nil +} + +// GetHeader represents the headers returned in the response from a Get request. +type GetHeader struct { + ContentDisposition string `json:"Content-Disposition"` + ContentEncoding string `json:"Content-Encoding"` + ContentLength int64 `json:"Content-Length"` + ContentType string `json:"Content-Type"` + Date gophercloud.JSONRFC1123 `json:"Date"` + DeleteAt gophercloud.JSONUnix `json:"X-Delete-At"` + ETag string `json:"Etag"` + LastModified gophercloud.JSONRFC1123 `json:"Last-Modified"` + ObjectManifest string `json:"X-Object-Manifest"` + StaticLargeObject bool `json:"X-Static-Large-Object"` + TransID string `json:"X-Trans-Id"` +} + +func (h *GetHeader) UnmarshalJSON(b []byte) error { + type tmp GetHeader + var hTmp *struct { + tmp + ContentLength string `json:"Content-Length"` + } + err := json.Unmarshal(b, &hTmp) + if err != nil { + return err + } + + *h = GetHeader(hTmp.tmp) + + switch hTmp.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(hTmp.ContentLength, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// GetResult is a *http.Response that is returned from a call to the Get function. +type GetResult struct { + gophercloud.HeaderResult +} + +// Extract will return a struct of headers returned from a call to Get. To obtain +// a map of headers, call the ExtractHeader method on the GetResult. +func (r GetResult) Extract() (*GetHeader, error) { + var s *GetHeader + err := r.ExtractInto(&s) + return s, err +} + +// ExtractMetadata is a function that takes a GetResult (of type *http.Response) +// and returns the custom metadata associated with the object. +func (r GetResult) ExtractMetadata() (map[string]string, error) { + if r.Err != nil { + return nil, r.Err + } + metadata := make(map[string]string) + for k, v := range r.Header { + if strings.HasPrefix(k, "X-Object-Meta-") { + key := strings.TrimPrefix(k, "X-Object-Meta-") + metadata[key] = v[0] + } + } + return metadata, nil +} + +// CreateHeader represents the headers returned in the response from a Create request. +type CreateHeader struct { + ContentLength int64 `json:"Content-Length"` + ContentType string `json:"Content-Type"` + Date gophercloud.JSONRFC1123 `json:"Date"` + ETag string `json:"Etag"` + LastModified gophercloud.JSONRFC1123 `json:"Last-Modified"` + TransID string `json:"X-Trans-Id"` +} + +func (h *CreateHeader) UnmarshalJSON(b []byte) error { + type tmp CreateHeader + var hTmp *struct { + tmp + ContentLength string `json:"Content-Length"` + } + err := json.Unmarshal(b, &hTmp) + if err != nil { + return err + } + + *h = CreateHeader(hTmp.tmp) + + switch hTmp.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(hTmp.ContentLength, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// CreateResult represents the result of a create operation. +type CreateResult struct { + checksum string + gophercloud.HeaderResult +} + +// Extract will return a struct of headers returned from a call to Create. To obtain +// a map of headers, call the ExtractHeader method on the CreateResult. +func (r CreateResult) Extract() (*CreateHeader, error) { + //if r.Header.Get("ETag") != fmt.Sprintf("%x", localChecksum) { + // return nil, ErrWrongChecksum{} + //} + var s *CreateHeader + err := r.ExtractInto(&s) + return s, err +} + +// UpdateHeader represents the headers returned in the response from a Update request. +type UpdateHeader struct { + ContentLength int64 `json:"Content-Length"` + ContentType string `json:"Content-Type"` + Date gophercloud.JSONRFC1123 `json:"Date"` + TransID string `json:"X-Trans-Id"` +} + +func (h *UpdateHeader) UnmarshalJSON(b []byte) error { + type tmp UpdateHeader + var hTmp *struct { + tmp + ContentLength string `json:"Content-Length"` + } + err := json.Unmarshal(b, &hTmp) + if err != nil { + return err + } + + *h = UpdateHeader(hTmp.tmp) + + switch hTmp.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(hTmp.ContentLength, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// UpdateResult represents the result of an update operation. +type UpdateResult struct { + gophercloud.HeaderResult +} + +// Extract will return a struct of headers returned from a call to Update. To obtain +// a map of headers, call the ExtractHeader method on the UpdateResult. +func (r UpdateResult) Extract() (*UpdateHeader, error) { + var s *UpdateHeader + err := r.ExtractInto(&s) + return s, err +} + +// DeleteHeader represents the headers returned in the response from a Delete request. +type DeleteHeader struct { + ContentLength int64 `json:"Content-Length"` + ContentType string `json:"Content-Type"` + Date gophercloud.JSONRFC1123 `json:"Date"` + TransID string `json:"X-Trans-Id"` +} + +func (h *DeleteHeader) UnmarshalJSON(b []byte) error { + type tmp DeleteHeader + var hTmp *struct { + tmp + ContentLength string `json:"Content-Length"` + } + err := json.Unmarshal(b, &hTmp) + if err != nil { + return err + } + + *h = DeleteHeader(hTmp.tmp) + + switch hTmp.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(hTmp.ContentLength, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// DeleteResult represents the result of a delete operation. +type DeleteResult struct { + gophercloud.HeaderResult +} + +// Extract will return a struct of headers returned from a call to Delete. To obtain +// a map of headers, call the ExtractHeader method on the DeleteResult. +func (r DeleteResult) Extract() (*DeleteHeader, error) { + var s *DeleteHeader + err := r.ExtractInto(&s) + return s, err +} + +// CopyHeader represents the headers returned in the response from a Copy request. +type CopyHeader struct { + ContentLength int64 `json:"Content-Length"` + ContentType string `json:"Content-Type"` + CopiedFrom string `json:"X-Copied-From"` + CopiedFromLastModified gophercloud.JSONRFC1123 `json:"X-Copied-From-Last-Modified"` + Date gophercloud.JSONRFC1123 `json:"Date"` + ETag string `json:"Etag"` + LastModified gophercloud.JSONRFC1123 `json:"Last-Modified"` + TransID string `json:"X-Trans-Id"` +} + +func (h *CopyHeader) UnmarshalJSON(b []byte) error { + type tmp CopyHeader + var hTmp *struct { + tmp + ContentLength string `json:"Content-Length"` + } + err := json.Unmarshal(b, &hTmp) + if err != nil { + return err + } + + *h = CopyHeader(hTmp.tmp) + + switch hTmp.ContentLength { + case "": + h.ContentLength = 0 + default: + h.ContentLength, err = strconv.ParseInt(hTmp.ContentLength, 10, 64) + if err != nil { + return err + } + } + + return nil +} + +// CopyResult represents the result of a copy operation. +type CopyResult struct { + gophercloud.HeaderResult +} + +// Extract will return a struct of headers returned from a call to Copy. To obtain +// a map of headers, call the ExtractHeader method on the CopyResult. +func (r CopyResult) Extract() (*CopyHeader, error) { + var s *CopyHeader + err := r.ExtractInto(&s) + return s, err +} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/urls.go b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/urls.go similarity index 95% rename from vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/urls.go rename to vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/urls.go index d2ec62cff..b3ac304b7 100644 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/urls.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects/urls.go @@ -1,7 +1,7 @@ package objects import ( - "github.com/rackspace/gophercloud" + "github.com/gophercloud/gophercloud" ) func listURL(c *gophercloud.ServiceClient, container string) string { diff --git a/vendor/github.com/rackspace/gophercloud/CONTRIBUTING.md b/vendor/github.com/rackspace/gophercloud/CONTRIBUTING.md deleted file mode 100644 index 73c95bd82..000000000 --- a/vendor/github.com/rackspace/gophercloud/CONTRIBUTING.md +++ /dev/null @@ -1,275 +0,0 @@ -# Contributing to gophercloud - -- [Getting started](#getting-started) -- [Tests](#tests) -- [Style guide](#basic-style-guide) -- [5 ways to get involved](#5-ways-to-get-involved) - -## Setting up your git workspace - -As a contributor you will need to setup your workspace in a slightly different -way than just downloading it. Here are the basic installation instructions: - -1. Configure your `$GOPATH` and run `go get` as described in the main -[README](/README.md#how-to-install) but add `-tags "fixtures acceptance"` to -get dependencies for unit and acceptance tests. - -2. Move into the directory that houses your local repository: - - ```bash - cd ${GOPATH}/src/github.com/rackspace/gophercloud - ``` - -3. Fork the `rackspace/gophercloud` repository and update your remote refs. You -will need to rename the `origin` remote branch to `upstream`, and add your -fork as `origin` instead: - - ```bash - git remote rename origin upstream - git remote add origin git@github.com//gophercloud - ``` - -4. Checkout the latest development branch: - - ```bash - git checkout master - ``` - -5. If you're working on something (discussed more in detail below), you will -need to checkout a new feature branch: - - ```bash - git checkout -b my-new-feature - ``` - -Another thing to bear in mind is that you will need to add a few extra -environment variables for acceptance tests - this is documented in our -[acceptance tests readme](/acceptance). - -## Tests - -When working on a new or existing feature, testing will be the backbone of your -work since it helps uncover and prevent regressions in the codebase. There are -two types of test we use in gophercloud: unit tests and acceptance tests, which -are both described below. - -### Unit tests - -Unit tests are the fine-grained tests that establish and ensure the behaviour -of individual units of functionality. We usually test on an -operation-by-operation basis (an operation typically being an API action) with -the use of mocking to set up explicit expectations. Each operation will set up -its HTTP response expectation, and then test how the system responds when fed -this controlled, pre-determined input. - -To make life easier, we've introduced a bunch of test helpers to simplify the -process of testing expectations with assertions: - -```go -import ( - "testing" - - "github.com/rackspace/gophercloud/testhelper" -) - -func TestSomething(t *testing.T) { - result, err := Operation() - - testhelper.AssertEquals(t, "foo", result.Bar) - testhelper.AssertNoErr(t, err) -} - -func TestSomethingElse(t *testing.T) { - testhelper.CheckEquals(t, "expected", "actual") -} -``` - -`AssertEquals` and `AssertNoErr` will throw a fatal error if a value does not -match an expected value or if an error has been declared, respectively. You can -also use `CheckEquals` and `CheckNoErr` for the same purpose; the only difference -being that `t.Errorf` is raised rather than `t.Fatalf`. - -Here is a truncated example of mocked HTTP responses: - -```go -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestGet(t *testing.T) { - // Setup the HTTP request multiplexer and server - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - // Test we're using the correct HTTP method - th.TestMethod(t, r, "GET") - - // Test we're setting the auth token - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - // Set the appropriate headers for our mocked response - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - // Set the HTTP body - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "name": "private-network", - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - } -} - `) - }) - - // Call our API operation - network, err := Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - - // Assert no errors and equality - th.AssertNoErr(t, err) - th.AssertEquals(t, n.Status, "ACTIVE") -} -``` - -### Acceptance tests - -As we've already mentioned, unit tests have a very narrow and confined focus - -they test small units of behaviour. Acceptance tests on the other hand have a -far larger scope: they are fully functional tests that test the entire API of a -service in one fell swoop. They don't care about unit isolation or mocking -expectations, they instead do a full run-through and consequently test how the -entire system _integrates_ together. When an API satisfies expectations, it -proves by default that the requirements for a contract have been met. - -Please be aware that acceptance tests will hit a live API - and may incur -service charges from your provider. Although most tests handle their own -teardown procedures, it is always worth manually checking that resources are -deleted after the test suite finishes. - -### Running tests - -To run all tests: - -```bash -go test -tags fixtures ./... -``` - -To run all tests with verbose output: - -```bash -go test -v -tags fixtures ./... -``` - -To run tests that match certain [build tags](): - -```bash -go test -tags "fixtures foo bar" ./... -``` - -To run tests for a particular sub-package: - -```bash -cd ./path/to/package && go test -tags fixtures . -``` - -## Basic style guide - -We follow the standard formatting recommendations and language idioms set out -in the [Effective Go](https://golang.org/doc/effective_go.html) guide. It's -definitely worth reading - but the relevant sections are -[formatting](https://golang.org/doc/effective_go.html#formatting) -and [names](https://golang.org/doc/effective_go.html#names). - -## 5 ways to get involved - -There are five main ways you can get involved in our open-source project, and -each is described briefly below. Once you've made up your mind and decided on -your fix, you will need to follow the same basic steps that all submissions are -required to adhere to: - -1. [fork](https://help.github.com/articles/fork-a-repo/) the `rackspace/gophercloud` repository -2. checkout a [new branch](https://github.com/Kunena/Kunena-Forum/wiki/Create-a-new-branch-with-git-and-manage-branches) -3. submit your branch as a [pull request](https://help.github.com/articles/creating-a-pull-request/) - -### 1. Providing feedback - -On of the easiest ways to get readily involved in our project is to let us know -about your experiences using our SDK. Feedback like this is incredibly useful -to us, because it allows us to refine and change features based on what our -users want and expect of us. There are a bunch of ways to get in contact! You -can [ping us](https://developer.rackspace.com/support/) via e-mail, talk to us on irc -(#rackspace-dev on freenode), [tweet us](https://twitter.com/rackspace), or -submit an issue on our [bug tracker](/issues). Things you might like to tell us -are: - -* how easy was it to start using our SDK? -* did it meet your expectations? If not, why not? -* did our documentation help or hinder you? -* what could we improve in general? - -### 2. Fixing bugs - -If you want to start fixing open bugs, we'd really appreciate that! Bug fixing -is central to any project. The best way to get started is by heading to our -[bug tracker](https://github.com/rackspace/gophercloud/issues) and finding open -bugs that you think nobody is working on. It might be useful to comment on the -thread to see the current state of the issue and if anybody has made any -breakthroughs on it so far. - -### 3. Improving documentation - -We have three forms of documentation: - -* short README documents that briefly introduce a topic -* reference documentation on [godoc.org](http://godoc.org) that is automatically -generated from source code comments -* user documentation on our [homepage](http://gophercloud.io) that includes -getting started guides, installation guides and code samples - -If you feel that a certain section could be improved - whether it's to clarify -ambiguity, correct a technical mistake, or to fix a grammatical error - please -feel entitled to do so! We welcome doc pull requests with the same childlike -enthusiasm as any other contribution! - -### 4. Optimizing existing features - -If you would like to improve or optimize an existing feature, please be aware -that we adhere to [semantic versioning](http://semver.org) - which means that -we cannot introduce breaking changes to the API without a major version change -(v1.x -> v2.x). Making that leap is a big step, so we encourage contributors to -refactor rather than rewrite. Running tests will prevent regression and avoid -the possibility of breaking somebody's current implementation. - -Another tip is to keep the focus of your work as small as possible - try not to -introduce a change that affects lots and lots of files because it introduces -added risk and increases the cognitive load on the reviewers checking your -work. Change-sets which are easily understood and will not negatively impact -users are more likely to be integrated quickly. - -Lastly, if you're seeking to optimize a particular operation, you should try to -demonstrate a negative performance impact - perhaps using go's inbuilt -[benchmark capabilities](http://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go). - -### 5. Working on a new feature - -If you've found something we've left out, definitely feel free to start work on -introducing that feature. It's always useful to open an issue or submit a pull -request early on to indicate your intent to a core contributor - this enables -quick/early feedback and can help steer you in the right direction by avoiding -known issues. It might also help you avoid losing time implementing something -that might not ever work. One tip is to prefix your Pull Request issue title -with [wip] - then people know it's a work in progress. - -You must ensure that all of your work is well tested - both in terms of unit -and acceptance tests. Untested code will not be merged because it introduces -too much of a risk to end-users. - -Happy hacking! diff --git a/vendor/github.com/rackspace/gophercloud/CONTRIBUTORS.md b/vendor/github.com/rackspace/gophercloud/CONTRIBUTORS.md deleted file mode 100644 index 63beb30b2..000000000 --- a/vendor/github.com/rackspace/gophercloud/CONTRIBUTORS.md +++ /dev/null @@ -1,13 +0,0 @@ -Contributors -============ - -| Name | Email | -| ---- | ----- | -| Samuel A. Falvo II | -| Glen Campbell | -| Jesse Noller | -| Jon Perritt | -| Ash Wilson | -| Jamie Hannaford | -| Don Schenck | don.schenck@rackspace.com> -| Joe Topjian | diff --git a/vendor/github.com/rackspace/gophercloud/LICENSE b/vendor/github.com/rackspace/gophercloud/LICENSE deleted file mode 100644 index fbbbc9e4c..000000000 --- a/vendor/github.com/rackspace/gophercloud/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Copyright 2012-2013 Rackspace, Inc. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software distributed -under the License is distributed on an "AS IS" BASIS, 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. - ------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/vendor/github.com/rackspace/gophercloud/README.md b/vendor/github.com/rackspace/gophercloud/README.md deleted file mode 100644 index 4b0042b3b..000000000 --- a/vendor/github.com/rackspace/gophercloud/README.md +++ /dev/null @@ -1,160 +0,0 @@ -# Gophercloud: an OpenStack SDK for Go -[![Build Status](https://travis-ci.org/rackspace/gophercloud.svg?branch=master)](https://travis-ci.org/rackspace/gophercloud) [![Coverage Status](https://coveralls.io/repos/rackspace/gophercloud/badge.png)](https://coveralls.io/r/rackspace/gophercloud) - -Gophercloud is a flexible SDK that allows you to consume and work with OpenStack -clouds in a simple and idiomatic way using golang. Many services are supported, -including Compute, Block Storage, Object Storage, Networking, and Identity. -Each service API is backed with getting started guides, code samples, reference -documentation, unit tests and acceptance tests. - -## Useful links - -* [Gophercloud homepage](http://gophercloud.io) -* [Reference documentation](http://godoc.org/github.com/rackspace/gophercloud) -* [Getting started guides](http://gophercloud.io/docs) -* [Effective Go](https://golang.org/doc/effective_go.html) - -## How to install - -Before installing, you need to ensure that your [GOPATH environment variable](https://golang.org/doc/code.html#GOPATH) -is pointing to an appropriate directory where you want to install Gophercloud: - -```bash -mkdir $HOME/go -export GOPATH=$HOME/go -``` - -To protect yourself against changes in your dependencies, we highly recommend choosing a -[dependency management solution](https://github.com/golang/go/wiki/PackageManagementTools) for -your projects, such as [godep](https://github.com/tools/godep). Once this is set up, you can install -Gophercloud as a dependency like so: - -```bash -go get github.com/rackspace/gophercloud - -# Edit your code to import relevant packages from "github.com/rackspace/gophercloud" - -godep save ./... -``` - -This will install all the source files you need into a `Godeps/_workspace` directory, which is -referenceable from your own source files when you use the `godep go` command. - -## Getting started - -### Credentials - -Because you'll be hitting an API, you will need to retrieve your OpenStack -credentials and either store them as environment variables or in your local Go -files. The first method is recommended because it decouples credential -information from source code, allowing you to push the latter to your version -control system without any security risk. - -You will need to retrieve the following: - -* username -* password -* tenant name or tenant ID -* a valid Keystone identity URL - -For users that have the OpenStack dashboard installed, there's a shortcut. If -you visit the `project/access_and_security` path in Horizon and click on the -"Download OpenStack RC File" button at the top right hand corner, you will -download a bash file that exports all of your access details to environment -variables. To execute the file, run `source admin-openrc.sh` and you will be -prompted for your password. - -### Authentication - -Once you have access to your credentials, you can begin plugging them into -Gophercloud. The next step is authentication, and this is handled by a base -"Provider" struct. To get one, you can either pass in your credentials -explicitly, or tell Gophercloud to use environment variables: - -```go -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" - "github.com/rackspace/gophercloud/openstack/utils" -) - -// Option 1: Pass in the values yourself -opts := gophercloud.AuthOptions{ - IdentityEndpoint: "https://my-openstack.com:5000/v2.0", - Username: "{username}", - Password: "{password}", - TenantID: "{tenant_id}", -} - -// Option 2: Use a utility function to retrieve all your environment variables -opts, err := openstack.AuthOptionsFromEnv() -``` - -Once you have the `opts` variable, you can pass it in and get back a -`ProviderClient` struct: - -```go -provider, err := openstack.AuthenticatedClient(opts) -``` - -The `ProviderClient` is the top-level client that all of your OpenStack services -derive from. The provider contains all of the authentication details that allow -your Go code to access the API - such as the base URL and token ID. - -### Provision a server - -Once we have a base Provider, we inject it as a dependency into each OpenStack -service. In order to work with the Compute API, we need a Compute service -client; which can be created like so: - -```go -client, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), -}) -``` - -We then use this `client` for any Compute API operation we want. In our case, -we want to provision a new server - so we invoke the `Create` method and pass -in the flavor ID (hardware specification) and image ID (operating system) we're -interested in: - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -server, err := servers.Create(client, servers.CreateOpts{ - Name: "My new server!", - FlavorRef: "flavor_id", - ImageRef: "image_id", -}).Extract() -``` - -If you are unsure about what images and flavors are, you can read our [Compute -Getting Started guide](http://gophercloud.io/docs/compute). The above code -sample creates a new server with the parameters, and embodies the new resource -in the `server` variable (a -[`servers.Server`](http://godoc.org/github.com/rackspace/gophercloud) struct). - -### Next steps - -Cool! You've handled authentication, got your `ProviderClient` and provisioned -a new server. You're now ready to use more OpenStack services. - -* [Getting started with Compute](http://gophercloud.io/docs/compute) -* [Getting started with Object Storage](http://gophercloud.io/docs/object-storage) -* [Getting started with Networking](http://gophercloud.io/docs/networking) -* [Getting started with Block Storage](http://gophercloud.io/docs/block-storage) -* [Getting started with Identity](http://gophercloud.io/docs/identity) - -## Contributing - -Engaging the community and lowering barriers for contributors is something we -care a lot about. For this reason, we've taken the time to write a [contributing -guide](./CONTRIBUTING.md) for folks interested in getting involved in our project. -If you're not sure how you can get involved, feel free to submit an issue or -[contact us](https://developer.rackspace.com/support/). You don't need to be a -Go expert - all members of the community are welcome! - -## Help and feedback - -If you're struggling with something or have spotted a potential bug, feel free -to submit an issue to our [bug tracker](/issues) or [contact us directly](https://developer.rackspace.com/support/). diff --git a/vendor/github.com/rackspace/gophercloud/UPGRADING.md b/vendor/github.com/rackspace/gophercloud/UPGRADING.md deleted file mode 100644 index 76a94d570..000000000 --- a/vendor/github.com/rackspace/gophercloud/UPGRADING.md +++ /dev/null @@ -1,338 +0,0 @@ -# Upgrading to v1.0.0 - -With the arrival of this new major version increment, the unfortunate news is -that breaking changes have been introduced to existing services. The API -has been completely rewritten from the ground up to make the library more -extensible, maintainable and easy-to-use. - -Below we've compiled upgrade instructions for the various services that -existed before. If you have a specific issue that is not addressed below, -please [submit an issue](/issues/new) or -[e-mail our support team](https://developer.rackspace.com/support/). - -* [Authentication](#authentication) -* [Servers](#servers) - * [List servers](#list-servers) - * [Get server details](#get-server-details) - * [Create server](#create-server) - * [Resize server](#resize-server) - * [Reboot server](#reboot-server) - * [Update server](#update-server) - * [Rebuild server](#rebuild-server) - * [Change admin password](#change-admin-password) - * [Delete server](#delete-server) - * [Rescue server](#rescue-server) -* [Images and flavors](#images-and-flavors) - * [List images](#list-images) - * [List flavors](#list-flavors) - * [Create/delete image](#createdelete-image) -* [Other](#other) - * [List keypairs](#list-keypairs) - * [Create/delete keypair](#createdelete-keypair) - * [List IP addresses](#list-ip-addresses) - -# Authentication - -One of the major differences that this release introduces is the level of -sub-packaging to differentiate between services and providers. You now have -the option of authenticating with OpenStack and other providers (like Rackspace). - -To authenticate with a vanilla OpenStack installation, you can either specify -your credentials like this: - -```go -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" -) - -opts := gophercloud.AuthOptions{ - IdentityEndpoint: "https://my-openstack.com:5000/v2.0", - Username: "{username}", - Password: "{password}", - TenantID: "{tenant_id}", -} -``` - -Or have them pulled in through environment variables, like this: - -```go -opts, err := openstack.AuthOptionsFromEnv() -``` - -Once you have your `AuthOptions` struct, you pass it in to get back a `Provider`, -like so: - -```go -provider, err := openstack.AuthenticatedClient(opts) -``` - -This provider is the top-level structure that all services are created from. - -# Servers - -Before you can interact with the Compute API, you need to retrieve a -`gophercloud.ServiceClient`. To do this: - -```go -// Define your region, etc. -opts := gophercloud.EndpointOpts{Region: "RegionOne"} - -client, err := openstack.NewComputeV2(provider, opts) -``` - -## List servers - -All operations that involve API collections (servers, flavors, images) now use -the `pagination.Pager` interface. This interface represents paginated entities -that can be iterated over. - -Once you have a Pager, you can then pass a callback function into its `EachPage` -method, and this will allow you to traverse over the collection and execute -arbitrary functionality. So, an example with list servers: - -```go -import ( - "fmt" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" -) - -// We have the option of filtering the server list. If we want the full -// collection, leave it as an empty struct or nil -opts := servers.ListOpts{Name: "server_1"} - -// Retrieve a pager (i.e. a paginated collection) -pager := servers.List(client, opts) - -// Define an anonymous function to be executed on each page's iteration -err := pager.EachPage(func(page pagination.Page) (bool, error) { - serverList, err := servers.ExtractServers(page) - - // `s' will be a servers.Server struct - for _, s := range serverList { - fmt.Printf("We have a server. ID=%s, Name=%s", s.ID, s.Name) - } -}) -``` - -## Get server details - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -// Get the HTTP result -response := servers.Get(client, "server_id") - -// Extract a Server struct from the response -server, err := response.Extract() -``` - -## Create server - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -// Define our options -opts := servers.CreateOpts{ - Name: "new_server", - FlavorRef: "flavorID", - ImageRef: "imageID", -} - -// Get our response -response := servers.Create(client, opts) - -// Extract -server, err := response.Extract() -``` - -## Change admin password - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -result := servers.ChangeAdminPassword(client, "server_id", "newPassword_&123") -``` - -## Resize server - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -result := servers.Resize(client, "server_id", "new_flavor_id") -``` - -## Reboot server - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -// You have a choice of two reboot methods: servers.SoftReboot or servers.HardReboot -result := servers.Reboot(client, "server_id", servers.SoftReboot) -``` - -## Update server - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -opts := servers.UpdateOpts{Name: "new_name"} - -server, err := servers.Update(client, "server_id", opts).Extract() -``` - -## Rebuild server - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -// You have the option of specifying additional options -opts := RebuildOpts{ - Name: "new_name", - AdminPass: "admin_password", - ImageID: "image_id", - Metadata: map[string]string{"owner": "me"}, -} - -result := servers.Rebuild(client, "server_id", opts) - -// You can extract a servers.Server struct from the HTTP response -server, err := result.Extract() -``` - -## Delete server - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - -response := servers.Delete(client, "server_id") -``` - -## Rescue server - -The server rescue extension for Compute is not currently supported. - -# Images and flavors - -## List images - -As with listing servers (see above), you first retrieve a Pager, and then pass -in a callback over each page: - -```go -import ( - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/openstack/compute/v2/images" -) - -// We have the option of filtering the image list. If we want the full -// collection, leave it as an empty struct -opts := images.ListOpts{ChangesSince: "2014-01-01T01:02:03Z", Name: "Ubuntu 12.04"} - -// Retrieve a pager (i.e. a paginated collection) -pager := images.List(client, opts) - -// Define an anonymous function to be executed on each page's iteration -err := pager.EachPage(func(page pagination.Page) (bool, error) { - imageList, err := images.ExtractImages(page) - - for _, i := range imageList { - // "i" will be an images.Image - } -}) -``` - -## List flavors - -```go -import ( - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/openstack/compute/v2/flavors" -) - -// We have the option of filtering the flavor list. If we want the full -// collection, leave it as an empty struct -opts := flavors.ListOpts{ChangesSince: "2014-01-01T01:02:03Z", MinRAM: 4} - -// Retrieve a pager (i.e. a paginated collection) -pager := flavors.List(client, opts) - -// Define an anonymous function to be executed on each page's iteration -err := pager.EachPage(func(page pagination.Page) (bool, error) { - flavorList, err := networks.ExtractFlavors(page) - - for _, f := range flavorList { - // "f" will be a flavors.Flavor - } -}) -``` - -## Create/delete image - -Image management has been shifted to Glance, but unfortunately this service is -not supported as of yet. You can, however, list Compute images like so: - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/images" - -// Retrieve a pager (i.e. a paginated collection) -pager := images.List(client, opts) - -// Define an anonymous function to be executed on each page's iteration -err := pager.EachPage(func(page pagination.Page) (bool, error) { - imageList, err := images.ExtractImages(page) - - for _, i := range imageList { - // "i" will be an images.Image - } -}) -``` - -# Other - -## List keypairs - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" - -// Retrieve a pager (i.e. a paginated collection) -pager := keypairs.List(client, opts) - -// Define an anonymous function to be executed on each page's iteration -err := pager.EachPage(func(page pagination.Page) (bool, error) { - keyList, err := keypairs.ExtractKeyPairs(page) - - for _, k := range keyList { - // "k" will be a keypairs.KeyPair - } -}) -``` - -## Create/delete keypairs - -To create a new keypair, you need to specify its name and, optionally, a -pregenerated OpenSSH-formatted public key. - -```go -import "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" - -opts := keypairs.CreateOpts{ - Name: "new_key", - PublicKey: "...", -} - -response := keypairs.Create(client, opts) - -key, err := response.Extract() -``` - -To delete an existing keypair: - -```go -response := keypairs.Delete(client, "keypair_id") -``` - -## List IP addresses - -This operation is not currently supported. diff --git a/vendor/github.com/rackspace/gophercloud/auth_options.go b/vendor/github.com/rackspace/gophercloud/auth_options.go deleted file mode 100644 index 07ace1366..000000000 --- a/vendor/github.com/rackspace/gophercloud/auth_options.go +++ /dev/null @@ -1,55 +0,0 @@ -package gophercloud - -/* -AuthOptions stores information needed to authenticate to an OpenStack cluster. -You can populate one manually, or use a provider's AuthOptionsFromEnv() function -to read relevant information from the standard environment variables. Pass one -to a provider's AuthenticatedClient function to authenticate and obtain a -ProviderClient representing an active session on that provider. - -Its fields are the union of those recognized by each identity implementation and -provider. -*/ -type AuthOptions struct { - // IdentityEndpoint specifies the HTTP endpoint that is required to work with - // the Identity API of the appropriate version. While it's ultimately needed by - // all of the identity services, it will often be populated by a provider-level - // function. - IdentityEndpoint string - - // Username is required if using Identity V2 API. Consult with your provider's - // control panel to discover your account's username. In Identity V3, either - // UserID or a combination of Username and DomainID or DomainName are needed. - Username, UserID string - - // Exactly one of Password or APIKey is required for the Identity V2 and V3 - // APIs. Consult with your provider's control panel to discover your account's - // preferred method of authentication. - Password, APIKey string - - // At most one of DomainID and DomainName must be provided if using Username - // with Identity V3. Otherwise, either are optional. - DomainID, DomainName string - - // The TenantID and TenantName fields are optional for the Identity V2 API. - // Some providers allow you to specify a TenantName instead of the TenantId. - // Some require both. Your provider's authentication policies will determine - // how these fields influence authentication. - TenantID, TenantName string - - // AllowReauth should be set to true if you grant permission for Gophercloud to - // cache your credentials in memory, and to allow Gophercloud to attempt to - // re-authenticate automatically if/when your token expires. If you set it to - // false, it will not cache these settings, but re-authentication will not be - // possible. This setting defaults to false. - // - // NOTE: The reauth function will try to re-authenticate endlessly if left unchecked. - // The way to limit the number of attempts is to provide a custom HTTP client to the provider client - // and provide a transport that implements the RoundTripper interface and stores the number of failed retries. - // For an example of this, see here: https://github.com/rackspace/rack/blob/1.0.0/auth/clients.go#L311 - AllowReauth bool - - // TokenID allows users to authenticate (possibly as another user) with an - // authentication token ID. - TokenID string -} diff --git a/vendor/github.com/rackspace/gophercloud/auth_results.go b/vendor/github.com/rackspace/gophercloud/auth_results.go deleted file mode 100644 index 856a23382..000000000 --- a/vendor/github.com/rackspace/gophercloud/auth_results.go +++ /dev/null @@ -1,14 +0,0 @@ -package gophercloud - -import "time" - -// AuthResults [deprecated] is a leftover type from the v0.x days. It was -// intended to describe common functionality among identity service results, but -// is not actually used anywhere. -type AuthResults interface { - // TokenID returns the token's ID value from the authentication response. - TokenID() (string, error) - - // ExpiresAt retrieves the token's expiration time. - ExpiresAt() (time.Time, error) -} diff --git a/vendor/github.com/rackspace/gophercloud/doc.go b/vendor/github.com/rackspace/gophercloud/doc.go deleted file mode 100644 index fb81a9d8f..000000000 --- a/vendor/github.com/rackspace/gophercloud/doc.go +++ /dev/null @@ -1,67 +0,0 @@ -/* -Package gophercloud provides a multi-vendor interface to OpenStack-compatible -clouds. The library has a three-level hierarchy: providers, services, and -resources. - -Provider structs represent the service providers that offer and manage a -collection of services. Examples of providers include: OpenStack, Rackspace, -HP. These are defined like so: - - opts := gophercloud.AuthOptions{ - IdentityEndpoint: "https://my-openstack.com:5000/v2.0", - Username: "{username}", - Password: "{password}", - TenantID: "{tenant_id}", - } - - provider, err := openstack.AuthenticatedClient(opts) - -Service structs are specific to a provider and handle all of the logic and -operations for a particular OpenStack service. Examples of services include: -Compute, Object Storage, Block Storage. In order to define one, you need to -pass in the parent provider, like so: - - opts := gophercloud.EndpointOpts{Region: "RegionOne"} - - client := openstack.NewComputeV2(provider, opts) - -Resource structs are the domain models that services make use of in order -to work with and represent the state of API resources: - - server, err := servers.Get(client, "{serverId}").Extract() - -Intermediate Result structs are returned for API operations, which allow -generic access to the HTTP headers, response body, and any errors associated -with the network transaction. To turn a result into a usable resource struct, -you must call the Extract method which is chained to the response, or an -Extract function from an applicable extension: - - result := servers.Get(client, "{serverId}") - - // Attempt to extract the disk configuration from the OS-DCF disk config - // extension: - config, err := diskconfig.ExtractGet(result) - -All requests that enumerate a collection return a Pager struct that is used to -iterate through the results one page at a time. Use the EachPage method on that -Pager to handle each successive Page in a closure, then use the appropriate -extraction method from that request's package to interpret that Page as a slice -of results: - - err := servers.List(client, nil).EachPage(func (page pagination.Page) (bool, error) { - s, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - - // Handle the []servers.Server slice. - - // Return "false" or an error to prematurely stop fetching new pages. - return true, nil - }) - -This top-level package contains utility functions and data types that are used -throughout the provider and service packages. Of particular note for end users -are the AuthOptions and EndpointOpts structs. -*/ -package gophercloud diff --git a/vendor/github.com/rackspace/gophercloud/endpoint_search.go b/vendor/github.com/rackspace/gophercloud/endpoint_search.go deleted file mode 100644 index 518943121..000000000 --- a/vendor/github.com/rackspace/gophercloud/endpoint_search.go +++ /dev/null @@ -1,92 +0,0 @@ -package gophercloud - -import "errors" - -var ( - // ErrServiceNotFound is returned when no service in a service catalog matches - // the provided EndpointOpts. This is generally returned by provider service - // factory methods like "NewComputeV2()" and can mean that a service is not - // enabled for your account. - ErrServiceNotFound = errors.New("No suitable service could be found in the service catalog.") - - // ErrEndpointNotFound is returned when no available endpoints match the - // provided EndpointOpts. This is also generally returned by provider service - // factory methods, and usually indicates that a region was specified - // incorrectly. - ErrEndpointNotFound = errors.New("No suitable endpoint could be found in the service catalog.") -) - -// Availability indicates to whom a specific service endpoint is accessible: -// the internet at large, internal networks only, or only to administrators. -// Different identity services use different terminology for these. Identity v2 -// lists them as different kinds of URLs within the service catalog ("adminURL", -// "internalURL", and "publicURL"), while v3 lists them as "Interfaces" in an -// endpoint's response. -type Availability string - -const ( - // AvailabilityAdmin indicates that an endpoint is only available to - // administrators. - AvailabilityAdmin Availability = "admin" - - // AvailabilityPublic indicates that an endpoint is available to everyone on - // the internet. - AvailabilityPublic Availability = "public" - - // AvailabilityInternal indicates that an endpoint is only available within - // the cluster's internal network. - AvailabilityInternal Availability = "internal" -) - -// EndpointOpts specifies search criteria used by queries against an -// OpenStack service catalog. The options must contain enough information to -// unambiguously identify one, and only one, endpoint within the catalog. -// -// Usually, these are passed to service client factory functions in a provider -// package, like "rackspace.NewComputeV2()". -type EndpointOpts struct { - // Type [required] is the service type for the client (e.g., "compute", - // "object-store"). Generally, this will be supplied by the service client - // function, but a user-given value will be honored if provided. - Type string - - // Name [optional] is the service name for the client (e.g., "nova") as it - // appears in the service catalog. Services can have the same Type but a - // different Name, which is why both Type and Name are sometimes needed. - Name string - - // Region [required] is the geographic region in which the endpoint resides, - // generally specifying which datacenter should house your resources. - // Required only for services that span multiple regions. - Region string - - // Availability [optional] is the visibility of the endpoint to be returned. - // Valid types include the constants AvailabilityPublic, AvailabilityInternal, - // or AvailabilityAdmin from this package. - // - // Availability is not required, and defaults to AvailabilityPublic. Not all - // providers or services offer all Availability options. - Availability Availability -} - -/* -EndpointLocator is an internal function to be used by provider implementations. - -It provides an implementation that locates a single endpoint from a service -catalog for a specific ProviderClient based on user-provided EndpointOpts. The -provider then uses it to discover related ServiceClients. -*/ -type EndpointLocator func(EndpointOpts) (string, error) - -// ApplyDefaults is an internal method to be used by provider implementations. -// -// It sets EndpointOpts fields if not already set, including a default type. -// Currently, EndpointOpts.Availability defaults to the public endpoint. -func (eo *EndpointOpts) ApplyDefaults(t string) { - if eo.Type == "" { - eo.Type = t - } - if eo.Availability == "" { - eo.Availability = AvailabilityPublic - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/auth_env.go b/vendor/github.com/rackspace/gophercloud/openstack/auth_env.go deleted file mode 100644 index 2d226d609..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/auth_env.go +++ /dev/null @@ -1,61 +0,0 @@ -package openstack - -import ( - "fmt" - "os" - - "github.com/rackspace/gophercloud" -) - -var nilOptions = gophercloud.AuthOptions{} - -// ErrNoAuthUrl, ErrNoUsername, and ErrNoPassword errors indicate of the required OS_AUTH_URL, OS_USERNAME, or OS_PASSWORD -// environment variables, respectively, remain undefined. See the AuthOptions() function for more details. -var ( - ErrNoAuthURL = fmt.Errorf("Environment variable OS_AUTH_URL needs to be set.") - ErrNoUsername = fmt.Errorf("Environment variable OS_USERNAME, OS_USERID, or OS_TOKEN needs to be set.") - ErrNoPassword = fmt.Errorf("Environment variable OS_PASSWORD or OS_TOKEN needs to be set.") -) - -// AuthOptionsFromEnv fills out an AuthOptions structure from the environment -// variables: OS_AUTH_URL, OS_USERNAME, OS_USERID, OS_PASSWORD, OS_TENANT_ID, -// OS_TENANT_NAME, OS_DOMAIN_ID, OS_DOMAIN_NAME, OS_TOKEN. It checks that -// (1) OS_AUTH_URL is set, (2) OS_USERNAME, OS_USERID, or OS_TOKEN is set, -// (3) OS_PASSWORD or OS_TOKEN is set. -func AuthOptionsFromEnv() (gophercloud.AuthOptions, error) { - authURL := os.Getenv("OS_AUTH_URL") - username := os.Getenv("OS_USERNAME") - userID := os.Getenv("OS_USERID") - password := os.Getenv("OS_PASSWORD") - tenantID := os.Getenv("OS_TENANT_ID") - tenantName := os.Getenv("OS_TENANT_NAME") - domainID := os.Getenv("OS_DOMAIN_ID") - domainName := os.Getenv("OS_DOMAIN_NAME") - tokenID := os.Getenv("OS_TOKEN") - - if authURL == "" { - return nilOptions, ErrNoAuthURL - } - - if username == "" && userID == "" && tokenID == "" { - return nilOptions, ErrNoUsername - } - - if password == "" && tokenID == "" { - return nilOptions, ErrNoPassword - } - - ao := gophercloud.AuthOptions{ - IdentityEndpoint: authURL, - UserID: userID, - Username: username, - Password: password, - TenantID: tenantID, - TenantName: tenantName, - DomainID: domainID, - DomainName: domainName, - TokenID: tokenID, - } - - return ao, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/doc.go deleted file mode 100644 index 307b8b12d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package volumes provides information and interaction with volumes in the -// OpenStack Block Storage service. A volume is a detachable block storage -// device, akin to a USB hard drive. It can only be attached to one instance at -// a time. -package volumes diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/requests.go deleted file mode 100644 index 3e9243ac4..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/requests.go +++ /dev/null @@ -1,236 +0,0 @@ -package volumes - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// CreateOptsBuilder allows extensions to add additional parameters to the -// Create request. -type CreateOptsBuilder interface { - ToVolumeCreateMap() (map[string]interface{}, error) -} - -// CreateOpts contains options for creating a Volume. This object is passed to -// the volumes.Create function. For more information about these parameters, -// see the Volume object. -type CreateOpts struct { - // OPTIONAL - Availability string - // OPTIONAL - Description string - // OPTIONAL - Metadata map[string]string - // OPTIONAL - Name string - // REQUIRED - Size int - // OPTIONAL - SnapshotID, SourceVolID, ImageID string - // OPTIONAL - VolumeType string -} - -// ToVolumeCreateMap assembles a request body based on the contents of a -// CreateOpts. -func (opts CreateOpts) ToVolumeCreateMap() (map[string]interface{}, error) { - v := make(map[string]interface{}) - - if opts.Size == 0 { - return nil, fmt.Errorf("Required CreateOpts field 'Size' not set.") - } - v["size"] = opts.Size - - if opts.Availability != "" { - v["availability_zone"] = opts.Availability - } - if opts.Description != "" { - v["display_description"] = opts.Description - } - if opts.ImageID != "" { - v["imageRef"] = opts.ImageID - } - if opts.Metadata != nil { - v["metadata"] = opts.Metadata - } - if opts.Name != "" { - v["display_name"] = opts.Name - } - if opts.SourceVolID != "" { - v["source_volid"] = opts.SourceVolID - } - if opts.SnapshotID != "" { - v["snapshot_id"] = opts.SnapshotID - } - if opts.VolumeType != "" { - v["volume_type"] = opts.VolumeType - } - - return map[string]interface{}{"volume": v}, nil -} - -// Create will create a new Volume based on the values in CreateOpts. To extract -// the Volume object from the response, call the Extract method on the -// CreateResult. -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToVolumeCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Post(createURL(client), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 201}, - }) - return res -} - -// Delete will delete the existing Volume with the provided ID. -func Delete(client *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = client.Delete(deleteURL(client, id), nil) - return res -} - -// Get retrieves the Volume with the provided ID. To extract the Volume object -// from the response, call the Extract method on the GetResult. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, id), &res.Body, nil) - return res -} - -// ListOptsBuilder allows extensions to add additional parameters to the List -// request. -type ListOptsBuilder interface { - ToVolumeListQuery() (string, error) -} - -// ListOpts holds options for listing Volumes. It is passed to the volumes.List -// function. -type ListOpts struct { - // admin-only option. Set it to true to see all tenant volumes. - AllTenants bool `q:"all_tenants"` - // List only volumes that contain Metadata. - Metadata map[string]string `q:"metadata"` - // List only volumes that have Name as the display name. - Name string `q:"name"` - // List only volumes that have a status of Status. - Status string `q:"status"` -} - -// ToVolumeListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToVolumeListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns Volumes optionally limited by the conditions provided in ListOpts. -func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listURL(client) - if opts != nil { - query, err := opts.ToVolumeListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - createPage := func(r pagination.PageResult) pagination.Page { - return ListResult{pagination.SinglePageBase(r)} - } - - return pagination.NewPager(client, url, createPage) -} - -// UpdateOptsBuilder allows extensions to add additional parameters to the -// Update request. -type UpdateOptsBuilder interface { - ToVolumeUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts contain options for updating an existing Volume. This object is passed -// to the volumes.Update function. For more information about the parameters, see -// the Volume object. -type UpdateOpts struct { - // OPTIONAL - Name string - // OPTIONAL - Description string - // OPTIONAL - Metadata map[string]string -} - -// ToVolumeUpdateMap assembles a request body based on the contents of an -// UpdateOpts. -func (opts UpdateOpts) ToVolumeUpdateMap() (map[string]interface{}, error) { - v := make(map[string]interface{}) - - if opts.Description != "" { - v["display_description"] = opts.Description - } - if opts.Metadata != nil { - v["metadata"] = opts.Metadata - } - if opts.Name != "" { - v["display_name"] = opts.Name - } - - return map[string]interface{}{"volume": v}, nil -} - -// Update will update the Volume with provided information. To extract the updated -// Volume from the response, call the Extract method on the UpdateResult. -func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToVolumeUpdateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Put(updateURL(client, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// IDFromName is a convienience function that returns a server's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - volumeCount := 0 - volumeID := "" - if name == "" { - return "", fmt.Errorf("A volume name must be provided.") - } - pager := List(client, nil) - pager.EachPage(func(page pagination.Page) (bool, error) { - volumeList, err := ExtractVolumes(page) - if err != nil { - return false, err - } - - for _, s := range volumeList { - if s.Name == name { - volumeCount++ - volumeID = s.ID - } - } - return true, nil - }) - - switch volumeCount { - case 0: - return "", fmt.Errorf("Unable to find volume: %s", name) - case 1: - return volumeID, nil - default: - return "", fmt.Errorf("Found %d volumes matching %s", volumeCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/results.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/results.go deleted file mode 100644 index 2fd4ef14e..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/results.go +++ /dev/null @@ -1,113 +0,0 @@ -package volumes - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - - "github.com/mitchellh/mapstructure" -) - -// Volume contains all the information associated with an OpenStack Volume. -type Volume struct { - // Current status of the volume. - Status string `mapstructure:"status"` - - // Human-readable display name for the volume. - Name string `mapstructure:"display_name"` - - // Instances onto which the volume is attached. - Attachments []map[string]interface{} `mapstructure:"attachments"` - - // This parameter is no longer used. - AvailabilityZone string `mapstructure:"availability_zone"` - - // Indicates whether this is a bootable volume. - Bootable string `mapstructure:"bootable"` - - // The date when this volume was created. - CreatedAt string `mapstructure:"created_at"` - - // Human-readable description for the volume. - Description string `mapstructure:"display_description"` - - // The type of volume to create, either SATA or SSD. - VolumeType string `mapstructure:"volume_type"` - - // The ID of the snapshot from which the volume was created - SnapshotID string `mapstructure:"snapshot_id"` - - // The ID of another block storage volume from which the current volume was created - SourceVolID string `mapstructure:"source_volid"` - - // Arbitrary key-value pairs defined by the user. - Metadata map[string]string `mapstructure:"metadata"` - - // Unique identifier for the volume. - ID string `mapstructure:"id"` - - // Size of the volume in GB. - Size int `mapstructure:"size"` -} - -// CreateResult contains the response body and error from a Create request. -type CreateResult struct { - commonResult -} - -// GetResult contains the response body and error from a Get request. -type GetResult struct { - commonResult -} - -// DeleteResult contains the response body and error from a Delete request. -type DeleteResult struct { - gophercloud.ErrResult -} - -// ListResult is a pagination.pager that is returned from a call to the List function. -type ListResult struct { - pagination.SinglePageBase -} - -// IsEmpty returns true if a ListResult contains no Volumes. -func (r ListResult) IsEmpty() (bool, error) { - volumes, err := ExtractVolumes(r) - if err != nil { - return true, err - } - return len(volumes) == 0, nil -} - -// ExtractVolumes extracts and returns Volumes. It is used while iterating over a volumes.List call. -func ExtractVolumes(page pagination.Page) ([]Volume, error) { - var response struct { - Volumes []Volume `json:"volumes"` - } - - err := mapstructure.Decode(page.(ListResult).Body, &response) - return response.Volumes, err -} - -// UpdateResult contains the response body and error from an Update request. -type UpdateResult struct { - commonResult -} - -type commonResult struct { - gophercloud.Result -} - -// Extract will get the Volume object out of the commonResult object. -func (r commonResult) Extract() (*Volume, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Volume *Volume `json:"volume"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Volume, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/urls.go deleted file mode 100644 index 29629a1af..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/urls.go +++ /dev/null @@ -1,23 +0,0 @@ -package volumes - -import "github.com/rackspace/gophercloud" - -func createURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("volumes") -} - -func listURL(c *gophercloud.ServiceClient) string { - return createURL(c) -} - -func deleteURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL("volumes", id) -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return deleteURL(c, id) -} - -func updateURL(c *gophercloud.ServiceClient, id string) string { - return deleteURL(c, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/util.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/util.go deleted file mode 100644 index 1dda695ea..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/util.go +++ /dev/null @@ -1,22 +0,0 @@ -package volumes - -import ( - "github.com/rackspace/gophercloud" -) - -// WaitForStatus will continually poll the resource, checking for a particular -// status. It will do this for the amount of seconds defined. -func WaitForStatus(c *gophercloud.ServiceClient, id, status string, secs int) error { - return gophercloud.WaitFor(secs, func() (bool, error) { - current, err := Get(c, id).Extract() - if err != nil { - return false, err - } - - if current.Status == status { - return true, nil - } - - return false, nil - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/doc.go deleted file mode 100644 index 307b8b12d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package volumes provides information and interaction with volumes in the -// OpenStack Block Storage service. A volume is a detachable block storage -// device, akin to a USB hard drive. It can only be attached to one instance at -// a time. -package volumes diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/fixtures.go deleted file mode 100644 index b70e2987b..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/fixtures.go +++ /dev/null @@ -1,204 +0,0 @@ -package volumes - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func MockListResponse(t *testing.T) { - th.Mux.HandleFunc("/volumes/detail", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` - { - "volumes": [ - { - "volume_type": "lvmdriver-1", - "created_at": "2015-09-17T03:35:03.000000", - "bootable": "false", - "name": "vol-001", - "os-vol-mig-status-attr:name_id": null, - "consistencygroup_id": null, - "source_volid": null, - "os-volume-replication:driver_data": null, - "multiattach": false, - "snapshot_id": null, - "replication_status": "disabled", - "os-volume-replication:extended_status": null, - "encrypted": false, - "os-vol-host-attr:host": null, - "availability_zone": "nova", - "attachments": [ - { - "attachment_id": "03987cd1-0ad5-40d1-9b2a-7cc48295d4fa", - "id": "47e9ecc5-4045-4ee3-9a4b-d859d546a0cf", - "volume_id": "289da7f8-6440-407c-9fb4-7db01ec49164", - "server_id": "d1c4788b-9435-42e2-9b81-29f3be1cd01f", - "host_name": "stack", - "device": "/dev/vdc" - } - ], - "id": "289da7f8-6440-407c-9fb4-7db01ec49164", - "size": 75, - "user_id": "ff1ce52c03ab433aaba9108c2e3ef541", - "os-vol-tenant-attr:tenant_id": "304dc00909ac4d0da6c62d816bcb3459", - "os-vol-mig-status-attr:migstat": null, - "metadata": {"foo": "bar"}, - "status": "available", - "description": null - }, - { - "volume_type": "lvmdriver-1", - "created_at": "2015-09-17T03:32:29.000000", - "bootable": "false", - "name": "vol-002", - "os-vol-mig-status-attr:name_id": null, - "consistencygroup_id": null, - "source_volid": null, - "os-volume-replication:driver_data": null, - "multiattach": false, - "snapshot_id": null, - "replication_status": "disabled", - "os-volume-replication:extended_status": null, - "encrypted": false, - "os-vol-host-attr:host": null, - "availability_zone": "nova", - "attachments": [], - "id": "96c3bda7-c82a-4f50-be73-ca7621794835", - "size": 75, - "user_id": "ff1ce52c03ab433aaba9108c2e3ef541", - "os-vol-tenant-attr:tenant_id": "304dc00909ac4d0da6c62d816bcb3459", - "os-vol-mig-status-attr:migstat": null, - "metadata": {}, - "status": "available", - "description": null - } - ] -} - - `) - }) -} - -func MockGetResponse(t *testing.T) { - th.Mux.HandleFunc("/volumes/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, ` -{ - "volume": { - "volume_type": "lvmdriver-1", - "created_at": "2015-09-17T03:32:29.000000", - "bootable": "false", - "name": "vol-001", - "os-vol-mig-status-attr:name_id": null, - "consistencygroup_id": null, - "source_volid": null, - "os-volume-replication:driver_data": null, - "multiattach": false, - "snapshot_id": null, - "replication_status": "disabled", - "os-volume-replication:extended_status": null, - "encrypted": false, - "os-vol-host-attr:host": null, - "availability_zone": "nova", - "attachments": [{ - "attachment_id": "dbce64e3-f3b9-4423-a44f-a2b15deffa1b", - "id": "3eafc6f5-ed74-456d-90fb-f253f594dbae", - "volume_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "server_id": "d1c4788b-9435-42e2-9b81-29f3be1cd01f", - "host_name": "stack", - "device": "/dev/vdd" - }], - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "size": 75, - "user_id": "ff1ce52c03ab433aaba9108c2e3ef541", - "os-vol-tenant-attr:tenant_id": "304dc00909ac4d0da6c62d816bcb3459", - "os-vol-mig-status-attr:migstat": null, - "metadata": {}, - "status": "available", - "description": null - } -} - `) - }) -} - -func MockCreateResponse(t *testing.T) { - th.Mux.HandleFunc("/volumes", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "volume": { - "name": "vol-001", - "size": 75 - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusAccepted) - - fmt.Fprintf(w, ` -{ - "volume": { - "size": 75, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "metadata": {}, - "created_at": "2015-09-17T03:32:29.044216", - "encrypted": false, - "bootable": "false", - "availability_zone": "nova", - "attachments": [], - "user_id": "ff1ce52c03ab433aaba9108c2e3ef541", - "status": "creating", - "description": null, - "volume_type": "lvmdriver-1", - "name": "vol-001", - "replication_status": "disabled", - "consistencygroup_id": null, - "source_volid": null, - "snapshot_id": null, - "multiattach": false - } -} - `) - }) -} - -func MockDeleteResponse(t *testing.T) { - th.Mux.HandleFunc("/volumes/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusAccepted) - }) -} - -func MockUpdateResponse(t *testing.T) { - th.Mux.HandleFunc("/volumes/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, ` -{ - "volume": { - "name": "vol-002" - } -} - `) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/requests.go deleted file mode 100644 index 4c60936ac..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/requests.go +++ /dev/null @@ -1,251 +0,0 @@ -package volumes - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// CreateOptsBuilder allows extensions to add additional parameters to the -// Create request. -type CreateOptsBuilder interface { - ToVolumeCreateMap() (map[string]interface{}, error) -} - -// CreateOpts contains options for creating a Volume. This object is passed to -// the volumes.Create function. For more information about these parameters, -// see the Volume object. -type CreateOpts struct { - // The availability zone [OPTIONAL] - AvailabilityZone string - // ConsistencyGroupID is the ID of a consistency group [OPTINAL] - ConsistencyGroupID string - // The volume description [OPTIONAL] - Description string - // One or more metadata key and value pairs to associate with the volume [OPTIONAL] - Metadata map[string]string - // The volume name [OPTIONAL] - Name string - // The size of the volume, in gibibytes (GiB) [REQUIRED] - Size int - // the ID of the existing volume snapshot [OPTIONAL] - SnapshotID string - // SourceReplica is a UUID of an existing volume to replicate with [OPTIONAL] - SourceReplica string - // the ID of the existing volume [OPTIONAL] - SourceVolID string - // The ID of the image from which you want to create the volume. - // Required to create a bootable volume. - ImageID string - // The associated volume type [OPTIONAL] - VolumeType string -} - -// ToVolumeCreateMap assembles a request body based on the contents of a -// CreateOpts. -func (opts CreateOpts) ToVolumeCreateMap() (map[string]interface{}, error) { - v := make(map[string]interface{}) - - if opts.Size == 0 { - return nil, fmt.Errorf("Required CreateOpts field 'Size' not set.") - } - v["size"] = opts.Size - - if opts.AvailabilityZone != "" { - v["availability_zone"] = opts.AvailabilityZone - } - if opts.ConsistencyGroupID != "" { - v["consistencygroup_id"] = opts.ConsistencyGroupID - } - if opts.Description != "" { - v["description"] = opts.Description - } - if opts.ImageID != "" { - v["imageRef"] = opts.ImageID - } - if opts.Metadata != nil { - v["metadata"] = opts.Metadata - } - if opts.Name != "" { - v["name"] = opts.Name - } - if opts.SourceReplica != "" { - v["source_replica"] = opts.SourceReplica - } - if opts.SourceVolID != "" { - v["source_volid"] = opts.SourceVolID - } - if opts.SnapshotID != "" { - v["snapshot_id"] = opts.SnapshotID - } - if opts.VolumeType != "" { - v["volume_type"] = opts.VolumeType - } - - return map[string]interface{}{"volume": v}, nil -} - -// Create will create a new Volume based on the values in CreateOpts. To extract -// the Volume object from the response, call the Extract method on the -// CreateResult. -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToVolumeCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Post(createURL(client), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{202}, - }) - return res -} - -// Delete will delete the existing Volume with the provided ID. -func Delete(client *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = client.Delete(deleteURL(client, id), nil) - return res -} - -// Get retrieves the Volume with the provided ID. To extract the Volume object -// from the response, call the Extract method on the GetResult. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, id), &res.Body, nil) - return res -} - -// ListOptsBuilder allows extensions to add additional parameters to the List -// request. -type ListOptsBuilder interface { - ToVolumeListQuery() (string, error) -} - -// ListOpts holds options for listing Volumes. It is passed to the volumes.List -// function. -type ListOpts struct { - // admin-only option. Set it to true to see all tenant volumes. - AllTenants bool `q:"all_tenants"` - // List only volumes that contain Metadata. - Metadata map[string]string `q:"metadata"` - // List only volumes that have Name as the display name. - Name string `q:"name"` - // List only volumes that have a status of Status. - Status string `q:"status"` -} - -// ToVolumeListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToVolumeListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns Volumes optionally limited by the conditions provided in ListOpts. -func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listURL(client) - if opts != nil { - query, err := opts.ToVolumeListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - createPage := func(r pagination.PageResult) pagination.Page { - return ListResult{pagination.SinglePageBase(r)} - } - - return pagination.NewPager(client, url, createPage) -} - -// UpdateOptsBuilder allows extensions to add additional parameters to the -// Update request. -type UpdateOptsBuilder interface { - ToVolumeUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts contain options for updating an existing Volume. This object is passed -// to the volumes.Update function. For more information about the parameters, see -// the Volume object. -type UpdateOpts struct { - // OPTIONAL - Name string - // OPTIONAL - Description string - // OPTIONAL - Metadata map[string]string -} - -// ToVolumeUpdateMap assembles a request body based on the contents of an -// UpdateOpts. -func (opts UpdateOpts) ToVolumeUpdateMap() (map[string]interface{}, error) { - v := make(map[string]interface{}) - - if opts.Description != "" { - v["description"] = opts.Description - } - if opts.Metadata != nil { - v["metadata"] = opts.Metadata - } - if opts.Name != "" { - v["name"] = opts.Name - } - - return map[string]interface{}{"volume": v}, nil -} - -// Update will update the Volume with provided information. To extract the updated -// Volume from the response, call the Extract method on the UpdateResult. -func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToVolumeUpdateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Put(updateURL(client, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// IDFromName is a convienience function that returns a server's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - volumeCount := 0 - volumeID := "" - if name == "" { - return "", fmt.Errorf("A volume name must be provided.") - } - pager := List(client, nil) - pager.EachPage(func(page pagination.Page) (bool, error) { - volumeList, err := ExtractVolumes(page) - if err != nil { - return false, err - } - - for _, s := range volumeList { - if s.Name == name { - volumeCount++ - volumeID = s.ID - } - } - return true, nil - }) - - switch volumeCount { - case 0: - return "", fmt.Errorf("Unable to find volume: %s", name) - case 1: - return volumeID, nil - default: - return "", fmt.Errorf("Found %d volumes matching %s", volumeCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/results.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/results.go deleted file mode 100644 index 59fa53074..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/results.go +++ /dev/null @@ -1,137 +0,0 @@ -package volumes - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - - "github.com/mitchellh/mapstructure" -) - -// Volume contains all the information associated with an OpenStack Volume. -type Volume struct { - // Instances onto which the volume is attached. - Attachments []map[string]interface{} `mapstructure:"attachments"` - - // AvailabilityZone is which availability zone the volume is in. - AvailabilityZone string `mapstructure:"availability_zone"` - - // Indicates whether this is a bootable volume. - Bootable string `mapstructure:"bootable"` - - // ConsistencyGroupID is the consistency group ID. - ConsistencyGroupID string `mapstructure:"consistencygroup_id"` - - // The date when this volume was created. - CreatedAt string `mapstructure:"created_at"` - - // Human-readable description for the volume. - Description string `mapstructure:"description"` - - // Encrypted denotes if the volume is encrypted. - Encrypted bool `mapstructure:"encrypted"` - - // Human-readable display name for the volume. - Name string `mapstructure:"name"` - - // The type of volume to create, either SATA or SSD. - VolumeType string `mapstructure:"volume_type"` - - // ReplicationDriverData contains data about the replication driver. - ReplicationDriverData string `mapstructure:"os-volume-replication:driver_data"` - - // ReplicationExtendedStatus contains extended status about replication. - ReplicationExtendedStatus string `mapstructure:"os-volume-replication:extended_status"` - - // ReplicationStatus is the status of replication. - ReplicationStatus string `mapstructure:"replication_status"` - - // The ID of the snapshot from which the volume was created - SnapshotID string `mapstructure:"snapshot_id"` - - // The ID of another block storage volume from which the current volume was created - SourceVolID string `mapstructure:"source_volid"` - - // Current status of the volume. - Status string `mapstructure:"status"` - - // TenantID is the id of the project that owns the volume. - TenantID string `mapstructure:"os-vol-tenant-attr:tenant_id"` - - // Arbitrary key-value pairs defined by the user. - Metadata map[string]string `mapstructure:"metadata"` - - // Multiattach denotes if the volume is multi-attach capable. - Multiattach bool `mapstructure:"multiattach"` - - // Unique identifier for the volume. - ID string `mapstructure:"id"` - - // Size of the volume in GB. - Size int `mapstructure:"size"` - - // UserID is the id of the user who created the volume. - UserID string `mapstructure:"user_id"` -} - -// CreateResult contains the response body and error from a Create request. -type CreateResult struct { - commonResult -} - -// GetResult contains the response body and error from a Get request. -type GetResult struct { - commonResult -} - -// DeleteResult contains the response body and error from a Delete request. -type DeleteResult struct { - gophercloud.ErrResult -} - -// ListResult is a pagination.pager that is returned from a call to the List function. -type ListResult struct { - pagination.SinglePageBase -} - -// IsEmpty returns true if a ListResult contains no Volumes. -func (r ListResult) IsEmpty() (bool, error) { - volumes, err := ExtractVolumes(r) - if err != nil { - return true, err - } - return len(volumes) == 0, nil -} - -// ExtractVolumes extracts and returns Volumes. It is used while iterating over a volumes.List call. -func ExtractVolumes(page pagination.Page) ([]Volume, error) { - var response struct { - Volumes []Volume `json:"volumes"` - } - - err := mapstructure.Decode(page.(ListResult).Body, &response) - return response.Volumes, err -} - -// UpdateResult contains the response body and error from an Update request. -type UpdateResult struct { - commonResult -} - -type commonResult struct { - gophercloud.Result -} - -// Extract will get the Volume object out of the commonResult object. -func (r commonResult) Extract() (*Volume, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Volume *Volume `json:"volume"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Volume, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/urls.go deleted file mode 100644 index 2523ec62d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/urls.go +++ /dev/null @@ -1,23 +0,0 @@ -package volumes - -import "github.com/rackspace/gophercloud" - -func createURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("volumes") -} - -func listURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("volumes", "detail") -} - -func deleteURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL("volumes", id) -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return deleteURL(c, id) -} - -func updateURL(c *gophercloud.ServiceClient, id string) string { - return deleteURL(c, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/util.go b/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/util.go deleted file mode 100644 index 1dda695ea..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/util.go +++ /dev/null @@ -1,22 +0,0 @@ -package volumes - -import ( - "github.com/rackspace/gophercloud" -) - -// WaitForStatus will continually poll the resource, checking for a particular -// status. It will do this for the amount of seconds defined. -func WaitForStatus(c *gophercloud.ServiceClient, id, status string, secs int) error { - return gophercloud.WaitFor(secs, func() (bool, error) { - current, err := Get(c, id).Extract() - if err != nil { - return false, err - } - - if current.Status == status { - return true, nil - } - - return false, nil - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/client.go b/vendor/github.com/rackspace/gophercloud/openstack/client.go deleted file mode 100644 index fbb76ead0..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/client.go +++ /dev/null @@ -1,346 +0,0 @@ -package openstack - -import ( - "fmt" - "net/url" - "strconv" - "strings" - - "github.com/rackspace/gophercloud" - tokens2 "github.com/rackspace/gophercloud/openstack/identity/v2/tokens" - tokens3 "github.com/rackspace/gophercloud/openstack/identity/v3/tokens" - "github.com/rackspace/gophercloud/openstack/utils" -) - -const ( - v20 = "v2.0" - v30 = "v3.0" -) - -// NewClient prepares an unauthenticated ProviderClient instance. -// Most users will probably prefer using the AuthenticatedClient function instead. -// This is useful if you wish to explicitly control the version of the identity service that's used for authentication explicitly, -// for example. -func NewClient(endpoint string) (*gophercloud.ProviderClient, error) { - u, err := url.Parse(endpoint) - if err != nil { - return nil, err - } - - u.RawQuery, u.Fragment = "", "" - - // Base is url with path - endpoint = gophercloud.NormalizeURL(endpoint) - base := gophercloud.NormalizeURL(u.String()) - - path := u.Path - if !strings.HasSuffix(path, "/") { - path = path + "/" - } - - parts := strings.Split(path[0:len(path)-1], "/") - for index,version := range(parts) { - if 2 <= len(version) && len(version) <= 4 && strings.HasPrefix(version, "v") { - _, err := strconv.ParseFloat(version[1:], 64) - if err == nil { - // post version suffixes in path are not supported - // version must be on the last index - if index < len(parts) - 1 { - return nil, fmt.Errorf("Path suffixes (after version) are not supported.") - } - switch version { - case "v2.0", "v3": - // valid version found, strip from base - return &gophercloud.ProviderClient{ - IdentityBase: base[0:len(base)-len(version)-1], - IdentityEndpoint: endpoint, - }, nil - default: - return nil, fmt.Errorf("Invalid identity endpoint version %v. Supported versions: v2.0, v3", version) - } - } - } - } - - return &gophercloud.ProviderClient{ - IdentityBase: base, - IdentityEndpoint: "", - }, nil -} - -// AuthenticatedClient logs in to an OpenStack cloud found at the identity endpoint specified by options, acquires a token, and -// returns a Client instance that's ready to operate. -// It first queries the root identity endpoint to determine which versions of the identity service are supported, then chooses -// the most recent identity service available to proceed. -func AuthenticatedClient(options gophercloud.AuthOptions) (*gophercloud.ProviderClient, error) { - client, err := NewClient(options.IdentityEndpoint) - if err != nil { - return nil, err - } - - err = Authenticate(client, options) - if err != nil { - return nil, err - } - return client, nil -} - -// Authenticate or re-authenticate against the most recent identity service supported at the provided endpoint. -func Authenticate(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error { - versions := []*utils.Version{ - {ID: v20, Priority: 20, Suffix: "/v2.0/"}, - {ID: v30, Priority: 30, Suffix: "/v3/"}, - } - - chosen, endpoint, err := utils.ChooseVersion(client, versions) - if err != nil { - return err - } - - switch chosen.ID { - case v20: - return v2auth(client, endpoint, options) - case v30: - return v3auth(client, endpoint, options) - default: - // The switch statement must be out of date from the versions list. - return fmt.Errorf("Unrecognized identity version: %s", chosen.ID) - } -} - -// AuthenticateV2 explicitly authenticates against the identity v2 endpoint. -func AuthenticateV2(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error { - return v2auth(client, "", options) -} - -func v2auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions) error { - v2Client := NewIdentityV2(client) - if endpoint != "" { - v2Client.Endpoint = endpoint - } - - result := tokens2.Create(v2Client, tokens2.AuthOptions{AuthOptions: options}) - - token, err := result.ExtractToken() - if err != nil { - return err - } - - catalog, err := result.ExtractServiceCatalog() - if err != nil { - return err - } - - if options.AllowReauth { - client.ReauthFunc = func() error { - client.TokenID = "" - return v2auth(client, endpoint, options) - } - } - client.TokenID = token.ID - client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) { - return V2EndpointURL(catalog, opts) - } - - return nil -} - -// AuthenticateV3 explicitly authenticates against the identity v3 service. -func AuthenticateV3(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error { - return v3auth(client, "", options) -} - -func v3auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions) error { - // Override the generated service endpoint with the one returned by the version endpoint. - v3Client := NewIdentityV3(client) - if endpoint != "" { - v3Client.Endpoint = endpoint - } - - // copy the auth options to a local variable that we can change. `options` - // needs to stay as-is for reauth purposes - v3Options := options - - var scope *tokens3.Scope - if options.TenantID != "" { - scope = &tokens3.Scope{ - ProjectID: options.TenantID, - } - v3Options.TenantID = "" - v3Options.TenantName = "" - } else { - if options.TenantName != "" { - scope = &tokens3.Scope{ - ProjectName: options.TenantName, - DomainID: options.DomainID, - DomainName: options.DomainName, - } - v3Options.TenantName = "" - } - } - - result := tokens3.Create(v3Client, v3Options, scope) - - token, err := result.ExtractToken() - if err != nil { - return err - } - - catalog, err := result.ExtractServiceCatalog() - if err != nil { - return err - } - - client.TokenID = token.ID - - if options.AllowReauth { - client.ReauthFunc = func() error { - client.TokenID = "" - return v3auth(client, endpoint, options) - } - } - client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) { - return V3EndpointURL(catalog, opts) - } - - return nil -} - -// NewIdentityV2 creates a ServiceClient that may be used to interact with the v2 identity service. -func NewIdentityV2(client *gophercloud.ProviderClient) *gophercloud.ServiceClient { - v2Endpoint := client.IdentityBase + "v2.0/" - - return &gophercloud.ServiceClient{ - ProviderClient: client, - Endpoint: v2Endpoint, - } -} - -// NewIdentityV3 creates a ServiceClient that may be used to access the v3 identity service. -func NewIdentityV3(client *gophercloud.ProviderClient) *gophercloud.ServiceClient { - v3Endpoint := client.IdentityBase + "v3/" - - return &gophercloud.ServiceClient{ - ProviderClient: client, - Endpoint: v3Endpoint, - } -} - -func NewIdentityAdminV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("identity") - eo.Availability = gophercloud.AvailabilityAdmin - - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - - // Force using v2 API - if strings.Contains(url, "/v3") { - url = strings.Replace(url, "/v3", "/v2.0", -1) - } - - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -func NewIdentityAdminV3(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("identity") - eo.Availability = gophercloud.AvailabilityAdmin - - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - - // Force using v3 API - if strings.Contains(url, "/v2.0") { - url = strings.Replace(url, "/v2.0", "/v3", -1) - } - - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -// NewObjectStorageV1 creates a ServiceClient that may be used with the v1 object storage package. -func NewObjectStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("object-store") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -// NewComputeV2 creates a ServiceClient that may be used with the v2 compute package. -func NewComputeV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("compute") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -// NewNetworkV2 creates a ServiceClient that may be used with the v2 network package. -func NewNetworkV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("network") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ - ProviderClient: client, - Endpoint: url, - ResourceBase: url + "v2.0/", - }, nil -} - -// NewBlockStorageV1 creates a ServiceClient that may be used to access the v1 block storage service. -func NewBlockStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("volume") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -// NewBlockStorageV2 creates a ServiceClient that may be used to access the v2 block storage service. -func NewBlockStorageV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("volumev2") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -// NewCDNV1 creates a ServiceClient that may be used to access the OpenStack v1 -// CDN service. -func NewCDNV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("cdn") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -// NewOrchestrationV1 creates a ServiceClient that may be used to access the v1 orchestration service. -func NewOrchestrationV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("orchestration") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} - -// NewDBV1 creates a ServiceClient that may be used to access the v1 DB service. -func NewDBV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - eo.ApplyDefaults("database") - url, err := client.EndpointLocator(eo) - if err != nil { - return nil, err - } - return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/requests.go deleted file mode 100644 index a15c98d39..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/requests.go +++ /dev/null @@ -1,120 +0,0 @@ -package bootfromvolume - -import ( - "errors" - "strconv" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" -) - -// SourceType represents the type of medium being used to create the volume. -type SourceType string - -const ( - Volume SourceType = "volume" - Snapshot SourceType = "snapshot" - Image SourceType = "image" - Blank SourceType = "blank" -) - -// BlockDevice is a structure with options for booting a server instance -// from a volume. The volume may be created from an image, snapshot, or another -// volume. -type BlockDevice struct { - // BootIndex [optional] is the boot index. It defaults to 0. - BootIndex int `json:"boot_index"` - - // DeleteOnTermination [optional] specifies whether or not to delete the attached volume - // when the server is deleted. Defaults to `false`. - DeleteOnTermination bool `json:"delete_on_termination"` - - // DestinationType [optional] is the type that gets created. Possible values are "volume" - // and "local". - DestinationType string `json:"destination_type"` - - // GuestFormat [optional] specifies the format of the block device. - GuestFormat string `json:"guest_format"` - - // SourceType [required] must be one of: "volume", "snapshot", "image". - SourceType SourceType `json:"source_type"` - - // UUID [required] is the unique identifier for the volume, snapshot, or image (see above) - UUID string `json:"uuid"` - - // VolumeSize [optional] is the size of the volume to create (in gigabytes). - VolumeSize int `json:"volume_size"` -} - -// CreateOptsExt is a structure that extends the server `CreateOpts` structure -// by allowing for a block device mapping. -type CreateOptsExt struct { - servers.CreateOptsBuilder - BlockDevice []BlockDevice `json:"block_device_mapping_v2,omitempty"` -} - -// ToServerCreateMap adds the block device mapping option to the base server -// creation options. -func (opts CreateOptsExt) ToServerCreateMap() (map[string]interface{}, error) { - base, err := opts.CreateOptsBuilder.ToServerCreateMap() - if err != nil { - return nil, err - } - - if len(opts.BlockDevice) == 0 { - return nil, errors.New("Required fields UUID and SourceType not set.") - } - - serverMap := base["server"].(map[string]interface{}) - - blockDevice := make([]map[string]interface{}, len(opts.BlockDevice)) - - for i, bd := range opts.BlockDevice { - if string(bd.SourceType) == "" { - return nil, errors.New("SourceType must be one of: volume, image, snapshot.") - } - - blockDevice[i] = make(map[string]interface{}) - - blockDevice[i]["source_type"] = bd.SourceType - blockDevice[i]["boot_index"] = strconv.Itoa(bd.BootIndex) - blockDevice[i]["delete_on_termination"] = strconv.FormatBool(bd.DeleteOnTermination) - if bd.VolumeSize > 0 { - blockDevice[i]["volume_size"] = strconv.Itoa(bd.VolumeSize) - } - if bd.UUID != "" { - blockDevice[i]["uuid"] = bd.UUID - } - if bd.DestinationType != "" { - blockDevice[i]["destination_type"] = bd.DestinationType - } - if bd.GuestFormat != "" { - blockDevice[i]["guest_format"] = bd.GuestFormat - } - - } - serverMap["block_device_mapping_v2"] = blockDevice - - return base, nil -} - -// Create requests the creation of a server from the given block device mapping. -func Create(client *gophercloud.ServiceClient, opts servers.CreateOptsBuilder) servers.CreateResult { - var res servers.CreateResult - - reqBody, err := opts.ToServerCreateMap() - if err != nil { - res.Err = err - return res - } - - // Delete imageName and flavorName that come from ToServerCreateMap(). - // As of Liberty, Boot From Volume is failing if they are passed. - delete(reqBody["server"].(map[string]interface{}), "imageName") - delete(reqBody["server"].(map[string]interface{}), "flavorName") - - _, res.Err = client.Post(createURL(client), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/results.go deleted file mode 100644 index f60329f0f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/results.go +++ /dev/null @@ -1,10 +0,0 @@ -package bootfromvolume - -import ( - os "github.com/rackspace/gophercloud/openstack/compute/v2/servers" -) - -// CreateResult temporarily contains the response from a Create call. -type CreateResult struct { - os.CreateResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/urls.go deleted file mode 100644 index 0cffe25ff..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/urls.go +++ /dev/null @@ -1,7 +0,0 @@ -package bootfromvolume - -import "github.com/rackspace/gophercloud" - -func createURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("os-volumes_boot") -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/doc.go deleted file mode 100644 index f74f58ce8..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package floatingip provides the ability to manage floating ips through -// nova-network -package floatingip diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/fixtures.go deleted file mode 100644 index e47fa4ccd..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/fixtures.go +++ /dev/null @@ -1,193 +0,0 @@ -// +build fixtures - -package floatingip - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// ListOutput is a sample response to a List call. -const ListOutput = ` -{ - "floating_ips": [ - { - "fixed_ip": null, - "id": 1, - "instance_id": null, - "ip": "10.10.10.1", - "pool": "nova" - }, - { - "fixed_ip": "166.78.185.201", - "id": 2, - "instance_id": "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - "ip": "10.10.10.2", - "pool": "nova" - } - ] -} -` - -// GetOutput is a sample response to a Get call. -const GetOutput = ` -{ - "floating_ip": { - "fixed_ip": "166.78.185.201", - "id": 2, - "instance_id": "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - "ip": "10.10.10.2", - "pool": "nova" - } -} -` - -// CreateOutput is a sample response to a Post call -const CreateOutput = ` -{ - "floating_ip": { - "fixed_ip": null, - "id": 1, - "instance_id": null, - "ip": "10.10.10.1", - "pool": "nova" - } -} -` - -// FirstFloatingIP is the first result in ListOutput. -var FirstFloatingIP = FloatingIP{ - ID: "1", - IP: "10.10.10.1", - Pool: "nova", -} - -// SecondFloatingIP is the first result in ListOutput. -var SecondFloatingIP = FloatingIP{ - FixedIP: "166.78.185.201", - ID: "2", - InstanceID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - IP: "10.10.10.2", - Pool: "nova", -} - -// ExpectedFloatingIPsSlice is the slice of results that should be parsed -// from ListOutput, in the expected order. -var ExpectedFloatingIPsSlice = []FloatingIP{FirstFloatingIP, SecondFloatingIP} - -// CreatedFloatingIP is the parsed result from CreateOutput. -var CreatedFloatingIP = FloatingIP{ - ID: "1", - IP: "10.10.10.1", - Pool: "nova", -} - -// HandleListSuccessfully configures the test server to respond to a List request. -func HandleListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-floating-ips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ListOutput) - }) -} - -// HandleGetSuccessfully configures the test server to respond to a Get request -// for an existing floating ip -func HandleGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-floating-ips/2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, GetOutput) - }) -} - -// HandleCreateSuccessfully configures the test server to respond to a Create request -// for a new floating ip -func HandleCreateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-floating-ips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, ` -{ - "pool": "nova" -} -`) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, CreateOutput) - }) -} - -// HandleDeleteSuccessfully configures the test server to respond to a Delete request for a -// an existing floating ip -func HandleDeleteSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-floating-ips/1", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandleAssociateSuccessfully configures the test server to respond to a Post request -// to associate an allocated floating IP -func HandleAssociateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/4d8c3732-a248-40ed-bebc-539a6ffd25c0/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, ` -{ - "addFloatingIp": { - "address": "10.10.10.2" - } -} -`) - - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandleFixedAssociateSucessfully configures the test server to respond to a Post request -// to associate an allocated floating IP with a specific fixed IP address -func HandleAssociateFixedSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/4d8c3732-a248-40ed-bebc-539a6ffd25c0/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, ` -{ - "addFloatingIp": { - "address": "10.10.10.2", - "fixed_address": "166.78.185.201" - } -} -`) - - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandleDisassociateSuccessfully configures the test server to respond to a Post request -// to disassociate an allocated floating IP -func HandleDisassociateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/4d8c3732-a248-40ed-bebc-539a6ffd25c0/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, ` -{ - "removeFloatingIp": { - "address": "10.10.10.2" - } -} -`) - - w.WriteHeader(http.StatusAccepted) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/requests.go deleted file mode 100644 index 820646297..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/requests.go +++ /dev/null @@ -1,171 +0,0 @@ -package floatingip - -import ( - "errors" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// List returns a Pager that allows you to iterate over a collection of FloatingIPs. -func List(client *gophercloud.ServiceClient) pagination.Pager { - return pagination.NewPager(client, listURL(client), func(r pagination.PageResult) pagination.Page { - return FloatingIPsPage{pagination.SinglePageBase(r)} - }) -} - -// CreateOptsBuilder describes struct types that can be accepted by the Create call. Notable, the -// CreateOpts struct in this package does. -type CreateOptsBuilder interface { - ToFloatingIPCreateMap() (map[string]interface{}, error) -} - -// CreateOpts specifies a Floating IP allocation request -type CreateOpts struct { - // Pool is the pool of floating IPs to allocate one from - Pool string -} - -// AssociateOpts specifies the required information to associate or disassociate a floating IP to an instance -type AssociateOpts struct { - // ServerID is the UUID of the server - ServerID string - - // FixedIP is an optional fixed IP address of the server - FixedIP string - - // FloatingIP is the floating IP to associate with an instance - FloatingIP string -} - -// ToFloatingIPCreateMap constructs a request body from CreateOpts. -func (opts CreateOpts) ToFloatingIPCreateMap() (map[string]interface{}, error) { - if opts.Pool == "" { - return nil, errors.New("Missing field required for floating IP creation: Pool") - } - - return map[string]interface{}{"pool": opts.Pool}, nil -} - -// ToAssociateMap constructs a request body from AssociateOpts. -func (opts AssociateOpts) ToAssociateMap() (map[string]interface{}, error) { - if opts.ServerID == "" { - return nil, errors.New("Required field missing for floating IP association: ServerID") - } - - if opts.FloatingIP == "" { - return nil, errors.New("Required field missing for floating IP association: FloatingIP") - } - - associateInfo := map[string]interface{}{ - "serverId": opts.ServerID, - "floatingIp": opts.FloatingIP, - "fixedIp": opts.FixedIP, - } - - return associateInfo, nil - -} - -// Create requests the creation of a new floating IP -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToFloatingIPCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Post(createURL(client), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Get returns data about a previously created FloatingIP. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, id), &res.Body, nil) - return res -} - -// Delete requests the deletion of a previous allocated FloatingIP. -func Delete(client *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = client.Delete(deleteURL(client, id), nil) - return res -} - -// association / disassociation - -// Associate pairs an allocated floating IP with an instance -// Deprecated. Use AssociateInstance. -func Associate(client *gophercloud.ServiceClient, serverId, fip string) AssociateResult { - var res AssociateResult - - addFloatingIp := make(map[string]interface{}) - addFloatingIp["address"] = fip - reqBody := map[string]interface{}{"addFloatingIp": addFloatingIp} - - _, res.Err = client.Post(associateURL(client, serverId), reqBody, nil, nil) - return res -} - -// AssociateInstance pairs an allocated floating IP with an instance. -func AssociateInstance(client *gophercloud.ServiceClient, opts AssociateOpts) AssociateResult { - var res AssociateResult - - associateInfo, err := opts.ToAssociateMap() - if err != nil { - res.Err = err - return res - } - - addFloatingIp := make(map[string]interface{}) - addFloatingIp["address"] = associateInfo["floatingIp"].(string) - - // fixedIp is not required - if associateInfo["fixedIp"] != "" { - addFloatingIp["fixed_address"] = associateInfo["fixedIp"].(string) - } - - serverId := associateInfo["serverId"].(string) - - reqBody := map[string]interface{}{"addFloatingIp": addFloatingIp} - _, res.Err = client.Post(associateURL(client, serverId), reqBody, nil, nil) - return res -} - -// Disassociate decouples an allocated floating IP from an instance -// Deprecated. Use DisassociateInstance. -func Disassociate(client *gophercloud.ServiceClient, serverId, fip string) DisassociateResult { - var res DisassociateResult - - removeFloatingIp := make(map[string]interface{}) - removeFloatingIp["address"] = fip - reqBody := map[string]interface{}{"removeFloatingIp": removeFloatingIp} - - _, res.Err = client.Post(disassociateURL(client, serverId), reqBody, nil, nil) - return res -} - -// DisassociateInstance decouples an allocated floating IP from an instance -func DisassociateInstance(client *gophercloud.ServiceClient, opts AssociateOpts) DisassociateResult { - var res DisassociateResult - - associateInfo, err := opts.ToAssociateMap() - if err != nil { - res.Err = err - return res - } - - removeFloatingIp := make(map[string]interface{}) - removeFloatingIp["address"] = associateInfo["floatingIp"].(string) - reqBody := map[string]interface{}{"removeFloatingIp": removeFloatingIp} - - serverId := associateInfo["serverId"].(string) - - _, res.Err = client.Post(disassociateURL(client, serverId), reqBody, nil, nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/results.go deleted file mode 100644 index be77fa179..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/results.go +++ /dev/null @@ -1,99 +0,0 @@ -package floatingip - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// A FloatingIP is an IP that can be associated with an instance -type FloatingIP struct { - // ID is a unique ID of the Floating IP - ID string `mapstructure:"id"` - - // FixedIP is the IP of the instance related to the Floating IP - FixedIP string `mapstructure:"fixed_ip,omitempty"` - - // InstanceID is the ID of the instance that is using the Floating IP - InstanceID string `mapstructure:"instance_id"` - - // IP is the actual Floating IP - IP string `mapstructure:"ip"` - - // Pool is the pool of floating IPs that this floating IP belongs to - Pool string `mapstructure:"pool"` -} - -// FloatingIPsPage stores a single, only page of FloatingIPs -// results from a List call. -type FloatingIPsPage struct { - pagination.SinglePageBase -} - -// IsEmpty determines whether or not a FloatingIPsPage is empty. -func (page FloatingIPsPage) IsEmpty() (bool, error) { - va, err := ExtractFloatingIPs(page) - return len(va) == 0, err -} - -// ExtractFloatingIPs interprets a page of results as a slice of -// FloatingIPs. -func ExtractFloatingIPs(page pagination.Page) ([]FloatingIP, error) { - casted := page.(FloatingIPsPage).Body - var response struct { - FloatingIPs []FloatingIP `mapstructure:"floating_ips"` - } - - err := mapstructure.WeakDecode(casted, &response) - - return response.FloatingIPs, err -} - -type FloatingIPResult struct { - gophercloud.Result -} - -// Extract is a method that attempts to interpret any FloatingIP resource -// response as a FloatingIP struct. -func (r FloatingIPResult) Extract() (*FloatingIP, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - FloatingIP *FloatingIP `json:"floating_ip" mapstructure:"floating_ip"` - } - - err := mapstructure.WeakDecode(r.Body, &res) - return res.FloatingIP, err -} - -// CreateResult is the response from a Create operation. Call its Extract method to interpret it -// as a FloatingIP. -type CreateResult struct { - FloatingIPResult -} - -// GetResult is the response from a Get operation. Call its Extract method to interpret it -// as a FloatingIP. -type GetResult struct { - FloatingIPResult -} - -// DeleteResult is the response from a Delete operation. Call its Extract method to determine if -// the call succeeded or failed. -type DeleteResult struct { - gophercloud.ErrResult -} - -// AssociateResult is the response from a Delete operation. Call its Extract method to determine if -// the call succeeded or failed. -type AssociateResult struct { - gophercloud.ErrResult -} - -// DisassociateResult is the response from a Delete operation. Call its Extract method to determine if -// the call succeeded or failed. -type DisassociateResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/urls.go deleted file mode 100644 index 54198f852..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/urls.go +++ /dev/null @@ -1,37 +0,0 @@ -package floatingip - -import "github.com/rackspace/gophercloud" - -const resourcePath = "os-floating-ips" - -func resourceURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(resourcePath) -} - -func listURL(c *gophercloud.ServiceClient) string { - return resourceURL(c) -} - -func createURL(c *gophercloud.ServiceClient) string { - return resourceURL(c) -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(resourcePath, id) -} - -func deleteURL(c *gophercloud.ServiceClient, id string) string { - return getURL(c, id) -} - -func serverURL(c *gophercloud.ServiceClient, serverId string) string { - return c.ServiceURL("servers/" + serverId + "/action") -} - -func associateURL(c *gophercloud.ServiceClient, serverId string) string { - return serverURL(c, serverId) -} - -func disassociateURL(c *gophercloud.ServiceClient, serverId string) string { - return serverURL(c, serverId) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/doc.go deleted file mode 100644 index 856f41bac..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package keypairs provides information and interaction with the Keypairs -// extension for the OpenStack Compute service. -package keypairs diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/fixtures.go deleted file mode 100644 index d10af99d0..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/fixtures.go +++ /dev/null @@ -1,171 +0,0 @@ -// +build fixtures - -package keypairs - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// ListOutput is a sample response to a List call. -const ListOutput = ` -{ - "keypairs": [ - { - "keypair": { - "fingerprint": "15:b0:f8:b3:f9:48:63:71:cf:7b:5b:38:6d:44:2d:4a", - "name": "firstkey", - "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC+Eo/RZRngaGTkFs7I62ZjsIlO79KklKbMXi8F+KITD4bVQHHn+kV+4gRgkgCRbdoDqoGfpaDFs877DYX9n4z6FrAIZ4PES8TNKhatifpn9NdQYWA+IkU8CuvlEKGuFpKRi/k7JLos/gHi2hy7QUwgtRvcefvD/vgQZOVw/mGR9Q== Generated by Nova\n" - } - }, - { - "keypair": { - "fingerprint": "35:9d:d0:c3:4a:80:d3:d8:86:f1:ca:f7:df:c4:f9:d8", - "name": "secondkey", - "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC9mC3WZN9UGLxgPBpP7H5jZMc6pKwOoSgre8yun6REFktn/Kz7DUt9jaR1UJyRzHxITfCfAIgSxPdGqB/oF1suMyWgu5i0625vavLB5z5kC8Hq3qZJ9zJO1poE1kyD+htiTtPWJ88e12xuH2XB/CZN9OpEiF98hAagiOE0EnOS5Q== Generated by Nova\n" - } - } - ] -} -` - -// GetOutput is a sample response to a Get call. -const GetOutput = ` -{ - "keypair": { - "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC+Eo/RZRngaGTkFs7I62ZjsIlO79KklKbMXi8F+KITD4bVQHHn+kV+4gRgkgCRbdoDqoGfpaDFs877DYX9n4z6FrAIZ4PES8TNKhatifpn9NdQYWA+IkU8CuvlEKGuFpKRi/k7JLos/gHi2hy7QUwgtRvcefvD/vgQZOVw/mGR9Q== Generated by Nova\n", - "name": "firstkey", - "fingerprint": "15:b0:f8:b3:f9:48:63:71:cf:7b:5b:38:6d:44:2d:4a" - } -} -` - -// CreateOutput is a sample response to a Create call. -const CreateOutput = ` -{ - "keypair": { - "fingerprint": "35:9d:d0:c3:4a:80:d3:d8:86:f1:ca:f7:df:c4:f9:d8", - "name": "createdkey", - "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQC9mC3WZN9UGLxgPBpP7H5jZMc6pKwOoSgre8yun6REFktn/Kz7\nDUt9jaR1UJyRzHxITfCfAIgSxPdGqB/oF1suMyWgu5i0625vavLB5z5kC8Hq3qZJ\n9zJO1poE1kyD+htiTtPWJ88e12xuH2XB/CZN9OpEiF98hAagiOE0EnOS5QIDAQAB\nAoGAE5XO1mDhORy9COvsg+kYPUhB1GsCYxh+v88wG7HeFDKBY6KUc/Kxo6yoGn5T\nTjRjekyi2KoDZHz4VlIzyZPwFS4I1bf3oCunVoAKzgLdmnTtvRNMC5jFOGc2vUgP\n9bSyRj3S1R4ClVk2g0IDeagko/jc8zzLEYuIK+fbkds79YECQQDt3vcevgegnkga\ntF4NsDmmBPRkcSHCqrANP/7vFcBQN3czxeYYWX3DK07alu6GhH1Y4sHbdm616uU0\nll7xbDzxAkEAzAtN2IyftNygV2EGiaGgqLyo/tD9+Vui2qCQplqe4jvWh/5Sparl\nOjmKo+uAW+hLrLVMnHzRWxbWU8hirH5FNQJATO+ZxCK4etXXAnQmG41NCAqANWB2\nB+2HJbH2NcQ2QHvAHUm741JGn/KI/aBlo7KEjFRDWUVUB5ji64BbUwCsMQJBAIku\nLGcjnBf/oLk+XSPZC2eGd2Ph5G5qYmH0Q2vkTx+wtTn3DV+eNsDfgMtWAJVJ5t61\ngU1QSXyhLPVlKpnnxuUCQC+xvvWjWtsLaFtAsZywJiqLxQzHts8XLGZptYJ5tLWV\nrtmYtBcJCN48RrgQHry/xWYeA4K/AFQpXfNPgprQ96Q=\n-----END RSA PRIVATE KEY-----\n", - "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC9mC3WZN9UGLxgPBpP7H5jZMc6pKwOoSgre8yun6REFktn/Kz7DUt9jaR1UJyRzHxITfCfAIgSxPdGqB/oF1suMyWgu5i0625vavLB5z5kC8Hq3qZJ9zJO1poE1kyD+htiTtPWJ88e12xuH2XB/CZN9OpEiF98hAagiOE0EnOS5Q== Generated by Nova\n", - "user_id": "fake" - } -} -` - -// ImportOutput is a sample response to a Create call that provides its own public key. -const ImportOutput = ` -{ - "keypair": { - "fingerprint": "1e:2c:9b:56:79:4b:45:77:f9:ca:7a:98:2c:b0:d5:3c", - "name": "importedkey", - "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGgB4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0lRE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYcpSxsIbECHw== Generated by Nova", - "user_id": "fake" - } -} -` - -// FirstKeyPair is the first result in ListOutput. -var FirstKeyPair = KeyPair{ - Name: "firstkey", - Fingerprint: "15:b0:f8:b3:f9:48:63:71:cf:7b:5b:38:6d:44:2d:4a", - PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC+Eo/RZRngaGTkFs7I62ZjsIlO79KklKbMXi8F+KITD4bVQHHn+kV+4gRgkgCRbdoDqoGfpaDFs877DYX9n4z6FrAIZ4PES8TNKhatifpn9NdQYWA+IkU8CuvlEKGuFpKRi/k7JLos/gHi2hy7QUwgtRvcefvD/vgQZOVw/mGR9Q== Generated by Nova\n", -} - -// SecondKeyPair is the second result in ListOutput. -var SecondKeyPair = KeyPair{ - Name: "secondkey", - Fingerprint: "35:9d:d0:c3:4a:80:d3:d8:86:f1:ca:f7:df:c4:f9:d8", - PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC9mC3WZN9UGLxgPBpP7H5jZMc6pKwOoSgre8yun6REFktn/Kz7DUt9jaR1UJyRzHxITfCfAIgSxPdGqB/oF1suMyWgu5i0625vavLB5z5kC8Hq3qZJ9zJO1poE1kyD+htiTtPWJ88e12xuH2XB/CZN9OpEiF98hAagiOE0EnOS5Q== Generated by Nova\n", -} - -// ExpectedKeyPairSlice is the slice of results that should be parsed from ListOutput, in the expected -// order. -var ExpectedKeyPairSlice = []KeyPair{FirstKeyPair, SecondKeyPair} - -// CreatedKeyPair is the parsed result from CreatedOutput. -var CreatedKeyPair = KeyPair{ - Name: "createdkey", - Fingerprint: "35:9d:d0:c3:4a:80:d3:d8:86:f1:ca:f7:df:c4:f9:d8", - PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC9mC3WZN9UGLxgPBpP7H5jZMc6pKwOoSgre8yun6REFktn/Kz7DUt9jaR1UJyRzHxITfCfAIgSxPdGqB/oF1suMyWgu5i0625vavLB5z5kC8Hq3qZJ9zJO1poE1kyD+htiTtPWJ88e12xuH2XB/CZN9OpEiF98hAagiOE0EnOS5Q== Generated by Nova\n", - PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQC9mC3WZN9UGLxgPBpP7H5jZMc6pKwOoSgre8yun6REFktn/Kz7\nDUt9jaR1UJyRzHxITfCfAIgSxPdGqB/oF1suMyWgu5i0625vavLB5z5kC8Hq3qZJ\n9zJO1poE1kyD+htiTtPWJ88e12xuH2XB/CZN9OpEiF98hAagiOE0EnOS5QIDAQAB\nAoGAE5XO1mDhORy9COvsg+kYPUhB1GsCYxh+v88wG7HeFDKBY6KUc/Kxo6yoGn5T\nTjRjekyi2KoDZHz4VlIzyZPwFS4I1bf3oCunVoAKzgLdmnTtvRNMC5jFOGc2vUgP\n9bSyRj3S1R4ClVk2g0IDeagko/jc8zzLEYuIK+fbkds79YECQQDt3vcevgegnkga\ntF4NsDmmBPRkcSHCqrANP/7vFcBQN3czxeYYWX3DK07alu6GhH1Y4sHbdm616uU0\nll7xbDzxAkEAzAtN2IyftNygV2EGiaGgqLyo/tD9+Vui2qCQplqe4jvWh/5Sparl\nOjmKo+uAW+hLrLVMnHzRWxbWU8hirH5FNQJATO+ZxCK4etXXAnQmG41NCAqANWB2\nB+2HJbH2NcQ2QHvAHUm741JGn/KI/aBlo7KEjFRDWUVUB5ji64BbUwCsMQJBAIku\nLGcjnBf/oLk+XSPZC2eGd2Ph5G5qYmH0Q2vkTx+wtTn3DV+eNsDfgMtWAJVJ5t61\ngU1QSXyhLPVlKpnnxuUCQC+xvvWjWtsLaFtAsZywJiqLxQzHts8XLGZptYJ5tLWV\nrtmYtBcJCN48RrgQHry/xWYeA4K/AFQpXfNPgprQ96Q=\n-----END RSA PRIVATE KEY-----\n", - UserID: "fake", -} - -// ImportedKeyPair is the parsed result from ImportOutput. -var ImportedKeyPair = KeyPair{ - Name: "importedkey", - Fingerprint: "1e:2c:9b:56:79:4b:45:77:f9:ca:7a:98:2c:b0:d5:3c", - PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGgB4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0lRE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYcpSxsIbECHw== Generated by Nova", - UserID: "fake", -} - -// HandleListSuccessfully configures the test server to respond to a List request. -func HandleListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-keypairs", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ListOutput) - }) -} - -// HandleGetSuccessfully configures the test server to respond to a Get request for "firstkey". -func HandleGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-keypairs/firstkey", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, GetOutput) - }) -} - -// HandleCreateSuccessfully configures the test server to respond to a Create request for a new -// keypair called "createdkey". -func HandleCreateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-keypairs", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "keypair": { "name": "createdkey" } }`) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, CreateOutput) - }) -} - -// HandleImportSuccessfully configures the test server to respond to an Import request for an -// existing keypair called "importedkey". -func HandleImportSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-keypairs", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, ` - { - "keypair": { - "name": "importedkey", - "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGgB4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0lRE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYcpSxsIbECHw== Generated by Nova" - } - } - `) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ImportOutput) - }) -} - -// HandleDeleteSuccessfully configures the test server to respond to a Delete request for a -// keypair called "deletedkey". -func HandleDeleteSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-keypairs/deletedkey", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusAccepted) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/requests.go deleted file mode 100644 index c56ee67ea..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/requests.go +++ /dev/null @@ -1,102 +0,0 @@ -package keypairs - -import ( - "errors" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/pagination" -) - -// CreateOptsExt adds a KeyPair option to the base CreateOpts. -type CreateOptsExt struct { - servers.CreateOptsBuilder - KeyName string `json:"key_name,omitempty"` -} - -// ToServerCreateMap adds the key_name and, optionally, key_data options to -// the base server creation options. -func (opts CreateOptsExt) ToServerCreateMap() (map[string]interface{}, error) { - base, err := opts.CreateOptsBuilder.ToServerCreateMap() - if err != nil { - return nil, err - } - - if opts.KeyName == "" { - return base, nil - } - - serverMap := base["server"].(map[string]interface{}) - serverMap["key_name"] = opts.KeyName - - return base, nil -} - -// List returns a Pager that allows you to iterate over a collection of KeyPairs. -func List(client *gophercloud.ServiceClient) pagination.Pager { - return pagination.NewPager(client, listURL(client), func(r pagination.PageResult) pagination.Page { - return KeyPairPage{pagination.SinglePageBase(r)} - }) -} - -// CreateOptsBuilder describes struct types that can be accepted by the Create call. Notable, the -// CreateOpts struct in this package does. -type CreateOptsBuilder interface { - ToKeyPairCreateMap() (map[string]interface{}, error) -} - -// CreateOpts specifies keypair creation or import parameters. -type CreateOpts struct { - // Name [required] is a friendly name to refer to this KeyPair in other services. - Name string - - // PublicKey [optional] is a pregenerated OpenSSH-formatted public key. If provided, this key - // will be imported and no new key will be created. - PublicKey string -} - -// ToKeyPairCreateMap constructs a request body from CreateOpts. -func (opts CreateOpts) ToKeyPairCreateMap() (map[string]interface{}, error) { - if opts.Name == "" { - return nil, errors.New("Missing field required for keypair creation: Name") - } - - keypair := make(map[string]interface{}) - keypair["name"] = opts.Name - if opts.PublicKey != "" { - keypair["public_key"] = opts.PublicKey - } - - return map[string]interface{}{"keypair": keypair}, nil -} - -// Create requests the creation of a new keypair on the server, or to import a pre-existing -// keypair. -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToKeyPairCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Post(createURL(client), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Get returns public data about a previously uploaded KeyPair. -func Get(client *gophercloud.ServiceClient, name string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, name), &res.Body, nil) - return res -} - -// Delete requests the deletion of a previous stored KeyPair from the server. -func Delete(client *gophercloud.ServiceClient, name string) DeleteResult { - var res DeleteResult - _, res.Err = client.Delete(deleteURL(client, name), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/results.go deleted file mode 100644 index f1a0d8e11..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/results.go +++ /dev/null @@ -1,94 +0,0 @@ -package keypairs - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// KeyPair is an SSH key known to the OpenStack cluster that is available to be injected into -// servers. -type KeyPair struct { - // Name is used to refer to this keypair from other services within this region. - Name string `mapstructure:"name"` - - // Fingerprint is a short sequence of bytes that can be used to authenticate or validate a longer - // public key. - Fingerprint string `mapstructure:"fingerprint"` - - // PublicKey is the public key from this pair, in OpenSSH format. "ssh-rsa AAAAB3Nz..." - PublicKey string `mapstructure:"public_key"` - - // PrivateKey is the private key from this pair, in PEM format. - // "-----BEGIN RSA PRIVATE KEY-----\nMIICXA..." It is only present if this keypair was just - // returned from a Create call - PrivateKey string `mapstructure:"private_key"` - - // UserID is the user who owns this keypair. - UserID string `mapstructure:"user_id"` -} - -// KeyPairPage stores a single, only page of KeyPair results from a List call. -type KeyPairPage struct { - pagination.SinglePageBase -} - -// IsEmpty determines whether or not a KeyPairPage is empty. -func (page KeyPairPage) IsEmpty() (bool, error) { - ks, err := ExtractKeyPairs(page) - return len(ks) == 0, err -} - -// ExtractKeyPairs interprets a page of results as a slice of KeyPairs. -func ExtractKeyPairs(page pagination.Page) ([]KeyPair, error) { - type pair struct { - KeyPair KeyPair `mapstructure:"keypair"` - } - - var resp struct { - KeyPairs []pair `mapstructure:"keypairs"` - } - - err := mapstructure.Decode(page.(KeyPairPage).Body, &resp) - results := make([]KeyPair, len(resp.KeyPairs)) - for i, pair := range resp.KeyPairs { - results[i] = pair.KeyPair - } - return results, err -} - -type keyPairResult struct { - gophercloud.Result -} - -// Extract is a method that attempts to interpret any KeyPair resource response as a KeyPair struct. -func (r keyPairResult) Extract() (*KeyPair, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - KeyPair *KeyPair `json:"keypair" mapstructure:"keypair"` - } - - err := mapstructure.Decode(r.Body, &res) - return res.KeyPair, err -} - -// CreateResult is the response from a Create operation. Call its Extract method to interpret it -// as a KeyPair. -type CreateResult struct { - keyPairResult -} - -// GetResult is the response from a Get operation. Call its Extract method to interpret it -// as a KeyPair. -type GetResult struct { - keyPairResult -} - -// DeleteResult is the response from a Delete operation. Call its Extract method to determine if -// the call succeeded or failed. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/urls.go deleted file mode 100644 index 702f5329e..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/urls.go +++ /dev/null @@ -1,25 +0,0 @@ -package keypairs - -import "github.com/rackspace/gophercloud" - -const resourcePath = "os-keypairs" - -func resourceURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(resourcePath) -} - -func listURL(c *gophercloud.ServiceClient) string { - return resourceURL(c) -} - -func createURL(c *gophercloud.ServiceClient) string { - return resourceURL(c) -} - -func getURL(c *gophercloud.ServiceClient, name string) string { - return c.ServiceURL(resourcePath, name) -} - -func deleteURL(c *gophercloud.ServiceClient, name string) string { - return getURL(c, name) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/doc.go deleted file mode 100644 index 0bd45661b..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package schedulerhints enables instances to provide the OpenStack scheduler -// hints about where they should be placed in the cloud. -package schedulerhints diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/requests.go deleted file mode 100644 index 567eef41a..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/requests.go +++ /dev/null @@ -1,134 +0,0 @@ -package schedulerhints - -import ( - "fmt" - "net" - "regexp" - "strings" - - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" -) - -// SchedulerHints represents a set of scheduling hints that are passed to the -// OpenStack scheduler -type SchedulerHints struct { - // Group specifies a Server Group to place the instance in. - Group string - - // DifferentHost will place the instance on a compute node that does not - // host the given instances. - DifferentHost []string - - // SameHost will place the instance on a compute node that hosts the given - // instances. - SameHost []string - - // Query is a conditional statement that results in compute nodes able to - // host the instance. - Query []interface{} - - // TargetCell specifies a cell name where the instance will be placed. - TargetCell string - - // BuildNearHostIP specifies a subnet of compute nodes to host the instance. - BuildNearHostIP string -} - -// SchedulerHintsBuilder builds the scheduler hints into a serializable format. -type SchedulerHintsBuilder interface { - ToServerSchedulerHintsMap() (map[string]interface{}, error) -} - -// ToServerSchedulerHintsMap builds the scheduler hints into a serializable format. -func (opts SchedulerHints) ToServerSchedulerHintsMap() (map[string]interface{}, error) { - sh := make(map[string]interface{}) - - uuidRegex, _ := regexp.Compile("^[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}$") - - if opts.Group != "" { - if !uuidRegex.MatchString(opts.Group) { - return nil, fmt.Errorf("Group must be a UUID") - } - sh["group"] = opts.Group - } - - if len(opts.DifferentHost) > 0 { - for _, diffHost := range opts.DifferentHost { - if !uuidRegex.MatchString(diffHost) { - return nil, fmt.Errorf("The hosts in DifferentHost must be in UUID format.") - } - } - sh["different_host"] = opts.DifferentHost - } - - if len(opts.SameHost) > 0 { - for _, sameHost := range opts.SameHost { - if !uuidRegex.MatchString(sameHost) { - return nil, fmt.Errorf("The hosts in SameHost must be in UUID format.") - } - } - sh["same_host"] = opts.SameHost - } - - /* Query can be something simple like: - [">=", "$free_ram_mb", 1024] - - Or more complex like: - ['and', - ['>=', '$free_ram_mb', 1024], - ['>=', '$free_disk_mb', 200 * 1024] - ] - - Because of the possible complexity, just make sure the length is a minimum of 3. - */ - if len(opts.Query) > 0 { - if len(opts.Query) < 3 { - return nil, fmt.Errorf("Query must be a conditional statement in the format of [op,variable,value]") - } - sh["query"] = opts.Query - } - - if opts.TargetCell != "" { - sh["target_cell"] = opts.TargetCell - } - - if opts.BuildNearHostIP != "" { - if _, _, err := net.ParseCIDR(opts.BuildNearHostIP); err != nil { - return nil, fmt.Errorf("BuildNearHostIP must be a valid subnet in the form 192.168.1.1/24") - } - ipParts := strings.Split(opts.BuildNearHostIP, "/") - sh["build_near_host_ip"] = ipParts[0] - sh["cidr"] = "/" + ipParts[1] - } - - return sh, nil -} - -// CreateOptsExt adds a SchedulerHints option to the base CreateOpts. -type CreateOptsExt struct { - servers.CreateOptsBuilder - - // SchedulerHints provides a set of hints to the scheduler. - SchedulerHints SchedulerHintsBuilder -} - -// ToServerCreateMap adds the SchedulerHints option to the base server creation options. -func (opts CreateOptsExt) ToServerCreateMap() (map[string]interface{}, error) { - base, err := opts.CreateOptsBuilder.ToServerCreateMap() - if err != nil { - return nil, err - } - - schedulerHints, err := opts.SchedulerHints.ToServerSchedulerHintsMap() - if err != nil { - return nil, err - } - - if len(schedulerHints) == 0 { - return base, nil - } - - base["os:scheduler_hints"] = schedulerHints - - return base, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/doc.go deleted file mode 100644 index 702f32c98..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/doc.go +++ /dev/null @@ -1 +0,0 @@ -package secgroups diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/fixtures.go deleted file mode 100644 index d58d90894..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/fixtures.go +++ /dev/null @@ -1,305 +0,0 @@ -// +build fixtures - -package secgroups - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -const rootPath = "/os-security-groups" - -const listGroupsJSON = ` -{ - "security_groups": [ - { - "description": "default", - "id": "{groupID}", - "name": "default", - "rules": [], - "tenant_id": "openstack" - } - ] -} -` - -func mockListGroupsResponse(t *testing.T) { - th.Mux.HandleFunc(rootPath, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, listGroupsJSON) - }) -} - -func mockListGroupsByServerResponse(t *testing.T, serverID string) { - url := fmt.Sprintf("/servers/%s%s", serverID, rootPath) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, listGroupsJSON) - }) -} - -func mockCreateGroupResponse(t *testing.T) { - th.Mux.HandleFunc(rootPath, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - th.TestJSONRequest(t, r, ` -{ - "security_group": { - "name": "test", - "description": "something" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group": { - "description": "something", - "id": "{groupID}", - "name": "test", - "rules": [], - "tenant_id": "openstack" - } -} -`) - }) -} - -func mockUpdateGroupResponse(t *testing.T, groupID string) { - url := fmt.Sprintf("%s/%s", rootPath, groupID) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - th.TestJSONRequest(t, r, ` -{ - "security_group": { - "name": "new_name", - "description": "new_desc" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group": { - "description": "something", - "id": "{groupID}", - "name": "new_name", - "rules": [], - "tenant_id": "openstack" - } -} -`) - }) -} - -func mockGetGroupsResponse(t *testing.T, groupID string) { - url := fmt.Sprintf("%s/%s", rootPath, groupID) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group": { - "description": "default", - "id": "{groupID}", - "name": "default", - "rules": [ - { - "from_port": 80, - "group": { - "tenant_id": "openstack", - "name": "default" - }, - "ip_protocol": "TCP", - "to_port": 85, - "parent_group_id": "{groupID}", - "ip_range": { - "cidr": "0.0.0.0" - }, - "id": "{ruleID}" - } - ], - "tenant_id": "openstack" - } -} - `) - }) -} - -func mockGetNumericIDGroupResponse(t *testing.T, groupID int) { - url := fmt.Sprintf("%s/%d", rootPath, groupID) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group": { - "id": 12345 - } -} - `) - }) -} - -func mockDeleteGroupResponse(t *testing.T, groupID string) { - url := fmt.Sprintf("%s/%s", rootPath, groupID) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusAccepted) - }) -} - -func mockAddRuleResponse(t *testing.T) { - th.Mux.HandleFunc("/os-security-group-rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - th.TestJSONRequest(t, r, ` -{ - "security_group_rule": { - "from_port": 22, - "ip_protocol": "TCP", - "to_port": 22, - "parent_group_id": "{groupID}", - "cidr": "0.0.0.0/0" - } -} `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group_rule": { - "from_port": 22, - "group": {}, - "ip_protocol": "TCP", - "to_port": 22, - "parent_group_id": "{groupID}", - "ip_range": { - "cidr": "0.0.0.0/0" - }, - "id": "{ruleID}" - } -}`) - }) -} - -func mockAddRuleResponseICMPZero(t *testing.T) { - th.Mux.HandleFunc("/os-security-group-rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - th.TestJSONRequest(t, r, ` -{ - "security_group_rule": { - "from_port": 0, - "ip_protocol": "ICMP", - "to_port": 0, - "parent_group_id": "{groupID}", - "cidr": "0.0.0.0/0" - } -} `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group_rule": { - "from_port": 0, - "group": {}, - "ip_protocol": "ICMP", - "to_port": 0, - "parent_group_id": "{groupID}", - "ip_range": { - "cidr": "0.0.0.0/0" - }, - "id": "{ruleID}" - } -}`) - }) -} - -func mockDeleteRuleResponse(t *testing.T, ruleID string) { - url := fmt.Sprintf("/os-security-group-rules/%s", ruleID) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusAccepted) - }) -} - -func mockAddServerToGroupResponse(t *testing.T, serverID string) { - url := fmt.Sprintf("/servers/%s/action", serverID) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - th.TestJSONRequest(t, r, ` -{ - "addSecurityGroup": { - "name": "test" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusAccepted) - fmt.Fprintf(w, `{}`) - }) -} - -func mockRemoveServerFromGroupResponse(t *testing.T, serverID string) { - url := fmt.Sprintf("/servers/%s/action", serverID) - th.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - th.TestJSONRequest(t, r, ` -{ - "removeSecurityGroup": { - "name": "test" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusAccepted) - fmt.Fprintf(w, `{}`) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/requests.go deleted file mode 100644 index 120dcae3c..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/requests.go +++ /dev/null @@ -1,258 +0,0 @@ -package secgroups - -import ( - "errors" - "strings" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -func commonList(client *gophercloud.ServiceClient, url string) pagination.Pager { - createPage := func(r pagination.PageResult) pagination.Page { - return SecurityGroupPage{pagination.SinglePageBase(r)} - } - - return pagination.NewPager(client, url, createPage) -} - -// List will return a collection of all the security groups for a particular -// tenant. -func List(client *gophercloud.ServiceClient) pagination.Pager { - return commonList(client, rootURL(client)) -} - -// ListByServer will return a collection of all the security groups which are -// associated with a particular server. -func ListByServer(client *gophercloud.ServiceClient, serverID string) pagination.Pager { - return commonList(client, listByServerURL(client, serverID)) -} - -// GroupOpts is the underlying struct responsible for creating or updating -// security groups. It therefore represents the mutable attributes of a -// security group. -type GroupOpts struct { - // Required - the name of your security group. - Name string `json:"name"` - - // Required - the description of your security group. - Description string `json:"description"` -} - -// CreateOpts is the struct responsible for creating a security group. -type CreateOpts GroupOpts - -// CreateOptsBuilder builds the create options into a serializable format. -type CreateOptsBuilder interface { - ToSecGroupCreateMap() (map[string]interface{}, error) -} - -var ( - errName = errors.New("Name is a required field") - errDesc = errors.New("Description is a required field") -) - -// ToSecGroupCreateMap builds the create options into a serializable format. -func (opts CreateOpts) ToSecGroupCreateMap() (map[string]interface{}, error) { - sg := make(map[string]interface{}) - - if opts.Name == "" { - return sg, errName - } - if opts.Description == "" { - return sg, errDesc - } - - sg["name"] = opts.Name - sg["description"] = opts.Description - - return map[string]interface{}{"security_group": sg}, nil -} - -// Create will create a new security group. -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var result CreateResult - - reqBody, err := opts.ToSecGroupCreateMap() - if err != nil { - result.Err = err - return result - } - - _, result.Err = client.Post(rootURL(client), reqBody, &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return result -} - -// UpdateOpts is the struct responsible for updating an existing security group. -type UpdateOpts GroupOpts - -// UpdateOptsBuilder builds the update options into a serializable format. -type UpdateOptsBuilder interface { - ToSecGroupUpdateMap() (map[string]interface{}, error) -} - -// ToSecGroupUpdateMap builds the update options into a serializable format. -func (opts UpdateOpts) ToSecGroupUpdateMap() (map[string]interface{}, error) { - sg := make(map[string]interface{}) - - if opts.Name == "" { - return sg, errName - } - if opts.Description == "" { - return sg, errDesc - } - - sg["name"] = opts.Name - sg["description"] = opts.Description - - return map[string]interface{}{"security_group": sg}, nil -} - -// Update will modify the mutable properties of a security group, notably its -// name and description. -func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var result UpdateResult - - reqBody, err := opts.ToSecGroupUpdateMap() - if err != nil { - result.Err = err - return result - } - - _, result.Err = client.Put(resourceURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return result -} - -// Get will return details for a particular security group. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var result GetResult - _, result.Err = client.Get(resourceURL(client, id), &result.Body, nil) - return result -} - -// Delete will permanently delete a security group from the project. -func Delete(client *gophercloud.ServiceClient, id string) gophercloud.ErrResult { - var result gophercloud.ErrResult - _, result.Err = client.Delete(resourceURL(client, id), nil) - return result -} - -// CreateRuleOpts represents the configuration for adding a new rule to an -// existing security group. -type CreateRuleOpts struct { - // Required - the ID of the group that this rule will be added to. - ParentGroupID string `json:"parent_group_id"` - - // Required - the lower bound of the port range that will be opened. - FromPort int `json:"from_port"` - - // Required - the upper bound of the port range that will be opened. - ToPort int `json:"to_port"` - - // Required - the protocol type that will be allowed, e.g. TCP. - IPProtocol string `json:"ip_protocol"` - - // ONLY required if FromGroupID is blank. This represents the IP range that - // will be the source of network traffic to your security group. Use - // 0.0.0.0/0 to allow all IP addresses. - CIDR string `json:"cidr,omitempty"` - - // ONLY required if CIDR is blank. This value represents the ID of a group - // that forwards traffic to the parent group. So, instead of accepting - // network traffic from an entire IP range, you can instead refine the - // inbound source by an existing security group. - FromGroupID string `json:"group_id,omitempty"` -} - -// CreateRuleOptsBuilder builds the create rule options into a serializable format. -type CreateRuleOptsBuilder interface { - ToRuleCreateMap() (map[string]interface{}, error) -} - -// ToRuleCreateMap builds the create rule options into a serializable format. -func (opts CreateRuleOpts) ToRuleCreateMap() (map[string]interface{}, error) { - rule := make(map[string]interface{}) - - if opts.ParentGroupID == "" { - return rule, errors.New("A ParentGroupID must be set") - } - if opts.FromPort == 0 && strings.ToUpper(opts.IPProtocol) != "ICMP" { - return rule, errors.New("A FromPort must be set") - } - if opts.ToPort == 0 && strings.ToUpper(opts.IPProtocol) != "ICMP" { - return rule, errors.New("A ToPort must be set") - } - if opts.IPProtocol == "" { - return rule, errors.New("A IPProtocol must be set") - } - if opts.CIDR == "" && opts.FromGroupID == "" { - return rule, errors.New("A CIDR or FromGroupID must be set") - } - - rule["parent_group_id"] = opts.ParentGroupID - rule["from_port"] = opts.FromPort - rule["to_port"] = opts.ToPort - rule["ip_protocol"] = opts.IPProtocol - - if opts.CIDR != "" { - rule["cidr"] = opts.CIDR - } - if opts.FromGroupID != "" { - rule["group_id"] = opts.FromGroupID - } - - return map[string]interface{}{"security_group_rule": rule}, nil -} - -// CreateRule will add a new rule to an existing security group (whose ID is -// specified in CreateRuleOpts). You have the option of controlling inbound -// traffic from either an IP range (CIDR) or from another security group. -func CreateRule(client *gophercloud.ServiceClient, opts CreateRuleOptsBuilder) CreateRuleResult { - var result CreateRuleResult - - reqBody, err := opts.ToRuleCreateMap() - if err != nil { - result.Err = err - return result - } - - _, result.Err = client.Post(rootRuleURL(client), reqBody, &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return result -} - -// DeleteRule will permanently delete a rule from a security group. -func DeleteRule(client *gophercloud.ServiceClient, id string) gophercloud.ErrResult { - var result gophercloud.ErrResult - _, result.Err = client.Delete(resourceRuleURL(client, id), nil) - return result -} - -func actionMap(prefix, groupName string) map[string]map[string]string { - return map[string]map[string]string{ - prefix + "SecurityGroup": map[string]string{"name": groupName}, - } -} - -// AddServerToGroup will associate a server and a security group, enforcing the -// rules of the group on the server. -func AddServerToGroup(client *gophercloud.ServiceClient, serverID, groupName string) gophercloud.ErrResult { - var result gophercloud.ErrResult - _, result.Err = client.Post(serverActionURL(client, serverID), actionMap("add", groupName), &result.Body, nil) - return result -} - -// RemoveServerFromGroup will disassociate a server from a security group. -func RemoveServerFromGroup(client *gophercloud.ServiceClient, serverID, groupName string) gophercloud.ErrResult { - var result gophercloud.ErrResult - _, result.Err = client.Post(serverActionURL(client, serverID), actionMap("remove", groupName), &result.Body, nil) - return result -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/results.go deleted file mode 100644 index 478c5dc09..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/results.go +++ /dev/null @@ -1,147 +0,0 @@ -package secgroups - -import ( - "github.com/mitchellh/mapstructure" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// SecurityGroup represents a security group. -type SecurityGroup struct { - // The unique ID of the group. If Neutron is installed, this ID will be - // represented as a string UUID; if Neutron is not installed, it will be a - // numeric ID. For the sake of consistency, we always cast it to a string. - ID string - - // The human-readable name of the group, which needs to be unique. - Name string - - // The human-readable description of the group. - Description string - - // The rules which determine how this security group operates. - Rules []Rule - - // The ID of the tenant to which this security group belongs. - TenantID string `mapstructure:"tenant_id"` -} - -// Rule represents a security group rule, a policy which determines how a -// security group operates and what inbound traffic it allows in. -type Rule struct { - // The unique ID. If Neutron is installed, this ID will be - // represented as a string UUID; if Neutron is not installed, it will be a - // numeric ID. For the sake of consistency, we always cast it to a string. - ID string - - // The lower bound of the port range which this security group should open up - FromPort int `mapstructure:"from_port"` - - // The upper bound of the port range which this security group should open up - ToPort int `mapstructure:"to_port"` - - // The IP protocol (e.g. TCP) which the security group accepts - IPProtocol string `mapstructure:"ip_protocol"` - - // The CIDR IP range whose traffic can be received - IPRange IPRange `mapstructure:"ip_range"` - - // The security group ID to which this rule belongs - ParentGroupID string `mapstructure:"parent_group_id"` - - // Not documented. - Group Group -} - -// IPRange represents the IP range whose traffic will be accepted by the -// security group. -type IPRange struct { - CIDR string -} - -// Group represents a group. -type Group struct { - TenantID string `mapstructure:"tenant_id"` - Name string -} - -// SecurityGroupPage is a single page of a SecurityGroup collection. -type SecurityGroupPage struct { - pagination.SinglePageBase -} - -// IsEmpty determines whether or not a page of Security Groups contains any results. -func (page SecurityGroupPage) IsEmpty() (bool, error) { - users, err := ExtractSecurityGroups(page) - if err != nil { - return false, err - } - return len(users) == 0, nil -} - -// ExtractSecurityGroups returns a slice of SecurityGroups contained in a single page of results. -func ExtractSecurityGroups(page pagination.Page) ([]SecurityGroup, error) { - casted := page.(SecurityGroupPage).Body - var response struct { - SecurityGroups []SecurityGroup `mapstructure:"security_groups"` - } - - err := mapstructure.WeakDecode(casted, &response) - - return response.SecurityGroups, err -} - -type commonResult struct { - gophercloud.Result -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// Extract will extract a SecurityGroup struct from most responses. -func (r commonResult) Extract() (*SecurityGroup, error) { - if r.Err != nil { - return nil, r.Err - } - - var response struct { - SecurityGroup SecurityGroup `mapstructure:"security_group"` - } - - err := mapstructure.WeakDecode(r.Body, &response) - - return &response.SecurityGroup, err -} - -// CreateRuleResult represents the result when adding rules to a security group. -type CreateRuleResult struct { - gophercloud.Result -} - -// Extract will extract a Rule struct from a CreateRuleResult. -func (r CreateRuleResult) Extract() (*Rule, error) { - if r.Err != nil { - return nil, r.Err - } - - var response struct { - Rule Rule `mapstructure:"security_group_rule"` - } - - err := mapstructure.WeakDecode(r.Body, &response) - - return &response.Rule, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/urls.go deleted file mode 100644 index dc53fbfac..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/urls.go +++ /dev/null @@ -1,32 +0,0 @@ -package secgroups - -import "github.com/rackspace/gophercloud" - -const ( - secgrouppath = "os-security-groups" - rulepath = "os-security-group-rules" -) - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(secgrouppath, id) -} - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(secgrouppath) -} - -func listByServerURL(c *gophercloud.ServiceClient, serverID string) string { - return c.ServiceURL("servers", serverID, secgrouppath) -} - -func rootRuleURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rulepath) -} - -func resourceRuleURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rulepath, id) -} - -func serverActionURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL("servers", id, "action") -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/doc.go deleted file mode 100644 index 1e5ed568d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package servergroups provides the ability to manage server groups -package servergroups diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/fixtures.go deleted file mode 100644 index 133fd85ce..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/fixtures.go +++ /dev/null @@ -1,161 +0,0 @@ -// +build fixtures - -package servergroups - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// ListOutput is a sample response to a List call. -const ListOutput = ` -{ - "server_groups": [ - { - "id": "616fb98f-46ca-475e-917e-2563e5a8cd19", - "name": "test", - "policies": [ - "anti-affinity" - ], - "members": [], - "metadata": {} - }, - { - "id": "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - "name": "test2", - "policies": [ - "affinity" - ], - "members": [], - "metadata": {} - } - ] -} -` - -// GetOutput is a sample response to a Get call. -const GetOutput = ` -{ - "server_group": { - "id": "616fb98f-46ca-475e-917e-2563e5a8cd19", - "name": "test", - "policies": [ - "anti-affinity" - ], - "members": [], - "metadata": {} - } -} -` - -// CreateOutput is a sample response to a Post call -const CreateOutput = ` -{ - "server_group": { - "id": "616fb98f-46ca-475e-917e-2563e5a8cd19", - "name": "test", - "policies": [ - "anti-affinity" - ], - "members": [], - "metadata": {} - } -} -` - -// FirstServerGroup is the first result in ListOutput. -var FirstServerGroup = ServerGroup{ - ID: "616fb98f-46ca-475e-917e-2563e5a8cd19", - Name: "test", - Policies: []string{ - "anti-affinity", - }, - Members: []string{}, - Metadata: map[string]interface{}{}, -} - -// SecondServerGroup is the second result in ListOutput. -var SecondServerGroup = ServerGroup{ - ID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - Name: "test2", - Policies: []string{ - "affinity", - }, - Members: []string{}, - Metadata: map[string]interface{}{}, -} - -// ExpectedServerGroupSlice is the slice of results that should be parsed -// from ListOutput, in the expected order. -var ExpectedServerGroupSlice = []ServerGroup{FirstServerGroup, SecondServerGroup} - -// CreatedServerGroup is the parsed result from CreateOutput. -var CreatedServerGroup = ServerGroup{ - ID: "616fb98f-46ca-475e-917e-2563e5a8cd19", - Name: "test", - Policies: []string{ - "anti-affinity", - }, - Members: []string{}, - Metadata: map[string]interface{}{}, -} - -// HandleListSuccessfully configures the test server to respond to a List request. -func HandleListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-server-groups", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ListOutput) - }) -} - -// HandleGetSuccessfully configures the test server to respond to a Get request -// for an existing server group -func HandleGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-server-groups/4d8c3732-a248-40ed-bebc-539a6ffd25c0", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, GetOutput) - }) -} - -// HandleCreateSuccessfully configures the test server to respond to a Create request -// for a new server group -func HandleCreateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-server-groups", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, ` -{ - "server_group": { - "name": "test", - "policies": [ - "anti-affinity" - ] - } -} -`) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, CreateOutput) - }) -} - -// HandleDeleteSuccessfully configures the test server to respond to a Delete request for a -// an existing server group -func HandleDeleteSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-server-groups/616fb98f-46ca-475e-917e-2563e5a8cd19", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusAccepted) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/requests.go deleted file mode 100644 index 1597b43eb..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/requests.go +++ /dev/null @@ -1,77 +0,0 @@ -package servergroups - -import ( - "errors" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// List returns a Pager that allows you to iterate over a collection of ServerGroups. -func List(client *gophercloud.ServiceClient) pagination.Pager { - return pagination.NewPager(client, listURL(client), func(r pagination.PageResult) pagination.Page { - return ServerGroupsPage{pagination.SinglePageBase(r)} - }) -} - -// CreateOptsBuilder describes struct types that can be accepted by the Create call. Notably, the -// CreateOpts struct in this package does. -type CreateOptsBuilder interface { - ToServerGroupCreateMap() (map[string]interface{}, error) -} - -// CreateOpts specifies a Server Group allocation request -type CreateOpts struct { - // Name is the name of the server group - Name string - - // Policies are the server group policies - Policies []string -} - -// ToServerGroupCreateMap constructs a request body from CreateOpts. -func (opts CreateOpts) ToServerGroupCreateMap() (map[string]interface{}, error) { - if opts.Name == "" { - return nil, errors.New("Missing field required for server group creation: Name") - } - - if len(opts.Policies) < 1 { - return nil, errors.New("Missing field required for server group creation: Policies") - } - - serverGroup := make(map[string]interface{}) - serverGroup["name"] = opts.Name - serverGroup["policies"] = opts.Policies - - return map[string]interface{}{"server_group": serverGroup}, nil -} - -// Create requests the creation of a new Server Group -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToServerGroupCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Post(createURL(client), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Get returns data about a previously created ServerGroup. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, id), &res.Body, nil) - return res -} - -// Delete requests the deletion of a previously allocated ServerGroup. -func Delete(client *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = client.Delete(deleteURL(client, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/results.go deleted file mode 100644 index d74ee5dbb..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/results.go +++ /dev/null @@ -1,87 +0,0 @@ -package servergroups - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// A ServerGroup creates a policy for instance placement in the cloud -type ServerGroup struct { - // ID is the unique ID of the Server Group. - ID string `mapstructure:"id"` - - // Name is the common name of the server group. - Name string `mapstructure:"name"` - - // Polices are the group policies. - Policies []string `mapstructure:"policies"` - - // Members are the members of the server group. - Members []string `mapstructure:"members"` - - // Metadata includes a list of all user-specified key-value pairs attached to the Server Group. - Metadata map[string]interface{} -} - -// ServerGroupsPage stores a single, only page of ServerGroups -// results from a List call. -type ServerGroupsPage struct { - pagination.SinglePageBase -} - -// IsEmpty determines whether or not a ServerGroupsPage is empty. -func (page ServerGroupsPage) IsEmpty() (bool, error) { - va, err := ExtractServerGroups(page) - return len(va) == 0, err -} - -// ExtractServerGroups interprets a page of results as a slice of -// ServerGroups. -func ExtractServerGroups(page pagination.Page) ([]ServerGroup, error) { - casted := page.(ServerGroupsPage).Body - var response struct { - ServerGroups []ServerGroup `mapstructure:"server_groups"` - } - - err := mapstructure.WeakDecode(casted, &response) - - return response.ServerGroups, err -} - -type ServerGroupResult struct { - gophercloud.Result -} - -// Extract is a method that attempts to interpret any Server Group resource -// response as a ServerGroup struct. -func (r ServerGroupResult) Extract() (*ServerGroup, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - ServerGroup *ServerGroup `json:"server_group" mapstructure:"server_group"` - } - - err := mapstructure.WeakDecode(r.Body, &res) - return res.ServerGroup, err -} - -// CreateResult is the response from a Create operation. Call its Extract method to interpret it -// as a ServerGroup. -type CreateResult struct { - ServerGroupResult -} - -// GetResult is the response from a Get operation. Call its Extract method to interpret it -// as a ServerGroup. -type GetResult struct { - ServerGroupResult -} - -// DeleteResult is the response from a Delete operation. Call its Extract method to determine if -// the call succeeded or failed. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/urls.go deleted file mode 100644 index 074a16c67..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/urls.go +++ /dev/null @@ -1,25 +0,0 @@ -package servergroups - -import "github.com/rackspace/gophercloud" - -const resourcePath = "os-server-groups" - -func resourceURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(resourcePath) -} - -func listURL(c *gophercloud.ServiceClient) string { - return resourceURL(c) -} - -func createURL(c *gophercloud.ServiceClient) string { - return resourceURL(c) -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(resourcePath, id) -} - -func deleteURL(c *gophercloud.ServiceClient, id string) string { - return getURL(c, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/doc.go deleted file mode 100644 index d2729f874..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -/* -Package startstop provides functionality to start and stop servers that have -been provisioned by the OpenStack Compute service. -*/ -package startstop diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/fixtures.go deleted file mode 100644 index e2c33fe2d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/fixtures.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build fixtures - -package startstop - -import ( - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func mockStartServerResponse(t *testing.T, id string) { - th.Mux.HandleFunc("/servers/"+id+"/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{"os-start": null}`) - w.WriteHeader(http.StatusAccepted) - }) -} - -func mockStopServerResponse(t *testing.T, id string) { - th.Mux.HandleFunc("/servers/"+id+"/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{"os-stop": null}`) - w.WriteHeader(http.StatusAccepted) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/requests.go deleted file mode 100644 index 0e090e69f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/requests.go +++ /dev/null @@ -1,23 +0,0 @@ -package startstop - -import "github.com/rackspace/gophercloud" - -func actionURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("servers", id, "action") -} - -// Start is the operation responsible for starting a Compute server. -func Start(client *gophercloud.ServiceClient, id string) gophercloud.ErrResult { - var res gophercloud.ErrResult - reqBody := map[string]interface{}{"os-start": nil} - _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil) - return res -} - -// Stop is the operation responsible for stopping a Compute server. -func Stop(client *gophercloud.ServiceClient, id string) gophercloud.ErrResult { - var res gophercloud.ErrResult - reqBody := map[string]interface{}{"os-stop": nil} - _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/doc.go deleted file mode 100644 index 65c46ff50..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package tenantnetworks provides the ability for tenants to see information about the networks they have access to -package tenantnetworks diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/fixtures.go deleted file mode 100644 index 0cfa72ab0..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/fixtures.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build fixtures - -package tenantnetworks - -import ( - "fmt" - "net/http" - "testing" - "time" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// ListOutput is a sample response to a List call. -const ListOutput = ` -{ - "networks": [ - { - "cidr": "10.0.0.0/29", - "id": "20c8acc0-f747-4d71-a389-46d078ebf047", - "label": "mynet_0" - }, - { - "cidr": "10.0.0.10/29", - "id": "20c8acc0-f747-4d71-a389-46d078ebf000", - "label": "mynet_1" - } - ] -} -` - -// GetOutput is a sample response to a Get call. -const GetOutput = ` -{ - "network": { - "cidr": "10.0.0.10/29", - "id": "20c8acc0-f747-4d71-a389-46d078ebf000", - "label": "mynet_1" - } -} -` - -// FirstNetwork is the first result in ListOutput. -var nilTime time.Time -var FirstNetwork = Network{ - CIDR: "10.0.0.0/29", - ID: "20c8acc0-f747-4d71-a389-46d078ebf047", - Name: "mynet_0", -} - -// SecondNetwork is the second result in ListOutput. -var SecondNetwork = Network{ - CIDR: "10.0.0.10/29", - ID: "20c8acc0-f747-4d71-a389-46d078ebf000", - Name: "mynet_1", -} - -// ExpectedNetworkSlice is the slice of results that should be parsed -// from ListOutput, in the expected order. -var ExpectedNetworkSlice = []Network{FirstNetwork, SecondNetwork} - -// HandleListSuccessfully configures the test server to respond to a List request. -func HandleListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-tenant-networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ListOutput) - }) -} - -// HandleGetSuccessfully configures the test server to respond to a Get request -// for an existing network. -func HandleGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/os-tenant-networks/20c8acc0-f747-4d71-a389-46d078ebf000", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, GetOutput) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/requests.go deleted file mode 100644 index 3ec13d384..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/requests.go +++ /dev/null @@ -1,22 +0,0 @@ -package tenantnetworks - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// List returns a Pager that allows you to iterate over a collection of Network. -func List(client *gophercloud.ServiceClient) pagination.Pager { - url := listURL(client) - createPage := func(r pagination.PageResult) pagination.Page { - return NetworkPage{pagination.SinglePageBase(r)} - } - return pagination.NewPager(client, url, createPage) -} - -// Get returns data about a previously created Network. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, id), &res.Body, nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/results.go deleted file mode 100644 index 805009247..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/results.go +++ /dev/null @@ -1,68 +0,0 @@ -package tenantnetworks - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// A Network represents a nova-network that an instance communicates on -type Network struct { - // CIDR is the IPv4 subnet. - CIDR string `mapstructure:"cidr"` - - // ID is the UUID of the network. - ID string `mapstructure:"id"` - - // Name is the common name that the network has. - Name string `mapstructure:"label"` -} - -// NetworkPage stores a single, only page of Networks -// results from a List call. -type NetworkPage struct { - pagination.SinglePageBase -} - -// IsEmpty determines whether or not a NetworkPage is empty. -func (page NetworkPage) IsEmpty() (bool, error) { - va, err := ExtractNetworks(page) - return len(va) == 0, err -} - -// ExtractNetworks interprets a page of results as a slice of Networks -func ExtractNetworks(page pagination.Page) ([]Network, error) { - networks := page.(NetworkPage).Body - var res struct { - Networks []Network `mapstructure:"networks"` - } - - err := mapstructure.WeakDecode(networks, &res) - - return res.Networks, err -} - -type NetworkResult struct { - gophercloud.Result -} - -// Extract is a method that attempts to interpret any Network resource -// response as a Network struct. -func (r NetworkResult) Extract() (*Network, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Network *Network `json:"network" mapstructure:"network"` - } - - err := mapstructure.Decode(r.Body, &res) - return res.Network, err -} - -// GetResult is the response from a Get operation. Call its Extract method to interpret it -// as a Network. -type GetResult struct { - NetworkResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/urls.go deleted file mode 100644 index 2401a5d03..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/urls.go +++ /dev/null @@ -1,17 +0,0 @@ -package tenantnetworks - -import "github.com/rackspace/gophercloud" - -const resourcePath = "os-tenant-networks" - -func resourceURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(resourcePath) -} - -func listURL(c *gophercloud.ServiceClient) string { - return resourceURL(c) -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/doc.go deleted file mode 100644 index 22f68d80e..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package volumeattach provides the ability to attach and detach volumes -// to instances -package volumeattach diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/requests.go deleted file mode 100644 index b4ebedea8..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/requests.go +++ /dev/null @@ -1,75 +0,0 @@ -package volumeattach - -import ( - "errors" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// List returns a Pager that allows you to iterate over a collection of VolumeAttachments. -func List(client *gophercloud.ServiceClient, serverId string) pagination.Pager { - return pagination.NewPager(client, listURL(client, serverId), func(r pagination.PageResult) pagination.Page { - return VolumeAttachmentsPage{pagination.SinglePageBase(r)} - }) -} - -// CreateOptsBuilder describes struct types that can be accepted by the Create call. Notable, the -// CreateOpts struct in this package does. -type CreateOptsBuilder interface { - ToVolumeAttachmentCreateMap() (map[string]interface{}, error) -} - -// CreateOpts specifies volume attachment creation or import parameters. -type CreateOpts struct { - // Device is the device that the volume will attach to the instance as. Omit for "auto" - Device string - - // VolumeID is the ID of the volume to attach to the instance - VolumeID string -} - -// ToVolumeAttachmentCreateMap constructs a request body from CreateOpts. -func (opts CreateOpts) ToVolumeAttachmentCreateMap() (map[string]interface{}, error) { - if opts.VolumeID == "" { - return nil, errors.New("Missing field required for volume attachment creation: VolumeID") - } - - volumeAttachment := make(map[string]interface{}) - volumeAttachment["volumeId"] = opts.VolumeID - if opts.Device != "" { - volumeAttachment["device"] = opts.Device - } - - return map[string]interface{}{"volumeAttachment": volumeAttachment}, nil -} - -// Create requests the creation of a new volume attachment on the server -func Create(client *gophercloud.ServiceClient, serverId string, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToVolumeAttachmentCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Post(createURL(client, serverId), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Get returns public data about a previously created VolumeAttachment. -func Get(client *gophercloud.ServiceClient, serverId, aId string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, serverId, aId), &res.Body, nil) - return res -} - -// Delete requests the deletion of a previous stored VolumeAttachment from the server. -func Delete(client *gophercloud.ServiceClient, serverId, aId string) DeleteResult { - var res DeleteResult - _, res.Err = client.Delete(deleteURL(client, serverId, aId), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/results.go deleted file mode 100644 index 26be39e4f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/results.go +++ /dev/null @@ -1,84 +0,0 @@ -package volumeattach - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// VolumeAttach controls the attachment of a volume to an instance. -type VolumeAttachment struct { - // ID is a unique id of the attachment - ID string `mapstructure:"id"` - - // Device is what device the volume is attached as - Device string `mapstructure:"device"` - - // VolumeID is the ID of the attached volume - VolumeID string `mapstructure:"volumeId"` - - // ServerID is the ID of the instance that has the volume attached - ServerID string `mapstructure:"serverId"` -} - -// VolumeAttachmentsPage stores a single, only page of VolumeAttachments -// results from a List call. -type VolumeAttachmentsPage struct { - pagination.SinglePageBase -} - -// IsEmpty determines whether or not a VolumeAttachmentsPage is empty. -func (page VolumeAttachmentsPage) IsEmpty() (bool, error) { - va, err := ExtractVolumeAttachments(page) - return len(va) == 0, err -} - -// ExtractVolumeAttachments interprets a page of results as a slice of -// VolumeAttachments. -func ExtractVolumeAttachments(page pagination.Page) ([]VolumeAttachment, error) { - casted := page.(VolumeAttachmentsPage).Body - var response struct { - VolumeAttachments []VolumeAttachment `mapstructure:"volumeAttachments"` - } - - err := mapstructure.WeakDecode(casted, &response) - - return response.VolumeAttachments, err -} - -type VolumeAttachmentResult struct { - gophercloud.Result -} - -// Extract is a method that attempts to interpret any VolumeAttachment resource -// response as a VolumeAttachment struct. -func (r VolumeAttachmentResult) Extract() (*VolumeAttachment, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - VolumeAttachment *VolumeAttachment `json:"volumeAttachment" mapstructure:"volumeAttachment"` - } - - err := mapstructure.Decode(r.Body, &res) - return res.VolumeAttachment, err -} - -// CreateResult is the response from a Create operation. Call its Extract method to interpret it -// as a VolumeAttachment. -type CreateResult struct { - VolumeAttachmentResult -} - -// GetResult is the response from a Get operation. Call its Extract method to interpret it -// as a VolumeAttachment. -type GetResult struct { - VolumeAttachmentResult -} - -// DeleteResult is the response from a Delete operation. Call its Extract method to determine if -// the call succeeded or failed. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/urls.go deleted file mode 100644 index 9d9d1786d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/urls.go +++ /dev/null @@ -1,25 +0,0 @@ -package volumeattach - -import "github.com/rackspace/gophercloud" - -const resourcePath = "os-volume_attachments" - -func resourceURL(c *gophercloud.ServiceClient, serverId string) string { - return c.ServiceURL("servers", serverId, resourcePath) -} - -func listURL(c *gophercloud.ServiceClient, serverId string) string { - return resourceURL(c, serverId) -} - -func createURL(c *gophercloud.ServiceClient, serverId string) string { - return resourceURL(c, serverId) -} - -func getURL(c *gophercloud.ServiceClient, serverId, aId string) string { - return c.ServiceURL("servers", serverId, resourcePath, aId) -} - -func deleteURL(c *gophercloud.ServiceClient, serverId, aId string) string { - return getURL(c, serverId, aId) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/doc.go deleted file mode 100644 index 5822e1bcf..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package flavors provides information and interaction with the flavor API -// resource in the OpenStack Compute service. -// -// A flavor is an available hardware configuration for a server. Each flavor -// has a unique combination of disk space, memory capacity and priority for CPU -// time. -package flavors diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/requests.go deleted file mode 100644 index 59123aaf7..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/requests.go +++ /dev/null @@ -1,103 +0,0 @@ -package flavors - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToFlavorListQuery() (string, error) -} - -// ListOpts helps control the results returned by the List() function. -// For example, a flavor with a minDisk field of 10 will not be returned if you specify MinDisk set to 20. -// Typically, software will use the last ID of the previous call to List to set the Marker for the current call. -type ListOpts struct { - - // ChangesSince, if provided, instructs List to return only those things which have changed since the timestamp provided. - ChangesSince string `q:"changes-since"` - - // MinDisk and MinRAM, if provided, elides flavors which do not meet your criteria. - MinDisk int `q:"minDisk"` - MinRAM int `q:"minRam"` - - // Marker and Limit control paging. - // Marker instructs List where to start listing from. - Marker string `q:"marker"` - - // Limit instructs List to refrain from sending excessively large lists of flavors. - Limit int `q:"limit"` -} - -// ToFlavorListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToFlavorListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// ListDetail instructs OpenStack to provide a list of flavors. -// You may provide criteria by which List curtails its results for easier processing. -// See ListOpts for more details. -func ListDetail(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listURL(client) - if opts != nil { - query, err := opts.ToFlavorListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - createPage := func(r pagination.PageResult) pagination.Page { - return FlavorPage{pagination.LinkedPageBase{PageResult: r}} - } - - return pagination.NewPager(client, url, createPage) -} - -// Get instructs OpenStack to provide details on a single flavor, identified by its ID. -// Use ExtractFlavor to convert its result into a Flavor. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = client.Get(getURL(client, id), &res.Body, nil) - return res -} - -// IDFromName is a convienience function that returns a flavor's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - flavorCount := 0 - flavorID := "" - if name == "" { - return "", fmt.Errorf("A flavor name must be provided.") - } - pager := ListDetail(client, nil) - pager.EachPage(func(page pagination.Page) (bool, error) { - flavorList, err := ExtractFlavors(page) - if err != nil { - return false, err - } - - for _, f := range flavorList { - if f.Name == name { - flavorCount++ - flavorID = f.ID - } - } - return true, nil - }) - - switch flavorCount { - case 0: - return "", fmt.Errorf("Unable to find flavor: %s", name) - case 1: - return flavorID, nil - default: - return "", fmt.Errorf("Found %d flavors matching %s", flavorCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/results.go deleted file mode 100644 index 8dddd705c..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/results.go +++ /dev/null @@ -1,122 +0,0 @@ -package flavors - -import ( - "errors" - "reflect" - - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ErrCannotInterpret is returned by an Extract call if the response body doesn't have the expected structure. -var ErrCannotInterpet = errors.New("Unable to interpret a response body.") - -// GetResult temporarily holds the response from a Get call. -type GetResult struct { - gophercloud.Result -} - -// Extract provides access to the individual Flavor returned by the Get function. -func (gr GetResult) Extract() (*Flavor, error) { - if gr.Err != nil { - return nil, gr.Err - } - - var result struct { - Flavor Flavor `mapstructure:"flavor"` - } - - cfg := &mapstructure.DecoderConfig{ - DecodeHook: defaulter, - Result: &result, - } - decoder, err := mapstructure.NewDecoder(cfg) - if err != nil { - return nil, err - } - err = decoder.Decode(gr.Body) - return &result.Flavor, err -} - -// Flavor records represent (virtual) hardware configurations for server resources in a region. -type Flavor struct { - // The Id field contains the flavor's unique identifier. - // For example, this identifier will be useful when specifying which hardware configuration to use for a new server instance. - ID string `mapstructure:"id"` - - // The Disk and RA< fields provide a measure of storage space offered by the flavor, in GB and MB, respectively. - Disk int `mapstructure:"disk"` - RAM int `mapstructure:"ram"` - - // The Name field provides a human-readable moniker for the flavor. - Name string `mapstructure:"name"` - - RxTxFactor float64 `mapstructure:"rxtx_factor"` - - // Swap indicates how much space is reserved for swap. - // If not provided, this field will be set to 0. - Swap int `mapstructure:"swap"` - - // VCPUs indicates how many (virtual) CPUs are available for this flavor. - VCPUs int `mapstructure:"vcpus"` -} - -// FlavorPage contains a single page of the response from a List call. -type FlavorPage struct { - pagination.LinkedPageBase -} - -// IsEmpty determines if a page contains any results. -func (p FlavorPage) IsEmpty() (bool, error) { - flavors, err := ExtractFlavors(p) - if err != nil { - return true, err - } - return len(flavors) == 0, nil -} - -// NextPageURL uses the response's embedded link reference to navigate to the next page of results. -func (p FlavorPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"flavors_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -func defaulter(from, to reflect.Kind, v interface{}) (interface{}, error) { - if (from == reflect.String) && (to == reflect.Int) { - return 0, nil - } - return v, nil -} - -// ExtractFlavors provides access to the list of flavors in a page acquired from the List operation. -func ExtractFlavors(page pagination.Page) ([]Flavor, error) { - casted := page.(FlavorPage).Body - var container struct { - Flavors []Flavor `mapstructure:"flavors"` - } - - cfg := &mapstructure.DecoderConfig{ - DecodeHook: defaulter, - Result: &container, - } - decoder, err := mapstructure.NewDecoder(cfg) - if err != nil { - return container.Flavors, err - } - err = decoder.Decode(casted) - if err != nil { - return container.Flavors, err - } - - return container.Flavors, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/urls.go deleted file mode 100644 index 683c107dc..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/urls.go +++ /dev/null @@ -1,13 +0,0 @@ -package flavors - -import ( - "github.com/rackspace/gophercloud" -) - -func getURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("flavors", id) -} - -func listURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("flavors", "detail") -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/doc.go deleted file mode 100644 index 0edaa3f02..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package images provides information and interaction with the image API -// resource in the OpenStack Compute service. -// -// An image is a collection of files used to create or rebuild a server. -// Operators provide a number of pre-built OS images by default. You may also -// create custom images from cloud servers you have launched. -package images diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/requests.go deleted file mode 100644 index 1e021ad4c..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/requests.go +++ /dev/null @@ -1,109 +0,0 @@ -package images - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToImageListQuery() (string, error) -} - -// ListOpts contain options for limiting the number of Images returned from a call to ListDetail. -type ListOpts struct { - // When the image last changed status (in date-time format). - ChangesSince string `q:"changes-since"` - // The number of Images to return. - Limit int `q:"limit"` - // UUID of the Image at which to set a marker. - Marker string `q:"marker"` - // The name of the Image. - Name string `q:"name"` - // The name of the Server (in URL format). - Server string `q:"server"` - // The current status of the Image. - Status string `q:"status"` - // The value of the type of image (e.g. BASE, SERVER, ALL) - Type string `q:"type"` -} - -// ToImageListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToImageListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// ListDetail enumerates the available images. -func ListDetail(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listDetailURL(client) - if opts != nil { - query, err := opts.ToImageListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - createPage := func(r pagination.PageResult) pagination.Page { - return ImagePage{pagination.LinkedPageBase{PageResult: r}} - } - - return pagination.NewPager(client, url, createPage) -} - -// Get acquires additional detail about a specific image by ID. -// Use ExtractImage() to interpret the result as an openstack Image. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var result GetResult - _, result.Err = client.Get(getURL(client, id), &result.Body, nil) - return result -} - -// Delete deletes the specified image ID. -func Delete(client *gophercloud.ServiceClient, id string) DeleteResult { - var result DeleteResult - _, result.Err = client.Delete(deleteURL(client, id), nil) - return result -} - -// IDFromName is a convienience function that returns an image's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - imageCount := 0 - imageID := "" - if name == "" { - return "", fmt.Errorf("An image name must be provided.") - } - pager := ListDetail(client, &ListOpts{ - Name: name, - }) - pager.EachPage(func(page pagination.Page) (bool, error) { - imageList, err := ExtractImages(page) - if err != nil { - return false, err - } - - for _, i := range imageList { - if i.Name == name { - imageCount++ - imageID = i.ID - } - } - return true, nil - }) - - switch imageCount { - case 0: - return "", fmt.Errorf("Unable to find image: %s", name) - case 1: - return imageID, nil - default: - return "", fmt.Errorf("Found %d images matching %s", imageCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/results.go deleted file mode 100644 index 482e7d6f6..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/results.go +++ /dev/null @@ -1,97 +0,0 @@ -package images - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// GetResult temporarily stores a Get response. -type GetResult struct { - gophercloud.Result -} - -// DeleteResult represents the result of an image.Delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// Extract interprets a GetResult as an Image. -func (gr GetResult) Extract() (*Image, error) { - if gr.Err != nil { - return nil, gr.Err - } - - var decoded struct { - Image Image `mapstructure:"image"` - } - - err := mapstructure.Decode(gr.Body, &decoded) - return &decoded.Image, err -} - -// Image is used for JSON (un)marshalling. -// It provides a description of an OS image. -type Image struct { - // ID contains the image's unique identifier. - ID string - - Created string - - // MinDisk and MinRAM specify the minimum resources a server must provide to be able to install the image. - MinDisk int - MinRAM int - - // Name provides a human-readable moniker for the OS image. - Name string - - // The Progress and Status fields indicate image-creation status. - // Any usable image will have 100% progress. - Progress int - Status string - - Updated string - - Metadata map[string]string -} - -// ImagePage contains a single page of results from a List operation. -// Use ExtractImages to convert it into a slice of usable structs. -type ImagePage struct { - pagination.LinkedPageBase -} - -// IsEmpty returns true if a page contains no Image results. -func (page ImagePage) IsEmpty() (bool, error) { - images, err := ExtractImages(page) - if err != nil { - return true, err - } - return len(images) == 0, nil -} - -// NextPageURL uses the response's embedded link reference to navigate to the next page of results. -func (page ImagePage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"images_links"` - } - - var r resp - err := mapstructure.Decode(page.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// ExtractImages converts a page of List results into a slice of usable Image structs. -func ExtractImages(page pagination.Page) ([]Image, error) { - casted := page.(ImagePage).Body - var results struct { - Images []Image `mapstructure:"images"` - } - - err := mapstructure.Decode(casted, &results) - return results.Images, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/urls.go deleted file mode 100644 index b1bf1038f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/images/urls.go +++ /dev/null @@ -1,15 +0,0 @@ -package images - -import "github.com/rackspace/gophercloud" - -func listDetailURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("images", "detail") -} - -func getURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("images", id) -} - -func deleteURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("images", id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/doc.go deleted file mode 100644 index fe4567120..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Package servers provides information and interaction with the server API -// resource in the OpenStack Compute service. -// -// A server is a virtual machine instance in the compute system. In order for -// one to be provisioned, a valid flavor and image are required. -package servers diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/fixtures.go deleted file mode 100644 index 85cea70a8..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/fixtures.go +++ /dev/null @@ -1,692 +0,0 @@ -// +build fixtures - -package servers - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// ServerListBody contains the canned body of a servers.List response. -const ServerListBody = ` -{ - "servers": [ - { - "status": "ACTIVE", - "updated": "2014-09-25T13:10:10Z", - "hostId": "29d3c8c896a45aa4c34e52247875d7fefc3d94bbcc9f622b5d204362", - "OS-EXT-SRV-ATTR:host": "devstack", - "addresses": { - "private": [ - { - "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:7c:1b:2b", - "version": 4, - "addr": "10.0.0.32", - "OS-EXT-IPS:type": "fixed" - } - ] - }, - "links": [ - { - "href": "http://104.130.131.164:8774/v2/fcad67a6189847c4aecfa3c81a05783b/servers/ef079b0c-e610-4dfb-b1aa-b49f07ac48e5", - "rel": "self" - }, - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/servers/ef079b0c-e610-4dfb-b1aa-b49f07ac48e5", - "rel": "bookmark" - } - ], - "key_name": null, - "image": { - "id": "f90f6034-2570-4974-8351-6b49732ef2eb", - "links": [ - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - "rel": "bookmark" - } - ] - }, - "OS-EXT-STS:task_state": null, - "OS-EXT-STS:vm_state": "active", - "OS-EXT-SRV-ATTR:instance_name": "instance-0000001e", - "OS-SRV-USG:launched_at": "2014-09-25T13:10:10.000000", - "OS-EXT-SRV-ATTR:hypervisor_hostname": "devstack", - "flavor": { - "id": "1", - "links": [ - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/flavors/1", - "rel": "bookmark" - } - ] - }, - "id": "ef079b0c-e610-4dfb-b1aa-b49f07ac48e5", - "security_groups": [ - { - "name": "default" - } - ], - "OS-SRV-USG:terminated_at": null, - "OS-EXT-AZ:availability_zone": "nova", - "user_id": "9349aff8be7545ac9d2f1d00999a23cd", - "name": "herp", - "created": "2014-09-25T13:10:02Z", - "tenant_id": "fcad67a6189847c4aecfa3c81a05783b", - "OS-DCF:diskConfig": "MANUAL", - "os-extended-volumes:volumes_attached": [], - "accessIPv4": "", - "accessIPv6": "", - "progress": 0, - "OS-EXT-STS:power_state": 1, - "config_drive": "", - "metadata": {} - }, - { - "status": "ACTIVE", - "updated": "2014-09-25T13:04:49Z", - "hostId": "29d3c8c896a45aa4c34e52247875d7fefc3d94bbcc9f622b5d204362", - "OS-EXT-SRV-ATTR:host": "devstack", - "addresses": { - "private": [ - { - "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:9e:89:be", - "version": 4, - "addr": "10.0.0.31", - "OS-EXT-IPS:type": "fixed" - } - ] - }, - "links": [ - { - "href": "http://104.130.131.164:8774/v2/fcad67a6189847c4aecfa3c81a05783b/servers/9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "rel": "self" - }, - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/servers/9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "rel": "bookmark" - } - ], - "key_name": null, - "image": { - "id": "f90f6034-2570-4974-8351-6b49732ef2eb", - "links": [ - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - "rel": "bookmark" - } - ] - }, - "OS-EXT-STS:task_state": null, - "OS-EXT-STS:vm_state": "active", - "OS-EXT-SRV-ATTR:instance_name": "instance-0000001d", - "OS-SRV-USG:launched_at": "2014-09-25T13:04:49.000000", - "OS-EXT-SRV-ATTR:hypervisor_hostname": "devstack", - "flavor": { - "id": "1", - "links": [ - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/flavors/1", - "rel": "bookmark" - } - ] - }, - "id": "9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "security_groups": [ - { - "name": "default" - } - ], - "OS-SRV-USG:terminated_at": null, - "OS-EXT-AZ:availability_zone": "nova", - "user_id": "9349aff8be7545ac9d2f1d00999a23cd", - "name": "derp", - "created": "2014-09-25T13:04:41Z", - "tenant_id": "fcad67a6189847c4aecfa3c81a05783b", - "OS-DCF:diskConfig": "MANUAL", - "os-extended-volumes:volumes_attached": [], - "accessIPv4": "", - "accessIPv6": "", - "progress": 0, - "OS-EXT-STS:power_state": 1, - "config_drive": "", - "metadata": {} - } - ] -} -` - -// SingleServerBody is the canned body of a Get request on an existing server. -const SingleServerBody = ` -{ - "server": { - "status": "ACTIVE", - "updated": "2014-09-25T13:04:49Z", - "hostId": "29d3c8c896a45aa4c34e52247875d7fefc3d94bbcc9f622b5d204362", - "OS-EXT-SRV-ATTR:host": "devstack", - "addresses": { - "private": [ - { - "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:9e:89:be", - "version": 4, - "addr": "10.0.0.31", - "OS-EXT-IPS:type": "fixed" - } - ] - }, - "links": [ - { - "href": "http://104.130.131.164:8774/v2/fcad67a6189847c4aecfa3c81a05783b/servers/9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "rel": "self" - }, - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/servers/9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "rel": "bookmark" - } - ], - "key_name": null, - "image": { - "id": "f90f6034-2570-4974-8351-6b49732ef2eb", - "links": [ - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - "rel": "bookmark" - } - ] - }, - "OS-EXT-STS:task_state": null, - "OS-EXT-STS:vm_state": "active", - "OS-EXT-SRV-ATTR:instance_name": "instance-0000001d", - "OS-SRV-USG:launched_at": "2014-09-25T13:04:49.000000", - "OS-EXT-SRV-ATTR:hypervisor_hostname": "devstack", - "flavor": { - "id": "1", - "links": [ - { - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/flavors/1", - "rel": "bookmark" - } - ] - }, - "id": "9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "security_groups": [ - { - "name": "default" - } - ], - "OS-SRV-USG:terminated_at": null, - "OS-EXT-AZ:availability_zone": "nova", - "user_id": "9349aff8be7545ac9d2f1d00999a23cd", - "name": "derp", - "created": "2014-09-25T13:04:41Z", - "tenant_id": "fcad67a6189847c4aecfa3c81a05783b", - "OS-DCF:diskConfig": "MANUAL", - "os-extended-volumes:volumes_attached": [], - "accessIPv4": "", - "accessIPv6": "", - "progress": 0, - "OS-EXT-STS:power_state": 1, - "config_drive": "", - "metadata": {} - } -} -` - -const ServerPasswordBody = ` -{ - "password": "xlozO3wLCBRWAa2yDjCCVx8vwNPypxnypmRYDa/zErlQ+EzPe1S/Gz6nfmC52mOlOSCRuUOmG7kqqgejPof6M7bOezS387zjq4LSvvwp28zUknzy4YzfFGhnHAdai3TxUJ26pfQCYrq8UTzmKF2Bq8ioSEtVVzM0A96pDh8W2i7BOz6MdoiVyiev/I1K2LsuipfxSJR7Wdke4zNXJjHHP2RfYsVbZ/k9ANu+Nz4iIH8/7Cacud/pphH7EjrY6a4RZNrjQskrhKYed0YERpotyjYk1eDtRe72GrSiXteqCM4biaQ5w3ruS+AcX//PXk3uJ5kC7d67fPXaVz4WaQRYMg==" -} -` - -var ( - // ServerHerp is a Server struct that should correspond to the first result in ServerListBody. - ServerHerp = Server{ - Status: "ACTIVE", - Updated: "2014-09-25T13:10:10Z", - HostID: "29d3c8c896a45aa4c34e52247875d7fefc3d94bbcc9f622b5d204362", - Addresses: map[string]interface{}{ - "private": []interface{}{ - map[string]interface{}{ - "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:7c:1b:2b", - "version": float64(4), - "addr": "10.0.0.32", - "OS-EXT-IPS:type": "fixed", - }, - }, - }, - Links: []interface{}{ - map[string]interface{}{ - "href": "http://104.130.131.164:8774/v2/fcad67a6189847c4aecfa3c81a05783b/servers/ef079b0c-e610-4dfb-b1aa-b49f07ac48e5", - "rel": "self", - }, - map[string]interface{}{ - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/servers/ef079b0c-e610-4dfb-b1aa-b49f07ac48e5", - "rel": "bookmark", - }, - }, - Image: map[string]interface{}{ - "id": "f90f6034-2570-4974-8351-6b49732ef2eb", - "links": []interface{}{ - map[string]interface{}{ - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - "rel": "bookmark", - }, - }, - }, - Flavor: map[string]interface{}{ - "id": "1", - "links": []interface{}{ - map[string]interface{}{ - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/flavors/1", - "rel": "bookmark", - }, - }, - }, - ID: "ef079b0c-e610-4dfb-b1aa-b49f07ac48e5", - UserID: "9349aff8be7545ac9d2f1d00999a23cd", - Name: "herp", - Created: "2014-09-25T13:10:02Z", - TenantID: "fcad67a6189847c4aecfa3c81a05783b", - Metadata: map[string]interface{}{}, - SecurityGroups: []map[string]interface{}{ - map[string]interface{}{ - "name": "default", - }, - }, - } - - // ServerDerp is a Server struct that should correspond to the second server in ServerListBody. - ServerDerp = Server{ - Status: "ACTIVE", - Updated: "2014-09-25T13:04:49Z", - HostID: "29d3c8c896a45aa4c34e52247875d7fefc3d94bbcc9f622b5d204362", - Addresses: map[string]interface{}{ - "private": []interface{}{ - map[string]interface{}{ - "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:9e:89:be", - "version": float64(4), - "addr": "10.0.0.31", - "OS-EXT-IPS:type": "fixed", - }, - }, - }, - Links: []interface{}{ - map[string]interface{}{ - "href": "http://104.130.131.164:8774/v2/fcad67a6189847c4aecfa3c81a05783b/servers/9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "rel": "self", - }, - map[string]interface{}{ - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/servers/9e5476bd-a4ec-4653-93d6-72c93aa682ba", - "rel": "bookmark", - }, - }, - Image: map[string]interface{}{ - "id": "f90f6034-2570-4974-8351-6b49732ef2eb", - "links": []interface{}{ - map[string]interface{}{ - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - "rel": "bookmark", - }, - }, - }, - Flavor: map[string]interface{}{ - "id": "1", - "links": []interface{}{ - map[string]interface{}{ - "href": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/flavors/1", - "rel": "bookmark", - }, - }, - }, - ID: "9e5476bd-a4ec-4653-93d6-72c93aa682ba", - UserID: "9349aff8be7545ac9d2f1d00999a23cd", - Name: "derp", - Created: "2014-09-25T13:04:41Z", - TenantID: "fcad67a6189847c4aecfa3c81a05783b", - Metadata: map[string]interface{}{}, - SecurityGroups: []map[string]interface{}{ - map[string]interface{}{ - "name": "default", - }, - }, - } -) - -// HandleServerCreationSuccessfully sets up the test server to respond to a server creation request -// with a given response. -func HandleServerCreationSuccessfully(t *testing.T, response string) { - th.Mux.HandleFunc("/servers", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "server": { - "name": "derp", - "imageRef": "f90f6034-2570-4974-8351-6b49732ef2eb", - "flavorRef": "1" - } - }`) - - w.WriteHeader(http.StatusAccepted) - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, response) - }) -} - -// HandleServerListSuccessfully sets up the test server to respond to a server List request. -func HandleServerListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/detail", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, ServerListBody) - case "9e5476bd-a4ec-4653-93d6-72c93aa682ba": - fmt.Fprintf(w, `{ "servers": [] }`) - default: - t.Fatalf("/servers/detail invoked with unexpected marker=[%s]", marker) - } - }) -} - -// HandleServerDeletionSuccessfully sets up the test server to respond to a server deletion request. -func HandleServerDeletionSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/asdfasdfasdf", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleServerForceDeletionSuccessfully sets up the test server to respond to a server force deletion -// request. -func HandleServerForceDeletionSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/asdfasdfasdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "forceDelete": "" }`) - - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandleServerGetSuccessfully sets up the test server to respond to a server Get request. -func HandleServerGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, SingleServerBody) - }) -} - -// HandleServerUpdateSuccessfully sets up the test server to respond to a server Update request. -func HandleServerUpdateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestJSONRequest(t, r, `{ "server": { "name": "new-name" } }`) - - fmt.Fprintf(w, SingleServerBody) - }) -} - -// HandleAdminPasswordChangeSuccessfully sets up the test server to respond to a server password -// change request. -func HandleAdminPasswordChangeSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "changePassword": { "adminPass": "new-password" } }`) - - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandleRebootSuccessfully sets up the test server to respond to a reboot request with success. -func HandleRebootSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "reboot": { "type": "SOFT" } }`) - - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandleRebuildSuccessfully sets up the test server to respond to a rebuild request with success. -func HandleRebuildSuccessfully(t *testing.T, response string) { - th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, ` - { - "rebuild": { - "name": "new-name", - "adminPass": "swordfish", - "imageRef": "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - "accessIPv4": "1.2.3.4" - } - } - `) - - w.WriteHeader(http.StatusAccepted) - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, response) - }) -} - -// HandleServerRescueSuccessfully sets up the test server to respond to a server Rescue request. -func HandleServerRescueSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "rescue": { "adminPass": "1234567890" } }`) - - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{ "adminPass": "1234567890" }`)) - }) -} - -// HandleMetadatumGetSuccessfully sets up the test server to respond to a metadatum Get request. -func HandleMetadatumGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/metadata/foo", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.WriteHeader(http.StatusOK) - w.Header().Add("Content-Type", "application/json") - w.Write([]byte(`{ "meta": {"foo":"bar"}}`)) - }) -} - -// HandleMetadatumCreateSuccessfully sets up the test server to respond to a metadatum Create request. -func HandleMetadatumCreateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/metadata/foo", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "meta": { - "foo": "bar" - } - }`) - - w.WriteHeader(http.StatusOK) - w.Header().Add("Content-Type", "application/json") - w.Write([]byte(`{ "meta": {"foo":"bar"}}`)) - }) -} - -// HandleMetadatumDeleteSuccessfully sets up the test server to respond to a metadatum Delete request. -func HandleMetadatumDeleteSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/metadata/foo", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleMetadataGetSuccessfully sets up the test server to respond to a metadata Get request. -func HandleMetadataGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/metadata", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{ "metadata": {"foo":"bar", "this":"that"}}`)) - }) -} - -// HandleMetadataResetSuccessfully sets up the test server to respond to a metadata Create request. -func HandleMetadataResetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/metadata", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "metadata": { - "foo": "bar", - "this": "that" - } - }`) - - w.WriteHeader(http.StatusOK) - w.Header().Add("Content-Type", "application/json") - w.Write([]byte(`{ "metadata": {"foo":"bar", "this":"that"}}`)) - }) -} - -// HandleMetadataUpdateSuccessfully sets up the test server to respond to a metadata Update request. -func HandleMetadataUpdateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/metadata", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "metadata": { - "foo": "baz", - "this": "those" - } - }`) - - w.WriteHeader(http.StatusOK) - w.Header().Add("Content-Type", "application/json") - w.Write([]byte(`{ "metadata": {"foo":"baz", "this":"those"}}`)) - }) -} - -// ListAddressesExpected represents an expected repsonse from a ListAddresses request. -var ListAddressesExpected = map[string][]Address{ - "public": []Address{ - Address{ - Version: 4, - Address: "80.56.136.39", - }, - Address{ - Version: 6, - Address: "2001:4800:790e:510:be76:4eff:fe04:82a8", - }, - }, - "private": []Address{ - Address{ - Version: 4, - Address: "10.880.3.154", - }, - }, -} - -// HandleAddressListSuccessfully sets up the test server to respond to a ListAddresses request. -func HandleAddressListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/asdfasdfasdf/ips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, `{ - "addresses": { - "public": [ - { - "version": 4, - "addr": "50.56.176.35" - }, - { - "version": 6, - "addr": "2001:4800:780e:510:be76:4eff:fe04:84a8" - } - ], - "private": [ - { - "version": 4, - "addr": "10.180.3.155" - } - ] - } - }`) - }) -} - -// ListNetworkAddressesExpected represents an expected repsonse from a ListAddressesByNetwork request. -var ListNetworkAddressesExpected = []Address{ - Address{ - Version: 4, - Address: "50.56.176.35", - }, - Address{ - Version: 6, - Address: "2001:4800:780e:510:be76:4eff:fe04:84a8", - }, -} - -// HandleNetworkAddressListSuccessfully sets up the test server to respond to a ListAddressesByNetwork request. -func HandleNetworkAddressListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/asdfasdfasdf/ips/public", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, `{ - "public": [ - { - "version": 4, - "addr": "50.56.176.35" - }, - { - "version": 6, - "addr": "2001:4800:780e:510:be76:4eff:fe04:84a8" - } - ] - }`) - }) -} - -// HandleCreateServerImageSuccessfully sets up the test server to respond to a TestCreateServerImage request. -func HandleCreateServerImageSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/serverimage/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - w.Header().Add("Location", "https://0.0.0.0/images/xxxx-xxxxx-xxxxx-xxxx") - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandlePasswordGetSuccessfully sets up the test server to respond to a password Get request. -func HandlePasswordGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/servers/1234asdf/os-server-password", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, ServerPasswordBody) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/requests.go deleted file mode 100644 index e6490539c..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/requests.go +++ /dev/null @@ -1,872 +0,0 @@ -package servers - -import ( - "encoding/base64" - "encoding/json" - "errors" - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/compute/v2/flavors" - "github.com/rackspace/gophercloud/openstack/compute/v2/images" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToServerListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the server attributes you want to see returned. Marker and Limit are used -// for pagination. -type ListOpts struct { - // A time/date stamp for when the server last changed status. - ChangesSince string `q:"changes-since"` - - // Name of the image in URL format. - Image string `q:"image"` - - // Name of the flavor in URL format. - Flavor string `q:"flavor"` - - // Name of the server as a string; can be queried with regular expressions. - // Realize that ?name=bob returns both bob and bobb. If you need to match bob - // only, you can use a regular expression matching the syntax of the - // underlying database server implemented for Compute. - Name string `q:"name"` - - // Value of the status of the server so that you can filter on "ACTIVE" for example. - Status string `q:"status"` - - // Name of the host as a string. - Host string `q:"host"` - - // UUID of the server at which you want to set a marker. - Marker string `q:"marker"` - - // Integer value for the limit of values to return. - Limit int `q:"limit"` - - // Bool to show all tenants - AllTenants bool `q:"all_tenants"` -} - -// ToServerListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToServerListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List makes a request against the API to list servers accessible to you. -func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listDetailURL(client) - - if opts != nil { - query, err := opts.ToServerListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - createPageFn := func(r pagination.PageResult) pagination.Page { - return ServerPage{pagination.LinkedPageBase{PageResult: r}} - } - - return pagination.NewPager(client, url, createPageFn) -} - -// CreateOptsBuilder describes struct types that can be accepted by the Create call. -// The CreateOpts struct in this package does. -type CreateOptsBuilder interface { - ToServerCreateMap() (map[string]interface{}, error) -} - -// Network is used within CreateOpts to control a new server's network attachments. -type Network struct { - // UUID of a nova-network to attach to the newly provisioned server. - // Required unless Port is provided. - UUID string - - // Port of a neutron network to attach to the newly provisioned server. - // Required unless UUID is provided. - Port string - - // FixedIP [optional] specifies a fixed IPv4 address to be used on this network. - FixedIP string -} - -// Personality is an array of files that are injected into the server at launch. -type Personality []*File - -// File is used within CreateOpts and RebuildOpts to inject a file into the server at launch. -// File implements the json.Marshaler interface, so when a Create or Rebuild operation is requested, -// json.Marshal will call File's MarshalJSON method. -type File struct { - // Path of the file - Path string - // Contents of the file. Maximum content size is 255 bytes. - Contents []byte -} - -// MarshalJSON marshals the escaped file, base64 encoding the contents. -func (f *File) MarshalJSON() ([]byte, error) { - file := struct { - Path string `json:"path"` - Contents string `json:"contents"` - }{ - Path: f.Path, - Contents: base64.StdEncoding.EncodeToString(f.Contents), - } - return json.Marshal(file) -} - -// CreateOpts specifies server creation parameters. -type CreateOpts struct { - // Name [required] is the name to assign to the newly launched server. - Name string - - // ImageRef [optional; required if ImageName is not provided] is the ID or full - // URL to the image that contains the server's OS and initial state. - // Also optional if using the boot-from-volume extension. - ImageRef string - - // ImageName [optional; required if ImageRef is not provided] is the name of the - // image that contains the server's OS and initial state. - // Also optional if using the boot-from-volume extension. - ImageName string - - // FlavorRef [optional; required if FlavorName is not provided] is the ID or - // full URL to the flavor that describes the server's specs. - FlavorRef string - - // FlavorName [optional; required if FlavorRef is not provided] is the name of - // the flavor that describes the server's specs. - FlavorName string - - // SecurityGroups [optional] lists the names of the security groups to which this server should belong. - SecurityGroups []string - - // UserData [optional] contains configuration information or scripts to use upon launch. - // Create will base64-encode it for you. - UserData []byte - - // AvailabilityZone [optional] in which to launch the server. - AvailabilityZone string - - // Networks [optional] dictates how this server will be attached to available networks. - // By default, the server will be attached to all isolated networks for the tenant. - Networks []Network - - // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server. - Metadata map[string]string - - // Personality [optional] includes files to inject into the server at launch. - // Create will base64-encode file contents for you. - Personality Personality - - // ConfigDrive [optional] enables metadata injection through a configuration drive. - ConfigDrive bool - - // AdminPass [optional] sets the root user password. If not set, a randomly-generated - // password will be created and returned in the response. - AdminPass string - - // AccessIPv4 [optional] specifies an IPv4 address for the instance. - AccessIPv4 string - - // AccessIPv6 [optional] specifies an IPv6 address for the instance. - AccessIPv6 string -} - -// ToServerCreateMap assembles a request body based on the contents of a CreateOpts. -func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) { - server := make(map[string]interface{}) - - server["name"] = opts.Name - server["imageRef"] = opts.ImageRef - server["imageName"] = opts.ImageName - server["flavorRef"] = opts.FlavorRef - server["flavorName"] = opts.FlavorName - - if opts.UserData != nil { - encoded := base64.StdEncoding.EncodeToString(opts.UserData) - server["user_data"] = &encoded - } - if opts.ConfigDrive { - server["config_drive"] = "true" - } - if opts.AvailabilityZone != "" { - server["availability_zone"] = opts.AvailabilityZone - } - if opts.Metadata != nil { - server["metadata"] = opts.Metadata - } - if opts.AdminPass != "" { - server["adminPass"] = opts.AdminPass - } - if opts.AccessIPv4 != "" { - server["accessIPv4"] = opts.AccessIPv4 - } - if opts.AccessIPv6 != "" { - server["accessIPv6"] = opts.AccessIPv6 - } - - if len(opts.SecurityGroups) > 0 { - securityGroups := make([]map[string]interface{}, len(opts.SecurityGroups)) - for i, groupName := range opts.SecurityGroups { - securityGroups[i] = map[string]interface{}{"name": groupName} - } - server["security_groups"] = securityGroups - } - - if len(opts.Networks) > 0 { - networks := make([]map[string]interface{}, len(opts.Networks)) - for i, net := range opts.Networks { - networks[i] = make(map[string]interface{}) - if net.UUID != "" { - networks[i]["uuid"] = net.UUID - } - if net.Port != "" { - networks[i]["port"] = net.Port - } - if net.FixedIP != "" { - networks[i]["fixed_ip"] = net.FixedIP - } - } - server["networks"] = networks - } - - if len(opts.Personality) > 0 { - server["personality"] = opts.Personality - } - - return map[string]interface{}{"server": server}, nil -} - -// Create requests a server to be provisioned to the user in the current tenant. -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToServerCreateMap() - if err != nil { - res.Err = err - return res - } - - // If ImageRef isn't provided, use ImageName to ascertain the image ID. - if reqBody["server"].(map[string]interface{})["imageRef"].(string) == "" { - imageName := reqBody["server"].(map[string]interface{})["imageName"].(string) - if imageName == "" { - res.Err = errors.New("One and only one of ImageRef and ImageName must be provided.") - return res - } - imageID, err := images.IDFromName(client, imageName) - if err != nil { - res.Err = err - return res - } - reqBody["server"].(map[string]interface{})["imageRef"] = imageID - } - delete(reqBody["server"].(map[string]interface{}), "imageName") - - // If FlavorRef isn't provided, use FlavorName to ascertain the flavor ID. - if reqBody["server"].(map[string]interface{})["flavorRef"].(string) == "" { - flavorName := reqBody["server"].(map[string]interface{})["flavorName"].(string) - if flavorName == "" { - res.Err = errors.New("One and only one of FlavorRef and FlavorName must be provided.") - return res - } - flavorID, err := flavors.IDFromName(client, flavorName) - if err != nil { - res.Err = err - return res - } - reqBody["server"].(map[string]interface{})["flavorRef"] = flavorID - } - delete(reqBody["server"].(map[string]interface{}), "flavorName") - - _, res.Err = client.Post(listURL(client), reqBody, &res.Body, nil) - return res -} - -// Delete requests that a server previously provisioned be removed from your account. -func Delete(client *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = client.Delete(deleteURL(client, id), nil) - return res -} - -func ForceDelete(client *gophercloud.ServiceClient, id string) ActionResult { - var req struct { - ForceDelete string `json:"forceDelete"` - } - - var res ActionResult - _, res.Err = client.Post(actionURL(client, id), req, nil, nil) - return res - -} - -// Get requests details on a single server, by ID. -func Get(client *gophercloud.ServiceClient, id string) GetResult { - var result GetResult - _, result.Err = client.Get(getURL(client, id), &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 203}, - }) - return result -} - -// UpdateOptsBuilder allows extensions to add additional attributes to the Update request. -type UpdateOptsBuilder interface { - ToServerUpdateMap() map[string]interface{} -} - -// UpdateOpts specifies the base attributes that may be updated on an existing server. -type UpdateOpts struct { - // Name [optional] changes the displayed name of the server. - // The server host name will *not* change. - // Server names are not constrained to be unique, even within the same tenant. - Name string - - // AccessIPv4 [optional] provides a new IPv4 address for the instance. - AccessIPv4 string - - // AccessIPv6 [optional] provides a new IPv6 address for the instance. - AccessIPv6 string -} - -// ToServerUpdateMap formats an UpdateOpts structure into a request body. -func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} { - server := make(map[string]string) - if opts.Name != "" { - server["name"] = opts.Name - } - if opts.AccessIPv4 != "" { - server["accessIPv4"] = opts.AccessIPv4 - } - if opts.AccessIPv6 != "" { - server["accessIPv6"] = opts.AccessIPv6 - } - return map[string]interface{}{"server": server} -} - -// Update requests that various attributes of the indicated server be changed. -func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var result UpdateResult - reqBody := opts.ToServerUpdateMap() - _, result.Err = client.Put(updateURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return result -} - -// ChangeAdminPassword alters the administrator or root password for a specified server. -func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) ActionResult { - var req struct { - ChangePassword struct { - AdminPass string `json:"adminPass"` - } `json:"changePassword"` - } - - req.ChangePassword.AdminPass = newPassword - - var res ActionResult - _, res.Err = client.Post(actionURL(client, id), req, nil, nil) - return res -} - -// ErrArgument errors occur when an argument supplied to a package function -// fails to fall within acceptable values. For example, the Reboot() function -// expects the "how" parameter to be one of HardReboot or SoftReboot. These -// constants are (currently) strings, leading someone to wonder if they can pass -// other string values instead, perhaps in an effort to break the API of their -// provider. Reboot() returns this error in this situation. -// -// Function identifies which function was called/which function is generating -// the error. -// Argument identifies which formal argument was responsible for producing the -// error. -// Value provides the value as it was passed into the function. -type ErrArgument struct { - Function, Argument string - Value interface{} -} - -// Error yields a useful diagnostic for debugging purposes. -func (e *ErrArgument) Error() string { - return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value) -} - -func (e *ErrArgument) String() string { - return e.Error() -} - -// RebootMethod describes the mechanisms by which a server reboot can be requested. -type RebootMethod string - -// These constants determine how a server should be rebooted. -// See the Reboot() function for further details. -const ( - SoftReboot RebootMethod = "SOFT" - HardReboot RebootMethod = "HARD" - OSReboot = SoftReboot - PowerCycle = HardReboot -) - -// Reboot requests that a given server reboot. -// Two methods exist for rebooting a server: -// -// HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM, -// terminating it at the hypervisor level. -// It's done. Caput. Full stop. -// Then, after a brief while, power is restored or the VM instance restarted. -// -// SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures. -// E.g., in Linux, asking it to enter runlevel 6, or executing "sudo shutdown -r now", or by asking Windows to restart the machine. -func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) ActionResult { - var res ActionResult - - if (how != SoftReboot) && (how != HardReboot) { - res.Err = &ErrArgument{ - Function: "Reboot", - Argument: "how", - Value: how, - } - return res - } - - reqBody := struct { - C map[string]string `json:"reboot"` - }{ - map[string]string{"type": string(how)}, - } - - _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil) - return res -} - -// RebuildOptsBuilder is an interface that allows extensions to override the -// default behaviour of rebuild options -type RebuildOptsBuilder interface { - ToServerRebuildMap() (map[string]interface{}, error) -} - -// RebuildOpts represents the configuration options used in a server rebuild -// operation -type RebuildOpts struct { - // Required. The ID of the image you want your server to be provisioned on - ImageID string - - // Name to set the server to - Name string - - // Required. The server's admin password - AdminPass string - - // AccessIPv4 [optional] provides a new IPv4 address for the instance. - AccessIPv4 string - - // AccessIPv6 [optional] provides a new IPv6 address for the instance. - AccessIPv6 string - - // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server. - Metadata map[string]string - - // Personality [optional] includes files to inject into the server at launch. - // Rebuild will base64-encode file contents for you. - Personality Personality -} - -// ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON -func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) { - var err error - server := make(map[string]interface{}) - - if opts.AdminPass == "" { - err = fmt.Errorf("AdminPass is required") - } - - if opts.ImageID == "" { - err = fmt.Errorf("ImageID is required") - } - - if err != nil { - return server, err - } - - server["name"] = opts.Name - server["adminPass"] = opts.AdminPass - server["imageRef"] = opts.ImageID - - if opts.AccessIPv4 != "" { - server["accessIPv4"] = opts.AccessIPv4 - } - - if opts.AccessIPv6 != "" { - server["accessIPv6"] = opts.AccessIPv6 - } - - if opts.Metadata != nil { - server["metadata"] = opts.Metadata - } - - if len(opts.Personality) > 0 { - server["personality"] = opts.Personality - } - - return map[string]interface{}{"rebuild": server}, nil -} - -// Rebuild will reprovision the server according to the configuration options -// provided in the RebuildOpts struct. -func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult { - var result RebuildResult - - if id == "" { - result.Err = fmt.Errorf("ID is required") - return result - } - - reqBody, err := opts.ToServerRebuildMap() - if err != nil { - result.Err = err - return result - } - - _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, nil) - return result -} - -// ResizeOptsBuilder is an interface that allows extensions to override the default structure of -// a Resize request. -type ResizeOptsBuilder interface { - ToServerResizeMap() (map[string]interface{}, error) -} - -// ResizeOpts represents the configuration options used to control a Resize operation. -type ResizeOpts struct { - // FlavorRef is the ID of the flavor you wish your server to become. - FlavorRef string -} - -// ToServerResizeMap formats a ResizeOpts as a map that can be used as a JSON request body for the -// Resize request. -func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) { - resize := map[string]interface{}{ - "flavorRef": opts.FlavorRef, - } - - return map[string]interface{}{"resize": resize}, nil -} - -// Resize instructs the provider to change the flavor of the server. -// Note that this implies rebuilding it. -// Unfortunately, one cannot pass rebuild parameters to the resize function. -// When the resize completes, the server will be in RESIZE_VERIFY state. -// While in this state, you can explore the use of the new server's configuration. -// If you like it, call ConfirmResize() to commit the resize permanently. -// Otherwise, call RevertResize() to restore the old configuration. -func Resize(client *gophercloud.ServiceClient, id string, opts ResizeOptsBuilder) ActionResult { - var res ActionResult - reqBody, err := opts.ToServerResizeMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil) - return res -} - -// ConfirmResize confirms a previous resize operation on a server. -// See Resize() for more details. -func ConfirmResize(client *gophercloud.ServiceClient, id string) ActionResult { - var res ActionResult - - reqBody := map[string]interface{}{"confirmResize": nil} - _, res.Err = client.Post(actionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{ - OkCodes: []int{201, 202, 204}, - }) - return res -} - -// RevertResize cancels a previous resize operation on a server. -// See Resize() for more details. -func RevertResize(client *gophercloud.ServiceClient, id string) ActionResult { - var res ActionResult - reqBody := map[string]interface{}{"revertResize": nil} - _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil) - return res -} - -// RescueOptsBuilder is an interface that allows extensions to override the -// default structure of a Rescue request. -type RescueOptsBuilder interface { - ToServerRescueMap() (map[string]interface{}, error) -} - -// RescueOpts represents the configuration options used to control a Rescue -// option. -type RescueOpts struct { - // AdminPass is the desired administrative password for the instance in - // RESCUE mode. If it's left blank, the server will generate a password. - AdminPass string -} - -// ToServerRescueMap formats a RescueOpts as a map that can be used as a JSON -// request body for the Rescue request. -func (opts RescueOpts) ToServerRescueMap() (map[string]interface{}, error) { - server := make(map[string]interface{}) - if opts.AdminPass != "" { - server["adminPass"] = opts.AdminPass - } - return map[string]interface{}{"rescue": server}, nil -} - -// Rescue instructs the provider to place the server into RESCUE mode. -func Rescue(client *gophercloud.ServiceClient, id string, opts RescueOptsBuilder) RescueResult { - var result RescueResult - - if id == "" { - result.Err = fmt.Errorf("ID is required") - return result - } - reqBody, err := opts.ToServerRescueMap() - if err != nil { - result.Err = err - return result - } - - _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return result -} - -// ResetMetadataOptsBuilder allows extensions to add additional parameters to the -// Reset request. -type ResetMetadataOptsBuilder interface { - ToMetadataResetMap() (map[string]interface{}, error) -} - -// MetadataOpts is a map that contains key-value pairs. -type MetadataOpts map[string]string - -// ToMetadataResetMap assembles a body for a Reset request based on the contents of a MetadataOpts. -func (opts MetadataOpts) ToMetadataResetMap() (map[string]interface{}, error) { - return map[string]interface{}{"metadata": opts}, nil -} - -// ToMetadataUpdateMap assembles a body for an Update request based on the contents of a MetadataOpts. -func (opts MetadataOpts) ToMetadataUpdateMap() (map[string]interface{}, error) { - return map[string]interface{}{"metadata": opts}, nil -} - -// ResetMetadata will create multiple new key-value pairs for the given server ID. -// Note: Using this operation will erase any already-existing metadata and create -// the new metadata provided. To keep any already-existing metadata, use the -// UpdateMetadatas or UpdateMetadata function. -func ResetMetadata(client *gophercloud.ServiceClient, id string, opts ResetMetadataOptsBuilder) ResetMetadataResult { - var res ResetMetadataResult - metadata, err := opts.ToMetadataResetMap() - if err != nil { - res.Err = err - return res - } - _, res.Err = client.Put(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Metadata requests all the metadata for the given server ID. -func Metadata(client *gophercloud.ServiceClient, id string) GetMetadataResult { - var res GetMetadataResult - _, res.Err = client.Get(metadataURL(client, id), &res.Body, nil) - return res -} - -// UpdateMetadataOptsBuilder allows extensions to add additional parameters to the -// Create request. -type UpdateMetadataOptsBuilder interface { - ToMetadataUpdateMap() (map[string]interface{}, error) -} - -// UpdateMetadata updates (or creates) all the metadata specified by opts for the given server ID. -// This operation does not affect already-existing metadata that is not specified -// by opts. -func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMetadataOptsBuilder) UpdateMetadataResult { - var res UpdateMetadataResult - metadata, err := opts.ToMetadataUpdateMap() - if err != nil { - res.Err = err - return res - } - _, res.Err = client.Post(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// MetadatumOptsBuilder allows extensions to add additional parameters to the -// Create request. -type MetadatumOptsBuilder interface { - ToMetadatumCreateMap() (map[string]interface{}, string, error) -} - -// MetadatumOpts is a map of length one that contains a key-value pair. -type MetadatumOpts map[string]string - -// ToMetadatumCreateMap assembles a body for a Create request based on the contents of a MetadataumOpts. -func (opts MetadatumOpts) ToMetadatumCreateMap() (map[string]interface{}, string, error) { - if len(opts) != 1 { - return nil, "", errors.New("CreateMetadatum operation must have 1 and only 1 key-value pair.") - } - metadatum := map[string]interface{}{"meta": opts} - var key string - for k := range metadatum["meta"].(MetadatumOpts) { - key = k - } - return metadatum, key, nil -} - -// CreateMetadatum will create or update the key-value pair with the given key for the given server ID. -func CreateMetadatum(client *gophercloud.ServiceClient, id string, opts MetadatumOptsBuilder) CreateMetadatumResult { - var res CreateMetadatumResult - metadatum, key, err := opts.ToMetadatumCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = client.Put(metadatumURL(client, id, key), metadatum, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Metadatum requests the key-value pair with the given key for the given server ID. -func Metadatum(client *gophercloud.ServiceClient, id, key string) GetMetadatumResult { - var res GetMetadatumResult - _, res.Err = client.Request("GET", metadatumURL(client, id, key), gophercloud.RequestOpts{ - JSONResponse: &res.Body, - }) - return res -} - -// DeleteMetadatum will delete the key-value pair with the given key for the given server ID. -func DeleteMetadatum(client *gophercloud.ServiceClient, id, key string) DeleteMetadatumResult { - var res DeleteMetadatumResult - _, res.Err = client.Delete(metadatumURL(client, id, key), nil) - return res -} - -// ListAddresses makes a request against the API to list the servers IP addresses. -func ListAddresses(client *gophercloud.ServiceClient, id string) pagination.Pager { - createPageFn := func(r pagination.PageResult) pagination.Page { - return AddressPage{pagination.SinglePageBase(r)} - } - return pagination.NewPager(client, listAddressesURL(client, id), createPageFn) -} - -// ListAddressesByNetwork makes a request against the API to list the servers IP addresses -// for the given network. -func ListAddressesByNetwork(client *gophercloud.ServiceClient, id, network string) pagination.Pager { - createPageFn := func(r pagination.PageResult) pagination.Page { - return NetworkAddressPage{pagination.SinglePageBase(r)} - } - return pagination.NewPager(client, listAddressesByNetworkURL(client, id, network), createPageFn) -} - -type CreateImageOpts struct { - // Name [required] of the image/snapshot - Name string - // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the created image. - Metadata map[string]string -} - -type CreateImageOptsBuilder interface { - ToServerCreateImageMap() (map[string]interface{}, error) -} - -// ToServerCreateImageMap formats a CreateImageOpts structure into a request body. -func (opts CreateImageOpts) ToServerCreateImageMap() (map[string]interface{}, error) { - var err error - img := make(map[string]interface{}) - if opts.Name == "" { - return nil, fmt.Errorf("Cannot create a server image without a name") - } - img["name"] = opts.Name - if opts.Metadata != nil { - img["metadata"] = opts.Metadata - } - createImage := make(map[string]interface{}) - createImage["createImage"] = img - return createImage, err -} - -// CreateImage makes a request against the nova API to schedule an image to be created of the server -func CreateImage(client *gophercloud.ServiceClient, serverId string, opts CreateImageOptsBuilder) CreateImageResult { - var res CreateImageResult - reqBody, err := opts.ToServerCreateImageMap() - if err != nil { - res.Err = err - return res - } - response, err := client.Post(actionURL(client, serverId), reqBody, nil, &gophercloud.RequestOpts{ - OkCodes: []int{202}, - }) - res.Err = err - res.Header = response.Header - return res -} - -// IDFromName is a convienience function that returns a server's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - serverCount := 0 - serverID := "" - if name == "" { - return "", fmt.Errorf("A server name must be provided.") - } - pager := List(client, nil) - pager.EachPage(func(page pagination.Page) (bool, error) { - serverList, err := ExtractServers(page) - if err != nil { - return false, err - } - - for _, s := range serverList { - if s.Name == name { - serverCount++ - serverID = s.ID - } - } - return true, nil - }) - - switch serverCount { - case 0: - return "", fmt.Errorf("Unable to find server: %s", name) - case 1: - return serverID, nil - default: - return "", fmt.Errorf("Found %d servers matching %s", serverCount, name) - } -} - -// GetPassword makes a request against the nova API to get the encrypted administrative password. -func GetPassword(client *gophercloud.ServiceClient, serverId string) GetPasswordResult { - var res GetPasswordResult - _, res.Err = client.Request("GET", passwordURL(client, serverId), gophercloud.RequestOpts{ - JSONResponse: &res.Body, - }) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/results.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/results.go deleted file mode 100644 index 406f68935..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/results.go +++ /dev/null @@ -1,415 +0,0 @@ -package servers - -import ( - "crypto/rsa" - "encoding/base64" - "fmt" - "net/url" - "path" - "reflect" - - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type serverResult struct { - gophercloud.Result -} - -// Extract interprets any serverResult as a Server, if possible. -func (r serverResult) Extract() (*Server, error) { - if r.Err != nil { - return nil, r.Err - } - - var response struct { - Server Server `mapstructure:"server"` - } - - config := &mapstructure.DecoderConfig{ - DecodeHook: toMapFromString, - Result: &response, - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - - err = decoder.Decode(r.Body) - if err != nil { - return nil, err - } - - return &response.Server, nil -} - -// CreateResult temporarily contains the response from a Create call. -type CreateResult struct { - serverResult -} - -// GetResult temporarily contains the response from a Get call. -type GetResult struct { - serverResult -} - -// UpdateResult temporarily contains the response from an Update call. -type UpdateResult struct { - serverResult -} - -// DeleteResult temporarily contains the response from a Delete call. -type DeleteResult struct { - gophercloud.ErrResult -} - -// RebuildResult temporarily contains the response from a Rebuild call. -type RebuildResult struct { - serverResult -} - -// ActionResult represents the result of server action operations, like reboot -type ActionResult struct { - gophercloud.ErrResult -} - -// RescueResult represents the result of a server rescue operation -type RescueResult struct { - ActionResult -} - -// CreateImageResult represents the result of an image creation operation -type CreateImageResult struct { - gophercloud.Result -} - -// GetPasswordResult represent the result of a get os-server-password operation. -type GetPasswordResult struct { - gophercloud.Result -} - -// ExtractPassword gets the encrypted password. -// If privateKey != nil the password is decrypted with the private key. -// If privateKey == nil the encrypted password is returned and can be decrypted with: -// echo '' | base64 -D | openssl rsautl -decrypt -inkey -func (r GetPasswordResult) ExtractPassword(privateKey *rsa.PrivateKey) (string, error) { - - if r.Err != nil { - return "", r.Err - } - - var response struct { - Password string `mapstructure:"password"` - } - - err := mapstructure.Decode(r.Body, &response) - if err == nil && privateKey != nil && response.Password != "" { - return decryptPassword(response.Password, privateKey) - } - return response.Password, err -} - -func decryptPassword(encryptedPassword string, privateKey *rsa.PrivateKey) (string, error) { - b64EncryptedPassword := make([]byte, base64.StdEncoding.DecodedLen(len(encryptedPassword))) - - n, err := base64.StdEncoding.Decode(b64EncryptedPassword, []byte(encryptedPassword)) - if err != nil { - return "", fmt.Errorf("Failed to base64 decode encrypted password: %s", err) - } - password, err := rsa.DecryptPKCS1v15(nil, privateKey, b64EncryptedPassword[0:n]) - if err != nil { - return "", fmt.Errorf("Failed to decrypt password: %s", err) - } - - return string(password), nil -} - -// ExtractImageID gets the ID of the newly created server image from the header -func (res CreateImageResult) ExtractImageID() (string, error) { - if res.Err != nil { - return "", res.Err - } - // Get the image id from the header - u, err := url.ParseRequestURI(res.Header.Get("Location")) - if err != nil { - return "", fmt.Errorf("Failed to parse the image id: %s", err.Error()) - } - imageId := path.Base(u.Path) - if imageId == "." || imageId == "/" { - return "", fmt.Errorf("Failed to parse the ID of newly created image: %s", u) - } - return imageId, nil -} - -// Extract interprets any RescueResult as an AdminPass, if possible. -func (r RescueResult) Extract() (string, error) { - if r.Err != nil { - return "", r.Err - } - - var response struct { - AdminPass string `mapstructure:"adminPass"` - } - - err := mapstructure.Decode(r.Body, &response) - return response.AdminPass, err -} - -// Server exposes only the standard OpenStack fields corresponding to a given server on the user's account. -type Server struct { - // ID uniquely identifies this server amongst all other servers, including those not accessible to the current tenant. - ID string - - // TenantID identifies the tenant owning this server resource. - TenantID string `mapstructure:"tenant_id"` - - // UserID uniquely identifies the user account owning the tenant. - UserID string `mapstructure:"user_id"` - - // Name contains the human-readable name for the server. - Name string - - // Updated and Created contain ISO-8601 timestamps of when the state of the server last changed, and when it was created. - Updated string - Created string - - HostID string - - // Status contains the current operational status of the server, such as IN_PROGRESS or ACTIVE. - Status string - - // Progress ranges from 0..100. - // A request made against the server completes only once Progress reaches 100. - Progress int - - // AccessIPv4 and AccessIPv6 contain the IP addresses of the server, suitable for remote access for administration. - AccessIPv4, AccessIPv6 string - - // Image refers to a JSON object, which itself indicates the OS image used to deploy the server. - Image map[string]interface{} - - // Flavor refers to a JSON object, which itself indicates the hardware configuration of the deployed server. - Flavor map[string]interface{} - - // Addresses includes a list of all IP addresses assigned to the server, keyed by pool. - Addresses map[string]interface{} - - // Metadata includes a list of all user-specified key-value pairs attached to the server. - Metadata map[string]interface{} - - // Links includes HTTP references to the itself, useful for passing along to other APIs that might want a server reference. - Links []interface{} - - // KeyName indicates which public key was injected into the server on launch. - KeyName string `json:"key_name" mapstructure:"key_name"` - - // AdminPass will generally be empty (""). However, it will contain the administrative password chosen when provisioning a new server without a set AdminPass setting in the first place. - // Note that this is the ONLY time this field will be valid. - AdminPass string `json:"adminPass" mapstructure:"adminPass"` - - // SecurityGroups includes the security groups that this instance has applied to it - SecurityGroups []map[string]interface{} `json:"security_groups" mapstructure:"security_groups"` -} - -// ServerPage abstracts the raw results of making a List() request against the API. -// As OpenStack extensions may freely alter the response bodies of structures returned to the client, you may only safely access the -// data provided through the ExtractServers call. -type ServerPage struct { - pagination.LinkedPageBase -} - -// IsEmpty returns true if a page contains no Server results. -func (page ServerPage) IsEmpty() (bool, error) { - servers, err := ExtractServers(page) - if err != nil { - return true, err - } - return len(servers) == 0, nil -} - -// NextPageURL uses the response's embedded link reference to navigate to the next page of results. -func (page ServerPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"servers_links"` - } - - var r resp - err := mapstructure.Decode(page.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// ExtractServers interprets the results of a single page from a List() call, producing a slice of Server entities. -func ExtractServers(page pagination.Page) ([]Server, error) { - casted := page.(ServerPage).Body - - var response struct { - Servers []Server `mapstructure:"servers"` - } - - config := &mapstructure.DecoderConfig{ - DecodeHook: toMapFromString, - Result: &response, - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - - err = decoder.Decode(casted) - - return response.Servers, err -} - -// MetadataResult contains the result of a call for (potentially) multiple key-value pairs. -type MetadataResult struct { - gophercloud.Result -} - -// GetMetadataResult temporarily contains the response from a metadata Get call. -type GetMetadataResult struct { - MetadataResult -} - -// ResetMetadataResult temporarily contains the response from a metadata Reset call. -type ResetMetadataResult struct { - MetadataResult -} - -// UpdateMetadataResult temporarily contains the response from a metadata Update call. -type UpdateMetadataResult struct { - MetadataResult -} - -// MetadatumResult contains the result of a call for individual a single key-value pair. -type MetadatumResult struct { - gophercloud.Result -} - -// GetMetadatumResult temporarily contains the response from a metadatum Get call. -type GetMetadatumResult struct { - MetadatumResult -} - -// CreateMetadatumResult temporarily contains the response from a metadatum Create call. -type CreateMetadatumResult struct { - MetadatumResult -} - -// DeleteMetadatumResult temporarily contains the response from a metadatum Delete call. -type DeleteMetadatumResult struct { - gophercloud.ErrResult -} - -// Extract interprets any MetadataResult as a Metadata, if possible. -func (r MetadataResult) Extract() (map[string]string, error) { - if r.Err != nil { - return nil, r.Err - } - - var response struct { - Metadata map[string]string `mapstructure:"metadata"` - } - - err := mapstructure.Decode(r.Body, &response) - return response.Metadata, err -} - -// Extract interprets any MetadatumResult as a Metadatum, if possible. -func (r MetadatumResult) Extract() (map[string]string, error) { - if r.Err != nil { - return nil, r.Err - } - - var response struct { - Metadatum map[string]string `mapstructure:"meta"` - } - - err := mapstructure.Decode(r.Body, &response) - return response.Metadatum, err -} - -func toMapFromString(from reflect.Kind, to reflect.Kind, data interface{}) (interface{}, error) { - if (from == reflect.String) && (to == reflect.Map) { - return map[string]interface{}{}, nil - } - return data, nil -} - -// Address represents an IP address. -type Address struct { - Version int `mapstructure:"version"` - Address string `mapstructure:"addr"` -} - -// AddressPage abstracts the raw results of making a ListAddresses() request against the API. -// As OpenStack extensions may freely alter the response bodies of structures returned -// to the client, you may only safely access the data provided through the ExtractAddresses call. -type AddressPage struct { - pagination.SinglePageBase -} - -// IsEmpty returns true if an AddressPage contains no networks. -func (r AddressPage) IsEmpty() (bool, error) { - addresses, err := ExtractAddresses(r) - if err != nil { - return true, err - } - return len(addresses) == 0, nil -} - -// ExtractAddresses interprets the results of a single page from a ListAddresses() call, -// producing a map of addresses. -func ExtractAddresses(page pagination.Page) (map[string][]Address, error) { - casted := page.(AddressPage).Body - - var response struct { - Addresses map[string][]Address `mapstructure:"addresses"` - } - - err := mapstructure.Decode(casted, &response) - if err != nil { - return nil, err - } - - return response.Addresses, err -} - -// NetworkAddressPage abstracts the raw results of making a ListAddressesByNetwork() request against the API. -// As OpenStack extensions may freely alter the response bodies of structures returned -// to the client, you may only safely access the data provided through the ExtractAddresses call. -type NetworkAddressPage struct { - pagination.SinglePageBase -} - -// IsEmpty returns true if a NetworkAddressPage contains no addresses. -func (r NetworkAddressPage) IsEmpty() (bool, error) { - addresses, err := ExtractNetworkAddresses(r) - if err != nil { - return true, err - } - return len(addresses) == 0, nil -} - -// ExtractNetworkAddresses interprets the results of a single page from a ListAddressesByNetwork() call, -// producing a slice of addresses. -func ExtractNetworkAddresses(page pagination.Page) ([]Address, error) { - casted := page.(NetworkAddressPage).Body - - var response map[string][]Address - err := mapstructure.Decode(casted, &response) - if err != nil { - return nil, err - } - - var key string - for k := range response { - key = k - } - - return response[key], err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/urls.go deleted file mode 100644 index d51fcbe6c..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/urls.go +++ /dev/null @@ -1,51 +0,0 @@ -package servers - -import "github.com/rackspace/gophercloud" - -func createURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("servers") -} - -func listURL(client *gophercloud.ServiceClient) string { - return createURL(client) -} - -func listDetailURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("servers", "detail") -} - -func deleteURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("servers", id) -} - -func getURL(client *gophercloud.ServiceClient, id string) string { - return deleteURL(client, id) -} - -func updateURL(client *gophercloud.ServiceClient, id string) string { - return deleteURL(client, id) -} - -func actionURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("servers", id, "action") -} - -func metadatumURL(client *gophercloud.ServiceClient, id, key string) string { - return client.ServiceURL("servers", id, "metadata", key) -} - -func metadataURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("servers", id, "metadata") -} - -func listAddressesURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("servers", id, "ips") -} - -func listAddressesByNetworkURL(client *gophercloud.ServiceClient, id, network string) string { - return client.ServiceURL("servers", id, "ips", network) -} - -func passwordURL(client *gophercloud.ServiceClient, id string) string { - return client.ServiceURL("servers", id, "os-server-password") -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/util.go b/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/util.go deleted file mode 100644 index e6baf7416..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/util.go +++ /dev/null @@ -1,20 +0,0 @@ -package servers - -import "github.com/rackspace/gophercloud" - -// WaitForStatus will continually poll a server until it successfully transitions to a specified -// status. It will do this for at most the number of seconds specified. -func WaitForStatus(c *gophercloud.ServiceClient, id, status string, secs int) error { - return gophercloud.WaitFor(secs, func() (bool, error) { - current, err := Get(c, id).Extract() - if err != nil { - return false, err - } - - if current.Status == status { - return true, nil - } - - return false, nil - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/endpoint_location.go b/vendor/github.com/rackspace/gophercloud/openstack/endpoint_location.go deleted file mode 100644 index 29d02c43f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/endpoint_location.go +++ /dev/null @@ -1,91 +0,0 @@ -package openstack - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - tokens2 "github.com/rackspace/gophercloud/openstack/identity/v2/tokens" - tokens3 "github.com/rackspace/gophercloud/openstack/identity/v3/tokens" -) - -// V2EndpointURL discovers the endpoint URL for a specific service from a ServiceCatalog acquired -// during the v2 identity service. The specified EndpointOpts are used to identify a unique, -// unambiguous endpoint to return. It's an error both when multiple endpoints match the provided -// criteria and when none do. The minimum that can be specified is a Type, but you will also often -// need to specify a Name and/or a Region depending on what's available on your OpenStack -// deployment. -func V2EndpointURL(catalog *tokens2.ServiceCatalog, opts gophercloud.EndpointOpts) (string, error) { - // Extract Endpoints from the catalog entries that match the requested Type, Name if provided, and Region if provided. - var endpoints = make([]tokens2.Endpoint, 0, 1) - for _, entry := range catalog.Entries { - if (entry.Type == opts.Type) && (opts.Name == "" || entry.Name == opts.Name) { - for _, endpoint := range entry.Endpoints { - if opts.Region == "" || endpoint.Region == opts.Region { - endpoints = append(endpoints, endpoint) - } - } - } - } - - // Report an error if the options were ambiguous. - if len(endpoints) > 1 { - return "", fmt.Errorf("Discovered %d matching endpoints: %#v", len(endpoints), endpoints) - } - - // Extract the appropriate URL from the matching Endpoint. - for _, endpoint := range endpoints { - switch opts.Availability { - case gophercloud.AvailabilityPublic: - return gophercloud.NormalizeURL(endpoint.PublicURL), nil - case gophercloud.AvailabilityInternal: - return gophercloud.NormalizeURL(endpoint.InternalURL), nil - case gophercloud.AvailabilityAdmin: - return gophercloud.NormalizeURL(endpoint.AdminURL), nil - default: - return "", fmt.Errorf("Unexpected availability in endpoint query: %s", opts.Availability) - } - } - - // Report an error if there were no matching endpoints. - return "", gophercloud.ErrEndpointNotFound -} - -// V3EndpointURL discovers the endpoint URL for a specific service from a Catalog acquired -// during the v3 identity service. The specified EndpointOpts are used to identify a unique, -// unambiguous endpoint to return. It's an error both when multiple endpoints match the provided -// criteria and when none do. The minimum that can be specified is a Type, but you will also often -// need to specify a Name and/or a Region depending on what's available on your OpenStack -// deployment. -func V3EndpointURL(catalog *tokens3.ServiceCatalog, opts gophercloud.EndpointOpts) (string, error) { - // Extract Endpoints from the catalog entries that match the requested Type, Interface, - // Name if provided, and Region if provided. - var endpoints = make([]tokens3.Endpoint, 0, 1) - for _, entry := range catalog.Entries { - if (entry.Type == opts.Type) && (opts.Name == "" || entry.Name == opts.Name) { - for _, endpoint := range entry.Endpoints { - if opts.Availability != gophercloud.AvailabilityAdmin && - opts.Availability != gophercloud.AvailabilityPublic && - opts.Availability != gophercloud.AvailabilityInternal { - return "", fmt.Errorf("Unexpected availability in endpoint query: %s", opts.Availability) - } - if (opts.Availability == gophercloud.Availability(endpoint.Interface)) && - (opts.Region == "" || endpoint.Region == opts.Region) { - endpoints = append(endpoints, endpoint) - } - } - } - } - - // Report an error if the options were ambiguous. - if len(endpoints) > 1 { - return "", fmt.Errorf("Discovered %d matching endpoints: %#v", len(endpoints), endpoints) - } - - // Extract the URL from the matching Endpoint. - for _, endpoint := range endpoints { - return gophercloud.NormalizeURL(endpoint.URL), nil - } - - // Report an error if there were no matching endpoints. - return "", gophercloud.ErrEndpointNotFound -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/doc.go deleted file mode 100644 index 0c2d49d56..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package tenants provides information and interaction with the -// tenants API resource for the OpenStack Identity service. -// -// See http://developer.openstack.org/api-ref-identity-v2.html#identity-auth-v2 -// and http://developer.openstack.org/api-ref-identity-v2.html#admin-tenants -// for more information. -package tenants diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/fixtures.go deleted file mode 100644 index 7f044ac3b..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/fixtures.go +++ /dev/null @@ -1,65 +0,0 @@ -// +build fixtures - -package tenants - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// ListOutput provides a single page of Tenant results. -const ListOutput = ` -{ - "tenants": [ - { - "id": "1234", - "name": "Red Team", - "description": "The team that is red", - "enabled": true - }, - { - "id": "9876", - "name": "Blue Team", - "description": "The team that is blue", - "enabled": false - } - ] -} -` - -// RedTeam is a Tenant fixture. -var RedTeam = Tenant{ - ID: "1234", - Name: "Red Team", - Description: "The team that is red", - Enabled: true, -} - -// BlueTeam is a Tenant fixture. -var BlueTeam = Tenant{ - ID: "9876", - Name: "Blue Team", - Description: "The team that is blue", - Enabled: false, -} - -// ExpectedTenantSlice is the slice of tenants expected to be returned from ListOutput. -var ExpectedTenantSlice = []Tenant{RedTeam, BlueTeam} - -// HandleListTenantsSuccessfully creates an HTTP handler at `/tenants` on the test handler mux that -// responds with a list of two tenants. -func HandleListTenantsSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/tenants", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, ListOutput) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/requests.go deleted file mode 100644 index 5a359f5c9..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/requests.go +++ /dev/null @@ -1,33 +0,0 @@ -package tenants - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts filters the Tenants that are returned by the List call. -type ListOpts struct { - // Marker is the ID of the last Tenant on the previous page. - Marker string `q:"marker"` - - // Limit specifies the page size. - Limit int `q:"limit"` -} - -// List enumerates the Tenants to which the current token has access. -func List(client *gophercloud.ServiceClient, opts *ListOpts) pagination.Pager { - createPage := func(r pagination.PageResult) pagination.Page { - return TenantPage{pagination.LinkedPageBase{PageResult: r}} - } - - url := listURL(client) - if opts != nil { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return pagination.Pager{Err: err} - } - url += q.String() - } - - return pagination.NewPager(client, url, createPage) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/results.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/results.go deleted file mode 100644 index c1220c384..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/results.go +++ /dev/null @@ -1,62 +0,0 @@ -package tenants - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// Tenant is a grouping of users in the identity service. -type Tenant struct { - // ID is a unique identifier for this tenant. - ID string `mapstructure:"id"` - - // Name is a friendlier user-facing name for this tenant. - Name string `mapstructure:"name"` - - // Description is a human-readable explanation of this Tenant's purpose. - Description string `mapstructure:"description"` - - // Enabled indicates whether or not a tenant is active. - Enabled bool `mapstructure:"enabled"` -} - -// TenantPage is a single page of Tenant results. -type TenantPage struct { - pagination.LinkedPageBase -} - -// IsEmpty determines whether or not a page of Tenants contains any results. -func (page TenantPage) IsEmpty() (bool, error) { - tenants, err := ExtractTenants(page) - if err != nil { - return false, err - } - return len(tenants) == 0, nil -} - -// NextPageURL extracts the "next" link from the tenants_links section of the result. -func (page TenantPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"tenants_links"` - } - - var r resp - err := mapstructure.Decode(page.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// ExtractTenants returns a slice of Tenants contained in a single page of results. -func ExtractTenants(page pagination.Page) ([]Tenant, error) { - casted := page.(TenantPage).Body - var response struct { - Tenants []Tenant `mapstructure:"tenants"` - } - - err := mapstructure.Decode(casted, &response) - return response.Tenants, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/urls.go deleted file mode 100644 index 1dd6ce023..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/urls.go +++ /dev/null @@ -1,7 +0,0 @@ -package tenants - -import "github.com/rackspace/gophercloud" - -func listURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("tenants") -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/doc.go deleted file mode 100644 index 31cacc5e1..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package tokens provides information and interaction with the token API -// resource for the OpenStack Identity service. -// For more information, see: -// http://developer.openstack.org/api-ref-identity-v2.html#identity-auth-v2 -package tokens diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/errors.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/errors.go deleted file mode 100644 index 3dfdc08db..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/errors.go +++ /dev/null @@ -1,30 +0,0 @@ -package tokens - -import ( - "errors" - "fmt" -) - -var ( - // ErrUserIDProvided is returned if you attempt to authenticate with a UserID. - ErrUserIDProvided = unacceptedAttributeErr("UserID") - - // ErrAPIKeyProvided is returned if you attempt to authenticate with an APIKey. - ErrAPIKeyProvided = unacceptedAttributeErr("APIKey") - - // ErrDomainIDProvided is returned if you attempt to authenticate with a DomainID. - ErrDomainIDProvided = unacceptedAttributeErr("DomainID") - - // ErrDomainNameProvided is returned if you attempt to authenticate with a DomainName. - ErrDomainNameProvided = unacceptedAttributeErr("DomainName") - - // ErrUsernameRequired is returned if you attempt to authenticate without a Username. - ErrUsernameRequired = errors.New("You must supply a Username in your AuthOptions.") - - // ErrPasswordRequired is returned if you don't provide a password. - ErrPasswordRequired = errors.New("Please supply a Password in your AuthOptions.") -) - -func unacceptedAttributeErr(attribute string) error { - return fmt.Errorf("The base Identity V2 API does not accept authentication by %s", attribute) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/fixtures.go deleted file mode 100644 index 6245259e1..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/fixtures.go +++ /dev/null @@ -1,195 +0,0 @@ -// +build fixtures - -package tokens - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/rackspace/gophercloud/openstack/identity/v2/tenants" - th "github.com/rackspace/gophercloud/testhelper" - thclient "github.com/rackspace/gophercloud/testhelper/client" -) - -// ExpectedToken is the token that should be parsed from TokenCreationResponse. -var ExpectedToken = &Token{ - ID: "aaaabbbbccccdddd", - ExpiresAt: time.Date(2014, time.January, 31, 15, 30, 58, 0, time.UTC), - Tenant: tenants.Tenant{ - ID: "fc394f2ab2df4114bde39905f800dc57", - Name: "test", - Description: "There are many tenants. This one is yours.", - Enabled: true, - }, -} - -// ExpectedServiceCatalog is the service catalog that should be parsed from TokenCreationResponse. -var ExpectedServiceCatalog = &ServiceCatalog{ - Entries: []CatalogEntry{ - CatalogEntry{ - Name: "inscrutablewalrus", - Type: "something", - Endpoints: []Endpoint{ - Endpoint{ - PublicURL: "http://something0:1234/v2/", - Region: "region0", - }, - Endpoint{ - PublicURL: "http://something1:1234/v2/", - Region: "region1", - }, - }, - }, - CatalogEntry{ - Name: "arbitrarypenguin", - Type: "else", - Endpoints: []Endpoint{ - Endpoint{ - PublicURL: "http://else0:4321/v3/", - Region: "region0", - }, - }, - }, - }, -} - -// ExpectedUser is the token that should be parsed from TokenGetResponse. -var ExpectedUser = &User{ - ID: "a530fefc3d594c4ba2693a4ecd6be74e", - Name: "apiserver", - Roles: []Role{{"member"}, {"service"}}, - UserName: "apiserver", -} - -// TokenCreationResponse is a JSON response that contains ExpectedToken and ExpectedServiceCatalog. -const TokenCreationResponse = ` -{ - "access": { - "token": { - "issued_at": "2014-01-30T15:30:58.000000Z", - "expires": "2014-01-31T15:30:58Z", - "id": "aaaabbbbccccdddd", - "tenant": { - "description": "There are many tenants. This one is yours.", - "enabled": true, - "id": "fc394f2ab2df4114bde39905f800dc57", - "name": "test" - } - }, - "serviceCatalog": [ - { - "endpoints": [ - { - "publicURL": "http://something0:1234/v2/", - "region": "region0" - }, - { - "publicURL": "http://something1:1234/v2/", - "region": "region1" - } - ], - "type": "something", - "name": "inscrutablewalrus" - }, - { - "endpoints": [ - { - "publicURL": "http://else0:4321/v3/", - "region": "region0" - } - ], - "type": "else", - "name": "arbitrarypenguin" - } - ] - } -} -` - -// TokenGetResponse is a JSON response that contains ExpectedToken and ExpectedUser. -const TokenGetResponse = ` -{ - "access": { - "token": { - "issued_at": "2014-01-30T15:30:58.000000Z", - "expires": "2014-01-31T15:30:58Z", - "id": "aaaabbbbccccdddd", - "tenant": { - "description": "There are many tenants. This one is yours.", - "enabled": true, - "id": "fc394f2ab2df4114bde39905f800dc57", - "name": "test" - } - }, - "serviceCatalog": [], - "user": { - "id": "a530fefc3d594c4ba2693a4ecd6be74e", - "name": "apiserver", - "roles": [ - { - "name": "member" - }, - { - "name": "service" - } - ], - "roles_links": [], - "username": "apiserver" - } - } -}` - -// HandleTokenPost expects a POST against a /tokens handler, ensures that the request body has been -// constructed properly given certain auth options, and returns the result. -func HandleTokenPost(t *testing.T, requestJSON string) { - th.Mux.HandleFunc("/tokens", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - if requestJSON != "" { - th.TestJSONRequest(t, r, requestJSON) - } - - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, TokenCreationResponse) - }) -} - -// HandleTokenGet expects a Get against a /tokens handler, ensures that the request body has been -// constructed properly given certain auth options, and returns the result. -func HandleTokenGet(t *testing.T, token string) { - th.Mux.HandleFunc("/tokens/"+token, func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "X-Auth-Token", thclient.TokenID) - - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, TokenGetResponse) - }) -} - -// IsSuccessful ensures that a CreateResult was successful and contains the correct token and -// service catalog. -func IsSuccessful(t *testing.T, result CreateResult) { - token, err := result.ExtractToken() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedToken, token) - - serviceCatalog, err := result.ExtractServiceCatalog() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedServiceCatalog, serviceCatalog) -} - -// GetIsSuccessful ensures that a GetResult was successful and contains the correct token and -// User Info. -func GetIsSuccessful(t *testing.T, result GetResult) { - token, err := result.ExtractToken() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedToken, token) - - user, err := result.ExtractUser() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedUser, user) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/requests.go deleted file mode 100644 index 1f514386d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/requests.go +++ /dev/null @@ -1,99 +0,0 @@ -package tokens - -import ( - "fmt" - - "github.com/rackspace/gophercloud" -) - -// AuthOptionsBuilder describes any argument that may be passed to the Create call. -type AuthOptionsBuilder interface { - - // ToTokenCreateMap assembles the Create request body, returning an error if parameters are - // missing or inconsistent. - ToTokenCreateMap() (map[string]interface{}, error) -} - -// AuthOptions wraps a gophercloud AuthOptions in order to adhere to the AuthOptionsBuilder -// interface. -type AuthOptions struct { - gophercloud.AuthOptions -} - -// WrapOptions embeds a root AuthOptions struct in a package-specific one. -func WrapOptions(original gophercloud.AuthOptions) AuthOptions { - return AuthOptions{AuthOptions: original} -} - -// ToTokenCreateMap converts AuthOptions into nested maps that can be serialized into a JSON -// request. -func (auth AuthOptions) ToTokenCreateMap() (map[string]interface{}, error) { - // Error out if an unsupported auth option is present. - if auth.UserID != "" { - return nil, ErrUserIDProvided - } - if auth.APIKey != "" { - return nil, ErrAPIKeyProvided - } - if auth.DomainID != "" { - return nil, ErrDomainIDProvided - } - if auth.DomainName != "" { - return nil, ErrDomainNameProvided - } - - // Populate the request map. - authMap := make(map[string]interface{}) - - if auth.Username != "" { - if auth.Password != "" { - authMap["passwordCredentials"] = map[string]interface{}{ - "username": auth.Username, - "password": auth.Password, - } - } else { - return nil, ErrPasswordRequired - } - } else if auth.TokenID != "" { - authMap["token"] = map[string]interface{}{ - "id": auth.TokenID, - } - } else { - return nil, fmt.Errorf("You must provide either username/password or tenantID/token values.") - } - - if auth.TenantID != "" { - authMap["tenantId"] = auth.TenantID - } - if auth.TenantName != "" { - authMap["tenantName"] = auth.TenantName - } - - return map[string]interface{}{"auth": authMap}, nil -} - -// Create authenticates to the identity service and attempts to acquire a Token. -// If successful, the CreateResult -// Generally, rather than interact with this call directly, end users should call openstack.AuthenticatedClient(), -// which abstracts all of the gory details about navigating service catalogs and such. -func Create(client *gophercloud.ServiceClient, auth AuthOptionsBuilder) CreateResult { - request, err := auth.ToTokenCreateMap() - if err != nil { - return CreateResult{gophercloud.Result{Err: err}} - } - - var result CreateResult - _, result.Err = client.Post(CreateURL(client), request, &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 203}, - }) - return result -} - -// Validates and retrieves information for user's token. -func Get(client *gophercloud.ServiceClient, token string) GetResult { - var result GetResult - _, result.Err = client.Get(GetURL(client, token), &result.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 203}, - }) - return result -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/results.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/results.go deleted file mode 100644 index 67c577b8d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/results.go +++ /dev/null @@ -1,170 +0,0 @@ -package tokens - -import ( - "time" - - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/identity/v2/tenants" -) - -// Token provides only the most basic information related to an authentication token. -type Token struct { - // ID provides the primary means of identifying a user to the OpenStack API. - // OpenStack defines this field as an opaque value, so do not depend on its content. - // It is safe, however, to compare for equality. - ID string - - // ExpiresAt provides a timestamp in ISO 8601 format, indicating when the authentication token becomes invalid. - // After this point in time, future API requests made using this authentication token will respond with errors. - // Either the caller will need to reauthenticate manually, or more preferably, the caller should exploit automatic re-authentication. - // See the AuthOptions structure for more details. - ExpiresAt time.Time - - // Tenant provides information about the tenant to which this token grants access. - Tenant tenants.Tenant -} - -// Authorization need user info which can get from token authentication's response -type Role struct { - Name string `mapstructure:"name"` -} -type User struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - UserName string `mapstructure:"username"` - Roles []Role `mapstructure:"roles"` -} - -// Endpoint represents a single API endpoint offered by a service. -// It provides the public and internal URLs, if supported, along with a region specifier, again if provided. -// The significance of the Region field will depend upon your provider. -// -// In addition, the interface offered by the service will have version information associated with it -// through the VersionId, VersionInfo, and VersionList fields, if provided or supported. -// -// In all cases, fields which aren't supported by the provider and service combined will assume a zero-value (""). -type Endpoint struct { - TenantID string `mapstructure:"tenantId"` - PublicURL string `mapstructure:"publicURL"` - InternalURL string `mapstructure:"internalURL"` - AdminURL string `mapstructure:"adminURL"` - Region string `mapstructure:"region"` - VersionID string `mapstructure:"versionId"` - VersionInfo string `mapstructure:"versionInfo"` - VersionList string `mapstructure:"versionList"` -} - -// CatalogEntry provides a type-safe interface to an Identity API V2 service catalog listing. -// Each class of service, such as cloud DNS or block storage services, will have a single -// CatalogEntry representing it. -// -// Note: when looking for the desired service, try, whenever possible, to key off the type field. -// Otherwise, you'll tie the representation of the service to a specific provider. -type CatalogEntry struct { - // Name will contain the provider-specified name for the service. - Name string `mapstructure:"name"` - - // Type will contain a type string if OpenStack defines a type for the service. - // Otherwise, for provider-specific services, the provider may assign their own type strings. - Type string `mapstructure:"type"` - - // Endpoints will let the caller iterate over all the different endpoints that may exist for - // the service. - Endpoints []Endpoint `mapstructure:"endpoints"` -} - -// ServiceCatalog provides a view into the service catalog from a previous, successful authentication. -type ServiceCatalog struct { - Entries []CatalogEntry -} - -// CreateResult defers the interpretation of a created token. -// Use ExtractToken() to interpret it as a Token, or ExtractServiceCatalog() to interpret it as a service catalog. -type CreateResult struct { - gophercloud.Result -} - -// GetResult is the deferred response from a Get call, which is the same with a Created token. -// Use ExtractUser() to interpret it as a User. -type GetResult struct { - CreateResult -} - -// ExtractToken returns the just-created Token from a CreateResult. -func (result CreateResult) ExtractToken() (*Token, error) { - if result.Err != nil { - return nil, result.Err - } - - var response struct { - Access struct { - Token struct { - Expires string `mapstructure:"expires"` - ID string `mapstructure:"id"` - Tenant tenants.Tenant `mapstructure:"tenant"` - } `mapstructure:"token"` - } `mapstructure:"access"` - } - - err := mapstructure.Decode(result.Body, &response) - if err != nil { - return nil, err - } - - expiresTs, err := time.Parse(gophercloud.RFC3339Milli, response.Access.Token.Expires) - if err != nil { - return nil, err - } - - return &Token{ - ID: response.Access.Token.ID, - ExpiresAt: expiresTs, - Tenant: response.Access.Token.Tenant, - }, nil -} - -// ExtractServiceCatalog returns the ServiceCatalog that was generated along with the user's Token. -func (result CreateResult) ExtractServiceCatalog() (*ServiceCatalog, error) { - if result.Err != nil { - return nil, result.Err - } - - var response struct { - Access struct { - Entries []CatalogEntry `mapstructure:"serviceCatalog"` - } `mapstructure:"access"` - } - - err := mapstructure.Decode(result.Body, &response) - if err != nil { - return nil, err - } - - return &ServiceCatalog{Entries: response.Access.Entries}, nil -} - -// createErr quickly packs an error in a CreateResult. -func createErr(err error) CreateResult { - return CreateResult{gophercloud.Result{Err: err}} -} - -// ExtractUser returns the User from a GetResult. -func (result GetResult) ExtractUser() (*User, error) { - if result.Err != nil { - return nil, result.Err - } - - var response struct { - Access struct { - User User `mapstructure:"user"` - } `mapstructure:"access"` - } - - err := mapstructure.Decode(result.Body, &response) - if err != nil { - return nil, err - } - - return &response.Access.User, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/urls.go deleted file mode 100644 index ee1393299..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/urls.go +++ /dev/null @@ -1,13 +0,0 @@ -package tokens - -import "github.com/rackspace/gophercloud" - -// CreateURL generates the URL used to create new Tokens. -func CreateURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("tokens") -} - -// GetURL generates the URL used to Validate Tokens. -func GetURL(client *gophercloud.ServiceClient, token string) string { - return client.ServiceURL("tokens", token) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/doc.go deleted file mode 100644 index 76ff5f473..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Package tokens provides information and interaction with the token API -// resource for the OpenStack Identity service. -// -// For more information, see: -// http://developer.openstack.org/api-ref-identity-v3.html#tokens-v3 -package tokens diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/errors.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/errors.go deleted file mode 100644 index a9e1d5c2f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/errors.go +++ /dev/null @@ -1,72 +0,0 @@ -package tokens - -import ( - "errors" - "fmt" -) - -func unacceptedAttributeErr(attribute string) error { - return fmt.Errorf("The base Identity V3 API does not accept authentication by %s", attribute) -} - -func redundantWithTokenErr(attribute string) error { - return fmt.Errorf("%s may not be provided when authenticating with a TokenID", attribute) -} - -func redundantWithUserID(attribute string) error { - return fmt.Errorf("%s may not be provided when authenticating with a UserID", attribute) -} - -var ( - // ErrAPIKeyProvided indicates that an APIKey was provided but can't be used. - ErrAPIKeyProvided = unacceptedAttributeErr("APIKey") - - // ErrTenantIDProvided indicates that a TenantID was provided but can't be used. - ErrTenantIDProvided = unacceptedAttributeErr("TenantID") - - // ErrTenantNameProvided indicates that a TenantName was provided but can't be used. - ErrTenantNameProvided = unacceptedAttributeErr("TenantName") - - // ErrUsernameWithToken indicates that a Username was provided, but token authentication is being used instead. - ErrUsernameWithToken = redundantWithTokenErr("Username") - - // ErrUserIDWithToken indicates that a UserID was provided, but token authentication is being used instead. - ErrUserIDWithToken = redundantWithTokenErr("UserID") - - // ErrDomainIDWithToken indicates that a DomainID was provided, but token authentication is being used instead. - ErrDomainIDWithToken = redundantWithTokenErr("DomainID") - - // ErrDomainNameWithToken indicates that a DomainName was provided, but token authentication is being used instead.s - ErrDomainNameWithToken = redundantWithTokenErr("DomainName") - - // ErrUsernameOrUserID indicates that neither username nor userID are specified, or both are at once. - ErrUsernameOrUserID = errors.New("Exactly one of Username and UserID must be provided for password authentication") - - // ErrDomainIDWithUserID indicates that a DomainID was provided, but unnecessary because a UserID is being used. - ErrDomainIDWithUserID = redundantWithUserID("DomainID") - - // ErrDomainNameWithUserID indicates that a DomainName was provided, but unnecessary because a UserID is being used. - ErrDomainNameWithUserID = redundantWithUserID("DomainName") - - // ErrDomainIDOrDomainName indicates that a username was provided, but no domain to scope it. - // It may also indicate that both a DomainID and a DomainName were provided at once. - ErrDomainIDOrDomainName = errors.New("You must provide exactly one of DomainID or DomainName to authenticate by Username") - - // ErrMissingPassword indicates that no password and no token were provided and no token is available. - ErrMissingPassword = errors.New("You must provide a password or a token to authenticate") - - // ErrScopeDomainIDOrDomainName indicates that a domain ID or Name was required in a Scope, but not present. - ErrScopeDomainIDOrDomainName = errors.New("You must provide exactly one of DomainID or DomainName in a Scope with ProjectName") - - // ErrScopeProjectIDOrProjectName indicates that both a ProjectID and a ProjectName were provided in a Scope. - ErrScopeProjectIDOrProjectName = errors.New("You must provide at most one of ProjectID or ProjectName in a Scope") - - // ErrScopeProjectIDAlone indicates that a ProjectID was provided with other constraints in a Scope. - ErrScopeProjectIDAlone = errors.New("ProjectID must be supplied alone in a Scope") - - // ErrScopeDomainName indicates that a DomainName was provided alone in a Scope. - ErrScopeDomainName = errors.New("DomainName must be supplied with a ProjectName or ProjectID in a Scope.") - - // ErrScopeEmpty indicates that no credentials were provided in a Scope. - ErrScopeEmpty = errors.New("You must provide either a Project or Domain in a Scope") -) diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/requests.go deleted file mode 100644 index 2810f2fa2..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/requests.go +++ /dev/null @@ -1,278 +0,0 @@ -package tokens - -import ( - "net/http" - - "github.com/rackspace/gophercloud" -) - -// Scope allows a created token to be limited to a specific domain or project. -type Scope struct { - ProjectID string - ProjectName string - DomainID string - DomainName string -} - -func subjectTokenHeaders(c *gophercloud.ServiceClient, subjectToken string) map[string]string { - return map[string]string{ - "X-Subject-Token": subjectToken, - } -} - -// Create authenticates and either generates a new token, or changes the Scope of an existing token. -func Create(c *gophercloud.ServiceClient, options gophercloud.AuthOptions, scope *Scope) CreateResult { - type domainReq struct { - ID *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - } - - type projectReq struct { - Domain *domainReq `json:"domain,omitempty"` - Name *string `json:"name,omitempty"` - ID *string `json:"id,omitempty"` - } - - type userReq struct { - ID *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Password string `json:"password"` - Domain *domainReq `json:"domain,omitempty"` - } - - type passwordReq struct { - User userReq `json:"user"` - } - - type tokenReq struct { - ID string `json:"id"` - } - - type identityReq struct { - Methods []string `json:"methods"` - Password *passwordReq `json:"password,omitempty"` - Token *tokenReq `json:"token,omitempty"` - } - - type scopeReq struct { - Domain *domainReq `json:"domain,omitempty"` - Project *projectReq `json:"project,omitempty"` - } - - type authReq struct { - Identity identityReq `json:"identity"` - Scope *scopeReq `json:"scope,omitempty"` - } - - type request struct { - Auth authReq `json:"auth"` - } - - // Populate the request structure based on the provided arguments. Create and return an error - // if insufficient or incompatible information is present. - var req request - - // Test first for unrecognized arguments. - if options.APIKey != "" { - return createErr(ErrAPIKeyProvided) - } - if options.TenantID != "" { - return createErr(ErrTenantIDProvided) - } - if options.TenantName != "" { - return createErr(ErrTenantNameProvided) - } - - if options.Password == "" { - if options.TokenID != "" { - c.TokenID = options.TokenID - } - if c.TokenID != "" { - // Because we aren't using password authentication, it's an error to also provide any of the user-based authentication - // parameters. - if options.Username != "" { - return createErr(ErrUsernameWithToken) - } - if options.UserID != "" { - return createErr(ErrUserIDWithToken) - } - - // Configure the request for Token authentication. - req.Auth.Identity.Methods = []string{"token"} - req.Auth.Identity.Token = &tokenReq{ - ID: c.TokenID, - } - } else { - // If no password or token ID are available, authentication can't continue. - return createErr(ErrMissingPassword) - } - } else { - // Password authentication. - req.Auth.Identity.Methods = []string{"password"} - - // At least one of Username and UserID must be specified. - if options.Username == "" && options.UserID == "" { - return createErr(ErrUsernameOrUserID) - } - - if options.Username != "" { - // If Username is provided, UserID may not be provided. - if options.UserID != "" { - return createErr(ErrUsernameOrUserID) - } - - // Either DomainID or DomainName must also be specified. - if options.DomainID == "" && options.DomainName == "" { - return createErr(ErrDomainIDOrDomainName) - } - - if options.DomainID != "" { - if options.DomainName != "" { - return createErr(ErrDomainIDOrDomainName) - } - - // Configure the request for Username and Password authentication with a DomainID. - req.Auth.Identity.Password = &passwordReq{ - User: userReq{ - Name: &options.Username, - Password: options.Password, - Domain: &domainReq{ID: &options.DomainID}, - }, - } - } - - if options.DomainName != "" { - // Configure the request for Username and Password authentication with a DomainName. - req.Auth.Identity.Password = &passwordReq{ - User: userReq{ - Name: &options.Username, - Password: options.Password, - Domain: &domainReq{Name: &options.DomainName}, - }, - } - } - } - - if options.UserID != "" { - // If UserID is specified, neither DomainID nor DomainName may be. - if options.DomainID != "" { - return createErr(ErrDomainIDWithUserID) - } - if options.DomainName != "" { - return createErr(ErrDomainNameWithUserID) - } - - // Configure the request for UserID and Password authentication. - req.Auth.Identity.Password = &passwordReq{ - User: userReq{ID: &options.UserID, Password: options.Password}, - } - } - } - - // Add a "scope" element if a Scope has been provided. - if scope != nil { - if scope.ProjectName != "" { - // ProjectName provided: either DomainID or DomainName must also be supplied. - // ProjectID may not be supplied. - if scope.DomainID == "" && scope.DomainName == "" { - return createErr(ErrScopeDomainIDOrDomainName) - } - if scope.ProjectID != "" { - return createErr(ErrScopeProjectIDOrProjectName) - } - - if scope.DomainID != "" { - // ProjectName + DomainID - req.Auth.Scope = &scopeReq{ - Project: &projectReq{ - Name: &scope.ProjectName, - Domain: &domainReq{ID: &scope.DomainID}, - }, - } - } - - if scope.DomainName != "" { - // ProjectName + DomainName - req.Auth.Scope = &scopeReq{ - Project: &projectReq{ - Name: &scope.ProjectName, - Domain: &domainReq{Name: &scope.DomainName}, - }, - } - } - } else if scope.ProjectID != "" { - // ProjectID provided. ProjectName, DomainID, and DomainName may not be provided. - if scope.DomainID != "" { - return createErr(ErrScopeProjectIDAlone) - } - if scope.DomainName != "" { - return createErr(ErrScopeProjectIDAlone) - } - - // ProjectID - req.Auth.Scope = &scopeReq{ - Project: &projectReq{ID: &scope.ProjectID}, - } - } else if scope.DomainID != "" { - // DomainID provided. ProjectID, ProjectName, and DomainName may not be provided. - if scope.DomainName != "" { - return createErr(ErrScopeDomainIDOrDomainName) - } - - // DomainID - req.Auth.Scope = &scopeReq{ - Domain: &domainReq{ID: &scope.DomainID}, - } - } else if scope.DomainName != "" { - return createErr(ErrScopeDomainName) - } else { - return createErr(ErrScopeEmpty) - } - } - - var result CreateResult - var response *http.Response - response, result.Err = c.Post(tokenURL(c), req, &result.Body, nil) - if result.Err != nil { - return result - } - result.Header = response.Header - return result -} - -// Get validates and retrieves information about another token. -func Get(c *gophercloud.ServiceClient, token string) GetResult { - var result GetResult - var response *http.Response - response, result.Err = c.Get(tokenURL(c), &result.Body, &gophercloud.RequestOpts{ - MoreHeaders: subjectTokenHeaders(c, token), - OkCodes: []int{200, 203}, - }) - if result.Err != nil { - return result - } - result.Header = response.Header - return result -} - -// Validate determines if a specified token is valid or not. -func Validate(c *gophercloud.ServiceClient, token string) (bool, error) { - response, err := c.Request("HEAD", tokenURL(c), gophercloud.RequestOpts{ - MoreHeaders: subjectTokenHeaders(c, token), - OkCodes: []int{204, 404}, - }) - if err != nil { - return false, err - } - - return response.StatusCode == 204, nil -} - -// Revoke immediately makes specified token invalid. -func Revoke(c *gophercloud.ServiceClient, token string) RevokeResult { - var res RevokeResult - _, res.Err = c.Delete(tokenURL(c), &gophercloud.RequestOpts{ - MoreHeaders: subjectTokenHeaders(c, token), - }) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/results.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/results.go deleted file mode 100644 index d134f7d4d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/results.go +++ /dev/null @@ -1,139 +0,0 @@ -package tokens - -import ( - "time" - - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" -) - -// Endpoint represents a single API endpoint offered by a service. -// It matches either a public, internal or admin URL. -// If supported, it contains a region specifier, again if provided. -// The significance of the Region field will depend upon your provider. -type Endpoint struct { - ID string `mapstructure:"id"` - Region string `mapstructure:"region"` - Interface string `mapstructure:"interface"` - URL string `mapstructure:"url"` -} - -// CatalogEntry provides a type-safe interface to an Identity API V3 service catalog listing. -// Each class of service, such as cloud DNS or block storage services, could have multiple -// CatalogEntry representing it (one by interface type, e.g public, admin or internal). -// -// Note: when looking for the desired service, try, whenever possible, to key off the type field. -// Otherwise, you'll tie the representation of the service to a specific provider. -type CatalogEntry struct { - - // Service ID - ID string `mapstructure:"id"` - - // Name will contain the provider-specified name for the service. - Name string `mapstructure:"name"` - - // Type will contain a type string if OpenStack defines a type for the service. - // Otherwise, for provider-specific services, the provider may assign their own type strings. - Type string `mapstructure:"type"` - - // Endpoints will let the caller iterate over all the different endpoints that may exist for - // the service. - Endpoints []Endpoint `mapstructure:"endpoints"` -} - -// ServiceCatalog provides a view into the service catalog from a previous, successful authentication. -type ServiceCatalog struct { - Entries []CatalogEntry -} - -// commonResult is the deferred result of a Create or a Get call. -type commonResult struct { - gophercloud.Result -} - -// Extract is a shortcut for ExtractToken. -// This function is deprecated and still present for backward compatibility. -func (r commonResult) Extract() (*Token, error) { - return r.ExtractToken() -} - -// ExtractToken interprets a commonResult as a Token. -func (r commonResult) ExtractToken() (*Token, error) { - if r.Err != nil { - return nil, r.Err - } - - var response struct { - Token struct { - ExpiresAt string `mapstructure:"expires_at"` - } `mapstructure:"token"` - } - - var token Token - - // Parse the token itself from the stored headers. - token.ID = r.Header.Get("X-Subject-Token") - - err := mapstructure.Decode(r.Body, &response) - if err != nil { - return nil, err - } - - // Attempt to parse the timestamp. - token.ExpiresAt, err = time.Parse(gophercloud.RFC3339Milli, response.Token.ExpiresAt) - - return &token, err -} - -// ExtractServiceCatalog returns the ServiceCatalog that was generated along with the user's Token. -func (result CreateResult) ExtractServiceCatalog() (*ServiceCatalog, error) { - if result.Err != nil { - return nil, result.Err - } - - var response struct { - Token struct { - Entries []CatalogEntry `mapstructure:"catalog"` - } `mapstructure:"token"` - } - - err := mapstructure.Decode(result.Body, &response) - if err != nil { - return nil, err - } - - return &ServiceCatalog{Entries: response.Token.Entries}, nil -} - -// CreateResult defers the interpretation of a created token. -// Use ExtractToken() to interpret it as a Token, or ExtractServiceCatalog() to interpret it as a service catalog. -type CreateResult struct { - commonResult -} - -// createErr quickly creates a CreateResult that reports an error. -func createErr(err error) CreateResult { - return CreateResult{ - commonResult: commonResult{Result: gophercloud.Result{Err: err}}, - } -} - -// GetResult is the deferred response from a Get call. -type GetResult struct { - commonResult -} - -// RevokeResult is the deferred response from a Revoke call. -type RevokeResult struct { - commonResult -} - -// Token is a string that grants a user access to a controlled set of services in an OpenStack provider. -// Each Token is valid for a set length of time. -type Token struct { - // ID is the issued token. - ID string - - // ExpiresAt is the timestamp at which this token will no longer be accepted. - ExpiresAt time.Time -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/urls.go deleted file mode 100644 index 360b60a82..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/urls.go +++ /dev/null @@ -1,7 +0,0 @@ -package tokens - -import "github.com/rackspace/gophercloud" - -func tokenURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("auth", "tokens") -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/errors.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/errors.go deleted file mode 100644 index dd92bb20d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/errors.go +++ /dev/null @@ -1,11 +0,0 @@ -package firewalls - -import "fmt" - -func err(str string) error { - return fmt.Errorf("%s", str) -} - -var ( - errPolicyRequired = err("A policy ID is required") -) diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/requests.go deleted file mode 100644 index 12d587f38..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/requests.go +++ /dev/null @@ -1,216 +0,0 @@ -package firewalls - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -// Shared gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Yes` and `No` enums. -type Shared *bool - -// Convenience vars for AdminStateUp and Shared values. -var ( - iTrue = true - iFalse = false - Up AdminState = &iTrue - Down AdminState = &iFalse - Yes Shared = &iTrue - No Shared = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToFirewallListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the firewall attributes you want to see returned. SortKey allows you to sort -// by a particular firewall attribute. SortDir sets the direction, and is either -// `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - TenantID string `q:"tenant_id"` - Name string `q:"name"` - Description string `q:"description"` - AdminStateUp bool `q:"admin_state_up"` - Shared bool `q:"shared"` - PolicyID string `q:"firewall_policy_id"` - ID string `q:"id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToFirewallListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToFirewallListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// firewalls. It accepts a ListOpts struct, which allows you to filter -// and sort the returned collection for greater efficiency. -// -// Default policy settings return only those firewalls that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := rootURL(c) - - if opts != nil { - query, err := opts.ToFirewallListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return FirewallPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToFirewallCreateMap() (map[string]interface{}, error) -} - -// CreateOpts contains all the values needed to create a new firewall. -type CreateOpts struct { - // Only required if the caller has an admin role and wants to create a firewall - // for another tenant. - TenantID string - Name string - Description string - AdminStateUp *bool - Shared *bool - PolicyID string -} - -// ToFirewallCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToFirewallCreateMap() (map[string]interface{}, error) { - if opts.PolicyID == "" { - return nil, errPolicyRequired - } - - f := make(map[string]interface{}) - - if opts.TenantID != "" { - f["tenant_id"] = opts.TenantID - } - if opts.Name != "" { - f["name"] = opts.Name - } - if opts.Description != "" { - f["description"] = opts.Description - } - if opts.Shared != nil { - f["shared"] = *opts.Shared - } - if opts.AdminStateUp != nil { - f["admin_state_up"] = *opts.AdminStateUp - } - if opts.PolicyID != "" { - f["firewall_policy_id"] = opts.PolicyID - } - - return map[string]interface{}{"firewall": f}, nil -} - -// Create accepts a CreateOpts struct and uses the values to create a new firewall -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToFirewallCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular firewall based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToFirewallUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts contains the values used when updating a firewall. -type UpdateOpts struct { - // Name of the firewall. - Name string - Description string - AdminStateUp *bool - Shared *bool - PolicyID string -} - -// ToFirewallUpdateMap casts a CreateOpts struct to a map. -func (opts UpdateOpts) ToFirewallUpdateMap() (map[string]interface{}, error) { - f := make(map[string]interface{}) - - if opts.Name != "" { - f["name"] = opts.Name - } - if opts.Description != "" { - f["description"] = opts.Description - } - if opts.Shared != nil { - f["shared"] = *opts.Shared - } - if opts.AdminStateUp != nil { - f["admin_state_up"] = *opts.AdminStateUp - } - if opts.PolicyID != "" { - f["firewall_policy_id"] = opts.PolicyID - } - - return map[string]interface{}{"firewall": f}, nil -} - -// Update allows firewalls to be updated. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToFirewallUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Delete will permanently delete a particular firewall based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/results.go deleted file mode 100644 index a8c76eef2..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/results.go +++ /dev/null @@ -1,101 +0,0 @@ -package firewalls - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type Firewall struct { - ID string `json:"id" mapstructure:"id"` - Name string `json:"name" mapstructure:"name"` - Description string `json:"description" mapstructure:"description"` - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - Status string `json:"status" mapstructure:"status"` - PolicyID string `json:"firewall_policy_id" mapstructure:"firewall_policy_id"` - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a firewall. -func (r commonResult) Extract() (*Firewall, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Firewall *Firewall `json:"firewall"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Firewall, err -} - -// FirewallPage is the page returned by a pager when traversing over a -// collection of firewalls. -type FirewallPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of firewalls has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p FirewallPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"firewalls_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a FirewallPage struct is empty. -func (p FirewallPage) IsEmpty() (bool, error) { - is, err := ExtractFirewalls(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractFirewalls accepts a Page struct, specifically a RouterPage struct, -// and extracts the elements into a slice of Router structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractFirewalls(page pagination.Page) ([]Firewall, error) { - var resp struct { - Firewalls []Firewall `mapstructure:"firewalls" json:"firewalls"` - } - - err := mapstructure.Decode(page.(FirewallPage).Body, &resp) - - return resp.Firewalls, err -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/urls.go deleted file mode 100644 index 4dde53005..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/urls.go +++ /dev/null @@ -1,16 +0,0 @@ -package firewalls - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "fw" - resourcePath = "firewalls" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/requests.go deleted file mode 100644 index fe07d9abb..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/requests.go +++ /dev/null @@ -1,243 +0,0 @@ -package policies - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// Binary gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Yes` and `No` enums -type Binary *bool - -// Convenience vars for Audited and Shared values. -var ( - iTrue = true - iFalse = false - Yes Binary = &iTrue - No Binary = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToPolicyListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the firewall policy attributes you want to see returned. SortKey allows you -// to sort by a particular firewall policy attribute. SortDir sets the direction, -// and is either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - TenantID string `q:"tenant_id"` - Name string `q:"name"` - Description string `q:"description"` - Shared bool `q:"shared"` - Audited bool `q:"audited"` - ID string `q:"id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToPolicyListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToPolicyListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// firewall policies. It accepts a ListOpts struct, which allows you to filter -// and sort the returned collection for greater efficiency. -// -// Default policy settings return only those firewall policies that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := rootURL(c) - - if opts != nil { - query, err := opts.ToPolicyListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return PolicyPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToPolicyCreateMap() (map[string]interface{}, error) -} - -// CreateOpts contains all the values needed to create a new firewall policy. -type CreateOpts struct { - // Only required if the caller has an admin role and wants to create a firewall policy - // for another tenant. - TenantID string - Name string - Description string - Shared *bool - Audited *bool - Rules []string -} - -// ToPolicyCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToPolicyCreateMap() (map[string]interface{}, error) { - p := make(map[string]interface{}) - - if opts.TenantID != "" { - p["tenant_id"] = opts.TenantID - } - if opts.Name != "" { - p["name"] = opts.Name - } - if opts.Description != "" { - p["description"] = opts.Description - } - if opts.Shared != nil { - p["shared"] = *opts.Shared - } - if opts.Audited != nil { - p["audited"] = *opts.Audited - } - if opts.Rules != nil { - p["firewall_rules"] = opts.Rules - } - - return map[string]interface{}{"firewall_policy": p}, nil -} - -// Create accepts a CreateOpts struct and uses the values to create a new firewall policy -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToPolicyCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular firewall policy based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToPolicyUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts contains the values used when updating a firewall policy. -type UpdateOpts struct { - // Name of the firewall policy. - Name string - Description string - Shared *bool - Audited *bool - Rules []string -} - -// ToPolicyUpdateMap casts a CreateOpts struct to a map. -func (opts UpdateOpts) ToPolicyUpdateMap() (map[string]interface{}, error) { - p := make(map[string]interface{}) - - if opts.Name != "" { - p["name"] = opts.Name - } - if opts.Description != "" { - p["description"] = opts.Description - } - if opts.Shared != nil { - p["shared"] = *opts.Shared - } - if opts.Audited != nil { - p["audited"] = *opts.Audited - } - if opts.Rules != nil { - p["firewall_rules"] = opts.Rules - } - - return map[string]interface{}{"firewall_policy": p}, nil -} - -// Update allows firewall policies to be updated. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToPolicyUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Delete will permanently delete a particular firewall policy based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} - -func InsertRule(c *gophercloud.ServiceClient, policyID, ruleID, beforeID, afterID string) error { - type request struct { - RuleId string `json:"firewall_rule_id"` - Before string `json:"insert_before,omitempty"` - After string `json:"insert_after,omitempty"` - } - - reqBody := request{ - RuleId: ruleID, - Before: beforeID, - After: afterID, - } - - // Send request to API - var res commonResult - _, res.Err = c.Put(insertURL(c, policyID), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res.Err -} - -func RemoveRule(c *gophercloud.ServiceClient, policyID, ruleID string) error { - type request struct { - RuleId string `json:"firewall_rule_id"` - } - - reqBody := request{ - RuleId: ruleID, - } - - // Send request to API - var res commonResult - _, res.Err = c.Put(removeURL(c, policyID), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res.Err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/results.go deleted file mode 100644 index a9a0c358d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/results.go +++ /dev/null @@ -1,101 +0,0 @@ -package policies - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type Policy struct { - ID string `json:"id" mapstructure:"id"` - Name string `json:"name" mapstructure:"name"` - Description string `json:"description" mapstructure:"description"` - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - Audited bool `json:"audited" mapstructure:"audited"` - Shared bool `json:"shared" mapstructure:"shared"` - Rules []string `json:"firewall_rules,omitempty" mapstructure:"firewall_rules"` -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a firewall policy. -func (r commonResult) Extract() (*Policy, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Policy *Policy `json:"firewall_policy" mapstructure:"firewall_policy"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Policy, err -} - -// PolicyPage is the page returned by a pager when traversing over a -// collection of firewall policies. -type PolicyPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of firewall policies has -// reached the end of a page and the pager seeks to traverse over a new one. -// In order to do this, it needs to construct the next page's URL. -func (p PolicyPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"firewall_policies_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a PolicyPage struct is empty. -func (p PolicyPage) IsEmpty() (bool, error) { - is, err := ExtractPolicies(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractPolicies accepts a Page struct, specifically a RouterPage struct, -// and extracts the elements into a slice of Router structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractPolicies(page pagination.Page) ([]Policy, error) { - var resp struct { - Policies []Policy `mapstructure:"firewall_policies" json:"firewall_policies"` - } - - err := mapstructure.Decode(page.(PolicyPage).Body, &resp) - - return resp.Policies, err -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/urls.go deleted file mode 100644 index 27ea9ae61..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/urls.go +++ /dev/null @@ -1,26 +0,0 @@ -package policies - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "fw" - resourcePath = "firewall_policies" - insertPath = "insert_rule" - removePath = "remove_rule" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} - -func insertURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id, insertPath) -} - -func removeURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id, removePath) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/errors.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/errors.go deleted file mode 100644 index 0b29d39fd..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/errors.go +++ /dev/null @@ -1,12 +0,0 @@ -package rules - -import "fmt" - -func err(str string) error { - return fmt.Errorf("%s", str) -} - -var ( - errProtocolRequired = err("A protocol is required (tcp, udp, icmp or any)") - errActionRequired = err("An action is required (allow or deny)") -) diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/requests.go deleted file mode 100644 index 57a0e8baf..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/requests.go +++ /dev/null @@ -1,285 +0,0 @@ -package rules - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// Binary gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Yes` and `No` enums -type Binary *bool - -// Convenience vars for Enabled and Shared values. -var ( - iTrue = true - iFalse = false - Yes Binary = &iTrue - No Binary = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToRuleListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the Firewall rule attributes you want to see returned. SortKey allows you to -// sort by a particular firewall rule attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - TenantID string `q:"tenant_id"` - Name string `q:"name"` - Description string `q:"description"` - Protocol string `q:"protocol"` - Action string `q:"action"` - IPVersion int `q:"ip_version"` - SourceIPAddress string `q:"source_ip_address"` - DestinationIPAddress string `q:"destination_ip_address"` - SourcePort string `q:"source_port"` - DestinationPort string `q:"destination_port"` - Enabled bool `q:"enabled"` - ID string `q:"id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToRuleListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToRuleListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// firewall rules. It accepts a ListOpts struct, which allows you to filter -// and sort the returned collection for greater efficiency. -// -// Default policy settings return only those firewall rules that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := rootURL(c) - - if opts != nil { - query, err := opts.ToRuleListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return RulePage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToRuleCreateMap() (map[string]interface{}, error) -} - -// CreateOpts contains all the values needed to create a new firewall rule. -type CreateOpts struct { - // Mandatory for create - Protocol string - Action string - // Optional - TenantID string - Name string - Description string - IPVersion int - SourceIPAddress string - DestinationIPAddress string - SourcePort string - DestinationPort string - Shared *bool - Enabled *bool -} - -// ToRuleCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToRuleCreateMap() (map[string]interface{}, error) { - if opts.Protocol == "" { - return nil, errProtocolRequired - } - - if opts.Action == "" { - return nil, errActionRequired - } - - r := make(map[string]interface{}) - - r["protocol"] = opts.Protocol - r["action"] = opts.Action - - if opts.TenantID != "" { - r["tenant_id"] = opts.TenantID - } - if opts.Name != "" { - r["name"] = opts.Name - } - if opts.Description != "" { - r["description"] = opts.Description - } - if opts.IPVersion != 0 { - r["ip_version"] = opts.IPVersion - } - if opts.SourceIPAddress != "" { - r["source_ip_address"] = opts.SourceIPAddress - } - if opts.DestinationIPAddress != "" { - r["destination_ip_address"] = opts.DestinationIPAddress - } - if opts.SourcePort != "" { - r["source_port"] = opts.SourcePort - } - if opts.DestinationPort != "" { - r["destination_port"] = opts.DestinationPort - } - if opts.Shared != nil { - r["shared"] = *opts.Shared - } - if opts.Enabled != nil { - r["enabled"] = *opts.Enabled - } - - return map[string]interface{}{"firewall_rule": r}, nil -} - -// Create accepts a CreateOpts struct and uses the values to create a new firewall rule -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToRuleCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular firewall rule based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToRuleUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts contains the values used when updating a firewall rule. -// Optional -type UpdateOpts struct { - Protocol string - Action string - Name string - Description string - IPVersion int - SourceIPAddress *string - DestinationIPAddress *string - SourcePort *string - DestinationPort *string - Shared *bool - Enabled *bool -} - -// ToRuleUpdateMap casts a UpdateOpts struct to a map. -func (opts UpdateOpts) ToRuleUpdateMap() (map[string]interface{}, error) { - r := make(map[string]interface{}) - - if opts.Protocol != "" { - r["protocol"] = opts.Protocol - } - if opts.Action != "" { - r["action"] = opts.Action - } - if opts.Name != "" { - r["name"] = opts.Name - } - if opts.Description != "" { - r["description"] = opts.Description - } - if opts.IPVersion != 0 { - r["ip_version"] = opts.IPVersion - } - if opts.SourceIPAddress != nil { - s := *opts.SourceIPAddress - if s == "" { - r["source_ip_address"] = nil - } else { - r["source_ip_address"] = s - } - } - if opts.DestinationIPAddress != nil { - s := *opts.DestinationIPAddress - if s == "" { - r["destination_ip_address"] = nil - } else { - r["destination_ip_address"] = s - } - } - if opts.SourcePort != nil { - s := *opts.SourcePort - if s == "" { - r["source_port"] = nil - } else { - r["source_port"] = s - } - } - if opts.DestinationPort != nil { - s := *opts.DestinationPort - if s == "" { - r["destination_port"] = nil - } else { - r["destination_port"] = s - } - } - if opts.Shared != nil { - r["shared"] = *opts.Shared - } - if opts.Enabled != nil { - r["enabled"] = *opts.Enabled - } - - return map[string]interface{}{"firewall_rule": r}, nil -} - -// Update allows firewall policies to be updated. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToRuleUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return res -} - -// Delete will permanently delete a particular firewall rule based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/results.go deleted file mode 100644 index d772024b3..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/results.go +++ /dev/null @@ -1,110 +0,0 @@ -package rules - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// Rule represents a firewall rule -type Rule struct { - ID string `json:"id" mapstructure:"id"` - Name string `json:"name,omitempty" mapstructure:"name"` - Description string `json:"description,omitempty" mapstructure:"description"` - Protocol string `json:"protocol" mapstructure:"protocol"` - Action string `json:"action" mapstructure:"action"` - IPVersion int `json:"ip_version,omitempty" mapstructure:"ip_version"` - SourceIPAddress string `json:"source_ip_address,omitempty" mapstructure:"source_ip_address"` - DestinationIPAddress string `json:"destination_ip_address,omitempty" mapstructure:"destination_ip_address"` - SourcePort string `json:"source_port,omitempty" mapstructure:"source_port"` - DestinationPort string `json:"destination_port,omitempty" mapstructure:"destination_port"` - Shared bool `json:"shared,omitempty" mapstructure:"shared"` - Enabled bool `json:"enabled,omitempty" mapstructure:"enabled"` - PolicyID string `json:"firewall_policy_id" mapstructure:"firewall_policy_id"` - Position int `json:"position" mapstructure:"position"` - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` -} - -// RulePage is the page returned by a pager when traversing over a -// collection of firewall rules. -type RulePage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of firewall rules has -// reached the end of a page and the pager seeks to traverse over a new one. -// In order to do this, it needs to construct the next page's URL. -func (p RulePage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"firewall_rules_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a RulePage struct is empty. -func (p RulePage) IsEmpty() (bool, error) { - is, err := ExtractRules(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractRules accepts a Page struct, specifically a RouterPage struct, -// and extracts the elements into a slice of Router structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractRules(page pagination.Page) ([]Rule, error) { - var resp struct { - Rules []Rule `mapstructure:"firewall_rules" json:"firewall_rules"` - } - - err := mapstructure.Decode(page.(RulePage).Body, &resp) - - return resp.Rules, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a firewall rule. -func (r commonResult) Extract() (*Rule, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Rule *Rule `json:"firewall_rule" mapstructure:"firewall_rule"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Rule, err -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/urls.go deleted file mode 100644 index 20b08791e..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/urls.go +++ /dev/null @@ -1,16 +0,0 @@ -package rules - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "fw" - resourcePath = "firewall_rules" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/requests.go deleted file mode 100644 index 29f752a07..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/requests.go +++ /dev/null @@ -1,168 +0,0 @@ -package floatingips - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - ID string `q:"id"` - FloatingNetworkID string `q:"floating_network_id"` - PortID string `q:"port_id"` - FixedIP string `q:"fixed_ip_address"` - FloatingIP string `q:"floating_ip_address"` - TenantID string `q:"tenant_id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// floating IP resources. It accepts a ListOpts struct, which allows you to -// filter and sort the returned collection for greater efficiency. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return FloatingIPPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// CreateOpts contains all the values needed to create a new floating IP -// resource. The only required fields are FloatingNetworkID and PortID which -// refer to the external network and internal port respectively. -type CreateOpts struct { - FloatingNetworkID string - FloatingIP string - PortID string - FixedIP string - TenantID string -} - -var ( - errFloatingNetworkIDRequired = fmt.Errorf("A NetworkID is required") -) - -// Create accepts a CreateOpts struct and uses the values provided to create a -// new floating IP resource. You can create floating IPs on external networks -// only. If you provide a FloatingNetworkID which refers to a network that is -// not external (i.e. its `router:external' attribute is False), the operation -// will fail and return a 400 error. -// -// If you do not specify a FloatingIP address value, the operation will -// automatically allocate an available address for the new resource. If you do -// choose to specify one, it must fall within the subnet range for the external -// network - otherwise the operation returns a 400 error. If the FloatingIP -// address is already in use, the operation returns a 409 error code. -// -// You can associate the new resource with an internal port by using the PortID -// field. If you specify a PortID that is not valid, the operation will fail and -// return 404 error code. -// -// You must also configure an IP address for the port associated with the PortID -// you have provided - this is what the FixedIP refers to: an IP fixed to a port. -// Because a port might be associated with multiple IP addresses, you can use -// the FixedIP field to associate a particular IP address rather than have the -// API assume for you. If you specify an IP address that is not valid, the -// operation will fail and return a 400 error code. If the PortID and FixedIP -// are already associated with another resource, the operation will fail and -// returns a 409 error code. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - // Validate - if opts.FloatingNetworkID == "" { - res.Err = errFloatingNetworkIDRequired - return res - } - - // Define structures - type floatingIP struct { - FloatingNetworkID string `json:"floating_network_id"` - FloatingIP string `json:"floating_ip_address,omitempty"` - PortID string `json:"port_id,omitempty"` - FixedIP string `json:"fixed_ip_address,omitempty"` - TenantID string `json:"tenant_id,omitempty"` - } - type request struct { - FloatingIP floatingIP `json:"floatingip"` - } - - // Populate request body - reqBody := request{FloatingIP: floatingIP{ - FloatingNetworkID: opts.FloatingNetworkID, - FloatingIP: opts.FloatingIP, - PortID: opts.PortID, - FixedIP: opts.FixedIP, - TenantID: opts.TenantID, - }} - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular floating IP resource based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOpts contains the values used when updating a floating IP resource. The -// only value that can be updated is which internal port the floating IP is -// linked to. To associate the floating IP with a new internal port, provide its -// ID. To disassociate the floating IP from all ports, provide an empty string. -type UpdateOpts struct { - PortID string -} - -// Update allows floating IP resources to be updated. Currently, the only way to -// "update" a floating IP is to associate it with a new internal port, or -// disassociated it from all ports. See UpdateOpts for instructions of how to -// do this. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - type floatingIP struct { - PortID *string `json:"port_id"` - } - - type request struct { - FloatingIP floatingIP `json:"floatingip"` - } - - var portID *string - if opts.PortID == "" { - portID = nil - } else { - portID = &opts.PortID - } - - reqBody := request{FloatingIP: floatingIP{PortID: portID}} - - // Send request to API - var res UpdateResult - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return res -} - -// Delete will permanently delete a particular floating IP resource. Please -// ensure this is what you want - you can also disassociate the IP from existing -// internal ports. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/results.go deleted file mode 100644 index a1c7afe2c..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/results.go +++ /dev/null @@ -1,127 +0,0 @@ -package floatingips - -import ( - "fmt" - - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// FloatingIP represents a floating IP resource. A floating IP is an external -// IP address that is mapped to an internal port and, optionally, a specific -// IP address on a private network. In other words, it enables access to an -// instance on a private network from an external network. For this reason, -// floating IPs can only be defined on networks where the `router:external' -// attribute (provided by the external network extension) is set to True. -type FloatingIP struct { - // Unique identifier for the floating IP instance. - ID string `json:"id" mapstructure:"id"` - - // UUID of the external network where the floating IP is to be created. - FloatingNetworkID string `json:"floating_network_id" mapstructure:"floating_network_id"` - - // Address of the floating IP on the external network. - FloatingIP string `json:"floating_ip_address" mapstructure:"floating_ip_address"` - - // UUID of the port on an internal network that is associated with the floating IP. - PortID string `json:"port_id" mapstructure:"port_id"` - - // The specific IP address of the internal port which should be associated - // with the floating IP. - FixedIP string `json:"fixed_ip_address" mapstructure:"fixed_ip_address"` - - // Owner of the floating IP. Only admin users can specify a tenant identifier - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - // The condition of the API resource. - Status string `json:"status" mapstructure:"status"` -} - -type commonResult struct { - gophercloud.Result -} - -// Extract a result and extracts a FloatingIP resource. -func (r commonResult) Extract() (*FloatingIP, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - FloatingIP *FloatingIP `json:"floatingip"` - } - - err := mapstructure.Decode(r.Body, &res) - if err != nil { - return nil, fmt.Errorf("Error decoding Neutron floating IP: %v", err) - } - - return res.FloatingIP, nil -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of an update operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// FloatingIPPage is the page returned by a pager when traversing over a -// collection of floating IPs. -type FloatingIPPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of floating IPs has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p FloatingIPPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"floatingips_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a NetworkPage struct is empty. -func (p FloatingIPPage) IsEmpty() (bool, error) { - is, err := ExtractFloatingIPs(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractFloatingIPs accepts a Page struct, specifically a FloatingIPPage struct, -// and extracts the elements into a slice of FloatingIP structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractFloatingIPs(page pagination.Page) ([]FloatingIP, error) { - var resp struct { - FloatingIPs []FloatingIP `mapstructure:"floatingips" json:"floatingips"` - } - - err := mapstructure.Decode(page.(FloatingIPPage).Body, &resp) - - return resp.FloatingIPs, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/urls.go deleted file mode 100644 index 355f20dc0..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/urls.go +++ /dev/null @@ -1,13 +0,0 @@ -package floatingips - -import "github.com/rackspace/gophercloud" - -const resourcePath = "floatingips" - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/requests.go deleted file mode 100644 index 5fde23653..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/requests.go +++ /dev/null @@ -1,256 +0,0 @@ -package routers - -import ( - "errors" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - ID string `q:"id"` - Name string `q:"name"` - AdminStateUp *bool `q:"admin_state_up"` - Distributed *bool `q:"distributed"` - Status string `q:"status"` - TenantID string `q:"tenant_id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// routers. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those routers that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return RouterPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToRouterCreateMap() (map[string]interface{}, error) -} - -// CreateOpts contains all the values needed to create a new router. There are -// no required values. -type CreateOpts struct { - Name string - AdminStateUp *bool - Distributed *bool - TenantID string - GatewayInfo *GatewayInfo -} - -// ToRouterCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToRouterCreateMap() (map[string]interface{}, error) { - r := make(map[string]interface{}) - - if gophercloud.MaybeString(opts.Name) != nil { - r["name"] = opts.Name - } - - if opts.AdminStateUp != nil { - r["admin_state_up"] = opts.AdminStateUp - } - - if opts.Distributed != nil { - r["distributed"] = opts.Distributed - } - - if gophercloud.MaybeString(opts.TenantID) != nil { - r["tenant_id"] = opts.TenantID - } - - if opts.GatewayInfo != nil { - r["external_gateway_info"] = opts.GatewayInfo - } - - return map[string]interface{}{"router": r}, nil -} - -// Create accepts a CreateOpts struct and uses the values to create a new -// logical router. When it is created, the router does not have an internal -// interface - it is not associated to any subnet. -// -// You can optionally specify an external gateway for a router using the -// GatewayInfo struct. The external gateway for the router must be plugged into -// an external network (it is external if its `router:external' field is set to -// true). -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToRouterCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular router based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOpts contains the values used when updating a router. -type UpdateOpts struct { - Name string - AdminStateUp *bool - Distributed *bool - GatewayInfo *GatewayInfo - Routes []Route -} - -// Update allows routers to be updated. You can update the name, administrative -// state, and the external gateway. For more information about how to set the -// external gateway for a router, see Create. This operation does not enable -// the update of router interfaces. To do this, use the AddInterface and -// RemoveInterface functions. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - type router struct { - Name *string `json:"name,omitempty"` - AdminStateUp *bool `json:"admin_state_up,omitempty"` - Distributed *bool `json:"distributed,omitempty"` - GatewayInfo *GatewayInfo `json:"external_gateway_info,omitempty"` - Routes []Route `json:"routes"` - } - - type request struct { - Router router `json:"router"` - } - - reqBody := request{Router: router{ - Name: gophercloud.MaybeString(opts.Name), - AdminStateUp: opts.AdminStateUp, - Distributed: opts.Distributed, - }} - - if opts.GatewayInfo != nil { - reqBody.Router.GatewayInfo = opts.GatewayInfo - } - - if opts.Routes != nil { - reqBody.Router.Routes = opts.Routes - } - - // Send request to API - var res UpdateResult - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return res -} - -// Delete will permanently delete a particular router based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} - -var errInvalidInterfaceOpts = errors.New("When adding a router interface you must provide either a subnet ID or a port ID") - -// InterfaceOpts allow you to work with operations that either add or remote -// an internal interface from a router. -type InterfaceOpts struct { - SubnetID string - PortID string -} - -// AddInterface attaches a subnet to an internal router interface. You must -// specify either a SubnetID or PortID in the request body. If you specify both, -// the operation will fail and an error will be returned. -// -// If you specify a SubnetID, the gateway IP address for that particular subnet -// is used to create the router interface. Alternatively, if you specify a -// PortID, the IP address associated with the port is used to create the router -// interface. -// -// If you reference a port that is associated with multiple IP addresses, or -// if the port is associated with zero IP addresses, the operation will fail and -// a 400 Bad Request error will be returned. -// -// If you reference a port already in use, the operation will fail and a 409 -// Conflict error will be returned. -// -// The PortID that is returned after using Extract() on the result of this -// operation can either be the same PortID passed in or, on the other hand, the -// identifier of a new port created by this operation. After the operation -// completes, the device ID of the port is set to the router ID, and the -// device owner attribute is set to `network:router_interface'. -func AddInterface(c *gophercloud.ServiceClient, id string, opts InterfaceOpts) InterfaceResult { - var res InterfaceResult - - // Validate - if (opts.SubnetID == "" && opts.PortID == "") || (opts.SubnetID != "" && opts.PortID != "") { - res.Err = errInvalidInterfaceOpts - return res - } - - type request struct { - SubnetID string `json:"subnet_id,omitempty"` - PortID string `json:"port_id,omitempty"` - } - - body := request{SubnetID: opts.SubnetID, PortID: opts.PortID} - - _, res.Err = c.Put(addInterfaceURL(c, id), body, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return res -} - -// RemoveInterface removes an internal router interface, which detaches a -// subnet from the router. You must specify either a SubnetID or PortID, since -// these values are used to identify the router interface to remove. -// -// Unlike AddInterface, you can also specify both a SubnetID and PortID. If you -// choose to specify both, the subnet ID must correspond to the subnet ID of -// the first IP address on the port specified by the port ID. Otherwise, the -// operation will fail and return a 409 Conflict error. -// -// If the router, subnet or port which are referenced do not exist or are not -// visible to you, the operation will fail and a 404 Not Found error will be -// returned. After this operation completes, the port connecting the router -// with the subnet is removed from the subnet for the network. -func RemoveInterface(c *gophercloud.ServiceClient, id string, opts InterfaceOpts) InterfaceResult { - var res InterfaceResult - - type request struct { - SubnetID string `json:"subnet_id,omitempty"` - PortID string `json:"port_id,omitempty"` - } - - body := request{SubnetID: opts.SubnetID, PortID: opts.PortID} - - _, res.Err = c.Put(removeInterfaceURL(c, id), body, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/results.go deleted file mode 100644 index 453412398..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/results.go +++ /dev/null @@ -1,171 +0,0 @@ -package routers - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// GatewayInfo represents the information of an external gateway for any -// particular network router. -type GatewayInfo struct { - NetworkID string `json:"network_id" mapstructure:"network_id"` -} - -type Route struct { - NextHop string `mapstructure:"nexthop" json:"nexthop"` - DestinationCIDR string `mapstructure:"destination" json:"destination"` -} - -// Router represents a Neutron router. A router is a logical entity that -// forwards packets across internal subnets and NATs (network address -// translation) them on external networks through an appropriate gateway. -// -// A router has an interface for each subnet with which it is associated. By -// default, the IP address of such interface is the subnet's gateway IP. Also, -// whenever a router is associated with a subnet, a port for that router -// interface is added to the subnet's network. -type Router struct { - // Indicates whether or not a router is currently operational. - Status string `json:"status" mapstructure:"status"` - - // Information on external gateway for the router. - GatewayInfo GatewayInfo `json:"external_gateway_info" mapstructure:"external_gateway_info"` - - // Administrative state of the router. - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - - // Whether router is disitrubted or not.. - Distributed bool `json:"distributed" mapstructure:"distributed"` - - // Human readable name for the router. Does not have to be unique. - Name string `json:"name" mapstructure:"name"` - - // Unique identifier for the router. - ID string `json:"id" mapstructure:"id"` - - // Owner of the router. Only admin users can specify a tenant identifier - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - Routes []Route `json:"routes" mapstructure:"routes"` -} - -// RouterPage is the page returned by a pager when traversing over a -// collection of routers. -type RouterPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of routers has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p RouterPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"routers_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a RouterPage struct is empty. -func (p RouterPage) IsEmpty() (bool, error) { - is, err := ExtractRouters(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractRouters accepts a Page struct, specifically a RouterPage struct, -// and extracts the elements into a slice of Router structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractRouters(page pagination.Page) ([]Router, error) { - var resp struct { - Routers []Router `mapstructure:"routers" json:"routers"` - } - - err := mapstructure.Decode(page.(RouterPage).Body, &resp) - - return resp.Routers, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a router. -func (r commonResult) Extract() (*Router, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Router *Router `json:"router"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Router, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// InterfaceInfo represents information about a particular router interface. As -// mentioned above, in order for a router to forward to a subnet, it needs an -// interface. -type InterfaceInfo struct { - // The ID of the subnet which this interface is associated with. - SubnetID string `json:"subnet_id" mapstructure:"subnet_id"` - - // The ID of the port that is a part of the subnet. - PortID string `json:"port_id" mapstructure:"port_id"` - - // The UUID of the interface. - ID string `json:"id" mapstructure:"id"` - - // Owner of the interface. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` -} - -// InterfaceResult represents the result of interface operations, such as -// AddInterface() and RemoveInterface(). -type InterfaceResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts an information struct. -func (r InterfaceResult) Extract() (*InterfaceInfo, error) { - if r.Err != nil { - return nil, r.Err - } - - var res *InterfaceInfo - err := mapstructure.Decode(r.Body, &res) - - return res, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/urls.go deleted file mode 100644 index bc22c2a8a..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/urls.go +++ /dev/null @@ -1,21 +0,0 @@ -package routers - -import "github.com/rackspace/gophercloud" - -const resourcePath = "routers" - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(resourcePath, id) -} - -func addInterfaceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(resourcePath, id, "add_router_interface") -} - -func removeInterfaceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(resourcePath, id, "remove_router_interface") -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests.go deleted file mode 100644 index 848938f98..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests.go +++ /dev/null @@ -1,123 +0,0 @@ -package members - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - Status string `q:"status"` - Weight int `q:"weight"` - AdminStateUp *bool `q:"admin_state_up"` - TenantID string `q:"tenant_id"` - PoolID string `q:"pool_id"` - Address string `q:"address"` - ProtocolPort int `q:"protocol_port"` - ID string `q:"id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// pools. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those pools that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return MemberPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// CreateOpts contains all the values needed to create a new pool member. -type CreateOpts struct { - // Only required if the caller has an admin role and wants to create a pool - // for another tenant. - TenantID string - - // Required. The IP address of the member. - Address string - - // Required. The port on which the application is hosted. - ProtocolPort int - - // Required. The pool to which this member will belong. - PoolID string -} - -// Create accepts a CreateOpts struct and uses the values to create a new -// load balancer pool member. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - type member struct { - TenantID string `json:"tenant_id,omitempty"` - ProtocolPort int `json:"protocol_port"` - Address string `json:"address"` - PoolID string `json:"pool_id"` - } - type request struct { - Member member `json:"member"` - } - - reqBody := request{Member: member{ - Address: opts.Address, - TenantID: opts.TenantID, - ProtocolPort: opts.ProtocolPort, - PoolID: opts.PoolID, - }} - - var res CreateResult - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular pool member based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOpts contains the values used when updating a pool member. -type UpdateOpts struct { - // The administrative state of the member, which is up (true) or down (false). - AdminStateUp bool -} - -// Update allows members to be updated. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - type member struct { - AdminStateUp bool `json:"admin_state_up"` - } - type request struct { - Member member `json:"member"` - } - - reqBody := request{Member: member{AdminStateUp: opts.AdminStateUp}} - - // Send request to API - var res UpdateResult - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 201, 202}, - }) - return res -} - -// Delete will permanently delete a particular member based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/results.go deleted file mode 100644 index 3cad339b7..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/results.go +++ /dev/null @@ -1,122 +0,0 @@ -package members - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// Member represents the application running on a backend server. -type Member struct { - // The status of the member. Indicates whether the member is operational. - Status string - - // Weight of member. - Weight int - - // The administrative state of the member, which is up (true) or down (false). - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - - // Owner of the member. Only an administrative user can specify a tenant ID - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - // The pool to which the member belongs. - PoolID string `json:"pool_id" mapstructure:"pool_id"` - - // The IP address of the member. - Address string - - // The port on which the application is hosted. - ProtocolPort int `json:"protocol_port" mapstructure:"protocol_port"` - - // The unique ID for the member. - ID string -} - -// MemberPage is the page returned by a pager when traversing over a -// collection of pool members. -type MemberPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of members has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p MemberPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"members_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a MemberPage struct is empty. -func (p MemberPage) IsEmpty() (bool, error) { - is, err := ExtractMembers(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractMembers accepts a Page struct, specifically a MemberPage struct, -// and extracts the elements into a slice of Member structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractMembers(page pagination.Page) ([]Member, error) { - var resp struct { - Members []Member `mapstructure:"members" json:"members"` - } - - err := mapstructure.Decode(page.(MemberPage).Body, &resp) - if err != nil { - return nil, err - } - - return resp.Members, nil -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a router. -func (r commonResult) Extract() (*Member, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Member *Member `json:"member"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Member, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/urls.go deleted file mode 100644 index 94b57e4c5..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/urls.go +++ /dev/null @@ -1,16 +0,0 @@ -package members - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lb" - resourcePath = "members" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/requests.go deleted file mode 100644 index 71b21ef16..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/requests.go +++ /dev/null @@ -1,265 +0,0 @@ -package monitors - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - ID string `q:"id"` - TenantID string `q:"tenant_id"` - Type string `q:"type"` - Delay int `q:"delay"` - Timeout int `q:"timeout"` - MaxRetries int `q:"max_retries"` - HTTPMethod string `q:"http_method"` - URLPath string `q:"url_path"` - ExpectedCodes string `q:"expected_codes"` - AdminStateUp *bool `q:"admin_state_up"` - Status string `q:"status"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// routers. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those routers that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return MonitorPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Constants that represent approved monitoring types. -const ( - TypePING = "PING" - TypeTCP = "TCP" - TypeHTTP = "HTTP" - TypeHTTPS = "HTTPS" -) - -var ( - errValidTypeRequired = fmt.Errorf("A valid Type is required. Supported values are PING, TCP, HTTP and HTTPS") - errDelayRequired = fmt.Errorf("Delay is required") - errTimeoutRequired = fmt.Errorf("Timeout is required") - errMaxRetriesRequired = fmt.Errorf("MaxRetries is required") - errURLPathRequired = fmt.Errorf("URL path is required") - errExpectedCodesRequired = fmt.Errorf("ExpectedCodes is required") - errDelayMustGETimeout = fmt.Errorf("Delay must be greater than or equal to timeout") -) - -// CreateOpts contains all the values needed to create a new health monitor. -type CreateOpts struct { - // Required for admins. Indicates the owner of the VIP. - TenantID string - - // Required. The type of probe, which is PING, TCP, HTTP, or HTTPS, that is - // sent by the load balancer to verify the member state. - Type string - - // Required. The time, in seconds, between sending probes to members. - Delay int - - // Required. Maximum number of seconds for a monitor to wait for a ping reply - // before it times out. The value must be less than the delay value. - Timeout int - - // Required. Number of permissible ping failures before changing the member's - // status to INACTIVE. Must be a number between 1 and 10. - MaxRetries int - - // Required for HTTP(S) types. URI path that will be accessed if monitor type - // is HTTP or HTTPS. - URLPath string - - // Required for HTTP(S) types. The HTTP method used for requests by the - // monitor. If this attribute is not specified, it defaults to "GET". - HTTPMethod string - - // Required for HTTP(S) types. Expected HTTP codes for a passing HTTP(S) - // monitor. You can either specify a single status like "200", or a range - // like "200-202". - ExpectedCodes string - - AdminStateUp *bool -} - -// Create is an operation which provisions a new health monitor. There are -// different types of monitor you can provision: PING, TCP or HTTP(S). Below -// are examples of how to create each one. -// -// Here is an example config struct to use when creating a PING or TCP monitor: -// -// CreateOpts{Type: TypePING, Delay: 20, Timeout: 10, MaxRetries: 3} -// CreateOpts{Type: TypeTCP, Delay: 20, Timeout: 10, MaxRetries: 3} -// -// Here is an example config struct to use when creating a HTTP(S) monitor: -// -// CreateOpts{Type: TypeHTTP, Delay: 20, Timeout: 10, MaxRetries: 3, -// HttpMethod: "HEAD", ExpectedCodes: "200"} -// -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - // Validate inputs - allowed := map[string]bool{TypeHTTP: true, TypeHTTPS: true, TypeTCP: true, TypePING: true} - if opts.Type == "" || allowed[opts.Type] == false { - res.Err = errValidTypeRequired - } - if opts.Delay == 0 { - res.Err = errDelayRequired - } - if opts.Timeout == 0 { - res.Err = errTimeoutRequired - } - if opts.MaxRetries == 0 { - res.Err = errMaxRetriesRequired - } - if opts.Type == TypeHTTP || opts.Type == TypeHTTPS { - if opts.URLPath == "" { - res.Err = errURLPathRequired - } - if opts.ExpectedCodes == "" { - res.Err = errExpectedCodesRequired - } - } - if opts.Delay < opts.Timeout { - res.Err = errDelayMustGETimeout - } - if res.Err != nil { - return res - } - - type monitor struct { - Type string `json:"type"` - Delay int `json:"delay"` - Timeout int `json:"timeout"` - MaxRetries int `json:"max_retries"` - TenantID *string `json:"tenant_id,omitempty"` - URLPath *string `json:"url_path,omitempty"` - ExpectedCodes *string `json:"expected_codes,omitempty"` - HTTPMethod *string `json:"http_method,omitempty"` - AdminStateUp *bool `json:"admin_state_up,omitempty"` - } - - type request struct { - Monitor monitor `json:"health_monitor"` - } - - reqBody := request{Monitor: monitor{ - Type: opts.Type, - Delay: opts.Delay, - Timeout: opts.Timeout, - MaxRetries: opts.MaxRetries, - TenantID: gophercloud.MaybeString(opts.TenantID), - URLPath: gophercloud.MaybeString(opts.URLPath), - ExpectedCodes: gophercloud.MaybeString(opts.ExpectedCodes), - HTTPMethod: gophercloud.MaybeString(opts.HTTPMethod), - AdminStateUp: opts.AdminStateUp, - }} - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular health monitor based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOpts contains all the values needed to update an existing virtual IP. -// Attributes not listed here but appear in CreateOpts are immutable and cannot -// be updated. -type UpdateOpts struct { - // Required. The time, in seconds, between sending probes to members. - Delay int - - // Required. Maximum number of seconds for a monitor to wait for a ping reply - // before it times out. The value must be less than the delay value. - Timeout int - - // Required. Number of permissible ping failures before changing the member's - // status to INACTIVE. Must be a number between 1 and 10. - MaxRetries int - - // Required for HTTP(S) types. URI path that will be accessed if monitor type - // is HTTP or HTTPS. - URLPath string - - // Required for HTTP(S) types. The HTTP method used for requests by the - // monitor. If this attribute is not specified, it defaults to "GET". - HTTPMethod string - - // Required for HTTP(S) types. Expected HTTP codes for a passing HTTP(S) - // monitor. You can either specify a single status like "200", or a range - // like "200-202". - ExpectedCodes string - - AdminStateUp *bool -} - -// Update is an operation which modifies the attributes of the specified monitor. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - var res UpdateResult - - if opts.Delay > 0 && opts.Timeout > 0 && opts.Delay < opts.Timeout { - res.Err = errDelayMustGETimeout - } - - type monitor struct { - Delay int `json:"delay"` - Timeout int `json:"timeout"` - MaxRetries int `json:"max_retries"` - URLPath *string `json:"url_path,omitempty"` - ExpectedCodes *string `json:"expected_codes,omitempty"` - HTTPMethod *string `json:"http_method,omitempty"` - AdminStateUp *bool `json:"admin_state_up,omitempty"` - } - - type request struct { - Monitor monitor `json:"health_monitor"` - } - - reqBody := request{Monitor: monitor{ - Delay: opts.Delay, - Timeout: opts.Timeout, - MaxRetries: opts.MaxRetries, - URLPath: gophercloud.MaybeString(opts.URLPath), - ExpectedCodes: gophercloud.MaybeString(opts.ExpectedCodes), - HTTPMethod: gophercloud.MaybeString(opts.HTTPMethod), - AdminStateUp: opts.AdminStateUp, - }} - - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - - return res -} - -// Delete will permanently delete a particular monitor based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/results.go deleted file mode 100644 index ac2801b8b..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/results.go +++ /dev/null @@ -1,150 +0,0 @@ -package monitors - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// Monitor represents a load balancer health monitor. A health monitor is used -// to determine whether or not back-end members of the VIP's pool are usable -// for processing a request. A pool can have several health monitors associated -// with it. There are different types of health monitors supported: -// -// PING: used to ping the members using ICMP. -// TCP: used to connect to the members using TCP. -// HTTP: used to send an HTTP request to the member. -// HTTPS: used to send a secure HTTP request to the member. -// -// When a pool has several monitors associated with it, each member of the pool -// is monitored by all these monitors. If any monitor declares the member as -// unhealthy, then the member status is changed to INACTIVE and the member -// won't participate in its pool's load balancing. In other words, ALL monitors -// must declare the member to be healthy for it to stay ACTIVE. -type Monitor struct { - // The unique ID for the VIP. - ID string - - // Monitor name. Does not have to be unique. - Name string - - // Owner of the VIP. Only an administrative user can specify a tenant ID - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - // The type of probe sent by the load balancer to verify the member state, - // which is PING, TCP, HTTP, or HTTPS. - Type string - - // The time, in seconds, between sending probes to members. - Delay int - - // The maximum number of seconds for a monitor to wait for a connection to be - // established before it times out. This value must be less than the delay value. - Timeout int - - // Number of allowed connection failures before changing the status of the - // member to INACTIVE. A valid value is from 1 to 10. - MaxRetries int `json:"max_retries" mapstructure:"max_retries"` - - // The HTTP method that the monitor uses for requests. - HTTPMethod string `json:"http_method" mapstructure:"http_method"` - - // The HTTP path of the request sent by the monitor to test the health of a - // member. Must be a string beginning with a forward slash (/). - URLPath string `json:"url_path" mapstructure:"url_path"` - - // Expected HTTP codes for a passing HTTP(S) monitor. - ExpectedCodes string `json:"expected_codes" mapstructure:"expected_codes"` - - // The administrative state of the health monitor, which is up (true) or down (false). - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - - // The status of the health monitor. Indicates whether the health monitor is - // operational. - Status string -} - -// MonitorPage is the page returned by a pager when traversing over a -// collection of health monitors. -type MonitorPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of monitors has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p MonitorPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"health_monitors_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a PoolPage struct is empty. -func (p MonitorPage) IsEmpty() (bool, error) { - is, err := ExtractMonitors(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractMonitors accepts a Page struct, specifically a MonitorPage struct, -// and extracts the elements into a slice of Monitor structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractMonitors(page pagination.Page) ([]Monitor, error) { - var resp struct { - Monitors []Monitor `mapstructure:"health_monitors" json:"health_monitors"` - } - - err := mapstructure.Decode(page.(MonitorPage).Body, &resp) - - return resp.Monitors, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a monitor. -func (r commonResult) Extract() (*Monitor, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Monitor *Monitor `json:"health_monitor" mapstructure:"health_monitor"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Monitor, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/urls.go deleted file mode 100644 index 46e84bbf5..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/urls.go +++ /dev/null @@ -1,16 +0,0 @@ -package monitors - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lb" - resourcePath = "health_monitors" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/requests.go deleted file mode 100644 index e0002acd2..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/requests.go +++ /dev/null @@ -1,186 +0,0 @@ -package pools - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - Status string `q:"status"` - LBMethod string `q:"lb_method"` - Protocol string `q:"protocol"` - SubnetID string `q:"subnet_id"` - TenantID string `q:"tenant_id"` - AdminStateUp *bool `q:"admin_state_up"` - Name string `q:"name"` - ID string `q:"id"` - VIPID string `q:"vip_id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// pools. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those pools that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return PoolPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Supported attributes for create/update operations. -const ( - LBMethodRoundRobin = "ROUND_ROBIN" - LBMethodLeastConnections = "LEAST_CONNECTIONS" - - ProtocolTCP = "TCP" - ProtocolHTTP = "HTTP" - ProtocolHTTPS = "HTTPS" -) - -// CreateOpts contains all the values needed to create a new pool. -type CreateOpts struct { - // Only required if the caller has an admin role and wants to create a pool - // for another tenant. - TenantID string - - // Required. Name of the pool. - Name string - - // Required. The protocol used by the pool members, you can use either - // ProtocolTCP, ProtocolHTTP, or ProtocolHTTPS. - Protocol string - - // The network on which the members of the pool will be located. Only members - // that are on this network can be added to the pool. - SubnetID string - - // The algorithm used to distribute load between the members of the pool. The - // current specification supports LBMethodRoundRobin and - // LBMethodLeastConnections as valid values for this attribute. - LBMethod string - - // The provider of the pool - Provider string -} - -// Create accepts a CreateOpts struct and uses the values to create a new -// load balancer pool. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - type pool struct { - Name string `json:"name"` - TenantID string `json:"tenant_id,omitempty"` - Protocol string `json:"protocol"` - SubnetID string `json:"subnet_id"` - LBMethod string `json:"lb_method"` - Provider string `json:"provider,omitempty"` - } - type request struct { - Pool pool `json:"pool"` - } - - reqBody := request{Pool: pool{ - Name: opts.Name, - TenantID: opts.TenantID, - Protocol: opts.Protocol, - SubnetID: opts.SubnetID, - LBMethod: opts.LBMethod, - Provider: opts.Provider, - }} - - var res CreateResult - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular pool based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOpts contains the values used when updating a pool. -type UpdateOpts struct { - // Required. Name of the pool. - Name string - - // The algorithm used to distribute load between the members of the pool. The - // current specification supports LBMethodRoundRobin and - // LBMethodLeastConnections as valid values for this attribute. - LBMethod string -} - -// Update allows pools to be updated. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - type pool struct { - Name string `json:"name,"` - LBMethod string `json:"lb_method"` - } - type request struct { - Pool pool `json:"pool"` - } - - reqBody := request{Pool: pool{ - Name: opts.Name, - LBMethod: opts.LBMethod, - }} - - // Send request to API - var res UpdateResult - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Delete will permanently delete a particular pool based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} - -// AssociateMonitor will associate a health monitor with a particular pool. -// Once associated, the health monitor will start monitoring the members of the -// pool and will deactivate these members if they are deemed unhealthy. A -// member can be deactivated (status set to INACTIVE) if any of health monitors -// finds it unhealthy. -func AssociateMonitor(c *gophercloud.ServiceClient, poolID, monitorID string) AssociateResult { - type hm struct { - ID string `json:"id"` - } - type request struct { - Monitor hm `json:"health_monitor"` - } - - reqBody := request{hm{ID: monitorID}} - - var res AssociateResult - _, res.Err = c.Post(associateURL(c, poolID), reqBody, &res.Body, nil) - return res -} - -// DisassociateMonitor will disassociate a health monitor with a particular -// pool. When dissociation is successful, the health monitor will no longer -// check for the health of the members of the pool. -func DisassociateMonitor(c *gophercloud.ServiceClient, poolID, monitorID string) AssociateResult { - var res AssociateResult - _, res.Err = c.Delete(disassociateURL(c, poolID, monitorID), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/results.go deleted file mode 100644 index 07ec85eda..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/results.go +++ /dev/null @@ -1,146 +0,0 @@ -package pools - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// Pool represents a logical set of devices, such as web servers, that you -// group together to receive and process traffic. The load balancing function -// chooses a member of the pool according to the configured load balancing -// method to handle the new requests or connections received on the VIP address. -// There is only one pool per virtual IP. -type Pool struct { - // The status of the pool. Indicates whether the pool is operational. - Status string - - // The load-balancer algorithm, which is round-robin, least-connections, and - // so on. This value, which must be supported, is dependent on the provider. - // Round-robin must be supported. - LBMethod string `json:"lb_method" mapstructure:"lb_method"` - - // The protocol of the pool, which is TCP, HTTP, or HTTPS. - Protocol string - - // Description for the pool. - Description string - - // The IDs of associated monitors which check the health of the pool members. - MonitorIDs []string `json:"health_monitors" mapstructure:"health_monitors"` - - // The network on which the members of the pool will be located. Only members - // that are on this network can be added to the pool. - SubnetID string `json:"subnet_id" mapstructure:"subnet_id"` - - // Owner of the pool. Only an administrative user can specify a tenant ID - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - // The administrative state of the pool, which is up (true) or down (false). - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - - // Pool name. Does not have to be unique. - Name string - - // List of member IDs that belong to the pool. - MemberIDs []string `json:"members" mapstructure:"members"` - - // The unique ID for the pool. - ID string - - // The ID of the virtual IP associated with this pool - VIPID string `json:"vip_id" mapstructure:"vip_id"` - - // The provider - Provider string -} - -// PoolPage is the page returned by a pager when traversing over a -// collection of pools. -type PoolPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of pools has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p PoolPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"pools_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a PoolPage struct is empty. -func (p PoolPage) IsEmpty() (bool, error) { - is, err := ExtractPools(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractPools accepts a Page struct, specifically a RouterPage struct, -// and extracts the elements into a slice of Router structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractPools(page pagination.Page) ([]Pool, error) { - var resp struct { - Pools []Pool `mapstructure:"pools" json:"pools"` - } - - err := mapstructure.Decode(page.(PoolPage).Body, &resp) - - return resp.Pools, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a router. -func (r commonResult) Extract() (*Pool, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Pool *Pool `json:"pool"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Pool, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// AssociateResult represents the result of an association operation. -type AssociateResult struct { - commonResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/urls.go deleted file mode 100644 index 6cd15b002..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/urls.go +++ /dev/null @@ -1,25 +0,0 @@ -package pools - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lb" - resourcePath = "pools" - monitorPath = "health_monitors" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} - -func associateURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id, monitorPath) -} - -func disassociateURL(c *gophercloud.ServiceClient, poolID, monitorID string) string { - return c.ServiceURL(rootPath, resourcePath, poolID, monitorPath, monitorID) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/requests.go deleted file mode 100644 index 6216f873e..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/requests.go +++ /dev/null @@ -1,256 +0,0 @@ -package vips - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -// Convenience vars for AdminStateUp values. -var ( - iTrue = true - iFalse = false - - Up AdminState = &iTrue - Down AdminState = &iFalse -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - ID string `q:"id"` - Name string `q:"name"` - AdminStateUp *bool `q:"admin_state_up"` - Status string `q:"status"` - TenantID string `q:"tenant_id"` - SubnetID string `q:"subnet_id"` - Address string `q:"address"` - PortID string `q:"port_id"` - Protocol string `q:"protocol"` - ProtocolPort int `q:"protocol_port"` - ConnectionLimit int `q:"connection_limit"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// routers. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those routers that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return VIPPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -var ( - errNameRequired = fmt.Errorf("Name is required") - errSubnetIDRequried = fmt.Errorf("SubnetID is required") - errProtocolRequired = fmt.Errorf("Protocol is required") - errProtocolPortRequired = fmt.Errorf("Protocol port is required") - errPoolIDRequired = fmt.Errorf("PoolID is required") -) - -// CreateOpts contains all the values needed to create a new virtual IP. -type CreateOpts struct { - // Required. Human-readable name for the VIP. Does not have to be unique. - Name string - - // Required. The network on which to allocate the VIP's address. A tenant can - // only create VIPs on networks authorized by policy (e.g. networks that - // belong to them or networks that are shared). - SubnetID string - - // Required. The protocol - can either be TCP, HTTP or HTTPS. - Protocol string - - // Required. The port on which to listen for client traffic. - ProtocolPort int - - // Required. The ID of the pool with which the VIP is associated. - PoolID string - - // Required for admins. Indicates the owner of the VIP. - TenantID string - - // Optional. The IP address of the VIP. - Address string - - // Optional. Human-readable description for the VIP. - Description string - - // Optional. Omit this field to prevent session persistence. - Persistence *SessionPersistence - - // Optional. The maximum number of connections allowed for the VIP. - ConnLimit *int - - // Optional. The administrative state of the VIP. A valid value is true (UP) - // or false (DOWN). - AdminStateUp *bool -} - -// Create is an operation which provisions a new virtual IP based on the -// configuration defined in the CreateOpts struct. Once the request is -// validated and progress has started on the provisioning process, a -// CreateResult will be returned. -// -// Please note that the PoolID should refer to a pool that is not already -// associated with another vip. If the pool is already used by another vip, -// then the operation will fail with a 409 Conflict error will be returned. -// -// Users with an admin role can create VIPs on behalf of other tenants by -// specifying a TenantID attribute different than their own. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - // Validate required opts - if opts.Name == "" { - res.Err = errNameRequired - return res - } - if opts.SubnetID == "" { - res.Err = errSubnetIDRequried - return res - } - if opts.Protocol == "" { - res.Err = errProtocolRequired - return res - } - if opts.ProtocolPort == 0 { - res.Err = errProtocolPortRequired - return res - } - if opts.PoolID == "" { - res.Err = errPoolIDRequired - return res - } - - type vip struct { - Name string `json:"name"` - SubnetID string `json:"subnet_id"` - Protocol string `json:"protocol"` - ProtocolPort int `json:"protocol_port"` - PoolID string `json:"pool_id"` - Description *string `json:"description,omitempty"` - TenantID *string `json:"tenant_id,omitempty"` - Address *string `json:"address,omitempty"` - Persistence *SessionPersistence `json:"session_persistence,omitempty"` - ConnLimit *int `json:"connection_limit,omitempty"` - AdminStateUp *bool `json:"admin_state_up,omitempty"` - } - - type request struct { - VirtualIP vip `json:"vip"` - } - - reqBody := request{VirtualIP: vip{ - Name: opts.Name, - SubnetID: opts.SubnetID, - Protocol: opts.Protocol, - ProtocolPort: opts.ProtocolPort, - PoolID: opts.PoolID, - Description: gophercloud.MaybeString(opts.Description), - TenantID: gophercloud.MaybeString(opts.TenantID), - Address: gophercloud.MaybeString(opts.Address), - ConnLimit: opts.ConnLimit, - AdminStateUp: opts.AdminStateUp, - }} - - if opts.Persistence != nil { - reqBody.VirtualIP.Persistence = opts.Persistence - } - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular virtual IP based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOpts contains all the values needed to update an existing virtual IP. -// Attributes not listed here but appear in CreateOpts are immutable and cannot -// be updated. -type UpdateOpts struct { - // Human-readable name for the VIP. Does not have to be unique. - Name string - - // Required. The ID of the pool with which the VIP is associated. - PoolID string - - // Optional. Human-readable description for the VIP. - Description string - - // Optional. Omit this field to prevent session persistence. - Persistence *SessionPersistence - - // Optional. The maximum number of connections allowed for the VIP. - ConnLimit *int - - // Optional. The administrative state of the VIP. A valid value is true (UP) - // or false (DOWN). - AdminStateUp *bool -} - -// Update is an operation which modifies the attributes of the specified VIP. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - type vip struct { - Name string `json:"name,omitempty"` - PoolID string `json:"pool_id,omitempty"` - Description *string `json:"description,omitempty"` - Persistence *SessionPersistence `json:"session_persistence,omitempty"` - ConnLimit *int `json:"connection_limit,omitempty"` - AdminStateUp *bool `json:"admin_state_up,omitempty"` - } - - type request struct { - VirtualIP vip `json:"vip"` - } - - reqBody := request{VirtualIP: vip{ - Name: opts.Name, - PoolID: opts.PoolID, - Description: gophercloud.MaybeString(opts.Description), - ConnLimit: opts.ConnLimit, - AdminStateUp: opts.AdminStateUp, - }} - - if opts.Persistence != nil { - reqBody.VirtualIP.Persistence = opts.Persistence - } - - var res UpdateResult - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - - return res -} - -// Delete will permanently delete a particular virtual IP based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/results.go deleted file mode 100644 index e1092e780..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/results.go +++ /dev/null @@ -1,166 +0,0 @@ -package vips - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// SessionPersistence represents the session persistence feature of the load -// balancing service. It attempts to force connections or requests in the same -// session to be processed by the same member as long as it is ative. Three -// types of persistence are supported: -// -// SOURCE_IP: With this mode, all connections originating from the same source -// IP address, will be handled by the same member of the pool. -// HTTP_COOKIE: With this persistence mode, the load balancing function will -// create a cookie on the first request from a client. Subsequent -// requests containing the same cookie value will be handled by -// the same member of the pool. -// APP_COOKIE: With this persistence mode, the load balancing function will -// rely on a cookie established by the backend application. All -// requests carrying the same cookie value will be handled by the -// same member of the pool. -type SessionPersistence struct { - // The type of persistence mode - Type string `mapstructure:"type" json:"type"` - - // Name of cookie if persistence mode is set appropriately - CookieName string `mapstructure:"cookie_name" json:"cookie_name,omitempty"` -} - -// VirtualIP is the primary load balancing configuration object that specifies -// the virtual IP address and port on which client traffic is received, as well -// as other details such as the load balancing method to be use, protocol, etc. -// This entity is sometimes known in LB products under the name of a "virtual -// server", a "vserver" or a "listener". -type VirtualIP struct { - // The unique ID for the VIP. - ID string `mapstructure:"id" json:"id"` - - // Owner of the VIP. Only an admin user can specify a tenant ID other than its own. - TenantID string `mapstructure:"tenant_id" json:"tenant_id"` - - // Human-readable name for the VIP. Does not have to be unique. - Name string `mapstructure:"name" json:"name"` - - // Human-readable description for the VIP. - Description string `mapstructure:"description" json:"description"` - - // The ID of the subnet on which to allocate the VIP address. - SubnetID string `mapstructure:"subnet_id" json:"subnet_id"` - - // The IP address of the VIP. - Address string `mapstructure:"address" json:"address"` - - // The protocol of the VIP address. A valid value is TCP, HTTP, or HTTPS. - Protocol string `mapstructure:"protocol" json:"protocol"` - - // The port on which to listen to client traffic that is associated with the - // VIP address. A valid value is from 0 to 65535. - ProtocolPort int `mapstructure:"protocol_port" json:"protocol_port"` - - // The ID of the pool with which the VIP is associated. - PoolID string `mapstructure:"pool_id" json:"pool_id"` - - // The ID of the port which belongs to the load balancer - PortID string `mapstructure:"port_id" json:"port_id"` - - // Indicates whether connections in the same session will be processed by the - // same pool member or not. - Persistence SessionPersistence `mapstructure:"session_persistence" json:"session_persistence"` - - // The maximum number of connections allowed for the VIP. Default is -1, - // meaning no limit. - ConnLimit int `mapstructure:"connection_limit" json:"connection_limit"` - - // The administrative state of the VIP. A valid value is true (UP) or false (DOWN). - AdminStateUp bool `mapstructure:"admin_state_up" json:"admin_state_up"` - - // The status of the VIP. Indicates whether the VIP is operational. - Status string `mapstructure:"status" json:"status"` -} - -// VIPPage is the page returned by a pager when traversing over a -// collection of routers. -type VIPPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of routers has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p VIPPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"vips_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a RouterPage struct is empty. -func (p VIPPage) IsEmpty() (bool, error) { - is, err := ExtractVIPs(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractVIPs accepts a Page struct, specifically a VIPPage struct, -// and extracts the elements into a slice of VirtualIP structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractVIPs(page pagination.Page) ([]VirtualIP, error) { - var resp struct { - VIPs []VirtualIP `mapstructure:"vips" json:"vips"` - } - - err := mapstructure.Decode(page.(VIPPage).Body, &resp) - - return resp.VIPs, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a router. -func (r commonResult) Extract() (*VirtualIP, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - VirtualIP *VirtualIP `mapstructure:"vip" json:"vip"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.VirtualIP, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/urls.go deleted file mode 100644 index 2b6f67e71..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/urls.go +++ /dev/null @@ -1,16 +0,0 @@ -package vips - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lb" - resourcePath = "vips" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/doc.go deleted file mode 100644 index 247a75fac..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package lbaas_v2 provides information and interaction with the Load Balancer -// as a Service v2 extension for the OpenStack Networking service. -// lbaas v2 api docs: http://developer.openstack.org/api-ref-networking-v2-ext.html#lbaas-v2.0 -// lbaas v2 api schema: https://github.com/openstack/neutron-lbaas/blob/master/neutron_lbaas/extensions/loadbalancerv2.py -package lbaas_v2 diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/fixtures.go deleted file mode 100644 index 4c22f63d3..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/fixtures.go +++ /dev/null @@ -1,214 +0,0 @@ -// +build fixtures - -package listeners - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// ListenersListBody contains the canned body of a listeners list response. -const ListenersListBody = ` -{ - "listeners":[ - { - "id": "db902c0c-d5ff-4753-b465-668ad9656918", - "tenant_id": "310df60f-2a10-4ee5-9554-98393092194c", - "name": "web", - "description": "listener config for the web tier", - "loadbalancers": [{"id": "53306cda-815d-4354-9444-59e09da9c3c5"}], - "protocol": "HTTP", - "protocol_port": 80, - "default_pool_id": "fad389a3-9a4a-4762-a365-8c7038508b5d", - "admin_state_up": true, - "default_tls_container_ref": "2c433435-20de-4411-84ae-9cc8917def76", - "sni_container_refs": ["3d328d82-2547-4921-ac2f-61c3b452b5ff", "b3cfd7e3-8c19-455c-8ebb-d78dfd8f7e7d"] - }, - { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "tenant_id": "310df60f-2a10-4ee5-9554-98393092194c", - "name": "db", - "description": "listener config for the db tier", - "loadbalancers": [{"id": "79e05663-7f03-45d2-a092-8b94062f22ab"}], - "protocol": "TCP", - "protocol_port": 3306, - "default_pool_id": "41efe233-7591-43c5-9cf7-923964759f9e", - "connection_limit": 2000, - "admin_state_up": true, - "default_tls_container_ref": "2c433435-20de-4411-84ae-9cc8917def76", - "sni_container_refs": ["3d328d82-2547-4921-ac2f-61c3b452b5ff", "b3cfd7e3-8c19-455c-8ebb-d78dfd8f7e7d"] - } - ] -} -` - -// SingleServerBody is the canned body of a Get request on an existing listener. -const SingleListenerBody = ` -{ - "listener": { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "tenant_id": "310df60f-2a10-4ee5-9554-98393092194c", - "name": "db", - "description": "listener config for the db tier", - "loadbalancers": [{"id": "79e05663-7f03-45d2-a092-8b94062f22ab"}], - "protocol": "TCP", - "protocol_port": 3306, - "default_pool_id": "41efe233-7591-43c5-9cf7-923964759f9e", - "connection_limit": 2000, - "admin_state_up": true, - "default_tls_container_ref": "2c433435-20de-4411-84ae-9cc8917def76", - "sni_container_refs": ["3d328d82-2547-4921-ac2f-61c3b452b5ff", "b3cfd7e3-8c19-455c-8ebb-d78dfd8f7e7d"] - } -} -` - -// PostUpdateListenerBody is the canned response body of a Update request on an existing listener. -const PostUpdateListenerBody = ` -{ - "listener": { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "tenant_id": "310df60f-2a10-4ee5-9554-98393092194c", - "name": "NewListenerName", - "description": "listener config for the db tier", - "loadbalancers": [{"id": "79e05663-7f03-45d2-a092-8b94062f22ab"}], - "protocol": "TCP", - "protocol_port": 3306, - "default_pool_id": "41efe233-7591-43c5-9cf7-923964759f9e", - "connection_limit": 1000, - "admin_state_up": true, - "default_tls_container_ref": "2c433435-20de-4411-84ae-9cc8917def76", - "sni_container_refs": ["3d328d82-2547-4921-ac2f-61c3b452b5ff", "b3cfd7e3-8c19-455c-8ebb-d78dfd8f7e7d"] - } -} -` - -var ( - ListenerWeb = Listener{ - ID: "db902c0c-d5ff-4753-b465-668ad9656918", - TenantID: "310df60f-2a10-4ee5-9554-98393092194c", - Name: "web", - Description: "listener config for the web tier", - Loadbalancers: []LoadBalancerID{{ID: "53306cda-815d-4354-9444-59e09da9c3c5"}}, - Protocol: "HTTP", - ProtocolPort: 80, - DefaultPoolID: "fad389a3-9a4a-4762-a365-8c7038508b5d", - AdminStateUp: true, - DefaultTlsContainerRef: "2c433435-20de-4411-84ae-9cc8917def76", - SniContainerRefs: []string{"3d328d82-2547-4921-ac2f-61c3b452b5ff", "b3cfd7e3-8c19-455c-8ebb-d78dfd8f7e7d"}, - } - ListenerDb = Listener{ - ID: "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - TenantID: "310df60f-2a10-4ee5-9554-98393092194c", - Name: "db", - Description: "listener config for the db tier", - Loadbalancers: []LoadBalancerID{{ID: "79e05663-7f03-45d2-a092-8b94062f22ab"}}, - Protocol: "TCP", - ProtocolPort: 3306, - DefaultPoolID: "41efe233-7591-43c5-9cf7-923964759f9e", - ConnLimit: 2000, - AdminStateUp: true, - DefaultTlsContainerRef: "2c433435-20de-4411-84ae-9cc8917def76", - SniContainerRefs: []string{"3d328d82-2547-4921-ac2f-61c3b452b5ff", "b3cfd7e3-8c19-455c-8ebb-d78dfd8f7e7d"}, - } - ListenerUpdated = Listener{ - ID: "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - TenantID: "310df60f-2a10-4ee5-9554-98393092194c", - Name: "NewListenerName", - Description: "listener config for the db tier", - Loadbalancers: []LoadBalancerID{{ID: "79e05663-7f03-45d2-a092-8b94062f22ab"}}, - Protocol: "TCP", - ProtocolPort: 3306, - DefaultPoolID: "41efe233-7591-43c5-9cf7-923964759f9e", - ConnLimit: 1000, - AdminStateUp: true, - DefaultTlsContainerRef: "2c433435-20de-4411-84ae-9cc8917def76", - SniContainerRefs: []string{"3d328d82-2547-4921-ac2f-61c3b452b5ff", "b3cfd7e3-8c19-455c-8ebb-d78dfd8f7e7d"}, - } -) - -// HandleListenerListSuccessfully sets up the test server to respond to a listener List request. -func HandleListenerListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/listeners", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, ListenersListBody) - case "45e08a3e-a78f-4b40-a229-1e7e23eee1ab": - fmt.Fprintf(w, `{ "listeners": [] }`) - default: - t.Fatalf("/v2.0/lbaas/listeners invoked with unexpected marker=[%s]", marker) - } - }) -} - -// HandleListenerCreationSuccessfully sets up the test server to respond to a listener creation request -// with a given response. -func HandleListenerCreationSuccessfully(t *testing.T, response string) { - th.Mux.HandleFunc("/v2.0/lbaas/listeners", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "listener": { - "loadbalancer_id": "79e05663-7f03-45d2-a092-8b94062f22ab", - "protocol": "TCP", - "name": "db", - "admin_state_up": true, - "default_tls_container_ref": "2c433435-20de-4411-84ae-9cc8917def76", - "default_pool_id": "41efe233-7591-43c5-9cf7-923964759f9e", - "protocol_port": 3306 - } - }`) - - w.WriteHeader(http.StatusAccepted) - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, response) - }) -} - -// HandleListenerGetSuccessfully sets up the test server to respond to a listener Get request. -func HandleListenerGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/listeners/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, SingleListenerBody) - }) -} - -// HandleListenerDeletionSuccessfully sets up the test server to respond to a listener deletion request. -func HandleListenerDeletionSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/listeners/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleListenerUpdateSuccessfully sets up the test server to respond to a listener Update request. -func HandleListenerUpdateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/listeners/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestJSONRequest(t, r, `{ - "listener": { - "name": "NewListenerName", - "connection_limit": 1001 - } - }`) - - fmt.Fprintf(w, PostUpdateListenerBody) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/requests.go deleted file mode 100644 index a62e0cd9e..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/requests.go +++ /dev/null @@ -1,279 +0,0 @@ -package listeners - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -type listenerOpts struct { - // Required. The protocol - can either be TCP, HTTP or HTTPS. - Protocol Protocol - - // Required. The port on which to listen for client traffic. - ProtocolPort int - - // Required for admins. Indicates the owner of the Listener. - TenantID string - - // Required. The load balancer on which to provision this listener. - LoadbalancerID string - - // Human-readable name for the Listener. Does not have to be unique. - Name string - - // Optional. The ID of the default pool with which the Listener is associated. - DefaultPoolID string - - // Optional. Human-readable description for the Listener. - Description string - - // Optional. The maximum number of connections allowed for the Listener. - ConnLimit *int - - // Optional. A reference to a container of TLS secrets. - DefaultTlsContainerRef string - - // Optional. A list of references to TLS secrets. - SniContainerRefs []string - - // Optional. The administrative state of the Listener. A valid value is true (UP) - // or false (DOWN). - AdminStateUp *bool -} - -// Convenience vars for AdminStateUp values. -var ( - iTrue = true - iFalse = false - - Up AdminState = &iTrue - Down AdminState = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToListenerListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular listener attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - ID string `q:"id"` - Name string `q:"name"` - AdminStateUp *bool `q:"admin_state_up"` - TenantID string `q:"tenant_id"` - LoadbalancerID string `q:"loadbalancer_id"` - DefaultPoolID string `q:"default_pool_id"` - Protocol string `q:"protocol"` - ProtocolPort int `q:"protocol_port"` - ConnectionLimit int `q:"connection_limit"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToListenerListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToListenerListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// routers. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those routers that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := rootURL(c) - if opts != nil { - query, err := opts.ToListenerListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return ListenerPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -type Protocol string - -// Supported attributes for create/update operations. -const ( - ProtocolTCP Protocol = "TCP" - ProtocolHTTP Protocol = "HTTP" - ProtocolHTTPS Protocol = "HTTPS" -) - -var ( - errLoadbalancerIdRequired = fmt.Errorf("LoadbalancerID is required") - errProtocolRequired = fmt.Errorf("Protocol is required") - errProtocolPortRequired = fmt.Errorf("ProtocolPort is required") -) - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToListenerCreateMap() (map[string]interface{}, error) -} - -// CreateOpts is the common options struct used in this package's Create -// operation. -type CreateOpts listenerOpts - -// ToListenerCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToListenerCreateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - - if opts.LoadbalancerID != "" { - l["loadbalancer_id"] = opts.LoadbalancerID - } else { - return nil, errLoadbalancerIdRequired - } - if opts.Protocol != "" { - l["protocol"] = opts.Protocol - } else { - return nil, errProtocolRequired - } - if opts.ProtocolPort != 0 { - l["protocol_port"] = opts.ProtocolPort - } else { - return nil, errProtocolPortRequired - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.TenantID != "" { - l["tenant_id"] = opts.TenantID - } - if opts.DefaultPoolID != "" { - l["default_pool_id"] = opts.DefaultPoolID - } - if opts.Description != "" { - l["description"] = opts.Description - } - if opts.ConnLimit != nil { - l["connection_limit"] = &opts.ConnLimit - } - if opts.DefaultTlsContainerRef != "" { - l["default_tls_container_ref"] = opts.DefaultTlsContainerRef - } - if opts.SniContainerRefs != nil { - l["sni_container_refs"] = opts.SniContainerRefs - } - - return map[string]interface{}{"listener": l}, nil -} - -// Create is an operation which provisions a new Listeners based on the -// configuration defined in the CreateOpts struct. Once the request is -// validated and progress has started on the provisioning process, a -// CreateResult will be returned. -// -// Users with an admin role can create Listeners on behalf of other tenants by -// specifying a TenantID attribute different than their own. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - reqBody, err := opts.ToListenerCreateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular Listeners based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToListenerUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts is the common options struct used in this package's Update -// operation. -type UpdateOpts listenerOpts - -// ToListenerUpdateMap casts a UpdateOpts struct to a map. -func (opts UpdateOpts) ToListenerUpdateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.Description != "" { - l["description"] = opts.Description - } - if opts.ConnLimit != nil { - l["connection_limit"] = &opts.ConnLimit - } - if opts.DefaultTlsContainerRef != "" { - l["default_tls_container_ref"] = opts.DefaultTlsContainerRef - } - if opts.SniContainerRefs != nil { - l["sni_container_refs"] = opts.SniContainerRefs - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - - return map[string]interface{}{"listener": l}, nil -} - -// Update is an operation which modifies the attributes of the specified Listener. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToListenerUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - - return res -} - -// Delete will permanently delete a particular Listeners based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/results.go deleted file mode 100644 index 77a084a58..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/results.go +++ /dev/null @@ -1,139 +0,0 @@ -package listeners - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools" - "github.com/rackspace/gophercloud/pagination" -) - -type LoadBalancerID struct { - ID string `mapstructure:"id" json:"id"` -} - -// Listener is the primary load balancing configuration object that specifies -// the loadbalancer and port on which client traffic is received, as well -// as other details such as the load balancing method to be use, protocol, etc. -type Listener struct { - // The unique ID for the Listener. - ID string `mapstructure:"id" json:"id"` - - // Owner of the Listener. Only an admin user can specify a tenant ID other than its own. - TenantID string `mapstructure:"tenant_id" json:"tenant_id"` - - // Human-readable name for the Listener. Does not have to be unique. - Name string `mapstructure:"name" json:"name"` - - // Human-readable description for the Listener. - Description string `mapstructure:"description" json:"description"` - - // The protocol to loadbalance. A valid value is TCP, HTTP, or HTTPS. - Protocol string `mapstructure:"protocol" json:"protocol"` - - // The port on which to listen to client traffic that is associated with the - // Loadbalancer. A valid value is from 0 to 65535. - ProtocolPort int `mapstructure:"protocol_port" json:"protocol_port"` - - // The UUID of default pool. Must have compatible protocol with listener. - DefaultPoolID string `mapstructure:"default_pool_id" json:"default_pool_id"` - - // A list of load balancer IDs. - Loadbalancers []LoadBalancerID `mapstructure:"loadbalancers" json:"loadbalancers"` - - // The maximum number of connections allowed for the Loadbalancer. Default is -1, - // meaning no limit. - ConnLimit int `mapstructure:"connection_limit" json:"connection_limit"` - - // The list of references to TLS secrets. - SniContainerRefs []string `mapstructure:"sni_container_refs" json:"sni_container_refs"` - - // Optional. A reference to a container of TLS secrets. - DefaultTlsContainerRef string `mapstructure:"default_tls_container_ref" json:"default_tls_container_ref"` - - // The administrative state of the Listener. A valid value is true (UP) or false (DOWN). - AdminStateUp bool `mapstructure:"admin_state_up" json:"admin_state_up"` - - Pools []pools.Pool `mapstructure:"pools" json:"pools"` -} - -// ListenerPage is the page returned by a pager when traversing over a -// collection of routers. -type ListenerPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of routers has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p ListenerPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"listeners_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a RouterPage struct is empty. -func (p ListenerPage) IsEmpty() (bool, error) { - is, err := ExtractListeners(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractListeners accepts a Page struct, specifically a ListenerPage struct, -// and extracts the elements into a slice of Listener structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractListeners(page pagination.Page) ([]Listener, error) { - var resp struct { - Listeners []Listener `mapstructure:"listeners" json:"listeners"` - } - err := mapstructure.Decode(page.(ListenerPage).Body, &resp) - return resp.Listeners, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a router. -func (r commonResult) Extract() (*Listener, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Listener *Listener `mapstructure:"listener" json:"listener"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Listener, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/urls.go deleted file mode 100644 index b4cb90b08..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners/urls.go +++ /dev/null @@ -1,16 +0,0 @@ -package listeners - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lbaas" - resourcePath = "listeners" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/fixtures.go deleted file mode 100644 index cb4315876..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/fixtures.go +++ /dev/null @@ -1,278 +0,0 @@ -// +build fixtures - -package loadbalancers - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" - - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools" -) - -// LoadbalancersListBody contains the canned body of a loadbalancer list response. -const LoadbalancersListBody = ` -{ - "loadbalancers":[ - { - "id": "c331058c-6a40-4144-948e-b9fb1df9db4b", - "tenant_id": "54030507-44f7-473c-9342-b4d14a95f692", - "name": "web_lb", - "description": "lb config for the web tier", - "vip_subnet_id": "8a49c438-848f-467b-9655-ea1548708154", - "vip_address": "10.30.176.47", - "flavor": "small", - "provider": "haproxy", - "admin_state_up": true, - "provisioning_status": "ACTIVE", - "operating_status": "ONLINE" - }, - { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "tenant_id": "54030507-44f7-473c-9342-b4d14a95f692", - "name": "db_lb", - "description": "lb config for the db tier", - "vip_subnet_id": "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - "vip_address": "10.30.176.48", - "flavor": "medium", - "provider": "haproxy", - "admin_state_up": true, - "provisioning_status": "PENDING_CREATE", - "operating_status": "OFFLINE" - } - ] -} -` - -// SingleLoadbalancerBody is the canned body of a Get request on an existing loadbalancer. -const SingleLoadbalancerBody = ` -{ - "loadbalancer": { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "tenant_id": "54030507-44f7-473c-9342-b4d14a95f692", - "name": "db_lb", - "description": "lb config for the db tier", - "vip_subnet_id": "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - "vip_address": "10.30.176.48", - "flavor": "medium", - "provider": "haproxy", - "admin_state_up": true, - "provisioning_status": "PENDING_CREATE", - "operating_status": "OFFLINE" - } -} -` - -// PostUpdateLoadbalancerBody is the canned response body of a Update request on an existing loadbalancer. -const PostUpdateLoadbalancerBody = ` -{ - "loadbalancer": { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "tenant_id": "54030507-44f7-473c-9342-b4d14a95f692", - "name": "NewLoadbalancerName", - "description": "lb config for the db tier", - "vip_subnet_id": "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - "vip_address": "10.30.176.48", - "flavor": "medium", - "provider": "haproxy", - "admin_state_up": true, - "provisioning_status": "PENDING_CREATE", - "operating_status": "OFFLINE" - } -} -` - -// SingleLoadbalancerBody is the canned body of a Get request on an existing loadbalancer. -const LoadbalancerStatuesesTree = ` -{ - "statuses" : { - "loadbalancer": { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "name": "db_lb", - "provisioning_status": "PENDING_UPDATE", - "operating_status": "ACTIVE", - "listeners": [{ - "id": "db902c0c-d5ff-4753-b465-668ad9656918", - "name": "db", - "pools": [{ - "id": "fad389a3-9a4a-4762-a365-8c7038508b5d", - "name": "db", - "healthmonitor": { - "id": "67306cda-815d-4354-9fe4-59e09da9c3c5", - "type":"PING" - }, - "members":[{ - "id": "2a280670-c202-4b0b-a562-34077415aabf", - "name": "db", - "address": "10.0.2.11", - "protocol_port": 80 - }] - }] - }] - } - } -} -` - -var ( - LoadbalancerWeb = LoadBalancer{ - ID: "c331058c-6a40-4144-948e-b9fb1df9db4b", - TenantID: "54030507-44f7-473c-9342-b4d14a95f692", - Name: "web_lb", - Description: "lb config for the web tier", - VipSubnetID: "8a49c438-848f-467b-9655-ea1548708154", - VipAddress: "10.30.176.47", - Flavor: "small", - Provider: "haproxy", - AdminStateUp: true, - ProvisioningStatus: "ACTIVE", - OperatingStatus: "ONLINE", - } - LoadbalancerDb = LoadBalancer{ - ID: "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - TenantID: "54030507-44f7-473c-9342-b4d14a95f692", - Name: "db_lb", - Description: "lb config for the db tier", - VipSubnetID: "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - VipAddress: "10.30.176.48", - Flavor: "medium", - Provider: "haproxy", - AdminStateUp: true, - ProvisioningStatus: "PENDING_CREATE", - OperatingStatus: "OFFLINE", - } - LoadbalancerUpdated = LoadBalancer{ - ID: "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - TenantID: "54030507-44f7-473c-9342-b4d14a95f692", - Name: "NewLoadbalancerName", - Description: "lb config for the db tier", - VipSubnetID: "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - VipAddress: "10.30.176.48", - Flavor: "medium", - Provider: "haproxy", - AdminStateUp: true, - ProvisioningStatus: "PENDING_CREATE", - OperatingStatus: "OFFLINE", - } - LoadbalancerStatusesTree = LoadBalancer{ - ID: "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - Name: "db_lb", - ProvisioningStatus: "PENDING_UPDATE", - OperatingStatus: "ACTIVE", - Listeners: []listeners.Listener{{ - ID: "db902c0c-d5ff-4753-b465-668ad9656918", - Name: "db", - Pools: []pools.Pool{{ - ID: "fad389a3-9a4a-4762-a365-8c7038508b5d", - Name: "db", - Monitor: monitors.Monitor{ - ID: "67306cda-815d-4354-9fe4-59e09da9c3c5", - Type: "PING", - }, - Members: []pools.Member{{ - ID: "2a280670-c202-4b0b-a562-34077415aabf", - Name: "db", - Address: "10.0.2.11", - ProtocolPort: 80, - }}, - }}, - }}, - } -) - -// HandleLoadbalancerListSuccessfully sets up the test server to respond to a loadbalancer List request. -func HandleLoadbalancerListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/loadbalancers", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, LoadbalancersListBody) - case "45e08a3e-a78f-4b40-a229-1e7e23eee1ab": - fmt.Fprintf(w, `{ "loadbalancers": [] }`) - default: - t.Fatalf("/v2.0/lbaas/loadbalancers invoked with unexpected marker=[%s]", marker) - } - }) -} - -// HandleLoadbalancerCreationSuccessfully sets up the test server to respond to a loadbalancer creation request -// with a given response. -func HandleLoadbalancerCreationSuccessfully(t *testing.T, response string) { - th.Mux.HandleFunc("/v2.0/lbaas/loadbalancers", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "loadbalancer": { - "name": "db_lb", - "vip_subnet_id": "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - "vip_address": "10.30.176.48", - "flavor": "medium", - "provider": "haproxy", - "admin_state_up": true - } - }`) - - w.WriteHeader(http.StatusAccepted) - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, response) - }) -} - -// HandleLoadbalancerGetSuccessfully sets up the test server to respond to a loadbalancer Get request. -func HandleLoadbalancerGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/loadbalancers/36e08a3e-a78f-4b40-a229-1e7e23eee1ab", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, SingleLoadbalancerBody) - }) -} - -// HandleLoadbalancerGetStatusesTree sets up the test server to respond to a loadbalancer Get statuses tree request. -func HandleLoadbalancerGetStatusesTree(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/loadbalancers/36e08a3e-a78f-4b40-a229-1e7e23eee1ab/statuses", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, LoadbalancerStatuesesTree) - }) -} - -// HandleLoadbalancerDeletionSuccessfully sets up the test server to respond to a loadbalancer deletion request. -func HandleLoadbalancerDeletionSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/loadbalancers/36e08a3e-a78f-4b40-a229-1e7e23eee1ab", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleLoadbalancerUpdateSuccessfully sets up the test server to respond to a loadbalancer Update request. -func HandleLoadbalancerUpdateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/loadbalancers/36e08a3e-a78f-4b40-a229-1e7e23eee1ab", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestJSONRequest(t, r, `{ - "loadbalancer": { - "name": "NewLoadbalancerName" - } - }`) - - fmt.Fprintf(w, PostUpdateLoadbalancerBody) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/requests.go deleted file mode 100644 index 6607b8a6b..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/requests.go +++ /dev/null @@ -1,248 +0,0 @@ -package loadbalancers - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -type loadbalancerOpts struct { - // Optional. Human-readable name for the Loadbalancer. Does not have to be unique. - Name string - - // Optional. Human-readable description for the Loadbalancer. - Description string - - // Required. The network on which to allocate the Loadbalancer's address. A tenant can - // only create Loadbalancers on networks authorized by policy (e.g. networks that - // belong to them or networks that are shared). - VipSubnetID string - - // Required for admins. The UUID of the tenant who owns the Loadbalancer. - // Only administrative users can specify a tenant UUID other than their own. - TenantID string - - // Optional. The IP address of the Loadbalancer. - VipAddress string - - // Optional. The administrative state of the Loadbalancer. A valid value is true (UP) - // or false (DOWN). - AdminStateUp *bool - - // Optional. The UUID of a flavor. - Flavor string - - // Optional. The name of the provider. - Provider string -} - -// Convenience vars for AdminStateUp values. -var ( - iTrue = true - iFalse = false - - Up AdminState = &iTrue - Down AdminState = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToLoadbalancerListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the Loadbalancer attributes you want to see returned. SortKey allows you to -// sort by a particular attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - Description string `q:"description"` - AdminStateUp *bool `q:"admin_state_up"` - TenantID string `q:"tenant_id"` - ProvisioningStatus string `q:"provisioning_status"` - VipAddress string `q:"vip_address"` - VipSubnetID string `q:"vip_subnet_id"` - ID string `q:"id"` - OperatingStatus string `q:"operating_status"` - Name string `q:"name"` - Flavor string `q:"flavor"` - Provider string `q:"provider"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToLoadbalancerListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToLoadbalancerListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// routers. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those routers that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := rootURL(c) - if opts != nil { - query, err := opts.ToLoadbalancerListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return LoadbalancerPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -var ( - errVipSubnetIDRequried = fmt.Errorf("VipSubnetID is required") -) - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToLoadbalancerCreateMap() (map[string]interface{}, error) -} - -// CreateOpts is the common options struct used in this package's Create -// operation. -type CreateOpts loadbalancerOpts - -// ToLoadbalancerCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToLoadbalancerCreateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - - if opts.VipSubnetID != "" { - l["vip_subnet_id"] = opts.VipSubnetID - } else { - return nil, errVipSubnetIDRequried - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.TenantID != "" { - l["tenant_id"] = opts.TenantID - } - if opts.Description != "" { - l["description"] = opts.Description - } - if opts.VipAddress != "" { - l["vip_address"] = opts.VipAddress - } - if opts.Flavor != "" { - l["flavor"] = opts.Flavor - } - if opts.Provider != "" { - l["provider"] = opts.Provider - } - - return map[string]interface{}{"loadbalancer": l}, nil -} - -// Create is an operation which provisions a new loadbalancer based on the -// configuration defined in the CreateOpts struct. Once the request is -// validated and progress has started on the provisioning process, a -// CreateResult will be returned. -// -// Users with an admin role can create loadbalancers on behalf of other tenants by -// specifying a TenantID attribute different than their own. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - reqBody, err := opts.ToLoadbalancerCreateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular Loadbalancer based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToLoadbalancerUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts is the common options struct used in this package's Update -// operation. -type UpdateOpts loadbalancerOpts - -// ToLoadbalancerUpdateMap casts a UpdateOpts struct to a map. -func (opts UpdateOpts) ToLoadbalancerUpdateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.Description != "" { - l["description"] = opts.Description - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - - return map[string]interface{}{"loadbalancer": l}, nil -} - -// Update is an operation which modifies the attributes of the specified Loadbalancer. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToLoadbalancerUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - - return res -} - -// Delete will permanently delete a particular Loadbalancer based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} - -func GetStatuses(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(statusRootURL(c, id), &res.Body, nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/results.go deleted file mode 100644 index 911c15639..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/results.go +++ /dev/null @@ -1,146 +0,0 @@ -package loadbalancers - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners" - "github.com/rackspace/gophercloud/pagination" -) - -// LoadBalancer is the primary load balancing configuration object that specifies -// the virtual IP address on which client traffic is received, as well -// as other details such as the load balancing method to be use, protocol, etc. -type LoadBalancer struct { - // Human-readable description for the Loadbalancer. - Description string `mapstructure:"description" json:"description"` - - // The administrative state of the Loadbalancer. A valid value is true (UP) or false (DOWN). - AdminStateUp bool `mapstructure:"admin_state_up" json:"admin_state_up"` - - // Owner of the LoadBalancer. Only an admin user can specify a tenant ID other than its own. - TenantID string `mapstructure:"tenant_id" json:"tenant_id"` - - // The provisioning status of the LoadBalancer. This value is ACTIVE, PENDING_CREATE or ERROR. - ProvisioningStatus string `mapstructure:"provisioning_status" json:"provisioning_status"` - - // The IP address of the Loadbalancer. - VipAddress string `mapstructure:"vip_address" json:"vip_address"` - - // The UUID of the subnet on which to allocate the virtual IP for the Loadbalancer address. - VipSubnetID string `mapstructure:"vip_subnet_id" json:"vip_subnet_id"` - - // The unique ID for the LoadBalancer. - ID string `mapstructure:"id" json:"id"` - - // The operating status of the LoadBalancer. This value is ONLINE or OFFLINE. - OperatingStatus string `mapstructure:"operating_status" json:"operating_status"` - - // Human-readable name for the LoadBalancer. Does not have to be unique. - Name string `mapstructure:"name" json:"name"` - - // The UUID of a flavor if set. - Flavor string `mapstructure:"flavor" json:"flavor"` - - // The name of the provider. - Provider string `mapstructure:"provider" json:"provider"` - - Listeners []listeners.Listener `mapstructure:"listeners" json:"listeners"` -} - -type StatusTree struct { - Loadbalancer *LoadBalancer `mapstructure:"loadbalancer" json:"loadbalancer"` -} - -// LoadbalancerPage is the page returned by a pager when traversing over a -// collection of routers. -type LoadbalancerPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of routers has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p LoadbalancerPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"loadbalancers_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a RouterPage struct is empty. -func (p LoadbalancerPage) IsEmpty() (bool, error) { - is, err := ExtractLoadbalancers(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractLoadbalancers accepts a Page struct, specifically a LoadbalancerPage struct, -// and extracts the elements into a slice of LoadBalancer structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractLoadbalancers(page pagination.Page) ([]LoadBalancer, error) { - var resp struct { - LoadBalancers []LoadBalancer `mapstructure:"loadbalancers" json:"loadbalancers"` - } - err := mapstructure.Decode(page.(LoadbalancerPage).Body, &resp) - - return resp.LoadBalancers, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a router. -func (r commonResult) Extract() (*LoadBalancer, error) { - if r.Err != nil { - return nil, r.Err - } - var res struct { - LoadBalancer *LoadBalancer `mapstructure:"loadbalancer" json:"loadbalancer"` - } - err := mapstructure.Decode(r.Body, &res) - - return res.LoadBalancer, err -} - -// Extract is a function that accepts a result and extracts a Loadbalancer. -func (r commonResult) ExtractStatuses() (*StatusTree, error) { - if r.Err != nil { - return nil, r.Err - } - var res struct { - LoadBalancer *StatusTree `mapstructure:"statuses" json:"statuses"` - } - err := mapstructure.Decode(r.Body, &res) - - return res.LoadBalancer, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/urls.go deleted file mode 100644 index a30749058..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/loadbalancers/urls.go +++ /dev/null @@ -1,21 +0,0 @@ -package loadbalancers - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lbaas" - resourcePath = "loadbalancers" - statusPath = "statuses" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} - -func statusRootURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id, statusPath) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/fixtures.go deleted file mode 100644 index ad0b4883a..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/fixtures.go +++ /dev/null @@ -1,216 +0,0 @@ -// +build fixtures - -package monitors - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// HealthmonitorsListBody contains the canned body of a healthmonitor list response. -const HealthmonitorsListBody = ` -{ - "healthmonitors":[ - { - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "delay":10, - "name":"web", - "max_retries":1, - "timeout":1, - "type":"PING", - "pools": [{"id": "84f1b61f-58c4-45bf-a8a9-2dafb9e5214d"}], - "id":"466c8345-28d8-4f84-a246-e04380b0461d" - }, - { - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "delay":5, - "name":"db", - "expected_codes":"200", - "max_retries":2, - "http_method":"GET", - "timeout":2, - "url_path":"/", - "type":"HTTP", - "pools": [{"id": "d459f7d8-c6ee-439d-8713-d3fc08aeed8d"}], - "id":"5d4b5228-33b0-4e60-b225-9b727c1a20e7" - } - ] -} -` - -// SingleHealthmonitorBody is the canned body of a Get request on an existing healthmonitor. -const SingleHealthmonitorBody = ` -{ - "healthmonitor": { - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "delay":5, - "name":"db", - "expected_codes":"200", - "max_retries":2, - "http_method":"GET", - "timeout":2, - "url_path":"/", - "type":"HTTP", - "pools": [{"id": "d459f7d8-c6ee-439d-8713-d3fc08aeed8d"}], - "id":"5d4b5228-33b0-4e60-b225-9b727c1a20e7" - } -} -` - -// PostUpdateHealthmonitorBody is the canned response body of a Update request on an existing healthmonitor. -const PostUpdateHealthmonitorBody = ` -{ - "healthmonitor": { - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "delay":3, - "name":"NewHealthmonitorName", - "expected_codes":"301", - "max_retries":10, - "http_method":"GET", - "timeout":20, - "url_path":"/another_check", - "type":"HTTP", - "pools": [{"id": "d459f7d8-c6ee-439d-8713-d3fc08aeed8d"}], - "id":"5d4b5228-33b0-4e60-b225-9b727c1a20e7" - } -} -` - -var ( - HealthmonitorWeb = Monitor{ - AdminStateUp: true, - Name: "web", - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - Delay: 10, - MaxRetries: 1, - Timeout: 1, - Type: "PING", - ID: "466c8345-28d8-4f84-a246-e04380b0461d", - Pools: []PoolID{{ID: "84f1b61f-58c4-45bf-a8a9-2dafb9e5214d"}}, - } - HealthmonitorDb = Monitor{ - AdminStateUp: true, - Name: "db", - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - Delay: 5, - ExpectedCodes: "200", - MaxRetries: 2, - Timeout: 2, - URLPath: "/", - Type: "HTTP", - HTTPMethod: "GET", - ID: "5d4b5228-33b0-4e60-b225-9b727c1a20e7", - Pools: []PoolID{{ID: "d459f7d8-c6ee-439d-8713-d3fc08aeed8d"}}, - } - HealthmonitorUpdated = Monitor{ - AdminStateUp: true, - Name: "NewHealthmonitorName", - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - Delay: 3, - ExpectedCodes: "301", - MaxRetries: 10, - Timeout: 20, - URLPath: "/another_check", - Type: "HTTP", - HTTPMethod: "GET", - ID: "5d4b5228-33b0-4e60-b225-9b727c1a20e7", - Pools: []PoolID{{ID: "d459f7d8-c6ee-439d-8713-d3fc08aeed8d"}}, - } -) - -// HandleHealthmonitorListSuccessfully sets up the test server to respond to a healthmonitor List request. -func HandleHealthmonitorListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/healthmonitors", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, HealthmonitorsListBody) - case "556c8345-28d8-4f84-a246-e04380b0461d": - fmt.Fprintf(w, `{ "healthmonitors": [] }`) - default: - t.Fatalf("/v2.0/lbaas/healthmonitors invoked with unexpected marker=[%s]", marker) - } - }) -} - -// HandleHealthmonitorCreationSuccessfully sets up the test server to respond to a healthmonitor creation request -// with a given response. -func HandleHealthmonitorCreationSuccessfully(t *testing.T, response string) { - th.Mux.HandleFunc("/v2.0/lbaas/healthmonitors", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "healthmonitor": { - "type":"HTTP", - "pool_id":"84f1b61f-58c4-45bf-a8a9-2dafb9e5214d", - "tenant_id":"453105b9-1754-413f-aab1-55f1af620750", - "delay":20, - "name":"db", - "timeout":10, - "max_retries":5, - "url_path":"/check", - "expected_codes":"200-299" - } - }`) - - w.WriteHeader(http.StatusAccepted) - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, response) - }) -} - -// HandleHealthmonitorGetSuccessfully sets up the test server to respond to a healthmonitor Get request. -func HandleHealthmonitorGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/healthmonitors/5d4b5228-33b0-4e60-b225-9b727c1a20e7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, SingleHealthmonitorBody) - }) -} - -// HandleHealthmonitorDeletionSuccessfully sets up the test server to respond to a healthmonitor deletion request. -func HandleHealthmonitorDeletionSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/healthmonitors/5d4b5228-33b0-4e60-b225-9b727c1a20e7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleHealthmonitorUpdateSuccessfully sets up the test server to respond to a healthmonitor Update request. -func HandleHealthmonitorUpdateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/healthmonitors/5d4b5228-33b0-4e60-b225-9b727c1a20e7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestJSONRequest(t, r, `{ - "healthmonitor": { - "name": "NewHealthmonitorName", - "delay": 3, - "timeout": 20, - "max_retries": 10, - "url_path": "/another_check", - "expected_codes": "301" - } - }`) - - fmt.Fprintf(w, PostUpdateHealthmonitorBody) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/requests.go deleted file mode 100644 index 92e7e83f3..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/requests.go +++ /dev/null @@ -1,304 +0,0 @@ -package monitors - -import ( - "fmt" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type monitorOpts struct { - // Required. The Pool to Monitor. - PoolID string - - // Optional. The Name of the Monitor. - Name string - - // Required for admins. Indicates the owner of the Loadbalancer. - TenantID string - - // Required. The type of probe, which is PING, TCP, HTTP, or HTTPS, that is - // sent by the load balancer to verify the member state. - Type string - - // Required. The time, in seconds, between sending probes to members. - Delay int - - // Required. Maximum number of seconds for a Monitor to wait for a ping reply - // before it times out. The value must be less than the delay value. - Timeout int - - // Required. Number of permissible ping failures before changing the member's - // status to INACTIVE. Must be a number between 1 and 10. - MaxRetries int - - // Required for HTTP(S) types. URI path that will be accessed if Monitor type - // is HTTP or HTTPS. - URLPath string - - // Required for HTTP(S) types. The HTTP method used for requests by the - // Monitor. If this attribute is not specified, it defaults to "GET". - HTTPMethod string - - // Required for HTTP(S) types. Expected HTTP codes for a passing HTTP(S) - // Monitor. You can either specify a single status like "200", or a range - // like "200-202". - ExpectedCodes string - - AdminStateUp *bool -} - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToMonitorListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the Monitor attributes you want to see returned. SortKey allows you to -// sort by a particular Monitor attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - ID string `q:"id"` - Name string `q:"name"` - TenantID string `q:"tenant_id"` - PoolID string `q:"pool_id"` - Type string `q:"type"` - Delay int `q:"delay"` - Timeout int `q:"timeout"` - MaxRetries int `q:"max_retries"` - HTTPMethod string `q:"http_method"` - URLPath string `q:"url_path"` - ExpectedCodes string `q:"expected_codes"` - AdminStateUp *bool `q:"admin_state_up"` - Status string `q:"status"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToMonitorListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToMonitorListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// health monitors. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those health monitors that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := rootURL(c) - if opts != nil { - query, err := opts.ToMonitorListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return MonitorPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Constants that represent approved monitoring types. -const ( - TypePING = "PING" - TypeTCP = "TCP" - TypeHTTP = "HTTP" - TypeHTTPS = "HTTPS" -) - -var ( - errPoolIDRequired = fmt.Errorf("PoolID to monitor is required") - errValidTypeRequired = fmt.Errorf("A valid Type is required. Supported values are PING, TCP, HTTP and HTTPS") - errDelayRequired = fmt.Errorf("Delay is required") - errTimeoutRequired = fmt.Errorf("Timeout is required") - errMaxRetriesRequired = fmt.Errorf("MaxRetries is required") - errURLPathRequired = fmt.Errorf("URL path is required") - errExpectedCodesRequired = fmt.Errorf("ExpectedCodes is required") - errDelayMustGETimeout = fmt.Errorf("Delay must be greater than or equal to timeout") -) - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToMonitorCreateMap() (map[string]interface{}, error) -} - -// CreateOpts is the common options struct used in this package's Create -// operation. -type CreateOpts monitorOpts - -// ToMonitorCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToMonitorCreateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - allowed := map[string]bool{TypeHTTP: true, TypeHTTPS: true, TypeTCP: true, TypePING: true} - - if allowed[opts.Type] { - l["type"] = opts.Type - } else { - return nil, errValidTypeRequired - } - if opts.Type == TypeHTTP || opts.Type == TypeHTTPS { - if opts.URLPath != "" { - l["url_path"] = opts.URLPath - } else { - return nil, errURLPathRequired - } - if opts.ExpectedCodes != "" { - l["expected_codes"] = opts.ExpectedCodes - } else { - return nil, errExpectedCodesRequired - } - } - if opts.PoolID != "" { - l["pool_id"] = opts.PoolID - } else { - return nil, errPoolIDRequired - } - if opts.Delay != 0 { - l["delay"] = opts.Delay - } else { - return nil, errDelayRequired - } - if opts.Timeout != 0 { - l["timeout"] = opts.Timeout - } else { - return nil, errMaxRetriesRequired - } - if opts.MaxRetries != 0 { - l["max_retries"] = opts.MaxRetries - } else { - return nil, errMaxRetriesRequired - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.TenantID != "" { - l["tenant_id"] = opts.TenantID - } - if opts.HTTPMethod != "" { - l["http_method"] = opts.HTTPMethod - } - - return map[string]interface{}{"healthmonitor": l}, nil -} - -/* - Create is an operation which provisions a new Health Monitor. There are - different types of Monitor you can provision: PING, TCP or HTTP(S). Below - are examples of how to create each one. - - Here is an example config struct to use when creating a PING or TCP Monitor: - - CreateOpts{Type: TypePING, Delay: 20, Timeout: 10, MaxRetries: 3} - CreateOpts{Type: TypeTCP, Delay: 20, Timeout: 10, MaxRetries: 3} - - Here is an example config struct to use when creating a HTTP(S) Monitor: - - CreateOpts{Type: TypeHTTP, Delay: 20, Timeout: 10, MaxRetries: 3, - HttpMethod: "HEAD", ExpectedCodes: "200", PoolID: "2c946bfc-1804-43ab-a2ff-58f6a762b505"} -*/ - -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToMonitorCreateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular Health Monitor based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToMonitorUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts is the common options struct used in this package's Update -// operation. -type UpdateOpts monitorOpts - -// ToMonitorUpdateMap casts a UpdateOpts struct to a map. -func (opts UpdateOpts) ToMonitorUpdateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - - if opts.URLPath != "" { - l["url_path"] = opts.URLPath - } - if opts.ExpectedCodes != "" { - l["expected_codes"] = opts.ExpectedCodes - } - if opts.Delay != 0 { - l["delay"] = opts.Delay - } - if opts.Timeout != 0 { - l["timeout"] = opts.Timeout - } - if opts.MaxRetries != 0 { - l["max_retries"] = opts.MaxRetries - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.HTTPMethod != "" { - l["http_method"] = opts.HTTPMethod - } - - return map[string]interface{}{"healthmonitor": l}, nil -} - -// Update is an operation which modifies the attributes of the specified Monitor. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToMonitorUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - - return res -} - -// Delete will permanently delete a particular Monitor based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/results.go deleted file mode 100644 index da363c02b..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/results.go +++ /dev/null @@ -1,160 +0,0 @@ -package monitors - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type PoolID struct { - ID string `mapstructure:"id" json:"id"` -} - -// Monitor represents a load balancer health monitor. A health monitor is used -// to determine whether or not back-end members of the VIP's pool are usable -// for processing a request. A pool can have several health monitors associated -// with it. There are different types of health monitors supported: -// -// PING: used to ping the members using ICMP. -// TCP: used to connect to the members using TCP. -// HTTP: used to send an HTTP request to the member. -// HTTPS: used to send a secure HTTP request to the member. -// -// When a pool has several monitors associated with it, each member of the pool -// is monitored by all these monitors. If any monitor declares the member as -// unhealthy, then the member status is changed to INACTIVE and the member -// won't participate in its pool's load balancing. In other words, ALL monitors -// must declare the member to be healthy for it to stay ACTIVE. -type Monitor struct { - // The unique ID for the Monitor. - ID string - - // The Name of the Monitor. - Name string - - // Only an administrative user can specify a tenant ID - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - // The type of probe sent by the load balancer to verify the member state, - // which is PING, TCP, HTTP, or HTTPS. - Type string - - // The time, in seconds, between sending probes to members. - Delay int - - // The maximum number of seconds for a monitor to wait for a connection to be - // established before it times out. This value must be less than the delay value. - Timeout int - - // Number of allowed connection failures before changing the status of the - // member to INACTIVE. A valid value is from 1 to 10. - MaxRetries int `json:"max_retries" mapstructure:"max_retries"` - - // The HTTP method that the monitor uses for requests. - HTTPMethod string `json:"http_method" mapstructure:"http_method"` - - // The HTTP path of the request sent by the monitor to test the health of a - // member. Must be a string beginning with a forward slash (/). - URLPath string `json:"url_path" mapstructure:"url_path"` - - // Expected HTTP codes for a passing HTTP(S) monitor. - ExpectedCodes string `json:"expected_codes" mapstructure:"expected_codes"` - - // The administrative state of the health monitor, which is up (true) or down (false). - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - - // The status of the health monitor. Indicates whether the health monitor is - // operational. - Status string - - // List of pools that are associated with the health monitor. - Pools []PoolID `mapstructure:"pools" json:"pools"` -} - -type Pool struct { -} - -// MonitorPage is the page returned by a pager when traversing over a -// collection of health monitors. -type MonitorPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of monitors has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p MonitorPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"healthmonitors_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a PoolPage struct is empty. -func (p MonitorPage) IsEmpty() (bool, error) { - is, err := ExtractMonitors(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractMonitors accepts a Page struct, specifically a MonitorPage struct, -// and extracts the elements into a slice of Monitor structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractMonitors(page pagination.Page) ([]Monitor, error) { - var resp struct { - Monitors []Monitor `mapstructure:"healthmonitors" json:"healthmonitors"` - } - - err := mapstructure.Decode(page.(MonitorPage).Body, &resp) - - return resp.Monitors, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a monitor. -func (r commonResult) Extract() (*Monitor, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Monitor *Monitor `json:"healthmonitor" mapstructure:"healthmonitor"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Monitor, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/urls.go deleted file mode 100644 index a3abba428..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors/urls.go +++ /dev/null @@ -1,16 +0,0 @@ -package monitors - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lbaas" - resourcePath = "healthmonitors" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/fixtures.go deleted file mode 100644 index 8e6edc5ff..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/fixtures.go +++ /dev/null @@ -1,389 +0,0 @@ -// +build fixtures - -package pools - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// PoolsListBody contains the canned body of a pool list response. -const PoolsListBody = ` -{ - "pools":[ - { - "lb_algorithm":"ROUND_ROBIN", - "protocol":"HTTP", - "description":"", - "healthmonitor_id": "466c8345-28d8-4f84-a246-e04380b0461d", - "members":[{"id": "53306cda-815d-4354-9fe4-59e09da9c3c5"}], - "listeners":[{"id": "2a280670-c202-4b0b-a562-34077415aabf"}], - "loadbalancers":[{"id": "79e05663-7f03-45d2-a092-8b94062f22ab"}], - "id":"72741b06-df4d-4715-b142-276b6bce75ab", - "name":"web", - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "provider": "haproxy" - }, - { - "lb_algorithm":"LEAST_CONNECTION", - "protocol":"HTTP", - "description":"", - "healthmonitor_id": "5f6c8345-28d8-4f84-a246-e04380b0461d", - "members":[{"id": "67306cda-815d-4354-9fe4-59e09da9c3c5"}], - "listeners":[{"id": "2a280670-c202-4b0b-a562-34077415aabf"}], - "loadbalancers":[{"id": "79e05663-7f03-45d2-a092-8b94062f22ab"}], - "id":"c3741b06-df4d-4715-b142-276b6bce75ab", - "name":"db", - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "provider": "haproxy" - } - ] -} -` - -// SinglePoolBody is the canned body of a Get request on an existing pool. -const SinglePoolBody = ` -{ - "pool": { - "lb_algorithm":"LEAST_CONNECTION", - "protocol":"HTTP", - "description":"", - "healthmonitor_id": "5f6c8345-28d8-4f84-a246-e04380b0461d", - "members":[{"id": "67306cda-815d-4354-9fe4-59e09da9c3c5"}], - "listeners":[{"id": "2a280670-c202-4b0b-a562-34077415aabf"}], - "loadbalancers":[{"id": "79e05663-7f03-45d2-a092-8b94062f22ab"}], - "id":"c3741b06-df4d-4715-b142-276b6bce75ab", - "name":"db", - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "provider": "haproxy" - } -} -` - -// PostUpdatePoolBody is the canned response body of a Update request on an existing pool. -const PostUpdatePoolBody = ` -{ - "pool": { - "lb_algorithm":"LEAST_CONNECTION", - "protocol":"HTTP", - "description":"", - "healthmonitor_id": "5f6c8345-28d8-4f84-a246-e04380b0461d", - "members":[{"id": "67306cda-815d-4354-9fe4-59e09da9c3c5"}], - "listeners":[{"id": "2a280670-c202-4b0b-a562-34077415aabf"}], - "loadbalancers":[{"id": "79e05663-7f03-45d2-a092-8b94062f22ab"}], - "id":"c3741b06-df4d-4715-b142-276b6bce75ab", - "name":"db", - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "provider": "haproxy" - } -} -` - -var ( - PoolWeb = Pool{ - LBMethod: "ROUND_ROBIN", - Protocol: "HTTP", - Description: "", - MonitorID: "466c8345-28d8-4f84-a246-e04380b0461d", - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - AdminStateUp: true, - Name: "web", - Members: []Member{{ID: "53306cda-815d-4354-9fe4-59e09da9c3c5"}}, - ID: "72741b06-df4d-4715-b142-276b6bce75ab", - Loadbalancers: []LoadBalancerID{{ID: "79e05663-7f03-45d2-a092-8b94062f22ab"}}, - Listeners: []ListenerID{{ID: "2a280670-c202-4b0b-a562-34077415aabf"}}, - Provider: "haproxy", - } - PoolDb = Pool{ - LBMethod: "LEAST_CONNECTION", - Protocol: "HTTP", - Description: "", - MonitorID: "5f6c8345-28d8-4f84-a246-e04380b0461d", - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - AdminStateUp: true, - Name: "db", - Members: []Member{{ID: "67306cda-815d-4354-9fe4-59e09da9c3c5"}}, - ID: "c3741b06-df4d-4715-b142-276b6bce75ab", - Loadbalancers: []LoadBalancerID{{ID: "79e05663-7f03-45d2-a092-8b94062f22ab"}}, - Listeners: []ListenerID{{ID: "2a280670-c202-4b0b-a562-34077415aabf"}}, - Provider: "haproxy", - } - PoolUpdated = Pool{ - LBMethod: "LEAST_CONNECTION", - Protocol: "HTTP", - Description: "", - MonitorID: "5f6c8345-28d8-4f84-a246-e04380b0461d", - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - AdminStateUp: true, - Name: "db", - Members: []Member{{ID: "67306cda-815d-4354-9fe4-59e09da9c3c5"}}, - ID: "c3741b06-df4d-4715-b142-276b6bce75ab", - Loadbalancers: []LoadBalancerID{{ID: "79e05663-7f03-45d2-a092-8b94062f22ab"}}, - Listeners: []ListenerID{{ID: "2a280670-c202-4b0b-a562-34077415aabf"}}, - Provider: "haproxy", - } -) - -// HandlePoolListSuccessfully sets up the test server to respond to a pool List request. -func HandlePoolListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, PoolsListBody) - case "45e08a3e-a78f-4b40-a229-1e7e23eee1ab": - fmt.Fprintf(w, `{ "pools": [] }`) - default: - t.Fatalf("/v2.0/lbaas/pools invoked with unexpected marker=[%s]", marker) - } - }) -} - -// HandlePoolCreationSuccessfully sets up the test server to respond to a pool creation request -// with a given response. -func HandlePoolCreationSuccessfully(t *testing.T, response string) { - th.Mux.HandleFunc("/v2.0/lbaas/pools", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "pool": { - "lb_algorithm": "ROUND_ROBIN", - "protocol": "HTTP", - "name": "Example pool", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f", - "loadbalancer_id": "79e05663-7f03-45d2-a092-8b94062f22ab" - } - }`) - - w.WriteHeader(http.StatusAccepted) - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, response) - }) -} - -// HandlePoolGetSuccessfully sets up the test server to respond to a pool Get request. -func HandlePoolGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/c3741b06-df4d-4715-b142-276b6bce75ab", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, SinglePoolBody) - }) -} - -// HandlePoolDeletionSuccessfully sets up the test server to respond to a pool deletion request. -func HandlePoolDeletionSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/c3741b06-df4d-4715-b142-276b6bce75ab", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandlePoolUpdateSuccessfully sets up the test server to respond to a pool Update request. -func HandlePoolUpdateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/c3741b06-df4d-4715-b142-276b6bce75ab", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestJSONRequest(t, r, `{ - "pool": { - "name": "NewPoolName", - "lb_algorithm": "LEAST_CONNECTIONS" - } - }`) - - fmt.Fprintf(w, PostUpdatePoolBody) - }) -} - -// MembersListBody contains the canned body of a member list response. -const MembersListBody = ` -{ - "members":[ - { - "id": "2a280670-c202-4b0b-a562-34077415aabf", - "address": "10.0.2.10", - "weight": 5, - "name": "web", - "subnet_id": "1981f108-3c48-48d2-b908-30f7d28532c9", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f", - "admin_state_up":true, - "protocol_port": 80 - }, - { - "id": "fad389a3-9a4a-4762-a365-8c7038508b5d", - "address": "10.0.2.11", - "weight": 10, - "name": "db", - "subnet_id": "1981f108-3c48-48d2-b908-30f7d28532c9", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f", - "admin_state_up":false, - "protocol_port": 80 - } - ] -} -` - -// SingleMemberBody is the canned body of a Get request on an existing member. -const SingleMemberBody = ` -{ - "member": { - "id": "fad389a3-9a4a-4762-a365-8c7038508b5d", - "address": "10.0.2.11", - "weight": 10, - "name": "db", - "subnet_id": "1981f108-3c48-48d2-b908-30f7d28532c9", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f", - "admin_state_up":false, - "protocol_port": 80 - } -} -` - -// PostUpdateMemberBody is the canned response body of a Update request on an existing member. -const PostUpdateMemberBody = ` -{ - "member": { - "id": "fad389a3-9a4a-4762-a365-8c7038508b5d", - "address": "10.0.2.11", - "weight": 10, - "name": "db", - "subnet_id": "1981f108-3c48-48d2-b908-30f7d28532c9", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f", - "admin_state_up":false, - "protocol_port": 80 - } -} -` - -var ( - MemberWeb = Member{ - SubnetID: "1981f108-3c48-48d2-b908-30f7d28532c9", - TenantID: "2ffc6e22aae24e4795f87155d24c896f", - AdminStateUp: true, - Name: "web", - ID: "2a280670-c202-4b0b-a562-34077415aabf", - Address: "10.0.2.10", - Weight: 5, - ProtocolPort: 80, - } - MemberDb = Member{ - SubnetID: "1981f108-3c48-48d2-b908-30f7d28532c9", - TenantID: "2ffc6e22aae24e4795f87155d24c896f", - AdminStateUp: false, - Name: "db", - ID: "fad389a3-9a4a-4762-a365-8c7038508b5d", - Address: "10.0.2.11", - Weight: 10, - ProtocolPort: 80, - } - MemberUpdated = Member{ - SubnetID: "1981f108-3c48-48d2-b908-30f7d28532c9", - TenantID: "2ffc6e22aae24e4795f87155d24c896f", - AdminStateUp: false, - Name: "db", - ID: "fad389a3-9a4a-4762-a365-8c7038508b5d", - Address: "10.0.2.11", - Weight: 10, - ProtocolPort: 80, - } -) - -// HandleMemberListSuccessfully sets up the test server to respond to a member List request. -func HandleMemberListSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/332abe93-f488-41ba-870b-2ac66be7f853/members", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, MembersListBody) - case "45e08a3e-a78f-4b40-a229-1e7e23eee1ab": - fmt.Fprintf(w, `{ "members": [] }`) - default: - t.Fatalf("/v2.0/lbaas/pools/332abe93-f488-41ba-870b-2ac66be7f853/members invoked with unexpected marker=[%s]", marker) - } - }) -} - -// HandleMemberCreationSuccessfully sets up the test server to respond to a member creation request -// with a given response. -func HandleMemberCreationSuccessfully(t *testing.T, response string) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/332abe93-f488-41ba-870b-2ac66be7f853/members", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ - "member": { - "address": "10.0.2.11", - "weight": 10, - "name": "db", - "subnet_id": "1981f108-3c48-48d2-b908-30f7d28532c9", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f", - "protocol_port": 80 - } - }`) - - w.WriteHeader(http.StatusAccepted) - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, response) - }) -} - -// HandleMemberGetSuccessfully sets up the test server to respond to a member Get request. -func HandleMemberGetSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/332abe93-f488-41ba-870b-2ac66be7f853/members/2a280670-c202-4b0b-a562-34077415aabf", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - fmt.Fprintf(w, SingleMemberBody) - }) -} - -// HandleMemberDeletionSuccessfully sets up the test server to respond to a member deletion request. -func HandleMemberDeletionSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/332abe93-f488-41ba-870b-2ac66be7f853/members/2a280670-c202-4b0b-a562-34077415aabf", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleMemberUpdateSuccessfully sets up the test server to respond to a member Update request. -func HandleMemberUpdateSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/v2.0/lbaas/pools/332abe93-f488-41ba-870b-2ac66be7f853/members/2a280670-c202-4b0b-a562-34077415aabf", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestJSONRequest(t, r, `{ - "member": { - "name": "newMemberName", - "weight": 4 - } - }`) - - fmt.Fprintf(w, PostUpdateMemberBody) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/requests.go deleted file mode 100644 index 706ce9616..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/requests.go +++ /dev/null @@ -1,485 +0,0 @@ -package pools - -import ( - "fmt" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -type poolOpts struct { - // Only required if the caller has an admin role and wants to create a pool - // for another tenant. - TenantID string - - // Optional. Name of the pool. - Name string - - // Optional. Human-readable description for the pool. - Description string - - // Required. The protocol used by the pool members, you can use either - // ProtocolTCP, ProtocolHTTP, or ProtocolHTTPS. - Protocol Protocol - - // The Loadbalancer on which the members of the pool will be associated with. - // Note: one of LoadbalancerID or ListenerID must be provided. - LoadbalancerID string - - // The Listener on which the members of the pool will be associated with. - // Note: one of LoadbalancerID or ListenerID must be provided. - ListenerID string - - // Required. The algorithm used to distribute load between the members of the pool. The - // current specification supports LBMethodRoundRobin, LBMethodLeastConnections - // and LBMethodSourceIp as valid values for this attribute. - LBMethod LBMethod - - // Optional. Omit this field to prevent session persistence. - Persistence *SessionPersistence - - // Optional. The administrative state of the Pool. A valid value is true (UP) - // or false (DOWN). - AdminStateUp *bool -} - -// Convenience vars for AdminStateUp values. -var ( - iTrue = true - iFalse = false - - Up AdminState = &iTrue - Down AdminState = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToPoolListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the Pool attributes you want to see returned. SortKey allows you to -// sort by a particular Pool attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - LBMethod string `q:"lb_algorithm"` - Protocol string `q:"protocol"` - TenantID string `q:"tenant_id"` - AdminStateUp *bool `q:"admin_state_up"` - Name string `q:"name"` - ID string `q:"id"` - LoadbalancerID string `q:"loadbalancer_id"` - ListenerID string `q:"listener_id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToPoolListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToPoolListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// pools. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those pools that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := rootURL(c) - if opts != nil { - query, err := opts.ToPoolListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return PoolPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -type LBMethod string -type Protocol string - -// Supported attributes for create/update operations. -const ( - LBMethodRoundRobin LBMethod = "ROUND_ROBIN" - LBMethodLeastConnections LBMethod = "LEAST_CONNECTIONS" - LBMethodSourceIp LBMethod = "SOURCE_IP" - - ProtocolTCP Protocol = "TCP" - ProtocolHTTP Protocol = "HTTP" - ProtocolHTTPS Protocol = "HTTPS" -) - -var ( - errLoadbalancerOrListenerRequired = fmt.Errorf("A ListenerID or LoadbalancerID is required") - errValidLBMethodRequired = fmt.Errorf("A valid LBMethod is required. Supported values are ROUND_ROBIN, LEAST_CONNECTIONS, SOURCE_IP") - errValidProtocolRequired = fmt.Errorf("A valid Protocol is required. Supported values are TCP, HTTP, HTTPS") -) - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToPoolCreateMap() (map[string]interface{}, error) -} - -// CreateOpts is the common options struct used in this package's Create -// operation. -type CreateOpts poolOpts - -// ToPoolCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToPoolCreateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - allowedLBMethod := map[LBMethod]bool{LBMethodRoundRobin: true, LBMethodLeastConnections: true, LBMethodSourceIp: true} - allowedProtocol := map[Protocol]bool{ProtocolTCP: true, ProtocolHTTP: true, ProtocolHTTPS: true} - - if allowedLBMethod[opts.LBMethod] { - l["lb_algorithm"] = opts.LBMethod - } else { - return nil, errValidLBMethodRequired - } - if allowedProtocol[opts.Protocol] { - l["protocol"] = opts.Protocol - } else { - return nil, errValidProtocolRequired - } - if opts.LoadbalancerID == "" && opts.ListenerID == "" { - return nil, errLoadbalancerOrListenerRequired - } else { - if opts.LoadbalancerID != "" { - l["loadbalancer_id"] = opts.LoadbalancerID - } - if opts.ListenerID != "" { - l["listener_id"] = opts.ListenerID - } - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.TenantID != "" { - l["tenant_id"] = opts.TenantID - } - if opts.Persistence != nil { - l["session_persistence"] = &opts.Persistence - } - - return map[string]interface{}{"pool": l}, nil -} - -// Create accepts a CreateOpts struct and uses the values to create a new -// load balancer pool. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - reqBody, err := opts.ToPoolCreateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular pool based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToPoolUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts is the common options struct used in this package's Update -// operation. -type UpdateOpts poolOpts - -// ToPoolUpdateMap casts a UpdateOpts struct to a map. -func (opts UpdateOpts) ToPoolUpdateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - allowedLBMethod := map[LBMethod]bool{LBMethodRoundRobin: true, LBMethodLeastConnections: true, LBMethodSourceIp: true} - - if opts.LBMethod != "" { - if allowedLBMethod[opts.LBMethod] { - l["lb_algorithm"] = opts.LBMethod - } else { - return nil, errValidLBMethodRequired - } - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.Description != "" { - l["description"] = opts.Description - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - - return map[string]interface{}{"pool": l}, nil -} - -// Update allows pools to be updated. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToPoolUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return res -} - -// Delete will permanently delete a particular pool based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} - -// CreateOpts contains all the values needed to create a new Member for a Pool. -type memberOpts struct { - // Optional. Name of the Member. - Name string - - // Only required if the caller has an admin role and wants to create a Member - // for another tenant. - TenantID string - - // Required. The IP address of the member to receive traffic from the load balancer. - Address string - - // Required. The port on which to listen for client traffic. - ProtocolPort int - - // Optional. A positive integer value that indicates the relative portion of - // traffic that this member should receive from the pool. For example, a - // member with a weight of 10 receives five times as much traffic as a member - // with a weight of 2. - Weight int - - // Optional. If you omit this parameter, LBaaS uses the vip_subnet_id - // parameter value for the subnet UUID. - SubnetID string - - // Optional. The administrative state of the Pool. A valid value is true (UP) - // or false (DOWN). - AdminStateUp *bool -} - -// MemberListOptsBuilder allows extensions to add additional parameters to the -// Member List request. -type MemberListOptsBuilder interface { - ToMemberListQuery() (string, error) -} - -// MemberListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the Member attributes you want to see returned. SortKey allows you to -// sort by a particular Member attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type MemberListOpts struct { - Name string `q:"name"` - Weight int `q:"weight"` - AdminStateUp *bool `q:"admin_state_up"` - TenantID string `q:"tenant_id"` - Address string `q:"address"` - ProtocolPort int `q:"protocol_port"` - ID string `q:"id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToMemberListQuery formats a ListOpts into a query string. -func (opts MemberListOpts) ToMemberListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// members. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those members that are owned by the -// tenant who submits the request, unless an admin user submits the request. -func ListAssociateMembers(c *gophercloud.ServiceClient, poolID string, opts MemberListOptsBuilder) pagination.Pager { - url := memberRootURL(c, poolID) - if opts != nil { - query, err := opts.ToMemberListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return MemberPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -var ( - errPoolIdRequired = fmt.Errorf("PoolID is required") - errAddressRequired = fmt.Errorf("Address is required") - errProtocolPortRequired = fmt.Errorf("ProtocolPort is required") -) - -// MemberCreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type MemberCreateOptsBuilder interface { - ToMemberCreateMap() (map[string]interface{}, error) -} - -// MemberCreateOpts is the common options struct used in this package's Create -// operation. -type MemberCreateOpts memberOpts - -// ToMemberCreateMap casts a CreateOpts struct to a map. -func (opts MemberCreateOpts) ToMemberCreateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - - if opts.Address != "" { - l["address"] = opts.Address - } else { - return nil, errAddressRequired - } - if opts.ProtocolPort != 0 { - l["protocol_port"] = opts.ProtocolPort - } else { - return nil, errProtocolPortRequired - } - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.TenantID != "" { - l["tenant_id"] = opts.TenantID - } - if opts.SubnetID != "" { - l["subnet_id"] = opts.SubnetID - } - if opts.Weight != 0 { - l["weight"] = opts.Weight - } - - return map[string]interface{}{"member": l}, nil -} - -// CreateAssociateMember will create and associate a Member with a particular Pool. -func CreateAssociateMember(c *gophercloud.ServiceClient, poolID string, opts MemberCreateOpts) AssociateResult { - var res AssociateResult - - if poolID == "" { - res.Err = errPoolIdRequired - return res - } - - reqBody, err := opts.ToMemberCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(memberRootURL(c, poolID), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular Pool Member based on its unique ID. -func GetAssociateMember(c *gophercloud.ServiceClient, poolID string, memberID string) GetResult { - var res GetResult - _, res.Err = c.Get(memberResourceURL(c, poolID, memberID), &res.Body, nil) - return res -} - -// MemberUpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type MemberUpdateOptsBuilder interface { - ToMemberUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts is the common options struct used in this package's Update -// operation. -type MemberUpdateOpts memberOpts - -// ToMemberUpdateMap casts a UpdateOpts struct to a map. -func (opts MemberUpdateOpts) ToMemberUpdateMap() (map[string]interface{}, error) { - l := make(map[string]interface{}) - - if opts.AdminStateUp != nil { - l["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - l["name"] = opts.Name - } - if opts.Weight != 0 { - l["weight"] = opts.Weight - } - - return map[string]interface{}{"member": l}, nil -} - -// Update allows Member to be updated. -func UpdateAssociateMember(c *gophercloud.ServiceClient, poolID string, memberID string, opts MemberUpdateOpts) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToMemberUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(memberResourceURL(c, poolID, memberID), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 201, 202}, - }) - return res -} - -// DisassociateMember will remove and disassociate a Member from a particular Pool. -func DeleteMember(c *gophercloud.ServiceClient, poolID string, memberID string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(memberResourceURL(c, poolID, memberID), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/results.go deleted file mode 100644 index 17f677ddf..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/results.go +++ /dev/null @@ -1,274 +0,0 @@ -package pools - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/monitors" - "github.com/rackspace/gophercloud/pagination" -) - -// SessionPersistence represents the session persistence feature of the load -// balancing service. It attempts to force connections or requests in the same -// session to be processed by the same member as long as it is ative. Three -// types of persistence are supported: -// -// SOURCE_IP: With this mode, all connections originating from the same source -// IP address, will be handled by the same Member of the Pool. -// HTTP_COOKIE: With this persistence mode, the load balancing function will -// create a cookie on the first request from a client. Subsequent -// requests containing the same cookie value will be handled by -// the same Member of the Pool. -// APP_COOKIE: With this persistence mode, the load balancing function will -// rely on a cookie established by the backend application. All -// requests carrying the same cookie value will be handled by the -// same Member of the Pool. -type SessionPersistence struct { - // The type of persistence mode - Type string `mapstructure:"type" json:"type"` - - // Name of cookie if persistence mode is set appropriately - CookieName string `mapstructure:"cookie_name" json:"cookie_name,omitempty"` -} - -type LoadBalancerID struct { - ID string `mapstructure:"id" json:"id"` -} - -type ListenerID struct { - ID string `mapstructure:"id" json:"id"` -} - -// Pool represents a logical set of devices, such as web servers, that you -// group together to receive and process traffic. The load balancing function -// chooses a Member of the Pool according to the configured load balancing -// method to handle the new requests or connections received on the VIP address. -type Pool struct { - // The load-balancer algorithm, which is round-robin, least-connections, and - // so on. This value, which must be supported, is dependent on the provider. - // Round-robin must be supported. - LBMethod string `json:"lb_algorithm" mapstructure:"lb_algorithm"` - - // The protocol of the Pool, which is TCP, HTTP, or HTTPS. - Protocol string - - // Description for the Pool. - Description string - - // A list of listeners objects IDs. - Listeners []ListenerID `mapstructure:"listeners" json:"listeners"` //[]map[string]interface{} - - // A list of member objects IDs. - Members []Member `mapstructure:"members" json:"members"` - - // The ID of associated health monitor. - MonitorID string `json:"healthmonitor_id" mapstructure:"healthmonitor_id"` - - // The network on which the members of the Pool will be located. Only members - // that are on this network can be added to the Pool. - SubnetID string `json:"subnet_id" mapstructure:"subnet_id"` - - // Owner of the Pool. Only an administrative user can specify a tenant ID - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - // The administrative state of the Pool, which is up (true) or down (false). - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - - // Pool name. Does not have to be unique. - Name string - - // The unique ID for the Pool. - ID string - - // A list of load balancer objects IDs. - Loadbalancers []LoadBalancerID `mapstructure:"loadbalancers" json:"loadbalancers"` - - // Indicates whether connections in the same session will be processed by the - // same Pool member or not. - Persistence SessionPersistence `mapstructure:"session_persistence" json:"session_persistence"` - - // The provider - Provider string - - Monitor monitors.Monitor `mapstructure:"healthmonitor" json:"healthmonitor"` -} - -// PoolPage is the page returned by a pager when traversing over a -// collection of pools. -type PoolPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of pools has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p PoolPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"pools_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a PoolPage struct is empty. -func (p PoolPage) IsEmpty() (bool, error) { - is, err := ExtractPools(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractPools accepts a Page struct, specifically a RouterPage struct, -// and extracts the elements into a slice of Router structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractPools(page pagination.Page) ([]Pool, error) { - var resp struct { - Pools []Pool `mapstructure:"pools" json:"pools"` - } - - err := mapstructure.Decode(page.(PoolPage).Body, &resp) - - return resp.Pools, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a router. -func (r commonResult) Extract() (*Pool, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Pool *Pool `json:"pool"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Pool, err -} - -// Member represents the application running on a backend server. -type Member struct { - // Name of the Member. - Name string `json:"name" mapstructure:"name"` - - // Weight of Member. - Weight int `json:"weight" mapstructure:"weight"` - - // The administrative state of the member, which is up (true) or down (false). - AdminStateUp bool `json:"admin_state_up" mapstructure:"admin_state_up"` - - // Owner of the Member. Only an administrative user can specify a tenant ID - // other than its own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` - - // parameter value for the subnet UUID. - SubnetID string `json:"subnet_id" mapstructure:"subnet_id"` - - // The Pool to which the Member belongs. - PoolID string `json:"pool_id" mapstructure:"pool_id"` - - // The IP address of the Member. - Address string `json:"address" mapstructure:"address"` - - // The port on which the application is hosted. - ProtocolPort int `json:"protocol_port" mapstructure:"protocol_port"` - - // The unique ID for the Member. - ID string -} - -// MemberPage is the page returned by a pager when traversing over a -// collection of Members in a Pool. -type MemberPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of members has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p MemberPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"members_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a MemberPage struct is empty. -func (p MemberPage) IsEmpty() (bool, error) { - is, err := ExtractMembers(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractMembers accepts a Page struct, specifically a RouterPage struct, -// and extracts the elements into a slice of Router structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractMembers(page pagination.Page) ([]Member, error) { - var resp struct { - Member []Member `mapstructure:"members" json:"members"` - } - - err := mapstructure.Decode(page.(MemberPage).Body, &resp) - - return resp.Member, err -} - -// ExtractMember is a function that accepts a result and extracts a router. -func (r commonResult) ExtractMember() (*Member, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Member *Member `json:"member"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Member, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// AssociateResult represents the result of an association operation. -type AssociateResult struct { - commonResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/urls.go deleted file mode 100644 index e206406bd..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2/pools/urls.go +++ /dev/null @@ -1,25 +0,0 @@ -package pools - -import "github.com/rackspace/gophercloud" - -const ( - rootPath = "lbaas" - resourcePath = "pools" - memberPath = "members" -) - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath, resourcePath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, resourcePath, id) -} - -func memberRootURL(c *gophercloud.ServiceClient, poolId string) string { - return c.ServiceURL(rootPath, resourcePath, poolId, memberPath) -} - -func memberResourceURL(c *gophercloud.ServiceClient, poolID string, memeberID string) string { - return c.ServiceURL(rootPath, resourcePath, poolID, memberPath, memeberID) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/requests.go deleted file mode 100644 index 2712ac162..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/requests.go +++ /dev/null @@ -1,131 +0,0 @@ -package groups - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the floating IP attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - ID string `q:"id"` - Name string `q:"name"` - TenantID string `q:"tenant_id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// security groups. It accepts a ListOpts struct, which allows you to filter -// and sort the returned collection for greater efficiency. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return SecGroupPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -var ( - errNameRequired = fmt.Errorf("Name is required") -) - -// CreateOpts contains all the values needed to create a new security group. -type CreateOpts struct { - // Required. Human-readable name for the VIP. Does not have to be unique. - Name string - - // Required for admins. Indicates the owner of the VIP. - TenantID string - - // Optional. Describes the security group. - Description string -} - -// Create is an operation which provisions a new security group with default -// security group rules for the IPv4 and IPv6 ether types. -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - // Validate required opts - if opts.Name == "" { - res.Err = errNameRequired - return res - } - - type secgroup struct { - Name string `json:"name"` - TenantID string `json:"tenant_id,omitempty"` - Description string `json:"description,omitempty"` - } - - type request struct { - SecGroup secgroup `json:"security_group"` - } - - reqBody := request{SecGroup: secgroup{ - Name: opts.Name, - TenantID: opts.TenantID, - Description: opts.Description, - }} - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular security group based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// Delete will permanently delete a particular security group based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} - -// IDFromName is a convenience function that returns a security group's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - securityGroupCount := 0 - securityGroupID := "" - if name == "" { - return "", fmt.Errorf("A security group name must be provided.") - } - pager := List(client, ListOpts{}) - pager.EachPage(func(page pagination.Page) (bool, error) { - securityGroupList, err := ExtractGroups(page) - if err != nil { - return false, err - } - - for _, s := range securityGroupList { - if s.Name == name { - securityGroupCount++ - securityGroupID = s.ID - } - } - return true, nil - }) - - switch securityGroupCount { - case 0: - return "", fmt.Errorf("Unable to find security group: %s", name) - case 1: - return securityGroupID, nil - default: - return "", fmt.Errorf("Found %d security groups matching %s", securityGroupCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/results.go deleted file mode 100644 index 49db261c2..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/results.go +++ /dev/null @@ -1,108 +0,0 @@ -package groups - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules" - "github.com/rackspace/gophercloud/pagination" -) - -// SecGroup represents a container for security group rules. -type SecGroup struct { - // The UUID for the security group. - ID string - - // Human-readable name for the security group. Might not be unique. Cannot be - // named "default" as that is automatically created for a tenant. - Name string - - // The security group description. - Description string - - // A slice of security group rules that dictate the permitted behaviour for - // traffic entering and leaving the group. - Rules []rules.SecGroupRule `json:"security_group_rules" mapstructure:"security_group_rules"` - - // Owner of the security group. Only admin users can specify a TenantID - // other than their own. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` -} - -// SecGroupPage is the page returned by a pager when traversing over a -// collection of security groups. -type SecGroupPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of security groups has -// reached the end of a page and the pager seeks to traverse over a new one. In -// order to do this, it needs to construct the next page's URL. -func (p SecGroupPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"security_groups_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a SecGroupPage struct is empty. -func (p SecGroupPage) IsEmpty() (bool, error) { - is, err := ExtractGroups(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractGroups accepts a Page struct, specifically a SecGroupPage struct, -// and extracts the elements into a slice of SecGroup structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractGroups(page pagination.Page) ([]SecGroup, error) { - var resp struct { - SecGroups []SecGroup `mapstructure:"security_groups" json:"security_groups"` - } - - err := mapstructure.Decode(page.(SecGroupPage).Body, &resp) - - return resp.SecGroups, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a security group. -func (r commonResult) Extract() (*SecGroup, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - SecGroup *SecGroup `mapstructure:"security_group" json:"security_group"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.SecGroup, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/urls.go deleted file mode 100644 index 84f7324f0..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/urls.go +++ /dev/null @@ -1,13 +0,0 @@ -package groups - -import "github.com/rackspace/gophercloud" - -const rootPath = "security-groups" - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/requests.go deleted file mode 100644 index e06934a09..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/requests.go +++ /dev/null @@ -1,174 +0,0 @@ -package rules - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the security group attributes you want to see returned. SortKey allows you to -// sort by a particular network attribute. SortDir sets the direction, and is -// either `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - Direction string `q:"direction"` - EtherType string `q:"ethertype"` - ID string `q:"id"` - PortRangeMax int `q:"port_range_max"` - PortRangeMin int `q:"port_range_min"` - Protocol string `q:"protocol"` - RemoteGroupID string `q:"remote_group_id"` - RemoteIPPrefix string `q:"remote_ip_prefix"` - SecGroupID string `q:"security_group_id"` - TenantID string `q:"tenant_id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// List returns a Pager which allows you to iterate over a collection of -// security group rules. It accepts a ListOpts struct, which allows you to filter -// and sort the returned collection for greater efficiency. -func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { - q, err := gophercloud.BuildQueryString(&opts) - if err != nil { - return pagination.Pager{Err: err} - } - u := rootURL(c) + q.String() - return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { - return SecGroupRulePage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Errors -var ( - errValidDirectionRequired = fmt.Errorf("A valid Direction is required") - errValidEtherTypeRequired = fmt.Errorf("A valid EtherType is required") - errSecGroupIDRequired = fmt.Errorf("A valid SecGroupID is required") - errValidProtocolRequired = fmt.Errorf("A valid Protocol is required") -) - -// Constants useful for CreateOpts -const ( - DirIngress = "ingress" - DirEgress = "egress" - Ether4 = "IPv4" - Ether6 = "IPv6" - ProtocolTCP = "tcp" - ProtocolUDP = "udp" - ProtocolICMP = "icmp" -) - -// CreateOpts contains all the values needed to create a new security group rule. -type CreateOpts struct { - // Required. Must be either "ingress" or "egress": the direction in which the - // security group rule is applied. - Direction string - - // Required. Must be "IPv4" or "IPv6", and addresses represented in CIDR must - // match the ingress or egress rules. - EtherType string - - // Required. The security group ID to associate with this security group rule. - SecGroupID string - - // Optional. The maximum port number in the range that is matched by the - // security group rule. The PortRangeMin attribute constrains the PortRangeMax - // attribute. If the protocol is ICMP, this value must be an ICMP type. - PortRangeMax int - - // Optional. The minimum port number in the range that is matched by the - // security group rule. If the protocol is TCP or UDP, this value must be - // less than or equal to the value of the PortRangeMax attribute. If the - // protocol is ICMP, this value must be an ICMP type. - PortRangeMin int - - // Optional. The protocol that is matched by the security group rule. Valid - // values are "tcp", "udp", "icmp" or an empty string. - Protocol string - - // Optional. The remote group ID to be associated with this security group - // rule. You can specify either RemoteGroupID or RemoteIPPrefix. - RemoteGroupID string - - // Optional. The remote IP prefix to be associated with this security group - // rule. You can specify either RemoteGroupID or RemoteIPPrefix. This - // attribute matches the specified IP prefix as the source IP address of the - // IP packet. - RemoteIPPrefix string - - // Required for admins. Indicates the owner of the VIP. - TenantID string -} - -// Create is an operation which adds a new security group rule and associates it -// with an existing security group (whose ID is specified in CreateOpts). -func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { - var res CreateResult - - // Validate required opts - if opts.Direction != DirIngress && opts.Direction != DirEgress { - res.Err = errValidDirectionRequired - return res - } - if opts.EtherType != Ether4 && opts.EtherType != Ether6 { - res.Err = errValidEtherTypeRequired - return res - } - if opts.SecGroupID == "" { - res.Err = errSecGroupIDRequired - return res - } - if opts.Protocol != "" && opts.Protocol != ProtocolTCP && opts.Protocol != ProtocolUDP && opts.Protocol != ProtocolICMP { - res.Err = errValidProtocolRequired - return res - } - - type secrule struct { - Direction string `json:"direction"` - EtherType string `json:"ethertype"` - SecGroupID string `json:"security_group_id"` - PortRangeMax int `json:"port_range_max,omitempty"` - PortRangeMin int `json:"port_range_min,omitempty"` - Protocol string `json:"protocol,omitempty"` - RemoteGroupID string `json:"remote_group_id,omitempty"` - RemoteIPPrefix string `json:"remote_ip_prefix,omitempty"` - TenantID string `json:"tenant_id,omitempty"` - } - - type request struct { - SecRule secrule `json:"security_group_rule"` - } - - reqBody := request{SecRule: secrule{ - Direction: opts.Direction, - EtherType: opts.EtherType, - SecGroupID: opts.SecGroupID, - PortRangeMax: opts.PortRangeMax, - PortRangeMin: opts.PortRangeMin, - Protocol: opts.Protocol, - RemoteGroupID: opts.RemoteGroupID, - RemoteIPPrefix: opts.RemoteIPPrefix, - TenantID: opts.TenantID, - }} - - _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) - return res -} - -// Get retrieves a particular security group rule based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) - return res -} - -// Delete will permanently delete a particular security group rule based on its unique ID. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(resourceURL(c, id), nil) - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/results.go deleted file mode 100644 index 6e1385768..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/results.go +++ /dev/null @@ -1,133 +0,0 @@ -package rules - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// SecGroupRule represents a rule to dictate the behaviour of incoming or -// outgoing traffic for a particular security group. -type SecGroupRule struct { - // The UUID for this security group rule. - ID string - - // The direction in which the security group rule is applied. The only values - // allowed are "ingress" or "egress". For a compute instance, an ingress - // security group rule is applied to incoming (ingress) traffic for that - // instance. An egress rule is applied to traffic leaving the instance. - Direction string - - // Must be IPv4 or IPv6, and addresses represented in CIDR must match the - // ingress or egress rules. - EtherType string `json:"ethertype" mapstructure:"ethertype"` - - // The security group ID to associate with this security group rule. - SecGroupID string `json:"security_group_id" mapstructure:"security_group_id"` - - // The minimum port number in the range that is matched by the security group - // rule. If the protocol is TCP or UDP, this value must be less than or equal - // to the value of the PortRangeMax attribute. If the protocol is ICMP, this - // value must be an ICMP type. - PortRangeMin int `json:"port_range_min" mapstructure:"port_range_min"` - - // The maximum port number in the range that is matched by the security group - // rule. The PortRangeMin attribute constrains the PortRangeMax attribute. If - // the protocol is ICMP, this value must be an ICMP type. - PortRangeMax int `json:"port_range_max" mapstructure:"port_range_max"` - - // The protocol that is matched by the security group rule. Valid values are - // "tcp", "udp", "icmp" or an empty string. - Protocol string - - // The remote group ID to be associated with this security group rule. You - // can specify either RemoteGroupID or RemoteIPPrefix. - RemoteGroupID string `json:"remote_group_id" mapstructure:"remote_group_id"` - - // The remote IP prefix to be associated with this security group rule. You - // can specify either RemoteGroupID or RemoteIPPrefix . This attribute - // matches the specified IP prefix as the source IP address of the IP packet. - RemoteIPPrefix string `json:"remote_ip_prefix" mapstructure:"remote_ip_prefix"` - - // The owner of this security group rule. - TenantID string `json:"tenant_id" mapstructure:"tenant_id"` -} - -// SecGroupRulePage is the page returned by a pager when traversing over a -// collection of security group rules. -type SecGroupRulePage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of security group rules has -// reached the end of a page and the pager seeks to traverse over a new one. In -// order to do this, it needs to construct the next page's URL. -func (p SecGroupRulePage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"security_group_rules_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a SecGroupRulePage struct is empty. -func (p SecGroupRulePage) IsEmpty() (bool, error) { - is, err := ExtractRules(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractRules accepts a Page struct, specifically a SecGroupRulePage struct, -// and extracts the elements into a slice of SecGroupRule structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractRules(page pagination.Page) ([]SecGroupRule, error) { - var resp struct { - SecGroupRules []SecGroupRule `mapstructure:"security_group_rules" json:"security_group_rules"` - } - - err := mapstructure.Decode(page.(SecGroupRulePage).Body, &resp) - - return resp.SecGroupRules, err -} - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a security rule. -func (r commonResult) Extract() (*SecGroupRule, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - SecGroupRule *SecGroupRule `mapstructure:"security_group_rule" json:"security_group_rule"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.SecGroupRule, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/urls.go deleted file mode 100644 index 8e2b2bb28..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/urls.go +++ /dev/null @@ -1,13 +0,0 @@ -package rules - -import "github.com/rackspace/gophercloud" - -const rootPath = "security-group-rules" - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL(rootPath) -} - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL(rootPath, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/doc.go deleted file mode 100644 index c87a7ce27..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Package networks contains functionality for working with Neutron network -// resources. A network is an isolated virtual layer-2 broadcast domain that is -// typically reserved for the tenant who created it (unless you configure the -// network to be shared). Tenants can create multiple networks until the -// thresholds per-tenant quota is reached. -// -// In the v2.0 Networking API, the network is the main entity. Ports and subnets -// are always associated with a network. -package networks diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/errors.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/errors.go deleted file mode 100644 index 83c4a6a86..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/errors.go +++ /dev/null @@ -1 +0,0 @@ -package networks diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/requests.go deleted file mode 100644 index 25ab7a8b6..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/requests.go +++ /dev/null @@ -1,226 +0,0 @@ -package networks - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -// Convenience vars for AdminStateUp values. -var ( - iTrue = true - iFalse = false - - Up AdminState = &iTrue - Down AdminState = &iFalse -) - -type networkOpts struct { - AdminStateUp *bool - Name string - Shared *bool - TenantID string -} - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToNetworkListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the network attributes you want to see returned. SortKey allows you to sort -// by a particular network attribute. SortDir sets the direction, and is either -// `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - Status string `q:"status"` - Name string `q:"name"` - AdminStateUp *bool `q:"admin_state_up"` - TenantID string `q:"tenant_id"` - Shared *bool `q:"shared"` - ID string `q:"id"` - Marker string `q:"marker"` - Limit int `q:"limit"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToNetworkListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToNetworkListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// networks. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listURL(c) - if opts != nil { - query, err := opts.ToNetworkListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return NetworkPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Get retrieves a specific network based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(getURL(c, id), &res.Body, nil) - return res -} - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToNetworkCreateMap() (map[string]interface{}, error) -} - -// CreateOpts is the common options struct used in this package's Create -// operation. -type CreateOpts networkOpts - -// ToNetworkCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToNetworkCreateMap() (map[string]interface{}, error) { - n := make(map[string]interface{}) - - if opts.AdminStateUp != nil { - n["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - n["name"] = opts.Name - } - if opts.Shared != nil { - n["shared"] = &opts.Shared - } - if opts.TenantID != "" { - n["tenant_id"] = opts.TenantID - } - - return map[string]interface{}{"network": n}, nil -} - -// Create accepts a CreateOpts struct and creates a new network using the values -// provided. This operation does not actually require a request body, i.e. the -// CreateOpts struct argument can be empty. -// -// The tenant ID that is contained in the URI is the tenant that creates the -// network. An admin user, however, has the option of specifying another tenant -// ID in the CreateOpts struct. -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToNetworkCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(createURL(c), reqBody, &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToNetworkUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts is the common options struct used in this package's Update -// operation. -type UpdateOpts networkOpts - -// ToNetworkUpdateMap casts a UpdateOpts struct to a map. -func (opts UpdateOpts) ToNetworkUpdateMap() (map[string]interface{}, error) { - n := make(map[string]interface{}) - - if opts.AdminStateUp != nil { - n["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - n["name"] = opts.Name - } - if opts.Shared != nil { - n["shared"] = &opts.Shared - } - - return map[string]interface{}{"network": n}, nil -} - -// Update accepts a UpdateOpts struct and updates an existing network using the -// values provided. For more information, see the Create function. -func Update(c *gophercloud.ServiceClient, networkID string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToNetworkUpdateMap() - if err != nil { - res.Err = err - return res - } - - // Send request to API - _, res.Err = c.Put(updateURL(c, networkID), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 201}, - }) - - return res -} - -// Delete accepts a unique ID and deletes the network associated with it. -func Delete(c *gophercloud.ServiceClient, networkID string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(deleteURL(c, networkID), nil) - return res -} - -// IDFromName is a convenience function that returns a network's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - networkCount := 0 - networkID := "" - if name == "" { - return "", fmt.Errorf("A network name must be provided.") - } - pager := List(client, nil) - pager.EachPage(func(page pagination.Page) (bool, error) { - networkList, err := ExtractNetworks(page) - if err != nil { - return false, err - } - - for _, n := range networkList { - if n.Name == name { - networkCount++ - networkID = n.ID - } - } - return true, nil - }) - - switch networkCount { - case 0: - return "", fmt.Errorf("Unable to find network: %s", name) - case 1: - return networkID, nil - default: - return "", fmt.Errorf("Found %d networks matching %s", networkCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/results.go deleted file mode 100644 index 3ecedde9a..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/results.go +++ /dev/null @@ -1,116 +0,0 @@ -package networks - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a network resource. -func (r commonResult) Extract() (*Network, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Network *Network `json:"network"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Network, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// Network represents, well, a network. -type Network struct { - // UUID for the network - ID string `mapstructure:"id" json:"id"` - - // Human-readable name for the network. Might not be unique. - Name string `mapstructure:"name" json:"name"` - - // The administrative state of network. If false (down), the network does not forward packets. - AdminStateUp bool `mapstructure:"admin_state_up" json:"admin_state_up"` - - // Indicates whether network is currently operational. Possible values include - // `ACTIVE', `DOWN', `BUILD', or `ERROR'. Plug-ins might define additional values. - Status string `mapstructure:"status" json:"status"` - - // Subnets associated with this network. - Subnets []string `mapstructure:"subnets" json:"subnets"` - - // Owner of network. Only admin users can specify a tenant_id other than its own. - TenantID string `mapstructure:"tenant_id" json:"tenant_id"` - - // Specifies whether the network resource can be accessed by any tenant or not. - Shared bool `mapstructure:"shared" json:"shared"` -} - -// NetworkPage is the page returned by a pager when traversing over a -// collection of networks. -type NetworkPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of networks has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p NetworkPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"networks_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a NetworkPage struct is empty. -func (p NetworkPage) IsEmpty() (bool, error) { - is, err := ExtractNetworks(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractNetworks accepts a Page struct, specifically a NetworkPage struct, -// and extracts the elements into a slice of Network structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractNetworks(page pagination.Page) ([]Network, error) { - var resp struct { - Networks []Network `mapstructure:"networks" json:"networks"` - } - - err := mapstructure.Decode(page.(NetworkPage).Body, &resp) - - return resp.Networks, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/urls.go deleted file mode 100644 index a9eecc529..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/networks/urls.go +++ /dev/null @@ -1,31 +0,0 @@ -package networks - -import "github.com/rackspace/gophercloud" - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL("networks", id) -} - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("networks") -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} - -func listURL(c *gophercloud.ServiceClient) string { - return rootURL(c) -} - -func createURL(c *gophercloud.ServiceClient) string { - return rootURL(c) -} - -func updateURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} - -func deleteURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/doc.go deleted file mode 100644 index f16a4bb01..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package ports contains functionality for working with Neutron port resources. -// A port represents a virtual switch port on a logical network switch. Virtual -// instances attach their interfaces into ports. The logical port also defines -// the MAC address and the IP address(es) to be assigned to the interfaces -// plugged into them. When IP addresses are associated to a port, this also -// implies the port is associated with a subnet, as the IP address was taken -// from the allocation pool for a specific subnet. -package ports diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/errors.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/errors.go deleted file mode 100644 index 111d977e7..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/errors.go +++ /dev/null @@ -1,11 +0,0 @@ -package ports - -import "fmt" - -func err(str string) error { - return fmt.Errorf("%s", str) -} - -var ( - errNetworkIDRequired = err("A Network ID is required") -) diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/requests.go deleted file mode 100644 index e73e10ac6..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/requests.go +++ /dev/null @@ -1,268 +0,0 @@ -package ports - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -// Convenience vars for AdminStateUp values. -var ( - iTrue = true - iFalse = false - - Up AdminState = &iTrue - Down AdminState = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToPortListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the port attributes you want to see returned. SortKey allows you to sort -// by a particular port attribute. SortDir sets the direction, and is either -// `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - Status string `q:"status"` - Name string `q:"name"` - AdminStateUp *bool `q:"admin_state_up"` - NetworkID string `q:"network_id"` - TenantID string `q:"tenant_id"` - DeviceOwner string `q:"device_owner"` - MACAddress string `q:"mac_address"` - ID string `q:"id"` - DeviceID string `q:"device_id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToPortListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToPortListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// ports. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those ports that are owned by the tenant -// who submits the request, unless the request is submitted by a user with -// administrative rights. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listURL(c) - if opts != nil { - query, err := opts.ToPortListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return PortPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Get retrieves a specific port based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(getURL(c, id), &res.Body, nil) - return res -} - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToPortCreateMap() (map[string]interface{}, error) -} - -// CreateOpts represents the attributes used when creating a new port. -type CreateOpts struct { - NetworkID string - Name string - AdminStateUp *bool - MACAddress string - FixedIPs interface{} - DeviceID string - DeviceOwner string - TenantID string - SecurityGroups []string - AllowedAddressPairs []AddressPair -} - -// ToPortCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToPortCreateMap() (map[string]interface{}, error) { - p := make(map[string]interface{}) - - if opts.NetworkID == "" { - return nil, errNetworkIDRequired - } - p["network_id"] = opts.NetworkID - - if opts.DeviceID != "" { - p["device_id"] = opts.DeviceID - } - if opts.DeviceOwner != "" { - p["device_owner"] = opts.DeviceOwner - } - if opts.FixedIPs != nil { - p["fixed_ips"] = opts.FixedIPs - } - if opts.SecurityGroups != nil { - p["security_groups"] = opts.SecurityGroups - } - if opts.TenantID != "" { - p["tenant_id"] = opts.TenantID - } - if opts.AdminStateUp != nil { - p["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - p["name"] = opts.Name - } - if opts.MACAddress != "" { - p["mac_address"] = opts.MACAddress - } - if opts.AllowedAddressPairs != nil { - p["allowed_address_pairs"] = opts.AllowedAddressPairs - } - - return map[string]interface{}{"port": p}, nil -} - -// Create accepts a CreateOpts struct and creates a new network using the values -// provided. You must remember to provide a NetworkID value. -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToPortCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(createURL(c), reqBody, &res.Body, nil) - return res -} - -// UpdateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Update operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type UpdateOptsBuilder interface { - ToPortUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts represents the attributes used when updating an existing port. -type UpdateOpts struct { - Name string - AdminStateUp *bool - FixedIPs interface{} - DeviceID string - DeviceOwner string - SecurityGroups []string - AllowedAddressPairs []AddressPair -} - -// ToPortUpdateMap casts an UpdateOpts struct to a map. -func (opts UpdateOpts) ToPortUpdateMap() (map[string]interface{}, error) { - p := make(map[string]interface{}) - - if opts.DeviceID != "" { - p["device_id"] = opts.DeviceID - } - if opts.DeviceOwner != "" { - p["device_owner"] = opts.DeviceOwner - } - if opts.FixedIPs != nil { - p["fixed_ips"] = opts.FixedIPs - } - if opts.SecurityGroups != nil { - p["security_groups"] = opts.SecurityGroups - } - if opts.AdminStateUp != nil { - p["admin_state_up"] = &opts.AdminStateUp - } - if opts.Name != "" { - p["name"] = opts.Name - } - if opts.AllowedAddressPairs != nil { - p["allowed_address_pairs"] = opts.AllowedAddressPairs - } - - return map[string]interface{}{"port": p}, nil -} - -// Update accepts a UpdateOpts struct and updates an existing port using the -// values provided. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToPortUpdateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Put(updateURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 201}, - }) - return res -} - -// Delete accepts a unique ID and deletes the port associated with it. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(deleteURL(c, id), nil) - return res -} - -// IDFromName is a convenience function that returns a port's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - portCount := 0 - portID := "" - if name == "" { - return "", fmt.Errorf("A port name must be provided.") - } - pager := List(client, nil) - pager.EachPage(func(page pagination.Page) (bool, error) { - portList, err := ExtractPorts(page) - if err != nil { - return false, err - } - - for _, p := range portList { - if p.Name == name { - portCount++ - portID = p.ID - } - } - return true, nil - }) - - switch portCount { - case 0: - return "", fmt.Errorf("Unable to find port: %s", name) - case 1: - return portID, nil - default: - return "", fmt.Errorf("Found %d ports matching %s", portCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/results.go deleted file mode 100644 index 1f7eea169..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/results.go +++ /dev/null @@ -1,132 +0,0 @@ -package ports - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a port resource. -func (r commonResult) Extract() (*Port, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Port *Port `json:"port"` - } - err := mapstructure.Decode(r.Body, &res) - - return res.Port, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// IP is a sub-struct that represents an individual IP. -type IP struct { - SubnetID string `mapstructure:"subnet_id" json:"subnet_id"` - IPAddress string `mapstructure:"ip_address" json:"ip_address,omitempty"` -} - -type AddressPair struct { - IPAddress string `mapstructure:"ip_address" json:"ip_address,omitempty"` - MACAddress string `mapstructure:"mac_address" json:"mac_address,omitempty"` -} - -// Port represents a Neutron port. See package documentation for a top-level -// description of what this is. -type Port struct { - // UUID for the port. - ID string `mapstructure:"id" json:"id"` - // Network that this port is associated with. - NetworkID string `mapstructure:"network_id" json:"network_id"` - // Human-readable name for the port. Might not be unique. - Name string `mapstructure:"name" json:"name"` - // Administrative state of port. If false (down), port does not forward packets. - AdminStateUp bool `mapstructure:"admin_state_up" json:"admin_state_up"` - // Indicates whether network is currently operational. Possible values include - // `ACTIVE', `DOWN', `BUILD', or `ERROR'. Plug-ins might define additional values. - Status string `mapstructure:"status" json:"status"` - // Mac address to use on this port. - MACAddress string `mapstructure:"mac_address" json:"mac_address"` - // Specifies IP addresses for the port thus associating the port itself with - // the subnets where the IP addresses are picked from - FixedIPs []IP `mapstructure:"fixed_ips" json:"fixed_ips"` - // Owner of network. Only admin users can specify a tenant_id other than its own. - TenantID string `mapstructure:"tenant_id" json:"tenant_id"` - // Identifies the entity (e.g.: dhcp agent) using this port. - DeviceOwner string `mapstructure:"device_owner" json:"device_owner"` - // Specifies the IDs of any security groups associated with a port. - SecurityGroups []string `mapstructure:"security_groups" json:"security_groups"` - // Identifies the device (e.g., virtual server) using this port. - DeviceID string `mapstructure:"device_id" json:"device_id"` - // Identifies the list of IP addresses the port will recognize/accept - AllowedAddressPairs []AddressPair `mapstructure:"allowed_address_pairs" json:"allowed_address_pairs"` -} - -// PortPage is the page returned by a pager when traversing over a collection -// of network ports. -type PortPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of ports has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p PortPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"ports_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a PortPage struct is empty. -func (p PortPage) IsEmpty() (bool, error) { - is, err := ExtractPorts(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractPorts accepts a Page struct, specifically a PortPage struct, -// and extracts the elements into a slice of Port structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractPorts(page pagination.Page) ([]Port, error) { - var resp struct { - Ports []Port `mapstructure:"ports" json:"ports"` - } - - err := mapstructure.Decode(page.(PortPage).Body, &resp) - - return resp.Ports, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/urls.go deleted file mode 100644 index 6d0572f1f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/ports/urls.go +++ /dev/null @@ -1,31 +0,0 @@ -package ports - -import "github.com/rackspace/gophercloud" - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL("ports", id) -} - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("ports") -} - -func listURL(c *gophercloud.ServiceClient) string { - return rootURL(c) -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} - -func createURL(c *gophercloud.ServiceClient) string { - return rootURL(c) -} - -func updateURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} - -func deleteURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/doc.go deleted file mode 100644 index 43e8296c7..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -// Package subnets contains functionality for working with Neutron subnet -// resources. A subnet represents an IP address block that can be used to -// assign IP addresses to virtual instances. Each subnet must have a CIDR and -// must be associated with a network. IPs can either be selected from the whole -// subnet CIDR or from allocation pools specified by the user. -// -// A subnet can also have a gateway, a list of DNS name servers, and host routes. -// This information is pushed to instances whose interfaces are associated with -// the subnet. -package subnets diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/errors.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/errors.go deleted file mode 100644 index d2f7b46e3..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/errors.go +++ /dev/null @@ -1,14 +0,0 @@ -package subnets - -import "fmt" - -func err(str string) error { - return fmt.Errorf("%s", str) -} - -var ( - errNetworkIDRequired = err("A network ID is required") - errCIDRRequired = err("A valid CIDR is required") - errInvalidIPType = err("An IP type must either be 4 or 6") - errInvalidGatewayConfig = err("Both disabling the gateway and specifying a gateway is not allowed") -) diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests.go deleted file mode 100644 index 8fa1e6dbe..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests.go +++ /dev/null @@ -1,287 +0,0 @@ -package subnets - -import ( - "fmt" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// AdminState gives users a solid type to work with for create and update -// operations. It is recommended that users use the `Up` and `Down` enums. -type AdminState *bool - -// Convenience vars for AdminStateUp values. -var ( - iTrue = true - iFalse = false - - Up AdminState = &iTrue - Down AdminState = &iFalse -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToSubnetListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the subnet attributes you want to see returned. SortKey allows you to sort -// by a particular subnet attribute. SortDir sets the direction, and is either -// `asc' or `desc'. Marker and Limit are used for pagination. -type ListOpts struct { - Name string `q:"name"` - EnableDHCP *bool `q:"enable_dhcp"` - NetworkID string `q:"network_id"` - TenantID string `q:"tenant_id"` - IPVersion int `q:"ip_version"` - GatewayIP string `q:"gateway_ip"` - CIDR string `q:"cidr"` - ID string `q:"id"` - Limit int `q:"limit"` - Marker string `q:"marker"` - SortKey string `q:"sort_key"` - SortDir string `q:"sort_dir"` -} - -// ToSubnetListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToSubnetListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return "", err - } - return q.String(), nil -} - -// List returns a Pager which allows you to iterate over a collection of -// subnets. It accepts a ListOpts struct, which allows you to filter and sort -// the returned collection for greater efficiency. -// -// Default policy settings return only those subnets that are owned by the tenant -// who submits the request, unless the request is submitted by a user with -// administrative rights. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := listURL(c) - if opts != nil { - query, err := opts.ToSubnetListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - - return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { - return SubnetPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Get retrieves a specific subnet based on its unique ID. -func Get(c *gophercloud.ServiceClient, id string) GetResult { - var res GetResult - _, res.Err = c.Get(getURL(c, id), &res.Body, nil) - return res -} - -// Valid IP types -const ( - IPv4 = 4 - IPv6 = 6 -) - -// CreateOptsBuilder is the interface options structs have to satisfy in order -// to be used in the main Create operation in this package. Since many -// extensions decorate or modify the common logic, it is useful for them to -// satisfy a basic interface in order for them to be used. -type CreateOptsBuilder interface { - ToSubnetCreateMap() (map[string]interface{}, error) -} - -// CreateOpts represents the attributes used when creating a new subnet. -type CreateOpts struct { - // Required - NetworkID string - CIDR string - // Optional - Name string - TenantID string - AllocationPools []AllocationPool - GatewayIP string - NoGateway bool - IPVersion int - EnableDHCP *bool - DNSNameservers []string - HostRoutes []HostRoute -} - -// ToSubnetCreateMap casts a CreateOpts struct to a map. -func (opts CreateOpts) ToSubnetCreateMap() (map[string]interface{}, error) { - s := make(map[string]interface{}) - - if opts.NetworkID == "" { - return nil, errNetworkIDRequired - } - if opts.CIDR == "" { - return nil, errCIDRRequired - } - if opts.IPVersion != 0 && opts.IPVersion != IPv4 && opts.IPVersion != IPv6 { - return nil, errInvalidIPType - } - - // Both GatewayIP and NoGateway should not be set - if opts.GatewayIP != "" && opts.NoGateway { - return nil, errInvalidGatewayConfig - } - - s["network_id"] = opts.NetworkID - s["cidr"] = opts.CIDR - - if opts.EnableDHCP != nil { - s["enable_dhcp"] = &opts.EnableDHCP - } - if opts.Name != "" { - s["name"] = opts.Name - } - if opts.GatewayIP != "" { - s["gateway_ip"] = opts.GatewayIP - } else if opts.NoGateway { - s["gateway_ip"] = nil - } - if opts.TenantID != "" { - s["tenant_id"] = opts.TenantID - } - if opts.IPVersion != 0 { - s["ip_version"] = opts.IPVersion - } - if len(opts.AllocationPools) != 0 { - s["allocation_pools"] = opts.AllocationPools - } - if len(opts.DNSNameservers) != 0 { - s["dns_nameservers"] = opts.DNSNameservers - } - if len(opts.HostRoutes) != 0 { - s["host_routes"] = opts.HostRoutes - } - - return map[string]interface{}{"subnet": s}, nil -} - -// Create accepts a CreateOpts struct and creates a new subnet using the values -// provided. You must remember to provide a valid NetworkID, CIDR and IP version. -func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { - var res CreateResult - - reqBody, err := opts.ToSubnetCreateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Post(createURL(c), reqBody, &res.Body, nil) - return res -} - -// UpdateOptsBuilder allows extensions to add additional parameters to the -// Update request. -type UpdateOptsBuilder interface { - ToSubnetUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts represents the attributes used when updating an existing subnet. -type UpdateOpts struct { - Name string - GatewayIP string - NoGateway bool - DNSNameservers []string - HostRoutes []HostRoute - EnableDHCP *bool -} - -// ToSubnetUpdateMap casts an UpdateOpts struct to a map. -func (opts UpdateOpts) ToSubnetUpdateMap() (map[string]interface{}, error) { - s := make(map[string]interface{}) - - // Both GatewayIP and NoGateway should not be set - if opts.GatewayIP != "" && opts.NoGateway { - return nil, errInvalidGatewayConfig - } - - if opts.EnableDHCP != nil { - s["enable_dhcp"] = &opts.EnableDHCP - } - if opts.Name != "" { - s["name"] = opts.Name - } - if opts.GatewayIP != "" { - s["gateway_ip"] = opts.GatewayIP - } else if opts.NoGateway { - s["gateway_ip"] = nil - } - if opts.DNSNameservers != nil { - s["dns_nameservers"] = opts.DNSNameservers - } - if opts.HostRoutes != nil { - s["host_routes"] = opts.HostRoutes - } - - return map[string]interface{}{"subnet": s}, nil -} - -// Update accepts a UpdateOpts struct and updates an existing subnet using the -// values provided. -func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - - reqBody, err := opts.ToSubnetUpdateMap() - if err != nil { - res.Err = err - return res - } - - _, res.Err = c.Put(updateURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 201}, - }) - - return res -} - -// Delete accepts a unique ID and deletes the subnet associated with it. -func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(deleteURL(c, id), nil) - return res -} - -// IDFromName is a convenience function that returns a subnet's ID given its name. -func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { - subnetCount := 0 - subnetID := "" - if name == "" { - return "", fmt.Errorf("A subnet name must be provided.") - } - pager := List(client, nil) - pager.EachPage(func(page pagination.Page) (bool, error) { - subnetList, err := ExtractSubnets(page) - if err != nil { - return false, err - } - - for _, s := range subnetList { - if s.Name == name { - subnetCount++ - subnetID = s.ID - } - } - return true, nil - }) - - switch subnetCount { - case 0: - return "", fmt.Errorf("Unable to find subnet: %s", name) - case 1: - return subnetID, nil - default: - return "", fmt.Errorf("Found %d subnets matching %s", subnetCount, name) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/results.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/results.go deleted file mode 100644 index 77b956a17..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/results.go +++ /dev/null @@ -1,132 +0,0 @@ -package subnets - -import ( - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -type commonResult struct { - gophercloud.Result -} - -// Extract is a function that accepts a result and extracts a subnet resource. -func (r commonResult) Extract() (*Subnet, error) { - if r.Err != nil { - return nil, r.Err - } - - var res struct { - Subnet *Subnet `json:"subnet"` - } - - err := mapstructure.Decode(r.Body, &res) - - return res.Subnet, err -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - commonResult -} - -// GetResult represents the result of a get operation. -type GetResult struct { - commonResult -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - commonResult -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.ErrResult -} - -// AllocationPool represents a sub-range of cidr available for dynamic -// allocation to ports, e.g. {Start: "10.0.0.2", End: "10.0.0.254"} -type AllocationPool struct { - Start string `json:"start"` - End string `json:"end"` -} - -// HostRoute represents a route that should be used by devices with IPs from -// a subnet (not including local subnet route). -type HostRoute struct { - DestinationCIDR string `mapstructure:"destination" json:"destination"` - NextHop string `mapstructure:"nexthop" json:"nexthop"` -} - -// Subnet represents a subnet. See package documentation for a top-level -// description of what this is. -type Subnet struct { - // UUID representing the subnet - ID string `mapstructure:"id" json:"id"` - // UUID of the parent network - NetworkID string `mapstructure:"network_id" json:"network_id"` - // Human-readable name for the subnet. Might not be unique. - Name string `mapstructure:"name" json:"name"` - // IP version, either `4' or `6' - IPVersion int `mapstructure:"ip_version" json:"ip_version"` - // CIDR representing IP range for this subnet, based on IP version - CIDR string `mapstructure:"cidr" json:"cidr"` - // Default gateway used by devices in this subnet - GatewayIP string `mapstructure:"gateway_ip" json:"gateway_ip"` - // DNS name servers used by hosts in this subnet. - DNSNameservers []string `mapstructure:"dns_nameservers" json:"dns_nameservers"` - // Sub-ranges of CIDR available for dynamic allocation to ports. See AllocationPool. - AllocationPools []AllocationPool `mapstructure:"allocation_pools" json:"allocation_pools"` - // Routes that should be used by devices with IPs from this subnet (not including local subnet route). - HostRoutes []HostRoute `mapstructure:"host_routes" json:"host_routes"` - // Specifies whether DHCP is enabled for this subnet or not. - EnableDHCP bool `mapstructure:"enable_dhcp" json:"enable_dhcp"` - // Owner of network. Only admin users can specify a tenant_id other than its own. - TenantID string `mapstructure:"tenant_id" json:"tenant_id"` -} - -// SubnetPage is the page returned by a pager when traversing over a collection -// of subnets. -type SubnetPage struct { - pagination.LinkedPageBase -} - -// NextPageURL is invoked when a paginated collection of subnets has reached -// the end of a page and the pager seeks to traverse over a new one. In order -// to do this, it needs to construct the next page's URL. -func (p SubnetPage) NextPageURL() (string, error) { - type resp struct { - Links []gophercloud.Link `mapstructure:"subnets_links"` - } - - var r resp - err := mapstructure.Decode(p.Body, &r) - if err != nil { - return "", err - } - - return gophercloud.ExtractNextURL(r.Links) -} - -// IsEmpty checks whether a SubnetPage struct is empty. -func (p SubnetPage) IsEmpty() (bool, error) { - is, err := ExtractSubnets(p) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -// ExtractSubnets accepts a Page struct, specifically a SubnetPage struct, -// and extracts the elements into a slice of Subnet structs. In other words, -// a generic collection is mapped into a relevant slice. -func ExtractSubnets(page pagination.Page) ([]Subnet, error) { - var resp struct { - Subnets []Subnet `mapstructure:"subnets" json:"subnets"` - } - - err := mapstructure.Decode(page.(SubnetPage).Body, &resp) - - return resp.Subnets, err -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/urls.go deleted file mode 100644 index 0d0236894..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/urls.go +++ /dev/null @@ -1,31 +0,0 @@ -package subnets - -import "github.com/rackspace/gophercloud" - -func resourceURL(c *gophercloud.ServiceClient, id string) string { - return c.ServiceURL("subnets", id) -} - -func rootURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("subnets") -} - -func listURL(c *gophercloud.ServiceClient) string { - return rootURL(c) -} - -func getURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} - -func createURL(c *gophercloud.ServiceClient) string { - return rootURL(c) -} - -func updateURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} - -func deleteURL(c *gophercloud.ServiceClient, id string) string { - return resourceURL(c, id) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/fixtures.go deleted file mode 100644 index f22b68700..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/fixtures.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build fixtures - -package accounts - -import ( - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -// HandleGetAccountSuccessfully creates an HTTP handler at `/` on the test handler mux that -// responds with a `Get` response. -func HandleGetAccountSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "HEAD") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Set("X-Account-Container-Count", "2") - w.Header().Set("X-Account-Bytes-Used", "14") - w.Header().Set("X-Account-Meta-Subject", "books") - - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleUpdateAccountSuccessfully creates an HTTP handler at `/` on the test handler mux that -// responds with a `Update` response. -func HandleUpdateAccountSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "X-Account-Meta-Gophercloud-Test", "accounts") - - w.WriteHeader(http.StatusNoContent) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/results.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/results.go deleted file mode 100644 index 6ab1a2306..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/results.go +++ /dev/null @@ -1,102 +0,0 @@ -package accounts - -import ( - "strings" - "time" - - "github.com/rackspace/gophercloud" -) - -// UpdateResult is returned from a call to the Update function. -type UpdateResult struct { - gophercloud.HeaderResult -} - -// UpdateHeader represents the headers returned in the response from an Update request. -type UpdateHeader struct { - ContentLength string `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// Extract will return a struct of headers returned from a call to Get. To obtain -// a map of headers, call the ExtractHeader method on the GetResult. -func (ur UpdateResult) Extract() (UpdateHeader, error) { - var uh UpdateHeader - if ur.Err != nil { - return uh, ur.Err - } - - if err := gophercloud.DecodeHeader(ur.Header, &uh); err != nil { - return uh, err - } - - if date, ok := ur.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, ur.Header["Date"][0]) - if err != nil { - return uh, err - } - uh.Date = t - } - - return uh, nil -} - -// GetHeader represents the headers returned in the response from a Get request. -type GetHeader struct { - BytesUsed int64 `mapstructure:"X-Account-Bytes-Used"` - ContainerCount int `mapstructure:"X-Account-Container-Count"` - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - ObjectCount int64 `mapstructure:"X-Account-Object-Count"` - TransID string `mapstructure:"X-Trans-Id"` - TempURLKey string `mapstructure:"X-Account-Meta-Temp-URL-Key"` - TempURLKey2 string `mapstructure:"X-Account-Meta-Temp-URL-Key-2"` -} - -// GetResult is returned from a call to the Get function. -type GetResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Get. To obtain -// a map of headers, call the ExtractHeader method on the GetResult. -func (gr GetResult) Extract() (GetHeader, error) { - var gh GetHeader - if gr.Err != nil { - return gh, gr.Err - } - - if err := gophercloud.DecodeHeader(gr.Header, &gh); err != nil { - return gh, err - } - - if date, ok := gr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, gr.Header["Date"][0]) - if err != nil { - return gh, err - } - gh.Date = t - } - - return gh, nil -} - -// ExtractMetadata is a function that takes a GetResult (of type *http.Response) -// and returns the custom metatdata associated with the account. -func (gr GetResult) ExtractMetadata() (map[string]string, error) { - if gr.Err != nil { - return nil, gr.Err - } - - metadata := make(map[string]string) - for k, v := range gr.Header { - if strings.HasPrefix(k, "X-Account-Meta-") { - key := strings.TrimPrefix(k, "X-Account-Meta-") - metadata[key] = v[0] - } - } - return metadata, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/doc.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/doc.go deleted file mode 100644 index 5fed5537f..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package containers contains functionality for working with Object Storage -// container resources. A container serves as a logical namespace for objects -// that are placed inside it - an object with the same name in two different -// containers represents two different objects. -// -// In addition to containing objects, you can also use the container to control -// access to objects by using an access control list (ACL). -package containers diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/fixtures.go deleted file mode 100644 index e60735248..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/fixtures.go +++ /dev/null @@ -1,143 +0,0 @@ -// +build fixtures - -package containers - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -// ExpectedListInfo is the result expected from a call to `List` when full -// info is requested. -var ExpectedListInfo = []Container{ - Container{ - Count: 0, - Bytes: 0, - Name: "janeausten", - }, - Container{ - Count: 1, - Bytes: 14, - Name: "marktwain", - }, -} - -// ExpectedListNames is the result expected from a call to `List` when just -// container names are requested. -var ExpectedListNames = []string{"janeausten", "marktwain"} - -// HandleListContainerInfoSuccessfully creates an HTTP handler at `/` on the test handler mux that -// responds with a `List` response when full info is requested. -func HandleListContainerInfoSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, `[ - { - "count": 0, - "bytes": 0, - "name": "janeausten" - }, - { - "count": 1, - "bytes": 14, - "name": "marktwain" - } - ]`) - case "janeausten": - fmt.Fprintf(w, `[ - { - "count": 1, - "bytes": 14, - "name": "marktwain" - } - ]`) - case "marktwain": - fmt.Fprintf(w, `[]`) - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) -} - -// HandleListContainerNamesSuccessfully creates an HTTP handler at `/` on the test handler mux that -// responds with a `ListNames` response when only container names are requested. -func HandleListContainerNamesSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "text/plain") - - w.Header().Set("Content-Type", "text/plain") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, "janeausten\nmarktwain\n") - case "janeausten": - fmt.Fprintf(w, "marktwain\n") - case "marktwain": - fmt.Fprintf(w, ``) - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) -} - -// HandleCreateContainerSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that -// responds with a `Create` response. -func HandleCreateContainerSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Add("X-Container-Meta-Foo", "bar") - w.Header().Add("X-Trans-Id", "1234567") - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleDeleteContainerSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that -// responds with a `Delete` response. -func HandleDeleteContainerSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleUpdateContainerSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that -// responds with a `Update` response. -func HandleUpdateContainerSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleGetContainerSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that -// responds with a `Get` response. -func HandleGetContainerSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "HEAD") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - w.WriteHeader(http.StatusNoContent) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/requests.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/requests.go deleted file mode 100644 index cd8e82bf0..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/requests.go +++ /dev/null @@ -1,205 +0,0 @@ -package containers - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" -) - -// ListOptsBuilder allows extensions to add additional parameters to the List -// request. -type ListOptsBuilder interface { - ToContainerListParams() (bool, string, error) -} - -// ListOpts is a structure that holds options for listing containers. -type ListOpts struct { - Full bool - Limit int `q:"limit"` - Marker string `q:"marker"` - EndMarker string `q:"end_marker"` - Format string `q:"format"` - Prefix string `q:"prefix"` - Delimiter string `q:"delimiter"` -} - -// ToContainerListParams formats a ListOpts into a query string and boolean -// representing whether to list complete information for each container. -func (opts ListOpts) ToContainerListParams() (bool, string, error) { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return false, "", err - } - return opts.Full, q.String(), nil -} - -// List is a function that retrieves containers associated with the account as -// well as account metadata. It returns a pager which can be iterated with the -// EachPage function. -func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - headers := map[string]string{"Accept": "text/plain", "Content-Type": "text/plain"} - - url := listURL(c) - if opts != nil { - full, query, err := opts.ToContainerListParams() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - - if full { - headers = map[string]string{"Accept": "application/json", "Content-Type": "application/json"} - } - } - - createPage := func(r pagination.PageResult) pagination.Page { - p := ContainerPage{pagination.MarkerPageBase{PageResult: r}} - p.MarkerPageBase.Owner = p - return p - } - - pager := pagination.NewPager(c, url, createPage) - pager.Headers = headers - return pager -} - -// CreateOptsBuilder allows extensions to add additional parameters to the -// Create request. -type CreateOptsBuilder interface { - ToContainerCreateMap() (map[string]string, error) -} - -// CreateOpts is a structure that holds parameters for creating a container. -type CreateOpts struct { - Metadata map[string]string - ContainerRead string `h:"X-Container-Read"` - ContainerSyncTo string `h:"X-Container-Sync-To"` - ContainerSyncKey string `h:"X-Container-Sync-Key"` - ContainerWrite string `h:"X-Container-Write"` - ContentType string `h:"Content-Type"` - DetectContentType bool `h:"X-Detect-Content-Type"` - IfNoneMatch string `h:"If-None-Match"` - VersionsLocation string `h:"X-Versions-Location"` -} - -// ToContainerCreateMap formats a CreateOpts into a map of headers. -func (opts CreateOpts) ToContainerCreateMap() (map[string]string, error) { - h, err := gophercloud.BuildHeaders(opts) - if err != nil { - return nil, err - } - for k, v := range opts.Metadata { - h["X-Container-Meta-"+k] = v - } - return h, nil -} - -// Create is a function that creates a new container. -func Create(c *gophercloud.ServiceClient, containerName string, opts CreateOptsBuilder) CreateResult { - var res CreateResult - h := make(map[string]string) - - if opts != nil { - headers, err := opts.ToContainerCreateMap() - if err != nil { - res.Err = err - return res - } - - for k, v := range headers { - h[k] = v - } - } - - resp, err := c.Request("PUT", createURL(c, containerName), gophercloud.RequestOpts{ - MoreHeaders: h, - OkCodes: []int{201, 202, 204}, - }) - if resp != nil { - res.Header = resp.Header - } - res.Err = err - return res -} - -// Delete is a function that deletes a container. -func Delete(c *gophercloud.ServiceClient, containerName string) DeleteResult { - var res DeleteResult - _, res.Err = c.Delete(deleteURL(c, containerName), nil) - return res -} - -// UpdateOptsBuilder allows extensions to add additional parameters to the -// Update request. -type UpdateOptsBuilder interface { - ToContainerUpdateMap() (map[string]string, error) -} - -// UpdateOpts is a structure that holds parameters for updating, creating, or -// deleting a container's metadata. -type UpdateOpts struct { - Metadata map[string]string - ContainerRead string `h:"X-Container-Read"` - ContainerSyncTo string `h:"X-Container-Sync-To"` - ContainerSyncKey string `h:"X-Container-Sync-Key"` - ContainerWrite string `h:"X-Container-Write"` - ContentType string `h:"Content-Type"` - DetectContentType bool `h:"X-Detect-Content-Type"` - RemoveVersionsLocation string `h:"X-Remove-Versions-Location"` - VersionsLocation string `h:"X-Versions-Location"` -} - -// ToContainerUpdateMap formats a CreateOpts into a map of headers. -func (opts UpdateOpts) ToContainerUpdateMap() (map[string]string, error) { - h, err := gophercloud.BuildHeaders(opts) - if err != nil { - return nil, err - } - for k, v := range opts.Metadata { - h["X-Container-Meta-"+k] = v - } - return h, nil -} - -// Update is a function that creates, updates, or deletes a container's -// metadata. -func Update(c *gophercloud.ServiceClient, containerName string, opts UpdateOptsBuilder) UpdateResult { - var res UpdateResult - h := make(map[string]string) - - if opts != nil { - headers, err := opts.ToContainerUpdateMap() - if err != nil { - res.Err = err - return res - } - - for k, v := range headers { - h[k] = v - } - } - - resp, err := c.Request("POST", updateURL(c, containerName), gophercloud.RequestOpts{ - MoreHeaders: h, - OkCodes: []int{201, 202, 204}, - }) - if resp != nil { - res.Header = resp.Header - } - res.Err = err - return res -} - -// Get is a function that retrieves the metadata of a container. To extract just -// the custom metadata, pass the GetResult response to the ExtractMetadata -// function. -func Get(c *gophercloud.ServiceClient, containerName string) GetResult { - var res GetResult - resp, err := c.Request("HEAD", getURL(c, containerName), gophercloud.RequestOpts{ - OkCodes: []int{200, 204}, - }) - if resp != nil { - res.Header = resp.Header - } - res.Err = err - return res -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/results.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/results.go deleted file mode 100644 index e682b8dcc..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/results.go +++ /dev/null @@ -1,270 +0,0 @@ -package containers - -import ( - "fmt" - "strings" - "time" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - - "github.com/mitchellh/mapstructure" -) - -// Container represents a container resource. -type Container struct { - // The total number of bytes stored in the container. - Bytes int `json:"bytes" mapstructure:"bytes"` - - // The total number of objects stored in the container. - Count int `json:"count" mapstructure:"count"` - - // The name of the container. - Name string `json:"name" mapstructure:"name"` -} - -// ContainerPage is the page returned by a pager when traversing over a -// collection of containers. -type ContainerPage struct { - pagination.MarkerPageBase -} - -// IsEmpty returns true if a ListResult contains no container names. -func (r ContainerPage) IsEmpty() (bool, error) { - names, err := ExtractNames(r) - if err != nil { - return true, err - } - return len(names) == 0, nil -} - -// LastMarker returns the last container name in a ListResult. -func (r ContainerPage) LastMarker() (string, error) { - names, err := ExtractNames(r) - if err != nil { - return "", err - } - if len(names) == 0 { - return "", nil - } - return names[len(names)-1], nil -} - -// ExtractInfo is a function that takes a ListResult and returns the containers' information. -func ExtractInfo(page pagination.Page) ([]Container, error) { - untyped := page.(ContainerPage).Body.([]interface{}) - results := make([]Container, len(untyped)) - for index, each := range untyped { - container := each.(map[string]interface{}) - err := mapstructure.Decode(container, &results[index]) - if err != nil { - return results, err - } - } - return results, nil -} - -// ExtractNames is a function that takes a ListResult and returns the containers' names. -func ExtractNames(page pagination.Page) ([]string, error) { - casted := page.(ContainerPage) - ct := casted.Header.Get("Content-Type") - - switch { - case strings.HasPrefix(ct, "application/json"): - parsed, err := ExtractInfo(page) - if err != nil { - return nil, err - } - - names := make([]string, 0, len(parsed)) - for _, container := range parsed { - names = append(names, container.Name) - } - return names, nil - case strings.HasPrefix(ct, "text/plain"): - names := make([]string, 0, 50) - - body := string(page.(ContainerPage).Body.([]uint8)) - for _, name := range strings.Split(body, "\n") { - if len(name) > 0 { - names = append(names, name) - } - } - - return names, nil - default: - return nil, fmt.Errorf("Cannot extract names from response with content-type: [%s]", ct) - } -} - -// GetHeader represents the headers returned in the response from a Get request. -type GetHeader struct { - AcceptRanges string `mapstructure:"Accept-Ranges"` - BytesUsed int64 `mapstructure:"X-Account-Bytes-Used"` - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - ObjectCount int64 `mapstructure:"X-Container-Object-Count"` - Read string `mapstructure:"X-Container-Read"` - TransID string `mapstructure:"X-Trans-Id"` - VersionsLocation string `mapstructure:"X-Versions-Location"` - Write string `mapstructure:"X-Container-Write"` -} - -// GetResult represents the result of a get operation. -type GetResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Get. To obtain -// a map of headers, call the ExtractHeader method on the GetResult. -func (gr GetResult) Extract() (GetHeader, error) { - var gh GetHeader - if gr.Err != nil { - return gh, gr.Err - } - - if err := gophercloud.DecodeHeader(gr.Header, &gh); err != nil { - return gh, err - } - - if date, ok := gr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, gr.Header["Date"][0]) - if err != nil { - return gh, err - } - gh.Date = t - } - - return gh, nil -} - -// ExtractMetadata is a function that takes a GetResult (of type *http.Response) -// and returns the custom metadata associated with the container. -func (gr GetResult) ExtractMetadata() (map[string]string, error) { - if gr.Err != nil { - return nil, gr.Err - } - metadata := make(map[string]string) - for k, v := range gr.Header { - if strings.HasPrefix(k, "X-Container-Meta-") { - key := strings.TrimPrefix(k, "X-Container-Meta-") - metadata[key] = v[0] - } - } - return metadata, nil -} - -// CreateHeader represents the headers returned in the response from a Create request. -type CreateHeader struct { - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// CreateResult represents the result of a create operation. To extract the -// the headers from the HTTP response, you can invoke the 'ExtractHeader' -// method on the result struct. -type CreateResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Create. To obtain -// a map of headers, call the ExtractHeader method on the CreateResult. -func (cr CreateResult) Extract() (CreateHeader, error) { - var ch CreateHeader - if cr.Err != nil { - return ch, cr.Err - } - - if err := gophercloud.DecodeHeader(cr.Header, &ch); err != nil { - return ch, err - } - - if date, ok := cr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, cr.Header["Date"][0]) - if err != nil { - return ch, err - } - ch.Date = t - } - - return ch, nil -} - -// UpdateHeader represents the headers returned in the response from a Update request. -type UpdateHeader struct { - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// UpdateResult represents the result of an update operation. To extract the -// the headers from the HTTP response, you can invoke the 'ExtractHeader' -// method on the result struct. -type UpdateResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Update. To obtain -// a map of headers, call the ExtractHeader method on the UpdateResult. -func (ur UpdateResult) Extract() (UpdateHeader, error) { - var uh UpdateHeader - if ur.Err != nil { - return uh, ur.Err - } - - if err := gophercloud.DecodeHeader(ur.Header, &uh); err != nil { - return uh, err - } - - if date, ok := ur.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, ur.Header["Date"][0]) - if err != nil { - return uh, err - } - uh.Date = t - } - - return uh, nil -} - -// DeleteHeader represents the headers returned in the response from a Delete request. -type DeleteHeader struct { - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// DeleteResult represents the result of a delete operation. To extract the -// the headers from the HTTP response, you can invoke the 'ExtractHeader' -// method on the result struct. -type DeleteResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Delete. To obtain -// a map of headers, call the ExtractHeader method on the DeleteResult. -func (dr DeleteResult) Extract() (DeleteHeader, error) { - var dh DeleteHeader - if dr.Err != nil { - return dh, dr.Err - } - - if err := gophercloud.DecodeHeader(dr.Header, &dh); err != nil { - return dh, err - } - - if date, ok := dr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, dr.Header["Date"][0]) - if err != nil { - return dh, err - } - dh.Date = t - } - - return dh, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/urls.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/urls.go deleted file mode 100644 index f864f846e..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/urls.go +++ /dev/null @@ -1,23 +0,0 @@ -package containers - -import "github.com/rackspace/gophercloud" - -func listURL(c *gophercloud.ServiceClient) string { - return c.Endpoint -} - -func createURL(c *gophercloud.ServiceClient, container string) string { - return c.ServiceURL(container) -} - -func getURL(c *gophercloud.ServiceClient, container string) string { - return createURL(c, container) -} - -func deleteURL(c *gophercloud.ServiceClient, container string) string { - return createURL(c, container) -} - -func updateURL(c *gophercloud.ServiceClient, container string) string { - return createURL(c, container) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/fixtures.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/fixtures.go deleted file mode 100644 index d2ea18c1d..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/fixtures.go +++ /dev/null @@ -1,213 +0,0 @@ -// +build fixtures - -package objects - -import ( - "crypto/md5" - "fmt" - "io" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -// HandleDownloadObjectSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler mux that -// responds with a `Download` response. -func HandleDownloadObjectSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, "Successful download with Gophercloud") - }) -} - -// ExpectedListInfo is the result expected from a call to `List` when full -// info is requested. -var ExpectedListInfo = []Object{ - Object{ - Hash: "451e372e48e0f6b1114fa0724aa79fa1", - LastModified: "2009-11-10 23:00:00 +0000 UTC", - Bytes: 14, - Name: "goodbye", - ContentType: "application/octet-stream", - }, - Object{ - Hash: "451e372e48e0f6b1114fa0724aa79fa1", - LastModified: "2009-11-10 23:00:00 +0000 UTC", - Bytes: 14, - Name: "hello", - ContentType: "application/octet-stream", - }, -} - -// ExpectedListNames is the result expected from a call to `List` when just -// object names are requested. -var ExpectedListNames = []string{"hello", "goodbye"} - -// HandleListObjectsInfoSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that -// responds with a `List` response when full info is requested. -func HandleListObjectsInfoSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, `[ - { - "hash": "451e372e48e0f6b1114fa0724aa79fa1", - "last_modified": "2009-11-10 23:00:00 +0000 UTC", - "bytes": 14, - "name": "goodbye", - "content_type": "application/octet-stream" - }, - { - "hash": "451e372e48e0f6b1114fa0724aa79fa1", - "last_modified": "2009-11-10 23:00:00 +0000 UTC", - "bytes": 14, - "name": "hello", - "content_type": "application/octet-stream" - } - ]`) - case "hello": - fmt.Fprintf(w, `[]`) - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) -} - -// HandleListObjectNamesSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that -// responds with a `List` response when only object names are requested. -func HandleListObjectNamesSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "text/plain") - - w.Header().Set("Content-Type", "text/plain") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, "hello\ngoodbye\n") - case "goodbye": - fmt.Fprintf(w, "") - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) -} - -// HandleCreateTextObjectSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler mux -// that responds with a `Create` response. A Content-Type of "text/plain" is expected. -func HandleCreateTextObjectSuccessfully(t *testing.T, content string) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "text/plain") - th.TestHeader(t, r, "Accept", "application/json") - - hash := md5.New() - io.WriteString(hash, content) - localChecksum := hash.Sum(nil) - - w.Header().Set("ETag", fmt.Sprintf("%x", localChecksum)) - w.WriteHeader(http.StatusCreated) - }) -} - -// HandleCreateTextWithCacheControlSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler -// mux that responds with a `Create` response. A Cache-Control of `max-age="3600", public` is expected. -func HandleCreateTextWithCacheControlSuccessfully(t *testing.T, content string) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Cache-Control", `max-age="3600", public`) - th.TestHeader(t, r, "Accept", "application/json") - - hash := md5.New() - io.WriteString(hash, content) - localChecksum := hash.Sum(nil) - - w.Header().Set("ETag", fmt.Sprintf("%x", localChecksum)) - w.WriteHeader(http.StatusCreated) - }) -} - -// HandleCreateTypelessObjectSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler -// mux that responds with a `Create` response. No Content-Type header may be present in the request, so that server- -// side content-type detection will be triggered properly. -func HandleCreateTypelessObjectSuccessfully(t *testing.T, content string) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - if contentType, present := r.Header["Content-Type"]; present { - t.Errorf("Expected Content-Type header to be omitted, but was %#v", contentType) - } - - hash := md5.New() - io.WriteString(hash, content) - localChecksum := hash.Sum(nil) - - w.Header().Set("ETag", fmt.Sprintf("%x", localChecksum)) - w.WriteHeader(http.StatusCreated) - }) -} - -// HandleCopyObjectSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler mux that -// responds with a `Copy` response. -func HandleCopyObjectSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "COPY") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "Destination", "/newTestContainer/newTestObject") - w.WriteHeader(http.StatusCreated) - }) -} - -// HandleDeleteObjectSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler mux that -// responds with a `Delete` response. -func HandleDeleteObjectSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - w.WriteHeader(http.StatusNoContent) - }) -} - -// HandleUpdateObjectSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler mux that -// responds with a `Update` response. -func HandleUpdateObjectSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestHeader(t, r, "X-Object-Meta-Gophercloud-Test", "objects") - w.WriteHeader(http.StatusAccepted) - }) -} - -// HandleGetObjectSuccessfully creates an HTTP handler at `/testContainer/testObject` on the test handler mux that -// responds with a `Get` response. -func HandleGetObjectSuccessfully(t *testing.T) { - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "HEAD") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - w.Header().Add("X-Object-Meta-Gophercloud-Test", "objects") - w.WriteHeader(http.StatusNoContent) - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/results.go b/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/results.go deleted file mode 100644 index ecb2c5458..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/results.go +++ /dev/null @@ -1,438 +0,0 @@ -package objects - -import ( - "fmt" - "io" - "io/ioutil" - "strconv" - "strings" - "time" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - - "github.com/mitchellh/mapstructure" -) - -// Object is a structure that holds information related to a storage object. -type Object struct { - // Bytes is the total number of bytes that comprise the object. - Bytes int64 `json:"bytes" mapstructure:"bytes"` - - // ContentType is the content type of the object. - ContentType string `json:"content_type" mapstructure:"content_type"` - - // Hash represents the MD5 checksum value of the object's content. - Hash string `json:"hash" mapstructure:"hash"` - - // LastModified is the RFC3339Milli time the object was last modified, represented - // as a string. For any given object (obj), this value may be parsed to a time.Time: - // lastModified, err := time.Parse(gophercloud.RFC3339Milli, obj.LastModified) - LastModified string `json:"last_modified" mapstructure:"last_modified"` - - // Name is the unique name for the object. - Name string `json:"name" mapstructure:"name"` -} - -// ObjectPage is a single page of objects that is returned from a call to the -// List function. -type ObjectPage struct { - pagination.MarkerPageBase -} - -// IsEmpty returns true if a ListResult contains no object names. -func (r ObjectPage) IsEmpty() (bool, error) { - names, err := ExtractNames(r) - if err != nil { - return true, err - } - return len(names) == 0, nil -} - -// LastMarker returns the last object name in a ListResult. -func (r ObjectPage) LastMarker() (string, error) { - names, err := ExtractNames(r) - if err != nil { - return "", err - } - if len(names) == 0 { - return "", nil - } - return names[len(names)-1], nil -} - -// ExtractInfo is a function that takes a page of objects and returns their full information. -func ExtractInfo(page pagination.Page) ([]Object, error) { - untyped := page.(ObjectPage).Body.([]interface{}) - results := make([]Object, len(untyped)) - for index, each := range untyped { - object := each.(map[string]interface{}) - err := mapstructure.Decode(object, &results[index]) - if err != nil { - return results, err - } - } - return results, nil -} - -// ExtractNames is a function that takes a page of objects and returns only their names. -func ExtractNames(page pagination.Page) ([]string, error) { - casted := page.(ObjectPage) - ct := casted.Header.Get("Content-Type") - switch { - case strings.HasPrefix(ct, "application/json"): - parsed, err := ExtractInfo(page) - if err != nil { - return nil, err - } - - names := make([]string, 0, len(parsed)) - for _, object := range parsed { - names = append(names, object.Name) - } - - return names, nil - case strings.HasPrefix(ct, "text/plain"): - names := make([]string, 0, 50) - - body := string(page.(ObjectPage).Body.([]uint8)) - for _, name := range strings.Split(body, "\n") { - if len(name) > 0 { - names = append(names, name) - } - } - - return names, nil - case strings.HasPrefix(ct, "text/html"): - return []string{}, nil - default: - return nil, fmt.Errorf("Cannot extract names from response with content-type: [%s]", ct) - } -} - -// DownloadHeader represents the headers returned in the response from a Download request. -type DownloadHeader struct { - AcceptRanges string `mapstructure:"Accept-Ranges"` - ContentDisposition string `mapstructure:"Content-Disposition"` - ContentEncoding string `mapstructure:"Content-Encoding"` - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - DeleteAt time.Time `mapstructure:"-"` - ETag string `mapstructure:"Etag"` - LastModified time.Time `mapstructure:"-"` - ObjectManifest string `mapstructure:"X-Object-Manifest"` - StaticLargeObject bool `mapstructure:"X-Static-Large-Object"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// DownloadResult is a *http.Response that is returned from a call to the Download function. -type DownloadResult struct { - gophercloud.HeaderResult - Body io.ReadCloser -} - -// Extract will return a struct of headers returned from a call to Download. To obtain -// a map of headers, call the ExtractHeader method on the DownloadResult. -func (dr DownloadResult) Extract() (DownloadHeader, error) { - var dh DownloadHeader - if dr.Err != nil { - return dh, dr.Err - } - - if err := gophercloud.DecodeHeader(dr.Header, &dh); err != nil { - return dh, err - } - - if date, ok := dr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, date[0]) - if err != nil { - return dh, err - } - dh.Date = t - } - - if date, ok := dr.Header["Last-Modified"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, date[0]) - if err != nil { - return dh, err - } - dh.LastModified = t - } - - if date, ok := dr.Header["X-Delete-At"]; ok && len(date) > 0 { - unix, err := strconv.ParseInt(date[0], 10, 64) - if err != nil { - return dh, err - } - dh.DeleteAt = time.Unix(unix, 0) - } - - return dh, nil -} - -// ExtractContent is a function that takes a DownloadResult's io.Reader body -// and reads all available data into a slice of bytes. Please be aware that due -// the nature of io.Reader is forward-only - meaning that it can only be read -// once and not rewound. You can recreate a reader from the output of this -// function by using bytes.NewReader(downloadBytes) -func (dr DownloadResult) ExtractContent() ([]byte, error) { - if dr.Err != nil { - return nil, dr.Err - } - body, err := ioutil.ReadAll(dr.Body) - if err != nil { - return nil, err - } - dr.Body.Close() - return body, nil -} - -// GetHeader represents the headers returned in the response from a Get request. -type GetHeader struct { - ContentDisposition string `mapstructure:"Content-Disposition"` - ContentEncoding string `mapstructure:"Content-Encoding"` - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - DeleteAt time.Time `mapstructure:"-"` - ETag string `mapstructure:"Etag"` - LastModified time.Time `mapstructure:"-"` - ObjectManifest string `mapstructure:"X-Object-Manifest"` - StaticLargeObject bool `mapstructure:"X-Static-Large-Object"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// GetResult is a *http.Response that is returned from a call to the Get function. -type GetResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Get. To obtain -// a map of headers, call the ExtractHeader method on the GetResult. -func (gr GetResult) Extract() (GetHeader, error) { - var gh GetHeader - if gr.Err != nil { - return gh, gr.Err - } - - if err := gophercloud.DecodeHeader(gr.Header, &gh); err != nil { - return gh, err - } - - if date, ok := gr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, gr.Header["Date"][0]) - if err != nil { - return gh, err - } - gh.Date = t - } - - if date, ok := gr.Header["Last-Modified"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, gr.Header["Last-Modified"][0]) - if err != nil { - return gh, err - } - gh.LastModified = t - } - - if date, ok := gr.Header["X-Delete-At"]; ok && len(date) > 0 { - unix, err := strconv.ParseInt(date[0], 10, 64) - if err != nil { - return gh, err - } - gh.DeleteAt = time.Unix(unix, 0) - } - - return gh, nil -} - -// ExtractMetadata is a function that takes a GetResult (of type *http.Response) -// and returns the custom metadata associated with the object. -func (gr GetResult) ExtractMetadata() (map[string]string, error) { - if gr.Err != nil { - return nil, gr.Err - } - metadata := make(map[string]string) - for k, v := range gr.Header { - if strings.HasPrefix(k, "X-Object-Meta-") { - key := strings.TrimPrefix(k, "X-Object-Meta-") - metadata[key] = v[0] - } - } - return metadata, nil -} - -// CreateHeader represents the headers returned in the response from a Create request. -type CreateHeader struct { - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - ETag string `mapstructure:"Etag"` - LastModified time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// CreateResult represents the result of a create operation. -type CreateResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Create. To obtain -// a map of headers, call the ExtractHeader method on the CreateResult. -func (cr CreateResult) Extract() (CreateHeader, error) { - var ch CreateHeader - if cr.Err != nil { - return ch, cr.Err - } - - if err := gophercloud.DecodeHeader(cr.Header, &ch); err != nil { - return ch, err - } - - if date, ok := cr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, cr.Header["Date"][0]) - if err != nil { - return ch, err - } - ch.Date = t - } - - if date, ok := cr.Header["Last-Modified"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, cr.Header["Last-Modified"][0]) - if err != nil { - return ch, err - } - ch.LastModified = t - } - - return ch, nil -} - -// UpdateHeader represents the headers returned in the response from a Update request. -type UpdateHeader struct { - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// UpdateResult represents the result of an update operation. -type UpdateResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Update. To obtain -// a map of headers, call the ExtractHeader method on the UpdateResult. -func (ur UpdateResult) Extract() (UpdateHeader, error) { - var uh UpdateHeader - if ur.Err != nil { - return uh, ur.Err - } - - if err := gophercloud.DecodeHeader(ur.Header, &uh); err != nil { - return uh, err - } - - if date, ok := ur.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, ur.Header["Date"][0]) - if err != nil { - return uh, err - } - uh.Date = t - } - - return uh, nil -} - -// DeleteHeader represents the headers returned in the response from a Delete request. -type DeleteHeader struct { - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - Date time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// DeleteResult represents the result of a delete operation. -type DeleteResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Delete. To obtain -// a map of headers, call the ExtractHeader method on the DeleteResult. -func (dr DeleteResult) Extract() (DeleteHeader, error) { - var dh DeleteHeader - if dr.Err != nil { - return dh, dr.Err - } - - if err := gophercloud.DecodeHeader(dr.Header, &dh); err != nil { - return dh, err - } - - if date, ok := dr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, dr.Header["Date"][0]) - if err != nil { - return dh, err - } - dh.Date = t - } - - return dh, nil -} - -// CopyHeader represents the headers returned in the response from a Copy request. -type CopyHeader struct { - ContentLength int64 `mapstructure:"Content-Length"` - ContentType string `mapstructure:"Content-Type"` - CopiedFrom string `mapstructure:"X-Copied-From"` - CopiedFromLastModified time.Time `mapstructure:"-"` - Date time.Time `mapstructure:"-"` - ETag string `mapstructure:"Etag"` - LastModified time.Time `mapstructure:"-"` - TransID string `mapstructure:"X-Trans-Id"` -} - -// CopyResult represents the result of a copy operation. -type CopyResult struct { - gophercloud.HeaderResult -} - -// Extract will return a struct of headers returned from a call to Copy. To obtain -// a map of headers, call the ExtractHeader method on the CopyResult. -func (cr CopyResult) Extract() (CopyHeader, error) { - var ch CopyHeader - if cr.Err != nil { - return ch, cr.Err - } - - if err := gophercloud.DecodeHeader(cr.Header, &ch); err != nil { - return ch, err - } - - if date, ok := cr.Header["Date"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, cr.Header["Date"][0]) - if err != nil { - return ch, err - } - ch.Date = t - } - - if date, ok := cr.Header["Last-Modified"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, cr.Header["Last-Modified"][0]) - if err != nil { - return ch, err - } - ch.LastModified = t - } - - if date, ok := cr.Header["X-Copied-From-Last-Modified"]; ok && len(date) > 0 { - t, err := time.Parse(time.RFC1123, cr.Header["X-Copied-From-Last-Modified"][0]) - if err != nil { - return ch, err - } - ch.CopiedFromLastModified = t - } - - return ch, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/openstack/utils/choose_version.go b/vendor/github.com/rackspace/gophercloud/openstack/utils/choose_version.go deleted file mode 100644 index b697ba816..000000000 --- a/vendor/github.com/rackspace/gophercloud/openstack/utils/choose_version.go +++ /dev/null @@ -1,114 +0,0 @@ -package utils - -import ( - "fmt" - "strings" - - "github.com/rackspace/gophercloud" -) - -// Version is a supported API version, corresponding to a vN package within the appropriate service. -type Version struct { - ID string - Suffix string - Priority int -} - -var goodStatus = map[string]bool{ - "current": true, - "supported": true, - "stable": true, -} - -// ChooseVersion queries the base endpoint of an API to choose the most recent non-experimental alternative from a service's -// published versions. -// It returns the highest-Priority Version among the alternatives that are provided, as well as its corresponding endpoint. -func ChooseVersion(client *gophercloud.ProviderClient, recognized []*Version) (*Version, string, error) { - type linkResp struct { - Href string `json:"href"` - Rel string `json:"rel"` - } - - type valueResp struct { - ID string `json:"id"` - Status string `json:"status"` - Links []linkResp `json:"links"` - } - - type versionsResp struct { - Values []valueResp `json:"values"` - } - - type response struct { - Versions versionsResp `json:"versions"` - } - - normalize := func(endpoint string) string { - if !strings.HasSuffix(endpoint, "/") { - return endpoint + "/" - } - return endpoint - } - identityEndpoint := normalize(client.IdentityEndpoint) - - // If a full endpoint is specified, check version suffixes for a match first. - for _, v := range recognized { - if strings.HasSuffix(identityEndpoint, v.Suffix) { - return v, identityEndpoint, nil - } - } - - var resp response - _, err := client.Request("GET", client.IdentityBase, gophercloud.RequestOpts{ - JSONResponse: &resp, - OkCodes: []int{200, 300}, - }) - - if err != nil { - return nil, "", err - } - - byID := make(map[string]*Version) - for _, version := range recognized { - byID[version.ID] = version - } - - var highest *Version - var endpoint string - - for _, value := range resp.Versions.Values { - href := "" - for _, link := range value.Links { - if link.Rel == "self" { - href = normalize(link.Href) - } - } - - if matching, ok := byID[value.ID]; ok { - // Prefer a version that exactly matches the provided endpoint. - if href == identityEndpoint { - if href == "" { - return nil, "", fmt.Errorf("Endpoint missing in version %s response from %s", value.ID, client.IdentityBase) - } - return matching, href, nil - } - - // Otherwise, find the highest-priority version with a whitelisted status. - if goodStatus[strings.ToLower(value.Status)] { - if highest == nil || matching.Priority > highest.Priority { - highest = matching - endpoint = href - } - } - } - } - - if highest == nil { - return nil, "", fmt.Errorf("No supported version available from endpoint %s", client.IdentityBase) - } - if endpoint == "" { - return nil, "", fmt.Errorf("Endpoint missing in version %s response from %s", highest.ID, client.IdentityBase) - } - - return highest, endpoint, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/pagination/http.go b/vendor/github.com/rackspace/gophercloud/pagination/http.go deleted file mode 100644 index 1b3fe94ab..000000000 --- a/vendor/github.com/rackspace/gophercloud/pagination/http.go +++ /dev/null @@ -1,60 +0,0 @@ -package pagination - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "github.com/rackspace/gophercloud" -) - -// PageResult stores the HTTP response that returned the current page of results. -type PageResult struct { - gophercloud.Result - url.URL -} - -// PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the -// results, interpreting it as JSON if the content type indicates. -func PageResultFrom(resp *http.Response) (PageResult, error) { - var parsedBody interface{} - - defer resp.Body.Close() - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return PageResult{}, err - } - - if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { - err = json.Unmarshal(rawBody, &parsedBody) - if err != nil { - return PageResult{}, err - } - } else { - parsedBody = rawBody - } - - return PageResultFromParsed(resp, parsedBody), err -} - -// PageResultFromParsed constructs a PageResult from an HTTP response that has already had its -// body parsed as JSON (and closed). -func PageResultFromParsed(resp *http.Response, body interface{}) PageResult { - return PageResult{ - Result: gophercloud.Result{ - Body: body, - Header: resp.Header, - }, - URL: *resp.Request.URL, - } -} - -// Request performs an HTTP request and extracts the http.Response from the result. -func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (*http.Response, error) { - return client.Request("GET", url, gophercloud.RequestOpts{ - MoreHeaders: headers, - OkCodes: []int{200, 204}, - }) -} diff --git a/vendor/github.com/rackspace/gophercloud/pagination/linked.go b/vendor/github.com/rackspace/gophercloud/pagination/linked.go deleted file mode 100644 index e9bd8dec9..000000000 --- a/vendor/github.com/rackspace/gophercloud/pagination/linked.go +++ /dev/null @@ -1,67 +0,0 @@ -package pagination - -import "fmt" - -// LinkedPageBase may be embedded to implement a page that provides navigational "Next" and "Previous" links within its result. -type LinkedPageBase struct { - PageResult - - // LinkPath lists the keys that should be traversed within a response to arrive at the "next" pointer. - // If any link along the path is missing, an empty URL will be returned. - // If any link results in an unexpected value type, an error will be returned. - // When left as "nil", []string{"links", "next"} will be used as a default. - LinkPath []string -} - -// NextPageURL extracts the pagination structure from a JSON response and returns the "next" link, if one is present. -// It assumes that the links are available in a "links" element of the top-level response object. -// If this is not the case, override NextPageURL on your result type. -func (current LinkedPageBase) NextPageURL() (string, error) { - var path []string - var key string - - if current.LinkPath == nil { - path = []string{"links", "next"} - } else { - path = current.LinkPath - } - - submap, ok := current.Body.(map[string]interface{}) - if !ok { - return "", fmt.Errorf("Expected an object, but was %#v", current.Body) - } - - for { - key, path = path[0], path[1:len(path)] - - value, ok := submap[key] - if !ok { - return "", nil - } - - if len(path) > 0 { - submap, ok = value.(map[string]interface{}) - if !ok { - return "", fmt.Errorf("Expected an object, but was %#v", value) - } - } else { - if value == nil { - // Actual null element. - return "", nil - } - - url, ok := value.(string) - if !ok { - return "", fmt.Errorf("Expected a string, but was %#v", value) - } - - return url, nil - } - } -} - -// GetBody returns the linked page's body. This method is needed to satisfy the -// Page interface. -func (current LinkedPageBase) GetBody() interface{} { - return current.Body -} diff --git a/vendor/github.com/rackspace/gophercloud/pagination/marker.go b/vendor/github.com/rackspace/gophercloud/pagination/marker.go deleted file mode 100644 index f355afc54..000000000 --- a/vendor/github.com/rackspace/gophercloud/pagination/marker.go +++ /dev/null @@ -1,40 +0,0 @@ -package pagination - -// MarkerPage is a stricter Page interface that describes additional functionality required for use with NewMarkerPager. -// For convenience, embed the MarkedPageBase struct. -type MarkerPage interface { - Page - - // LastMarker returns the last "marker" value on this page. - LastMarker() (string, error) -} - -// MarkerPageBase is a page in a collection that's paginated by "limit" and "marker" query parameters. -type MarkerPageBase struct { - PageResult - - // Owner is a reference to the embedding struct. - Owner MarkerPage -} - -// NextPageURL generates the URL for the page of results after this one. -func (current MarkerPageBase) NextPageURL() (string, error) { - currentURL := current.URL - - mark, err := current.Owner.LastMarker() - if err != nil { - return "", err - } - - q := currentURL.Query() - q.Set("marker", mark) - currentURL.RawQuery = q.Encode() - - return currentURL.String(), nil -} - -// GetBody returns the linked page's body. This method is needed to satisfy the -// Page interface. -func (current MarkerPageBase) GetBody() interface{} { - return current.Body -} diff --git a/vendor/github.com/rackspace/gophercloud/pagination/null.go b/vendor/github.com/rackspace/gophercloud/pagination/null.go deleted file mode 100644 index ae57e1886..000000000 --- a/vendor/github.com/rackspace/gophercloud/pagination/null.go +++ /dev/null @@ -1,20 +0,0 @@ -package pagination - -// nullPage is an always-empty page that trivially satisfies all Page interfacts. -// It's useful to be returned along with an error. -type nullPage struct{} - -// NextPageURL always returns "" to indicate that there are no more pages to return. -func (p nullPage) NextPageURL() (string, error) { - return "", nil -} - -// IsEmpty always returns true to prevent iteration over nullPages. -func (p nullPage) IsEmpty() (bool, error) { - return true, nil -} - -// LastMark always returns "" because the nullPage contains no items to have a mark. -func (p nullPage) LastMark() (string, error) { - return "", nil -} diff --git a/vendor/github.com/rackspace/gophercloud/pagination/pager.go b/vendor/github.com/rackspace/gophercloud/pagination/pager.go deleted file mode 100644 index 6f1ca046f..000000000 --- a/vendor/github.com/rackspace/gophercloud/pagination/pager.go +++ /dev/null @@ -1,238 +0,0 @@ -package pagination - -import ( - "errors" - "fmt" - "net/http" - "reflect" - "strings" - - "github.com/rackspace/gophercloud" -) - -var ( - // ErrPageNotAvailable is returned from a Pager when a next or previous page is requested, but does not exist. - ErrPageNotAvailable = errors.New("The requested page does not exist.") -) - -// Page must be satisfied by the result type of any resource collection. -// It allows clients to interact with the resource uniformly, regardless of whether or not or how it's paginated. -// Generally, rather than implementing this interface directly, implementors should embed one of the concrete PageBase structs, -// instead. -// Depending on the pagination strategy of a particular resource, there may be an additional subinterface that the result type -// will need to implement. -type Page interface { - - // NextPageURL generates the URL for the page of data that follows this collection. - // Return "" if no such page exists. - NextPageURL() (string, error) - - // IsEmpty returns true if this Page has no items in it. - IsEmpty() (bool, error) - - // GetBody returns the Page Body. This is used in the `AllPages` method. - GetBody() interface{} -} - -// Pager knows how to advance through a specific resource collection, one page at a time. -type Pager struct { - client *gophercloud.ServiceClient - - initialURL string - - createPage func(r PageResult) Page - - Err error - - // Headers supplies additional HTTP headers to populate on each paged request. - Headers map[string]string -} - -// NewPager constructs a manually-configured pager. -// Supply the URL for the first page, a function that requests a specific page given a URL, and a function that counts a page. -func NewPager(client *gophercloud.ServiceClient, initialURL string, createPage func(r PageResult) Page) Pager { - return Pager{ - client: client, - initialURL: initialURL, - createPage: createPage, - } -} - -// WithPageCreator returns a new Pager that substitutes a different page creation function. This is -// useful for overriding List functions in delegation. -func (p Pager) WithPageCreator(createPage func(r PageResult) Page) Pager { - return Pager{ - client: p.client, - initialURL: p.initialURL, - createPage: createPage, - } -} - -func (p Pager) fetchNextPage(url string) (Page, error) { - resp, err := Request(p.client, p.Headers, url) - if err != nil { - return nil, err - } - - remembered, err := PageResultFrom(resp) - if err != nil { - return nil, err - } - - return p.createPage(remembered), nil -} - -// EachPage iterates over each page returned by a Pager, yielding one at a time to a handler function. -// Return "false" from the handler to prematurely stop iterating. -func (p Pager) EachPage(handler func(Page) (bool, error)) error { - if p.Err != nil { - return p.Err - } - currentURL := p.initialURL - for { - currentPage, err := p.fetchNextPage(currentURL) - if err != nil { - return err - } - - empty, err := currentPage.IsEmpty() - if err != nil { - return err - } - if empty { - return nil - } - - ok, err := handler(currentPage) - if err != nil { - return err - } - if !ok { - return nil - } - - currentURL, err = currentPage.NextPageURL() - if err != nil { - return err - } - if currentURL == "" { - return nil - } - } -} - -// AllPages returns all the pages from a `List` operation in a single page, -// allowing the user to retrieve all the pages at once. -func (p Pager) AllPages() (Page, error) { - // pagesSlice holds all the pages until they get converted into as Page Body. - var pagesSlice []interface{} - // body will contain the final concatenated Page body. - var body reflect.Value - - // Grab a test page to ascertain the page body type. - testPage, err := p.fetchNextPage(p.initialURL) - if err != nil { - return nil, err - } - // Store the page type so we can use reflection to create a new mega-page of - // that type. - pageType := reflect.TypeOf(testPage) - - // if it's a single page, just return the testPage (first page) - if _, found := pageType.FieldByName("SinglePageBase"); found { - return testPage, nil - } - - // Switch on the page body type. Recognized types are `map[string]interface{}`, - // `[]byte`, and `[]interface{}`. - switch testPage.GetBody().(type) { - case map[string]interface{}: - // key is the map key for the page body if the body type is `map[string]interface{}`. - var key string - // Iterate over the pages to concatenate the bodies. - err := p.EachPage(func(page Page) (bool, error) { - b := page.GetBody().(map[string]interface{}) - for k := range b { - // If it's a linked page, we don't want the `links`, we want the other one. - if !strings.HasSuffix(k, "links") { - key = k - } - } - switch keyType := b[key].(type) { - case map[string]interface{}: - pagesSlice = append(pagesSlice, keyType) - case []interface{}: - pagesSlice = append(pagesSlice, b[key].([]interface{})...) - default: - return false, fmt.Errorf("Unsupported page body type: %+v", keyType) - } - return true, nil - }) - if err != nil { - return nil, err - } - // Set body to value of type `map[string]interface{}` - body = reflect.MakeMap(reflect.MapOf(reflect.TypeOf(key), reflect.TypeOf(pagesSlice))) - body.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(pagesSlice)) - case []byte: - // Iterate over the pages to concatenate the bodies. - err := p.EachPage(func(page Page) (bool, error) { - b := page.GetBody().([]byte) - pagesSlice = append(pagesSlice, b) - // seperate pages with a comma - pagesSlice = append(pagesSlice, []byte{10}) - return true, nil - }) - if err != nil { - return nil, err - } - if len(pagesSlice) > 0 { - // Remove the trailing comma. - pagesSlice = pagesSlice[:len(pagesSlice)-1] - } - var b []byte - // Combine the slice of slices in to a single slice. - for _, slice := range pagesSlice { - b = append(b, slice.([]byte)...) - } - // Set body to value of type `bytes`. - body = reflect.New(reflect.TypeOf(b)).Elem() - body.SetBytes(b) - case []interface{}: - // Iterate over the pages to concatenate the bodies. - err := p.EachPage(func(page Page) (bool, error) { - b := page.GetBody().([]interface{}) - pagesSlice = append(pagesSlice, b...) - return true, nil - }) - if err != nil { - return nil, err - } - // Set body to value of type `[]interface{}` - body = reflect.MakeSlice(reflect.TypeOf(pagesSlice), len(pagesSlice), len(pagesSlice)) - for i, s := range pagesSlice { - body.Index(i).Set(reflect.ValueOf(s)) - } - default: - return nil, fmt.Errorf("Page body has unrecognized type.") - } - - // Each `Extract*` function is expecting a specific type of page coming back, - // otherwise the type assertion in those functions will fail. pageType is needed - // to create a type in this method that has the same type that the `Extract*` - // function is expecting and set the Body of that object to the concatenated - // pages. - page := reflect.New(pageType) - // Set the page body to be the concatenated pages. - page.Elem().FieldByName("Body").Set(body) - // Set any additional headers that were pass along. The `objectstorage` pacakge, - // for example, passes a Content-Type header. - h := make(http.Header) - for k, v := range p.Headers { - h.Add(k, v) - } - page.Elem().FieldByName("Header").Set(reflect.ValueOf(h)) - // Type assert the page to a Page interface so that the type assertion in the - // `Extract*` methods will work. - return page.Elem().Interface().(Page), err -} diff --git a/vendor/github.com/rackspace/gophercloud/pagination/pkg.go b/vendor/github.com/rackspace/gophercloud/pagination/pkg.go deleted file mode 100644 index 912daea36..000000000 --- a/vendor/github.com/rackspace/gophercloud/pagination/pkg.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs. -*/ -package pagination diff --git a/vendor/github.com/rackspace/gophercloud/pagination/single.go b/vendor/github.com/rackspace/gophercloud/pagination/single.go deleted file mode 100644 index f78d4ab5d..000000000 --- a/vendor/github.com/rackspace/gophercloud/pagination/single.go +++ /dev/null @@ -1,15 +0,0 @@ -package pagination - -// SinglePageBase may be embedded in a Page that contains all of the results from an operation at once. -type SinglePageBase PageResult - -// NextPageURL always returns "" to indicate that there are no more pages to return. -func (current SinglePageBase) NextPageURL() (string, error) { - return "", nil -} - -// GetBody returns the single page's body. This method is needed to satisfy the -// Page interface. -func (current SinglePageBase) GetBody() interface{} { - return current.Body -} diff --git a/vendor/github.com/rackspace/gophercloud/params.go b/vendor/github.com/rackspace/gophercloud/params.go deleted file mode 100644 index 4d0f1e6e0..000000000 --- a/vendor/github.com/rackspace/gophercloud/params.go +++ /dev/null @@ -1,271 +0,0 @@ -package gophercloud - -import ( - "fmt" - "net/url" - "reflect" - "strconv" - "strings" - "time" -) - -// EnabledState is a convenience type, mostly used in Create and Update -// operations. Because the zero value of a bool is FALSE, we need to use a -// pointer instead to indicate zero-ness. -type EnabledState *bool - -// Convenience vars for EnabledState values. -var ( - iTrue = true - iFalse = false - - Enabled EnabledState = &iTrue - Disabled EnabledState = &iFalse -) - -// IntToPointer is a function for converting integers into integer pointers. -// This is useful when passing in options to operations. -func IntToPointer(i int) *int { - return &i -} - -/* -MaybeString is an internal function to be used by request methods in individual -resource packages. - -It takes a string that might be a zero value and returns either a pointer to its -address or nil. This is useful for allowing users to conveniently omit values -from an options struct by leaving them zeroed, but still pass nil to the JSON -serializer so they'll be omitted from the request body. -*/ -func MaybeString(original string) *string { - if original != "" { - return &original - } - return nil -} - -/* -MaybeInt is an internal function to be used by request methods in individual -resource packages. - -Like MaybeString, it accepts an int that may or may not be a zero value, and -returns either a pointer to its address or nil. It's intended to hint that the -JSON serializer should omit its field. -*/ -func MaybeInt(original int) *int { - if original != 0 { - return &original - } - return nil -} - -var t time.Time - -func isZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Func, reflect.Map, reflect.Slice: - return v.IsNil() - case reflect.Array: - z := true - for i := 0; i < v.Len(); i++ { - z = z && isZero(v.Index(i)) - } - return z - case reflect.Struct: - if v.Type() == reflect.TypeOf(t) { - if v.Interface().(time.Time).IsZero() { - return true - } - return false - } - z := true - for i := 0; i < v.NumField(); i++ { - z = z && isZero(v.Field(i)) - } - return z - } - // Compare other types directly: - z := reflect.Zero(v.Type()) - return v.Interface() == z.Interface() -} - -/* -BuildQueryString is an internal function to be used by request methods in -individual resource packages. - -It accepts a tagged structure and expands it into a URL struct. Field names are -converted into query parameters based on a "q" tag. For example: - - type struct Something { - Bar string `q:"x_bar"` - Baz int `q:"lorem_ipsum"` - } - - instance := Something{ - Bar: "AAA", - Baz: "BBB", - } - -will be converted into "?x_bar=AAA&lorem_ipsum=BBB". - -The struct's fields may be strings, integers, or boolean values. Fields left at -their type's zero value will be omitted from the query. -*/ -func BuildQueryString(opts interface{}) (*url.URL, error) { - optsValue := reflect.ValueOf(opts) - if optsValue.Kind() == reflect.Ptr { - optsValue = optsValue.Elem() - } - - optsType := reflect.TypeOf(opts) - if optsType.Kind() == reflect.Ptr { - optsType = optsType.Elem() - } - - params := url.Values{} - - if optsValue.Kind() == reflect.Struct { - for i := 0; i < optsValue.NumField(); i++ { - v := optsValue.Field(i) - f := optsType.Field(i) - qTag := f.Tag.Get("q") - - // if the field has a 'q' tag, it goes in the query string - if qTag != "" { - tags := strings.Split(qTag, ",") - - // if the field is set, add it to the slice of query pieces - if !isZero(v) { - switch v.Kind() { - case reflect.String: - params.Add(tags[0], v.String()) - case reflect.Int: - params.Add(tags[0], strconv.FormatInt(v.Int(), 10)) - case reflect.Bool: - params.Add(tags[0], strconv.FormatBool(v.Bool())) - case reflect.Slice: - switch v.Type().Elem() { - case reflect.TypeOf(0): - for i := 0; i < v.Len(); i++ { - params.Add(tags[0], strconv.FormatInt(v.Index(i).Int(), 10)) - } - default: - for i := 0; i < v.Len(); i++ { - params.Add(tags[0], v.Index(i).String()) - } - } - } - } else { - // Otherwise, the field is not set. - if len(tags) == 2 && tags[1] == "required" { - // And the field is required. Return an error. - return nil, fmt.Errorf("Required query parameter [%s] not set.", f.Name) - } - } - } - } - - return &url.URL{RawQuery: params.Encode()}, nil - } - // Return an error if the underlying type of 'opts' isn't a struct. - return nil, fmt.Errorf("Options type is not a struct.") -} - -/* -BuildHeaders is an internal function to be used by request methods in -individual resource packages. - -It accepts an arbitrary tagged structure and produces a string map that's -suitable for use as the HTTP headers of an outgoing request. Field names are -mapped to header names based in "h" tags. - - type struct Something { - Bar string `h:"x_bar"` - Baz int `h:"lorem_ipsum"` - } - - instance := Something{ - Bar: "AAA", - Baz: "BBB", - } - -will be converted into: - - map[string]string{ - "x_bar": "AAA", - "lorem_ipsum": "BBB", - } - -Untagged fields and fields left at their zero values are skipped. Integers, -booleans and string values are supported. -*/ -func BuildHeaders(opts interface{}) (map[string]string, error) { - optsValue := reflect.ValueOf(opts) - if optsValue.Kind() == reflect.Ptr { - optsValue = optsValue.Elem() - } - - optsType := reflect.TypeOf(opts) - if optsType.Kind() == reflect.Ptr { - optsType = optsType.Elem() - } - - optsMap := make(map[string]string) - if optsValue.Kind() == reflect.Struct { - for i := 0; i < optsValue.NumField(); i++ { - v := optsValue.Field(i) - f := optsType.Field(i) - hTag := f.Tag.Get("h") - - // if the field has a 'h' tag, it goes in the header - if hTag != "" { - tags := strings.Split(hTag, ",") - - // if the field is set, add it to the slice of query pieces - if !isZero(v) { - switch v.Kind() { - case reflect.String: - optsMap[tags[0]] = v.String() - case reflect.Int: - optsMap[tags[0]] = strconv.FormatInt(v.Int(), 10) - case reflect.Bool: - optsMap[tags[0]] = strconv.FormatBool(v.Bool()) - } - } else { - // Otherwise, the field is not set. - if len(tags) == 2 && tags[1] == "required" { - // And the field is required. Return an error. - return optsMap, fmt.Errorf("Required header not set.") - } - } - } - - } - return optsMap, nil - } - // Return an error if the underlying type of 'opts' isn't a struct. - return optsMap, fmt.Errorf("Options type is not a struct.") -} - -// IDSliceToQueryString takes a slice of elements and converts them into a query -// string. For example, if name=foo and slice=[]int{20, 40, 60}, then the -// result would be `?name=20&name=40&name=60' -func IDSliceToQueryString(name string, ids []int) string { - str := "" - for k, v := range ids { - if k == 0 { - str += "?" - } else { - str += "&" - } - str += fmt.Sprintf("%s=%s", name, strconv.Itoa(v)) - } - return str -} - -// IntWithinRange returns TRUE if an integer falls within a defined range, and -// FALSE if not. -func IntWithinRange(val, min, max int) bool { - return val > min && val < max -} diff --git a/vendor/github.com/rackspace/gophercloud/provider_client.go b/vendor/github.com/rackspace/gophercloud/provider_client.go deleted file mode 100644 index 53fce7370..000000000 --- a/vendor/github.com/rackspace/gophercloud/provider_client.go +++ /dev/null @@ -1,331 +0,0 @@ -package gophercloud - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// DefaultUserAgent is the default User-Agent string set in the request header. -const DefaultUserAgent = "gophercloud/1.0.0" - -// UserAgent represents a User-Agent header. -type UserAgent struct { - // prepend is the slice of User-Agent strings to prepend to DefaultUserAgent. - // All the strings to prepend are accumulated and prepended in the Join method. - prepend []string -} - -// Prepend prepends a user-defined string to the default User-Agent string. Users -// may pass in one or more strings to prepend. -func (ua *UserAgent) Prepend(s ...string) { - ua.prepend = append(s, ua.prepend...) -} - -// Join concatenates all the user-defined User-Agend strings with the default -// Gophercloud User-Agent string. -func (ua *UserAgent) Join() string { - uaSlice := append(ua.prepend, DefaultUserAgent) - return strings.Join(uaSlice, " ") -} - -// ProviderClient stores details that are required to interact with any -// services within a specific provider's API. -// -// Generally, you acquire a ProviderClient by calling the NewClient method in -// the appropriate provider's child package, providing whatever authentication -// credentials are required. -type ProviderClient struct { - // IdentityBase is the base URL used for a particular provider's identity - // service - it will be used when issuing authenticatation requests. It - // should point to the root resource of the identity service, not a specific - // identity version. - IdentityBase string - - // IdentityEndpoint is the identity endpoint. This may be a specific version - // of the identity service. If this is the case, this endpoint is used rather - // than querying versions first. - IdentityEndpoint string - - // TokenID is the ID of the most recently issued valid token. - TokenID string - - // EndpointLocator describes how this provider discovers the endpoints for - // its constituent services. - EndpointLocator EndpointLocator - - // HTTPClient allows users to interject arbitrary http, https, or other transit behaviors. - HTTPClient http.Client - - // UserAgent represents the User-Agent header in the HTTP request. - UserAgent UserAgent - - // ReauthFunc is the function used to re-authenticate the user if the request - // fails with a 401 HTTP response code. This a needed because there may be multiple - // authentication functions for different Identity service versions. - ReauthFunc func() error -} - -// AuthenticatedHeaders returns a map of HTTP headers that are common for all -// authenticated service requests. -func (client *ProviderClient) AuthenticatedHeaders() map[string]string { - if client.TokenID == "" { - return map[string]string{} - } - return map[string]string{"X-Auth-Token": client.TokenID} -} - -// RequestOpts customizes the behavior of the provider.Request() method. -type RequestOpts struct { - // JSONBody, if provided, will be encoded as JSON and used as the body of the HTTP request. The - // content type of the request will default to "application/json" unless overridden by MoreHeaders. - // It's an error to specify both a JSONBody and a RawBody. - JSONBody interface{} - // RawBody contains an io.ReadSeeker that will be consumed by the request directly. No content-type - // will be set unless one is provided explicitly by MoreHeaders. - RawBody io.ReadSeeker - - // JSONResponse, if provided, will be populated with the contents of the response body parsed as - // JSON. - JSONResponse interface{} - // OkCodes contains a list of numeric HTTP status codes that should be interpreted as success. If - // the response has a different code, an error will be returned. - OkCodes []int - - // MoreHeaders specifies additional HTTP headers to be provide on the request. If a header is - // provided with a blank value (""), that header will be *omitted* instead: use this to suppress - // the default Accept header or an inferred Content-Type, for example. - MoreHeaders map[string]string -} - -// UnexpectedResponseCodeError is returned by the Request method when a response code other than -// those listed in OkCodes is encountered. -type UnexpectedResponseCodeError struct { - URL string - Method string - Expected []int - Actual int - Body []byte -} - -func (err *UnexpectedResponseCodeError) Error() string { - return fmt.Sprintf( - "Expected HTTP response code %v when accessing [%s %s], but got %d instead\n%s", - err.Expected, err.Method, err.URL, err.Actual, err.Body, - ) -} - -var applicationJSON = "application/json" - -// Request performs an HTTP request using the ProviderClient's current HTTPClient. An authentication -// header will automatically be provided. -func (client *ProviderClient) Request(method, url string, options RequestOpts) (*http.Response, error) { - var body io.ReadSeeker - var contentType *string - - // Derive the content body by either encoding an arbitrary object as JSON, or by taking a provided - // io.ReadSeeker as-is. Default the content-type to application/json. - if options.JSONBody != nil { - if options.RawBody != nil { - panic("Please provide only one of JSONBody or RawBody to gophercloud.Request().") - } - - rendered, err := json.Marshal(options.JSONBody) - if err != nil { - return nil, err - } - - body = bytes.NewReader(rendered) - contentType = &applicationJSON - } - - if options.RawBody != nil { - body = options.RawBody - } - - // Construct the http.Request. - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - // Populate the request headers. Apply options.MoreHeaders last, to give the caller the chance to - // modify or omit any header. - if contentType != nil { - req.Header.Set("Content-Type", *contentType) - } - req.Header.Set("Accept", applicationJSON) - - for k, v := range client.AuthenticatedHeaders() { - req.Header.Add(k, v) - } - - // Set the User-Agent header - req.Header.Set("User-Agent", client.UserAgent.Join()) - - if options.MoreHeaders != nil { - for k, v := range options.MoreHeaders { - if v != "" { - req.Header.Set(k, v) - } else { - req.Header.Del(k) - } - } - } - - // Set connection parameter to close the connection immediately when we've got the response - req.Close = true - - // Issue the request. - resp, err := client.HTTPClient.Do(req) - if err != nil { - return nil, err - } - - if resp.StatusCode == http.StatusUnauthorized { - if client.ReauthFunc != nil { - err = client.ReauthFunc() - if err != nil { - return nil, fmt.Errorf("Error trying to re-authenticate: %s", err) - } - if options.RawBody != nil { - options.RawBody.Seek(0, 0) - } - resp.Body.Close() - resp, err = client.Request(method, url, options) - if err != nil { - return nil, fmt.Errorf("Successfully re-authenticated, but got error executing request: %s", err) - } - - return resp, nil - } - } - - // Allow default OkCodes if none explicitly set - if options.OkCodes == nil { - options.OkCodes = defaultOkCodes(method) - } - - // Validate the HTTP response status. - var ok bool - for _, code := range options.OkCodes { - if resp.StatusCode == code { - ok = true - break - } - } - if !ok { - body, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - return resp, &UnexpectedResponseCodeError{ - URL: url, - Method: method, - Expected: options.OkCodes, - Actual: resp.StatusCode, - Body: body, - } - } - - // Parse the response body as JSON, if requested to do so. - if options.JSONResponse != nil { - defer resp.Body.Close() - if err := json.NewDecoder(resp.Body).Decode(options.JSONResponse); err != nil { - return nil, err - } - } - - return resp, nil -} - -func defaultOkCodes(method string) []int { - switch { - case method == "GET": - return []int{200} - case method == "POST": - return []int{201, 202} - case method == "PUT": - return []int{201, 202} - case method == "PATCH": - return []int{200, 204} - case method == "DELETE": - return []int{202, 204} - } - - return []int{} -} - -func (client *ProviderClient) Get(url string, JSONResponse *interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = &RequestOpts{} - } - if JSONResponse != nil { - opts.JSONResponse = JSONResponse - } - return client.Request("GET", url, *opts) -} - -func (client *ProviderClient) Post(url string, JSONBody interface{}, JSONResponse *interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = &RequestOpts{} - } - - if v, ok := (JSONBody).(io.ReadSeeker); ok { - opts.RawBody = v - } else if JSONBody != nil { - opts.JSONBody = JSONBody - } - - if JSONResponse != nil { - opts.JSONResponse = JSONResponse - } - - return client.Request("POST", url, *opts) -} - -func (client *ProviderClient) Put(url string, JSONBody interface{}, JSONResponse *interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = &RequestOpts{} - } - - if v, ok := (JSONBody).(io.ReadSeeker); ok { - opts.RawBody = v - } else if JSONBody != nil { - opts.JSONBody = JSONBody - } - - if JSONResponse != nil { - opts.JSONResponse = JSONResponse - } - - return client.Request("PUT", url, *opts) -} - -func (client *ProviderClient) Patch(url string, JSONBody interface{}, JSONResponse *interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = &RequestOpts{} - } - - if v, ok := (JSONBody).(io.ReadSeeker); ok { - opts.RawBody = v - } else if JSONBody != nil { - opts.JSONBody = JSONBody - } - - if JSONResponse != nil { - opts.JSONResponse = JSONResponse - } - - return client.Request("PATCH", url, *opts) -} - -func (client *ProviderClient) Delete(url string, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = &RequestOpts{} - } - - return client.Request("DELETE", url, *opts) -} diff --git a/vendor/github.com/rackspace/gophercloud/results.go b/vendor/github.com/rackspace/gophercloud/results.go deleted file mode 100644 index 27fd1b60f..000000000 --- a/vendor/github.com/rackspace/gophercloud/results.go +++ /dev/null @@ -1,153 +0,0 @@ -package gophercloud - -import ( - "encoding/json" - "net/http" - "reflect" - - "github.com/mitchellh/mapstructure" -) - -/* -Result is an internal type to be used by individual resource packages, but its -methods will be available on a wide variety of user-facing embedding types. - -It acts as a base struct that other Result types, returned from request -functions, can embed for convenience. All Results capture basic information -from the HTTP transaction that was performed, including the response body, -HTTP headers, and any errors that happened. - -Generally, each Result type will have an Extract method that can be used to -further interpret the result's payload in a specific context. Extensions or -providers can then provide additional extraction functions to pull out -provider- or extension-specific information as well. -*/ -type Result struct { - // Body is the payload of the HTTP response from the server. In most cases, - // this will be the deserialized JSON structure. - Body interface{} - - // Header contains the HTTP header structure from the original response. - Header http.Header - - // Err is an error that occurred during the operation. It's deferred until - // extraction to make it easier to chain the Extract call. - Err error -} - -// PrettyPrintJSON creates a string containing the full response body as -// pretty-printed JSON. It's useful for capturing test fixtures and for -// debugging extraction bugs. If you include its output in an issue related to -// a buggy extraction function, we will all love you forever. -func (r Result) PrettyPrintJSON() string { - pretty, err := json.MarshalIndent(r.Body, "", " ") - if err != nil { - panic(err.Error()) - } - return string(pretty) -} - -// ErrResult is an internal type to be used by individual resource packages, but -// its methods will be available on a wide variety of user-facing embedding -// types. -// -// It represents results that only contain a potential error and -// nothing else. Usually, if the operation executed successfully, the Err field -// will be nil; otherwise it will be stocked with a relevant error. Use the -// ExtractErr method -// to cleanly pull it out. -type ErrResult struct { - Result -} - -// ExtractErr is a function that extracts error information, or nil, from a result. -func (r ErrResult) ExtractErr() error { - return r.Err -} - -/* -HeaderResult is an internal type to be used by individual resource packages, but -its methods will be available on a wide variety of user-facing embedding types. - -It represents a result that only contains an error (possibly nil) and an -http.Header. This is used, for example, by the objectstorage packages in -openstack, because most of the operations don't return response bodies, but do -have relevant information in headers. -*/ -type HeaderResult struct { - Result -} - -// ExtractHeader will return the http.Header and error from the HeaderResult. -// -// header, err := objects.Create(client, "my_container", objects.CreateOpts{}).ExtractHeader() -func (hr HeaderResult) ExtractHeader() (http.Header, error) { - return hr.Header, hr.Err -} - -// DecodeHeader is a function that decodes a header (usually of type map[string]interface{}) to -// another type (usually a struct). This function is used by the objectstorage package to give -// users access to response headers without having to query a map. A DecodeHookFunction is used, -// because OpenStack-based clients return header values as arrays (Go slices). -func DecodeHeader(from, to interface{}) error { - config := &mapstructure.DecoderConfig{ - DecodeHook: func(from, to reflect.Kind, data interface{}) (interface{}, error) { - if from == reflect.Slice { - return data.([]string)[0], nil - } - return data, nil - }, - Result: to, - WeaklyTypedInput: true, - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return err - } - if err := decoder.Decode(from); err != nil { - return err - } - return nil -} - -// RFC3339Milli describes a common time format used by some API responses. -const RFC3339Milli = "2006-01-02T15:04:05.999999Z" - -// Time format used in cloud orchestration -const STACK_TIME_FMT = "2006-01-02T15:04:05" - -/* -Link is an internal type to be used in packages of collection resources that are -paginated in a certain way. - -It's a response substructure common to many paginated collection results that is -used to point to related pages. Usually, the one we care about is the one with -Rel field set to "next". -*/ -type Link struct { - Href string `mapstructure:"href"` - Rel string `mapstructure:"rel"` -} - -/* -ExtractNextURL is an internal function useful for packages of collection -resources that are paginated in a certain way. - -It attempts attempts to extract the "next" URL from slice of Link structs, or -"" if no such URL is present. -*/ -func ExtractNextURL(links []Link) (string, error) { - var url string - - for _, l := range links { - if l.Rel == "next" { - url = l.Href - } - } - - if url == "" { - return "", nil - } - - return url, nil -} diff --git a/vendor/github.com/rackspace/gophercloud/service_client.go b/vendor/github.com/rackspace/gophercloud/service_client.go deleted file mode 100644 index 3490da05f..000000000 --- a/vendor/github.com/rackspace/gophercloud/service_client.go +++ /dev/null @@ -1,32 +0,0 @@ -package gophercloud - -import "strings" - -// ServiceClient stores details required to interact with a specific service API implemented by a provider. -// Generally, you'll acquire these by calling the appropriate `New` method on a ProviderClient. -type ServiceClient struct { - // ProviderClient is a reference to the provider that implements this service. - *ProviderClient - - // Endpoint is the base URL of the service's API, acquired from a service catalog. - // It MUST end with a /. - Endpoint string - - // ResourceBase is the base URL shared by the resources within a service's API. It should include - // the API version and, like Endpoint, MUST end with a / if set. If not set, the Endpoint is used - // as-is, instead. - ResourceBase string -} - -// ResourceBaseURL returns the base URL of any resources used by this service. It MUST end with a /. -func (client *ServiceClient) ResourceBaseURL() string { - if client.ResourceBase != "" { - return client.ResourceBase - } - return client.Endpoint -} - -// ServiceURL constructs a URL for a resource belonging to this provider. -func (client *ServiceClient) ServiceURL(parts ...string) string { - return client.ResourceBaseURL() + strings.Join(parts, "/") -} diff --git a/vendor/github.com/rackspace/gophercloud/testhelper/client/fake.go b/vendor/github.com/rackspace/gophercloud/testhelper/client/fake.go deleted file mode 100644 index 5b69b058f..000000000 --- a/vendor/github.com/rackspace/gophercloud/testhelper/client/fake.go +++ /dev/null @@ -1,17 +0,0 @@ -package client - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/testhelper" -) - -// Fake token to use. -const TokenID = "cbc36478b0bd8e67e89469c7749d4127" - -// ServiceClient returns a generic service client for use in tests. -func ServiceClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{ - ProviderClient: &gophercloud.ProviderClient{TokenID: TokenID}, - Endpoint: testhelper.Endpoint(), - } -} diff --git a/vendor/github.com/rackspace/gophercloud/testhelper/convenience.go b/vendor/github.com/rackspace/gophercloud/testhelper/convenience.go deleted file mode 100644 index cf33e1ad1..000000000 --- a/vendor/github.com/rackspace/gophercloud/testhelper/convenience.go +++ /dev/null @@ -1,329 +0,0 @@ -package testhelper - -import ( - "encoding/json" - "fmt" - "path/filepath" - "reflect" - "runtime" - "strings" - "testing" -) - -const ( - logBodyFmt = "\033[1;31m%s %s\033[0m" - greenCode = "\033[0m\033[1;32m" - yellowCode = "\033[0m\033[1;33m" - resetCode = "\033[0m\033[1;31m" -) - -func prefix(depth int) string { - _, file, line, _ := runtime.Caller(depth) - return fmt.Sprintf("Failure in %s, line %d:", filepath.Base(file), line) -} - -func green(str interface{}) string { - return fmt.Sprintf("%s%#v%s", greenCode, str, resetCode) -} - -func yellow(str interface{}) string { - return fmt.Sprintf("%s%#v%s", yellowCode, str, resetCode) -} - -func logFatal(t *testing.T, str string) { - t.Fatalf(logBodyFmt, prefix(3), str) -} - -func logError(t *testing.T, str string) { - t.Errorf(logBodyFmt, prefix(3), str) -} - -type diffLogger func([]string, interface{}, interface{}) - -type visit struct { - a1 uintptr - a2 uintptr - typ reflect.Type -} - -// Recursively visits the structures of "expected" and "actual". The diffLogger function will be -// invoked with each different value encountered, including the reference path that was followed -// to get there. -func deepDiffEqual(expected, actual reflect.Value, visited map[visit]bool, path []string, logDifference diffLogger) { - defer func() { - // Fall back to the regular reflect.DeepEquals function. - if r := recover(); r != nil { - var e, a interface{} - if expected.IsValid() { - e = expected.Interface() - } - if actual.IsValid() { - a = actual.Interface() - } - - if !reflect.DeepEqual(e, a) { - logDifference(path, e, a) - } - } - }() - - if !expected.IsValid() && actual.IsValid() { - logDifference(path, nil, actual.Interface()) - return - } - if expected.IsValid() && !actual.IsValid() { - logDifference(path, expected.Interface(), nil) - return - } - if !expected.IsValid() && !actual.IsValid() { - return - } - - hard := func(k reflect.Kind) bool { - switch k { - case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: - return true - } - return false - } - - if expected.CanAddr() && actual.CanAddr() && hard(expected.Kind()) { - addr1 := expected.UnsafeAddr() - addr2 := actual.UnsafeAddr() - - if addr1 > addr2 { - addr1, addr2 = addr2, addr1 - } - - if addr1 == addr2 { - // References are identical. We can short-circuit - return - } - - typ := expected.Type() - v := visit{addr1, addr2, typ} - if visited[v] { - // Already visited. - return - } - - // Remember this visit for later. - visited[v] = true - } - - switch expected.Kind() { - case reflect.Array: - for i := 0; i < expected.Len(); i++ { - hop := append(path, fmt.Sprintf("[%d]", i)) - deepDiffEqual(expected.Index(i), actual.Index(i), visited, hop, logDifference) - } - return - case reflect.Slice: - if expected.IsNil() != actual.IsNil() { - logDifference(path, expected.Interface(), actual.Interface()) - return - } - if expected.Len() == actual.Len() && expected.Pointer() == actual.Pointer() { - return - } - for i := 0; i < expected.Len(); i++ { - hop := append(path, fmt.Sprintf("[%d]", i)) - deepDiffEqual(expected.Index(i), actual.Index(i), visited, hop, logDifference) - } - return - case reflect.Interface: - if expected.IsNil() != actual.IsNil() { - logDifference(path, expected.Interface(), actual.Interface()) - return - } - deepDiffEqual(expected.Elem(), actual.Elem(), visited, path, logDifference) - return - case reflect.Ptr: - deepDiffEqual(expected.Elem(), actual.Elem(), visited, path, logDifference) - return - case reflect.Struct: - for i, n := 0, expected.NumField(); i < n; i++ { - field := expected.Type().Field(i) - hop := append(path, "."+field.Name) - deepDiffEqual(expected.Field(i), actual.Field(i), visited, hop, logDifference) - } - return - case reflect.Map: - if expected.IsNil() != actual.IsNil() { - logDifference(path, expected.Interface(), actual.Interface()) - return - } - if expected.Len() == actual.Len() && expected.Pointer() == actual.Pointer() { - return - } - - var keys []reflect.Value - if expected.Len() >= actual.Len() { - keys = expected.MapKeys() - } else { - keys = actual.MapKeys() - } - - for _, k := range keys { - expectedValue := expected.MapIndex(k) - actualValue := expected.MapIndex(k) - - if !expectedValue.IsValid() { - logDifference(path, nil, actual.Interface()) - return - } - if !actualValue.IsValid() { - logDifference(path, expected.Interface(), nil) - return - } - - hop := append(path, fmt.Sprintf("[%v]", k)) - deepDiffEqual(expectedValue, actualValue, visited, hop, logDifference) - } - return - case reflect.Func: - if expected.IsNil() != actual.IsNil() { - logDifference(path, expected.Interface(), actual.Interface()) - } - return - default: - if expected.Interface() != actual.Interface() { - logDifference(path, expected.Interface(), actual.Interface()) - } - } -} - -func deepDiff(expected, actual interface{}, logDifference diffLogger) { - if expected == nil || actual == nil { - logDifference([]string{}, expected, actual) - return - } - - expectedValue := reflect.ValueOf(expected) - actualValue := reflect.ValueOf(actual) - - if expectedValue.Type() != actualValue.Type() { - logDifference([]string{}, expected, actual) - return - } - deepDiffEqual(expectedValue, actualValue, map[visit]bool{}, []string{}, logDifference) -} - -// AssertEquals compares two arbitrary values and performs a comparison. If the -// comparison fails, a fatal error is raised that will fail the test -func AssertEquals(t *testing.T, expected, actual interface{}) { - if expected != actual { - logFatal(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual))) - } -} - -// CheckEquals is similar to AssertEquals, except with a non-fatal error -func CheckEquals(t *testing.T, expected, actual interface{}) { - if expected != actual { - logError(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual))) - } -} - -// AssertDeepEquals - like Equals - performs a comparison - but on more complex -// structures that requires deeper inspection -func AssertDeepEquals(t *testing.T, expected, actual interface{}) { - pre := prefix(2) - - differed := false - deepDiff(expected, actual, func(path []string, expected, actual interface{}) { - differed = true - t.Errorf("\033[1;31m%sat %s expected %s, but got %s\033[0m", - pre, - strings.Join(path, ""), - green(expected), - yellow(actual)) - }) - if differed { - logFatal(t, "The structures were different.") - } -} - -// CheckDeepEquals is similar to AssertDeepEquals, except with a non-fatal error -func CheckDeepEquals(t *testing.T, expected, actual interface{}) { - pre := prefix(2) - - deepDiff(expected, actual, func(path []string, expected, actual interface{}) { - t.Errorf("\033[1;31m%s at %s expected %s, but got %s\033[0m", - pre, - strings.Join(path, ""), - green(expected), - yellow(actual)) - }) -} - -// isJSONEquals is a utility function that implements JSON comparison for AssertJSONEquals and -// CheckJSONEquals. -func isJSONEquals(t *testing.T, expectedJSON string, actual interface{}) bool { - var parsedExpected, parsedActual interface{} - err := json.Unmarshal([]byte(expectedJSON), &parsedExpected) - if err != nil { - t.Errorf("Unable to parse expected value as JSON: %v", err) - return false - } - - jsonActual, err := json.Marshal(actual) - AssertNoErr(t, err) - err = json.Unmarshal(jsonActual, &parsedActual) - AssertNoErr(t, err) - - if !reflect.DeepEqual(parsedExpected, parsedActual) { - prettyExpected, err := json.MarshalIndent(parsedExpected, "", " ") - if err != nil { - t.Logf("Unable to pretty-print expected JSON: %v\n%s", err, expectedJSON) - } else { - // We can't use green() here because %#v prints prettyExpected as a byte array literal, which - // is... unhelpful. Converting it to a string first leaves "\n" uninterpreted for some reason. - t.Logf("Expected JSON:\n%s%s%s", greenCode, prettyExpected, resetCode) - } - - prettyActual, err := json.MarshalIndent(actual, "", " ") - if err != nil { - t.Logf("Unable to pretty-print actual JSON: %v\n%#v", err, actual) - } else { - // We can't use yellow() for the same reason. - t.Logf("Actual JSON:\n%s%s%s", yellowCode, prettyActual, resetCode) - } - - return false - } - return true -} - -// AssertJSONEquals serializes a value as JSON, parses an expected string as JSON, and ensures that -// both are consistent. If they aren't, the expected and actual structures are pretty-printed and -// shown for comparison. -// -// This is useful for comparing structures that are built as nested map[string]interface{} values, -// which are a pain to construct as literals. -func AssertJSONEquals(t *testing.T, expectedJSON string, actual interface{}) { - if !isJSONEquals(t, expectedJSON, actual) { - logFatal(t, "The generated JSON structure differed.") - } -} - -// CheckJSONEquals is similar to AssertJSONEquals, but nonfatal. -func CheckJSONEquals(t *testing.T, expectedJSON string, actual interface{}) { - if !isJSONEquals(t, expectedJSON, actual) { - logError(t, "The generated JSON structure differed.") - } -} - -// AssertNoErr is a convenience function for checking whether an error value is -// an actual error -func AssertNoErr(t *testing.T, e error) { - if e != nil { - logFatal(t, fmt.Sprintf("unexpected error %s", yellow(e.Error()))) - } -} - -// CheckNoErr is similar to AssertNoErr, except with a non-fatal error -func CheckNoErr(t *testing.T, e error) { - if e != nil { - logError(t, fmt.Sprintf("unexpected error %s", yellow(e.Error()))) - } -} diff --git a/vendor/github.com/rackspace/gophercloud/testhelper/doc.go b/vendor/github.com/rackspace/gophercloud/testhelper/doc.go deleted file mode 100644 index 25b4dfebb..000000000 --- a/vendor/github.com/rackspace/gophercloud/testhelper/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package testhelper container methods that are useful for writing unit tests. -*/ -package testhelper diff --git a/vendor/github.com/rackspace/gophercloud/testhelper/http_responses.go b/vendor/github.com/rackspace/gophercloud/testhelper/http_responses.go deleted file mode 100644 index e1f1f9ac0..000000000 --- a/vendor/github.com/rackspace/gophercloud/testhelper/http_responses.go +++ /dev/null @@ -1,91 +0,0 @@ -package testhelper - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "testing" -) - -var ( - // Mux is a multiplexer that can be used to register handlers. - Mux *http.ServeMux - - // Server is an in-memory HTTP server for testing. - Server *httptest.Server -) - -// SetupHTTP prepares the Mux and Server. -func SetupHTTP() { - Mux = http.NewServeMux() - Server = httptest.NewServer(Mux) -} - -// TeardownHTTP releases HTTP-related resources. -func TeardownHTTP() { - Server.Close() -} - -// Endpoint returns a fake endpoint that will actually target the Mux. -func Endpoint() string { - return Server.URL + "/" -} - -// TestFormValues ensures that all the URL parameters given to the http.Request are the same as values. -func TestFormValues(t *testing.T, r *http.Request, values map[string]string) { - want := url.Values{} - for k, v := range values { - want.Add(k, v) - } - - r.ParseForm() - if !reflect.DeepEqual(want, r.Form) { - t.Errorf("Request parameters = %v, want %v", r.Form, want) - } -} - -// TestMethod checks that the Request has the expected method (e.g. GET, POST). -func TestMethod(t *testing.T, r *http.Request, expected string) { - if expected != r.Method { - t.Errorf("Request method = %v, expected %v", r.Method, expected) - } -} - -// TestHeader checks that the header on the http.Request matches the expected value. -func TestHeader(t *testing.T, r *http.Request, header string, expected string) { - if actual := r.Header.Get(header); expected != actual { - t.Errorf("Header %s = %s, expected %s", header, actual, expected) - } -} - -// TestBody verifies that the request body matches an expected body. -func TestBody(t *testing.T, r *http.Request, expected string) { - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Unable to read body: %v", err) - } - str := string(b) - if expected != str { - t.Errorf("Body = %s, expected %s", str, expected) - } -} - -// TestJSONRequest verifies that the JSON payload of a request matches an expected structure, without asserting things about -// whitespace or ordering. -func TestJSONRequest(t *testing.T, r *http.Request, expected string) { - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Unable to read request body: %v", err) - } - - var actualJSON interface{} - err = json.Unmarshal(b, &actualJSON) - if err != nil { - t.Errorf("Unable to parse request body as JSON: %v", err) - } - - CheckJSONEquals(t, expected, actualJSON) -} diff --git a/vendor/github.com/rackspace/gophercloud/util.go b/vendor/github.com/rackspace/gophercloud/util.go deleted file mode 100644 index 3d6a4e490..000000000 --- a/vendor/github.com/rackspace/gophercloud/util.go +++ /dev/null @@ -1,82 +0,0 @@ -package gophercloud - -import ( - "errors" - "net/url" - "path/filepath" - "strings" - "time" -) - -// WaitFor polls a predicate function, once per second, up to a timeout limit. -// It usually does this to wait for a resource to transition to a certain state. -// Resource packages will wrap this in a more convenient function that's -// specific to a certain resource, but it can also be useful on its own. -func WaitFor(timeout int, predicate func() (bool, error)) error { - start := time.Now().Second() - for { - // Force a 1s sleep - time.Sleep(1 * time.Second) - - // If a timeout is set, and that's been exceeded, shut it down - if timeout >= 0 && time.Now().Second()-start >= timeout { - return errors.New("A timeout occurred") - } - - // Execute the function - satisfied, err := predicate() - if err != nil { - return err - } - if satisfied { - return nil - } - } -} - -// NormalizeURL is an internal function to be used by provider clients. -// -// It ensures that each endpoint URL has a closing `/`, as expected by -// ServiceClient's methods. -func NormalizeURL(url string) string { - if !strings.HasSuffix(url, "/") { - return url + "/" - } - return url -} - -// NormalizePathURL is used to convert rawPath to a fqdn, using basePath as -// a reference in the filesystem, if necessary. basePath is assumed to contain -// either '.' when first used, or the file:// type fqdn of the parent resource. -// e.g. myFavScript.yaml => file://opt/lib/myFavScript.yaml -func NormalizePathURL(basePath, rawPath string) (string, error) { - u, err := url.Parse(rawPath) - if err != nil { - return "", err - } - // if a scheme is defined, it must be a fqdn already - if u.Scheme != "" { - return u.String(), nil - } - // if basePath is a url, then child resources are assumed to be relative to it - bu, err := url.Parse(basePath) - if err != nil { - return "", err - } - var basePathSys, absPathSys string - if bu.Scheme != "" { - basePathSys = filepath.FromSlash(bu.Path) - absPathSys = filepath.Join(basePathSys, rawPath) - bu.Path = filepath.ToSlash(absPathSys) - return bu.String(), nil - } - - absPathSys = filepath.Join(basePath, rawPath) - u.Path = filepath.ToSlash(absPathSys) - if err != nil { - return "", err - } - u.Scheme = "file" - return u.String(), nil - -} diff --git a/vendor/vendor.json b/vendor/vendor.json index 866d5a0c3..8e44e89d4 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -1183,12 +1183,24 @@ "revision": "e3d6384a3714b335d075862e6eb0a681180643df", "revisionTime": "2016-10-25T18:03:21Z" }, + { + "checksumSHA1": "yIerdfSMJRUnjh2EZikMhWcgwlY=", + "path": "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/accounts", + "revision": "45720eeefeeeba03b2d7da500297ec68eeee51af", + "revisionTime": "2016-10-31T15:28:56Z" + }, { "checksumSHA1": "5XMyCSYDLmv/b54K3HNNNCJdnBk=", "path": "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/containers", "revision": "e3d6384a3714b335d075862e6eb0a681180643df", "revisionTime": "2016-10-25T18:03:21Z" }, + { + "checksumSHA1": "CRiIA3oRRlKRDF2ZYnZT8rTlJBU=", + "path": "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects", + "revision": "45720eeefeeeba03b2d7da500297ec68eeee51af", + "revisionTime": "2016-10-31T15:28:56Z" + }, { "checksumSHA1": "TDOZnaS0TO0NirpxV1QwPerAQTY=", "path": "github.com/gophercloud/gophercloud/openstack/utils", @@ -1758,271 +1770,24 @@ "path": "github.com/pkg/errors", "revision": "42fa80f2ac6ed17a977ce826074bd3009593fa9d" }, - { - "checksumSHA1": "4Q/JrLYYcwGRPVpd6sJ5yW/E9GQ=", - "path": "github.com/rackspace/gophercloud", - "revision": "985a863d6dd5f928b485dbc8ef440813aafa39ad", - "revisionTime": "2016-06-23T23:57:31Z" - }, - { - "checksumSHA1": "dh2tsaicjrx9LgR6uuSeilSFzAY=", - "path": "github.com/rackspace/gophercloud/openstack", - "revision": "985a863d6dd5f928b485dbc8ef440813aafa39ad", - "revisionTime": "2016-06-23T23:57:31Z" - }, - { - "checksumSHA1": "KXOy+EDMJgyZT0MoTXMhcFZVgNM=", - "path": "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, { "checksumSHA1": "uh4DrOO+91jmxNlamBoloURUPO0=", "path": "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/testing", "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", "revisionTime": "2016-06-03T22:34:01Z" }, - { - "checksumSHA1": "ptDng4MELpgmyMbKx7q46euXYck=", - "path": "github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "pQOpY/k5Gh8pUDmsf8ntH6mtGYQ=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume", - "revision": "985a863d6dd5f928b485dbc8ef440813aafa39ad", - "revisionTime": "2016-06-23T23:57:31Z" - }, - { - "checksumSHA1": "Jpju6sEOCeMRL9SP+zy86ydhPDo=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "I9QKv1AKFpSzX/O3KT6BSFat+tk=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "mA4UpOZ0dWxMKkzZqSJ3yzmDGng=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "foERSFhAuTWCXRL11GUOX+uWiaI=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "uNrf4iwP1ABn2ArI1mUS7jwnTQo=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "jqSmOJoNKVtGwDhuoilAF7iftqA=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "rHEOEAm10HDsfBLU8FqKSUdwqFY=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "yMt7J+JXn8fC/b8qQLyeJYK6Kyc=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, { "checksumSHA1": "/CUwRPw3GTR4kDDyhlevEJOz8VM=", "path": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/testing", "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", "revisionTime": "2016-06-03T22:34:01Z" }, - { - "checksumSHA1": "evzUqx0LmT1wg1XLJBvfaDhb6Pc=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/flavors", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "il+znRRlkKOSfP+hxrz+0IAb2FU=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/images", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "LMxGZMRGX1MK7qaPmamj7cDJLbU=", - "path": "github.com/rackspace/gophercloud/openstack/compute/v2/servers", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "gJg3QKHt4wCjM5kUjUZnXGlL57c=", - "path": "github.com/rackspace/gophercloud/openstack/identity/v2/tenants", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "6R8yUmY2FsIYn5rjvBEx4eZuVfQ=", - "path": "github.com/rackspace/gophercloud/openstack/identity/v2/tokens", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "yQG3tZgPMFBw2kIp4TR+9E4QH78=", - "path": "github.com/rackspace/gophercloud/openstack/identity/v3/tokens", - "revision": "985a863d6dd5f928b485dbc8ef440813aafa39ad", - "revisionTime": "2016-06-23T23:57:31Z" - }, { "checksumSHA1": "EMdUpMYV9vQAEtBkpUdSqYaYBVc=", "path": "github.com/rackspace/gophercloud/openstack/networking/v2/common", "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", "revisionTime": "2016-06-03T22:34:01Z" }, - { - "checksumSHA1": "CIMIys+Dh/kkLj4i+Xyn7CUDTyM=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "Dq/QBMYHUlISQXYrDCltTaF2HKU=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "NppejKsGwws2GmxajE6ZZVuP61M=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "2zGAc21qrvbg0BWMqb6ADhiIJvc=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "N1I73FBojC4D1kiASMHBLhYNV5A=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "qqJpW4mn6W25zzaXgVS9FeRYmlU=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "YaxzH3aa+FSPo7kt5wVxJfKFE04=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "61RDejBCkPnueotbY/2uVzCPt/Y=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "dD5y2ImtufAHjyVFdShtBhtAWkA=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "fChoykh7X7OjiV29nV+pl3k6y3Y=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas_v2", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z", - "tree": true - }, - { - "checksumSHA1": "VlAkiJAb6yIWthZpDM/hNXBzmo4=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "CKBV6wraj8j/fwkUllbry6kx/TE=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "3p4PfOfnJ9ZpqpbkgP2hpe/ZhCs=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/networks", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "UGPFc7aRab78XkJp9/c0MUfVy3I=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/ports", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "23UqLsJHksZiopcSwWmkrX3e0CY=", - "path": "github.com/rackspace/gophercloud/openstack/networking/v2/subnets", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "HecTWfPTprklkbLV5wOycG/PiGA=", - "path": "github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "bCETKrDen/3DNnzvR0fTr91Sq+k=", - "path": "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "gaOb5FwWD06v8fAyHqcejyD7wHY=", - "path": "github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "WkgQ5ZIv6/KQlNfweJd+889nWPk=", - "path": "github.com/rackspace/gophercloud/openstack/utils", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "6YVL0nw4z/n45Mx2SXTsQ8N1LYk=", - "path": "github.com/rackspace/gophercloud/pagination", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "U2yzK8GFNeHZqcoeotcHmK57lAI=", - "path": "github.com/rackspace/gophercloud/testhelper", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, - { - "checksumSHA1": "fXtvTbQBML8QLu/qpD9sAt53J00=", - "path": "github.com/rackspace/gophercloud/testhelper/client", - "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", - "revisionTime": "2016-06-03T22:34:01Z" - }, { "path": "github.com/rainycape/unidecode", "revision": "cb7f23ec59bec0d61b19c56cd88cee3d0cc1870c" diff --git a/website/source/docs/state/remote/swift.html.md b/website/source/docs/state/remote/swift.html.md index 9e8444469..293fb9ca1 100644 --- a/website/source/docs/state/remote/swift.html.md +++ b/website/source/docs/state/remote/swift.html.md @@ -34,6 +34,7 @@ data "terraform_remote_state" "foo" { The following configuration option is supported: * `path` - (Required) The path where to store `terraform.tfstate` + * `insecure` - (Optional) Allow "insecure" SSL requests. Defaults to `false`. The following environment variables are supported: @@ -42,3 +43,5 @@ The following environment variables are supported: * `OS_PASSWORD` - (Required) The password * `OS_REGION_NAME` - (Required) The region * `OS_TENANT_NAME` - (Required) The name of the tenant + * `OS_DOMAIN_ID` - (Optional) The ID of the domain + * `OS_DOMAIN_NAME` - (Optional) The name of the domain