Update gophercloud networking for autoprobing external network

This commit is contained in:
FengyunPan
2017-11-28 10:07:54 +08:00
parent de7c96ad3c
commit 62fb644781
18 changed files with 1012 additions and 55 deletions

View File

@@ -45,6 +45,7 @@ filegroup(
"//vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/extensions/trusts:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/networks:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/ports:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/utils:all-srcs",
],

View File

@@ -65,7 +65,7 @@ type Flavor struct {
VCPUs int `json:"vcpus"`
// IsPublic indicates whether the flavor is public.
IsPublic bool `json:"is_public"`
IsPublic bool `json:"os-flavor-access:is_public"`
}
func (r *Flavor) UnmarshalJSON(b []byte) error {

View File

@@ -515,7 +515,7 @@ func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) {
// 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.
// When the resize completes, the server will be in VERIFY_RESIZE 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.

View File

@@ -23,6 +23,7 @@ filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/external:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/floatingips:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/routers:all-srcs",
"//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners:all-srcs",

View File

@@ -0,0 +1,27 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"requests.go",
"results.go",
],
importpath = "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/external",
visibility = ["//visibility:public"],
deps = ["//vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/networks:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,46 @@
/*
Package external provides information and interaction with the external
extension for the OpenStack Networking service.
Example to List Networks with External Information
type NetworkWithExternalExt struct {
networks.Network
external.NetworkExternalExt
}
var allNetworks []NetworkWithExternalExt
allPages, err := networks.List(networkClient, nil).AllPages()
if err != nil {
panic(err)
}
err = networks.ExtractNetworksInto(allPages, &allNetworks)
if err != nil {
panic(err)
}
for _, network := range allNetworks {
fmt.Println("%+v\n", network)
}
Example to Create a Network with External Information
iTrue := true
networkCreateOpts := networks.CreateOpts{
Name: "private",
AdminStateUp: &iTrue,
}
createOpts := external.CreateOptsExt{
networkCreateOpts,
&iTrue,
}
network, err := networks.Create(networkClient, createOpts).Extract()
if err != nil {
panic(err)
}
*/
package external

View File

@@ -0,0 +1,56 @@
package external
import (
"github.com/gophercloud/gophercloud/openstack/networking/v2/networks"
)
// CreateOptsExt is the structure used when creating new external network
// resources. It embeds networks.CreateOpts and so inherits all of its required
// and optional fields, with the addition of the External field.
type CreateOptsExt struct {
networks.CreateOptsBuilder
External *bool `json:"router:external,omitempty"`
}
// ToNetworkCreateMap adds the router:external options to the base network
// creation options.
func (opts CreateOptsExt) ToNetworkCreateMap() (map[string]interface{}, error) {
base, err := opts.CreateOptsBuilder.ToNetworkCreateMap()
if err != nil {
return nil, err
}
if opts.External == nil {
return base, nil
}
networkMap := base["network"].(map[string]interface{})
networkMap["router:external"] = opts.External
return base, nil
}
// UpdateOptsExt is the structure used when updating existing external network
// resources. It embeds networks.UpdateOpts and so inherits all of its required
// and optional fields, with the addition of the External field.
type UpdateOptsExt struct {
networks.UpdateOptsBuilder
External *bool `json:"router:external,omitempty"`
}
// ToNetworkUpdateMap casts an UpdateOpts struct to a map.
func (opts UpdateOptsExt) ToNetworkUpdateMap() (map[string]interface{}, error) {
base, err := opts.UpdateOptsBuilder.ToNetworkUpdateMap()
if err != nil {
return nil, err
}
if opts.External == nil {
return base, nil
}
networkMap := base["network"].(map[string]interface{})
networkMap["router:external"] = opts.External
return base, nil
}

View File

@@ -0,0 +1,8 @@
package external
// NetworkExternalExt represents a decorated form of a Network with based on the
// "external-net" extension.
type NetworkExternalExt struct {
// Specifies whether the network is an external network or not.
External bool `json:"router:external"`
}

View File

@@ -0,0 +1,31 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"requests.go",
"results.go",
"urls.go",
],
importpath = "github.com/gophercloud/gophercloud/openstack/networking/v2/networks",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/gophercloud/gophercloud:go_default_library",
"//vendor/github.com/gophercloud/gophercloud/pagination:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,65 @@
/*
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.
Example to List Networks
listOpts := networks.ListOpts{
TenantID: "a99e9b4e620e4db09a2dfb6e42a01e66",
}
allPages, err := networks.List(networkClient, listOpts).AllPages()
if err != nil {
panic(err)
}
allNetworks, err := networks.ExtractNetworks(allPages)
if err != nil {
panic(err)
}
for _, network := range allNetworks {
fmt.Printf("%+v", network)
}
Example to Create a Network
iTrue := true
createOpts := networks.CreateOpts{
Name: "network_1",
AdminStateUp: &iTrue,
}
network, err := networks.Create(networkClient, createOpts).Extract()
if err != nil {
panic(err)
}
Example to Update a Network
networkID := "484cda0e-106f-4f4b-bb3f-d413710bbe78"
updateOpts := networks.UpdateOpts{
Name: "new_name",
}
network, err := networks.Update(networkClient, networkID, updateOpts).Extract()
if err != nil {
panic(err)
}
Example to Delete a Network
networkID := "484cda0e-106f-4f4b-bb3f-d413710bbe78"
err := networks.Delete(networkClient, networkID).ExtractErr()
if err != nil {
panic(err)
}
*/
package networks

View File

