-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathutil.go
829 lines (678 loc) · 24.3 KB
/
util.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
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 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_curr
import (
"bufio"
"context"
"encoding/json"
"fmt"
"os"
"reflect"
"regexp"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/gogo/protobuf/proto"
"github.com/olekukonko/tablewriter"
"github.com/urfave/cli"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
historypb "go.temporal.io/api/history/v1"
sdkclient "go.temporal.io/sdk/client"
"go.temporal.io/sdk/converter"
"github.com/temporalio/tctl/cli/headers"
"github.com/temporalio/tctl/cli_curr/dataconverter"
"github.com/temporalio/tctl/cli_curr/stringify"
"go.temporal.io/server/common/codec"
"go.temporal.io/server/common/collection"
"go.temporal.io/server/common/payloads"
)
// GetHistory helper method to iterate over all pages and return complete list of history events
func GetHistory(ctx context.Context, workflowClient sdkclient.Client, workflowID, runID string) (*historypb.History, error) {
iter := workflowClient.GetWorkflowHistory(ctx, workflowID, runID, false,
enumspb.HISTORY_EVENT_FILTER_TYPE_ALL_EVENT)
var events []*historypb.HistoryEvent
for iter.HasNext() {
event, err := iter.Next()
if err != nil {
return nil, err
}
events = append(events, event)
}
history := &historypb.History{}
history.Events = events
return history, nil
}
// HistoryEventToString convert HistoryEvent to string
func HistoryEventToString(e *historypb.HistoryEvent, printFully bool, maxFieldLength int) string {
data := getEventAttributes(e)
return stringify.AnyToString(data, printFully, maxFieldLength, customDataConverter())
}
// ColorEvent takes an event and return string with color
// Event with color mapping rules:
// Failed - red
// Timeout - yellow
// Canceled - magenta
// Completed - green
// Started - blue
// Others - default (white/black)
func ColorEvent(e *historypb.HistoryEvent) string {
var data string
switch e.GetEventType() {
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED:
data = color.BlueString(e.EventType.String())
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED:
data = color.GreenString(e.EventType.String())
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_FAILED:
data = color.RedString(e.EventType.String())
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT:
data = color.YellowString(e.EventType.String())
case enumspb.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_STARTED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_COMPLETED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_TIMED_OUT:
data = color.YellowString(e.EventType.String())
case enumspb.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_STARTED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_COMPLETED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_FAILED:
data = color.RedString(e.EventType.String())
case enumspb.EVENT_TYPE_ACTIVITY_TASK_TIMED_OUT:
data = color.YellowString(e.EventType.String())
case enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCEL_REQUESTED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCELED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_TIMER_STARTED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_TIMER_FIRED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_TIMER_CANCELED:
data = color.MagentaString(e.EventType.String())
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CANCEL_REQUESTED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED:
data = color.MagentaString(e.EventType.String())
case enumspb.EVENT_TYPE_REQUEST_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_INITIATED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_REQUEST_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED:
data = color.RedString(e.EventType.String())
case enumspb.EVENT_TYPE_EXTERNAL_WORKFLOW_EXECUTION_CANCEL_REQUESTED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_MARKER_RECORDED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW:
data = e.EventType.String()
case enumspb.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_FAILED:
data = color.RedString(e.EventType.String())
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED:
data = color.BlueString(e.EventType.String())
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_COMPLETED:
data = color.GreenString(e.EventType.String())
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_FAILED:
data = color.RedString(e.EventType.String())
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_CANCELED:
data = color.MagentaString(e.EventType.String())
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_TIMED_OUT:
data = color.YellowString(e.EventType.String())
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_TERMINATED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_INITIATED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED:
data = color.RedString(e.EventType.String())
case enumspb.EVENT_TYPE_EXTERNAL_WORKFLOW_EXECUTION_SIGNALED:
data = e.EventType.String()
case enumspb.EVENT_TYPE_UPSERT_WORKFLOW_SEARCH_ATTRIBUTES:
data = e.EventType.String()
default:
data = e.EventType.String()
}
return data
}
func getEventAttributes(e *historypb.HistoryEvent) interface{} {
var data interface{}
switch e.GetEventType() {
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED:
data = e.GetWorkflowExecutionStartedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED:
data = e.GetWorkflowExecutionCompletedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_FAILED:
data = e.GetWorkflowExecutionFailedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_FAILED:
data = e.GetWorkflowTaskFailedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT:
data = e.GetWorkflowExecutionTimedOutEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED:
data = e.GetWorkflowTaskScheduledEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_STARTED:
data = e.GetWorkflowTaskStartedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_COMPLETED:
data = e.GetWorkflowTaskCompletedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_TASK_TIMED_OUT:
data = e.GetWorkflowTaskTimedOutEventAttributes()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED:
data = e.GetActivityTaskScheduledEventAttributes()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_STARTED:
data = e.GetActivityTaskStartedEventAttributes()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_COMPLETED:
data = e.GetActivityTaskCompletedEventAttributes()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_FAILED:
data = e.GetActivityTaskFailedEventAttributes()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_TIMED_OUT:
data = e.GetActivityTaskTimedOutEventAttributes()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCEL_REQUESTED:
data = e.GetActivityTaskCancelRequestedEventAttributes()
case enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCELED:
data = e.GetActivityTaskCanceledEventAttributes()
case enumspb.EVENT_TYPE_TIMER_STARTED:
data = e.GetTimerStartedEventAttributes()
case enumspb.EVENT_TYPE_TIMER_FIRED:
data = e.GetTimerFiredEventAttributes()
case enumspb.EVENT_TYPE_TIMER_CANCELED:
data = e.GetTimerCanceledEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CANCEL_REQUESTED:
data = e.GetWorkflowExecutionCancelRequestedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED:
data = e.GetWorkflowExecutionCanceledEventAttributes()
case enumspb.EVENT_TYPE_REQUEST_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_INITIATED:
data = e.GetRequestCancelExternalWorkflowExecutionInitiatedEventAttributes()
case enumspb.EVENT_TYPE_REQUEST_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED:
data = e.GetRequestCancelExternalWorkflowExecutionFailedEventAttributes()
case enumspb.EVENT_TYPE_EXTERNAL_WORKFLOW_EXECUTION_CANCEL_REQUESTED:
data = e.GetExternalWorkflowExecutionCancelRequestedEventAttributes()
case enumspb.EVENT_TYPE_MARKER_RECORDED:
data = e.GetMarkerRecordedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED:
data = e.GetWorkflowExecutionSignaledEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED:
data = e.GetWorkflowExecutionTerminatedEventAttributes()
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW:
data = e.GetWorkflowExecutionContinuedAsNewEventAttributes()
case enumspb.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED:
data = e.GetStartChildWorkflowExecutionInitiatedEventAttributes()
case enumspb.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_FAILED:
data = e.GetStartChildWorkflowExecutionFailedEventAttributes()
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED:
data = e.GetChildWorkflowExecutionStartedEventAttributes()
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_COMPLETED:
data = e.GetChildWorkflowExecutionCompletedEventAttributes()
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_FAILED:
data = e.GetChildWorkflowExecutionFailedEventAttributes()
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_CANCELED:
data = e.GetChildWorkflowExecutionCanceledEventAttributes()
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_TIMED_OUT:
data = e.GetChildWorkflowExecutionTimedOutEventAttributes()
case enumspb.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_TERMINATED:
data = e.GetChildWorkflowExecutionTerminatedEventAttributes()
case enumspb.EVENT_TYPE_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_INITIATED:
data = e.GetSignalExternalWorkflowExecutionInitiatedEventAttributes()
case enumspb.EVENT_TYPE_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED:
data = e.GetSignalExternalWorkflowExecutionFailedEventAttributes()
case enumspb.EVENT_TYPE_EXTERNAL_WORKFLOW_EXECUTION_SIGNALED:
data = e.GetExternalWorkflowExecutionSignaledEventAttributes()
case enumspb.EVENT_TYPE_UPSERT_WORKFLOW_SEARCH_ATTRIBUTES:
data = e.GetUpsertWorkflowSearchAttributesEventAttributes()
default:
data = e
}
return data
}
func getCurrentUserFromEnv() string {
for _, n := range envKeysForUserName {
if len(os.Getenv(n)) > 0 {
return os.Getenv(n)
}
}
return "unknown"
}
func prettyPrintJSONObject(o interface{}) {
v := reflect.ValueOf(o)
if o == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
fmt.Println("nil")
return
}
var b []byte
var err error
if pb, ok := o.(proto.Message); ok {
encoder := codec.NewJSONPBIndentEncoder(" ")
b, err = encoder.Encode(pb)
} else {
b, err = json.MarshalIndent(o, "", " ")
}
if err != nil {
fmt.Printf("%s. Raw data:", color.RedString("Unable to marshal object to JSON for pretty print: %v", err))
fmt.Println(o)
return
}
_, _ = os.Stdout.Write(b)
fmt.Println()
}
func mapKeysToArray(m map[string]interface{}) []string {
var out []string
for k := range m {
out = append(out, k)
}
return out
}
func printError(msg string, err error) {
if err != nil {
fmt.Printf("%s %s\n%s %+v\n", colorRed("Error:"), msg, colorMagenta("Error Details:"), err)
if os.Getenv(showErrorStackEnv) != `` {
fmt.Printf("Stack trace:\n")
debug.PrintStack()
} else {
fmt.Printf("('export %s=1' to see stack traces)\n", showErrorStackEnv)
}
} else {
fmt.Printf("%s %s\n", colorRed("Error:"), msg)
}
}
// ErrorAndExit print easy to understand error msg first then error detail in a new line
func ErrorAndExit(msg string, err error) {
printError(msg, err)
osExit(1)
}
func getSDKClient(c *cli.Context) sdkclient.Client {
namespace := getRequiredGlobalOption(c, FlagNamespace)
return cFactory.SDKClient(c, namespace)
}
func getRequiredOption(c *cli.Context, optionName string) string {
value := c.String(optionName)
if len(value) == 0 {
ErrorAndExit(fmt.Sprintf("Option %s is required", optionName), nil)
}
return value
}
func getRequiredStringSliceOption(c *cli.Context, optionName string) []string {
value := c.StringSlice(optionName)
if len(value) == 0 {
ErrorAndExit(fmt.Sprintf("Option %s is required", optionName), nil)
}
return value
}
func getRequiredInt64Option(c *cli.Context, optionName string) int64 {
if !c.IsSet(optionName) {
ErrorAndExit(fmt.Sprintf("Option %s is required", optionName), nil)
}
return c.Int64(optionName)
}
func getRequiredIntOption(c *cli.Context, optionName string) int {
if !c.IsSet(optionName) {
ErrorAndExit(fmt.Sprintf("Option %s is required", optionName), nil)
}
return c.Int(optionName)
}
func getRequiredGlobalOption(c *cli.Context, optionName string) string {
value := c.GlobalString(optionName)
if len(value) == 0 {
ErrorAndExit(fmt.Sprintf("Global option %s is required", optionName), nil)
}
return value
}
func formatTime(t time.Time, onlyTime bool) string {
var result string
if onlyTime {
result = t.Format(defaultTimeFormat)
} else {
result = t.Format(defaultDateTimeFormat)
}
return result
}
func parseTime(timeStr string, defaultValue time.Time, now time.Time) time.Time {
if len(timeStr) == 0 {
return defaultValue
}
// try to parse
parsedTime, err := time.Parse(defaultDateTimeFormat, timeStr)
if err == nil {
return parsedTime
}
// treat as raw unix time
resultValue, err := strconv.ParseInt(timeStr, 10, 64)
if err == nil {
return time.Unix(0, resultValue).UTC()
}
// treat as time range format
parsedTime, err = parseTimeRange(timeStr, now)
if err != nil {
ErrorAndExit(fmt.Sprintf("Cannot parse time '%s', use UTC format '2006-01-02T15:04:05', "+
"time range or raw UnixNano directly. See help for more details.", timeStr), err)
}
return parsedTime
}
// parseTimeRange parses a given time duration string (in format X<time-duration>) and
// returns parsed timestamp given that duration in the past from current time.
// All valid values must contain a number followed by a time-duration, from the following list (long form/short form):
// - second/s
// - minute/m
// - hour/h
// - day/d
// - week/w
// - month/M
// - year/y
// For example, possible input values, and their result:
// - "3d" or "3day" --> three days --> time.Now().UTC().Add(-3 * 24 * time.Hour)
// - "2m" or "2minute" --> two minutes --> time.Now().UTC().Add(-2 * time.Minute)
// - "1w" or "1week" --> one week --> time.Now().UTC().Add(-7 * 24 * time.Hour)
// - "30s" or "30second" --> thirty seconds --> time.Now().UTC().Add(-30 * time.Second)
// Note: Duration strings are case-sensitive, and should be used as mentioned above only.
// Limitation: Value of numerical multiplier, X should be in b/w 0 - 1e6 (1 million), boundary values excluded i.e.
// 0 < X < 1e6. Also, the maximum time in the past can be 1 January 1970 00:00:00 UTC (epoch time),
// so giving "1000y" will result in epoch time.
func parseTimeRange(timeRange string, now time.Time) (time.Time, error) {
match, err := regexp.MatchString(defaultDateTimeRangeShortRE, timeRange)
if !match { // fallback on to check if it's of longer notation
match, err = regexp.MatchString(defaultDateTimeRangeLongRE, timeRange)
}
if err != nil {
return time.Time{}, err
}
re, _ := regexp.Compile(defaultDateTimeRangeNum)
idx := re.FindStringSubmatchIndex(timeRange)
if idx == nil {
return time.Time{}, fmt.Errorf("cannot parse timeRange %s", timeRange)
}
num, err := strconv.Atoi(timeRange[idx[0]:idx[1]])
if err != nil {
return time.Time{}, fmt.Errorf("cannot parse timeRange %s", timeRange)
}
if num >= 1e6 {
return time.Time{}, fmt.Errorf("invalid time-duation multiplier %d, allowed range is 0 < multiplier < 1000000", num)
}
dur, err := parseTimeDuration(timeRange[idx[1]:])
if err != nil {
return time.Time{}, fmt.Errorf("cannot parse timeRange %s", timeRange)
}
res := now.Add(time.Duration(-num) * dur) // using server's local timezone
epochTime := time.Unix(0, 0).UTC()
if res.Before(epochTime) {
res = epochTime
}
return res, nil
}
// parseTimeDuration parses the given time duration in either short or long convention
// and returns the time.Duration
// Valid values (long notation/short notation):
// - second/s
// - minute/m
// - hour/h
// - day/d
// - week/w
// - month/M
// - year/y
// NOTE: the input "duration" is case-sensitive
func parseTimeDuration(duration string) (dur time.Duration, err error) {
switch duration {
case "s", "second":
dur = time.Second
case "m", "minute":
dur = time.Minute
case "h", "hour":
dur = time.Hour
case "d", "day":
dur = day
case "w", "week":
dur = week
case "M", "month":
dur = month
case "y", "year":
dur = year
default:
err = fmt.Errorf("unknown time duration %s", duration)
}
return
}
func strToTaskQueueType(str string) enumspb.TaskQueueType {
if strings.ToLower(str) == "activity" {
return enumspb.TASK_QUEUE_TYPE_ACTIVITY
}
return enumspb.TASK_QUEUE_TYPE_WORKFLOW
}
func getCliIdentity() string {
hostName, err := os.Hostname()
if err != nil {
hostName = "UnKnown"
}
return fmt.Sprintf("tctl@%s", hostName)
}
func newContext(c *cli.Context) (context.Context, context.CancelFunc) {
return newContextWithTimeout(c, defaultContextTimeout)
}
func newContextForLongPoll(c *cli.Context) (context.Context, context.CancelFunc) {
return newContextWithTimeout(c, defaultContextTimeoutForLongPoll)
}
func newIndefiniteContext(c *cli.Context) (context.Context, context.CancelFunc) {
if c.GlobalIsSet(FlagContextTimeout) {
timeout := time.Duration(c.GlobalInt(FlagContextTimeout)) * time.Second
return NewContextWithTimeoutAndCLIHeaders(timeout)
}
return NewContextWithCLIHeaders()
}
func newContextWithTimeout(c *cli.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if c.GlobalIsSet(FlagContextTimeout) {
timeout = time.Duration(c.GlobalInt(FlagContextTimeout)) * time.Second
}
return NewContextWithTimeoutAndCLIHeaders(timeout)
}
// NewContextWithCLIHeaders creates context with version headers for CLI.
func NewContextWithCLIHeaders() (context.Context, context.CancelFunc) {
return context.WithCancel(headers.SetCLIVersions(context.Background()))
}
// NewContextWithTimeoutAndCLIHeaders creates context with timeout and version headers for CLI.
func NewContextWithTimeoutAndCLIHeaders(timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(headers.SetCLIVersions(context.Background()), timeout)
}
// process and validate input provided through cmd or file
func processJSONInput(c *cli.Context) *commonpb.Payloads {
jsonsRaw := readJSONInputs(c)
var jsons []interface{}
for _, jsonRaw := range jsonsRaw {
if jsonRaw == nil {
jsons = append(jsons, nil)
} else {
var j interface{}
if err := json.Unmarshal(jsonRaw, &j); err != nil {
ErrorAndExit("Input is not valid JSON.", err)
}
jsons = append(jsons, j)
}
}
p, err := payloads.Encode(jsons...)
if err != nil {
ErrorAndExit("Unable to encode input.", err)
}
return p
}
// read multiple inputs presented in json format
func readJSONInputs(c *cli.Context) [][]byte {
if c.IsSet(FlagInput) {
inputsG := c.Generic(FlagInput)
var inputs *cli.StringSlice
var ok bool
if inputs, ok = inputsG.(*cli.StringSlice); !ok {
// input could be provided as StringFlag instead of StringSliceFlag
ss := make(cli.StringSlice, 1)
ss[0] = fmt.Sprintf("%v", inputsG)
inputs = &ss
}
var inputsRaw [][]byte
for _, i := range *inputs {
if strings.EqualFold(i, "null") {
inputsRaw = append(inputsRaw, []byte(nil))
} else {
inputsRaw = append(inputsRaw, []byte(i))
}
}
return inputsRaw
} else if c.IsSet(FlagInputFile) {
inputFile := c.String(FlagInputFile)
// This method is purely used to parse input from the CLI. The input comes from a trusted user
// #nosec
data, err := os.ReadFile(inputFile)
if err != nil {
ErrorAndExit("Error reading input file", err)
}
return [][]byte{data}
}
return nil
}
func truncate(str string) string {
if len(str) > maxOutputStringLength {
return str[:maxOutputStringLength]
}
return str
}
// this only works for ANSI terminal, which means remove existing lines won't work if users redirect to file
// ref: https://en.wikipedia.org/wiki/ANSI_escape_code
func removePrevious2LinesFromTerminal() {
fmt.Printf("\033[1A")
fmt.Printf("\033[2K")
fmt.Printf("\033[1A")
fmt.Printf("\033[2K")
}
func showNextPage() bool {
fmt.Printf("Press %s to show next page, press %s to quit: ",
color.GreenString("Enter"), color.RedString("any other key then Enter"))
var input string
_, _ = fmt.Scanln(&input)
return strings.Trim(input, " ") == ""
}
// paginate creates an interactive CLI mode to control the printing of items
func paginate[V any](c *cli.Context, paginationFn collection.PaginationFn[V], pageSize int) error {
more := c.Bool(FlagMore)
isTableView := !c.Bool(FlagPrintJSON)
iter := collection.NewPagingIterator(paginationFn)
var pageItems []interface{}
for iter.HasNext() {
item, err := iter.Next()
if err != nil {
return err
}
pageItems = append(pageItems, item)
if len(pageItems) == pageSize || !iter.HasNext() {
if isTableView {
printTable(pageItems)
} else {
prettyPrintJSONObject(pageItems)
}
if !more || !showNextPage() {
break
}
pageItems = pageItems[:0]
}
}
return nil
}
func printTable(items []interface{}) error {
if len(items) == 0 {
return nil
}
e := reflect.ValueOf(items[0])
for e.Type().Kind() == reflect.Ptr {
e = e.Elem()
}
var fields []string
t := e.Type()
for i := 0; i < e.NumField(); i++ {
fields = append(fields, t.Field(i).Name)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetBorder(false)
table.SetColumnSeparator("|")
table.SetHeader(fields)
table.SetHeaderLine(false)
for i := 0; i < len(items); i++ {
item := reflect.ValueOf(items[i])
for item.Type().Kind() == reflect.Ptr {
item = item.Elem()
}
var columns []string
for j := 0; j < len(fields); j++ {
col := item.Field(j)
columns = append(columns, fmt.Sprintf("%v", col.Interface()))
}
table.Append(columns)
}
table.Render()
table.ClearRows()
return nil
}
func stringToEnum(search string, candidates map[string]int32) (int32, error) {
if search == "" {
return 0, nil
}
var candidateNames []string
for key, value := range candidates {
if strings.EqualFold(key, search) {
return value, nil
}
candidateNames = append(candidateNames, key)
}
return 0, fmt.Errorf("unable to find corresponding candidate for %s from %s list", search, candidateNames)
}
func allowedEnumValues(names map[int32]string) []string {
result := make([]string, len(names)-1)
for i := 0; i < len(result); i++ {
result[i] = names[int32(i+1)]
}
return result
}
// prompt will show input msg, then waiting user input y/yes to continue
func prompt(msg string, autoConfirm bool) {
reader := bufio.NewReader(os.Stdin)
fmt.Print(msg, " ")
var text string
if autoConfirm {
text = "y"
fmt.Print("y")
} else {
text, _ = reader.ReadString('\n')
}
fmt.Println()
textLower := strings.ToLower(strings.TrimRight(text, "\n"))
if textLower != "y" && textLower != "yes" {
os.Exit(1)
}
}
func defaultDataConverter() converter.DataConverter {
return converter.GetDefaultDataConverter()
}
func customDataConverter() converter.DataConverter {
return dataconverter.GetCurrent()
}