github.com/gophercloud/gophercloud@v1.11.0/openstack/networking/v2/ports/requests.go (about)

     1  package ports
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"strings"
     7  
     8  	"github.com/gophercloud/gophercloud"
     9  	"github.com/gophercloud/gophercloud/pagination"
    10  )
    11  
    12  // ListOptsBuilder allows extensions to add additional parameters to the
    13  // List request.
    14  type ListOptsBuilder interface {
    15  	ToPortListQuery() (string, error)
    16  }
    17  
    18  // ListOpts allows the filtering and sorting of paginated collections through
    19  // the API. Filtering is achieved by passing in struct field values that map to
    20  // the port attributes you want to see returned. SortKey allows you to sort
    21  // by a particular port attribute. SortDir sets the direction, and is either
    22  // `asc' or `desc'. Marker and Limit are used for pagination.
    23  type ListOpts struct {
    24  	Status         string   `q:"status"`
    25  	Name           string   `q:"name"`
    26  	Description    string   `q:"description"`
    27  	AdminStateUp   *bool    `q:"admin_state_up"`
    28  	NetworkID      string   `q:"network_id"`
    29  	TenantID       string   `q:"tenant_id"`
    30  	ProjectID      string   `q:"project_id"`
    31  	DeviceOwner    string   `q:"device_owner"`
    32  	MACAddress     string   `q:"mac_address"`
    33  	ID             string   `q:"id"`
    34  	DeviceID       string   `q:"device_id"`
    35  	Limit          int      `q:"limit"`
    36  	Marker         string   `q:"marker"`
    37  	SortKey        string   `q:"sort_key"`
    38  	SortDir        string   `q:"sort_dir"`
    39  	Tags           string   `q:"tags"`
    40  	TagsAny        string   `q:"tags-any"`
    41  	NotTags        string   `q:"not-tags"`
    42  	NotTagsAny     string   `q:"not-tags-any"`
    43  	SecurityGroups []string `q:"security_groups"`
    44  	FixedIPs       []FixedIPOpts
    45  }
    46  
    47  type FixedIPOpts struct {
    48  	IPAddress       string
    49  	IPAddressSubstr string
    50  	SubnetID        string
    51  }
    52  
    53  func (f FixedIPOpts) String() string {
    54  	var res []string
    55  	if f.IPAddress != "" {
    56  		res = append(res, fmt.Sprintf("ip_address=%s", f.IPAddress))
    57  	}
    58  	if f.IPAddressSubstr != "" {
    59  		res = append(res, fmt.Sprintf("ip_address_substr=%s", f.IPAddressSubstr))
    60  	}
    61  	if f.SubnetID != "" {
    62  		res = append(res, fmt.Sprintf("subnet_id=%s", f.SubnetID))
    63  	}
    64  	return strings.Join(res, ",")
    65  }
    66  
    67  // ToPortListQuery formats a ListOpts into a query string.
    68  func (opts ListOpts) ToPortListQuery() (string, error) {
    69  	q, err := gophercloud.BuildQueryString(opts)
    70  	params := q.Query()
    71  	for _, fixedIP := range opts.FixedIPs {
    72  		params.Add("fixed_ips", fixedIP.String())
    73  	}
    74  	q = &url.URL{RawQuery: params.Encode()}
    75  	return q.String(), err
    76  }
    77  
    78  // List returns a Pager which allows you to iterate over a collection of
    79  // ports. It accepts a ListOpts struct, which allows you to filter and sort
    80  // the returned collection for greater efficiency.
    81  //
    82  // Default policy settings return only those ports that are owned by the tenant
    83  // who submits the request, unless the request is submitted by a user with
    84  // administrative rights.
    85  func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
    86  	url := listURL(c)
    87  	if opts != nil {
    88  		query, err := opts.ToPortListQuery()
    89  		if err != nil {
    90  			return pagination.Pager{Err: err}
    91  		}
    92  		url += query
    93  	}
    94  	return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page {
    95  		return PortPage{pagination.LinkedPageBase{PageResult: r}}
    96  	})
    97  }
    98  
    99  // Get retrieves a specific port based on its unique ID.
   100  func Get(c *gophercloud.ServiceClient, id string) (r GetResult) {
   101  	resp, err := c.Get(getURL(c, id), &r.Body, nil)
   102  	_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)
   103  	return
   104  }
   105  
   106  // CreateOptsBuilder allows extensions to add additional parameters to the
   107  // Create request.
   108  type CreateOptsBuilder interface {
   109  	ToPortCreateMap() (map[string]interface{}, error)
   110  }
   111  
   112  // CreateOpts represents the attributes used when creating a new port.
   113  type CreateOpts struct {
   114  	NetworkID             string             `json:"network_id" required:"true"`
   115  	Name                  string             `json:"name,omitempty"`
   116  	Description           string             `json:"description,omitempty"`
   117  	AdminStateUp          *bool              `json:"admin_state_up,omitempty"`
   118  	MACAddress            string             `json:"mac_address,omitempty"`
   119  	FixedIPs              interface{}        `json:"fixed_ips,omitempty"`
   120  	DeviceID              string             `json:"device_id,omitempty"`
   121  	DeviceOwner           string             `json:"device_owner,omitempty"`
   122  	TenantID              string             `json:"tenant_id,omitempty"`
   123  	ProjectID             string             `json:"project_id,omitempty"`
   124  	SecurityGroups        *[]string          `json:"security_groups,omitempty"`
   125  	AllowedAddressPairs   []AddressPair      `json:"allowed_address_pairs,omitempty"`
   126  	PropagateUplinkStatus *bool              `json:"propagate_uplink_status,omitempty"`
   127  	ValueSpecs            *map[string]string `json:"value_specs,omitempty"`
   128  }
   129  
   130  // ToPortCreateMap builds a request body from CreateOpts.
   131  func (opts CreateOpts) ToPortCreateMap() (map[string]interface{}, error) {
   132  	return gophercloud.BuildRequestBody(opts, "port")
   133  }
   134  
   135  // Create accepts a CreateOpts struct and creates a new network using the values
   136  // provided. You must remember to provide a NetworkID value.
   137  func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
   138  	b, err := opts.ToPortCreateMap()
   139  	if err != nil {
   140  		r.Err = err
   141  		return
   142  	}
   143  	resp, err := c.Post(createURL(c), b, &r.Body, nil)
   144  	_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)
   145  	return
   146  }
   147  
   148  // UpdateOptsBuilder allows extensions to add additional parameters to the
   149  // Update request.
   150  type UpdateOptsBuilder interface {
   151  	ToPortUpdateMap() (map[string]interface{}, error)
   152  }
   153  
   154  // UpdateOpts represents the attributes used when updating an existing port.
   155  type UpdateOpts struct {
   156  	Name                  *string            `json:"name,omitempty"`
   157  	Description           *string            `json:"description,omitempty"`
   158  	AdminStateUp          *bool              `json:"admin_state_up,omitempty"`
   159  	FixedIPs              interface{}        `json:"fixed_ips,omitempty"`
   160  	DeviceID              *string            `json:"device_id,omitempty"`
   161  	DeviceOwner           *string            `json:"device_owner,omitempty"`
   162  	SecurityGroups        *[]string          `json:"security_groups,omitempty"`
   163  	AllowedAddressPairs   *[]AddressPair     `json:"allowed_address_pairs,omitempty"`
   164  	PropagateUplinkStatus *bool              `json:"propagate_uplink_status,omitempty"`
   165  	ValueSpecs            *map[string]string `json:"value_specs,omitempty"`
   166  
   167  	// RevisionNumber implements extension:standard-attr-revisions. If != "" it
   168  	// will set revision_number=%s. If the revision number does not match, the
   169  	// update will fail.
   170  	RevisionNumber *int `json:"-" h:"If-Match"`
   171  }
   172  
   173  // ToPortUpdateMap builds a request body from UpdateOpts.
   174  func (opts UpdateOpts) ToPortUpdateMap() (map[string]interface{}, error) {
   175  	return gophercloud.BuildRequestBody(opts, "port")
   176  }
   177  
   178  // Update accepts a UpdateOpts struct and updates an existing port using the
   179  // values provided.
   180  func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
   181  	b, err := opts.ToPortUpdateMap()
   182  	if err != nil {
   183  		r.Err = err
   184  		return
   185  	}
   186  	h, err := gophercloud.BuildHeaders(opts)
   187  	if err != nil {
   188  		r.Err = err
   189  		return
   190  	}
   191  	for k := range h {
   192  		if k == "If-Match" {
   193  			h[k] = fmt.Sprintf("revision_number=%s", h[k])
   194  		}
   195  	}
   196  	resp, err := c.Put(updateURL(c, id), b, &r.Body, &gophercloud.RequestOpts{
   197  		MoreHeaders: h,
   198  		OkCodes:     []int{200, 201},
   199  	})
   200  	_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)
   201  	return
   202  }
   203  
   204  // Delete accepts a unique ID and deletes the port associated with it.
   205  func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {
   206  	resp, err := c.Delete(deleteURL(c, id), nil)
   207  	_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)
   208  	return
   209  }