github.com/chnsz/golangsdk@v0.0.0-20240506093406-85a3fbfa605b/openstack/evs/v2/cloudvolumes/requests.go (about)

     1  package cloudvolumes
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/chnsz/golangsdk"
     7  	"github.com/chnsz/golangsdk/pagination"
     8  )
     9  
    10  var requestOpts = golangsdk.RequestOpts{
    11  	MoreHeaders: map[string]string{"Content-Type": "application/json", "X-Language": "en-us"},
    12  }
    13  
    14  // CreateOptsBuilder allows extensions to add additional parameters to the
    15  // Create request.
    16  type CreateOptsBuilder interface {
    17  	ToVolumeCreateMap() (map[string]interface{}, error)
    18  }
    19  
    20  // CreateOpts contains options for creating a Volume. This object is passed to
    21  // the cloudvolumes.Create function.
    22  type CreateOpts struct {
    23  	Volume     VolumeOpts     `json:"volume" required:"true"`
    24  	ChargeInfo *BssParam      `json:"bssParam,omitempty"`
    25  	Scheduler  *SchedulerOpts `json:"OS-SCH-HNT:scheduler_hints,omitempty"`
    26  	ServerID   string         `json:"server_id,omitempty"`
    27  }
    28  
    29  type BssParam struct {
    30  	// Specifies the billing mode. The default value is postPaid.
    31  	//   prePaid: indicates the yearly/monthly billing mode.
    32  	//   postPaid: indicates the pay-per-use billing mode.
    33  	ChargingMode string `json:"chargingMode" required:"true"`
    34  	// Specifies the unit of the subscription term.
    35  	// This parameter is valid and mandatory only when chargingMode is set to prePaid.
    36  	//   month: indicates that the unit is month.
    37  	//   year: indicates that the unit is year.
    38  	PeriodType string `json:"periodType,omitempty"`
    39  	// Specifies the subscription term. This parameter is valid and mandatory only when chargingMode is set to prePaid.
    40  	//   When periodType is set to month, the parameter value ranges from 1 to 9.
    41  	//   When periodType is set to year, the parameter value must be set to 1.
    42  	PeriodNum int `json:"periodNum,omitempty"`
    43  	// Specifies whether to pay immediately. This parameter is valid only when chargingMode is set to prePaid. The default value is false.
    44  	//   false: indicates not to pay immediately after an order is created.
    45  	//   true: indicates to pay immediately after an order is created. The system will automatically deduct fees from the account balance.
    46  	IsAutoPay string `json:"isAutoPay,omitempty"`
    47  	// Specifies whether to automatically renew the subscription.
    48  	// This parameter is valid only when chargingMode is set to prePaid. The default value is false.
    49  	//   false: indicates not to automatically renew the subscription.
    50  	//   true: indicates to automatically renew the subscription. The automatic renewal term is the same as the subscription term.
    51  	IsAutoRenew string `json:"isAutoRenew,omitempty"`
    52  }
    53  
    54  // VolumeOpts contains options for creating a Volume.
    55  type VolumeOpts struct {
    56  	// The availability zone
    57  	AvailabilityZone string `json:"availability_zone" required:"true"`
    58  	// The associated volume type
    59  	VolumeType string `json:"volume_type" required:"true"`
    60  	// The volume name
    61  	Name string `json:"name,omitempty"`
    62  	// The volume description
    63  	Description string `json:"description,omitempty"`
    64  	// The size of the volume, in GB
    65  	Size int `json:"size,omitempty"`
    66  	// The number to be created in a batch
    67  	Count int `json:"count,omitempty"`
    68  	// The backup_id
    69  	BackupID string `json:"backup_id,omitempty"`
    70  	// the ID of the existing volume snapshot
    71  	SnapshotID string `json:"snapshot_id,omitempty"`
    72  	// the ID of the image in IMS
    73  	ImageID string `json:"imageRef,omitempty"`
    74  	// Shared disk
    75  	Multiattach bool `json:"multiattach,omitempty"`
    76  	// One or more metadata key and value pairs to associate with the volume
    77  	Metadata map[string]string `json:"metadata,omitempty"`
    78  	// One or more tag key and value pairs to associate with the volume
    79  	Tags map[string]string `json:"tags,omitempty"`
    80  	// the enterprise project id
    81  	EnterpriseProjectID string `json:"enterprise_project_id,omitempty"`
    82  	// The iops of evs volume. Only required when volume_type is `GPSSD2` or `ESSD2`
    83  	IOPS int `json:"iops,omitempty"`
    84  	// The throughput of evs volume. Only required when volume_type is `GPSSD2`
    85  	Throughput int `json:"throughput,omitempty"`
    86  }
    87  
    88  // SchedulerOpts contains the scheduler hints
    89  type SchedulerOpts struct {
    90  	StorageID string `json:"dedicated_storage_id,omitempty"`
    91  }
    92  
    93  // ToVolumeCreateMap assembles a request body based on the contents of a
    94  // CreateOpts.
    95  func (opts CreateOpts) ToVolumeCreateMap() (map[string]interface{}, error) {
    96  	return golangsdk.BuildRequestBody(opts, "")
    97  }
    98  
    99  // Create will create a new Volume based on the values in CreateOpts.
   100  func Create(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r JobResult) {
   101  	b, err := opts.ToVolumeCreateMap()
   102  	if err != nil {
   103  		r.Err = err
   104  		return
   105  	}
   106  
   107  	// the version of create API is v2.1
   108  	newClient := *client
   109  	baseURL := newClient.ResourceBaseURL()
   110  	newClient.ResourceBase = strings.Replace(baseURL, "/v2/", "/v2.1/", 1)
   111  
   112  	_, r.Err = newClient.Post(createURL(&newClient), b, &r.Body, nil)
   113  	return
   114  }
   115  
   116  // ExtendOptsBuilder allows extensions to add additional parameters to the
   117  // ExtendSize request.
   118  type ExtendOptsBuilder interface {
   119  	ToVolumeExtendMap() (map[string]interface{}, error)
   120  }
   121  
   122  // ExtendOpts contains options for extending the size of an existing Volume.
   123  // This object is passed to the cloudvolumes.ExtendSize function.
   124  type ExtendOpts struct {
   125  	SizeOpts   ExtendSizeOpts    `json:"os-extend" required:"true"`
   126  	ChargeInfo *ExtendChargeOpts `json:"bssParam,omitempty"`
   127  }
   128  
   129  // ExtendSizeOpts contains the new size of the volume, in GB.
   130  type ExtendSizeOpts struct {
   131  	NewSize int `json:"new_size" required:"true"`
   132  }
   133  
   134  // ExtendChargeOpts contains the charging parameters of the volume
   135  type ExtendChargeOpts struct {
   136  	IsAutoPay string `json:"isAutoPay,omitempty"`
   137  }
   138  
   139  // ToVolumeExtendMap assembles a request body based on the contents of an
   140  // ExtendOpts.
   141  func (opts ExtendOpts) ToVolumeExtendMap() (map[string]interface{}, error) {
   142  	return golangsdk.BuildRequestBody(opts, "")
   143  }
   144  
   145  // ExtendSize will extend the size of the volume based on the provided information.
   146  // This operation does not return a response body.
   147  func ExtendSize(client *golangsdk.ServiceClient, id string, opts ExtendOptsBuilder) (r JobResult) {
   148  	b, err := opts.ToVolumeExtendMap()
   149  	if err != nil {
   150  		r.Err = err
   151  		return
   152  	}
   153  	// the version of extend API is v2.1
   154  	newClient := *client
   155  	baseURL := newClient.ResourceBaseURL()
   156  	newClient.ResourceBase = strings.Replace(baseURL, "/v2/", "/v2.1/", 1)
   157  
   158  	_, r.Err = newClient.Post(actionURL(&newClient, id), b, &r.Body, &golangsdk.RequestOpts{
   159  		OkCodes: []int{202},
   160  	})
   161  	return
   162  }
   163  
   164  // UpdateOptsBuilder allows extensions to add additional parameters to the
   165  // Update request.
   166  type UpdateOptsBuilder interface {
   167  	ToVolumeUpdateMap() (map[string]interface{}, error)
   168  }
   169  
   170  // UpdateOpts contain options for updating an existing Volume. This object is passed
   171  // to the cloudvolumes.Update function.
   172  type UpdateOpts struct {
   173  	Name        string  `json:"name,omitempty"`
   174  	Description *string `json:"description,omitempty"`
   175  }
   176  
   177  // ToVolumeUpdateMap assembles a request body based on the contents of an
   178  // UpdateOpts.
   179  func (opts UpdateOpts) ToVolumeUpdateMap() (map[string]interface{}, error) {
   180  	return golangsdk.BuildRequestBody(opts, "volume")
   181  }
   182  
   183  // Update will update the Volume with provided information. To extract the updated
   184  // Volume from the response, call the Extract method on the UpdateResult.
   185  func Update(client *golangsdk.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
   186  	b, err := opts.ToVolumeUpdateMap()
   187  	if err != nil {
   188  		r.Err = err
   189  		return
   190  	}
   191  	_, r.Err = client.Put(resourceURL(client, id), b, &r.Body, &golangsdk.RequestOpts{
   192  		OkCodes: []int{200},
   193  	})
   194  	return
   195  }
   196  
   197  // DeleteOptsBuilder is an interface by which can be able to build the query string
   198  // of volume deletion.
   199  type DeleteOptsBuilder interface {
   200  	ToVolumeDeleteQuery() (string, error)
   201  }
   202  
   203  // DeleteOpts contain options for deleting an existing Volume. This object is passed
   204  // to the cloudvolumes.Delete function.
   205  type DeleteOpts struct {
   206  	// Specifies to delete all snapshots associated with the EVS disk.
   207  	Cascade bool `q:"cascade"`
   208  }
   209  
   210  // ToVolumeDeleteQuery assembles a request body based on the contents of an
   211  // DeleteOpts.
   212  func (opts DeleteOpts) ToVolumeDeleteQuery() (string, error) {
   213  	q, err := golangsdk.BuildQueryString(opts)
   214  	return q.String(), err
   215  }
   216  
   217  // Delete will delete the existing Volume with the provided ID
   218  func Delete(client *golangsdk.ServiceClient, id string, opts DeleteOptsBuilder) (r DeleteResult) {
   219  	url := resourceURL(client, id)
   220  	if opts != nil {
   221  		q, err := opts.ToVolumeDeleteQuery()
   222  		if err != nil {
   223  			r.Err = err
   224  			return
   225  		}
   226  		url += q
   227  	}
   228  	_, r.Err = client.Delete(url, &golangsdk.RequestOpts{
   229  		OkCodes: []int{200},
   230  	})
   231  	return
   232  }
   233  
   234  // Get retrieves the Volume with the provided ID. To extract the Volume object
   235  // from the response, call the Extract method on the GetResult.
   236  func Get(client *golangsdk.ServiceClient, id string) (r GetResult) {
   237  	_, r.Err = client.Get(resourceURL(client, id), &r.Body, nil)
   238  	return
   239  }
   240  
   241  // ListOptsBuilder allows extensions to add additional parameters to the List
   242  // request.
   243  type ListOptsBuilder interface {
   244  	ToVolumeListQuery() (string, error)
   245  }
   246  
   247  // ListOpts holds options for listing Volumes. It is passed to the volumes.List
   248  // function.
   249  type ListOpts struct {
   250  	// Name will filter by the specified volume name.
   251  	Name string `q:"name"`
   252  	// Status will filter by the specified status.
   253  	Status string `q:"status"`
   254  	// Metadata will filter results based on specified metadata.
   255  	Metadata string `q:"metadata"`
   256  	// Specifies the disk ID.
   257  	ID string `q:"id"`
   258  	// Specifies the disk IDs. The parameter value is in the ids=["id1","id2",...,"idx"] format.
   259  	// In the response, the ids value contains valid disk IDs only. Invalid disk IDs will be ignored.
   260  	// Details about a maximum of 60 disks can be queried.
   261  	// If parameters id and ids are both specified in the request, id will be ignored.
   262  	IDs string `q:"ids"`
   263  	// Specifies the AZ.
   264  	AvailabilityZone string `q:"availability_zone"`
   265  	// Specifies the ID of the DSS storage pool. All disks in the DSS storage pool can be filtered out.
   266  	// Only precise match is supported.
   267  	DedicatedStorageID string `q:"dedicated_storage_id"`
   268  	// Specifies the name of the DSS storage pool. All disks in the DSS storage pool can be filtered out.
   269  	// Fuzzy match is supported.
   270  	DedicatedStorageName string `q:"dedicated_storage_name"`
   271  	// Specifies the enterprise project ID for filtering. If input parameter all_granted_eps exists, disks in all
   272  	// enterprise projects that are within the permission scope will be queried.
   273  	EnterpriseProjectID string `q:"enterprise_project_id"`
   274  	// Specifies whether the disk is shareable.
   275  	//   true: specifies a shared disk.
   276  	//   false: specifies a non-shared disk.
   277  	Multiattach bool `q:"multiattach"`
   278  	// Specifies the service type. Currently, the supported services are EVS, DSS, and DESS.
   279  	ServiceType string `q:"service_type"`
   280  	// Specifies the server ID.
   281  	// This parameter is used to filter all the EVS disks that have been attached to this server.
   282  	ServerID string `q:"server_id"`
   283  	// Specifies the keyword based on which the returned results are sorted.
   284  	// The value can be id, status, size, or created_at, and the default value is created_at.
   285  	SortKey string `q:"sort_key"`
   286  	// Specifies the result sorting order. The default value is desc.
   287  	//   desc: indicates the descending order.
   288  	//   asc: indicates the ascending order.
   289  	SortDir string `q:"sort_dir"`
   290  	// Specifies the disk type ID.
   291  	// You can obtain the disk type ID in Querying EVS Disk Types.
   292  	// That is, the id value in the volume_types parameter description table.
   293  	VolumeTypeID string `q:"volume_type_id"`
   294  	// Requests a page size of items.
   295  	Limit int `q:"limit"`
   296  	// Used in conjunction with limit to return a slice of items.
   297  	Offset int `q:"offset"`
   298  	// The ID of the last-seen item.
   299  	Marker string `q:"marker"`
   300  }
   301  
   302  // ToVolumeListQuery formats a ListOpts into a query string.
   303  func (opts ListOpts) ToVolumeListQuery() (string, error) {
   304  	q, err := golangsdk.BuildQueryString(opts)
   305  	return q.String(), err
   306  }
   307  
   308  // List returns Volumes optionally limited by the conditions provided in ListOpts.
   309  func List(client *golangsdk.ServiceClient, opts ListOptsBuilder) pagination.Pager {
   310  	url := listURL(client)
   311  	if opts != nil {
   312  		query, err := opts.ToVolumeListQuery()
   313  		if err != nil {
   314  			return pagination.Pager{Err: err}
   315  		}
   316  		url += query
   317  	}
   318  
   319  	return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {
   320  		p := VolumePage{pagination.OffsetPageBase{PageResult: r}}
   321  		return p
   322  	})
   323  }
   324  
   325  func ListPage(client *golangsdk.ServiceClient, opts ListOptsBuilder) ([]Volume, error) {
   326  	url := listURL(client)
   327  	if opts != nil {
   328  		query, err := opts.ToVolumeListQuery()
   329  		if err != nil {
   330  			return nil, err
   331  		}
   332  		url += query
   333  	}
   334  
   335  	var rst golangsdk.Result
   336  	_, err := client.Get(url, &rst.Body, &golangsdk.RequestOpts{
   337  		MoreHeaders: requestOpts.MoreHeaders,
   338  	})
   339  
   340  	if err != nil {
   341  		return nil, err
   342  	}
   343  
   344  	var r struct {
   345  		Volumes []Volume
   346  	}
   347  	err = rst.ExtractInto(&r)
   348  	return r.Volumes, err
   349  }