forked from ringtail/cluster-capacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
193 lines (163 loc) · 3.97 KB
/
watch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package watch
import (
"bytes"
"fmt"
"io"
"strings"
"sync"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/kubernetes/pkg/api/legacyscheme"
ccapi "github.com/kubernetes-incubator/cluster-capacity/pkg/api"
)
// Every watcher expects infinite byte stream
// E.g. http.Body can provide continuous byte stream,
// each chunk sent asynchronously (invocation of Read is blocked until new chunk)
// Implementation of io.ReadCloser
type WatchBuffer struct {
buf *bytes.Buffer
read chan []byte
write chan []byte
retc chan retc
Resource ccapi.ResourceType
closed bool
closeMux sync.RWMutex
}
type retc struct {
n int
e error
}
var _ io.ReadCloser = &WatchBuffer{}
// Read watch events as byte stream
func (w *WatchBuffer) Read(p []byte) (n int, err error) {
if w.closed {
return 0, io.EOF
}
w.read <- p
ret := <-w.retc
return ret.n, ret.e
}
// Close all channels
func (w *WatchBuffer) Close() error {
w.closeMux.Lock()
defer w.closeMux.Unlock()
if !w.closed {
w.closed = true
close(w.read)
close(w.write)
close(w.retc)
}
return nil
}
// Write
func (w *WatchBuffer) Write(data []byte) (nr int, err error) {
if w.closed {
return 0, io.EOF
}
w.write <- data
return len(data), nil
}
func (c *WatchBuffer) EmitWatchEvent(eType watch.EventType, object runtime.Object) error {
//event := watch.Event{
// Type: eType,
// Object: object,
//}
info, ok := runtime.SerializerInfoForMediaType(legacyscheme.Codecs.SupportedMediaTypes(), runtime.ContentTypeJSON)
if !ok {
return fmt.Errorf("serializer for %s not registered", runtime.ContentTypeJSON)
}
gv := v1.SchemeGroupVersion
encoder := legacyscheme.Codecs.EncoderForVersion(info.Serializer, gv)
obj_str := runtime.EncodeOrDie(encoder, object)
obj_str = strings.Replace(obj_str, "\n", "", -1)
var buffer bytes.Buffer
buffer.WriteString("{\"type\":\"")
buffer.WriteString(string(eType))
buffer.WriteString("\",\"object\":")
buffer.WriteString(obj_str)
buffer.WriteString("}")
_, err := c.Write(buffer.Bytes())
return err
}
func (w *WatchBuffer) loop() {
var dataIn, dataOut []byte
var ok bool
for {
select {
case dataIn = <-w.write:
// channel closed
if len(dataIn) == 0 {
if w.closed {
return
}
}
_, err := w.buf.Write(dataIn)
if err != nil {
// TODO(jchaloup): add log message
fmt.Println("Write error")
break
}
case dataOut = <-w.read:
if w.buf.Len() == 0 {
dataIn, ok = <-w.write
if !ok {
break
}
_, err := w.buf.Write(dataIn)
if err != nil {
// TODO(jchaloup): add log message
fmt.Println("Write error")
break
}
}
nr, err := w.buf.Read(dataOut)
if w.closed {
break
}
w.retc <- retc{nr, err}
}
}
}
func NewWatchBuffer(resource ccapi.ResourceType) *WatchBuffer {
wb := &WatchBuffer{
buf: bytes.NewBuffer(nil),
read: make(chan []byte),
write: make(chan []byte),
retc: make(chan retc),
Resource: resource,
closed: false,
}
go wb.loop()
return wb
}
func main() {
buffer := NewWatchBuffer("pods")
go func() {
buffer.Write([]byte("Ahoj"))
time.Sleep(5 * time.Second)
buffer.Write([]byte(" Svete"))
//time.Sleep(time.Second)
}()
data := []byte{0, 0, 0, 0, 0, 0}
buffer.Read(data)
fmt.Printf("\tdata: %s\n", data)
buffer.Read(data)
fmt.Printf("\tdata: %s\n", data)
time.Sleep(10 * time.Second)
buffer.Close()
fmt.Println("Ahoj")
}