-
Notifications
You must be signed in to change notification settings - Fork 290
/
fake_client.go
430 lines (363 loc) · 10.2 KB
/
fake_client.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package k8s
import (
"bytes"
"context"
"io"
"io/ioutil"
"sync"
"time"
"github.com/docker/distribution/reference"
"github.com/google/uuid"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/watch"
"github.com/windmilleng/tilt/internal/container"
"github.com/windmilleng/tilt/pkg/logger"
)
// A magic constant. If the docker client returns this constant, we always match
// even if the container doesn't have the correct image name.
const MagicTestContainerID = "tilt-testcontainer"
var _ Client = &FakeK8sClient{}
// For keying PodLogsByPodAndContainer
type PodAndCName struct {
PID PodID
CName container.Name
}
type FakeK8sClient struct {
FakePortForwardClient
Yaml string
Lb LoadBalancerSpec
DeletedYaml string
DeleteError error
LastPodQueryNamespace Namespace
LastPodQueryImage reference.NamedTagged
PodLogsByPodAndContainer map[PodAndCName]BufferCloser
LastPodLogStartTime time.Time
ContainerLogsError error
podWatcherMu sync.Mutex
podWatches []fakePodWatch
serviceWatcherMu sync.Mutex
serviceWatches []fakeServiceWatch
eventsCh chan *v1.Event
EventsWatchErr error
UpsertError error
LastUpsertResult []K8sEntity
Runtime container.Runtime
Registry container.Registry
entityByName map[string]K8sEntity
getByReferenceCallCount int
ExecCalls []ExecCall
ExecErrors []error
}
type ExecCall struct {
PID PodID
CName container.Name
Ns Namespace
Cmd []string
Stdin []byte
}
type fakeServiceWatch struct {
ls labels.Selector
ch chan *v1.Service
}
type fakePodWatch struct {
ls labels.Selector
ch chan ObjectUpdate
}
func (c *FakeK8sClient) EmitService(ls labels.Selector, s *v1.Service) {
c.podWatcherMu.Lock()
defer c.podWatcherMu.Unlock()
for _, w := range c.serviceWatches {
if SelectorEqual(ls, w.ls) {
w.ch <- s
}
}
}
func (c *FakeK8sClient) WatchServices(ctx context.Context, ls labels.Selector) (<-chan *v1.Service, error) {
c.serviceWatcherMu.Lock()
ch := make(chan *v1.Service, 20)
c.serviceWatches = append(c.serviceWatches, fakeServiceWatch{ls, ch})
c.serviceWatcherMu.Unlock()
go func() {
// when ctx is canceled, remove the label selector from the list of watched label selectors
<-ctx.Done()
c.serviceWatcherMu.Lock()
var newWatches []fakeServiceWatch
for _, e := range c.serviceWatches {
if !SelectorEqual(e.ls, ls) {
newWatches = append(newWatches, e)
}
}
c.serviceWatches = newWatches
c.serviceWatcherMu.Unlock()
}()
return ch, nil
}
func (c *FakeK8sClient) WatchEvents(ctx context.Context) (<-chan *v1.Event, error) {
if c.EventsWatchErr != nil {
err := c.EventsWatchErr
c.EventsWatchErr = nil
return nil, err
}
return c.eventsCh, nil
}
func (c *FakeK8sClient) EmitEvent(ctx context.Context, evt *v1.Event) {
c.eventsCh <- evt
}
func (c *FakeK8sClient) WatchedSelectors() []labels.Selector {
c.podWatcherMu.Lock()
defer c.podWatcherMu.Unlock()
var ret []labels.Selector
for _, w := range c.podWatches {
ret = append(ret, w.ls)
}
return ret
}
func (c *FakeK8sClient) EmitPod(ls labels.Selector, p *v1.Pod) {
c.podWatcherMu.Lock()
defer c.podWatcherMu.Unlock()
for _, w := range c.podWatches {
if SelectorEqual(ls, w.ls) {
w.ch <- ObjectUpdate{obj: p}
}
}
}
func (c *FakeK8sClient) EmitPodDelete(ls labels.Selector, p *v1.Pod) {
c.podWatcherMu.Lock()
defer c.podWatcherMu.Unlock()
for _, w := range c.podWatches {
if SelectorEqual(ls, w.ls) {
w.ch <- ObjectUpdate{obj: p, isDelete: true}
}
}
}
func (c *FakeK8sClient) WatchPods(ctx context.Context, ls labels.Selector) (<-chan ObjectUpdate, error) {
c.podWatcherMu.Lock()
ch := make(chan ObjectUpdate, 20)
c.podWatches = append(c.podWatches, fakePodWatch{ls, ch})
c.podWatcherMu.Unlock()
go func() {
// when ctx is canceled, remove the label selector from the list of watched label selectors
<-ctx.Done()
c.podWatcherMu.Lock()
var newWatches []fakePodWatch
for _, e := range c.podWatches {
if !SelectorEqual(e.ls, ls) {
newWatches = append(newWatches, e)
}
}
c.podWatches = newWatches
c.podWatcherMu.Unlock()
}()
return ch, nil
}
func NewFakeK8sClient() *FakeK8sClient {
return &FakeK8sClient{
PodLogsByPodAndContainer: make(map[PodAndCName]BufferCloser),
eventsCh: make(chan *v1.Event, 10),
}
}
func (c *FakeK8sClient) TearDown() {
if c.eventsCh != nil {
close(c.eventsCh)
}
}
func (c *FakeK8sClient) ConnectedToCluster(ctx context.Context) error {
return nil
}
func (c *FakeK8sClient) Upsert(ctx context.Context, entities []K8sEntity) ([]K8sEntity, error) {
if c.UpsertError != nil {
return nil, c.UpsertError
}
yaml, err := SerializeSpecYAML(entities)
if err != nil {
return nil, errors.Wrap(err, "kubectl apply")
}
c.Yaml = yaml
result := make([]K8sEntity, 0, len(entities))
for _, e := range entities {
clone := e.DeepCopy()
err = SetUID(&clone, uuid.New().String())
if err != nil {
return nil, errors.Wrap(err, "Upsert: generating UUID")
}
result = append(result, clone)
}
c.LastUpsertResult = result
return result, nil
}
func (c *FakeK8sClient) Delete(ctx context.Context, entities []K8sEntity) error {
if c.DeleteError != nil {
err := c.DeleteError
c.DeleteError = nil
return err
}
yaml, err := SerializeSpecYAML(entities)
if err != nil {
return errors.Wrap(err, "kubectl delete")
}
c.DeletedYaml = yaml
return nil
}
func (c *FakeK8sClient) InjectEntityByName(entities ...K8sEntity) {
if c.entityByName == nil {
c.entityByName = make(map[string]K8sEntity)
}
for _, entity := range entities {
c.entityByName[entity.Name()] = entity
}
}
func (c *FakeK8sClient) GetByReference(ctx context.Context, ref v1.ObjectReference) (K8sEntity, error) {
c.getByReferenceCallCount++
resp, ok := c.entityByName[ref.Name]
if !ok {
logger.Get(ctx).Infof("FakeK8sClient.GetByReference: resource not found: %s", ref.Name)
return K8sEntity{}, apierrors.NewNotFound(v1.Resource(ref.Kind), ref.Name)
}
return resp, nil
}
func (c *FakeK8sClient) WatchPod(ctx context.Context, pod *v1.Pod) (watch.Interface, error) {
return watch.NewEmptyWatch(), nil
}
func (c *FakeK8sClient) SetLogsForPodContainer(pID PodID, cName container.Name, logs string) {
c.PodLogsByPodAndContainer[PodAndCName{pID, cName}] = BufferCloser{Buffer: bytes.NewBufferString(logs)}
}
func (c *FakeK8sClient) ContainerLogs(ctx context.Context, pID PodID, cName container.Name, n Namespace, startTime time.Time) (io.ReadCloser, error) {
if c.ContainerLogsError != nil {
return nil, c.ContainerLogsError
}
// If we have specific logs for this pod/container combo, return those
c.LastPodLogStartTime = startTime
if buf, ok := c.PodLogsByPodAndContainer[PodAndCName{pID, cName}]; ok {
return buf, nil
}
return BufferCloser{Buffer: bytes.NewBuffer(nil)}, nil
}
func (c *FakeK8sClient) PodByID(ctx context.Context, pID PodID, n Namespace) (*v1.Pod, error) {
return nil, nil
}
func FakePodStatus(image reference.NamedTagged, phase string) v1.PodStatus {
return v1.PodStatus{
Phase: v1.PodPhase(phase),
ContainerStatuses: []v1.ContainerStatus{
{
Name: "main",
ContainerID: "docker://" + MagicTestContainerID,
Image: image.String(),
Ready: true,
},
{
Name: "tilt-synclet",
ContainerID: "docker://tilt-testsynclet",
// can't use the constants in synclet because that would create a dep cycle
Image: "gcr.io/windmill-public-containers/tilt-synclet:latest",
Ready: true,
},
},
}
}
func FakePodSpec(image reference.NamedTagged) v1.PodSpec {
return v1.PodSpec{
Containers: []v1.Container{
{
Name: "main",
Image: image.String(),
Ports: []v1.ContainerPort{
{
ContainerPort: 8080,
},
},
},
{
Name: "tilt-synclet",
Image: "gcr.io/windmill-public-containers/tilt-synclet:latest",
},
},
}
}
func (c *FakeK8sClient) applyWasCalled() bool {
return c.Yaml != ""
}
func (c *FakeK8sClient) CreatePortForwarder(ctx context.Context, namespace Namespace, podID PodID, optionalLocalPort, remotePort int, host string) (PortForwarder, error) {
pfc := &(c.FakePortForwardClient)
return pfc.CreatePortForwarder(ctx, namespace, podID, optionalLocalPort, remotePort, host)
}
func (c *FakeK8sClient) ContainerRuntime(ctx context.Context) container.Runtime {
if c.Runtime != "" {
return c.Runtime
}
return container.RuntimeDocker
}
func (c *FakeK8sClient) LocalRegistry(ctx context.Context) container.Registry {
return c.Registry
}
func (c *FakeK8sClient) Exec(ctx context.Context, podID PodID, cName container.Name, n Namespace, cmd []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
var stdinBytes []byte
var err error
if stdin != nil {
stdinBytes, err = ioutil.ReadAll(stdin)
if err != nil {
return errors.Wrap(err, "reading Exec stdin")
}
}
c.ExecCalls = append(c.ExecCalls, ExecCall{
PID: podID,
CName: cName,
Ns: n,
Cmd: cmd,
Stdin: stdinBytes,
})
if len(c.ExecErrors) > 0 {
err = c.ExecErrors[0]
c.ExecErrors = c.ExecErrors[1:]
return err
}
return nil
}
type BufferCloser struct {
*bytes.Buffer
}
func (b BufferCloser) Close() error {
return nil
}
var _ io.ReadCloser = BufferCloser{}
type FakePortForwarder struct {
localPort int
ctx context.Context
Done chan error
}
func (pf FakePortForwarder) LocalPort() int {
return pf.localPort
}
func (pf FakePortForwarder) ForwardPorts() error {
select {
case <-pf.ctx.Done():
return pf.ctx.Err()
case <-pf.Done:
return nil
}
}
type FakePortForwardClient struct {
CreatePortForwardCallCount int
LastForwardPortPodID PodID
LastForwardPortRemotePort int
LastForwardPortHost string
LastForwarder FakePortForwarder
LastForwardContext context.Context
}
func (c *FakePortForwardClient) CreatePortForwarder(ctx context.Context, namespace Namespace, podID PodID, optionalLocalPort, remotePort int, host string) (PortForwarder, error) {
c.CreatePortForwardCallCount++
c.LastForwardContext = ctx
c.LastForwardPortPodID = podID
c.LastForwardPortRemotePort = remotePort
c.LastForwardPortHost = host
result := FakePortForwarder{
localPort: optionalLocalPort,
ctx: ctx,
Done: make(chan error),
}
c.LastForwarder = result
return result, nil
}