-
Notifications
You must be signed in to change notification settings - Fork 17
/
lifecycle.go
51 lines (45 loc) · 1.07 KB
/
lifecycle.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
package grill
import (
"context"
"fmt"
"sync"
)
type LifeCycle interface {
Start(ctx context.Context) error
Stop(ctx context.Context) error
}
func StartAll(ctx context.Context, grills ...LifeCycle) error {
startFn := func(ctx context.Context, lc LifeCycle) error {
return lc.Start(ctx)
}
return doAll(ctx, startFn, grills...)
}
func StopAll(ctx context.Context, grills ...LifeCycle) error {
stopFn := func(ctx context.Context, lc LifeCycle) error {
return lc.Stop(ctx)
}
return doAll(ctx, stopFn, grills...)
}
func doAll(ctx context.Context, fn func(ctx context.Context, lc LifeCycle) error, grills ...LifeCycle) error {
wg := sync.WaitGroup{}
wg.Add(len(grills))
errChan := make(chan error, len(grills))
for _, grill := range grills {
go func(g LifeCycle, wg *sync.WaitGroup) {
defer wg.Done()
if err := fn(ctx, g); err != nil {
errChan <- err
}
}(grill, &wg)
}
wg.Wait()
close(errChan)
var errors []string
for err := range errChan {
errors = append(errors, err.Error())
}
if len(errors) > 0 {
return fmt.Errorf("%v", errors)
}
return nil
}