/
stateless_actions.go
1172 lines (1025 loc) · 28.1 KB
/
stateless_actions.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
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cli
import (
"errors"
"fmt"
"io"
"io/ioutil"
"strings"
"time"
"github.com/uber/peloton/.gen/peloton/api/v0/task"
"github.com/uber/peloton/.gen/peloton/api/v1alpha/job/stateless"
statelesssvc "github.com/uber/peloton/.gen/peloton/api/v1alpha/job/stateless/svc"
v1alphapeloton "github.com/uber/peloton/.gen/peloton/api/v1alpha/peloton"
v1alphapod "github.com/uber/peloton/.gen/peloton/api/v1alpha/pod"
v1alphaquery "github.com/uber/peloton/.gen/peloton/api/v1alpha/query"
v1alpharespool "github.com/uber/peloton/.gen/peloton/api/v1alpha/respool"
"github.com/uber/peloton/.gen/peloton/private/jobmgrsvc"
jobmgrtask "github.com/uber/peloton/pkg/jobmgr/task"
"github.com/golang/protobuf/ptypes"
"go.uber.org/yarpc/yarpcerrors"
yaml "gopkg.in/yaml.v2"
)
const (
statelessJobSummaryFormatHeader = "ID\tName\tOwner\tState\tCreation Time\tTotal\t" +
"Running\tSucceeded\tFailed\tKilled\t" +
"Workflow Status\tCompleted\tFailed\tCurrent\n"
statelessSummaryFormatBody = "%s\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%s\t%d\t%d\t%d\t\n"
statelessUpdateEventsFormatHeader = "Type\tTimestamp\tState\t\n"
statelessUpdateEventsFormatBody = "%s\t%s\t%s\t\n"
workflowEventsV1AlphaFormatHeader = "Workflow State\tWorkflow Type\tTimestamp\n"
workflowEventsV1AlphaFormatBody = "%s\t%s\t%s\n"
queryPodsFormatHeader = "Pod ID\tName\tState\tContainer Name\tContainer State\tHealthy\tStart Time\tRun Time\t" +
"Host\tMessage\tReason\tTermination Status\t\n"
queryPodsFormatBody = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n"
podListFormatHeader = "Name\tPod ID\tState\tHealthy\tStart Time\t" +
"Host\tMessage\tReason\t\n"
podListFormatBody = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n"
)
// StatelessGetCacheAction get cache of stateless job
func (c *Client) StatelessGetCacheAction(jobID string) error {
resp, err := c.jobmgrClient.GetJobCache(
c.ctx,
&jobmgrsvc.GetJobCacheRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
})
if err != nil {
return err
}
out, err := marshallResponse(defaultResponseFormat, resp)
if err != nil {
return err
}
fmt.Printf("%v\n", string(out))
return nil
}
// StatelessRefreshAction refreshes a job
func (c *Client) StatelessRefreshAction(jobID string) error {
resp, err := c.jobmgrClient.RefreshJob(
c.ctx,
&jobmgrsvc.RefreshJobRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
})
if err != nil {
return err
}
out, err := marshallResponse(defaultResponseFormat, resp)
if err != nil {
return err
}
fmt.Printf("%v\n", string(out))
return nil
}
// StatelessWorkflowPauseAction pauses a workflow
func (c *Client) StatelessWorkflowPauseAction(
jobID string,
entityVersion string,
opaqueData string,
) error {
var opaque *v1alphapeloton.OpaqueData
if len(opaqueData) > 0 {
opaque = &v1alphapeloton.OpaqueData{Data: opaqueData}
}
resp, err := c.statelessClient.PauseJobWorkflow(
c.ctx,
&statelesssvc.PauseJobWorkflowRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: entityVersion},
OpaqueData: opaque,
},
)
if err != nil {
return err
}
fmt.Printf("Workflow paused. New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessWorkflowResumeAction resumes a workflow
func (c *Client) StatelessWorkflowResumeAction(
jobID string,
entityVersion string,
opaqueData string,
) error {
var opaque *v1alphapeloton.OpaqueData
if len(opaqueData) > 0 {
opaque = &v1alphapeloton.OpaqueData{Data: opaqueData}
}
resp, err := c.statelessClient.ResumeJobWorkflow(
c.ctx,
&statelesssvc.ResumeJobWorkflowRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: entityVersion},
OpaqueData: opaque,
},
)
if err != nil {
return err
}
fmt.Printf("Workflow resumed. New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessWorkflowAbortAction aborts a workflow
func (c *Client) StatelessWorkflowAbortAction(
jobID string,
entityVersion string,
opaqueData string,
) error {
var opaque *v1alphapeloton.OpaqueData
if len(opaqueData) > 0 {
opaque = &v1alphapeloton.OpaqueData{Data: opaqueData}
}
resp, err := c.statelessClient.AbortJobWorkflow(
c.ctx,
&statelesssvc.AbortJobWorkflowRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: entityVersion},
OpaqueData: opaque,
},
)
if err != nil {
return err
}
fmt.Printf("Workflow aborted. New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessStopJobAction stops a job
func (c *Client) StatelessStopJobAction(jobID string, entityVersion string) error {
resp, err := c.statelessClient.StopJob(
c.ctx,
&statelesssvc.StopJobRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: entityVersion},
},
)
if err != nil {
return err
}
fmt.Printf("Job stopped. New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessQueryAction queries a job given the spec
func (c *Client) StatelessQueryAction(
labels string,
respoolPath string,
keywords string,
states string,
owner string,
name string,
days uint32,
limit uint32,
maxLimit uint32,
offset uint32,
sortBy string,
sortOrder string) error {
pelotonLabels, err := parseLabels(labels)
if err != nil {
return err
}
orderBy, err := parseOrderBy(sortBy, sortOrder)
if err != nil {
return err
}
spec := &stateless.QuerySpec{
Pagination: &v1alphaquery.PaginationSpec{
Offset: offset,
Limit: limit,
OrderBy: orderBy,
MaxLimit: maxLimit,
},
Labels: pelotonLabels,
Keywords: parseKeyWords(keywords),
JobStates: parseJobStates(states),
Owner: owner,
Name: name,
}
if len(respoolPath) > 0 {
spec.Respool = &v1alpharespool.ResourcePoolPath{
Value: respoolPath,
}
}
if days > 0 {
now := time.Now().UTC()
max, err := ptypes.TimestampProto(now)
if err != nil {
return err
}
min, err := ptypes.TimestampProto(now.AddDate(0, 0, -int(days)))
if err != nil {
return err
}
spec.CreationTimeRange = &v1alphapeloton.TimeRange{Min: min, Max: max}
}
resp, err := c.statelessClient.QueryJobs(c.ctx, &statelesssvc.QueryJobsRequest{
Spec: spec,
})
if err != nil {
return err
}
printStatelessQueryResponse(resp)
tabWriter.Flush()
return nil
}
// StatelessReplaceJobAction updates job by replace its config
func (c *Client) StatelessReplaceJobAction(
jobID string,
spec string,
batchSize uint32,
respoolPath string,
entityVersion string,
override bool,
maxInstanceRetries uint32,
maxTolerableInstanceFailures uint32,
rollbackOnFailure bool,
startPaused bool,
opaqueData string,
inPlace bool,
startPods bool,
) error {
var jobSpec stateless.JobSpec
// read the job configuration
buffer, err := ioutil.ReadFile(spec)
if err != nil {
return fmt.Errorf("unable to open file %s: %v", spec, err)
}
if err := yaml.Unmarshal(buffer, &jobSpec); err != nil {
return fmt.Errorf("unable to parse file %s: %v", spec, err)
}
// fetch the resource pool id
respoolID, err := c.LookupResourcePoolID(respoolPath)
if err != nil {
return err
}
if respoolID == nil {
return fmt.Errorf("unable to find resource pool ID for "+
":%s", respoolPath)
}
// Get the entity version if not provided as input.
// The assumption is that the customer has ensured that
// there is no other ongoing write API request going on.
// In case the entityversion changes between Get and Replace,
// then let the Replace request fail.
if len(entityVersion) == 0 {
getRequest := statelesssvc.GetJobRequest{
JobId: &v1alphapeloton.JobID{
Value: jobID,
},
SummaryOnly: true,
}
getResponse, err := c.statelessClient.GetJob(
c.ctx,
&getRequest)
if err != nil {
return err
}
entityVersion = getResponse.GetSummary().GetStatus().GetVersion().GetValue()
}
// set the resource pool id
jobSpec.RespoolId = &v1alphapeloton.ResourcePoolID{Value: respoolID.GetValue()}
var opaque *v1alphapeloton.OpaqueData
if len(opaqueData) > 0 {
opaque = &v1alphapeloton.OpaqueData{Data: opaqueData}
}
req := &statelesssvc.ReplaceJobRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: entityVersion},
Spec: &jobSpec,
UpdateSpec: &stateless.UpdateSpec{
BatchSize: batchSize,
RollbackOnFailure: rollbackOnFailure,
MaxInstanceRetries: maxInstanceRetries,
MaxTolerableInstanceFailures: maxTolerableInstanceFailures,
StartPaused: startPaused,
InPlace: inPlace,
StartPods: startPods,
},
OpaqueData: opaque,
}
resp, err := c.statelessClient.ReplaceJob(c.ctx, req)
if err != nil {
return err
}
fmt.Printf("New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessRollbackJobAction roll backs a job to an older entity version by
// getting the old configuration, and triggering a replace action
// with the old configiuration.
func (c *Client) StatelessRollbackJobAction(
jobID string,
batchSize uint32,
entityVersion string,
maxInstanceRetries uint32,
maxTolerableInstanceFailures uint32,
startPaused bool,
opaqueData string,
inPlace bool,
startPods bool,
) error {
// First fetch the previous job configuration.
getConfigRequest := statelesssvc.GetJobRequest{
JobId: &v1alphapeloton.JobID{
Value: jobID,
},
Version: &v1alphapeloton.EntityVersion{
Value: entityVersion,
},
}
getConfigResponse, err := c.statelessClient.GetJob(
c.ctx,
&getConfigRequest,
)
if err != nil {
return err
}
jobSpec := getConfigResponse.GetJobInfo().GetSpec()
// Get the latest entity version.
getRequest := statelesssvc.GetJobRequest{
JobId: &v1alphapeloton.JobID{
Value: jobID,
},
SummaryOnly: true,
}
getResponse, err := c.statelessClient.GetJob(
c.ctx,
&getRequest,
)
if err != nil {
return err
}
version := getResponse.GetSummary().GetStatus().GetVersion().GetValue()
jobSpec.Revision = nil
var opaque *v1alphapeloton.OpaqueData
if len(opaqueData) > 0 {
opaque = &v1alphapeloton.OpaqueData{Data: opaqueData}
}
req := &statelesssvc.ReplaceJobRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: version},
Spec: jobSpec,
UpdateSpec: &stateless.UpdateSpec{
BatchSize: batchSize,
RollbackOnFailure: false,
MaxInstanceRetries: maxInstanceRetries,
MaxTolerableInstanceFailures: maxTolerableInstanceFailures,
StartPaused: startPaused,
InPlace: inPlace,
StartPods: startPods,
},
OpaqueData: opaque,
}
resp, err := c.statelessClient.ReplaceJob(c.ctx, req)
if err != nil {
return err
}
fmt.Printf("New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessListJobsAction prints summary of all jobs using the ListJobs API
func (c *Client) StatelessListJobsAction() error {
defer tabWriter.Flush()
stream, err := c.statelessClient.ListJobs(
c.ctx,
&statelesssvc.ListJobsRequest{},
)
if err != nil {
return err
}
fmt.Fprint(tabWriter, statelessJobSummaryFormatHeader)
for {
resp, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
printListJobsResponse(resp)
}
}
// StatelessReplaceJobDiffAction returns the set of instances which will be
// added, removed, updated and remain unchanged for a new
// job specification for a given job
func (c *Client) StatelessReplaceJobDiffAction(
jobID string,
spec string,
entityVersion string,
respoolPath string,
) error {
var jobSpec stateless.JobSpec
// read the job configuration
buffer, err := ioutil.ReadFile(spec)
if err != nil {
return fmt.Errorf("unable to open file %s: %v", spec, err)
}
if err := yaml.Unmarshal(buffer, &jobSpec); err != nil {
return fmt.Errorf("unable to parse file %s: %v", spec, err)
}
// fetch the resource pool id
respoolID, err := c.LookupResourcePoolID(respoolPath)
if err != nil {
return err
}
if respoolID == nil {
return fmt.Errorf("unable to find resource pool ID for "+
":%s", respoolPath)
}
// set the resource pool id
jobSpec.RespoolId = &v1alphapeloton.ResourcePoolID{Value: respoolID.GetValue()}
req := &statelesssvc.GetReplaceJobDiffRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Spec: &jobSpec,
Version: &v1alphapeloton.EntityVersion{Value: entityVersion},
}
resp, err := c.statelessClient.GetReplaceJobDiff(c.ctx, req)
if err != nil {
return err
}
printResponseJSON(resp)
return nil
}
// StatelessCreateAction is the action for creating a stateless job
func (c *Client) StatelessCreateAction(
jobID string,
respoolPath string,
batchSize uint32,
cfg string,
secretPath string,
secret []byte,
opaque string,
startPaused bool,
maxInstanceRetries uint32,
maxTolerableInstanceFailures uint32,
) error {
respoolID, err := c.LookupResourcePoolID(respoolPath)
if err != nil {
return err
}
if respoolID == nil {
return fmt.Errorf("unable to find resource pool ID for "+
":%s", respoolPath)
}
var jobSpec stateless.JobSpec
buffer, err := ioutil.ReadFile(cfg)
if err != nil {
return fmt.Errorf("unable to open file %s: %v", cfg, err)
}
if err := yaml.Unmarshal(buffer, &jobSpec); err != nil {
return fmt.Errorf("unable to parse file %s: %v", cfg, err)
}
jobSpec.RespoolId = &v1alphapeloton.ResourcePoolID{Value: respoolID.GetValue()}
var opaqueData *v1alphapeloton.OpaqueData
if len(opaque) != 0 {
opaqueData = &v1alphapeloton.OpaqueData{
Data: opaque,
}
}
var request = &statelesssvc.CreateJobRequest{
JobId: &v1alphapeloton.JobID{
Value: jobID,
},
Spec: &jobSpec,
OpaqueData: opaqueData,
CreateSpec: &stateless.CreateSpec{
BatchSize: batchSize,
MaxInstanceRetries: maxInstanceRetries,
MaxTolerableInstanceFailures: maxTolerableInstanceFailures,
StartPaused: startPaused,
},
}
// handle secrets
if secretPath != "" && len(secret) > 0 {
request.Secrets = []*v1alphapeloton.Secret{
jobmgrtask.CreateV1AlphaSecretProto("", secretPath, secret),
}
}
response, err := c.statelessClient.CreateJob(c.ctx, request)
printStatelessJobCreateResponse(request, response, err, c.Debug)
return err
}
// StatelessGetAction is the action for getting status
// and spec (or only summary) of a stateless job
func (c *Client) StatelessGetAction(
jobID string,
version string,
summaryOnly bool,
) error {
request := statelesssvc.GetJobRequest{
JobId: &v1alphapeloton.JobID{
Value: jobID,
},
SummaryOnly: summaryOnly,
}
if version != "" {
request.Version = &v1alphapeloton.EntityVersion{
Value: version,
}
}
resp, err := c.statelessClient.GetJob(
c.ctx,
&request)
if err != nil {
return err
}
out, err := marshallResponse(defaultResponseFormat, resp)
if err != nil {
return err
}
fmt.Printf("%v\n", string(out))
return nil
}
// StatelessQueryPodsAction is the action for querying pods of a job
func (c *Client) StatelessQueryPodsAction(
jobID string,
states string,
names string,
hosts string,
limit uint32,
offset uint32,
sortBy string,
sortOrder string,
) error {
var podStates []v1alphapod.PodState
var podNames []*v1alphapeloton.PodName
var podHosts []string
for _, k := range strings.Split(states, labelSeparator) {
if k != "" {
p, ok := v1alphapod.PodState_value[k]
if !ok {
return yarpcerrors.InvalidArgumentErrorf("invalid pod state %s", k)
}
podStates = append(podStates, v1alphapod.PodState(p))
}
}
for _, host := range strings.Split(hosts, labelSeparator) {
if host != "" {
podHosts = append(podHosts, host)
}
}
for _, name := range strings.Split(names, labelSeparator) {
if name != "" {
podNames = append(podNames, &v1alphapeloton.PodName{Value: name})
}
}
order := v1alphaquery.OrderBy_ORDER_BY_DESC
if sortOrder == "ASC" {
order = v1alphaquery.OrderBy_ORDER_BY_ASC
} else if sortOrder != "DESC" {
return yarpcerrors.InvalidArgumentErrorf("Invalid sort order " + sortOrder)
}
var sort []*v1alphaquery.OrderBy
for _, s := range strings.Split(sortBy, labelSeparator) {
if s != "" {
propertyPath := &v1alphaquery.PropertyPath{
Value: s,
}
sort = append(sort, &v1alphaquery.OrderBy{
Order: order,
Property: propertyPath,
})
}
}
var request = &statelesssvc.QueryPodsRequest{
JobId: &v1alphapeloton.JobID{
Value: jobID,
},
Spec: &v1alphapod.QuerySpec{
PodStates: podStates,
Names: podNames,
Hosts: podHosts,
Pagination: &v1alphaquery.PaginationSpec{
Limit: limit,
Offset: offset,
OrderBy: sort,
},
},
Pagination: &v1alphaquery.PaginationSpec{
Limit: limit,
Offset: offset,
OrderBy: sort,
},
}
response, err := c.statelessClient.QueryPods(c.ctx, request)
printQueryPodsResponse(response, err, c.Debug)
return err
}
// StatelessListPodsAction is the action to list pods in a job
func (c *Client) StatelessListPodsAction(
jobID string,
instanceRange *task.InstanceRange,
) error {
defer tabWriter.Flush()
idInstanceRange := &v1alphapod.InstanceIDRange{
From: instanceRange.GetFrom(),
To: instanceRange.GetTo(),
}
stream, err := c.statelessClient.ListPods(
c.ctx,
&statelesssvc.ListPodsRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Range: idInstanceRange,
},
)
if err != nil {
return err
}
fmt.Fprint(tabWriter, queryPodsFormatHeader)
for {
resp, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
printStatelessListPodsResponse(resp)
}
}
func printStatelessListPodsResponse(resp *statelesssvc.ListPodsResponse) {
for _, pod := range resp.GetPods() {
printPod(pod.GetStatus(), pod.GetPodName())
}
}
// StatelessStartJobAction is the action for starting a stateless job
func (c *Client) StatelessStartJobAction(
jobID string,
entityVersion string,
) error {
request := statelesssvc.StartJobRequest{
JobId: &v1alphapeloton.JobID{
Value: jobID,
},
Version: &v1alphapeloton.EntityVersion{
Value: entityVersion,
},
}
resp, err := c.statelessClient.StartJob(
c.ctx,
&request)
if err != nil {
return err
}
fmt.Printf("Job started. New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessDeleteAction is the action for deleting a stateless job
func (c *Client) StatelessDeleteAction(
jobID string,
version string,
forceDelete bool,
) error {
_, err := c.statelessClient.DeleteJob(
c.ctx,
&statelesssvc.DeleteJobRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: version},
Force: forceDelete,
},
)
if err != nil {
return err
}
fmt.Printf("Job deleted\n")
return nil
}
func printStatelessQueryResponse(resp *statelesssvc.QueryJobsResponse) {
results := resp.GetRecords()
if len(results) == 0 {
fmt.Fprintf(tabWriter, "No results found\n")
return
}
fmt.Fprint(tabWriter, statelessJobSummaryFormatHeader)
for _, r := range results {
printStatelessQueryResult(r)
}
}
func printStatelessQueryResult(j *stateless.JobSummary) {
creationTime, err := time.Parse(time.RFC3339Nano, j.GetStatus().GetCreationTime())
creationTimeStr := ""
if err == nil {
creationTimeStr = creationTime.Format(time.RFC3339)
}
fmt.Fprintf(
tabWriter,
statelessSummaryFormatBody,
j.GetJobId().GetValue(),
j.GetName(),
j.GetOwningTeam(),
j.GetStatus().GetState().String(),
creationTimeStr,
j.GetInstanceCount(),
j.GetStatus().GetPodStats()["POD_STATE_RUNNING"],
j.GetStatus().GetPodStats()["POD_STATE_SUCCEEDED"],
j.GetStatus().GetPodStats()["POD_STATE_FAILED"],
j.GetStatus().GetPodStats()["POD_STATE_KILLED"],
j.GetStatus().GetWorkflowStatus().GetState().String(),
j.GetStatus().GetWorkflowStatus().GetNumInstancesCompleted(),
j.GetStatus().GetWorkflowStatus().GetNumInstancesFailed(),
len(j.GetStatus().GetWorkflowStatus().GetInstancesCurrent()),
)
}
func parseLabels(labels string) ([]*v1alphapeloton.Label, error) {
var pelotonLabels []*v1alphapeloton.Label
if len(labels) == 0 {
return nil, nil
}
for _, l := range strings.Split(labels, labelSeparator) {
labelVals := strings.Split(l, keyValSeparator)
if len(labelVals) != 2 {
return nil, errors.New("Invalid label" + l)
}
pelotonLabels = append(pelotonLabels, &v1alphapeloton.Label{
Key: labelVals[0],
Value: labelVals[1],
})
}
return pelotonLabels, nil
}
func parseKeyWords(keywords string) []string {
if len(keywords) == 0 {
return nil
}
var pelotonKeyWords []string
for _, k := range strings.Split(keywords, labelSeparator) {
if k != "" {
pelotonKeyWords = append(pelotonKeyWords, k)
}
}
return pelotonKeyWords
}
func parseJobStates(states string) []stateless.JobState {
if len(states) == 0 {
return nil
}
var pelotonStates []stateless.JobState
for _, k := range strings.Split(states, labelSeparator) {
if k != "" {
pelotonStates = append(pelotonStates, stateless.JobState(stateless.JobState_value[k]))
}
}
return pelotonStates
}
func parseOrderBy(sortBy string, sortOrder string) ([]*v1alphaquery.OrderBy, error) {
if len(sortBy) == 0 || len(sortOrder) == 0 {
return nil, nil
}
order := v1alphaquery.OrderBy_ORDER_BY_DESC
if sortOrder == "ASC" {
order = v1alphaquery.OrderBy_ORDER_BY_ASC
} else if sortOrder != "DESC" {
return nil, errors.New("Invalid sort order " + sortOrder)
}
var sort []*v1alphaquery.OrderBy
for _, s := range strings.Split(sortBy, labelSeparator) {
if s != "" {
propertyPath := &v1alphaquery.PropertyPath{
Value: s,
}
sort = append(sort, &v1alphaquery.OrderBy{
Order: order,
Property: propertyPath,
})
}
}
return sort, nil
}
func printStatelessJobCreateResponse(
req *statelesssvc.CreateJobRequest,
resp *statelesssvc.CreateJobResponse,
err error,
jsonFormat bool,
) {
defer tabWriter.Flush()
if jsonFormat {
printResponseJSON(resp)
} else {
if err != nil {
if yarpcerrors.IsAlreadyExists(err) {
fmt.Fprintf(tabWriter, "Job %s already exists: %s\n",
req.GetJobId(), err.Error())
} else if yarpcerrors.IsInvalidArgument(err) {
fmt.Fprintf(tabWriter, "Invalid job spec: %s\n",
err.Error())
}
} else if resp.GetJobId() != nil {
fmt.Fprintf(
tabWriter,
"Job %s created. Entity Version: %s\n",
resp.GetJobId().GetValue(),
resp.GetVersion().GetValue(),
)
} else {
fmt.Fprint(tabWriter, "Missing job ID in job create response\n")
}
}
}
func printListJobsResponse(resp *statelesssvc.ListJobsResponse) {
jobs := resp.GetJobs()
for _, r := range jobs {
printStatelessQueryResult(r)
}
}
// StatelessRestartJobAction restarts a job
func (c *Client) StatelessRestartJobAction(
jobID string,
batchSize uint32,
entityVersion string,
instanceRanges []*task.InstanceRange,
opaqueData string,
inPlace bool,
) error {
var opaque *v1alphapeloton.OpaqueData
if len(opaqueData) > 0 {
opaque = &v1alphapeloton.OpaqueData{Data: opaqueData}
}
var idInstanceRanges []*v1alphapod.InstanceIDRange
for _, instanceRange := range instanceRanges {
idInstanceRanges = append(idInstanceRanges, &v1alphapod.InstanceIDRange{
From: instanceRange.GetFrom(),
To: instanceRange.GetTo(),
})
}
req := &statelesssvc.RestartJobRequest{
JobId: &v1alphapeloton.JobID{Value: jobID},
Version: &v1alphapeloton.EntityVersion{Value: entityVersion},
RestartSpec: &stateless.RestartSpec{
BatchSize: batchSize,
Ranges: idInstanceRanges,
InPlace: inPlace,
},
OpaqueData: opaque,
}
resp, err := c.statelessClient.RestartJob(c.ctx, req)
if err != nil {
return err
}
fmt.Printf("Job restarted. New EntityVersion: %s\n", resp.GetVersion().GetValue())
return nil
}
// StatelessListUpdatesAction lists updates of a job
func (c *Client) StatelessListUpdatesAction(
jobID string,