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

     1  package shares
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/huaweicloud/golangsdk"
     7  	"github.com/huaweicloud/golangsdk/pagination"
     8  )
     9  
    10  // SortDir is a type for specifying in which direction to sort a list of Shares.
    11  type SortDir string
    12  
    13  var (
    14  	// SortAsc is used to sort a list of Shares in ascending order.
    15  	SortAsc SortDir = "asc"
    16  	// SortDesc is used to sort a list of Shares in descending order.
    17  	SortDesc SortDir = "desc"
    18  )
    19  
    20  // ListOpts allows the filtering and sorting of paginated collections through
    21  // the API. Filtering is achieved by passing in struct field values that map to
    22  // the share attributes you want to see returned.
    23  type ListOpts struct {
    24  	ID               string
    25  	SnapshotID       string
    26  	ShareToMe        bool    `q:"share_to_me"`
    27  	Name             string  `q:"name"`
    28  	Status           string  `q:"status"`
    29  	BackupID         string  `q:"backup_id"`
    30  	FromProjectID    string  `q:"from_project_id"`
    31  	ToProjectID      string  `q:"to_project_id"`
    32  	AvailabilityZone string  `q:"availability_zone"`
    33  	SortDir          SortDir `q:"sort_dir"`
    34  	Limit            int     `q:"limit"`
    35  	Offset           int     `q:"offset"`
    36  	VolumeID         string  `q:"volume_id"`
    37  }
    38  
    39  // List returns collection of
    40  // share. It accepts a ListOpts struct, which allows you to filter and sort
    41  // the returned collection for greater efficiency.
    42  // Default policy settings return only those share that are owned by the
    43  // tenant who submits the request, unless an admin user submits the request.
    44  func List(c *golangsdk.ServiceClient, opts ListOpts) ([]Share, error) {
    45  	q, err := golangsdk.BuildQueryString(&opts)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	u := listURL(c) + q.String()
    50  	pages, err := pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page {
    51  		return SharePage{pagination.LinkedPageBase{PageResult: r}}
    52  	}).AllPages()
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  
    57  	allShares, err := ExtractShareList(pages)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	return FilterShares(allShares, opts)
    63  }
    64  
    65  func FilterShares(shares []Share, opts ListOpts) ([]Share, error) {
    66  
    67  	var refinedShares []Share
    68  	var matched bool
    69  	m := map[string]FilterStruct{}
    70  
    71  	if opts.ID != "" {
    72  		m["ID"] = FilterStruct{Value: opts.ID}
    73  	}
    74  	if opts.SnapshotID != "" {
    75  		m["SnapshotID"] = FilterStruct{Value: opts.SnapshotID, Driller: []string{"Backup"}}
    76  	}
    77  
    78  	if len(m) > 0 && len(shares) > 0 {
    79  		for _, share := range shares {
    80  			matched = true
    81  
    82  			for key, value := range m {
    83  				if sVal := GetStructNestedField(&share, key, value.Driller); !(sVal == value.Value) {
    84  					matched = false
    85  				}
    86  			}
    87  			if matched {
    88  				refinedShares = append(refinedShares, share)
    89  			}
    90  		}
    91  
    92  	} else {
    93  		refinedShares = shares
    94  	}
    95  
    96  	return refinedShares, nil
    97  }
    98  
    99  type FilterStruct struct {
   100  	Value   string
   101  	Driller []string
   102  }
   103  
   104  func GetStructNestedField(v *Share, field string, structDriller []string) string {
   105  	r := reflect.ValueOf(v)
   106  	for _, drillField := range structDriller {
   107  		f := reflect.Indirect(r).FieldByName(drillField).Interface()
   108  		r = reflect.ValueOf(f)
   109  	}
   110  	f1 := reflect.Indirect(r).FieldByName(field)
   111  	return string(f1.String())
   112  }
   113  
   114  // CreateOptsBuilder allows extensions to add additional parameters to the
   115  // Create request.
   116  type CreateOptsBuilder interface {
   117  	ToShareCreateMap() (map[string]interface{}, error)
   118  }
   119  
   120  // CreateOpts contains all the values needed to create a new share.
   121  type CreateOpts struct {
   122  	//ID of the backup to be shared
   123  	BackupID string `json:"backup_id" required:"true"`
   124  	//IDs of projects with which the backup is shared
   125  	ToProjectIDs []string `json:"to_project_ids" required:"true"`
   126  }
   127  
   128  // ToShareCreateMap builds a create request body from CreateOpts.
   129  func (opts CreateOpts) ToShareCreateMap() (map[string]interface{}, error) {
   130  	return golangsdk.BuildRequestBody(opts, "shared")
   131  }
   132  
   133  // Create will create a new Share based on the values in CreateOpts. To extract
   134  // the Share object from the response, call the Extract method on the
   135  // CreateResult.
   136  func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
   137  	b, err := opts.ToShareCreateMap()
   138  	if err != nil {
   139  		r.Err = err
   140  		return
   141  	}
   142  	reqOpt := &golangsdk.RequestOpts{OkCodes: []int{200}}
   143  	_, r.Err = c.Post(rootURL(c), b, &r.Body, reqOpt)
   144  	return
   145  }
   146  
   147  // Get retrieves a particular share based on its unique ID.
   148  func Get(c *golangsdk.ServiceClient, id string) (r GetResult) {
   149  	_, r.Err = c.Get(resourceURL(c, id), &r.Body, nil)
   150  	return
   151  }
   152  
   153  //DeleteOptsBuilder is an interface which can be able to build the query string
   154  //of share deletion.
   155  type DeleteOptsBuilder interface {
   156  	ToShareDeleteQuery() (string, error)
   157  }
   158  
   159  type DeleteOpts struct {
   160  	//Whether the ID in the URL is a backup share ID or a backup ID
   161  	IsBackupID bool `q:"is_backup_id"`
   162  }
   163  
   164  func (opts DeleteOpts) ToShareDeleteQuery() (string, error) {
   165  	q, err := golangsdk.BuildQueryString(opts)
   166  	return q.String(), err
   167  }
   168  
   169  //Delete is a method by which can be able to delete one or all shares of a backup.
   170  func Delete(client *golangsdk.ServiceClient, id string, opts DeleteOptsBuilder) (r DeleteResult) {
   171  	url := resourceURL(client, id)
   172  	if opts != nil {
   173  		q, err := opts.ToShareDeleteQuery()
   174  		if err != nil {
   175  			r.Err = err
   176  			return
   177  		}
   178  		url += q
   179  	}
   180  	reqOpt := &golangsdk.RequestOpts{OkCodes: []int{200}}
   181  	_, r.Err = client.Delete(url, reqOpt)
   182  	return
   183  }