-
Notifications
You must be signed in to change notification settings - Fork 303
/
fake_client.go
839 lines (699 loc) · 19.8 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
package k8s
import (
"context"
"fmt"
"io"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/distribution/reference"
"github.com/google/uuid"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/version"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/tilt-dev/tilt/internal/container"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/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"
// MagicTestExplodingPort causes FakePortForwarder to fail to initialize (i.e. return an error as soon as ForwardPorts
// is called without ever becoming ready).
const MagicTestExplodingPort = 34743
var _ Client = &FakeK8sClient{}
// For keying PodLogsByPodAndContainer
type PodAndCName struct {
PID PodID
CName container.Name
}
type FakeK8sClient struct {
t testing.TB
mu sync.Mutex
ownerFetcher OwnerFetcher
FakePortForwardClient
Yaml string
Lb LoadBalancerSpec
DeletedYaml string
DeleteError error
LastPodQueryNamespace Namespace
LastPodQueryImage reference.NamedTagged
PodLogsByPodAndContainer map[PodAndCName]ReaderCloser
LastPodLogStartTime time.Time
LastPodLogContext context.Context
LastPodLogPipeWriter *io.PipeWriter
ContainerLogsError error
podWatches []fakePodWatch
serviceWatches []fakeServiceWatch
eventWatches []fakeEventWatch
events map[types.NamespacedName]*v1.Event
services map[types.NamespacedName]*v1.Service
pods map[types.NamespacedName]*v1.Pod
EventsWatchErr error
UpsertError error
UpsertResult []K8sEntity
LastUpsertResult []K8sEntity
UpsertTimeout time.Duration
Runtime container.Runtime
Registry *v1alpha1.RegistryHosting
FakeNodeIP NodeIP
// entities are injected objects keyed by UID.
entities map[types.UID]K8sEntity
// currentVersions maintains a mapping of object name to UID which represents the most recently injected value.
//
// In real K8s, you'd need to delete the old object before being able to store the new one with the same name.
// For testing purposes, it's useful to be able to simulate out of order/stale data type scenarios, so the fake
// client doesn't enforce name uniqueness for storage. When appropriate (e.g. ListMeta), this map ensures that
// multiple objects for the same name aren't returned.
currentVersions map[string]types.UID
getByReferenceCallCount int
listCallCount int
listReturnsEmpty bool
ExecCalls []ExecCall
ExecOutputs []io.Reader
ExecErrors []error
ClusterHealthStatus *ClusterHealth
ClusterHealthError error
FakeAPIConfig *api.Config
}
var _ Client = &FakeK8sClient{}
type ExecCall struct {
PID PodID
CName container.Name
Ns Namespace
Cmd []string
Stdin []byte
}
type fakeServiceWatch struct {
cancel func()
ns Namespace
ch chan *v1.Service
}
type fakePodWatch struct {
cancel func()
ns Namespace
ch chan ObjectUpdate
}
type fakeEventWatch struct {
cancel func()
ns Namespace
ch chan *v1.Event
}
func (c *FakeK8sClient) UpsertService(s *v1.Service) {
c.mu.Lock()
defer c.mu.Unlock()
s = s.DeepCopy()
c.services[types.NamespacedName{Name: s.Name, Namespace: s.Namespace}] = s
for _, w := range c.serviceWatches {
if w.ns != Namespace(s.Namespace) {
continue
}
w.ch <- s
}
}
func (c *FakeK8sClient) UpsertPod(pod *v1.Pod) {
c.mu.Lock()
defer c.mu.Unlock()
pod = pod.DeepCopy()
c.pods[types.NamespacedName{Name: pod.Name, Namespace: pod.Namespace}] = pod
for _, w := range c.podWatches {
if w.ns != Namespace(pod.Namespace) {
continue
}
w.ch <- ObjectUpdate{obj: pod}
}
}
func (c *FakeK8sClient) UpsertEvent(event *v1.Event) {
c.mu.Lock()
defer c.mu.Unlock()
event = event.DeepCopy()
c.events[types.NamespacedName{Name: event.Name, Namespace: event.Namespace}] = event
for _, w := range c.eventWatches {
if w.ns != Namespace(event.Namespace) {
continue
}
w.ch <- event
}
}
func (c *FakeK8sClient) PodFromInformerCache(ctx context.Context, nn types.NamespacedName) (*v1.Pod, error) {
if nn.Namespace == "" {
return nil, fmt.Errorf("missing namespace from pod request")
}
c.mu.Lock()
defer c.mu.Unlock()
pod, ok := c.pods[nn]
if !ok {
return nil, apierrors.NewNotFound(PodGVR.GroupResource(), nn.Name)
}
return pod, nil
}
func (c *FakeK8sClient) WatchServices(ctx context.Context, ns Namespace) (<-chan *v1.Service, error) {
if ns == "" {
return nil, fmt.Errorf("missing namespace from watch request")
}
ctx, cancel := context.WithCancel(ctx)
c.mu.Lock()
ch := make(chan *v1.Service, 20)
c.serviceWatches = append(c.serviceWatches, fakeServiceWatch{cancel, ns, ch})
toEmit := []*v1.Service{}
for _, service := range c.services {
if Namespace(service.Namespace) == ns {
toEmit = append(toEmit, service)
}
}
c.mu.Unlock()
go func() {
// Initial list of objects
for _, obj := range toEmit {
ch <- obj
}
// when ctx is canceled, remove the label selector from the list of watched label selectors
<-ctx.Done()
c.mu.Lock()
var newWatches []fakeServiceWatch
for _, e := range c.serviceWatches {
if e.ns != ns {
newWatches = append(newWatches, e)
}
}
c.serviceWatches = newWatches
c.mu.Unlock()
close(ch)
}()
return ch, nil
}
func (c *FakeK8sClient) WatchEvents(ctx context.Context, ns Namespace) (<-chan *v1.Event, error) {
if ns == "" {
return nil, fmt.Errorf("missing namespace from watch request")
}
if c.EventsWatchErr != nil {
err := c.EventsWatchErr
c.EventsWatchErr = nil
return nil, err
}
ctx, cancel := context.WithCancel(ctx)
c.mu.Lock()
ch := make(chan *v1.Event, 20)
c.eventWatches = append(c.eventWatches, fakeEventWatch{cancel, ns, ch})
toEmit := []*v1.Event{}
for _, event := range c.events {
if Namespace(event.Namespace) == ns {
toEmit = append(toEmit, event)
}
}
c.mu.Unlock()
go func() {
// Initial list of objects
for _, obj := range toEmit {
ch <- obj
}
<-ctx.Done()
c.mu.Lock()
var newWatches []fakeEventWatch
for _, e := range c.eventWatches {
if e.ns != ns {
newWatches = append(newWatches, e)
}
}
c.eventWatches = newWatches
c.mu.Unlock()
close(ch)
}()
return ch, nil
}
func (c *FakeK8sClient) WatchMeta(ctx context.Context, gvk schema.GroupVersionKind, ns Namespace) (<-chan metav1.Object, error) {
if ns == "" {
return nil, fmt.Errorf("missing namespace from watch request")
}
return make(chan metav1.Object), nil
}
func (c *FakeK8sClient) EmitPodDelete(p *v1.Pod) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.pods, types.NamespacedName{Name: p.Name, Namespace: p.Namespace})
for _, w := range c.podWatches {
if w.ns != Namespace(p.Namespace) {
continue
}
w.ch <- ObjectUpdate{obj: p, isDelete: true}
}
}
func (c *FakeK8sClient) WatchPods(ctx context.Context, ns Namespace) (<-chan ObjectUpdate, error) {
if ns == "" {
return nil, fmt.Errorf("missing namespace from watch request")
}
ctx, cancel := context.WithCancel(ctx)
c.mu.Lock()
ch := make(chan ObjectUpdate, 20)
c.podWatches = append(c.podWatches, fakePodWatch{cancel, ns, ch})
toEmit := []*v1.Pod{}
for _, pod := range c.pods {
if Namespace(pod.Namespace) == ns {
toEmit = append(toEmit, pod)
}
}
c.mu.Unlock()
go func() {
// Initial list of objects
for _, obj := range toEmit {
ch <- ObjectUpdate{obj: obj}
}
<-ctx.Done()
c.mu.Lock()
var newWatches []fakePodWatch
for _, e := range c.podWatches {
if e.ns != ns {
newWatches = append(newWatches, e)
}
}
c.podWatches = newWatches
c.mu.Unlock()
close(ch)
}()
return ch, nil
}
func NewFakeK8sClient(t testing.TB) *FakeK8sClient {
cli := &FakeK8sClient{
t: t,
PodLogsByPodAndContainer: make(map[PodAndCName]ReaderCloser),
pods: make(map[types.NamespacedName]*v1.Pod),
services: make(map[types.NamespacedName]*v1.Service),
events: make(map[types.NamespacedName]*v1.Event),
entities: make(map[types.UID]K8sEntity),
currentVersions: make(map[string]types.UID),
FakeAPIConfig: &api.Config{
CurrentContext: "default",
Contexts: map[string]*api.Context{
"default": &api.Context{
Cluster: "default",
Namespace: "default",
},
},
Clusters: map[string]*api.Cluster{
"default": &api.Cluster{},
},
},
}
ctx, cancel := context.WithCancel(logger.WithLogger(context.Background(), logger.NewTestLogger(os.Stdout)))
t.Cleanup(cancel)
t.Cleanup(cli.tearDown)
cli.ownerFetcher = NewOwnerFetcher(ctx, cli)
return cli
}
func (c *FakeK8sClient) tearDown() {
c.mu.Lock()
podWatches := append([]fakePodWatch{}, c.podWatches...)
serviceWatches := append([]fakeServiceWatch{}, c.serviceWatches...)
eventWatches := append([]fakeEventWatch{}, c.eventWatches...)
c.mu.Unlock()
for _, watch := range podWatches {
watch.cancel()
for range watch.ch {
}
}
for _, watch := range serviceWatches {
watch.cancel()
for range watch.ch {
}
}
for _, watch := range eventWatches {
watch.cancel()
for range watch.ch {
}
}
}
func (c *FakeK8sClient) Upsert(_ context.Context, entities []K8sEntity, timeout time.Duration) ([]K8sEntity, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.UpsertError != nil {
return nil, c.UpsertError
}
var result []K8sEntity
if c.UpsertResult != nil {
result = c.UpsertResult
} else {
yaml, err := SerializeSpecYAML(entities)
if err != nil {
return nil, errors.Wrap(err, "kubectl apply")
}
c.Yaml = yaml
for _, e := range entities {
clone := e.DeepCopy()
clone.SetUID(uuid.New().String())
result = append(result, clone)
}
}
c.LastUpsertResult = result
c.UpsertTimeout = timeout
return result, nil
}
func (c *FakeK8sClient) Delete(_ context.Context, entities []K8sEntity, wait time.Duration) error {
c.mu.Lock()
defer c.mu.Unlock()
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
}
// Inject adds an entity or replaces it for subsequent retrieval.
//
// Entities are keyed by UID.
func (c *FakeK8sClient) Inject(entities ...K8sEntity) {
c.mu.Lock()
defer c.mu.Unlock()
c.t.Helper()
for i, entity := range entities {
if entity.UID() == "" {
c.t.Fatalf("Entity with name[%s] at index[%d] had no UID", entity.Name(), i)
}
c.entities[entity.UID()] = entity
c.currentVersions[entity.Name()] = entity.UID()
}
}
func (c *FakeK8sClient) GetMetaByReference(ctx context.Context, ref v1.ObjectReference) (metav1.Object, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.getByReferenceCallCount++
resp, ok := c.entities[ref.UID]
if !ok {
logger.Get(ctx).Infof("FakeK8sClient.GetMetaByReference: resource not found: %s", ref.Name)
return nil, apierrors.NewNotFound(v1.Resource(ref.Kind), ref.Name)
}
return resp.Meta(), nil
}
func (c *FakeK8sClient) ListMeta(_ context.Context, gvk schema.GroupVersionKind, ns Namespace) ([]metav1.Object, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.listCallCount++
if c.listReturnsEmpty {
return nil, nil
}
result := make([]metav1.Object, 0)
for _, uid := range c.currentVersions {
entity := c.entities[uid]
if entity.Namespace().String() != ns.String() {
continue
}
if entity.GVK() != gvk {
continue
}
result = append(result, entity.Meta())
}
return result, nil
}
func (c *FakeK8sClient) SetLogsForPodContainer(pID PodID, cName container.Name, logs string) {
c.SetLogReaderForPodContainer(pID, cName, strings.NewReader(logs))
}
func (c *FakeK8sClient) SetLogReaderForPodContainer(pID PodID, cName container.Name, reader io.Reader) {
c.mu.Lock()
defer c.mu.Unlock()
c.PodLogsByPodAndContainer[PodAndCName{pID, cName}] = ReaderCloser{Reader: reader}
}
func (c *FakeK8sClient) ContainerLogs(ctx context.Context, pID PodID, cName container.Name, n Namespace, startTime time.Time) (io.ReadCloser, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.ContainerLogsError != nil {
return nil, c.ContainerLogsError
}
// metav1.Time truncates to the nearest second when serializing across the
// wire, so truncate here to replicate that behavior.
c.LastPodLogStartTime = startTime.Truncate(time.Second)
c.LastPodLogContext = ctx
// If we have specific logs for this pod/container combo, return those
if buf, ok := c.PodLogsByPodAndContainer[PodAndCName{pID, cName}]; ok {
return buf, nil
}
r, w := io.Pipe()
c.LastPodLogPipeWriter = w
return ReaderCloser{Reader: r}, nil
}
func (c *FakeK8sClient) APIConfig() *api.Config {
return c.FakeAPIConfig
}
func (c *FakeK8sClient) ClusterHealth(_ context.Context, _ bool) (ClusterHealth, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.ClusterHealthStatus != nil {
return *c.ClusterHealthStatus, nil
}
if c.ClusterHealthError != nil {
return ClusterHealth{}, c.ClusterHealthError
}
return ClusterHealth{
Live: true,
Ready: true,
// these are not meant to be machine-readable, but they're formatted to
// look like the actual output in K8s for consistency
// https://kubernetes.io/docs/reference/using-api/health-checks/
LiveOutput: "[+]fake-tilt ok\nlivez check passed\n",
ReadyOutput: "[+]fake-tilt ok\nreadyz check passed\n",
}, 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) 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 {
c.mu.Lock()
defer c.mu.Unlock()
if c.Runtime != "" {
return c.Runtime
}
return container.RuntimeDocker
}
func (c *FakeK8sClient) LocalRegistry(_ context.Context) *v1alpha1.RegistryHosting {
c.mu.Lock()
defer c.mu.Unlock()
if c.Registry == nil {
return nil
}
return c.Registry.DeepCopy()
}
func (c *FakeK8sClient) NodeIP(ctx context.Context) NodeIP {
c.mu.Lock()
defer c.mu.Unlock()
return c.FakeNodeIP
}
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 {
c.mu.Lock()
defer c.mu.Unlock()
var stdinBytes []byte
var err error
if stdin != nil {
stdinBytes, err = io.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.ExecOutputs) > 0 {
out := c.ExecOutputs[0]
c.ExecOutputs = c.ExecOutputs[1:]
_, _ = io.Copy(stdout, out)
}
if len(c.ExecErrors) > 0 {
err = c.ExecErrors[0]
c.ExecErrors = c.ExecErrors[1:]
return err
}
return nil
}
func (c *FakeK8sClient) CheckConnected(ctx context.Context) (*version.Info, error) {
return &version.Info{}, nil
}
func (c *FakeK8sClient) OwnerFetcher() OwnerFetcher {
return c.ownerFetcher
}
type ReaderCloser struct {
io.Reader
}
func (b ReaderCloser) Close() error {
return nil
}
var _ io.ReadCloser = ReaderCloser{}
type FakePortForwarder struct {
localPort int
namespace Namespace
ctx context.Context
ready chan struct{}
done chan error
}
var _ PortForwarder = FakePortForwarder{}
func NewFakePortForwarder(ctx context.Context, localPort int, namespace Namespace) FakePortForwarder {
return FakePortForwarder{
localPort: localPort,
namespace: namespace,
ctx: ctx,
ready: make(chan struct{}, 1),
done: make(chan error),
}
}
func (pf FakePortForwarder) Addresses() []string {
return []string{"127.0.0.1", "::1"}
}
func (pf FakePortForwarder) LocalPort() int {
return pf.localPort
}
func (pf FakePortForwarder) Namespace() Namespace {
return pf.namespace
}
func (pf FakePortForwarder) ForwardPorts() error {
// in the real port forwarder, the binding/listening logic can fail before the forwarder signals it's ready
// to simulate this in tests, there's a magic port number
if pf.localPort == MagicTestExplodingPort {
return errors.New("fake error starting port forwarding")
}
close(pf.ready)
select {
case <-pf.ctx.Done():
// NOTE: the context error should NOT be returned here
return nil
case err := <-pf.done:
return err
}
}
func (pf FakePortForwarder) ReadyCh() <-chan struct{} {
return pf.ready
}
// TriggerFailure allows tests to inject errors during forwarding that will be returned by ForwardPorts.
func (pf FakePortForwarder) TriggerFailure(err error) {
pf.done <- err
}
type FakePortForwardClient struct {
mu sync.Mutex
portForwardCalls []PortForwardCall
}
func NewFakePortForwardClient() *FakePortForwardClient {
return &FakePortForwardClient{
portForwardCalls: []PortForwardCall{},
}
}
type PortForwardCall struct {
PodID PodID
RemotePort int
Host string
Forwarder FakePortForwarder
Context context.Context
}
func (c *FakePortForwardClient) CreatePortForwarder(ctx context.Context, namespace Namespace, podID PodID, optionalLocalPort, remotePort int, host string) (PortForwarder, error) {
c.mu.Lock()
defer c.mu.Unlock()
result := NewFakePortForwarder(ctx, optionalLocalPort, namespace)
c.portForwardCalls = append(c.portForwardCalls, PortForwardCall{
PodID: podID,
RemotePort: remotePort,
Host: host,
Forwarder: result,
Context: ctx,
})
return result, nil
}
func (c *FakePortForwardClient) CreatePortForwardCallCount() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.portForwardCalls)
}
func (c *FakePortForwardClient) LastForwardPortPodID() PodID {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.portForwardCalls) == 0 {
return ""
}
return c.portForwardCalls[len(c.portForwardCalls)-1].PodID
}
func (c *FakePortForwardClient) LastForwardPortRemotePort() int {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.portForwardCalls) == 0 {
return 0
}
return c.portForwardCalls[len(c.portForwardCalls)-1].RemotePort
}
func (c *FakePortForwardClient) LastForwardPortHost() string {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.portForwardCalls) == 0 {
return ""
}
return c.portForwardCalls[len(c.portForwardCalls)-1].Host
}
func (c *FakePortForwardClient) LastForwarder() FakePortForwarder {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.portForwardCalls) == 0 {
return FakePortForwarder{}
}
return c.portForwardCalls[len(c.portForwardCalls)-1].Forwarder
}
func (c *FakePortForwardClient) LastForwardContext() context.Context {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.portForwardCalls) == 0 {
return nil
}
return c.portForwardCalls[len(c.portForwardCalls)-1].Context
}
func (c *FakePortForwardClient) PortForwardCalls() []PortForwardCall {
c.mu.Lock()
defer c.mu.Unlock()
return append([]PortForwardCall(nil), c.portForwardCalls...)
}