Vendor: add Gophercloud networking v2 networks

Add package that allow to work with OpenStack networks via the
Networking V2 service API.
This commit is contained in:
Andrei Ozerov 2018-06-12 09:47:16 +03:00
parent 71bf67620f
commit f0f1967c9f
5 changed files with 388 additions and 0 deletions

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,168 @@
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"`
ProjectID string `q:"project_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"`
ProjectID string `json:"project_id,omitempty"`
AvailabilityZoneHints []string `json:"availability_zone_hints,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,118 @@
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"`
// TenantID is the project owner of the network.
TenantID string `json:"tenant_id"`
// ProjectID is the project owner of the network.
ProjectID string `json:"project_id"`
// Specifies whether the network resource can be accessed by any tenant.
Shared bool `json:"shared"`
// Availability zone hints groups network nodes that run services like DHCP, L3, FW, and others.
// Used to make network resources highly available.
AvailabilityZoneHints []string `json:"availability_zone_hints"`
}
// 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)
}

6
vendor/vendor.json vendored
View File

@ -845,6 +845,12 @@
"revision": "00dcc07f1071d5f96520fac7a2b9a30eabccf879", "revision": "00dcc07f1071d5f96520fac7a2b9a30eabccf879",
"revisionTime": "2018-06-10T02:06:14Z" "revisionTime": "2018-06-10T02:06:14Z"
}, },
{
"checksumSHA1": "XEVvG2f/dqATN4aCluZlPylW+9A=",
"path": "github.com/gophercloud/gophercloud/openstack/networking/v2/networks",
"revision": "00dcc07f1071d5f96520fac7a2b9a30eabccf879",
"revisionTime": "2018-06-10T02:06:14Z"
},
{ {
"checksumSHA1": "8KE4bJzhbFZKsYMxcRg6xLqqfTg=", "checksumSHA1": "8KE4bJzhbFZKsYMxcRg6xLqqfTg=",
"path": "github.com/gophercloud/gophercloud/openstack/utils", "path": "github.com/gophercloud/gophercloud/openstack/utils",