1// Copyright 2016-2020 The Libsacloud Authors 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package api 16 17import ( 18 "fmt" 19 20 "github.com/sacloud/libsacloud/sacloud" 21) 22 23// ProductServerAPI サーバープランAPI 24type ProductServerAPI struct { 25 *baseAPI 26} 27 28// NewProductServerAPI サーバープランAPI作成 29func NewProductServerAPI(client *Client) *ProductServerAPI { 30 return &ProductServerAPI{ 31 &baseAPI{ 32 client: client, 33 // FuncGetResourceURL 34 FuncGetResourceURL: func() string { 35 return "product/server" 36 }, 37 }, 38 } 39} 40 41// GetBySpec 指定のコア数/メモリサイズ/世代のプランを取得 42func (api *ProductServerAPI) GetBySpec(core, memGB int, gen sacloud.PlanGenerations) (*sacloud.ProductServer, error) { 43 return api.GetBySpecCommitment(core, memGB, gen, sacloud.ECommitmentStandard) 44} 45 46// GetBySpecCommitment 指定のコア数/メモリサイズ/世代のプランを取得 47func (api *ProductServerAPI) GetBySpecCommitment(core, memGB int, gen sacloud.PlanGenerations, commitment sacloud.ECommitment) (*sacloud.ProductServer, error) { 48 plans, err := api.Reset().Find() 49 if err != nil { 50 return nil, err 51 } 52 var res sacloud.ProductServer 53 var found bool 54 for _, plan := range plans.ServerPlans { 55 if plan.CPU == core && plan.GetMemoryGB() == memGB && plan.Commitment == commitment { 56 if gen == sacloud.PlanDefault || gen == plan.Generation { 57 // PlanDefaultの場合は複数ヒットしうる。 58 // この場合より新しい世代を優先する。 59 if found && plan.Generation <= res.Generation { 60 continue 61 } 62 res = plan 63 found = true 64 } 65 } 66 } 67 68 if !found { 69 return nil, fmt.Errorf("Server Plan[core:%d, memory:%d, gen:%d] is not found", core, memGB, gen) 70 } 71 return &res, nil 72} 73 74// IsValidPlan 指定のコア数/メモリサイズ/世代のプランが存在し、有効であるか判定 75func (api *ProductServerAPI) IsValidPlan(core int, memGB int, gen sacloud.PlanGenerations) (bool, error) { 76 77 productServer, err := api.GetBySpec(core, memGB, gen) 78 79 if err != nil { 80 return false, err 81 } 82 83 if productServer == nil { 84 return false, fmt.Errorf("Server Plan[core:%d, memory:%d, gen:%d] is not found", core, memGB, gen) 85 } 86 87 if productServer.Availability != sacloud.EAAvailable { 88 return false, fmt.Errorf("Server Plan[core:%d, memory:%d, gen:%d] is not available", core, memGB, gen) 89 } 90 91 return true, nil 92} 93