-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
109 lines (86 loc) · 1.88 KB
/
task.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
package qube
import (
"context"
"errors"
"os"
"os/signal"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
"golang.org/x/time/rate"
)
type Task struct {
*Options
ID string
}
func NewTask(options *Options) *Task {
task := &Task{
Options: options,
ID: uuid.NewString(),
}
return task
}
func (task *Task) makeAgents() ([]*Agent, *Recorder, error) {
agents := make([]*Agent, task.Nagents)
rec := NewRecorder(task.ID, task.Options)
var limiter *rate.Limiter
if task.Rate > 0 {
limiter = rate.NewLimiter(rate.Limit(task.Rate), 1)
}
for i := uint64(0); i < task.Nagents; i++ {
var err error
agents[i], err = NewAgent(task.ID, i, task.Options, rec, limiter)
if err != nil {
return nil, nil, err
}
}
return agents, rec, nil
}
func (task *Task) Run() (*Report, error) {
agents, rec, err := task.makeAgents()
if err != nil {
return nil, err
}
eg, ctx := errgroup.WithContext(context.Background())
ctx, cancel := context.WithCancel(ctx)
if task.Time > 0 {
ctx, cancel = context.WithTimeout(ctx, task.Time)
}
// Trap SIGINT
{
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
go func() {
select {
case <-ctx.Done():
// Nothing to do
case <-sigint:
// Stop query on interrupt
cancel()
eg.Wait() //nolint:errcheck
os.Exit(130)
}
}()
}
var progress = NewProgress(os.Stderr, !task.Progress || task.Noop)
fire := make(chan struct{})
for _, v := range agents {
agent := v
eg.Go(func() error {
<-fire
err := agent.Start(ctx)
progress.IncrDead()
return err
})
}
progress.Start(ctx, rec)
rec.Start()
close(fire)
err = eg.Wait()
cancel()
progress.Close() // Wait for ticker to stop
rec.Close() // Wait for buffer flush
if err != nil && !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) {
return nil, err
}
return rec.Report(), nil
}