-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
72 lines (52 loc) · 1.39 KB
/
runner.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
package runner
import (
"context"
"github.com/D3rus/go-library/closer"
"github.com/D3rus/go-library/logger"
"io"
"runtime/debug"
"sync"
"time"
)
type Runner interface {
io.Closer
AddProcesses(processes ...Process) error
}
type runner struct {
ctx context.Context
cancelFunc context.CancelFunc
wg *sync.WaitGroup
logger logger.Logger
}
func New(logger logger.Logger, closer closer.Closer) Runner {
ctx, cancelFunc := context.WithCancel(closer.GetContext())
return &runner{logger: logger, wg: &sync.WaitGroup{}, ctx: ctx, cancelFunc: cancelFunc}
}
func (runner *runner) AddProcesses(processes ...Process) error {
for _, process := range processes {
sync := make(chan struct{})
go runner.runProcess(process, sync)
<-sync
}
return nil
}
func (runner *runner) runProcess(process Process, sync chan struct{}) {
runner.wg.Add(1)
defer runner.wg.Done()
ctx, cancelFunc := context.WithCancel(runner.ctx)
defer cancelFunc()
runner.logger.Infof("runner: process '%s' running", process.Name())
go func() {
<-time.After(time.Microsecond)
sync <- struct{}{}
}()
if err := process.Process(ctx); err != nil {
runner.logger.Errorf("runner: process '%s' error: %s\n%s", process.Name(), err, debug.Stack())
}
runner.logger.Infof("runner: process '%s' shutdown", process.Name())
}
func (runner *runner) Close() error {
runner.cancelFunc()
runner.wg.Wait()
return nil
}