-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaitfor.go
108 lines (81 loc) · 2.01 KB
/
waitfor.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
package waitfor
import (
"bytes"
"context"
"fmt"
"os/exec"
"sync"
"github.com/cenkalti/backoff"
)
type (
Program struct {
Executable string
Args []string
Resources []string
}
Runner struct {
registry *Registry
}
)
func New(configurators ...ResourceConfig) *Runner {
r := new(Runner)
r.registry = newRegistry(configurators)
return r
}
// Resources returns resource registry
func (r *Runner) Resources() *Registry {
return r.registry
}
// Run runs resource availability tests and execute a given command
func (r *Runner) Run(ctx context.Context, program Program, setters ...Option) ([]byte, error) {
err := r.Test(ctx, program.Resources, setters...)
if err != nil {
return nil, err
}
cmd := exec.Command(program.Executable, program.Args...)
return cmd.CombinedOutput()
}
// Test tests resource availability
func (r *Runner) Test(ctx context.Context, resources []string, setters ...Option) error {
opts := newOptions(setters)
var buff bytes.Buffer
output := r.testAllInternal(ctx, resources, *opts)
for err := range output {
if err != nil {
buff.WriteString(err.Error() + ";")
}
}
if buff.Len() != 0 {
return fmt.Errorf("%s: %s", ErrWait, buff.String())
}
return nil
}
func (r *Runner) testAllInternal(ctx context.Context, resources []string, opts Options) <-chan error {
var wg sync.WaitGroup
wg.Add(len(resources))
output := make(chan error, len(resources))
for _, resource := range resources {
resource := resource
go func() {
defer wg.Done()
output <- r.testInternal(ctx, resource, opts)
}()
}
go func() {
wg.Wait()
close(output)
}()
return output
}
func (r *Runner) testInternal(ctx context.Context, resource string, opts Options) error {
rsc, err := r.registry.Resolve(resource)
if err != nil {
return err
}
b := backoff.NewExponentialBackOff()
b.InitialInterval = opts.interval
b.MaxInterval = opts.maxInterval
return backoff.Retry(func() error {
return rsc.Test(ctx)
}, backoff.WithContext(backoff.WithMaxRetries(b, opts.attempts), ctx))
}