github.com/sacloud/iaas-api-go@v1.12.0/helper/wait/simple_state_waiter.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 wait 16 17 import ( 18 "context" 19 "time" 20 21 "github.com/sacloud/iaas-api-go" 22 "github.com/sacloud/iaas-api-go/types" 23 "github.com/sacloud/packages-go/wait" 24 ) 25 26 // ByFunc デフォルトのパラメータでSimpleStateWaiterを作成して返す 27 func ByFunc(readStateFunc ReadStateFunc) wait.StateWaiter { 28 return &SimpleStateWaiter{ReadStateFunc: readStateFunc} 29 } 30 31 type ReadStateFunc func() (bool, error) 32 33 // SimpleStateWaiter シンプルな待ち処理のためのiaas.StateWaiterの実装 34 // 35 // iaas.StatePollingWaiterをラップし、シンプルなfuncのみで待つべきかを判定する 36 type SimpleStateWaiter struct { 37 // ReadStateFunc 待つべきかの判定func 38 // trueかつerrorが空の場合は待ち処理を完了させる 39 ReadStateFunc ReadStateFunc 40 41 // Timeout タイムアウト 42 Timeout time.Duration 43 44 // PollingInterval ポーリング間隔 45 PollingInterval time.Duration 46 } 47 48 func (s *SimpleStateWaiter) waiter() wait.StateWaiter { 49 return &iaas.StatePollingWaiter{ 50 ReadFunc: func() (interface{}, error) { 51 result, err := s.ReadStateFunc() 52 if err != nil { 53 return false, err 54 } 55 return &fakeState{available: result}, nil 56 }, 57 TargetAvailability: []types.EAvailability{ 58 types.Availabilities.Available, 59 }, 60 PendingAvailability: []types.EAvailability{ 61 types.Availabilities.Unknown, 62 }, 63 64 Interval: s.PollingInterval, 65 Timeout: s.Timeout, 66 } 67 } 68 69 // WaitForState iaas.StateWaiterの実装 70 func (s *SimpleStateWaiter) WaitForState(ctx context.Context) (interface{}, error) { 71 return s.waiter().WaitForState(ctx) 72 } 73 74 // WaitForStateAsync iaas.StateWaiterの実装 75 func (s *SimpleStateWaiter) WaitForStateAsync(ctx context.Context) (compCh <-chan interface{}, progressCh <-chan interface{}, errorCh <-chan error) { 76 return s.waiter().WaitForStateAsync(ctx) 77 } 78 79 type fakeState struct { 80 available bool 81 } 82 83 // GetAvailability accessor.Availabilityの実装 84 func (f *fakeState) GetAvailability() types.EAvailability { 85 if f.available { 86 return types.Availabilities.Available 87 } 88 return types.Availabilities.Unknown 89 } 90 91 // SetAvailability accessor.Availabilityの実装 92 func (f *fakeState) SetAvailability(v types.EAvailability) { 93 f.available = v == types.Availabilities.Available 94 }