-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
1027 lines (810 loc) · 23.5 KB
/
Copy pathmain.go
File metadata and controls
1027 lines (810 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023-2026 D. Bohdan
//
// 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 main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"math/rand/v2"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/alecthomas/repr"
"github.com/mitchellh/go-wordwrap"
"golang.org/x/term"
)
const (
envVarAttempt = "RECUR_ATTEMPT"
envVarAttemptSinceReset = "RECUR_ATTEMPT_SINCE_RESET"
envVarMaxAttempts = "RECUR_MAX_ATTEMPTS"
exitCodeBadUsage = 2
exitCodeCommandNotFound = 127
exitCodeError = 255
exitCodeTimeout = 124
version = "3.3.0"
invSqrt5 = 0.4472135954999579
reportSecondsFormat = "%0.3f"
reportPadding = 2
verboseLevelAttemptResults = 1
verboseLevelConditionDetails = 2
verboseLevelConfig = 3
verboseLevelConfigWithZeros = 4
verboseLevelMax = 4
)
type attempt struct {
CommandFound bool
Duration time.Duration
ExitCode int
MaxAttempts int
Number int
NumberSinceReset int
TotalTime time.Duration
}
type interval struct {
Start time.Duration
End time.Duration
}
func parseInterval(s string) (interval, error) {
var start, end time.Duration
var err error
parts := strings.Split(s, ",")
//nolint:mnd
switch len(parts) {
case 2:
start, err = time.ParseDuration(strings.TrimRight(parts[0], " "))
if err != nil {
return interval{}, fmt.Errorf("invalid start duration: %s", parts[0])
}
end, err = time.ParseDuration(strings.TrimLeft(parts[1], " "))
if err != nil {
return interval{}, fmt.Errorf("invalid end duration: %s", parts[1])
}
case 1:
end, err = time.ParseDuration(parts[0])
if err != nil {
return interval{}, fmt.Errorf("invalid end duration: %s", parts[0])
}
start = 0
default:
return interval{}, fmt.Errorf("invalid interval format: %s", s)
}
if start < 0 || end < 0 || start > end {
return interval{}, fmt.Errorf("invalid interval values: start=%s, end=%s", start.String(), end.String())
}
return interval{Start: start, End: end}, nil
}
type commandStatus int
const (
statusFinished commandStatus = iota
statusTimeout
statusNotFound
statusUnknownError
)
type commandResult struct {
Status commandStatus
ExitCode int
}
type reportFormat int
const (
reportFormatNone reportFormat = iota
reportFormatJSON
reportFormatText
)
func (r reportFormat) String() string {
switch r {
case reportFormatNone:
return "none"
case reportFormatJSON:
return "json"
case reportFormatText:
return "text"
default:
return "unknown"
}
}
type reportConfig struct {
Format reportFormat
Path string
}
func parseReportConfig(s string) reportConfig {
if s == "" {
return reportConfig{Format: reportFormatNone, Path: ""}
}
if path, found := strings.CutPrefix(s, "json:"); found {
return reportConfig{
Format: reportFormatJSON,
Path: path,
}
}
if path, found := strings.CutPrefix(s, "text:"); found {
return reportConfig{
Format: reportFormatText,
Path: path,
}
}
// Infer the format from the file extension.
format := reportFormatText
if strings.HasSuffix(s, ".json") {
format = reportFormatJSON
}
return reportConfig{
Format: format,
Path: s,
}
}
type retryConfig struct {
Command string
Args []string
Backoff time.Duration
Condition string
ConditionFile string
ConstantDelay time.Duration
DateTime bool
Fibonacci bool
HoldStderr bool
HoldStdout bool
MaxAttempts int
MaxDelay time.Duration
RandomDelay interval
RandomSeed uint64
ReplayStdin bool
Report reportConfig
Reset time.Duration
Timeout time.Duration
Verbose int
}
type recurStats struct {
Attempts int
CommandFound []bool
ConditionResults []bool
ExitCodes []int
Failures int
Successes int
TotalTime time.Duration
WaitTimes []time.Duration
}
const (
backoffDefault = time.Duration(0)
conditionDefault = "code == 0"
conditionFileDefault = ""
delayDefault = time.Duration(0)
jitterDefault = "0,0"
maxDelayDefault = time.Hour
maxAttemptsDefault = 10
randomSeedDefault = uint64(0)
reportDefault = ""
resetDefault = -time.Second
timeoutDefault = -time.Second
)
type logWriter struct {
dateTime bool
startTime time.Time
}
//nolint:mnd
func (w *logWriter) Write(bytes []byte) (int, error) {
if w.dateTime {
now := time.Now()
//nolint:wrapcheck
return fmt.Fprintf(
os.Stderr,
"recur [%s]: %s",
strings.Replace(now.Format(time.RFC3339), "T", " ", 1),
string(bytes),
)
}
elapsed := time.Since(w.startTime)
hours := int(elapsed.Hours())
minutes := int(elapsed.Minutes()) % 60
seconds := int(elapsed.Seconds()) % 60
deciseconds := elapsed.Milliseconds() % 1000 / 100
//nolint:wrapcheck
return fmt.Fprintf(os.Stderr, "recur [%02d:%02d:%02d.%01d]: %s", hours, minutes, seconds, deciseconds, string(bytes))
}
type exitRequestError struct {
Code int
}
func (e *exitRequestError) Error() string {
return fmt.Sprintf("exit requested with code %d", e.Code)
}
func executeCommand(command string, args []string, timeout time.Duration, envVars []string, stdinContent []byte, holdStdout bool, holdStderr bool) (commandResult, []byte, []byte) {
ctx := context.Background()
if timeout >= 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
cmd := exec.CommandContext(ctx, command, args...)
var stdoutBuffer, stderrBuffer bytes.Buffer
if holdStdout {
cmd.Stdout = &stdoutBuffer
} else {
cmd.Stdout = os.Stdout
}
if holdStderr {
cmd.Stderr = &stderrBuffer
} else {
cmd.Stderr = os.Stderr
}
if stdinContent == nil {
cmd.Stdin = os.Stdin
} else {
cmd.Stdin = bytes.NewReader(stdinContent)
}
cmd.Env = append(os.Environ(), envVars...)
err := cmd.Run()
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
return commandResult{
Status: statusTimeout,
ExitCode: exitCodeTimeout,
}, stdoutBuffer.Bytes(), stderrBuffer.Bytes()
}
var execErr *exec.Error
if errors.As(err, &execErr) {
return commandResult{
Status: statusNotFound,
ExitCode: exitCodeCommandNotFound,
}, nil, nil
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return commandResult{
Status: statusFinished,
ExitCode: exitErr.ExitCode(),
}, stdoutBuffer.Bytes(), stderrBuffer.Bytes()
}
return commandResult{
Status: statusUnknownError,
ExitCode: exitCodeError,
}, stdoutBuffer.Bytes(), stderrBuffer.Bytes()
}
return commandResult{
Status: statusFinished,
ExitCode: cmd.ProcessState.ExitCode(),
}, stdoutBuffer.Bytes(), stderrBuffer.Bytes()
}
func fib(n int) float64 {
nf := float64(n)
return math.Round((math.Pow(math.Phi, nf) - math.Pow(-math.Phi, -nf)) * invSqrt5)
}
func delayBeforeAttempt(attemptNum int, config retryConfig, rng *rand.Rand) time.Duration {
if attemptNum == 1 {
return 0
}
currFixed := config.ConstantDelay.Seconds()
currFixed += math.Pow(config.Backoff.Seconds(), float64(attemptNum-1))
if config.Fibonacci {
currFixed += fib(attemptNum - 1)
}
if currFixed > config.MaxDelay.Seconds() {
currFixed = config.MaxDelay.Seconds()
}
currRandom := config.RandomDelay.Start.Seconds() +
rng.Float64()*(config.RandomDelay.End-config.RandomDelay.Start).Seconds()
return time.Duration((currFixed + currRandom) * float64(time.Second))
}
func formatDuration(d time.Duration) string {
d = d.Round(time.Millisecond)
if d > time.Second {
//nolint:mnd
d = d.Round(100 * time.Millisecond)
}
zeroUnits := regexp.MustCompile("(^|[^0-9])(?:0h)?(?:0m)?(?:0s)?$")
s := zeroUnits.ReplaceAllString(d.String(), "$1")
if s == "" {
return "0"
}
return s
}
func retry(config retryConfig, stdinContent []byte, rng *rand.Rand) (int, recurStats, error) {
var stats recurStats
var cmdResult commandResult
var stdoutContent, stderrContent []byte
var startTime time.Time
var totalTime time.Duration
stats.CommandFound = make([]bool, 0)
stats.ConditionResults = make([]bool, 0)
stats.ExitCodes = make([]int, 0)
stats.WaitTimes = make([]time.Duration, 0)
resetAttemptNum := 1
for attemptNum := 1; config.MaxAttempts < 0 || attemptNum <= config.MaxAttempts; attemptNum++ {
attemptSinceReset := attemptNum - resetAttemptNum + 1
delay := delayBeforeAttempt(attemptSinceReset, config, rng)
stats.WaitTimes = append(stats.WaitTimes, delay)
if delay > 0 {
if config.Verbose >= verboseLevelAttemptResults {
log.Printf("waiting %s after attempt %d", formatDuration(delay), attemptNum-1)
}
time.Sleep(delay)
}
attemptStart := time.Now()
if startTime.IsZero() {
startTime = attemptStart
}
envVars := []string{
fmt.Sprintf("%s=%d", envVarAttempt, attemptNum),
fmt.Sprintf("%s=%d", envVarAttemptSinceReset, attemptSinceReset),
fmt.Sprintf("%s=%d", envVarMaxAttempts, config.MaxAttempts),
}
cmdResult, stdoutContent, stderrContent = executeCommand(config.Command, config.Args, config.Timeout, envVars, stdinContent, config.HoldStdout, config.HoldStderr)
attemptEnd := time.Now()
attemptDuration := attemptEnd.Sub(attemptStart)
totalTime = attemptEnd.Sub(startTime)
stats.ExitCodes = append(stats.ExitCodes, cmdResult.ExitCode)
stats.CommandFound = append(stats.CommandFound, cmdResult.Status != statusNotFound)
if config.Reset >= 0 && attemptDuration >= config.Reset {
resetAttemptNum = attemptNum
}
if config.Verbose >= verboseLevelAttemptResults {
switch cmdResult.Status {
case statusFinished:
log.Printf("command exited with code %d on attempt %d", cmdResult.ExitCode, attemptNum)
case statusTimeout:
log.Printf("command timed out after %s on attempt %d", formatDuration(attemptDuration), attemptNum)
case statusNotFound:
log.Printf("command was not found on attempt %d", attemptNum)
case statusUnknownError:
log.Printf("unknown error occurred on attempt %d", attemptNum)
}
}
attemptInfo := attempt{
CommandFound: cmdResult.Status != statusNotFound,
Duration: attemptDuration,
ExitCode: cmdResult.ExitCode,
MaxAttempts: config.MaxAttempts,
Number: attemptNum,
NumberSinceReset: attemptSinceReset,
TotalTime: totalTime,
}
evalResult, err := evaluateCondition(attemptInfo, config.Condition, config.ConditionFile, stdinContent, stdoutContent, stderrContent, config.ReplayStdin, config.HoldStdout, config.HoldStderr)
if evalResult.FlushStdout {
os.Stdout.Write(stdoutContent)
}
if evalResult.FlushStderr {
os.Stderr.Write(stderrContent)
}
stats.Attempts = attemptNum
if err != nil {
var exitErr *exitRequestError
if errors.As(err, &exitErr) {
return exitErr.Code, stats, nil
}
return 1, stats, fmt.Errorf("condition evaluation failed: %w", err)
}
stats.ConditionResults = append(stats.ConditionResults, evalResult.Success)
if evalResult.Success {
stats.Successes++
return cmdResult.ExitCode, stats, nil
}
stats.Failures++
if config.Verbose >= verboseLevelConditionDetails {
log.Printf("condition not met; continuing to next attempt")
}
}
stats.TotalTime = totalTime
return cmdResult.ExitCode, stats, fmt.Errorf("maximum %d attempts reached", config.MaxAttempts)
}
func wrapForTerm(s string) string {
width, _, err := term.GetSize(int(os.Stdin.Fd()))
if err != nil {
return s
}
return wordwrap.WrapString(s, uint(width))
}
func usage(w io.Writer) {
s := fmt.Sprintf(
`Usage: %s [-h] [-V] [-a <attempts>] [-b <backoff>] [-C <path>] [-c <condition>] [-d <delay>] [-E] [-F] [-I] [-j <jitter>] [-m <max-delay>] [-O] [-R <path>] [-r <reset-time>] [-s <seed>] [-T] [-t <timeout>] [-u] [-v] [--] <command> [<arg> ...]`,
filepath.Base(os.Args[0]),
)
fmt.Fprintln(w, wrapForTerm(s))
}
func singleQuote(s string) string {
if s == "" {
return "''"
}
valid := regexp.MustCompile("^[A-Za-z0-9_-]+$")
if valid.MatchString(s) {
return s
}
return "'" + s + "'"
}
func help() {
usage(os.Stdout)
s := fmt.Sprintf(
`
Retry a command with exponential backoff and jitter.
Arguments:
<command>
Command to run
[<arg> ...]
Arguments to the command
Options:
-h, --help
Print this help message and exit
-V, --version
Print version number and exit
-a, --attempts %v
Maximum number of attempts (negative for unlimited)
-b, --backoff %v
Base for exponential backoff (duration)
-C, --condition-file %v
Success condition Starlark source file (file path or '' to disable)
-c, --condition %v
Success condition (Starlark expression)
-d, --delay %v
Constant delay (duration)
-E, --hold-stderr
Buffer standard error for each attempt and only print it on success
-F, --fib
Add Fibonacci backoff
-I, --replay-stdin
Read standard input until EOF at the start and replay it on each attempt
-j, --jitter %v
Additional random delay (maximum duration or 'min,max' duration)
-m, --max-delay %v
Maximum allowed sum of constant delay, exponential backoff, and Fibonacci backoff (duration)
-O, --hold-stdout
Buffer standard output for each attempt and only print it on success
-R, --report %v
Report output (file path, '-' for stderr, or '' to disable; prefix with 'json:' or 'text:' to override the format)
-r, --reset %v
Minimum attempt time that resets exponential and Fibonacci backoff (duration; negative for no reset)
-s, --seed %v
Random seed for jitter (0 for automatic)
-T, --date-time
Print date-time per RFC 3339 instead of elapsed time in verbose mode
-t, --timeout %v
Timeout for each attempt (duration; negative for no timeout)
-u, --unlimited, -f, --forever
Unlimited attempts
-v, --verbose
Increase verbosity (up to %v times)
`,
maxAttemptsDefault,
formatDuration(backoffDefault),
singleQuote(conditionFileDefault),
singleQuote(conditionDefault),
formatDuration(delayDefault),
singleQuote(jitterDefault),
formatDuration(maxDelayDefault),
singleQuote(reportDefault),
formatDuration(resetDefault),
randomSeedDefault,
formatDuration(timeoutDefault),
verboseLevelMax,
)
fmt.Print(wrapForTerm(s))
}
func parseArgs() retryConfig {
config := retryConfig{
Args: []string{},
Backoff: backoffDefault,
Command: "",
Condition: conditionDefault,
ConditionFile: "",
ConstantDelay: delayDefault,
DateTime: false,
Fibonacci: false,
HoldStderr: false,
HoldStdout: false,
MaxAttempts: maxAttemptsDefault,
MaxDelay: maxDelayDefault,
RandomDelay: interval{Start: 0, End: 0},
RandomSeed: randomSeedDefault,
ReplayStdin: false,
Reset: resetDefault,
Timeout: timeoutDefault,
Verbose: 0,
Report: reportConfig{Format: reportFormatNone, Path: ""},
}
usageError := func(message string, badValue any) {
usage(os.Stderr)
fmt.Fprintf(os.Stderr, "\nError: "+message+"\n", badValue)
os.Exit(exitCodeBadUsage)
}
vShortFlags := regexp.MustCompile("^-v+$")
// Parse the command-line options.
var i int
printHelp := false
printVersion := false
conditionSet := false
conditionFileSet := false
nextArg := func(flag string) string {
i++
if i >= len(os.Args) {
usageError("no value for option: %s", flag)
}
return os.Args[i]
}
for i = 1; i < len(os.Args); i++ {
arg := os.Args[i]
if arg == "--" {
i++
break
}
if !strings.HasPrefix(arg, "-") {
break
}
switch arg {
case "-a", "--attempts":
value := nextArg(arg)
maxAttempts, err := strconv.Atoi(value)
if err != nil {
usageError("invalid maximum number of attempts: %v", value)
}
config.MaxAttempts = maxAttempts
case "-b", "--backoff":
value := nextArg(arg)
backoff, err := time.ParseDuration(value)
if err != nil {
usageError("invalid backoff: %v", value)
}
config.Backoff = backoff
case "-c", "--condition":
config.Condition = nextArg(arg)
config.ConditionFile = ""
conditionSet = true
case "-C", "--condition-file":
config.Condition = ""
config.ConditionFile = nextArg(arg)
conditionFileSet = true
case "-d", "--delay":
value := nextArg(arg)
delay, err := time.ParseDuration(value)
if err != nil {
usageError("invalid delay: %v", value)
}
config.ConstantDelay = delay
if config.MaxDelay < config.ConstantDelay {
config.MaxDelay = config.ConstantDelay
}
case "-E", "--hold-stderr":
config.HoldStderr = true
case "-F", "--fib":
config.Fibonacci = true
case "-h", "--help":
printHelp = true
case "-I", "--replay-stdin":
config.ReplayStdin = true
case "-j", "--jitter":
jitter, err := parseInterval(nextArg(arg))
if err != nil {
usageError("invalid jitter: %v", err)
}
config.RandomDelay = jitter
case "-m", "--max-delay":
value := nextArg(arg)
maxDelay, err := time.ParseDuration(value)
if err != nil {
usageError("invalid maximum delay: %v", value)
}
config.MaxDelay = maxDelay
case "-O", "--hold-stdout":
config.HoldStdout = true
case "-R", "--report":
reportStr := nextArg(arg)
report := parseReportConfig(reportStr)
config.Report = report
case "-r", "--reset":
value := nextArg(arg)
reset, err := time.ParseDuration(value)
if err != nil {
usageError("invalid reset time: %v", value)
}
config.Reset = reset
case "-s", "--seed":
value := nextArg(arg)
seed, err := strconv.ParseUint(value, 10, 64)
if err != nil {
usageError("invalid random seed: %v", value)
}
config.RandomSeed = seed
case "-T", "--date-time":
config.DateTime = true
case "-t", "--timeout":
value := nextArg(arg)
timeout, err := time.ParseDuration(value)
if err != nil {
usageError("invalid timeout: %v", value)
}
config.Timeout = timeout
case "-u", "--unlimited", "-f", "--forever":
config.MaxAttempts = -1
case "-V", "--version":
printVersion = true
// "-v" is handled in the default case.
case "--verbose":
config.Verbose++
default:
if vShortFlags.MatchString(arg) {
config.Verbose += len(arg) - 1
continue
}
usageError("unknown option: %v", arg)
}
}
if printHelp {
help()
os.Exit(0)
}
if printVersion {
fmt.Printf("%s\n", version)
os.Exit(0)
}
if conditionSet && conditionFileSet {
usageError("-C/--condition-file and -c/--condition are mutually exclusive%v", "")
}
if config.Verbose > verboseLevelMax {
usageError("up to %d verbose options is allowed", verboseLevelMax)
}
if i >= len(os.Args) {
usageError("<command> is required%v", "")
}
config.Command = os.Args[i]
config.Args = os.Args[i+1:]
return config
}
func formatList[T any](list []T) string {
strs := make([]string, len(list))
for i, elem := range list {
rv := reflect.ValueOf(elem)
switch rv.Kind() {
case reflect.Float64, reflect.Float32:
strs[i] = fmt.Sprintf(reportSecondsFormat, rv.Float())
default:
strs[i] = fmt.Sprintf("%v", elem)
}
}
return strings.Join(strs, ", ")
}
func generateReport(stats recurStats, report reportConfig) {
if report.Format == reportFormatNone {
return
}
type reportData struct {
Attempts int `json:"attempts"`
CommandFound []bool `json:"command_found"`
ConditionMet []bool `json:"condition_met"`
ExitCodes []int `json:"exit_codes"`
Failures int `json:"failures"`
Successes int `json:"successes"`
TotalTime float64 `json:"total_time"`
WaitTimes []float64 `json:"wait_times"`
}
waitTimeSeconds := make([]float64, len(stats.WaitTimes))
for i, wt := range stats.WaitTimes {
waitTimeSeconds[i] = wt.Seconds()
}
data := reportData{
Attempts: stats.Attempts,
CommandFound: stats.CommandFound,
ConditionMet: stats.ConditionResults,
ExitCodes: stats.ExitCodes,
Failures: stats.Failures,
Successes: stats.Successes,
TotalTime: stats.TotalTime.Seconds(),
WaitTimes: waitTimeSeconds,
}
var output io.Writer
if report.Path == "-" {
output = os.Stderr
} else {
file, err := os.Create(report.Path)
if err != nil {
log.Printf("failed to create report file: %v", err)
return
}
defer file.Close()
output = file
}
switch report.Format {
case reportFormatJSON:
var jsonData []byte
var err error
if report.Path == "-" {
jsonData, err = json.Marshal(data)
} else {
jsonData, err = json.MarshalIndent(data, "", " ")
}
if err != nil {
log.Printf("failed to marshal report to JSON: %v", err)
return
}
fmt.Fprintf(output, "%s\n", string(jsonData))
case reportFormatText:
tw := tabwriter.NewWriter(output, 0, 0, reportPadding, ' ', tabwriter.AlignRight)
fmt.Fprintln(output)
fmt.Fprintf(tw, "Total attempts: \t%d\n", data.Attempts)
fmt.Fprintf(tw, "Successes: \t%d\n", data.Successes)
fmt.Fprintf(tw, "Failures: \t%d\n", data.Failures)
fmt.Fprintf(tw, "\t\n")
fmt.Fprintf(tw, "Total time: \t"+reportSecondsFormat+"\n", data.TotalTime)
fmt.Fprintf(tw, "Wait times: \t%s\n", formatList(data.WaitTimes))
fmt.Fprintf(tw, "\t\n")
fmt.Fprintf(tw, "Condition met: \t%s\n", formatList(data.ConditionMet))
fmt.Fprintf(tw, "Command found: \t%s\n", formatList(data.CommandFound))
fmt.Fprintf(tw, "Exit codes: \t%s\n", formatList(data.ExitCodes))
tw.Flush()
default:
panic("unreachable")
}
}
func main() {
config := parseArgs()
// Initialize the random number generator for jitter.
var pcg *rand.PCG
if config.RandomSeed == randomSeedDefault {
//nolint:gosec
pcg = rand.NewPCG(rand.Uint64(), rand.Uint64())
} else {
pcg = rand.NewPCG(config.RandomSeed, 0)
}
// Configure logging.
customWriter := &logWriter{
dateTime: config.DateTime,
startTime: time.Now(),
}
log.SetOutput(customWriter)
log.SetFlags(0)
var stdinContent []byte
if config.ReplayStdin {
stdinContent = []byte{}
stat, err := os.Stdin.Stat()
if err != nil {
log.Printf("failed to stat stdin: %v", err)
os.Exit(1)
}
if stat.Mode()&os.ModeCharDevice == 0 {
stdinContent, err = io.ReadAll(os.Stdin)
if err != nil {
log.Printf("failed to read stdin: %v", err)
os.Exit(1)