2 Copyright 2014 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
23 "k8s.io/apimachinery/pkg/runtime"
24 "k8s.io/apimachinery/pkg/util/net"
25 utilruntime "k8s.io/apimachinery/pkg/util/runtime"
29 // Decoder allows StreamWatcher to watch any stream for which a Decoder can be written.
30 type Decoder interface {
31 // Decode should return the type of event, the decoded object, or an error.
32 // An error will cause StreamWatcher to call Close(). Decode should block until
33 // it has data or an error occurs.
34 Decode() (action EventType, object runtime.Object, err error)
36 // Close should close the underlying io.Reader, signalling to the source of
37 // the stream that it is no longer being watched. Close() must cause any
38 // outstanding call to Decode() to return with an error of some sort.
42 // StreamWatcher turns any stream for which you can write a Decoder interface
43 // into a watch.Interface.
44 type StreamWatcher struct {
51 // NewStreamWatcher creates a StreamWatcher from the given decoder.
52 func NewStreamWatcher(d Decoder) *StreamWatcher {
55 // It's easy for a consumer to add buffering via an extra
56 // goroutine/channel, but impossible for them to remove it,
57 // so nonbuffered is better.
58 result: make(chan Event),
64 // ResultChan implements Interface.
65 func (sw *StreamWatcher) ResultChan() <-chan Event {
69 // Stop implements Interface.
70 func (sw *StreamWatcher) Stop() {
71 // Call Close() exactly once by locking and setting a flag.
80 // stopping returns true if Stop() was called previously.
81 func (sw *StreamWatcher) stopping() bool {
87 // receive reads result from the decoder in a loop and sends down the result channel.
88 func (sw *StreamWatcher) receive() {
89 defer close(sw.result)
91 defer utilruntime.HandleCrash()
93 action, obj, err := sw.source.Decode()
95 // Ignore expected error.
101 // watch closed normally
102 case io.ErrUnexpectedEOF:
103 klog.V(1).Infof("Unexpected EOF during watch stream event decoding: %v", err)
105 msg := "Unable to decode an event from the watch stream: %v"
106 if net.IsProbableEOF(err) {
107 klog.V(5).Infof(msg, err)
109 klog.Errorf(msg, err)