-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathkubernetes.go
1067 lines (966 loc) · 29.2 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 (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strings"
"sync"
"time"
"github.com/ansible/receptor/pkg/logger"
"github.com/ghjm/cmdline"
"github.com/google/shlex"
corev1 "k8s.io/api/core/v1"
"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/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"
)
// 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")
// podRunningAndReady is a completion criterion for pod ready to be attached to.
func podRunningAndReady(event watch.Event) (bool, error) {
if event.Type == watch.Deleted {
return false, errors.NewNotFound(schema.GroupResource{Resource: "pods"}, "")
}
if t, ok := event.Object.(*corev1.Pod); ok {
switch t.Status.Phase {
case corev1.PodFailed, corev1.PodSucceeded:
return false, ErrPodCompleted
case corev1.PodRunning:
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
}
}
}
}
return false, nil
}
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
}
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)
}
ev, err := watch2.UntilWithSync(ctxPodReady, lw, &corev1.Pod{}, nil, podRunningAndReady)
var ok bool
kw.pod, ok = ev.Object.(*corev1.Pod)
if !ok {
return fmt.Errorf("watch did not return a pod")
}
if err == ErrPodCompleted {
if len(kw.pod.Status.ContainerStatuses) != 1 {
return fmt.Errorf("expected 1 container in pod but there were %d", len(kw.pod.Status.ContainerStatuses))
}
cstat := kw.pod.Status.ContainerStatuses[0]
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)
}
return err
} else if err != nil {
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)
}
}
return err
}
if ev == nil {
return fmt.Errorf("pod disappeared during watch")
}
return nil
}
func (kw *kubeUnit) runWorkUsingLogger() {
skipStdin := false
status := kw.Status()
ked := status.ExtraData.(*kubeExtraData)
var err error
var errMsg string
if ked.PodName == "" {
// Create the pod
err := kw.createPod(nil)
if err == ErrPodCompleted {
skipStdin = true
} else if err != nil {
errMsg = fmt.Sprintf("Error creating pod: %s", err)
}
} else {
skipStdin = true
kw.pod, err = kw.clientset.CoreV1().Pods(ked.KubeNamespace).Get(kw.ctx, ked.PodName, metav1.GetOptions{})
if err != nil {
errMsg = fmt.Sprintf("Error getting pod: %s", err)
}
}
if errMsg != "" {
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
logger.Error(errMsg)
return
}
// Open the pod log for stdout
logreq := kw.clientset.CoreV1().Pods(kw.pod.ObjectMeta.Namespace).GetLogs(kw.pod.Name, &corev1.PodLogOptions{
Container: "worker",
Follow: true,
})
logStream, err := logreq.Stream(kw.ctx)
if err != nil {
errMsg := fmt.Sprintf("Error opening pod stream: %s", err)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
logger.Error(errMsg)
return
}
defer logStream.Close()
// Attach stdin stream to the pod
var exec remotecommand.Executor
if !skipStdin {
req := kw.clientset.CoreV1().RESTClient().Post().
Resource("pods").
Name(kw.pod.Name).
Namespace(kw.pod.Namespace).
SubResource("attach")
req.VersionedParams(&corev1.PodExecOptions{
Container: "worker",
Stdin: true,
Stdout: false,
Stderr: false,
TTY: false,
}, scheme.ParameterCodec)
exec, err = remotecommand.NewSPDYExecutor(kw.config, "POST", req.URL())
if err != nil {
kw.UpdateBasicStatus(WorkStateFailed, fmt.Sprintf("Error attaching to pod: %s", err), 0)
return
}
}
// Check if we were cancelled before starting the streams
select {
case <-kw.ctx.Done():
kw.UpdateBasicStatus(WorkStateFailed, "Cancelled", 0)
return
default:
}
// Open stdin reader
var stdin *stdinReader
if !skipStdin {
stdin, err = newStdinReader(kw.UnitDir())
if err != nil {
errMsg := fmt.Sprintf("Error opening stdin file: %s", err)
logger.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
}
// Open stdout writer
stdout, err := newStdoutWriter(kw.UnitDir())
if err != nil {
errMsg := fmt.Sprintf("Error opening stdout file: %s", err)
logger.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
return
}
// Goroutine to update status when stdin is fully sent to the pod, which is when we
// update from WorkStatePending to WorkStateRunning.
finishedChan := make(chan struct{})
if !skipStdin {
kw.UpdateFullStatus(func(status *StatusFileData) {
status.State = WorkStatePending
status.Detail = "Sending stdin to pod"
})
go func() {
select {
case <-kw.ctx.Done():
return
case <-finishedChan:
return
case <-stdin.Done():
err := stdin.Error()
if err == io.EOF {
kw.UpdateBasicStatus(WorkStateRunning, "Pod Running", stdout.Size())
} else {
kw.UpdateBasicStatus(WorkStateFailed, fmt.Sprintf("Error reading stdin: %s", err), stdout.Size())
}
}
}()
}
// Actually run the streams. This blocks until the pod finishes.
var errStdin error
var errStdout error
streamWait := sync.WaitGroup{}
streamWait.Add(2)
if skipStdin {
streamWait.Done()
} else {
go func() {
errStdin = exec.Stream(remotecommand.StreamOptions{
Stdin: stdin,
Tty: false,
})
if errStdin != nil {
logStream.Close()
}
streamWait.Done()
}()
}
go func() {
_, errStdout = io.Copy(stdout, logStream)
streamWait.Done()
}()
streamWait.Wait()
close(finishedChan)
if errStdin != nil || errStdout != nil {
var errDetail string
switch {
case errStdin == nil:
errDetail = fmt.Sprintf("%s", errStdout)
case errStdout == nil:
errDetail = fmt.Sprintf("%s", errStdin)
default:
errDetail = fmt.Sprintf("stdin: %s, stdout: %s", errStdin, errStdout)
}
kw.UpdateBasicStatus(WorkStateFailed, fmt.Sprintf("Stream error running pod: %s", errDetail), stdout.Size())
return
}
kw.UpdateBasicStatus(WorkStateSucceeded, "Finished", stdout.Size())
}
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)
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)
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)
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)
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)
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)
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():
err := stdin.Error()
if err == io.EOF {
kw.UpdateBasicStatus(WorkStateRunning, "Pod Running", stdout.Size())
} else {
kw.UpdateBasicStatus(WorkStateFailed, fmt.Sprintf("Error reading stdin: %s", err), stdout.Size())
cancel()
}
}
}()
// Read stdout from pod
_, err = io.Copy(stdout, conn)
if ctx.Err() != nil {
return
}
if err != nil {
errMsg := fmt.Sprintf("Error reading stdout from pod: %s", err)
logger.Error(errMsg)
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
cancel()
return
}
if ctx.Err() == nil {
kw.UpdateBasicStatus(WorkStateSucceeded, "Finished", stdout.Size())
}
}
func (kw *kubeUnit) connectUsingKubeconfig() error {
var err error
ked := kw.UnredactedStatus().ExtraData.(*kubeExtraData)
if ked.KubeConfig == "" {
clr := clientcmd.NewDefaultClientConfigLoadingRules()
kw.config, err = clientcmd.BuildConfigFromFlags("", clr.GetDefaultFilename())
if ked.KubeNamespace == "" {
c, err := clr.Load()
if err != nil {
return err
}
curContext, ok := c.Contexts[c.CurrentContext]
if ok && curContext != nil {
kw.UpdateFullStatus(func(sfd *StatusFileData) {
sfd.ExtraData.(*kubeExtraData).KubeNamespace = curContext.Namespace
})
} else {
return fmt.Errorf("could not determine namespace")
}
}
} else {
cfg, err := clientcmd.NewClientConfigFromBytes([]byte(ked.KubeConfig))
if err != nil {
return err
}
if ked.KubeNamespace == "" {
namespace, _, err := cfg.Namespace()
if err != nil {
return err
}
kw.UpdateFullStatus(func(sfd *StatusFileData) {
sfd.ExtraData.(*kubeExtraData).KubeNamespace = namespace
})
}
kw.config, err = cfg.ClientConfig()
if err != nil {
return err
}
}
if err != nil {
return err
}
return nil
}
func (kw *kubeUnit) connectUsingIncluster() error {
var err error
kw.config, err = rest.InClusterConfig()
if err != nil {
return err
}
return nil
}
func (kw *kubeUnit) connectToKube() error {
var err error
switch {
case kw.authMethod == "kubeconfig" || kw.authMethod == "runtime":
err = kw.connectUsingKubeconfig()
case kw.authMethod == "incluster":
err = kw.connectUsingIncluster()
default:
return fmt.Errorf("unknown auth method %s", kw.authMethod)
}
if err != nil {
return err
}
kw.clientset, err = kubernetes.NewForConfig(kw.config)
if err != nil {
return err
}
return nil
}
func readFileToString(filename string) (string, error) {
// If filename is "", the function returns ""
if filename == "" {
return "", nil
}
content, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
return string(content), nil
}
// SetFromParams sets the in-memory state from parameters.
//nolint:ifshort // Method to magical for linter
func (kw *kubeUnit) SetFromParams(params map[string]string) error {
ked := kw.status.ExtraData.(*kubeExtraData)
type value struct {
name string
permission bool
setter func(string) error
}
setString := func(target *string) func(string) error {
ssf := func(value string) error {
*target = value
return nil
}
return ssf
}
var err error
ked.KubePod, err = readFileToString(ked.KubePod)
if err != nil {
return fmt.Errorf("could not read pod: %s", err)
}
ked.KubeConfig, err = readFileToString(ked.KubeConfig)
if err != nil {
return fmt.Errorf("could not read kubeconfig: %s", err)
}
userParams := ""
userCommand := ""
userImage := ""
userPod := ""
podPendingTimeoutString := ""
values := []value{
{name: "kube_command", permission: kw.allowRuntimeCommand, setter: setString(&userCommand)},
{name: "kube_image", permission: kw.allowRuntimeCommand, setter: setString(&userImage)},
{name: "kube_params", permission: kw.allowRuntimeParams, setter: setString(&userParams)},
{name: "kube_namespace", permission: kw.allowRuntimeAuth, setter: setString(&ked.KubeNamespace)},
{name: "secret_kube_config", permission: kw.allowRuntimeAuth, setter: setString(&ked.KubeConfig)},
{name: "secret_kube_pod", permission: kw.allowRuntimePod, setter: setString(&userPod)},
{name: "pod_pending_timeout", permission: kw.allowRuntimeParams, setter: setString(&podPendingTimeoutString)},
}
for i := range values {
v := values[i]
value, ok := params[v.name]
if ok && value != "" {
if !v.permission {
return fmt.Errorf("%s provided but not allowed", v.name)
}
err := v.setter(value)
if err != nil {
return fmt.Errorf("error setting value for %s: %s", v.name, err)
}
}
}
if kw.authMethod == "runtime" && ked.KubeConfig == "" {
return fmt.Errorf("param secret_kube_config must be provided if AuthMethod=runtime")
}
if userPod != "" && (userParams != "" || userCommand != "" || userImage != "") {
return fmt.Errorf("params kube_command, kube_image, kube_params not compatible with secret_kube_pod")
}
if podPendingTimeoutString != "" {
podPendingTimeout, err := time.ParseDuration(podPendingTimeoutString)
if err != nil {
logger.Error("Failed to parse pod_pending_timeout -- valid examples include '1.5h', '30m', '30m10s'")
return err
}
kw.podPendingTimeout = podPendingTimeout
}
if userCommand != "" {
ked.Command = userCommand
}
if userImage != "" {
ked.Image = userImage
}
if userPod != "" {
ked.KubePod = userPod
ked.Image = ""
ked.Command = ""
kw.baseParams = ""
} else {
ked.Params = combineParams(kw.baseParams, userParams)
}
return nil
}
// Status returns a copy of the status currently loaded in memory.
func (kw *kubeUnit) Status() *StatusFileData {
status := kw.UnredactedStatus()
ed, ok := status.ExtraData.(*kubeExtraData)
if ok {
ed.KubeConfig = ""
ed.KubePod = ""
}
return status
}
// Status returns a copy of the status currently loaded in memory.
func (kw *kubeUnit) UnredactedStatus() *StatusFileData {
kw.statusLock.RLock()
defer kw.statusLock.RUnlock()
status := kw.getStatus()
ked, ok := kw.status.ExtraData.(*kubeExtraData)
if ok {
kedCopy := *ked
status.ExtraData = &kedCopy
}
return status
}
// startOrRestart is a shared implementation of Start() and Restart().
func (kw *kubeUnit) startOrRestart() error {
// Connect to the Kubernetes API
if err := kw.connectToKube(); err != nil {
return err
}
// Launch runner process
if kw.streamMethod == "tcp" {
go kw.runWorkUsingTCP()
} else {
go kw.runWorkUsingLogger()
}
go kw.monitorLocalStatus()
return nil
}
// Restart resumes monitoring a job after a Receptor restart.
func (kw *kubeUnit) Restart() error {
status := kw.Status()
ked := status.ExtraData.(*kubeExtraData)
if IsComplete(status.State) {
return nil
}
isTCP := kw.streamMethod == "tcp"
if status.State == WorkStateRunning && !isTCP {
return kw.startOrRestart()
}
// Work unit is in Pending state
if kw.deletePodOnRestart {
err := kw.connectToKube()
if err != nil {
logger.Warning("Pod %s could not be deleted: %s", ked.PodName, err.Error())
} else {
err := kw.clientset.CoreV1().Pods(ked.KubeNamespace).Delete(context.Background(), ked.PodName, metav1.DeleteOptions{})
if err != nil {
logger.Warning("Pod %s could not be deleted: %s", ked.PodName, err.Error())
}
}
}
if isTCP {
return fmt.Errorf("restart not implemented for streammethod tcp")
}
return fmt.Errorf("work unit is not in running state, cannot be restarted")
}
// Start launches a job with given parameters.
func (kw *kubeUnit) Start() error {
kw.UpdateBasicStatus(WorkStatePending, "Connecting to Kubernetes", 0)
return kw.startOrRestart()
}
// Cancel releases resources associated with a job, including cancelling it if running.
func (kw *kubeUnit) Cancel() error {
kw.cancel()
if kw.pod != nil {
err := kw.clientset.CoreV1().Pods(kw.pod.Namespace).Delete(context.Background(), kw.pod.Name, metav1.DeleteOptions{})
if err != nil {
logger.Error("Error deleting pod %s: %s", kw.pod.Name, err)
}
}
if kw.cancel != nil {
kw.cancel()
}
return nil
}
// Release releases resources associated with a job. Implies Cancel.
func (kw *kubeUnit) Release(force bool) error {
err := kw.Cancel()
if err != nil && !force {
return err
}
return kw.BaseWorkUnit.Release(force)
}
// **************************************************************************
// Command line
// **************************************************************************
// workKubeCfg is the cmdline configuration object for a Kubernetes worker plugin.
type workKubeCfg struct {
WorkType string `required:"true" description:"Name for this worker type"`
Namespace string `description:"Kubernetes namespace to create pods in"`
Image string `description:"Container image to use for the worker pod"`
Command string `description:"Command to run in the container (overrides entrypoint)"`
Params string `description:"Command-line parameters to pass to the entrypoint"`
AuthMethod string `description:"One of: kubeconfig, incluster" default:"incluster"`
KubeConfig string `description:"Kubeconfig filename (for authmethod=kubeconfig)"`
Pod string `description:"Pod definition filename, in json or yaml format"`
AllowRuntimeAuth bool `description:"Allow passing API parameters at runtime" default:"false"`
AllowRuntimeCommand bool `description:"Allow specifying image & command at runtime" default:"false"`
AllowRuntimeParams bool `description:"Allow adding command parameters at runtime" default:"false"`
AllowRuntimePod bool `description:"Allow passing Pod at runtime" default:"false"`
DeletePodOnRestart bool `description:"On restart, delete the pod if in pending state" default:"true"`
StreamMethod string `description:"Method for connecting to worker pods: logger or tcp" default:"logger"`
VerifySignature bool `description:"Verify a signed work submission" default:"false"`
}
// newWorker is a factory to produce worker instances.
func (cfg workKubeCfg) newWorker(w *Workceptor, unitID string, workType string) WorkUnit {
ku := &kubeUnit{
BaseWorkUnit: BaseWorkUnit{
status: StatusFileData{
ExtraData: &kubeExtraData{
Image: cfg.Image,
Command: cfg.Command,
KubeNamespace: cfg.Namespace,
KubePod: cfg.Pod,
KubeConfig: cfg.KubeConfig,
},
},
},
authMethod: strings.ToLower(cfg.AuthMethod),
streamMethod: strings.ToLower(cfg.StreamMethod),
baseParams: cfg.Params,
allowRuntimeAuth: cfg.AllowRuntimeAuth,
allowRuntimeCommand: cfg.AllowRuntimeCommand,
allowRuntimeParams: cfg.AllowRuntimeParams,
allowRuntimePod: cfg.AllowRuntimePod,
deletePodOnRestart: cfg.DeletePodOnRestart,
namePrefix: fmt.Sprintf("%s-", strings.ToLower(cfg.WorkType)),
}
ku.BaseWorkUnit.Init(w, unitID, workType)
return ku
}
// Prepare inspects the configuration for validity.
func (cfg workKubeCfg) Prepare() error {
lcAuth := strings.ToLower(cfg.AuthMethod)
if lcAuth != "kubeconfig" && lcAuth != "incluster" && lcAuth != "runtime" {
return fmt.Errorf("invalid AuthMethod: %s", cfg.AuthMethod)
}
if cfg.Namespace == "" && !(lcAuth == "kubeconfig" || cfg.AllowRuntimeAuth) {
return fmt.Errorf("must provide namespace when AuthMethod is not kubeconfig")
}
if cfg.KubeConfig != "" {
if lcAuth != "kubeconfig" {
return fmt.Errorf("can only provide KubeConfig when AuthMethod=kubeconfig")
}
_, err := os.Stat(cfg.KubeConfig)
if err != nil {
return fmt.Errorf("error accessing kubeconfig file: %s", err)
}
}
if cfg.Pod != "" && (cfg.Image != "" || cfg.Command != "" || cfg.Params != "") {
return fmt.Errorf("can only provide Pod when Image, Command, and Params are empty")
}
if cfg.Image == "" && !cfg.AllowRuntimeCommand && !cfg.AllowRuntimePod {
return fmt.Errorf("must specify a container image to run")
}
method := strings.ToLower(cfg.StreamMethod)
if method != "logger" && method != "tcp" {
return fmt.Errorf("stream mode must be logger or tcp")
}
return nil
}
// Run runs the action.
func (cfg workKubeCfg) Run() error {
err := MainInstance.RegisterWorker(cfg.WorkType, cfg.newWorker, cfg.VerifySignature)
return err
}
func init() {
cmdline.RegisterConfigTypeForApp("receptor-workers",
"work-kubernetes", "Run a worker using Kubernetes", workKubeCfg{}, cmdline.Section(workersSection))
}
// Kubernetes allows receptor interfacing with a k8s cluster.
type Kubernetes struct {
// Name for this worker type.
WorkType string `mapstructure:"work-type"`
// Kubernetes namespace to create pods in.
Namespace *string `mapstructure:"namespace"`
// Container image to use for the worker pod.
Image string `mapstructure:"image"`
// Command to run in the container (overrides entrypoint).
Command string `mapstructure:"command"`
// Command-line parameters to pass to the entrypoint.
Params string `mapstructure:"parameters"`
// One of: kubeconfig, incluster.
AuthMethod *string `mapstructure:"auth-method"` // default:"incluster"`
// Kubeconfig filename (for authmethod=kubeconfig).
KubeConfig *string `mapstructure:"kube-config"`
// Pod definition filename, in json or yaml format.
Pod string `mapstructure:"pod"`
// Allow passing API parameters at runtime.
AllowRuntimeAuth bool `mapstructure:"allow-runtime-auth"`
// Allow specifying image & command at runtime.
AllowRuntimeCommand bool `mapstructure:"allow-runtime-command"`
// Allow adding command parameters at runtime.
AllowRuntimeParams bool `mapstructure:"allow-runtime-parameters"`
// Allow passing Pod at runtime.
AllowRuntimePod bool `mapstructure:"allow-runtime-pod"`
// On restart, keep the pod if in pending state instead of deleting it.
KeepPodOnRestart bool `mapstructure:"keep-pod-on-restart"`
// Method for connecting to worker pods: logger or tcp.
StreamMethod *string `mapstructure:"stream-method"`
}
func (k Kubernetes) setup(wc *Workceptor) error {
authMethod := "incluster"
if k.AuthMethod != nil {