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