-
Notifications
You must be signed in to change notification settings - Fork 82
/
kubernetes.go
1679 lines (1467 loc) · 49.1 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"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/ghjm/cmdline"
"github.com/google/shlex"
"github.com/spf13/viper"
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 {
BaseWorkUnitForWorkUnit
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
}
type KubeAPIer interface {
NewNotFound(schema.GroupResource, string) *apierrors.StatusError
OneTermEqualSelector(string, string) fields.Selector
NewForConfig(*rest.Config) (*kubernetes.Clientset, error)
GetLogs(*kubernetes.Clientset, string, string, *corev1.PodLogOptions) *rest.Request
Get(context.Context, *kubernetes.Clientset, string, string, metav1.GetOptions) (*corev1.Pod, error)
Create(context.Context, *kubernetes.Clientset, string, *corev1.Pod, metav1.CreateOptions) (*corev1.Pod, error)
List(context.Context, *kubernetes.Clientset, string, metav1.ListOptions) (*corev1.PodList, error)
Watch(context.Context, *kubernetes.Clientset, string, metav1.ListOptions) (watch.Interface, error)
Delete(context.Context, *kubernetes.Clientset, string, string, metav1.DeleteOptions) error
SubResource(*kubernetes.Clientset, string, string) *rest.Request
InClusterConfig() (*rest.Config, error)
NewDefaultClientConfigLoadingRules() *clientcmd.ClientConfigLoadingRules
BuildConfigFromFlags(string, string) (*rest.Config, error)
NewClientConfigFromBytes([]byte) (clientcmd.ClientConfig, error)
NewSPDYExecutor(*rest.Config, string, *url.URL) (remotecommand.Executor, error)
StreamWithContext(context.Context, remotecommand.Executor, remotecommand.StreamOptions) error
UntilWithSync(context.Context, cache.ListerWatcher, runtime.Object, watch2.PreconditionFunc, ...watch2.ConditionFunc) (*watch.Event, error)
NewFakeNeverRateLimiter() flowcontrol.RateLimiter
NewFakeAlwaysRateLimiter() flowcontrol.RateLimiter
}
type KubeAPIWrapper struct{}
func (ku KubeAPIWrapper) NewNotFound(qualifiedResource schema.GroupResource, name string) *apierrors.StatusError {
return apierrors.NewNotFound(qualifiedResource, name)
}
func (ku KubeAPIWrapper) OneTermEqualSelector(k string, v string) fields.Selector {
return fields.OneTermEqualSelector(k, v)
}
func (ku KubeAPIWrapper) NewForConfig(c *rest.Config) (*kubernetes.Clientset, error) {
return kubernetes.NewForConfig(c)
}
func (ku KubeAPIWrapper) GetLogs(clientset *kubernetes.Clientset, namespace string, name string, opts *corev1.PodLogOptions) *rest.Request {
return clientset.CoreV1().Pods(namespace).GetLogs(name, opts)
}
func (ku KubeAPIWrapper) Get(ctx context.Context, clientset *kubernetes.Clientset, namespace string, name string, opts metav1.GetOptions) (*corev1.Pod, error) {
return clientset.CoreV1().Pods(namespace).Get(ctx, name, opts)
}
func (ku KubeAPIWrapper) Create(ctx context.Context, clientset *kubernetes.Clientset, namespace string, pod *corev1.Pod, opts metav1.CreateOptions) (*corev1.Pod, error) {
return clientset.CoreV1().Pods(namespace).Create(ctx, pod, opts)
}
func (ku KubeAPIWrapper) List(ctx context.Context, clientset *kubernetes.Clientset, namespace string, opts metav1.ListOptions) (*corev1.PodList, error) {
return clientset.CoreV1().Pods(namespace).List(ctx, opts)
}
func (ku KubeAPIWrapper) Watch(ctx context.Context, clientset *kubernetes.Clientset, namespace string, opts metav1.ListOptions) (watch.Interface, error) {
return clientset.CoreV1().Pods(namespace).Watch(ctx, opts)
}
func (ku KubeAPIWrapper) Delete(ctx context.Context, clientset *kubernetes.Clientset, namespace string, name string, opts metav1.DeleteOptions) error {
return clientset.CoreV1().Pods(namespace).Delete(ctx, name, opts)
}
func (ku KubeAPIWrapper) SubResource(clientset *kubernetes.Clientset, podName string, podNamespace string) *rest.Request {
return clientset.CoreV1().RESTClient().Post().Resource("pods").Name(podName).Namespace(podNamespace).SubResource("attach")
}
func (ku KubeAPIWrapper) InClusterConfig() (*rest.Config, error) {
return rest.InClusterConfig()
}
func (ku KubeAPIWrapper) NewDefaultClientConfigLoadingRules() *clientcmd.ClientConfigLoadingRules {
return clientcmd.NewDefaultClientConfigLoadingRules()
}
func (ku KubeAPIWrapper) BuildConfigFromFlags(masterURL string, kubeconfigPath string) (*rest.Config, error) {
return clientcmd.BuildConfigFromFlags(masterURL, kubeconfigPath)
}
func (ku KubeAPIWrapper) NewClientConfigFromBytes(configBytes []byte) (clientcmd.ClientConfig, error) {
return clientcmd.NewClientConfigFromBytes(configBytes)
}
func (ku KubeAPIWrapper) NewSPDYExecutor(config *rest.Config, method string, url *url.URL) (remotecommand.Executor, error) {
return remotecommand.NewSPDYExecutor(config, method, url)
}
func (ku KubeAPIWrapper) StreamWithContext(ctx context.Context, exec remotecommand.Executor, options remotecommand.StreamOptions) error {
return exec.StreamWithContext(ctx, options)
}
func (ku KubeAPIWrapper) UntilWithSync(ctx context.Context, lw cache.ListerWatcher, objType runtime.Object, precondition watch2.PreconditionFunc, conditions ...watch2.ConditionFunc) (*watch.Event, error) {
return watch2.UntilWithSync(ctx, lw, objType, precondition, conditions...)
}
func (ku KubeAPIWrapper) NewFakeNeverRateLimiter() flowcontrol.RateLimiter {
return flowcontrol.NewFakeNeverRateLimiter()
}
func (ku KubeAPIWrapper) NewFakeAlwaysRateLimiter() flowcontrol.RateLimiter {
return flowcontrol.NewFakeAlwaysRateLimiter()
}
// KubeAPIWrapperInstance is a package level var that wraps all required kubernetes API calls.
// It is instantiated in the NewkubeWorker function and available throughout the package.
var KubeAPIWrapperInstance KubeAPIer
var KubeAPIWrapperLock sync.Mutex
// 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, KubeAPIWrapperInstance.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 GetTimeoutOpenLogstream(kw *KubeUnit) int {
// RECEPTOR_OPEN_LOGSTREAM_TIMEOUT
// default: 1
openLogStreamTimeout := 1
envTimeout := os.Getenv("RECEPTOR_OPEN_LOGSTREAM_TIMEOUT")
if envTimeout != "" {
var err error
openLogStreamTimeout, err = strconv.Atoi(envTimeout)
if err != nil || openLogStreamTimeout < 1 {
// ignore error, use default
kw.GetWorkceptor().nc.GetLogger().Warning("Invalid value for RECEPTOR_OPEN_LOGSTREAM_TIMEOUT: %s. Ignoring", envTimeout)
openLogStreamTimeout = 1
}
}
kw.GetWorkceptor().nc.GetLogger().Debug("RECEPTOR_OPEN_LOGSTREAM_TIMEOUT: %d", openLogStreamTimeout)
return openLogStreamTimeout
}
func (kw *KubeUnit) kubeLoggingConnectionHandler(timestamps bool, sinceTime time.Time) (io.ReadCloser, error) {
var logStream io.ReadCloser
var err error
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 := KubeAPIWrapperInstance.GetLogs(kw.clientset, podNamespace, podName, podOptions)
// get logstream, with retry
for retries := 5; retries > 0; retries-- {
logStream, err = logReq.Stream(kw.GetContext())
if err == nil {
break
}
kw.GetWorkceptor().nc.GetLogger().Warning(
"Error opening log stream for pod %s/%s. Will retry %d more times. Error: %s",
podNamespace,
podName,
retries,
err,
)
time.Sleep(time.Duration(GetTimeoutOpenLogstream(kw)) * time.Second)
}
if err != nil {
errMsg := fmt.Sprintf("Error opening log stream for pod %s/%s. Error: %s", podNamespace, podName, err)
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
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, time.Time{})
if err != nil {
return
}
_, *stdoutErr = io.Copy(stdout, logStream)
if *stdoutErr != nil {
kw.GetWorkceptor().nc.GetLogger().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 {
// fail to send stdin to pod, no need to continue
return
}
// get pod, with retry
for retries := 5; retries > 0; retries-- {
kw.pod, err = KubeAPIWrapperInstance.Get(kw.GetContext(), kw.clientset, podNamespace, podName, metav1.GetOptions{})
if err == nil {
break
}
kw.GetWorkceptor().nc.GetLogger().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.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
// fail to get pod, no need to continue
return
}
logStream, err := kw.kubeLoggingConnectionHandler(true, sinceTime)
if err != nil {
// fail to get log stream, no need to continue
return
}
// 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 != nil {
if kw.GetContext().Err() == context.Canceled {
kw.GetWorkceptor().nc.GetLogger().Info(
"Context was canceled while reading logs for pod %s/%s. Assuming pod has finished",
podNamespace,
podName,
)
return
}
kw.GetWorkceptor().nc.GetLogger().Info(
"Detected Error: %s for pod %s/%s. Will retry %d more times.",
err,
podNamespace,
podName,
remainingRetries,
)
successfulWrite = false
remainingRetries--
if remainingRetries > 0 {
time.Sleep(200 * time.Millisecond)
break
}
kw.GetWorkceptor().nc.GetLogger().Error("Error reading from pod %s/%s: %s", podNamespace, podName, err)
// At this point we exausted all retries, every retry we either failed to read OR we read but did not get newer msg
// If we got a EOF on the last retry we assume that we read everything and we can stop the loop
// we ASSUME this is the happy path.
// If kube api returned an error there is a missing new line and that line never gets read.
if err != io.EOF {
*stdoutErr = err
} else if line != "" && err == io.EOF {
_, err = stdout.Write([]byte(line + "\n"))
if err != nil {
*stdoutErr = fmt.Errorf("writing to stdout: %s", err)
kw.GetWorkceptor().nc.GetLogger().Error("Error writing to stdout: %s", err)
return
}
}
return
}
split := strings.SplitN(line, " ", 2)
msg := line
timestamp := ParseTime(split[0])
if timestamp != nil {
kw.GetWorkceptor().nc.GetLogger().Debug("No timestamp received, log line: '%s'", line)
if !timestamp.After(sinceTime) && !successfulWrite {
continue
}
sinceTime = *timestamp
msg = split[1]
}
_, err = stdout.Write([]byte(msg))
if err != nil {
*stdoutErr = fmt.Errorf("writing to stdout: %s", err)
kw.GetWorkceptor().nc.GetLogger().Error("Error writing to stdout: %s", err)
return
}
remainingRetries = retries // each time we read successfully, reset this counter
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 = KubeAPIWrapperInstance.Create(kw.GetContext(), kw.clientset, ked.KubeNamespace, pod, metav1.CreateOptions{})
if err != nil {
return err
}
select {
case <-kw.GetContext().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
KubeAPIWrapperLock.Lock()
fieldSelector := KubeAPIWrapperInstance.OneTermEqualSelector("metadata.name", kw.pod.Name).String()
KubeAPIWrapperLock.Unlock()
lw := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = fieldSelector
return KubeAPIWrapperInstance.List(kw.GetContext(), kw.clientset, ked.KubeNamespace, options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = fieldSelector
return KubeAPIWrapperInstance.Watch(kw.GetContext(), kw.clientset, ked.KubeNamespace, options)
},
}
ctxPodReady := kw.GetContext()
if kw.podPendingTimeout != time.Duration(0) {
var ctxPodCancel context.CancelFunc
ctxPodReady, ctxPodCancel = context.WithTimeout(kw.GetContext(), kw.podPendingTimeout)
defer ctxPodCancel()
}
time.Sleep(2 * time.Second)
KubeAPIWrapperLock.Lock()
ev, err := KubeAPIWrapperInstance.UntilWithSync(ctxPodReady, lw, &corev1.Pod{}, nil, podRunningAndReady())
KubeAPIWrapperLock.Unlock()
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(FileSystem{}, kw.UnitDir())
if err2 != nil {
errMsg := fmt.Sprintf("Error opening stdout file: %s", err2)
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return fmt.Errorf(errMsg) //nolint:govet,staticcheck
}
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
// TODO: add retry logic to make this more resilient to transient errors
if err := kw.CreatePod(nil); err != nil {
if err != ErrPodCompleted {
errMsg := fmt.Sprintf("Error creating pod: %s", err)
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
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.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
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.GetContext().Done():
errMsg := fmt.Sprintf("Context Done while getting pod %s/%s. Error: %s", podNamespace, podName, kw.GetContext().Err())
kw.GetWorkceptor().nc.GetLogger().Warning(errMsg) //nolint:govet
return
default:
}
kw.pod, err = KubeAPIWrapperInstance.Get(kw.GetContext(), kw.clientset, podNamespace, podName, metav1.GetOptions{})
if err == nil {
break
}
kw.GetWorkceptor().nc.GetLogger().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.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
}
// Attach stdin stream to the pod
var exec remotecommand.Executor
if !skipStdin {
req := KubeAPIWrapperInstance.SubResource(kw.clientset, podName, podNamespace)
req.VersionedParams(
&corev1.PodExecOptions{
Container: "worker",
Stdin: true,
Stdout: false,
Stderr: false,
TTY: false,
},
scheme.ParameterCodec,
)
var err error
exec, err = KubeAPIWrapperInstance.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(FileSystem{}, kw.UnitDir())
if err != nil {
if errors.Is(err, errFileSizeZero) {
skipStdin = true
} else {
errMsg := fmt.Sprintf("Error opening stdin file: %s", err)
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
} else {
// goroutine to cancel stdin reader
go func() {
select {
case <-kw.GetContext().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(FileSystem{}, kw.UnitDir())
if err != nil {
errMsg := fmt.Sprintf("Error opening stdout file: %s", err)
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
// goroutine to cancel stdout stream
go func() {
select {
case <-kw.GetContext().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 = KubeAPIWrapperInstance.StreamWithContext(kw.GetContext(), exec, remotecommand.StreamOptions{
Stdin: stdin,
Tty: false,
})
if err != nil {
// NOTE: io.EOF for stdin is handled by remotecommand and will not trigger this
kw.GetWorkceptor().nc.GetLogger().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.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
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.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
kw.GetWorkceptor().nc.GetLogger().Error("Pod status at time of error %s", kw.pod.Status.String())
kw.UpdateBasicStatus(WorkStateFailed, errMsg, stdout.Size())
close(stdinErrChan) // signal STDOUT goroutine to stop
}
}
}()
}
stdoutWithReconnect := ShouldUseReconnect(kw)
if stdoutWithReconnect && stdoutErr == nil {
kw.GetWorkceptor().nc.GetLogger().Debug("streaming stdout with reconnect support")
go kw.KubeLoggingWithReconnect(&streamWait, stdout, &stdinErr, &stdoutErr)
} else {
kw.GetWorkceptor().nc.GetLogger().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.GetContext().Err() != context.Canceled {
kw.UpdateBasicStatus(WorkStateFailed, errDetail, stdout.Size())
}
return
}
// only transition from WorkStateRunning to WorkStateSucceeded if WorkStateFailed is set we do not override
if kw.GetContext().Err() != context.Canceled && kw.Status().State == WorkStateRunning {
kw.UpdateBasicStatus(WorkStateSucceeded, "Finished", stdout.Size())
}
}
func IsCompatibleK8S(kw *KubeUnit, versionStr string) bool {
semver, err := version.ParseSemantic(versionStr)
if err != nil {
kw.GetWorkceptor().nc.GetLogger().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 check z stream based on the minor version
// if minor versions < 23, set to high value (e.g. v1.22.9999)
// if minor versions == 23, compare with v1.23.14
// if minor version == 24, compare with v1.24.8
// if minor version == 25, compare with v1.25.4
// if minor versions > 23, compare with low value (e.g. v1.26.0)
var compatibleVer string
switch {
case semver.Minor() == 23:
compatibleVer = "v1.23.14"
case semver.Minor() == 24:
compatibleVer = "v1.24.8"
case semver.Minor() == 25:
compatibleVer = "v1.25.4"
case semver.Minor() > 25:
compatibleVer = fmt.Sprintf("%d.%d.0", semver.Major(), semver.Minor())
default:
compatibleVer = fmt.Sprintf("%d.%d.9999", semver.Major(), semver.Minor())
}
if semver.AtLeast(version.MustParseSemantic(compatibleVer)) {
kw.GetWorkceptor().nc.GetLogger().Debug("Kubernetes version %s is at least %s, using reconnect support", semver, compatibleVer)
return true
}
kw.GetWorkceptor().nc.GetLogger().Debug("Kubernetes version %s not at least %s, not using reconnect support", semver, compatibleVer)
return false
}
func ShouldUseReconnect(kw *KubeUnit) bool {
// Support for streaming from pod with timestamps using reconnect method is in all current versions
// Can override the detection by setting the RECEPTOR_KUBE_SUPPORT_RECONNECT
// accepted values: "enabled", "disabled", "auto". The default is "enabled"
// all invalid values will assume to be "disabled"
version := viper.GetInt("version")
var env string
ok := false
switch version {
case 2:
env = viper.GetString("node.ReceptorKubeSupportReconnect")
if env != "" {
ok = true
}
default:
env, ok = os.LookupEnv("RECEPTOR_KUBE_SUPPORT_RECONNECT")
}
if ok {
switch env {
case "enabled":
return true
case "disabled":
return false
case "auto":
return true
default:
return false
}
}
serverVerInfo, err := kw.clientset.ServerVersion()
if err != nil {
kw.GetWorkceptor().nc.GetLogger().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()