blob: c2772ddb57a6a3f40a12340d4440f63ab1bd226a [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2016 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package watch
18
19import (
20 "errors"
21 "time"
22
23 "k8s.io/apimachinery/pkg/util/wait"
24)
25
26// ConditionFunc returns true if the condition has been reached, false if it has not been reached yet,
27// or an error if the condition cannot be checked and should terminate. In general, it is better to define
28// level driven conditions over edge driven conditions (pod has ready=true, vs pod modified and ready changed
29// from false to true).
30type ConditionFunc func(event Event) (bool, error)
31
32// ErrWatchClosed is returned when the watch channel is closed before timeout in Until.
33var ErrWatchClosed = errors.New("watch closed before Until timeout")
34
35// Until reads items from the watch until each provided condition succeeds, and then returns the last watch
36// encountered. The first condition that returns an error terminates the watch (and the event is also returned).
37// If no event has been received, the returned event will be nil.
38// Conditions are satisfied sequentially so as to provide a useful primitive for higher level composition.
39// A zero timeout means to wait forever.
40func Until(timeout time.Duration, watcher Interface, conditions ...ConditionFunc) (*Event, error) {
41 ch := watcher.ResultChan()
42 defer watcher.Stop()
43 var after <-chan time.Time
44 if timeout > 0 {
45 after = time.After(timeout)
46 } else {
47 ch := make(chan time.Time)
48 defer close(ch)
49 after = ch
50 }
51 var lastEvent *Event
52 for _, condition := range conditions {
53 // check the next condition against the previous event and short circuit waiting for the next watch
54 if lastEvent != nil {
55 done, err := condition(*lastEvent)
56 if err != nil {
57 return lastEvent, err
58 }
59 if done {
60 continue
61 }
62 }
63 ConditionSucceeded:
64 for {
65 select {
66 case event, ok := <-ch:
67 if !ok {
68 return lastEvent, ErrWatchClosed
69 }
70 lastEvent = &event
71
72 // TODO: check for watch expired error and retry watch from latest point?
73 done, err := condition(event)
74 if err != nil {
75 return lastEvent, err
76 }
77 if done {
78 break ConditionSucceeded
79 }
80
81 case <-after:
82 return lastEvent, wait.ErrWaitTimeout
83 }
84 }
85 }
86 return lastEvent, nil
87}