forked from cadence-workflow/cadence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workflowCommands.go
2006 lines (1795 loc) · 61.9 KB
/
workflowCommands.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) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cli
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/olekukonko/tablewriter"
"github.com/pborman/uuid"
"github.com/urfave/cli"
"github.com/valyala/fastjson"
s "go.uber.org/cadence/.gen/go/shared"
"go.uber.org/cadence/client"
"github.com/uber/cadence/.gen/go/cadence/workflowserviceclient"
"github.com/uber/cadence/.gen/go/shared"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/clock"
"github.com/uber/cadence/service/history"
)
// ShowHistory shows the history of given workflow execution based on workflowID and runID.
func ShowHistory(c *cli.Context) {
wid := getRequiredOption(c, FlagWorkflowID)
rid := c.String(FlagRunID)
showHistoryHelper(c, wid, rid)
}
// ShowHistoryWithWID shows the history of given workflow with workflow_id
func ShowHistoryWithWID(c *cli.Context) {
if !c.Args().Present() {
ErrorAndExit("Argument workflow_id is required.", nil)
}
wid := c.Args().First()
rid := ""
if c.NArg() >= 2 {
rid = c.Args().Get(1)
}
showHistoryHelper(c, wid, rid)
}
func showHistoryHelper(c *cli.Context, wid, rid string) {
wfClient := getWorkflowClient(c)
printDateTime := c.Bool(FlagPrintDateTime)
printRawTime := c.Bool(FlagPrintRawTime)
printFully := c.Bool(FlagPrintFullyDetail)
printVersion := c.Bool(FlagPrintEventVersion)
outputFileName := c.String(FlagOutputFilename)
var maxFieldLength int
if c.IsSet(FlagMaxFieldLength) || !printFully {
maxFieldLength = c.Int(FlagMaxFieldLength)
}
resetPointsOnly := c.Bool(FlagResetPointsOnly)
ctx, cancel := newContext(c)
defer cancel()
history, err := GetHistory(ctx, wfClient, wid, rid)
if err != nil {
ErrorAndExit(fmt.Sprintf("Failed to get history on workflow id: %s, run id: %s.", wid, rid), err)
}
prevEvent := s.HistoryEvent{}
if printFully { // dump everything
for _, e := range history.Events {
if resetPointsOnly {
if prevEvent.GetEventType() != s.EventTypeDecisionTaskStarted {
prevEvent = *e
continue
}
prevEvent = *e
}
fmt.Println(anyToString(e, true, maxFieldLength))
}
} else if c.IsSet(FlagEventID) { // only dump that event
eventID := c.Int(FlagEventID)
if eventID <= 0 || eventID > len(history.Events) {
ErrorAndExit("EventId out of range.", fmt.Errorf("number should be 1 - %d inclusive", len(history.Events)))
}
e := history.Events[eventID-1]
fmt.Println(anyToString(e, true, 0))
} else { // use table to pretty output, will trim long text
table := tablewriter.NewWriter(os.Stdout)
table.SetBorder(false)
table.SetColumnSeparator("")
for _, e := range history.Events {
if resetPointsOnly {
if prevEvent.GetEventType() != s.EventTypeDecisionTaskStarted {
prevEvent = *e
continue
}
prevEvent = *e
}
columns := []string{}
columns = append(columns, strconv.FormatInt(e.GetEventId(), 10))
if printRawTime {
columns = append(columns, strconv.FormatInt(e.GetTimestamp(), 10))
} else if printDateTime {
columns = append(columns, convertTime(e.GetTimestamp(), false))
}
if printVersion {
columns = append(columns, fmt.Sprintf("(Version: %v)", *e.Version))
}
columns = append(columns, ColorEvent(e), HistoryEventToString(e, false, maxFieldLength))
table.Append(columns)
}
table.Render()
}
if outputFileName != "" {
serializer := &JSONHistorySerializer{}
data, err := serializer.Serialize(history)
if err != nil {
ErrorAndExit("Failed to serialize history data.", err)
}
if err := ioutil.WriteFile(outputFileName, data, 0777); err != nil {
ErrorAndExit("Failed to export history data file.", err)
}
}
}
// StartWorkflow starts a new workflow execution
func StartWorkflow(c *cli.Context) {
startWorkflowHelper(c, false)
}
// RunWorkflow starts a new workflow execution and print workflow progress and result
func RunWorkflow(c *cli.Context) {
startWorkflowHelper(c, true)
}
func startWorkflowHelper(c *cli.Context, shouldPrintProgress bool) {
serviceClient := cFactory.ClientFrontendClient(c)
domain := getRequiredGlobalOption(c, FlagDomain)
taskList := getRequiredOption(c, FlagTaskList)
workflowType := getRequiredOption(c, FlagWorkflowType)
et := c.Int(FlagExecutionTimeout)
if et == 0 {
ErrorAndExit(fmt.Sprintf("Option %s format is invalid.", FlagExecutionTimeout), nil)
}
dt := c.Int(FlagDecisionTimeout)
wid := c.String(FlagWorkflowID)
if len(wid) == 0 {
wid = uuid.New()
}
reusePolicy := defaultWorkflowIDReusePolicy.Ptr()
if c.IsSet(FlagWorkflowIDReusePolicy) {
reusePolicy = getWorkflowIDReusePolicy(c.Int(FlagWorkflowIDReusePolicy))
}
input := processJSONInput(c)
startRequest := &s.StartWorkflowExecutionRequest{
RequestId: common.StringPtr(uuid.New()),
Domain: common.StringPtr(domain),
WorkflowId: common.StringPtr(wid),
WorkflowType: &s.WorkflowType{
Name: common.StringPtr(workflowType),
},
TaskList: &s.TaskList{
Name: common.StringPtr(taskList),
},
Input: []byte(input),
ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(int32(et)),
TaskStartToCloseTimeoutSeconds: common.Int32Ptr(int32(dt)),
Identity: common.StringPtr(getCliIdentity()),
WorkflowIdReusePolicy: reusePolicy,
}
if c.IsSet(FlagCronSchedule) {
startRequest.CronSchedule = common.StringPtr(c.String(FlagCronSchedule))
}
memoFields := processMemo(c)
if len(memoFields) != 0 {
startRequest.Memo = &s.Memo{Fields: memoFields}
}
searchAttrFields := processSearchAttr(c)
if len(searchAttrFields) != 0 {
startRequest.SearchAttributes = &s.SearchAttributes{IndexedFields: searchAttrFields}
}
startFn := func() {
tcCtx, cancel := newContext(c)
defer cancel()
resp, err := serviceClient.StartWorkflowExecution(tcCtx, startRequest)
if err != nil {
ErrorAndExit("Failed to create workflow.", err)
} else {
fmt.Printf("Started Workflow Id: %s, run Id: %s\n", wid, resp.GetRunId())
}
}
runFn := func() {
tcCtx, cancel := newContextForLongPoll(c)
defer cancel()
resp, err := serviceClient.StartWorkflowExecution(tcCtx, startRequest)
if err != nil {
ErrorAndExit("Failed to run workflow.", err)
}
// print execution summary
fmt.Println(colorMagenta("Running execution:"))
table := tablewriter.NewWriter(os.Stdout)
executionData := [][]string{
{"Workflow Id", wid},
{"Run Id", resp.GetRunId()},
{"Type", workflowType},
{"Domain", domain},
{"Task List", taskList},
{"Args", truncate(input)}, // in case of large input
}
table.SetBorder(false)
table.SetColumnSeparator(":")
table.AppendBulk(executionData) // Add Bulk Data
table.Render()
printWorkflowProgress(c, wid, resp.GetRunId())
}
if shouldPrintProgress {
runFn()
} else {
startFn()
}
}
func processSearchAttr(c *cli.Context) map[string][]byte {
rawSearchAttrKey := c.String(FlagSearchAttributesKey)
var searchAttrKeys []string
if strings.TrimSpace(rawSearchAttrKey) != "" {
searchAttrKeys = trimSpace(strings.Split(rawSearchAttrKey, searchAttrInputSeparator))
}
rawSearchAttrVal := c.String(FlagSearchAttributesVal)
var searchAttrVals []interface{}
if strings.TrimSpace(rawSearchAttrVal) != "" {
searchAttrValsStr := trimSpace(strings.Split(rawSearchAttrVal, searchAttrInputSeparator))
for _, v := range searchAttrValsStr {
searchAttrVals = append(searchAttrVals, convertStringToRealType(v))
}
}
if len(searchAttrKeys) != len(searchAttrVals) {
ErrorAndExit("Number of search attributes keys and values are not equal.", nil)
}
fields := map[string][]byte{}
for i, key := range searchAttrKeys {
val, err := json.Marshal(searchAttrVals[i])
if err != nil {
ErrorAndExit(fmt.Sprintf("Encode value %v error", val), err)
}
fields[key] = val
}
return fields
}
func processMemo(c *cli.Context) map[string][]byte {
rawMemoKey := c.String(FlagMemoKey)
var memoKeys []string
if strings.TrimSpace(rawMemoKey) != "" {
memoKeys = strings.Split(rawMemoKey, " ")
}
rawMemoValue := processJSONInputHelper(c, jsonTypeMemo)
var memoValues []string
var sc fastjson.Scanner
sc.Init(rawMemoValue)
for sc.Next() {
memoValues = append(memoValues, sc.Value().String())
}
if err := sc.Error(); err != nil {
ErrorAndExit("Parse json error.", err)
}
if len(memoKeys) != len(memoValues) {
ErrorAndExit("Number of memo keys and values are not equal.", nil)
}
fields := map[string][]byte{}
for i, key := range memoKeys {
fields[key] = []byte(memoValues[i])
}
return fields
}
func getPrintableMemo(memo *s.Memo) string {
buf := new(bytes.Buffer)
for k, v := range memo.Fields {
fmt.Fprintf(buf, "%s=%s\n", k, string(v))
}
return buf.String()
}
func getPrintableSearchAttr(searchAttr *s.SearchAttributes) string {
buf := new(bytes.Buffer)
for k, v := range searchAttr.IndexedFields {
var decodedVal interface{}
json.Unmarshal(v, &decodedVal)
fmt.Fprintf(buf, "%s=%v\n", k, decodedVal)
}
return buf.String()
}
// helper function to print workflow progress with time refresh every second
func printWorkflowProgress(c *cli.Context, wid, rid string) {
fmt.Println(colorMagenta("Progress:"))
wfClient := getWorkflowClient(c)
timeElapse := 1
isTimeElapseExist := false
doneChan := make(chan bool)
var lastEvent *s.HistoryEvent // used for print result of this run
ticker := time.NewTicker(time.Second).C
tcCtx, cancel := newContextForLongPoll(c)
defer cancel()
showDetails := c.Bool(FlagShowDetail)
var maxFieldLength int
if c.IsSet(FlagMaxFieldLength) {
maxFieldLength = c.Int(FlagMaxFieldLength)
}
go func() {
iter := wfClient.GetWorkflowHistory(tcCtx, wid, rid, true, s.HistoryEventFilterTypeAllEvent)
for iter.HasNext() {
event, err := iter.Next()
if err != nil {
ErrorAndExit("Unable to read event.", err)
}
if isTimeElapseExist {
removePrevious2LinesFromTerminal()
isTimeElapseExist = false
}
if showDetails {
fmt.Printf(" %d, %s, %s, %s\n", event.GetEventId(), convertTime(event.GetTimestamp(), false), ColorEvent(event), HistoryEventToString(event, true, maxFieldLength))
} else {
fmt.Printf(" %d, %s, %s\n", event.GetEventId(), convertTime(event.GetTimestamp(), false), ColorEvent(event))
}
lastEvent = event
}
doneChan <- true
}()
for {
select {
case <-ticker:
if isTimeElapseExist {
removePrevious2LinesFromTerminal()
}
fmt.Printf("\nTime elapse: %ds\n", timeElapse)
isTimeElapseExist = true
timeElapse++
case <-doneChan: // print result of this run
fmt.Println(colorMagenta("\nResult:"))
fmt.Printf(" Run Time: %d seconds\n", timeElapse)
printRunStatus(lastEvent)
return
}
}
}
// TerminateWorkflow terminates a workflow execution
func TerminateWorkflow(c *cli.Context) {
wfClient := getWorkflowClient(c)
wid := getRequiredOption(c, FlagWorkflowID)
rid := c.String(FlagRunID)
reason := c.String(FlagReason)
ctx, cancel := newContext(c)
defer cancel()
err := wfClient.TerminateWorkflow(ctx, wid, rid, reason, nil)
if err != nil {
ErrorAndExit("Terminate workflow failed.", err)
} else {
fmt.Println("Terminate workflow succeeded.")
}
}
// CancelWorkflow cancels a workflow execution
func CancelWorkflow(c *cli.Context) {
wfClient := getWorkflowClient(c)
wid := getRequiredOption(c, FlagWorkflowID)
rid := c.String(FlagRunID)
ctx, cancel := newContext(c)
defer cancel()
err := wfClient.CancelWorkflow(ctx, wid, rid)
if err != nil {
ErrorAndExit("Cancel workflow failed.", err)
} else {
fmt.Println("Cancel workflow succeeded.")
}
}
// SignalWorkflow signals a workflow execution
func SignalWorkflow(c *cli.Context) {
serviceClient := cFactory.ClientFrontendClient(c)
domain := getRequiredGlobalOption(c, FlagDomain)
wid := getRequiredOption(c, FlagWorkflowID)
rid := c.String(FlagRunID)
name := getRequiredOption(c, FlagName)
input := processJSONInput(c)
tcCtx, cancel := newContext(c)
defer cancel()
err := serviceClient.SignalWorkflowExecution(tcCtx, &s.SignalWorkflowExecutionRequest{
Domain: common.StringPtr(domain),
WorkflowExecution: &s.WorkflowExecution{
WorkflowId: common.StringPtr(wid),
RunId: getPtrOrNilIfEmpty(rid),
},
SignalName: common.StringPtr(name),
Input: []byte(input),
Identity: common.StringPtr(getCliIdentity()),
})
if err != nil {
ErrorAndExit("Signal workflow failed.", err)
} else {
fmt.Println("Signal workflow succeeded.")
}
}
// QueryWorkflow query workflow execution
func QueryWorkflow(c *cli.Context) {
getRequiredGlobalOption(c, FlagDomain) // for pre-check and alert if not provided
getRequiredOption(c, FlagWorkflowID)
queryType := getRequiredOption(c, FlagQueryType)
queryWorkflowHelper(c, queryType)
}
// QueryWorkflowUsingStackTrace query workflow execution using __stack_trace as query type
func QueryWorkflowUsingStackTrace(c *cli.Context) {
queryWorkflowHelper(c, "__stack_trace")
}
func queryWorkflowHelper(c *cli.Context, queryType string) {
serviceClient := cFactory.ClientFrontendClient(c)
domain := getRequiredGlobalOption(c, FlagDomain)
wid := getRequiredOption(c, FlagWorkflowID)
rid := c.String(FlagRunID)
input := processJSONInput(c)
tcCtx, cancel := newContext(c)
defer cancel()
queryRequest := &s.QueryWorkflowRequest{
Domain: common.StringPtr(domain),
Execution: &s.WorkflowExecution{
WorkflowId: common.StringPtr(wid),
RunId: getPtrOrNilIfEmpty(rid),
},
Query: &s.WorkflowQuery{
QueryType: common.StringPtr(queryType),
},
}
if input != "" {
queryRequest.Query.QueryArgs = []byte(input)
}
if c.IsSet(FlagQueryRejectCondition) {
var rejectCondition s.QueryRejectCondition
switch c.String(FlagQueryRejectCondition) {
case "not_open":
rejectCondition = s.QueryRejectConditionNotOpen
case "not_completed_cleanly":
rejectCondition = s.QueryRejectConditionNotCompletedCleanly
default:
ErrorAndExit(fmt.Sprintf("invalid reject condition %v, valid values are \"not_open\" and \"not_completed_cleanly\"", c.String(FlagQueryRejectCondition)), nil)
}
queryRequest.QueryRejectCondition = &rejectCondition
}
if c.IsSet(FlagQueryConsistencyLevel) {
var consistencyLevel s.QueryConsistencyLevel
switch c.String(FlagQueryConsistencyLevel) {
case "eventual":
consistencyLevel = s.QueryConsistencyLevelEventual
case "strong":
consistencyLevel = s.QueryConsistencyLevelStrong
default:
ErrorAndExit(fmt.Sprintf("invalid query consistency level %v, valid values are \"eventual\" and \"strong\"", c.String(FlagQueryConsistencyLevel)), nil)
}
queryRequest.QueryConsistencyLevel = &consistencyLevel
}
queryResponse, err := serviceClient.QueryWorkflow(tcCtx, queryRequest)
if err != nil {
ErrorAndExit("Query workflow failed.", err)
return
}
if queryResponse.QueryRejected != nil {
fmt.Printf("Query was rejected, workflow is in state: %v\n", *queryResponse.QueryRejected.CloseStatus)
} else {
// assume it is json encoded
fmt.Printf("Query result as JSON:\n%v\n", string(queryResponse.QueryResult))
}
}
// ListWorkflow list workflow executions based on filters
func ListWorkflow(c *cli.Context) {
more := c.Bool(FlagMore)
queryOpen := c.Bool(FlagOpen)
printJSON := c.Bool(FlagPrintJSON)
printDecodedRaw := c.Bool(FlagPrintFullyDetail)
if printJSON || printDecodedRaw {
if !more {
results, _ := getListResultInRaw(c, queryOpen, nil)
fmt.Println("[")
printListResults(results, printJSON, false)
fmt.Println("]")
} else {
ErrorAndExit("Not support printJSON in more mode", nil)
}
return
}
table := createTableForListWorkflow(c, false, queryOpen)
prepareTable := listWorkflow(c, table, queryOpen)
if !more { // default mode only show one page items
prepareTable(nil)
table.Render()
} else { // require input Enter to view next page
var nextPageToken []byte
for {
nextPageToken, _ = prepareTable(nextPageToken)
table.Render()
table.ClearRows()
if len(nextPageToken) == 0 {
break
}
if !showNextPage() {
break
}
}
}
}
// ListAllWorkflow list all workflow executions based on filters
func ListAllWorkflow(c *cli.Context) {
queryOpen := c.Bool(FlagOpen)
printJSON := c.Bool(FlagPrintJSON)
printDecodedRaw := c.Bool(FlagPrintFullyDetail)
if printJSON || printDecodedRaw {
var results []*s.WorkflowExecutionInfo
var nextPageToken []byte
fmt.Println("[")
for {
results, nextPageToken = getListResultInRaw(c, queryOpen, nextPageToken)
printListResults(results, printJSON, nextPageToken != nil)
if len(nextPageToken) == 0 {
break
}
}
fmt.Println("]")
return
}
table := createTableForListWorkflow(c, true, queryOpen)
prepareTable := listWorkflow(c, table, queryOpen)
var nextPageToken []byte
for {
nextPageToken, _ = prepareTable(nextPageToken)
if len(nextPageToken) == 0 {
break
}
}
table.Render()
}
// ScanAllWorkflow list all workflow executions using Scan API.
// It should be faster than ListAllWorkflow, but result are not sorted.
func ScanAllWorkflow(c *cli.Context) {
printJSON := c.Bool(FlagPrintJSON)
printDecodedRaw := c.Bool(FlagPrintFullyDetail)
if printJSON || printDecodedRaw {
var results []*s.WorkflowExecutionInfo
var nextPageToken []byte
fmt.Println("[")
for {
results, nextPageToken = getScanResultInRaw(c, nextPageToken)
printListResults(results, printJSON, nextPageToken != nil)
if len(nextPageToken) == 0 {
break
}
}
fmt.Println("]")
return
}
isQueryOpen := isQueryOpen(c.String(FlagListQuery))
table := createTableForListWorkflow(c, true, isQueryOpen)
prepareTable := scanWorkflow(c, table, isQueryOpen)
var nextPageToken []byte
for {
nextPageToken, _ = prepareTable(nextPageToken)
if len(nextPageToken) == 0 {
break
}
}
table.Render()
}
func isQueryOpen(query string) bool {
var openWFPattern = regexp.MustCompile(`CloseTime[ ]*=[ ]*missing`)
return openWFPattern.MatchString(query)
}
// CountWorkflow count number of workflows
func CountWorkflow(c *cli.Context) {
wfClient := getWorkflowClient(c)
query := c.String(FlagListQuery)
request := &s.CountWorkflowExecutionsRequest{
Query: common.StringPtr(query),
}
ctx, cancel := newContextForLongPoll(c)
defer cancel()
response, err := wfClient.CountWorkflow(ctx, request)
if err != nil {
ErrorAndExit("Failed to count workflow.", err)
}
fmt.Println(response.GetCount())
}
// ListArchivedWorkflow lists archived workflow executions based on filters
func ListArchivedWorkflow(c *cli.Context) {
wfClient := getWorkflowClient(c)
printJSON := c.Bool(FlagPrintJSON)
printDecodedRaw := c.Bool(FlagPrintFullyDetail)
pageSize := c.Int(FlagPageSize)
listQuery := getRequiredOption(c, FlagListQuery)
printAll := c.Bool(FlagAll)
if pageSize <= 0 {
pageSize = defaultPageSizeForList
}
request := &s.ListArchivedWorkflowExecutionsRequest{
PageSize: common.Int32Ptr(int32(pageSize)),
Query: common.StringPtr(listQuery),
}
contextTimeout := defaultContextTimeoutForListArchivedWorkflow
if c.GlobalIsSet(FlagContextTimeout) {
contextTimeout = time.Duration(c.GlobalInt(FlagContextTimeout)) * time.Second
}
var result *s.ListArchivedWorkflowExecutionsResponse
var err error
for result == nil || (len(result.Executions) == 0 && result.NextPageToken != nil) {
// the executions will be empty if the query is still running before timeout
// so keep calling the API until some results are returned (query completed)
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
result, err = wfClient.ListArchivedWorkflow(ctx, request)
if err != nil {
cancel()
ErrorAndExit("Failed to list archived workflow.", err)
}
request.NextPageToken = result.NextPageToken
cancel()
}
var table *tablewriter.Table
var printFn func([]*s.WorkflowExecutionInfo, bool)
var prePrintFn func()
var postPrintFn func()
printRawTime := c.Bool(FlagPrintRawTime)
printDateTime := c.Bool(FlagPrintDateTime)
printMemo := c.Bool(FlagPrintMemo)
printSearchAttr := c.Bool(FlagPrintSearchAttr)
if printJSON || printDecodedRaw {
prePrintFn = func() { fmt.Println("[") }
printFn = func(execution []*s.WorkflowExecutionInfo, more bool) {
printListResults(execution, printJSON, more)
}
postPrintFn = func() { fmt.Println("]") }
} else {
table = createTableForListWorkflow(c, false, false)
prePrintFn = func() { table.ClearRows() }
printFn = func(execution []*s.WorkflowExecutionInfo, _ bool) {
appendWorkflowExecutionsToTable(
table,
execution,
false,
printRawTime,
printDateTime,
printMemo,
printSearchAttr,
)
}
postPrintFn = func() { table.Render() }
}
prePrintFn()
printFn(result.Executions, result.NextPageToken != nil)
for len(result.NextPageToken) != 0 {
if !printAll {
postPrintFn()
}
if !printAll && !showNextPage() {
break
}
request.NextPageToken = result.NextPageToken
// create a new context for each new request as each request may take a long time
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
result, err = wfClient.ListArchivedWorkflow(ctx, request)
if err != nil {
cancel()
ErrorAndExit("Failed to list archived workflow", err)
}
cancel()
if !printAll {
prePrintFn()
}
printFn(result.Executions, result.NextPageToken != nil)
}
// if next page token is not nil here, then it means we are not in all mode,
// and user doesn't want to view the next page. In that case the post
// operation has already been done and we don't want to perform it again.
if len(result.NextPageToken) == 0 {
postPrintFn()
}
}
// DescribeWorkflow show information about the specified workflow execution
func DescribeWorkflow(c *cli.Context) {
wid := getRequiredOption(c, FlagWorkflowID)
rid := c.String(FlagRunID)
describeWorkflowHelper(c, wid, rid)
}
// DescribeWorkflowWithID show information about the specified workflow execution
func DescribeWorkflowWithID(c *cli.Context) {
if !c.Args().Present() {
ErrorAndExit("Argument workflow_id is required.", nil)
}
wid := c.Args().First()
rid := ""
if c.NArg() >= 2 {
rid = c.Args().Get(1)
}
describeWorkflowHelper(c, wid, rid)
}
func describeWorkflowHelper(c *cli.Context, wid, rid string) {
frontendClient := cFactory.ServerFrontendClient(c)
domain := getRequiredGlobalOption(c, FlagDomain)
printRaw := c.Bool(FlagPrintRaw) // printRaw is false by default,
// and will show datetime and decoded search attributes instead of raw timestamp and byte arrays
printResetPointsOnly := c.Bool(FlagResetPointsOnly)
ctx, cancel := newContext(c)
defer cancel()
resp, err := frontendClient.DescribeWorkflowExecution(ctx, &shared.DescribeWorkflowExecutionRequest{
Domain: common.StringPtr(domain),
Execution: &shared.WorkflowExecution{
WorkflowId: common.StringPtr(wid),
RunId: common.StringPtr(rid),
},
})
if err != nil {
ErrorAndExit("Describe workflow execution failed", err)
}
if printResetPointsOnly {
printAutoResetPoints(resp)
return
}
var o interface{}
if printRaw {
o = resp
} else {
o = convertDescribeWorkflowExecutionResponse(resp, frontendClient, c)
}
prettyPrintJSONObject(o)
}
func printAutoResetPoints(resp *shared.DescribeWorkflowExecutionResponse) {
fmt.Println("Auto Reset Points:")
table := tablewriter.NewWriter(os.Stdout)
table.SetBorder(true)
table.SetColumnSeparator("|")
header := []string{"Binary Checksum", "Create Time", "RunID", "EventID"}
headerColor := []tablewriter.Colors{tableHeaderBlue, tableHeaderBlue, tableHeaderBlue, tableHeaderBlue}
table.SetHeader(header)
table.SetHeaderColor(headerColor...)
if resp.WorkflowExecutionInfo.AutoResetPoints != nil && len(resp.WorkflowExecutionInfo.AutoResetPoints.Points) > 0 {
for _, pt := range resp.WorkflowExecutionInfo.AutoResetPoints.Points {
var row []string
row = append(row, pt.GetBinaryChecksum())
row = append(row, time.Unix(0, pt.GetCreatedTimeNano()).String())
row = append(row, pt.GetRunId())
row = append(row, strconv.FormatInt(pt.GetFirstDecisionCompletedId(), 10))
table.Append(row)
}
}
table.Render()
}
// describeWorkflowExecutionResponse is used to print datetime instead of print raw time
type describeWorkflowExecutionResponse struct {
ExecutionConfiguration *shared.WorkflowExecutionConfiguration
WorkflowExecutionInfo workflowExecutionInfo
PendingActivities []*pendingActivityInfo
PendingChildren []*shared.PendingChildExecutionInfo
}
// workflowExecutionInfo has same fields as shared.WorkflowExecutionInfo, but has datetime instead of raw time
type workflowExecutionInfo struct {
Execution *shared.WorkflowExecution
Type *shared.WorkflowType
StartTime *string // change from *int64
CloseTime *string // change from *int64
CloseStatus *shared.WorkflowExecutionCloseStatus
HistoryLength *int64
ParentDomainID *string
ParentExecution *shared.WorkflowExecution
Memo *shared.Memo
SearchAttributes map[string]interface{}
AutoResetPoints *shared.ResetPoints
}
// pendingActivityInfo has same fields as shared.PendingActivityInfo, but different field type for better display
type pendingActivityInfo struct {
ActivityID *string
ActivityType *shared.ActivityType
State *shared.PendingActivityState
ScheduledTimestamp *string `json:",omitempty"` // change from *int64
LastStartedTimestamp *string `json:",omitempty"` // change from *int64
HeartbeatDetails *string `json:",omitempty"` // change from []byte
LastHeartbeatTimestamp *string `json:",omitempty"` // change from *int64
Attempt *int32 `json:",omitempty"`
MaximumAttempts *int32 `json:",omitempty"`
ExpirationTimestamp *string `json:",omitempty"` // change from *int64
LastFailureReason *string `json:",omitempty"`
LastWorkerIdentity *string `json:",omitempty"`
LastFailureDetails *string `json:",omitempty"` // change from []byte
}
func convertDescribeWorkflowExecutionResponse(resp *shared.DescribeWorkflowExecutionResponse,
wfClient workflowserviceclient.Interface, c *cli.Context) *describeWorkflowExecutionResponse {
info := resp.WorkflowExecutionInfo
executionInfo := workflowExecutionInfo{
Execution: info.Execution,
Type: info.Type,
StartTime: common.StringPtr(convertTime(info.GetStartTime(), false)),
CloseTime: common.StringPtr(convertTime(info.GetCloseTime(), false)),
CloseStatus: info.CloseStatus,
HistoryLength: info.HistoryLength,
ParentDomainID: info.ParentDomainId,
ParentExecution: info.ParentExecution,
Memo: info.Memo,
SearchAttributes: convertSearchAttributesToMapOfInterface(info.SearchAttributes, wfClient, c),
AutoResetPoints: info.AutoResetPoints,
}
var pendingActs []*pendingActivityInfo
var tmpAct *pendingActivityInfo
for _, pa := range resp.PendingActivities {
tmpAct = &pendingActivityInfo{
ActivityID: pa.ActivityID,
ActivityType: pa.ActivityType,
State: pa.State,
ScheduledTimestamp: timestampPtrToStringPtr(pa.ScheduledTimestamp, false),
LastStartedTimestamp: timestampPtrToStringPtr(pa.LastStartedTimestamp, false),
LastHeartbeatTimestamp: timestampPtrToStringPtr(pa.LastHeartbeatTimestamp, false),
Attempt: pa.Attempt,
MaximumAttempts: pa.MaximumAttempts,
ExpirationTimestamp: timestampPtrToStringPtr(pa.ExpirationTimestamp, false),
LastFailureReason: pa.LastFailureReason,
LastWorkerIdentity: pa.LastWorkerIdentity,
}
if pa.HeartbeatDetails != nil {
tmpAct.HeartbeatDetails = common.StringPtr(string(pa.HeartbeatDetails))
}
if pa.LastFailureDetails != nil {
tmpAct.LastFailureDetails = common.StringPtr(string(pa.LastFailureDetails))
}
pendingActs = append(pendingActs, tmpAct)
}
return &describeWorkflowExecutionResponse{
ExecutionConfiguration: resp.ExecutionConfiguration,
WorkflowExecutionInfo: executionInfo,
PendingActivities: pendingActs,
PendingChildren: resp.PendingChildren,
}
}
func convertSearchAttributesToMapOfInterface(searchAttributes *shared.SearchAttributes,
wfClient workflowserviceclient.Interface, c *cli.Context) map[string]interface{} {
if searchAttributes == nil || len(searchAttributes.GetIndexedFields()) == 0 {
return nil
}
result := make(map[string]interface{})
ctx, cancel := newContext(c)
defer cancel()
validSearchAttributes, err := wfClient.GetSearchAttributes(ctx)
if err != nil {
ErrorAndExit("Error when get search attributes", err)
}
validKeys := validSearchAttributes.GetKeys()
indexedFields := searchAttributes.GetIndexedFields()
for k, v := range indexedFields {
valueType := validKeys[k]
switch valueType {
case shared.IndexedValueTypeString, shared.IndexedValueTypeKeyword:
var val string
json.Unmarshal(v, &val)
result[k] = val
case shared.IndexedValueTypeInt:
var val int64
json.Unmarshal(v, &val)
result[k] = val
case shared.IndexedValueTypeDouble:
var val float64
json.Unmarshal(v, &val)
result[k] = val
case shared.IndexedValueTypeBool:
var val bool
json.Unmarshal(v, &val)
result[k] = val
case shared.IndexedValueTypeDatetime:
var val time.Time
json.Unmarshal(v, &val)
result[k] = val
default:
ErrorAndExit(fmt.Sprintf("Error unknown index value type [%v]", valueType), nil)
}
}