Skip to content
This repository was archived by the owner on Aug 31, 2021. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions openstack/bms/v2/flavors/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
Package flavors enables management and retrieval of Flavors
BMS service.

Example to List Flavors

listOpts := flavors.ListOpts{}
allFlavors, err := flavors.List(bmsClient, listOpts)
if err != nil {
panic(err)
}

for _, flavor := range allFlavors {
fmt.Printf("%+v\n", flavor)
}
*/
package flavors
124 changes: 124 additions & 0 deletions openstack/bms/v2/flavors/requests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package flavors

import (
"reflect"
"strings"

"github.com/huaweicloud/golangsdk"
"github.com/huaweicloud/golangsdk/pagination"
)

// ListOptsBuilder allows extensions to add additional parameters to the
// List request.
type ListOptsBuilder interface {
ToFlavorListQuery() (string, error)
}

//The AccessType arguement is optional, and if it is not supplied, OpenStack
//returns the PublicAccess flavors.
type AccessType string

const (
// PublicAccess returns public flavors and private flavors associated with
// that project.
PublicAccess AccessType = "true"

// PrivateAccess (admin only) returns private flavors, across all projects.
PrivateAccess AccessType = "false"

// AllAccess (admin only) returns public and private flavors across all
// projects.
AllAccess AccessType = "None"
)

// ListOpts allows the filtering and sorting of paginated collections through
// the API. Filtering is achieved by passing in struct field values that map to
// the flavor attributes you want to see returned.
type ListOpts struct {
//Specifies the name of the BMS flavor
Name string

//Specifies the ID of the BMS flavor
ID string

// MinDisk and MinRAM, if provided, elides flavors which do not meet your
// criteria.
MinDisk int `q:"minDisk"`

MinRAM int `q:"minRam"`

// AccessType, if provided, instructs List which set of flavors to return.
// If IsPublic not provided, flavors for the current project are returned.
AccessType AccessType `q:"is_public"`

//SortKey allows you to sort by a particular attribute
SortKey string `q:"sort_key"`

//SortDir sets the direction, and is either `asc' or `desc'
SortDir string `q:"sort_dir"`
}

func List(c *golangsdk.ServiceClient, opts ListOpts) ([]Flavor, error) {
q, err := golangsdk.BuildQueryString(&opts)
if err != nil {
return nil, err
}
u := listURL(c) + q.String()
pages, err := pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page {
return FlavorPage{pagination.LinkedPageBase{PageResult: r}}
}).AllPages()

allFlavors, err := ExtractFlavors(pages)
if err != nil {
return nil, err
}

return FilterFlavors(allFlavors, opts)
}

//FilterFlavors used to filter flavors using Id and Name
func FilterFlavors(flavors []Flavor, opts ListOpts) ([]Flavor, error) {

var refinedFlavors []Flavor
var matched bool
m := map[string]interface{}{}

if opts.ID != "" {
m["ID"] = opts.ID
}
if opts.Name != "" {
m["Name"] = opts.Name
}
if len(m) > 0 && len(flavors) > 0 {
for _, flavor := range flavors {
matched = true

for key, value := range m {
if sVal := getStructField(&flavor, key); !(sVal == value) {
matched = false
}
}
if matched {
refinedFlavors = append(refinedFlavors, flavor)
}
}
} else {
refinedFlavors = flavors
}
var flavorList []Flavor

for i := 0; i < len(refinedFlavors); i++ {
if strings.Contains(refinedFlavors[i].Name, "physical") {
flavorList = append(flavorList, refinedFlavors[i])
}

}

return flavorList, nil
}

func getStructField(v *Flavor, field string) string {
r := reflect.ValueOf(v)
f := reflect.Indirect(r).FieldByName(field)
return string(f.String())
}
123 changes: 123 additions & 0 deletions openstack/bms/v2/flavors/results.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package flavors

import (
"encoding/json"
"strconv"

"github.com/huaweicloud/golangsdk"
"github.com/huaweicloud/golangsdk/pagination"
)

// Flavor represent (virtual) hardware configurations for server resources
// in a region.
type Flavor struct {
// ID is the flavor's unique ID.
ID string `json:"id"`

// Disk is the amount of root disk, measured in GB.
Disk int `json:"disk"`

// MinDisk and MinRAM, if provided, elides flavors which do not meet your
// criteria.
MinDisk int `json:"minDisk"`

MinRAM int `json:"minRam"`

// RAM is the amount of memory, measured in MB.
RAM int `json:"ram"`

// Name is the name of the flavor.
Name string `json:"name"`

// RxTxFactor describes bandwidth alterations of the flavor.
RxTxFactor float64 `json:"rxtx_factor"`

// Swap is the amount of swap space, measured in MB.
Swap int `json:"swap"`

// VCPUs indicates how many (virtual) CPUs are available for this flavor.
VCPUs int `json:"vcpus"`

// IsPublic indicates whether the flavor is public.
IsPublic bool `json:"os-flavor-access:is_public"`

// Ephemeral is the amount of ephemeral disk space, measured in GB.
Ephemeral int `json:"OS-FLV-EXT-DATA:ephemeral"`

// Whether or not the flavor has been administratively disabled
Disabled bool `json:"OS-FLV-DISABLED:disabled"`

// Specifies the shortcut link of the BMS flavor.
Links []golangsdk.Link `json:"links"`

SortKey string `json:"sort_key"`

//SortDir sets the direction, and is either `asc' or `desc'
SortDir string `json:"sort_dir"`
}

