-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathkubernetes.go
More file actions
2063 lines (1789 loc) · 64.6 KB
/
kubernetes.go
File metadata and controls
2063 lines (1789 loc) · 64.6 KB
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"
"math"
"net"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/ghjm/cmdline"
"github.com/google/shlex"
"github.com/spf13/viper"
batchv1 "k8s.io/api/batch/v1"
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
KubeAPIWrapperInstance KubeAPIer
authMethod string
streamMethod string
baseParams string
allowRuntimeAuth bool
allowRuntimeCommand bool
allowRuntimeParams bool
allowRuntimePod bool
deletePodOnRestart bool
namePrefix string
config *rest.Config
clientset kubernetes.Interface
Pod *corev1.Pod
Job *batchv1.Job
isJobSpec bool
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.Interface, error)
GetLogs(kubernetes.Interface, string, string, *corev1.PodLogOptions) *rest.Request
Get(context.Context, kubernetes.Interface, string, string, metav1.GetOptions) (*corev1.Pod, error)
Create(context.Context, kubernetes.Interface, string, *corev1.Pod, metav1.CreateOptions) (*corev1.Pod, error)
List(context.Context, kubernetes.Interface, string, metav1.ListOptions) (*corev1.PodList, error)
Watch(context.Context, kubernetes.Interface, string, metav1.ListOptions) (watch.Interface, error)
Delete(context.Context, kubernetes.Interface, string, string, metav1.DeleteOptions) error
CreateJob(context.Context, kubernetes.Interface, string, *batchv1.Job, metav1.CreateOptions) (*batchv1.Job, error)
GetJob(context.Context, kubernetes.Interface, string, string, metav1.GetOptions) (*batchv1.Job, error)
DeleteJob(context.Context, kubernetes.Interface, string, string, metav1.DeleteOptions) error
SubResource(kubernetes.Interface, 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.Interface, error) {
return kubernetes.NewForConfig(c)
}
func (ku KubeAPIWrapper) GetLogs(clientset kubernetes.Interface, 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.Interface, 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.Interface, 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.Interface, 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.Interface, 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.Interface, namespace string, name string, opts metav1.DeleteOptions) error {
return clientset.CoreV1().Pods(namespace).Delete(ctx, name, opts)
}
func (ku KubeAPIWrapper) CreateJob(ctx context.Context, clientset kubernetes.Interface, namespace string, job *batchv1.Job, opts metav1.CreateOptions) (*batchv1.Job, error) {
return clientset.BatchV1().Jobs(namespace).Create(ctx, job, opts)
}
func (ku KubeAPIWrapper) GetJob(ctx context.Context, clientset kubernetes.Interface, namespace string, name string, opts metav1.GetOptions) (*batchv1.Job, error) {
return clientset.BatchV1().Jobs(namespace).Get(ctx, name, opts)
}
func (ku KubeAPIWrapper) DeleteJob(ctx context.Context, clientset kubernetes.Interface, namespace string, name string, opts metav1.DeleteOptions) error {
return clientset.BatchV1().Jobs(namespace).Delete(ctx, name, opts)
}
func (ku KubeAPIWrapper) SubResource(clientset kubernetes.Interface, 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()
}
// 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")
const WorkerContainerName = "worker"
// podRunningAndReady is a completion criterion for pod ready to be attached to.
func podRunningAndReady(kw KubeUnit) func(event watch.Event) (bool, error) {
imagePullBackOffRetries := 3
inner := func(event watch.Event) (bool, error) {
if event.Type == watch.Deleted {
return false, kw.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 (kw *KubeUnit) waitForJobPod() error {
jobName := kw.Job.Name
namespace := kw.Job.Namespace
for i := 0; i < 60; i++ {
pods, err := kw.KubeAPIWrapperInstance.List(kw.GetContext(), kw.clientset, namespace, metav1.ListOptions{
LabelSelector: fmt.Sprintf("job-name=%s", jobName),
})
if err != nil {
return fmt.Errorf("failed to list pods for job %s: %w", jobName, err)
}
if len(pods.Items) > 0 {
kw.Pod = &pods.Items[0]
kw.UpdateFullStatus(func(status *StatusFileData) {
status.State = WorkStatePending
status.Detail = "Job created, pod found"
status.StdoutSize = 0
status.ExtraData.(*KubeExtraData).PodName = kw.Pod.Name
})
return nil
}
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("job %s did not create any pods within 30 seconds", jobName)
}
func (kw *KubeUnit) validateAndSetupWorkerContainer(spec *corev1.PodSpec) error {
foundWorker := false
for i := range spec.Containers {
if spec.Containers[i].Name == WorkerContainerName {
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
return nil
}
func (kw *KubeUnit) extractMetadata(objectMeta *metav1.ObjectMeta, ked *KubeExtraData) {
if objectMeta.Namespace != "" {
ked.KubeNamespace = objectMeta.Namespace
}
if objectMeta.Name != "" {
kw.namePrefix = objectMeta.Name + "-"
}
}
func (kw *KubeUnit) GetKubeTimeoutStart() time.Duration {
// RECEPTOR_KUBE_TIMEOUT_START
// default: 1 second
kubeTimeoutStart := 1 * time.Second
envTimeout := os.Getenv("RECEPTOR_KUBE_TIMEOUT_START")
if envTimeout != "" {
var err error
kubeTimeoutStart, err = time.ParseDuration(envTimeout)
if err != nil || kubeTimeoutStart <= 0 {
// ignore error, use default
kw.GetWorkceptor().nc.GetLogger().Warning("Invalid value for RECEPTOR_KUBE_TIMEOUT_START: %s. Ignoring", envTimeout)
kubeTimeoutStart = 1 * time.Second
}
// ignore if exceeds limit, use max
if kubeTimeoutStart > time.Minute*1 {
kw.GetWorkceptor().nc.GetLogger().Warning("RECEPTOR_KUBE_TIMEOUT_START of: %d is larger than the max timeout of 1m. Max of 1m will be used", kubeTimeoutStart)
kubeTimeoutStart = time.Minute * 1
}
}
kw.GetWorkceptor().nc.GetLogger().Debug("RECEPTOR_KUBE_TIMEOUT_START: %s", kubeTimeoutStart)
return kubeTimeoutStart
}
func (kw *KubeUnit) GetKubeRetryCount() int {
// RECEPTOR_KUBE_RETRY_COUNT
// default: 5
kubeRetryCount := 5
envRetryCount := os.Getenv("RECEPTOR_KUBE_RETRY_COUNT")
if envRetryCount != "" {
var err error
kubeRetryCount, err = strconv.Atoi(envRetryCount)
if err != nil || kubeRetryCount < 1 {
// ignore error, use default
kw.GetWorkceptor().nc.GetLogger().Warning("Invalid value for RECEPTOR_KUBE_RETRY_COUNT: %s. Default of 5 will be used", envRetryCount)
kubeRetryCount = 5
}
// ignore if exceeds limit, use max retry
if kubeRetryCount > 100 {
kw.GetWorkceptor().nc.GetLogger().Warning("RECEPTOR_KUBE_RETRY_COUNT of: %d is larger than the max retry count of 100. Retry count of 100 will be used", kubeRetryCount)
kubeRetryCount = 100
}
}
kw.GetWorkceptor().nc.GetLogger().Debug("RECEPTOR_KUBE_RETRY_COUNT: %d", kubeRetryCount)
return kubeRetryCount
}
func (kw *KubeUnit) GetSleepDuration(multipler int) time.Duration {
maxSleepDuration := time.Minute * 5
baseTimeout := int64(kw.GetKubeTimeoutStart())
if baseTimeout > 0 && int64(multipler) > math.MaxInt64/baseTimeout {
return maxSleepDuration
}
sleepDuration := kw.GetKubeTimeoutStart() * time.Duration(multipler)
if sleepDuration > maxSleepDuration {
return maxSleepDuration
}
return sleepDuration
}
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: WorkerContainerName,
Follow: true,
}
if timestamps {
podOptions.Timestamps = true
podOptions.SinceTime = &metav1.Time{Time: sinceTime}
}
logReq := kw.KubeAPIWrapperInstance.GetLogs(kw.clientset, podNamespace, podName, podOptions)
// get logstream, with retry
for retries := kw.GetKubeRetryCount(); 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(kw.GetKubeTimeoutStart())
}
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
var retryGetLogStream int
var successfulWrite bool
podNamespace := kw.Pod.Namespace
podName := kw.Pod.Name
retries := kw.GetKubeRetryCount()
prevDelay, curDelay := 0, 1
prevPodDelay, curPodDelay := 0, 1
prevContainerDelay, curContainerDelay := 0, 1
retryGetLogStream = retries
mainLoop:
for {
if *stdinErr != nil {
// fail to send stdin to pod, no need to continue
return
}
// get pod, with retry
for retryGetPod := retries; retryGetPod > 0; retryGetPod-- {
kw.Pod, err = kw.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,
retryGetPod,
err,
)
time.Sleep(kw.GetSleepDuration(curPodDelay))
prevPodDelay, curPodDelay = curPodDelay, prevPodDelay+curPodDelay
}
if err != nil {
errMsg := fmt.Errorf("Error getting pod %s/%s. Error: %s", podNamespace, podName, err)
kw.GetWorkceptor().nc.GetLogger().Error("%s", errMsg.Error())
*stdoutErr = errMsg
// fail to get pod, no need to continue
return
}
prevPodDelay, curPodDelay = 1, 1
// Reset successfulWrite on each reconnection attempt to ensure proper duplicate detection
successfulWrite = false
logStream, err := kw.kubeLoggingConnectionHandler(true, sinceTime)
if err != nil {
// fail to get log stream, no need to continue
return
}
defer logStream.Close()
// read from logstream
streamReader := bufio.NewReader(logStream)
for { // check between every line read to see if we need to stop reading
line, err := streamReader.ReadString('\n')
if err != nil {
// Check if the context was canceled and the work state isn't "Succeeded".
// If so, set the error and mark the job as failed.
if kw.GetContext().Err() == context.Canceled {
if kw.Status().State != WorkStateSucceeded &&
kw.Status().State != WorkStateFailed &&
kw.Status().State != WorkStateCanceled {
errMsg := fmt.Sprintf("Context was canceled while reading logs for pod %s/%s. This is unrecoverable. Marking the job as failed and exiting. Error: %s",
podNamespace,
podName,
err.Error(),
)
*stdoutErr = fmt.Errorf("%s", errMsg)
kw.GetWorkceptor().nc.GetLogger().Error("%s", errMsg)
}
return
}
// Check if the error is not EOF, if error is not EOF retry 5 times if error persists set error and mark the job as failed.
if err != io.EOF {
retryGetLogStream--
if retryGetLogStream > 0 {
kw.GetWorkceptor().nc.GetLogger().Info(
"Detected non-EOF Error: %s for pod %s/%s. Will retry %d more times.",
err,
podNamespace,
podName,
retryGetLogStream,
)
time.Sleep(kw.GetSleepDuration(curDelay))
prevDelay, curDelay = curDelay, prevDelay+curDelay
continue mainLoop
}
*stdoutErr = err
kw.GetWorkceptor().nc.GetLogger().Error(
"Unexpected non-EOF error while reading logs for pod %s/%s, retries exhausted. Error: %s",
podNamespace,
podName,
err.Error(),
)
return
}
// EOF errors are expected in two cases.
// 1. When the job is finished and the last line is sent.
// In this case we monitor the container status to ensure we move out of Running,
// and we make sure we get the last line of output.
// 2. When the job lasts longer than 4 hours and kube api closes the log stream.
// This is a recoverable EOF, so we attempt to reconnect with a back-off.
// In BOTH cases, we have a simular approach, wait 1-2 seconds and check if the container status has changed.
podDetails, kubeErr := kw.KubeAPIWrapperInstance.Get(kw.GetContext(), kw.clientset, podNamespace, podName, metav1.GetOptions{})
if kubeErr != nil {
// There are many reasons why the kube api might not be able to get the pod,
// This does not mean there is a problem just yet.
// Let's try to get the pod again, max 5 times, and decide.
kw.GetWorkceptor().nc.GetLogger().Info("Error getting pod after reading stream: '%s' , continuing try to get pod up to 5 more times.", kubeErr)
continue mainLoop
}
var containerState corev1.ContainerState
foundContainer := false
for _, containerStatus := range podDetails.Status.ContainerStatuses {
if containerStatus.Name == WorkerContainerName {
containerState = containerStatus.State
foundContainer = true
}
}
if !foundContainer {
kw.GetWorkceptor().nc.GetLogger().Error("Unable to find the container %s for pod %s. This is unrecoverable. Marking the job as failed and exiting", WorkerContainerName, podName)
*stdoutErr = fmt.Errorf("unable to find the container %s for pod %s. This is unrecoverable. Marking the job as failed and exiting", WorkerContainerName, podName)
return
}
switch {
case containerState.Running != nil:
// We got EOF but pod is running, is this because we checked too fast? Will it turn into a terminated state soon or are we hitting the 4 hour log stream kube error. We will attempt to reconnect a max of 5 times in order to cover both cases
// If we can't get reconnect without an EOF we will error and mark the job as failed.
retryGetLogStream--
if retryGetLogStream > 0 {
kw.GetWorkceptor().nc.GetLogger().Info(
"Detected EOF Error: %s for pod %s/%s in with container state: Running. Job may not be complete. Will retry %d more times.",
err,
podNamespace,
podName,
retryGetLogStream,
)
time.Sleep(kw.GetSleepDuration(curContainerDelay))
prevContainerDelay, curContainerDelay = curContainerDelay, prevContainerDelay+curContainerDelay
continue mainLoop
}
// Retrying hasn't worked we will error and mark the job as failed
kw.GetWorkceptor().nc.GetLogger().Error("Container in %s pod is running but is continuing to stream EOF after retries exhausted", WorkerContainerName)
*stdoutErr = fmt.Errorf("detected Error: %s for pod %s/%s. Pod is running but is continuing to stream EOF after retries exhausted", err,
podNamespace,
podName,
)
return
case containerState.Terminated != nil:
// We got EOF and the pod terminated, we will log the terminated information
if containerState.Terminated.ExitCode != 0 {
kw.GetWorkceptor().nc.GetLogger().Info("Container in %s pod has terminated, with nonzero exit code: %v, terminated reason: %v and terminated message: %v", WorkerContainerName, containerState.Terminated.ExitCode, containerState.Terminated.Reason, containerState.Terminated.Message)
}
// We need to check if last line has data
if line != "" {
msg, _, _ := kw.ProcessLogLine(line, sinceTime, successfulWrite)
if msg != "" {
_, err = stdout.Write([]byte(msg + "\n"))
if err != nil {
*stdoutErr = fmt.Errorf("error writing last line to stdout: %s", err)
kw.GetWorkceptor().nc.GetLogger().Error("Error writing last line to stdout: %s", err)
return
}
}
}
// Got EOF, terminated and ensured we captured last line then return
return
default:
// We dont expect to ever get here, However, beinging in an unknown state will not have a negative effect so we will log and ignore.
kw.GetWorkceptor().nc.GetLogger().Debug("%s is in an unexpected container state %s. This is unexpected. We will continue.", podName, containerState)
}
// Something has gone very wrong if we are here. EOF is true and we can get the container state, but it is not running or terminated.
// At this stage something has gone very wrong with our interactions with the container.
// We will fail, and mark the job as failed due to an unknown kube container state.
kw.GetWorkceptor().nc.GetLogger().Error("received EOF on log stream for pod %s and container state is not valid %s, failing and marking the job as failed", podName, containerState)
*stdoutErr = fmt.Errorf("received EOF on log stream for pod %s and container state is not valid %s, failing and marking the job as failed", podName, containerState)
return
}
msg, newSinceTime, shouldSkip := kw.ProcessLogLine(line, sinceTime, successfulWrite)
sinceTime = newSinceTime
// shouldSkip is a variable that is used to represent if a line has already be read from the container, if true we already have the line, move to the next iteration
if shouldSkip {
continue
}
_, 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
}
// Set successfulWrite = true after writing to stdout to track that we've successfully written during this connection session
successfulWrite = true
retryGetLogStream = retries
}
}
}
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
// Try Job first
job := &batchv1.Job{}
_, _, err := decode([]byte(ked.KubePod), nil, job)
if err == nil && job.Kind == "Job" {
kw.isJobSpec = true
spec = &job.Spec.Template.Spec
kw.extractMetadata(&job.ObjectMeta, ked)
err = kw.validateAndSetupWorkerContainer(spec)
if err != nil {
return err
}
// Create Job
job.ObjectMeta.Name = ""
job.ObjectMeta.GenerateName = kw.namePrefix
job.ObjectMeta.Namespace = ked.KubeNamespace
kw.Job, err = kw.KubeAPIWrapperInstance.CreateJob(kw.GetContext(), kw.clientset, ked.KubeNamespace, job, metav1.CreateOptions{})
if err != nil {
return err
}
// Wait for Job to create Pod
err = kw.waitForJobPod()
if err != nil {
return err
}
} else {
// Fall back to Pod spec
_, _, err := decode([]byte(ked.KubePod), nil, pod)
if err != nil {
return err
}
spec = &pod.Spec
kw.extractMetadata(&pod.ObjectMeta, ked)
err = kw.validateAndSetupWorkerContainer(spec)
if err != nil {
return err
}
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: WorkerContainerName,
Image: ked.Image,
Command: command,
Args: params,
Stdin: true,
StdinOnce: true,
TTY: false,
}},
RestartPolicy: corev1.RestartPolicyNever,
}
}
// Only create Pod directly if it's not a Job spec (Job already created Pod)
if !kw.isJobSpec {
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.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
fieldSelector := kw.KubeAPIWrapperInstance.OneTermEqualSelector("metadata.name", kw.Pod.Name).String()
lw := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = fieldSelector
return kw.KubeAPIWrapperInstance.List(kw.GetContext(), kw.clientset, ked.KubeNamespace, options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = fieldSelector
return kw.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)
ev, err := kw.KubeAPIWrapperInstance.UntilWithSync(ctxPodReady, lw, &corev1.Pod{}, nil, podRunningAndReady(*kw))
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 == WorkerContainerName {
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 == WorkerContainerName {
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
}
// runWorkUsingLogger is a private wrapper that calls the public RunWorkUsingLogger method.
// This maintains backward compatibility while enabling direct testing.
func (kw *KubeUnit) runWorkUsingLogger() {
kw.RunWorkUsingLogger()
}
// RunWorkUsingLogger orchestrates the complete workflow for running work in a Kubernetes pod
// using logger-based streaming. This method is exposed publicly to enable comprehensive testing
// of the complex pod lifecycle, stdin/stdout streaming, and error handling logic.
//
// The method handles:
// - Creating new pods or resuming existing ones
// - Setting up SPDY executors for stdin streaming
// - Managing goroutines for stdin/stdout coordination
// - Error propagation and status transitions
// - Proper cleanup and resource management.
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 = kw.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 := kw.KubeAPIWrapperInstance.SubResource(kw.clientset, podName, podNamespace)
req.VersionedParams(
&corev1.PodExecOptions{
Container: WorkerContainerName,
Stdin: true,
Stdout: false,
Stderr: false,
TTY: false,
},
scheme.ParameterCodec,
)
var err error
exec, err = kw.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