github.com/chnsz/golangsdk@v0.0.0-20240506093406-85a3fbfa605b/openstack/networking/v1/vpcs/requests.go (about)

     1  package vpcs
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/chnsz/golangsdk"
     7  	"github.com/chnsz/golangsdk/pagination"
     8  )
     9  
    10  // ListOpts allows the filtering and sorting of paginated collections through
    11  // the API. Filtering is achieved by passing in struct field values that map to
    12  // the floating IP attributes you want to see returned. SortKey allows you to
    13  // sort by a particular network attribute. SortDir sets the direction, and is
    14  // either `asc' or `desc'. Marker and Limit are used for pagination.
    15  
    16  type ListOpts struct {
    17  	// ID is the unique identifier for the vpc.
    18  	ID string `json:"id"`
    19  
    20  	// Name is the human readable name for the vpc. It does not have to be
    21  	// unique.
    22  	Name string `json:"name"`
    23  
    24  	//Specifies the range of available subnets in the VPC.
    25  	CIDR string `json:"cidr"`
    26  
    27  	// Enterprise project ID.
    28  	EnterpriseProjectID string `q:"enterprise_project_id"`
    29  
    30  	// Status indicates whether or not a vpc is currently operational.
    31  	Status string `json:"status"`
    32  
    33  	// Specifies tags VPCs must match (returning those matching all tags).
    34  	Tags string `q:"tags"`
    35  
    36  	// Specifies tags VPCs must match (returning those matching at least one of the tags).
    37  	TagsAny string `q:"tags-any"`
    38  
    39  	// Specifies tags VPCs mustn't match (returning those missing all tags).
    40  	NotTags string `q:"not-tags"`
    41  
    42  	// Specifies tags VPCs mustn't match (returning those missing at least one of the tags).
    43  	NotTagsAny string `q:"not-tags-any"`
    44  }
    45  
    46  func (opts ListOpts) hasQueryParameter() bool {
    47  	return opts.EnterpriseProjectID != "" || opts.Tags != "" || opts.TagsAny != "" || opts.NotTags != "" || opts.NotTagsAny != ""
    48  }
    49  
    50  // ToVpcListQuery formats a ListOpts into a query string
    51  func (opts ListOpts) ToVpcListQuery() (string, error) {
    52  	q, err := golangsdk.BuildQueryString(opts)
    53  	if err != nil {
    54  		return "", err
    55  	}
    56  	return q.String(), nil
    57  }
    58  
    59  // List returns collection of
    60  // vpcs. It accepts a ListOpts struct, which allows you to filter and sort
    61  // the returned collection for greater efficiency.
    62  //
    63  // Default policy settings return only those vpcs that are owned by the
    64  // tenant who submits the request, unless an admin user submits the request.
    65  func List(c *golangsdk.ServiceClient, opts ListOpts) ([]Vpc, error) {
    66  	url := rootURL(c)
    67  	if opts.hasQueryParameter() {
    68  		query, err := opts.ToVpcListQuery()
    69  		if err != nil {
    70  			return nil, err
    71  		}
    72  		url += query
    73  	}
    74  
    75  	pages, err := pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page {
    76  		return VpcPage{pagination.LinkedPageBase{PageResult: r}}
    77  	}).AllPages()
    78  	if err != nil {
    79  		return nil, err
    80  	}
    81  
    82  	allVpcs, err := ExtractVpcs(pages)
    83  	if err != nil {
    84  		return nil, err
    85  	}
    86  
    87  	return FilterVPCs(allVpcs, opts)
    88  }
    89  
    90  func FilterVPCs(vpcs []Vpc, opts ListOpts) ([]Vpc, error) {
    91  
    92  	var refinedVPCs []Vpc
    93  	var matched bool
    94  	m := map[string]interface{}{}
    95  
    96  	if opts.ID != "" {
    97  		m["ID"] = opts.ID
    98  	}
    99  	if opts.Name != "" {
   100  		m["Name"] = opts.Name
   101  	}
   102  	if opts.Status != "" {
   103  		m["Status"] = opts.Status
   104  	}
   105  	if opts.CIDR != "" {
   106  		m["CIDR"] = opts.CIDR
   107  	}
   108  
   109  	if len(m) > 0 && len(vpcs) > 0 {
   110  		for _, vpc := range vpcs {
   111  			matched = true
   112  
   113  			for key, value := range m {
   114  				if sVal := getStructField(&vpc, key); !(sVal == value) {
   115  					matched = false
   116  				}
   117  			}
   118  
   119  			if matched {
   120  				refinedVPCs = append(refinedVPCs, vpc)
   121  			}
   122  		}
   123  
   124  	} else {
   125  		refinedVPCs = vpcs
   126  	}
   127  
   128  	return refinedVPCs, nil
   129  }
   130  
   131  func getStructField(v *Vpc, field string) string {
   132  	r := reflect.ValueOf(v)
   133  	f := reflect.Indirect(r).FieldByName(field)
   134  	return string(f.String())
   135  }
   136  
   137  // CreateOptsBuilder allows extensions to add additional parameters to the
   138  // Create request.
   139  type CreateOptsBuilder interface {
   140  	ToVpcCreateMap() (map[string]interface{}, error)
   141  }
   142  
   143  // CreateOpts contains all the values needed to create a new vpc. There are
   144  // no required values.
   145  type CreateOpts struct {
   146  	Name                string `json:"name,omitempty"`
   147  	CIDR                string `json:"cidr,omitempty"`
   148  	Description         string `json:"description,omitempty"`
   149  	EnterpriseProjectID string `json:"enterprise_project_id,omitempty"`
   150  }
   151  
   152  // ToVpcCreateMap builds a create request body from CreateOpts.
   153  func (opts CreateOpts) ToVpcCreateMap() (map[string]interface{}, error) {
   154  	return golangsdk.BuildRequestBody(opts, "vpc")
   155  }
   156  
   157  // Create accepts a CreateOpts struct and uses the values to create a new
   158  // logical vpc. When it is created, the vpc does not have an internal
   159  // interface - it is not associated to any subnet.
   160  //
   161  // You can optionally specify an external gateway for a vpc using the
   162  // GatewayInfo struct. The external gateway for the vpc must be plugged into
   163  // an external network (it is external if its `vpc:external' field is set to
   164  // true).
   165  func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
   166  	b, err := opts.ToVpcCreateMap()
   167  	if err != nil {
   168  		r.Err = err
   169  		return
   170  	}
   171  	reqOpt := &golangsdk.RequestOpts{OkCodes: []int{200}}
   172  	_, r.Err = c.Post(rootURL(c), b, &r.Body, reqOpt)
   173  	return
   174  }
   175  
   176  // Get retrieves a particular vpc based on its unique ID.
   177  func Get(c *golangsdk.ServiceClient, id string) (r GetResult) {
   178  	_, r.Err = c.Get(resourceURL(c, id), &r.Body, nil)
   179  	return
   180  }
   181  
   182  // UpdateOptsBuilder allows extensions to add additional parameters to the
   183  // Update request.
   184  type UpdateOptsBuilder interface {
   185  	ToVpcUpdateMap() (map[string]interface{}, error)
   186  }
   187  
   188  // UpdateOpts contains the values used when updating a vpc.
   189  type UpdateOpts struct {
   190  	Name             string  `json:"name,omitempty"`
   191  	CIDR             string  `json:"cidr,omitempty"`
   192  	Description      *string `json:"description,omitempty"`
   193  	EnableSharedSnat *bool   `json:"enable_shared_snat,omitempty"`
   194  }
   195  
   196  // ToVpcUpdateMap builds an update body based on UpdateOpts.
   197  func (opts UpdateOpts) ToVpcUpdateMap() (map[string]interface{}, error) {
   198  	return golangsdk.BuildRequestBody(opts, "vpc")
   199  }
   200  
   201  // Update allows vpcs to be updated. You can update the name, administrative
   202  // state, and the external gateway. For more information about how to set the
   203  // external gateway for a vpc, see Create. This operation does not enable
   204  // the update of vpc interfaces. To do this, use the AddInterface and
   205  // RemoveInterface functions.
   206  func Update(c *golangsdk.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
   207  	b, err := opts.ToVpcUpdateMap()
   208  	if err != nil {
   209  		r.Err = err
   210  		return
   211  	}
   212  	_, r.Err = c.Put(resourceURL(c, id), b, &r.Body, &golangsdk.RequestOpts{
   213  		OkCodes: []int{200},
   214  	})
   215  	return
   216  }
   217  
   218  // Delete will permanently delete a particular vpc based on its unique ID.
   219  func Delete(c *golangsdk.ServiceClient, id string) (r DeleteResult) {
   220  	_, r.Err = c.Delete(resourceURL(c, id), nil)
   221  	return
   222  }