@@ -0,0 +1,165 @@
package networks
import (
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/pagination"
)
// 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)
return q.String(), err
}
// 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) (r GetResult) {
_, r.Err = c.Get(getURL(c, id), &r.Body, nil)
return
}
// CreateOptsBuilder allows extensions to add additional parameters to the
// Create request.
type CreateOptsBuilder interface {
ToNetworkCreateMap() (map[string]interface{}, error)
}
// CreateOpts represents options used to create a network.
type CreateOpts struct {
AdminStateUp *bool `json:"admin_state_up,omitempty"`
Name string `json:"name,omitempty"`
Shared *bool `json:"shared,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
}
// ToNetworkCreateMap builds a request body from CreateOpts.
func (opts CreateOpts) ToNetworkCreateMap() (map[string]interface{}, error) {
return gophercloud.BuildRequestBody(opts, "network")
}
// 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) (r CreateResult) {
b, err := opts.ToNetworkCreateMap()
if err != nil {
r.Err = err
return
}
_, r.Err = c.Post(createURL(c), b, &r.Body, nil)
return
}
// UpdateOptsBuilder allows extensions to add additional parameters to the
// Update request.
type UpdateOptsBuilder interface {
ToNetworkUpdateMap() (map[string]interface{}, error)
}
// UpdateOpts represents options used to update a network.
type UpdateOpts struct {
AdminStateUp *bool `json:"admin_state_up,omitempty"`
Name string `json:"name,omitempty"`
Shared *bool `json:"shared,omitempty"`
}
// ToNetworkUpdateMap builds a request body from UpdateOpts.
func (opts UpdateOpts) ToNetworkUpdateMap() (map[string]interface{}, error) {
return gophercloud.BuildRequestBody(opts, "network")
}
// 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) (r UpdateResult) {
b, err := opts.ToNetworkUpdateMap()
if err != nil {
r.Err = err
return
}
_, r.Err = c.Put(updateURL(c, networkID), b, &r.Body, &gophercloud.RequestOpts{
OkCodes: []int{200, 201},
})
return
}
// Delete accepts a unique ID and deletes the network associated with it.
func Delete(c *gophercloud.ServiceClient, networkID string) (r DeleteResult) {
_, r.Err = c.Delete(deleteURL(c, networkID), nil)
return
}
// IDFromName is a convenience function that returns a network's ID, given
// its name.
func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
count := 0
id := ""
pages, err := List(client, nil).AllPages()
if err != nil {
return "", err
}
all, err := ExtractNetworks(pages)
if err != nil {
return "", err
}
for _, s := range all {
if s.Name == name {
count++
id = s.ID
}
}
switch count {
case 0:
return "", gophercloud.ErrResourceNotFound{Name: name, ResourceType: "network"}
case 1:
return id, nil
default:
return "", gophercloud.ErrMultipleResourcesFound{Name: name, Count: count, ResourceType: "network"}
}
}

View File

@@ -0,0 +1,111 @@
package networks
import (
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/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) {
var s Network
err := r.ExtractInto(&s)
return &s, err
}
func (r commonResult) ExtractInto(v interface{}) error {
return r.Result.ExtractIntoStructPtr(v, "network")
}
// CreateResult represents the result of a create operation. Call its Extract
// method to interpret it as a Network.
type CreateResult struct {
commonResult
}
// GetResult represents the result of a get operation. Call its Extract
// method to interpret it as a Network.
type GetResult struct {
commonResult
}
// UpdateResult represents the result of an update operation. Call its Extract
// method to interpret it as a Network.
type UpdateResult struct {
commonResult
}
// DeleteResult represents the result of a delete operation. Call its
// ExtractErr method to determine if the request succeeded or failed.
type DeleteResult struct {
gophercloud.ErrResult
}
// Network represents, well, a network.
type Network struct {
// UUID for the network
ID string `json:"id"`
// Human-readable name for the network. Might not be unique.
Name string `json:"name"`
// The administrative state of network. If false (down), the network does not
// forward packets.
AdminStateUp bool `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 `json:"status"`
// Subnets associated with this network.
Subnets []string `json:"subnets"`
// Owner of network.
TenantID string `json:"tenant_id"`
// Specifies whether the network resource can be accessed by any tenant.
Shared bool `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 (r NetworkPage) NextPageURL() (string, error) {
var s struct {
Links []gophercloud.Link `json:"networks_links"`
}
err := r.ExtractInto(&s)
if err != nil {
return "", err
}
return gophercloud.ExtractNextURL(s.Links)
}
// IsEmpty checks whether a NetworkPage struct is empty.
func (r NetworkPage) IsEmpty() (bool, error) {
is, err := ExtractNetworks(r)
return len(is) == 0, err
}
// 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(r pagination.Page) ([]Network, error) {
var s []Network
err := ExtractNetworksInto(r, &s)
return s, err
}
func ExtractNetworksInto(r pagination.Page, v interface{}) error {
return r.(NetworkPage).Result.ExtractIntoSlicePtr(v, "networks")
}

View File

@@ -0,0 +1,31 @@
package networks
import "github.com/gophercloud/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)
}

View File

@@ -347,12 +347,21 @@ func BuildQueryString(opts interface{}) (*url.URL, error) {
params.Add(tags[0], v.Index(i).String())
}
}
case reflect.Map:
if v.Type().Key().Kind() == reflect.String && v.Type().Elem().Kind() == reflect.String {
var s []string
for _, k := range v.MapKeys() {
value := v.MapIndex(k).String()
s = append(s, fmt.Sprintf("'%s':'%s'", k.String(), value))
}
params.Add(tags[0], fmt.Sprintf("{%s}", strings.Join(s, ", ")))
}
}
} 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{}, fmt.Errorf("Required query parameter [%s] not set.", f.Name)
}
}
}