-
Notifications
You must be signed in to change notification settings - Fork 83
/
kubernetes.go
1468 lines (1289 loc) · 38.6 KB
/
kubernetes.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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build !no_workceptor
// +build !no_workceptor
package workceptor
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/ghjm/cmdline"
"github.com/google/shlex"
"golang.org/x/net/http2"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/version"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/remotecommand"
watch2 "k8s.io/client-go/tools/watch"
"k8s.io/client-go/util/flowcontrol"
)
// kubeUnit implements the WorkUnit interface.
type kubeUnit struct {
BaseWorkUnit
authMethod string
streamMethod string
baseParams string
allowRuntimeAuth bool
allowRuntimeCommand bool
allowRuntimeParams bool
allowRuntimePod bool
deletePodOnRestart bool
namePrefix string
config *rest.Config
clientset *kubernetes.Clientset
pod *corev1.Pod
podPendingTimeout time.Duration
}
// kubeExtraData is the content of the ExtraData JSON field for a Kubernetes worker.
type kubeExtraData struct {
Image string
Command string
Params string
KubeNamespace string
KubeConfig string
KubePod string
PodName string
}
// ErrPodCompleted is returned when pod has already completed before we could attach.
var ErrPodCompleted = fmt.Errorf("pod ran to completion")
// ErrPodFailed is returned when pod has failed before we could attach.
var ErrPodFailed = fmt.Errorf("pod failed to start")
// ErrImagePullBackOff is returned when the image for the container in the Pod cannot be pulled.
var ErrImagePullBackOff = fmt.Errorf("container failed to start")
// podRunningAndReady is a completion criterion for pod ready to be attached to.
func podRunningAndReady() func(event watch.Event) (bool, error) {
imagePullBackOffRetries := 3
inner := func(event watch.Event) (bool, error) {
if event.Type == watch.Deleted {
return false, apierrors.NewNotFound(schema.GroupResource{Resource: "pods"}, "")
}
if t, ok := event.Object.(*corev1.Pod); ok {
switch t.Status.Phase {
case corev1.PodFailed:
return false, ErrPodFailed
case corev1.PodSucceeded:
return false, ErrPodCompleted
case corev1.PodRunning, corev1.PodPending:
conditions := t.Status.Conditions
if conditions == nil {
return false, nil
}
for i := range conditions {
if conditions[i].Type == corev1.PodReady &&
conditions[i].Status == corev1.ConditionTrue {
return true, nil
}
if conditions[i].Type == corev1.ContainersReady &&
conditions[i].Status == corev1.ConditionFalse {
statuses := t.Status.ContainerStatuses
for j := range statuses {
if statuses[j].State.Waiting != nil {
if statuses[j].State.Waiting.Reason == "ImagePullBackOff" {
if imagePullBackOffRetries == 0 {
return false, ErrImagePullBackOff
}
imagePullBackOffRetries--
}
}
}
}
}
}
}
return false, nil
}
return inner
}
func (kw *kubeUnit) kubeLoggingConnectionHandler(timestamps bool) (io.ReadCloser, error) {
var logStream io.ReadCloser
var err error
var sinceTime time.Time
podNamespace := kw.pod.Namespace
podName := kw.pod.Name
podOptions := &corev1.PodLogOptions{
Container: "worker",
Follow: true,
}
if timestamps {
podOptions.Timestamps = true
podOptions.SinceTime = &metav1.Time{Time: sinceTime}
}
logReq := kw.clientset.CoreV1().Pods(podNamespace).GetLogs(
podName, podOptions,
)
// get logstream, with retry
for retries := 5; retries > 0; retries-- {
logStream, err = logReq.Stream(kw.ctx)
if err == nil {
break
}
kw.Warning(
"Error opening log stream for pod %s/%s. Will retry %d more times. Error: %s",
podNamespace,
podName,
retries,
err,
)
time.Sleep(time.Second)
}
if err != nil {
errMsg := fmt.Sprintf("Error opening log stream for pod %s/%s. Error: %s", podNamespace, podName, err)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return nil, err
}
return logStream, nil
}
func (kw *kubeUnit) kubeLoggingNoReconnect(streamWait *sync.WaitGroup, stdout *stdoutWriter, stdoutErr *error) {
// Legacy method, for use on k8s < v1.23.14
// uses io.Copy to stream data from pod to stdout file
// known issues around this, as logstream can terminate due to log rotation
// or 4 hr timeout
defer streamWait.Done()
podNamespace := kw.pod.Namespace
podName := kw.pod.Name
logStream, err := kw.kubeLoggingConnectionHandler(false)
if err != nil {
return
}
_, *stdoutErr = io.Copy(stdout, logStream)
if *stdoutErr != nil {
kw.Error(
"Error streaming pod logs to stdout for pod %s/%s. Error: %s",
podNamespace,
podName,
*stdoutErr,
)
}
}
func (kw *kubeUnit) kubeLoggingWithReconnect(streamWait *sync.WaitGroup, stdout *stdoutWriter, stdinErr *error, stdoutErr *error) {
// preferred method for k8s >= 1.23.14
defer streamWait.Done()
var sinceTime time.Time
var err error
podNamespace := kw.pod.Namespace
podName := kw.pod.Name
retries := 5
successfulWrite := false
remainingRetries := retries // resets on each successful read from pod stdout
for {
if *stdinErr != nil {
break
}
// get pod, with retry
for retries := 5; retries > 0; retries-- {
kw.pod, err = kw.clientset.CoreV1().Pods(podNamespace).Get(kw.ctx, podName, metav1.GetOptions{})
if err == nil {
break
}
kw.Warning(
"Error getting pod %s/%s. Will retry %d more times. Error: %s",
podNamespace,
podName,
retries,
err,
)
time.Sleep(time.Second)
}
if err != nil {
errMsg := fmt.Sprintf("Error getting pod %s/%s. Error: %s", podNamespace, podName, err)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
break
}
logStream, err := kw.kubeLoggingConnectionHandler(true)
if err != nil {
break
}
// read from logstream
streamReader := bufio.NewReader(logStream)
for *stdinErr == nil { // check between every line read to see if we need to stop reading
line, err := streamReader.ReadString('\n')
if err == io.EOF {
kw.Debug(
"Detected EOF for pod %s/%s. Will retry %d more times. Error: %s",
podNamespace,
podName,
remainingRetries,
err,
)
successfulWrite = false
remainingRetries--
if remainingRetries > 0 {
time.Sleep(200 * time.Millisecond)
break
}
return
} else if _, ok := err.(http2.GoAwayError); ok {
// GOAWAY is sent by the server to indicate that the server is gracefully shutting down
// this happens if the kube API server we are connected to is being restarted or is shutting down
// for example during a cluster upgrade and rolling restart of the master node
kw.Info(
"Detected http2.GoAwayError for pod %s/%s. Will retry %d more times. Error: %s",
podNamespace,
podName,
remainingRetries,
err,
)
successfulWrite = false
remainingRetries--
if remainingRetries > 0 {
time.Sleep(200 * time.Millisecond)
break
}
}
if err != nil {
*stdoutErr = err
kw.Error("Error reading from pod %s/%s: %s", podNamespace, podName, err)
return
}
split := strings.SplitN(line, " ", 2)
timeStamp := parseTime(split[0])
if !timeStamp.After(sinceTime) && !successfulWrite {
continue
}
msg := split[1]
_, err = stdout.Write([]byte(msg))
if err != nil {
*stdoutErr = fmt.Errorf("writing to stdout: %s", err)
kw.Error("Error writing to stdout: %s", err)
return
}
remainingRetries = retries // each time we read successfully, reset this counter
sinceTime = *timeStamp
successfulWrite = true
}
logStream.Close()
}
}
func (kw *kubeUnit) createPod(env map[string]string) error {
ked := kw.UnredactedStatus().ExtraData.(*kubeExtraData)
command, err := shlex.Split(ked.Command)
if err != nil {
return err
}
params, err := shlex.Split(ked.Params)
if err != nil {
return err
}
pod := &corev1.Pod{}
var spec *corev1.PodSpec
var objectMeta *metav1.ObjectMeta
if ked.KubePod != "" {
decode := scheme.Codecs.UniversalDeserializer().Decode
_, _, err := decode([]byte(ked.KubePod), nil, pod)
if err != nil {
return err
}
foundWorker := false
spec = &pod.Spec
for i := range spec.Containers {
if spec.Containers[i].Name == "worker" {
spec.Containers[i].Stdin = true
spec.Containers[i].StdinOnce = true
foundWorker = true
break
}
}
if !foundWorker {
return fmt.Errorf("at least one container must be named worker")
}
spec.RestartPolicy = corev1.RestartPolicyNever
userNamespace := pod.ObjectMeta.Namespace
if userNamespace != "" {
ked.KubeNamespace = userNamespace
}
userPodName := pod.ObjectMeta.Name
if userPodName != "" {
kw.namePrefix = userPodName + "-"
}
objectMeta = &pod.ObjectMeta
objectMeta.Name = ""
objectMeta.GenerateName = kw.namePrefix
objectMeta.Namespace = ked.KubeNamespace
} else {
objectMeta = &metav1.ObjectMeta{
GenerateName: kw.namePrefix,
Namespace: ked.KubeNamespace,
}
spec = &corev1.PodSpec{
Containers: []corev1.Container{{
Name: "worker",
Image: ked.Image,
Command: command,
Args: params,
Stdin: true,
StdinOnce: true,
TTY: false,
}},
RestartPolicy: corev1.RestartPolicyNever,
}
}
pod = &corev1.Pod{
ObjectMeta: *objectMeta,
Spec: *spec,
}
if env != nil {
evs := make([]corev1.EnvVar, 0)
for k, v := range env {
evs = append(evs, corev1.EnvVar{
Name: k,
Value: v,
})
}
pod.Spec.Containers[0].Env = evs
}
// get pod and store to kw.pod
kw.pod, err = kw.clientset.CoreV1().Pods(ked.KubeNamespace).Create(kw.ctx, pod, metav1.CreateOptions{})
if err != nil {
return err
}
select {
case <-kw.ctx.Done():
return fmt.Errorf("cancelled")
default:
}
kw.UpdateFullStatus(func(status *StatusFileData) {
status.State = WorkStatePending
status.Detail = "Pod created"
status.StdoutSize = 0
status.ExtraData.(*kubeExtraData).PodName = kw.pod.Name
})
// Wait for the pod to be running
fieldSelector := fields.OneTermEqualSelector("metadata.name", kw.pod.Name).String()
lw := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = fieldSelector
return kw.clientset.CoreV1().Pods(ked.KubeNamespace).List(kw.ctx, options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = fieldSelector
return kw.clientset.CoreV1().Pods(ked.KubeNamespace).Watch(kw.ctx, options)
},
}
ctxPodReady := kw.ctx
if kw.podPendingTimeout != time.Duration(0) {
ctxPodReady, _ = context.WithTimeout(kw.ctx, kw.podPendingTimeout)
}
time.Sleep(2 * time.Second)
ev, err := watch2.UntilWithSync(ctxPodReady, lw, &corev1.Pod{}, nil, podRunningAndReady())
if ev == nil || ev.Object == nil {
return fmt.Errorf("did not return an event while watching pod for work unit %s", kw.ID())
}
var ok bool
kw.pod, ok = ev.Object.(*corev1.Pod)
if !ok {
return fmt.Errorf("watch did not return a pod")
}
if err == ErrPodCompleted {
// Hao: shouldn't we also call kw.Cancel() in these cases?
for _, cstat := range kw.pod.Status.ContainerStatuses {
if cstat.Name == "worker" {
if cstat.State.Terminated != nil && cstat.State.Terminated.ExitCode != 0 {
return fmt.Errorf("container failed with exit code %d: %s", cstat.State.Terminated.ExitCode, cstat.State.Terminated.Message)
}
break
}
}
return err
} else if err != nil { // any other error besides ErrPodCompleted
stdout, err2 := newStdoutWriter(kw.UnitDir())
if err2 != nil {
errMsg := fmt.Sprintf("Error opening stdout file: %s", err2)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return fmt.Errorf(errMsg)
}
var stdoutErr error
var streamWait sync.WaitGroup
streamWait.Add(1)
go kw.kubeLoggingNoReconnect(&streamWait, stdout, &stdoutErr)
streamWait.Wait()
kw.Cancel()
if len(kw.pod.Status.ContainerStatuses) == 1 {
if kw.pod.Status.ContainerStatuses[0].State.Waiting != nil {
return fmt.Errorf("%s, %s", err.Error(), kw.pod.Status.ContainerStatuses[0].State.Waiting.Reason)
}
for _, cstat := range kw.pod.Status.ContainerStatuses {
if cstat.Name == "worker" {
if cstat.State.Waiting != nil {
return fmt.Errorf("%s, %s", err.Error(), cstat.State.Waiting.Reason)
}
if cstat.State.Terminated != nil && cstat.State.Terminated.ExitCode != 0 {
return fmt.Errorf("%s, exit code %d: %s", err.Error(), cstat.State.Terminated.ExitCode, cstat.State.Terminated.Message)
}
break
}
}
}
return err
}
return nil
}
func (kw *kubeUnit) runWorkUsingLogger() {
skipStdin := true
status := kw.Status()
ked := status.ExtraData.(*kubeExtraData)
podName := ked.PodName
podNamespace := ked.KubeNamespace
if podName == "" {
// create new pod if ked.PodName is empty
if err := kw.createPod(nil); err != nil {
if err != ErrPodCompleted {
errMsg := fmt.Sprintf("Error creating pod: %s", err)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
} else {
// for newly created pod we need to stream stdin
skipStdin = false
}
podName = kw.pod.Name
podNamespace = kw.pod.Namespace
} else {
if podNamespace == "" {
errMsg := fmt.Sprintf("Error creating pod: pod namespace is empty for pod %s",
podName,
)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
// resuming from a previously created pod
var err error
for retries := 5; retries > 0; retries-- {
// check if the kw.ctx is already cancel
select {
case <-kw.ctx.Done():
errMsg := fmt.Sprintf("Context Done while getting pod %s/%s. Error: %s", podNamespace, podName, kw.ctx.Err())
kw.Warning(errMsg)
return
default:
}
kw.pod, err = kw.clientset.CoreV1().Pods(podNamespace).Get(kw.ctx, podName, metav1.GetOptions{})
if err == nil {
break
}
kw.Warning(
"Error getting pod %s/%s. Will retry %d more times. Retrying: %s",
podNamespace,
podName,
retries,
err,
)
time.Sleep(200 * time.Millisecond)
}
if err != nil {
errMsg := fmt.Sprintf("Error getting pod %s/%s. Error: %s", podNamespace, podName, err)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
}
// Attach stdin stream to the pod
var exec remotecommand.Executor
if !skipStdin {
req := kw.clientset.CoreV1().RESTClient().Post().
Resource("pods").
Name(podName).
Namespace(podNamespace).
SubResource("attach")
req.VersionedParams(
&corev1.PodExecOptions{
Container: "worker",
Stdin: true,
Stdout: false,
Stderr: false,
TTY: false,
},
scheme.ParameterCodec,
)
var err error
exec, err = remotecommand.NewSPDYExecutor(kw.config, "POST", req.URL())
if err != nil {
errMsg := fmt.Sprintf("Error creating SPDY executor: %s", err)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
}
var stdinErr error
var stdoutErr error
// finishedChan signal the stdin and stdout monitoring goroutine to stop
finishedChan := make(chan struct{})
// this will signal the stdin and stdout monitoring goroutine to stop when this function returns
defer close(finishedChan)
stdinErrChan := make(chan struct{}) // signal that stdin goroutine have errored and stop stdout goroutine
// open stdin reader that reads from the work unit's data directory
var stdin *stdinReader
if !skipStdin {
var err error
stdin, err = newStdinReader(kw.UnitDir())
if err != nil {
if errors.Is(err, errFileSizeZero) {
skipStdin = true
} else {
errMsg := fmt.Sprintf("Error opening stdin file: %s", err)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
} else {
// goroutine to cancel stdin reader
go func() {
select {
case <-kw.ctx.Done():
stdin.reader.Close()
return
case <-finishedChan:
case <-stdin.Done():
return
}
}()
}
}
// open stdout writer that writes to work unit's data directory
stdout, err := newStdoutWriter(kw.UnitDir())
if err != nil {
errMsg := fmt.Sprintf("Error opening stdout file: %s", err)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
// goroutine to cancel stdout stream
go func() {
select {
case <-kw.ctx.Done():
stdout.writer.Close()
return
case <-stdinErrChan:
stdout.writer.Close()
return
case <-finishedChan:
return
}
}()
streamWait := sync.WaitGroup{}
streamWait.Add(2)
if skipStdin {
kw.UpdateBasicStatus(WorkStateRunning, "Pod Running", stdout.Size())
streamWait.Done()
} else {
go func() {
defer streamWait.Done()
kw.UpdateFullStatus(func(status *StatusFileData) {
status.State = WorkStatePending
status.Detail = "Sending stdin to pod"
})
var err error
for retries := 5; retries > 0; retries-- {
err = exec.StreamWithContext(kw.ctx, remotecommand.StreamOptions{
Stdin: stdin,
Tty: false,
})
if err != nil {
// NOTE: io.EOF for stdin is handled by remotecommand and will not trigger this
kw.Warning(
"Error streaming stdin to pod %s/%s. Will retry %d more times. Error: %s",
podNamespace,
podName,
retries,
err,
)
time.Sleep(200 * time.Millisecond)
} else {
break
}
}
if err != nil {
stdinErr = err
errMsg := fmt.Sprintf(
"Error streaming stdin to pod %s/%s. Error: %s",
podNamespace,
podName,
err,
)
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, stdout.Size())
close(stdinErrChan) // signal STDOUT goroutine to stop
} else {
if stdin.Error() == io.EOF {
kw.UpdateBasicStatus(WorkStateRunning, "Pod Running", stdout.Size())
} else {
// this is probably not possible...
errMsg := fmt.Sprintf("Error reading stdin: %s", stdin.Error())
kw.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, stdout.Size())
close(stdinErrChan) // signal STDOUT goroutine to stop
}
}
}()
}
stdoutWithReconnect := shouldUseReconnect(kw)
if stdoutWithReconnect && stdoutErr == nil {
kw.Debug("streaming stdout with reconnect support")
go kw.kubeLoggingWithReconnect(&streamWait, stdout, &stdinErr, &stdoutErr)
} else {
kw.Debug("streaming stdout with no reconnect support")
go kw.kubeLoggingNoReconnect(&streamWait, stdout, &stdoutErr)
}
streamWait.Wait()
if stdinErr != nil || stdoutErr != nil {
var errDetail string
switch {
case stdinErr == nil:
errDetail = fmt.Sprintf("Error with pod's stdout: %s", stdoutErr)
case stdoutErr == nil:
errDetail = fmt.Sprintf("Error with pod's stdin: %s", stdinErr)
default:
errDetail = fmt.Sprintf("Error running pod. stdin: %s, stdout: %s", stdinErr, stdoutErr)
}
if kw.ctx.Err() != context.Canceled {
kw.UpdateBasicStatus(WorkStateFailed, errDetail, stdout.Size())
}
return
}
if kw.ctx.Err() != context.Canceled {
kw.UpdateBasicStatus(WorkStateSucceeded, "Finished", stdout.Size())
}
}
func isCompatibleK8S(kw *kubeUnit, versionStr string) bool {
semver, err := version.ParseSemantic(versionStr)
if err != nil {
kw.w.nc.Logger.Warning("could parse Kubernetes server version %s, will not use reconnect support", versionStr)
return false
}
// ignore pre-release in version comparison
semver = semver.WithPreRelease("")
// The patch was backported to minor version 23, 24 and 25. We must check z stream
// based on the minor version
// if minor version == 24, compare with v1.24.8
// if minor version == 25, compare with v1.25.4
// all other minor versions compare with v1.23.14
var compatibleVer string
switch semver.Minor() {
case 24:
compatibleVer = "v1.24.8"
case 25:
compatibleVer = "v1.25.4"
default:
compatibleVer = "v1.23.14"
}
if semver.AtLeast(version.MustParseSemantic(compatibleVer)) {
kw.w.nc.Logger.Debug("Kubernetes version %s is at least %s, using reconnect support", semver, compatibleVer)
return true
}
kw.w.nc.Logger.Debug("Kubernetes version %s not at least %s, not using reconnect support", semver, compatibleVer)
return false
}
func shouldUseReconnect(kw *kubeUnit) bool {
// Attempt to detect support for streaming from pod with timestamps based on
// Kubernetes server version
// In order to use reconnect method, Kubernetes server must be at least
// v1.23.14
// v1.24.8
// v1.25.4
// These versions contain a critical patch that permits connecting to the
// logstream with timestamps enabled.
// Without the patch, stdout lines would be split after 4K characters into a
// new line, which will cause issues in Receptor.
// https://github.com/kubernetes/kubernetes/issues/77603
// Can override the detection by setting the RECEPTOR_KUBE_SUPPORT_RECONNECT
// accepted values: "enabled", "disabled", "auto" with "disabled" being the default
// all invalid value will assume to be "disabled"
env, ok := os.LookupEnv("RECEPTOR_KUBE_SUPPORT_RECONNECT")
if ok {
switch env {
case "enabled":
return true
case "disabled":
return false
case "auto":
// continue
default:
return false
}
}
serverVerInfo, err := kw.clientset.ServerVersion()
if err != nil {
kw.w.nc.Logger.Warning("could not detect Kubernetes server version, will not use reconnect support")
return false
}
return isCompatibleK8S(kw, serverVerInfo.String())
}
func parseTime(s string) *time.Time {
t, err := time.Parse(time.RFC3339, s)
if err == nil {
return &t
}
t, err = time.Parse(time.RFC3339Nano, s)
if err == nil {
return &t
}
return nil
}
func getDefaultInterface() (string, error) {
nifs, err := net.Interfaces()
if err != nil {
return "", err
}
for i := range nifs {
nif := nifs[i]
if nif.Flags&net.FlagUp != 0 && nif.Flags&net.FlagLoopback == 0 {
ads, err := nif.Addrs()
if err == nil && len(ads) > 0 {
for j := range ads {
ad := ads[j]
ip, ok := ad.(*net.IPNet)
if ok {
if !ip.IP.IsLoopback() && !ip.IP.IsMulticast() {
return ip.IP.String(), nil
}
}
}
}
}
}
return "", fmt.Errorf("could not determine local address")
}
func (kw *kubeUnit) runWorkUsingTCP() {
// Create local cancellable context
ctx, cancel := kw.ctx, kw.cancel
defer cancel()
// Create the TCP listener
lc := net.ListenConfig{}
defaultInterfaceIP, err := getDefaultInterface()
var li net.Listener
if err == nil {
li, err = lc.Listen(ctx, "tcp", fmt.Sprintf("%s:", defaultInterfaceIP))
}
if ctx.Err() != nil {
return
}
var listenHost, listenPort string
if err == nil {
listenHost, listenPort, err = net.SplitHostPort(li.Addr().String())
}
if err != nil {
errMsg := fmt.Sprintf("Error listening: %s", err)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
kw.w.nc.Logger.Error(errMsg)
return
}
// Wait for a single incoming connection
connChan := make(chan *net.TCPConn)
go func() {
conn, err := li.Accept()
_ = li.Close()
if ctx.Err() != nil {
return
}
var tcpConn *net.TCPConn
if err == nil {
var ok bool
tcpConn, ok = conn.(*net.TCPConn)
if !ok {
err = fmt.Errorf("connection was not a TCPConn")
}
}
if err != nil {
errMsg := fmt.Sprintf("Error accepting: %s", err)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
kw.w.nc.Logger.Error(errMsg)
cancel()
return
}
connChan <- tcpConn
}()
// Create the pod
err = kw.createPod(map[string]string{"RECEPTOR_HOST": listenHost, "RECEPTOR_PORT": listenPort})
if err != nil {
errMsg := fmt.Sprintf("Error creating pod: %s", err)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
kw.w.nc.Logger.Error(errMsg)
cancel()
return
}
// Wait for the pod to connect back to us
var conn *net.TCPConn
select {
case <-ctx.Done():
return
case conn = <-connChan:
}
// Open stdin reader
var stdin *stdinReader
stdin, err = newStdinReader(kw.UnitDir())
if err != nil {
errMsg := fmt.Sprintf("Error opening stdin file: %s", err)
kw.w.nc.Logger.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
cancel()
return
}
// Open stdout writer
stdout, err := newStdoutWriter(kw.UnitDir())
if err != nil {
errMsg := fmt.Sprintf("Error opening stdout file: %s", err)
kw.w.nc.Logger.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
cancel()
return
}
kw.UpdateBasicStatus(WorkStatePending, "Sending stdin to pod", 0)
// Write stdin to pod
go func() {
_, err := io.Copy(conn, stdin)
if ctx.Err() != nil {
return
}
_ = conn.CloseWrite()
if err != nil {
errMsg := fmt.Sprintf("Error sending stdin to pod: %s", err)
kw.w.nc.Logger.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
cancel()
return
}
}()
// Goroutine to update status when stdin is fully sent to the pod, which is when we
// update from WorkStatePending to WorkStateRunning.
go func() {
select {
case <-ctx.Done():
return
case <-stdin.Done():