-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
112 lines (100 loc) · 2.35 KB
/
service.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
110
111
112
package loaderbot
import (
"bytes"
"context"
"encoding/gob"
"log"
"net"
"sync"
"sync/atomic"
jsoniter "github.com/json-iterator/go"
"google.golang.org/grpc"
)
// TestPolicy only one runner is allowed per node
type TestPolicy struct {
*sync.Mutex
busy bool
}
func (m *TestPolicy) isBusy() bool {
m.Lock()
defer m.Unlock()
return m.busy
}
func (m *TestPolicy) setBusy(b bool) {
m.Lock()
defer m.Unlock()
m.busy = b
}
type server struct {
policy *TestPolicy
runnerCancelFunc context.CancelFunc
UnimplementedLoaderServer
}
func (r *Runner) streamResults(srv Loader_RunServer) {
for chunk := range r.OutResults {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
err := enc.Encode(chunk)
if err != nil {
r.L.Error(err)
}
if err := srv.Send(&ResultsResponse{ResultsChunk: b.Bytes()}); err != nil {
r.L.Error(err)
}
// send last tick batch and shutdown, other nodes will be cancelled by client
if atomic.LoadInt64(&r.Failed) == 1 {
r.L.Infof("runner failed, exiting")
r.CancelFunc()
}
}
}
func (s *server) Status(_ context.Context, _ *StatusRequest) (*StatusResponse, error) {
return &StatusResponse{
Busy: s.policy.isBusy(),
}, nil
}
// Run starts Runner and stream Results back to cluster client
func (s *server) Run(req *RunConfigRequest, srv Loader_RunServer) error {
if s.policy.isBusy() {
return nil
}
s.policy.setBusy(true)
cfg := UnmarshalConfigGob(req.Config)
r := NewRunner(&cfg, AttackerFromString(cfg.InstanceType), nil)
cfgJson, _ := jsoniter.MarshalIndent(cfg, "", " ")
r.L.Infof("running task: %s", cfgJson)
var ctx context.Context
ctx, s.runnerCancelFunc = context.WithCancel(context.Background())
go func() {
_, _ = r.Run(ctx)
}()
r.streamResults(srv)
s.policy.setBusy(false)
return nil
}
func (s *server) ShutdownNode(_ context.Context, _ *ShutdownNodeRequest) (*ShutdownNodeResponse, error) {
if s.runnerCancelFunc != nil {
s.runnerCancelFunc()
}
return &ShutdownNodeResponse{}, nil
}
func RunService(addr string) *grpc.Server {
lis, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
s := grpc.NewServer()
RegisterLoaderServer(s, &server{
policy: &TestPolicy{
Mutex: &sync.Mutex{},
busy: false,
},
})
log.Printf("running node on: %s", addr)
go func() {
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
return s
}