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

     1  package cloudimages
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"time"
     7  
     8  	"github.com/chnsz/golangsdk"
     9  	"github.com/chnsz/golangsdk/pagination"
    10  )
    11  
    12  type ListOptsBuilder interface {
    13  	ToImageListQuery() (string, error)
    14  }
    15  
    16  type ListOpts struct {
    17  	Isregistered           string `q:"__isregistered"`
    18  	Imagetype              string `q:"__imagetype"`
    19  	WholeImage             bool   `q:"__whole_image"`
    20  	SystemCmkid            string `q:"__system__cmkid"`
    21  	Protected              bool   `q:"protected"`
    22  	Visibility             string `q:"visibility"`
    23  	Owner                  string `q:"owner"`
    24  	ID                     string `q:"id"`
    25  	Status                 string `q:"status"`
    26  	Name                   string `q:"name"`
    27  	FlavorId               string `q:"flavor_id"`
    28  	ContainerFormat        string `q:"container_format"`
    29  	DiskFormat             string `q:"disk_format"`
    30  	MinRam                 int    `q:"min_ram"`
    31  	MinDisk                int    `q:"min_disk"`
    32  	Marker                 string `q:"marker"`
    33  	Limit                  int    `q:"limit"`
    34  	SortKey                string `q:"sort_key"`
    35  	SortDir                string `q:"sort_dir"`
    36  	OsType                 string `q:"__os_type"`
    37  	Platform               string `q:"__platform"`
    38  	OsVersion              string `q:"__os_version"`
    39  	OsBit                  string `q:"__os_bit"`
    40  	Tag                    string `q:"tag"`
    41  	MemberStatus           string `q:"member_status"`
    42  	SupportKvm             string `q:"__support_kvm"`
    43  	SupportXen             string `q:"__support_xen"`
    44  	SupportLargeMemory     string `q:"__support_largememory"`
    45  	SupportDiskintensive   string `q:"__support_diskintensive"`
    46  	SupportHighperformance string `q:"__support_highperformance"`
    47  	SupportXenGpuType      string `q:"__support_xen_gpu_type"`
    48  	SupportKvmGpuType      string `q:"__support_kvm_gpu_type"`
    49  	SupportXenHana         string `q:"__support_xen_hana"`
    50  	SupportKvmInfiniband   string `q:"__support_kvm_infiniband"`
    51  	VirtualEnvType         string `q:"virtual_env_type"`
    52  	Architecture           string `q:"architecture"`
    53  	EnterpriseProjectID    string `q:"enterprise_project_id"`
    54  	// CreatedAtQuery filters images based on their creation date.
    55  	CreatedAtQuery *ImageDateQuery
    56  	// UpdatedAtQuery filters images based on their updated date.
    57  	UpdatedAtQuery *ImageDateQuery
    58  }
    59  
    60  // ImageDateFilter represents a valid filter to use for filtering
    61  // images by their date during a List.
    62  type ImageDateFilter string
    63  
    64  const (
    65  	FilterGT  ImageDateFilter = "gt"
    66  	FilterGTE ImageDateFilter = "gte"
    67  	FilterLT  ImageDateFilter = "lt"
    68  	FilterLTE ImageDateFilter = "lte"
    69  	FilterNEQ ImageDateFilter = "neq"
    70  	FilterEQ  ImageDateFilter = "eq"
    71  )
    72  
    73  // ImageDateQuery represents a date field to be used for listing images.
    74  // If no filter is specified, the query will act as though FilterEQ was
    75  // set.
    76  type ImageDateQuery struct {
    77  	Date   time.Time
    78  	Filter ImageDateFilter
    79  }
    80  
    81  // ToImageListQuery formats a ListOpts into a query string.
    82  func (opts ListOpts) ToImageListQuery() (string, error) {
    83  	q, err := golangsdk.BuildQueryString(opts)
    84  	params := q.Query()
    85  
    86  	if opts.CreatedAtQuery != nil {
    87  		createdAt := opts.CreatedAtQuery.Date.Format(time.RFC3339)
    88  		if v := opts.CreatedAtQuery.Filter; v != "" {
    89  			createdAt = fmt.Sprintf("%s:%s", v, createdAt)
    90  		}
    91  		params.Add("created_at", createdAt)
    92  	}
    93  
    94  	if opts.UpdatedAtQuery != nil {
    95  		updatedAt := opts.UpdatedAtQuery.Date.Format(time.RFC3339)
    96  		if v := opts.UpdatedAtQuery.Filter; v != "" {
    97  			updatedAt = fmt.Sprintf("%s:%s", v, updatedAt)
    98  		}
    99  		params.Add("updated_at", updatedAt)
   100  	}
   101  
   102  	q = &url.URL{RawQuery: params.Encode()}
   103  	return q.String(), err
   104  }
   105  
   106  // List implements images list request
   107  func List(client *golangsdk.ServiceClient, opts ListOptsBuilder) pagination.Pager {
   108  	url := listURL(client)
   109  	if opts != nil {
   110  		query, err := opts.ToImageListQuery()
   111  		if err != nil {
   112  			return pagination.Pager{Err: err}
   113  		}
   114  		url += query
   115  	}
   116  	return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {
   117  		imagePage := ImagePage{
   118  			serviceURL:     client.ServiceURL(),
   119  			LinkedPageBase: pagination.LinkedPageBase{PageResult: r},
   120  		}
   121  
   122  		return imagePage
   123  	})
   124  }
   125  
   126  // CreateOptsBuilder allows extensions to add parameters to the Create request.
   127  type CreateOptsBuilder interface {
   128  	// Returns value that can be passed to json.Marshal
   129  	ToImageCreateMap() (map[string]interface{}, error)
   130  }
   131  
   132  // CreateOpts represents options used to create an image.
   133  type CreateByServerOpts struct {
   134  	// the name of the system disk image
   135  	Name string `json:"name" required:"true"`
   136  	// Description of the image
   137  	Description string `json:"description,omitempty"`
   138  	// server id to be converted
   139  	InstanceId string `json:"instance_id" required:"true"`
   140  	// the data disks to be converted
   141  	DataImages []DataImage `json:"data_images,omitempty"`
   142  	// image label "key.value"
   143  	Tags []string `json:"tags,omitempty"`
   144  	// One or more tag key and value pairs to associate with the image
   145  	ImageTags []ImageTag `json:"image_tags,omitempty"`
   146  	// the maximum memory of the image in the unit of MB
   147  	MaxRam int `json:"max_ram,omitempty"`
   148  	// the minimum memory of the image in the unit of MB
   149  	MinRam int `json:"min_ram,omitempty"`
   150  	// Enterprise project ID
   151  	EnterpriseProjectID string `json:"enterprise_project_id,omitempty"`
   152  }
   153  
   154  // CreateOpts represents options used to create an image.
   155  type CreateByOBSOpts struct {
   156  	// the name of the system disk image
   157  	Name string `json:"name" required:"true"`
   158  	// Description of image
   159  	Description string `json:"description,omitempty"`
   160  	// the OS version
   161  	OsVersion string `json:"os_version,omitempty"`
   162  	// the URL of the external image file in the OBS bucket
   163  	ImageUrl string `json:"image_url" required:"true"`
   164  	// the minimum size of the system disk in the unit of GB
   165  	MinDisk int `json:"min_disk" required:"true"`
   166  	//whether automatic configuration is enabled,the value can be true or false
   167  	IsConfig bool `json:"is_config,omitempty"`
   168  	// the master key used for encrypting an image
   169  	CmkId string `json:"cmk_id,omitempty"`
   170  	// image label "key.value"
   171  	Tags []string `json:"tags,omitempty"`
   172  	// One or more tag key and value pairs to associate with the image
   173  	ImageTags []ImageTag `json:"image_tags,omitempty"`
   174  	// the image type, the value can be ECS,BMS,FusionCompute, or Ironic
   175  	Type string `json:"type,omitempty"`
   176  	// the maximum memory of the image in the unit of MB
   177  	MaxRam int `json:"max_ram,omitempty"`
   178  	// the minimum memory of the image in the unit of MB
   179  	MinRam int `json:"min_ram,omitempty"`
   180  	// Enterprise project ID
   181  	EnterpriseProjectID string `json:"enterprise_project_id,omitempty"`
   182  }
   183  
   184  // CreateWholeImageOpts represents options used to create an image.
   185  type CreateWholeImageOpts struct {
   186  	// the name of the system disk image
   187  	Name string `json:"name" required:"true"`
   188  	// Description of image
   189  	Description string `json:"description,omitempty"`
   190  	// the ID of the instance
   191  	InstanceId string `json:"instance_id,omitempty"`
   192  	// the ID of the CBR backup
   193  	BackupId string `json:"backup_id,omitempty"`
   194  	// image label "key.value"
   195  	Tags []string `json:"tags,omitempty"`
   196  	// One or more tag key and value pairs to associate with the image
   197  	ImageTags []ImageTag `json:"image_tags,omitempty"`
   198  	// the maximum memory of the image in the unit of MB
   199  	MaxRam int `json:"max_ram,omitempty"`
   200  	// the minimum memory of the image in the unit of MB
   201  	MinRam int `json:"min_ram,omitempty"`
   202  	// Enterprise project ID
   203  	EnterpriseProjectID string `json:"enterprise_project_id,omitempty"`
   204  	// the ID of the vault to which an ECS is to be added or has been added
   205  	VaultId string `json:"vault_id,omitempty"`
   206  	// the method of creating a full-ECS image
   207  	WholeImageType string `json:"whole_image_type,omitempty"`
   208  }
   209  
   210  // CreateOpts represents options used to create an image.
   211  type CreateDataImageByServerOpts struct {
   212  	// the data disks to be converted
   213  	DataImages []DataImage `json:"data_images" required:"true"`
   214  }
   215  
   216  // CreateOpts represents options used to create an image.
   217  type CreateDataImageByOBSOpts struct {
   218  	// the name of the data disk image
   219  	Name string `json:"name" required:"true"`
   220  	// Description of image
   221  	Description string `json:"description,omitempty"`
   222  	// the OS type
   223  	OsType string `json:"os_type" required:"true"`
   224  	// the URL of the external image file in the OBS bucket
   225  	ImageUrl string `json:"image_url" required:"true"`
   226  	// the minimum size of the system disk in the unit of GB
   227  	MinDisk int `json:"min_disk" required:"true"`
   228  	// the master key used for encrypting an image
   229  	CmkId string `json:"cmk_id,omitempty"`
   230  	// Enterprise project ID
   231  	EnterpriseProjectID string `json:"enterprise_project_id,omitempty"`
   232  }
   233  
   234  type DataImage struct {
   235  	// the data disk image name
   236  	Name string `json:"name" required:"true"`
   237  	// the data disk ID
   238  	VolumeId string `json:"volume_id" required:"true"`
   239  	// information about the data disk
   240  	Description string `json:"description,omitempty"`
   241  	// the data disk image tags
   242  	Tags []string `json:"tags,omitempty"`
   243  }
   244  
   245  type ImageTag struct {
   246  	Key   string `json:"key" required:"true"`
   247  	Value string `json:"value,omitempty"`
   248  }
   249  
   250  // ToImageCreateMap assembles a request body based on the contents of
   251  // a CreateByServerOpts.
   252  func (opts CreateByServerOpts) ToImageCreateMap() (map[string]interface{}, error) {
   253  	return golangsdk.BuildRequestBody(opts, "")
   254  }
   255  
   256  func (opts CreateByOBSOpts) ToImageCreateMap() (map[string]interface{}, error) {
   257  	return golangsdk.BuildRequestBody(opts, "")
   258  }
   259  
   260  func (opts CreateDataImageByServerOpts) ToImageCreateMap() (map[string]interface{}, error) {
   261  	return golangsdk.BuildRequestBody(opts, "")
   262  }
   263  
   264  func (opts CreateDataImageByOBSOpts) ToImageCreateMap() (map[string]interface{}, error) {
   265  	return golangsdk.BuildRequestBody(opts, "")
   266  }
   267  
   268  func (opts CreateWholeImageOpts) ToImageCreateMap() (map[string]interface{}, error) {
   269  	return golangsdk.BuildRequestBody(opts, "")
   270  }
   271  
   272  // Create implements create image request.
   273  func CreateImageByServer(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r JobResult) {
   274  	b, err := opts.ToImageCreateMap()
   275  	if err != nil {
   276  		r.Err = err
   277  		return
   278  	}
   279  
   280  	_, r.Err = client.Post(createURL(client), b, &r.Body, &golangsdk.RequestOpts{OkCodes: []int{200}})
   281  	return
   282  }
   283  
   284  // Create implements create image request.
   285  func CreateImageByOBS(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r JobResult) {
   286  	b, err := opts.ToImageCreateMap()
   287  	if err != nil {
   288  		r.Err = err
   289  		return
   290  	}
   291  
   292  	_, r.Err = client.Post(createURL(client), b, &r.Body, &golangsdk.RequestOpts{OkCodes: []int{200}})
   293  	return
   294  }
   295  
   296  // Create implements create image request.
   297  func CreateDataImageByServer(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r JobResult) {
   298  	b, err := opts.ToImageCreateMap()
   299  	if err != nil {
   300  		r.Err = err
   301  		return
   302  	}
   303  
   304  	_, r.Err = client.Post(createURL(client), b, &r.Body, &golangsdk.RequestOpts{OkCodes: []int{200}})
   305  	return
   306  }
   307  
   308  // Create implements create image request.
   309  func CreateDataImageByOBS(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r JobResult) {
   310  	b, err := opts.ToImageCreateMap()
   311  	if err != nil {
   312  		r.Err = err
   313  		return
   314  	}
   315  
   316  	_, r.Err = client.Post(createDataImageURL(client), b, &r.Body, &golangsdk.RequestOpts{OkCodes: []int{200}})
   317  	return
   318  }
   319  
   320  // Create implements create whole image request.
   321  func CreateWholeImageByServer(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r JobResult) {
   322  	b, err := opts.ToImageCreateMap()
   323  	if err != nil {
   324  		r.Err = err
   325  		return
   326  	}
   327  
   328  	_, r.Err = client.Post(createWholeImageURL(client), b, &r.Body, nil)
   329  	return
   330  }
   331  
   332  // Create implements create image request.
   333  func CreateWholeImageByBackup(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r JobResult) {
   334  	b, err := opts.ToImageCreateMap()
   335  	if err != nil {
   336  		r.Err = err
   337  		return
   338  	}
   339  
   340  	_, r.Err = client.Post(createWholeImageURL(client), b, &r.Body, nil)
   341  	return
   342  }
   343  
   344  // Update implements image updated request.
   345  func Update(client *golangsdk.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
   346  	b, err := opts.ToImageUpdateMap()
   347  	if err != nil {
   348  		r.Err = err
   349  		return r
   350  	}
   351  	_, r.Err = client.Patch(updateURL(client, id), b, &r.Body, &golangsdk.RequestOpts{
   352  		OkCodes:     []int{200},
   353  		MoreHeaders: map[string]string{"Content-Type": "application/openstack-images-v2.1-json-patch"},
   354  	})
   355  	return
   356  }
   357  
   358  // UpdateOptsBuilder allows extensions to add additional parameters to the Update request.
   359  type UpdateOptsBuilder interface {
   360  	ToImageUpdateMap() ([]interface{}, error)
   361  }
   362  
   363  // UpdateOpts implements UpdateOpts
   364  type UpdateOpts []Patch
   365  
   366  // ToImageUpdateMap assembles a request body based on the contents of UpdateOpts.
   367  func (opts UpdateOpts) ToImageUpdateMap() ([]interface{}, error) {
   368  	m := make([]interface{}, len(opts))
   369  	for i, patch := range opts {
   370  		patchJSON := patch.ToImagePatchMap()
   371  		m[i] = patchJSON
   372  	}
   373  	return m, nil
   374  }
   375  
   376  // Patch represents a single update to an existing image. Multiple updates
   377  // to an image can be submitted at the same time.
   378  type Patch interface {
   379  	ToImagePatchMap() map[string]interface{}
   380  }
   381  
   382  // UpdateOp represents a valid update operation.
   383  type UpdateOp string
   384  
   385  const (
   386  	AddOp     UpdateOp = "add"
   387  	ReplaceOp UpdateOp = "replace"
   388  	RemoveOp  UpdateOp = "remove"
   389  )
   390  
   391  // UpdateImageProperty represents an update property request.
   392  type UpdateImageProperty struct {
   393  	Op    UpdateOp
   394  	Name  string
   395  	Value interface{}
   396  }
   397  
   398  // ToImagePatchMap assembles a request body based on UpdateImageProperty.
   399  func (r UpdateImageProperty) ToImagePatchMap() map[string]interface{} {
   400  	updateMap := map[string]interface{}{
   401  		"op":    r.Op,
   402  		"path":  fmt.Sprintf("/%s", r.Name),
   403  		"value": r.Value,
   404  	}
   405  
   406  	return updateMap
   407  }