github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/networking/v2/ports/requests.go (about)

     1  package ports
     2  
     3  import (
     4  	"github.com/huaweicloud/golangsdk"
     5  	"github.com/huaweicloud/golangsdk/pagination"
     6  )
     7  
     8  // ListOptsBuilder allows extensions to add additional parameters to the
     9  // List request.
    10  type ListOptsBuilder interface {
    11  	ToPortListQuery() (string, error)
    12  }
    13  
    14  // ListOpts allows the filtering and sorting of paginated collections through
    15  // the API. Filtering is achieved by passing in struct field values that map to
    16  // the port attributes you want to see returned. SortKey allows you to sort
    17  // by a particular port attribute. SortDir sets the direction, and is either
    18  // `asc' or `desc'. Marker and Limit are used for pagination.
    19  type ListOpts struct {
    20  	Status       string `q:"status"`
    21  	Name         string `q:"name"`
    22  	AdminStateUp *bool  `q:"admin_state_up"`
    23  	NetworkID    string `q:"network_id"`
    24  	TenantID     string `q:"tenant_id"`
    25  	ProjectID    string `q:"project_id"`
    26  	DeviceOwner  string `q:"device_owner"`
    27  	MACAddress   string `q:"mac_address"`
    28  	ID           string `q:"id"`
    29  	DeviceID     string `q:"device_id"`
    30  	Limit        int    `q:"limit"`
    31  	Marker       string `q:"marker"`
    32  	SortKey      string `q:"sort_key"`
    33  	SortDir      string `q:"sort_dir"`
    34  }
    35  
    36  // ToPortListQuery formats a ListOpts into a query string.
    37  func (opts ListOpts) ToPortListQuery() (string, error) {
    38  	q, err := golangsdk.BuildQueryString(opts)
    39  	return q.String(), err
    40  }
    41  
    42  // List returns a Pager which allows you to iterate over a collection of
    43  // ports. It accepts a ListOpts struct, which allows you to filter and sort
    44  // the returned collection for greater efficiency.
    45  //
    46  // Default policy settings return only those ports that are owned by the tenant
    47  // who submits the request, unless the request is submitted by a user with
    48  // administrative rights.
    49  func List(c *golangsdk.ServiceClient, opts ListOptsBuilder) pagination.Pager {
    50  	url := listURL(c)
    51  	if opts != nil {
    52  		query, err := opts.ToPortListQuery()
    53  		if err != nil {
    54  			return pagination.Pager{Err: err}
    55  		}
    56  		url += query
    57  	}
    58  	return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page {
    59  		return PortPage{pagination.LinkedPageBase{PageResult: r}}
    60  	})
    61  }
    62  
    63  // Get retrieves a specific port based on its unique ID.
    64  func Get(c *golangsdk.ServiceClient, id string) (r GetResult) {
    65  	_, r.Err = c.Get(getURL(c, id), &r.Body, nil)
    66  	return
    67  }
    68  
    69  // CreateOptsBuilder allows extensions to add additional parameters to the
    70  // Create request.
    71  type CreateOptsBuilder interface {
    72  	ToPortCreateMap() (map[string]interface{}, error)
    73  }
    74  
    75  // CreateOpts represents the attributes used when creating a new port.
    76  type CreateOpts struct {
    77  	NetworkID           string        `json:"network_id" required:"true"`
    78  	Name                string        `json:"name,omitempty"`
    79  	AdminStateUp        *bool         `json:"admin_state_up,omitempty"`
    80  	MACAddress          string        `json:"mac_address,omitempty"`
    81  	FixedIPs            interface{}   `json:"fixed_ips,omitempty"`
    82  	DeviceID            string        `json:"device_id,omitempty"`
    83  	DeviceOwner         string        `json:"device_owner,omitempty"`
    84  	TenantID            string        `json:"tenant_id,omitempty"`
    85  	ProjectID           string        `json:"project_id,omitempty"`
    86  	SecurityGroups      *[]string     `json:"security_groups,omitempty"`
    87  	AllowedAddressPairs []AddressPair `json:"allowed_address_pairs,omitempty"`
    88  }
    89  
    90  // ToPortCreateMap builds a request body from CreateOpts.
    91  func (opts CreateOpts) ToPortCreateMap() (map[string]interface{}, error) {
    92  	return golangsdk.BuildRequestBody(opts, "port")
    93  }
    94  
    95  // Create accepts a CreateOpts struct and creates a new network using the values
    96  // provided. You must remember to provide a NetworkID value.
    97  func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
    98  	b, err := opts.ToPortCreateMap()
    99  	if err != nil {
   100  		r.Err = err
   101  		return
   102  	}
   103  	_, r.Err = c.Post(createURL(c), b, &r.Body, nil)
   104  	return
   105  }
   106  
   107  // UpdateOptsBuilder allows extensions to add additional parameters to the
   108  // Update request.
   109  type UpdateOptsBuilder interface {
   110  	ToPortUpdateMap() (map[string]interface{}, error)
   111  }
   112  
   113  // UpdateOpts represents the attributes used when updating an existing port.
   114  type UpdateOpts struct {
   115  	Name                string         `json:"name,omitempty"`
   116  	AdminStateUp        *bool          `json:"admin_state_up,omitempty"`
   117  	FixedIPs            interface{}    `json:"fixed_ips,omitempty"`
   118  	DeviceID            string         `json:"device_id,omitempty"`
   119  	DeviceOwner         string         `json:"device_owner,omitempty"`
   120  	SecurityGroups      *[]string      `json:"security_groups,omitempty"`
   121  	AllowedAddressPairs *[]AddressPair `json:"allowed_address_pairs,omitempty"`
   122  }
   123  
   124  // ToPortUpdateMap builds a request body from UpdateOpts.
   125  func (opts UpdateOpts) ToPortUpdateMap() (map[string]interface{}, error) {
   126  	return golangsdk.BuildRequestBody(opts, "port")
   127  }
   128  
   129  // Update accepts a UpdateOpts struct and updates an existing port using the
   130  // values provided.
   131  func Update(c *golangsdk.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
   132  	b, err := opts.ToPortUpdateMap()
   133  	if err != nil {
   134  		r.Err = err
   135  		return
   136  	}
   137  	_, r.Err = c.Put(updateURL(c, id), b, &r.Body, &golangsdk.RequestOpts{
   138  		OkCodes: []int{200, 201},
   139  	})
   140  	return
   141  }
   142  
   143  // Delete accepts a unique ID and deletes the port associated with it.
   144  func Delete(c *golangsdk.ServiceClient, id string) (r DeleteResult) {
   145  	_, r.Err = c.Delete(deleteURL(c, id), nil)
   146  	return
   147  }
   148  
   149  // IDFromName is a convenience function that returns a port's ID,
   150  // given its name.
   151  func IDFromName(client *golangsdk.ServiceClient, name string) (string, error) {
   152  	count := 0
   153  	id := ""
   154  
   155  	listOpts := ListOpts{
   156  		Name: name,
   157  	}
   158  
   159  	pages, err := List(client, listOpts).AllPages()
   160  	if err != nil {
   161  		return "", err
   162  	}
   163  
   164  	all, err := ExtractPorts(pages)
   165  	if err != nil {
   166  		return "", err
   167  	}
   168  
   169  	for _, s := range all {
   170  		if s.Name == name {
   171  			count++
   172  			id = s.ID
   173  		}
   174  	}
   175  
   176  	switch count {
   177  	case 0:
   178  		return "", golangsdk.ErrResourceNotFound{Name: name, ResourceType: "port"}
   179  	case 1:
   180  		return id, nil
   181  	default:
   182  		return "", golangsdk.ErrMultipleResourcesFound{Name: name, Count: count, ResourceType: "port"}
   183  	}
   184  }