github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/csbs/v1/policies/requests.go (about)

     1  package policies
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/huaweicloud/golangsdk"
     7  	"github.com/huaweicloud/golangsdk/pagination"
     8  )
     9  
    10  type ListOpts struct {
    11  	// id and status are not supported in API, will filtered by FilterPolicies
    12  	ID         string `json:"id"`
    13  	Status     string `json:"status"`
    14  	Name       string `q:"name"`
    15  	Sort       string `q:"sort"`
    16  	Limit      int    `q:"limit"`
    17  	Marker     string `q:"marker"`
    18  	Offset     int    `q:"offset"`
    19  	AllTenants string `q:"all_tenants"`
    20  }
    21  
    22  // List returns a Pager which allows you to iterate over a collection of
    23  // backup policies. It accepts a ListOpts struct, which allows you to
    24  // filter the returned collection for greater efficiency.
    25  func List(c *golangsdk.ServiceClient, opts ListOpts) ([]BackupPolicy, error) {
    26  	q, err := golangsdk.BuildQueryString(&opts)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	u := rootURL(c) + q.String()
    31  	pages, err := pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page {
    32  		return BackupPolicyPage{pagination.LinkedPageBase{PageResult: r}}
    33  	}).AllPages()
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	allpolicy, err := ExtractBackupPolicies(pages)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  
    43  	return FilterPolicies(allpolicy, opts)
    44  }
    45  
    46  func FilterPolicies(policies []BackupPolicy, opts ListOpts) ([]BackupPolicy, error) {
    47  
    48  	var refinedPolicies []BackupPolicy
    49  	var matched bool
    50  	m := map[string]interface{}{}
    51  
    52  	if opts.ID != "" {
    53  		m["ID"] = opts.ID
    54  	}
    55  	if opts.Status != "" {
    56  		m["Status"] = opts.Status
    57  	}
    58  
    59  	if len(m) > 0 && len(policies) > 0 {
    60  		for _, policy := range policies {
    61  			matched = true
    62  
    63  			for key, value := range m {
    64  				if sVal := getStructPolicyField(&policy, key); !(sVal == value) {
    65  					matched = false
    66  				}
    67  			}
    68  
    69  			if matched {
    70  				refinedPolicies = append(refinedPolicies, policy)
    71  			}
    72  		}
    73  
    74  	} else {
    75  		refinedPolicies = policies
    76  	}
    77  
    78  	return refinedPolicies, nil
    79  }
    80  
    81  func getStructPolicyField(v *BackupPolicy, field string) string {
    82  	r := reflect.ValueOf(v)
    83  	f := reflect.Indirect(r).FieldByName(field)
    84  	return string(f.String())
    85  }
    86  
    87  // CreateOptsBuilder allows extensions to add additional parameters to the
    88  // Create request.
    89  type CreateOptsBuilder interface {
    90  	ToBackupPolicyCreateMap() (map[string]interface{}, error)
    91  }
    92  
    93  // CreateOpts contains the options for create a Backup Policy. This object is
    94  // passed to policies.Create().
    95  type CreateOpts struct {
    96  	Description         string               `json:"description,omitempty"`
    97  	Name                string               `json:"name" required:"true"`
    98  	Parameters          PolicyParam          `json:"parameters" required:"true"`
    99  	ProviderId          string               `json:"provider_id" required:"true"`
   100  	Resources           []Resource           `json:"resources" required:"true"`
   101  	ScheduledOperations []ScheduledOperation `json:"scheduled_operations" required:"true"`
   102  	Tags                []ResourceTag        `json:"tags,omitempty"`
   103  }
   104  
   105  type PolicyParam struct {
   106  	Common interface{} `json:"common,omitempty"`
   107  }
   108  
   109  type Resource struct {
   110  	Id        string      `json:"id" required:"true"`
   111  	Type      string      `json:"type" required:"true"`
   112  	Name      string      `json:"name" required:"true"`
   113  	ExtraInfo interface{} `json:"extra_info,omitempty"`
   114  }
   115  
   116  type ScheduledOperation struct {
   117  	Description         string              `json:"description,omitempty"`
   118  	Enabled             bool                `json:"enabled"`
   119  	Name                string              `json:"name,omitempty"`
   120  	OperationType       string              `json:"operation_type" required:"true"`
   121  	OperationDefinition OperationDefinition `json:"operation_definition" required:"true"`
   122  	Trigger             Trigger             `json:"trigger" required:"true"`
   123  }
   124  
   125  type OperationDefinition struct {
   126  	MaxBackups            int    `json:"max_backups,omitempty"`
   127  	RetentionDurationDays int    `json:"retention_duration_days,omitempty"`
   128  	Permanent             bool   `json:"permanent"`
   129  	PlanId                string `json:"plan_id,omitempty"`
   130  	ProviderId            string `json:"provider_id,omitempty"`
   131  }
   132  
   133  type Trigger struct {
   134  	Properties TriggerProperties `json:"properties" required:"true"`
   135  }
   136  
   137  type TriggerProperties struct {
   138  	Pattern string `json:"pattern" required:"true"`
   139  }
   140  
   141  type ResourceTag struct {
   142  	Key   string `json:"key" required:"true"`
   143  	Value string `json:"value" required:"true"`
   144  }
   145  
   146  // ToBackupPolicyCreateMap assembles a request body based on the contents of a
   147  // CreateOpts.
   148  func (opts CreateOpts) ToBackupPolicyCreateMap() (map[string]interface{}, error) {
   149  	return golangsdk.BuildRequestBody(opts, "policy")
   150  }
   151  
   152  // Create will create a new backup policy based on the values in CreateOpts. To extract
   153  // the Backup object from the response, call the Extract method on the
   154  // CreateResult.
   155  func Create(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
   156  	b, err := opts.ToBackupPolicyCreateMap()
   157  	if err != nil {
   158  		r.Err = err
   159  		return
   160  	}
   161  	_, r.Err = client.Post(rootURL(client), b, &r.Body, &golangsdk.RequestOpts{
   162  		OkCodes: []int{200},
   163  	})
   164  	return
   165  }
   166  
   167  // Get will get a single backup policy with specific ID.
   168  // call the Extract method on the GetResult.
   169  func Get(client *golangsdk.ServiceClient, policy_id string) (r GetResult) {
   170  	_, r.Err = client.Get(resourceURL(client, policy_id), &r.Body, &golangsdk.RequestOpts{
   171  		OkCodes:  []int{200},
   172  		JSONBody: nil,
   173  	})
   174  
   175  	return
   176  }
   177  
   178  // UpdateOptsBuilder allows extensions to add additional parameters to the
   179  // Update request.
   180  type UpdateOptsBuilder interface {
   181  	ToPoliciesUpdateMap() (map[string]interface{}, error)
   182  }
   183  
   184  // UpdateOpts contains the values used when updating a backup policy.
   185  type UpdateOpts struct {
   186  	Description         string                       `json:"description,omitempty"`
   187  	Name                string                       `json:"name,omitempty"`
   188  	Parameters          PolicyParam                  `json:"parameters,omitempty"`
   189  	Resources           []Resource                   `json:"resources,omitempty"`
   190  	ScheduledOperations []ScheduledOperationToUpdate `json:"scheduled_operations,omitempty"`
   191  }
   192  
   193  type ScheduledOperationToUpdate struct {
   194  	Description         string              `json:"description,omitempty"`
   195  	Enabled             bool                `json:"enabled"`
   196  	TriggerId           string              `json:"trigger_id,omitempty"`
   197  	Name                string              `json:"name,omitempty"`
   198  	OperationDefinition OperationDefinition `json:"operation_definition,omitempty"`
   199  	Trigger             Trigger             `json:"trigger,omitempty"`
   200  	Id                  string              `json:"id" required:"true"`
   201  }
   202  
   203  // ToPoliciesUpdateMap builds an update body based on UpdateOpts.
   204  func (opts UpdateOpts) ToPoliciesUpdateMap() (map[string]interface{}, error) {
   205  	return golangsdk.BuildRequestBody(opts, "policy")
   206  }
   207  
   208  // Update allows backup policies to be updated.
   209  // call the Extract method on the UpdateResult.
   210  func Update(c *golangsdk.ServiceClient, policy_id string, opts UpdateOptsBuilder) (r UpdateResult) {
   211  	b, err := opts.ToPoliciesUpdateMap()
   212  	if err != nil {
   213  		r.Err = err
   214  		return
   215  	}
   216  	_, r.Err = c.Put(resourceURL(c, policy_id), b, &r.Body, &golangsdk.RequestOpts{
   217  		OkCodes: []int{200},
   218  	})
   219  	return
   220  }
   221  
   222  // Delete will delete an existing backup policy.
   223  func Delete(client *golangsdk.ServiceClient, policy_id string) (r DeleteResult) {
   224  	_, r.Err = client.Delete(resourceURL(client, policy_id), &golangsdk.RequestOpts{
   225  		OkCodes:      []int{200},
   226  		JSONResponse: nil,
   227  	})
   228  	return
   229  }