github.com/sacloud/iaas-api-go@v1.12.0/helper/query/server_plan.go (about) 1 // Copyright 2016-2022 The sacloud/iaas-api-go 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 15 package query 16 17 import ( 18 "context" 19 "errors" 20 21 "github.com/sacloud/iaas-api-go" 22 "github.com/sacloud/iaas-api-go/search" 23 "github.com/sacloud/iaas-api-go/types" 24 "github.com/sacloud/packages-go/size" 25 ) 26 27 // FindServerPlanRequest サーバプラン検索パラメータ 28 type FindServerPlanRequest struct { 29 CPU int 30 MemoryGB int 31 GPU int 32 CPUModel string 33 Commitment types.ECommitment 34 Generation types.EPlanGeneration 35 } 36 37 func (f *FindServerPlanRequest) findCondition() *iaas.FindCondition { 38 cond := &iaas.FindCondition{ 39 Sort: search.SortKeys{ 40 {Key: "Generation", Order: search.SortDesc}, 41 }, 42 Filter: search.Filter{ 43 search.Key("Commitment"): types.Commitments.Standard, 44 search.Key("GPU"): f.GPU, 45 }, 46 Count: 1000, 47 } 48 if f.CPU > 0 { 49 cond.Filter[search.Key("CPU")] = f.CPU 50 } 51 if f.MemoryGB > 0 { 52 cond.Filter[search.Key("MemoryMB")] = size.GiBToMiB(f.MemoryGB) 53 } 54 55 if f.Generation != types.PlanGenerations.Default { 56 cond.Filter[search.Key("Generation")] = f.Generation 57 } 58 if f.Commitment != types.Commitments.Unknown && f.Commitment != types.Commitments.Standard { 59 cond.Filter[search.Key("Commitment")] = f.Commitment 60 } 61 if f.CPUModel != "" { 62 cond.Filter[search.Key("CPUModel")] = f.CPUModel 63 } 64 return cond 65 } 66 67 // FindServerPlan サーバプラン検索 68 func FindServerPlan(ctx context.Context, finder ServerPlanFinder, zone string, param *FindServerPlanRequest) (*iaas.ServerPlan, error) { 69 var cond *iaas.FindCondition 70 if param != nil { 71 cond = param.findCondition() 72 } 73 74 searched, err := finder.Find(ctx, zone, cond) 75 if err != nil { 76 return nil, err 77 } 78 if searched.Count == 0 || len(searched.ServerPlans) == 0 { 79 return nil, errors.New("server plan not found") 80 } 81 return searched.ServerPlans[0], nil 82 }