func (r *Flavor) UnmarshalJSON(b []byte) error {
type tmp Flavor
var s struct {
tmp
Swap interface{} `json:"swap"`
}
err := json.Unmarshal(b, &s)
if err != nil {
return err
}

*r = Flavor(s.tmp)

switch t := s.Swap.(type) {
case float64:
r.Swap = int(t)
case string:
switch t {
case "":
r.Swap = 0
default:
swap, err := strconv.ParseFloat(t, 64)
if err != nil {
return err
}
r.Swap = int(swap)
}
}

return nil
}

// FlavorPage contains a single page of all flavors from a List call.
type FlavorPage struct {
pagination.LinkedPageBase
}

// IsEmpty determines if a FlavorPage contains any results.
func (page FlavorPage) IsEmpty() (bool, error) {
flavors, err := ExtractFlavors(page)
return len(flavors) == 0, err
}

// NextPageURL uses the response's embedded link reference to navigate to the
// next page of results.
func (page FlavorPage) NextPageURL() (string, error) {
var s struct {
Links []golangsdk.Link `json:"flavors_links"`
}
err := page.ExtractInto(&s)
if err != nil {
return "", err
}
return golangsdk.ExtractNextURL(s.Links)
}

// ExtractFlavors provides access to the list of flavors in a page acquired
// from the List operation.
func ExtractFlavors(r pagination.Page) ([]Flavor, error) {
var s struct {
Flavors []Flavor `json:"flavors"`
}
err := (r.(FlavorPage)).ExtractInto(&s)
return s.Flavors, err
}
128 changes: 128 additions & 0 deletions openstack/bms/v2/flavors/testing/requests_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package testing

import (
"fmt"
"net/http"
"testing"

"github.com/huaweicloud/golangsdk"
"github.com/huaweicloud/golangsdk/openstack/bms/v2/flavors"
th "github.com/huaweicloud/golangsdk/testhelper"
fake "github.com/huaweicloud/golangsdk/testhelper/client"
)

func TestListFlavor(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()

th.Mux.HandleFunc("/flavors/detail", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "GET")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)

w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

fmt.Fprintf(w, `
{
"flavors": [
{
"name": "physical.h2.large",
"links": [
{
"href": "https://compute.region.eu-de.otc-tsi.de/v2/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.h2.large",
"rel": "self"
},
{
"href": "https://compute.region.eu-de.otc-tsi.de/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.h2.large",
"rel": "bookmark"
}
],
"ram": 196608,
"OS-FLV-DISABLED:disabled": false,
"vcpus": 36,
"os-flavor-access:is_public": true,
"rxtx_factor": 1,
"OS-FLV-EXT-DATA:ephemeral": 0,
"disk": 0,
"id": "physical.h2.large"
},
{
"name": "physical.m2.medium",
"links": [
{
"href": "https://compute.region.eu-de.otc-tsi.de/v2/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.m2.medium",
"rel": "self"
},
{
"href": "https://compute.region.eu-de.otc-tsi.de/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.m2.medium",
"rel": "bookmark"
}
],
"ram": 2097152,
"OS-FLV-DISABLED:disabled": false,
"vcpus": 192,
"os-flavor-access:is_public": true,
"rxtx_factor": 1,
"OS-FLV-EXT-DATA:ephemeral": 0,
"disk": 17000,
"id": "physical.m2.medium"
}
]
}
`)
})

//count := 0

actual, err := flavors.List(fake.ServiceClient(), flavors.ListOpts{})
if err != nil {
t.Errorf("Failed to extract flavors: %v", err)
}

expected := []flavors.Flavor{
{
ID: "physical.h2.large",
RAM: 196608,
Disabled: false,
Name: "physical.h2.large",
VCPUs: 36,
IsPublic: true,
RxTxFactor: 1,
Ephemeral: 0,
Disk: 0,
Links: []golangsdk.Link{
{
Href: "https://compute.region.eu-de.otc-tsi.de/v2/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.h2.large",
Rel: "self",
},
{
Href: "https://compute.region.eu-de.otc-tsi.de/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.h2.large",
Rel: "bookmark",
},
},
},
{
ID: "physical.m2.medium",
RAM: 2097152,
Disabled: false,
Name: "physical.m2.medium",
VCPUs: 192,
IsPublic: true,
RxTxFactor: 1,
Ephemeral: 0,
Disk: 17000,
Links: []golangsdk.Link{
{
Href: "https://compute.region.eu-de.otc-tsi.de/v2/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.m2.medium",
Rel: "self",
},
{
Href: "https://compute.region.eu-de.otc-tsi.de/91d687759aed45d28b5f6084bc2fa8ad/flavors/physical.m2.medium",
Rel: "bookmark",
},
},
},
}

th.AssertDeepEquals(t, expected, actual)
}
Loading