-
Notifications
You must be signed in to change notification settings - Fork 111
/
runner.go
352 lines (299 loc) · 9.4 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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package generator
import (
"fmt"
"hash/crc32"
"math/rand"
"strings"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/duration"
"github.com/pkg/errors"
"github.com/chef/automate/api/external/habitat"
"github.com/chef/automate/components/applications-service/pkg/nats"
uuid "github.com/chef/automate/lib/uuid4"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
log "github.com/sirupsen/logrus"
)
// Everything is hardcoded to 0.1.0 for now
const versionNumber = "0.1.0"
type RunnerConfig struct {
AuthToken string
Host string
Tick int
Verbosity int
}
type LoadGenRunner struct {
SupervisorGroups SupervisorGroupCollection
stats *RunnerStatsKeeper
}
func (r *LoadGenRunner) Run(cfg *RunnerConfig) {
logLevel := log.ErrorLevel
switch cfg.Verbosity {
case 0:
case 1:
logLevel = log.InfoLevel
default:
logLevel = log.DebugLevel
}
log.SetLevel(logLevel)
fmt.Print(r.SupervisorGroups.RollupStats())
for _, supGroup := range r.SupervisorGroups {
fmt.Print(supGroup.PrettyStr())
}
r.stats = NewStatsKeeper()
go r.stats.RunCollectAndPrintLoop()
for _, g := range r.SupervisorGroups {
g.Run(cfg, r.stats)
}
}
type SupervisorGroupCollection []*SupervisorGroup
func (s SupervisorGroupCollection) ReScaleTo(svcCount int32) {
if svcCount == 0 {
return
}
currentTotal := s.TotalSvcs()
scaleFactor := svcCount / currentTotal
for _, supGroup := range s {
supGroup.Count = supGroup.Count * scaleFactor
}
}
func (s SupervisorGroupCollection) RollupStats() string {
var b strings.Builder
headerStr := fmt.Sprintf("Totals")
fmt.Fprintln(&b, headerStr)
fmt.Fprintln(&b, strings.Repeat("=", len(headerStr)))
fmt.Fprintf(&b, "Supervisor groups: %d\n", len(s))
fmt.Fprintf(&b, "Total Supervisors: %d\n", s.TotalSups())
fmt.Fprintf(&b, "Total Services: %d\n", s.TotalSvcs())
fmt.Fprintf(&b, "HealthCheck rate/s: %.2f\n", s.HealthCheckRate())
fmt.Fprintln(&b, "")
return b.String()
}
func (s SupervisorGroupCollection) TotalSups() int32 {
var total int32
for _, supGroup := range s {
total += supGroup.Count
}
return total
}
func (s SupervisorGroupCollection) TotalSvcs() int32 {
var total int32
for _, supGroup := range s {
total += supGroup.Count * int32(len(supGroup.MessagePrototypes))
}
return total
}
// Have to assume a default RunnerConfig.Tick of 30s here.
func (s SupervisorGroupCollection) HealthCheckRate() float64 {
return float64(s.TotalSvcs()) / float64(30)
}
type SupervisorGroup struct {
Name string
Count int32
MessagePrototypes []*MessagePrototype
}
func (s *SupervisorGroup) PrettyStr() string {
var b strings.Builder
headerStr := fmt.Sprintf("Supervisor group: %s", s.Name)
fmt.Fprintln(&b, headerStr)
fmt.Fprintln(&b, strings.Repeat("=", len(headerStr)))
fmt.Fprintf(&b, "- Simulated supervisors: %d\n", s.Count)
fmt.Fprintf(&b, "- Services per supervisor: %d\n", len(s.MessagePrototypes))
fmt.Fprintln(&b, "")
for _, m := range s.MessagePrototypes {
fmt.Fprintln(&b, m.PrettyStr())
}
return b.String()
}
func (s *SupervisorGroup) Run(cfg *RunnerConfig, stats *RunnerStatsKeeper) {
for n := int32(0); n < s.Count; n++ {
log.WithFields(log.Fields{"name": s.Name, "index": n}).Info("spawning supervisor")
sup, err := s.NewSup(n, cfg, stats) // nolint: errcheck
if err != nil {
log.WithError(err).Error("failed to spawn supervisor")
continue
}
err = sup.Connect()
if err != nil {
log.WithError(err).Error("failed to spawn supervisor")
continue
}
go sup.Run()
}
}
func (s *SupervisorGroup) NewSup(n int32, cfg *RunnerConfig, stats *RunnerStatsKeeper) (*SupSim, error) {
uuid, err := uuid.NewV4()
if err != nil {
log.WithError(err).Error("Failed to make a V4 UUID")
return nil, err
}
sup := &SupSim{
Name: s.Name,
UUID: uuid,
Cfg: cfg,
MessagePrototypes: s.MessagePrototypes,
Stats: stats,
}
return sup, nil
}
type SupSim struct {
Name string
Idx int32
Cfg *RunnerConfig
UUID uuid.UUID
MessagePrototypes []*MessagePrototype
Stats *RunnerStatsKeeper
nc *nats.NatsClient
}
func (s *SupSim) Connect() error {
var (
url = fmt.Sprintf("nats://%s@%s:4222", s.Cfg.AuthToken, s.Cfg.Host)
cluster = "event-service"
client = fmt.Sprintf("load-generator-%s", s.UUID)
durable = client
subject = "habitat"
)
s.nc = nats.NewExternalClient(url, cluster, client, durable, subject)
s.nc.InsecureSkipVerify = true
return s.nc.Connect()
}
func (s *SupSim) Run() {
s.Stats.SupStarted()
defer s.Stats.SupDied()
defer s.nc.Close()
// run loadgen loop
log.WithFields(log.Fields{"name": s.Name, "index": s.Idx, "uuid": s.UUID.String()}).Info("starting supervisor")
// the ticker always waits its full time before publishing. Also we wish to
// splay out the simulated sups for a more even distribution of messages. So
// we get a random splay, publish once, then loop.
splay := rand.Int31n(int32(s.Cfg.Tick))
time.Sleep(time.Duration(splay) * time.Second)
s.PublishAll() // nolint: errcheck
ticker := time.NewTicker(time.Duration(s.Cfg.Tick) * time.Second)
for range ticker.C {
s.PublishAll() // nolint: errcheck
}
}
func (s *SupSim) PublishAll() error {
log.WithFields(log.Fields{
"name": s.Name,
"index": s.Idx,
"uuid": s.UUID.String(),
"service_count": len(s.MessagePrototypes),
}).Info("publishing messages")
for _, m := range s.MessagePrototypes {
msg := m.CreateMessage(s.UUID.String())
log.WithFields(log.Fields{
"name": s.Name,
"index": s.Idx,
"uuid": s.UUID.String(),
"service_count": len(s.MessagePrototypes),
"pkg_fqid": m.PkgFQID(),
}).Debug("publishing messages")
err := s.nc.PublishHabEvent(msg)
if err != nil {
s.Stats.FailedPublish()
return err
}
s.Stats.SuccessfulPublish()
}
return nil
}
// Data elements of a message that currently exist:
// sup-id AUTO
// group hardcode to "default"
// application assign per-service in sup template
// environment <name> The environment name of the current deployment
// health hardcode to 0 (OK) for now.
// status hardcode to 0 (RUNNING) for now
//
// Package Identifier
// --origin parse from service name
// --name parse from service name
// --version hardcode to 1.0.0 for now
// --release generate from the startup time of the generator
type MessagePrototype struct {
Application string
Environment string
Channel string
Site string
Origin string
PkgName string
Release string
}
func (m *MessagePrototype) SetRelease() {
m.Release = now.Format("20060102150405")
}
func (m *MessagePrototype) ApplySvcTemplate(t ServiceTemplate) error {
parts := strings.Split(t.Package, "/")
if len(parts) != 2 {
return errors.Errorf("failed to parse package name %q into origin/package components", t.Package)
}
m.Origin = parts[0]
m.PkgName = parts[1]
m.Application = t.Application
return nil
}
func (m *MessagePrototype) ApplySupCfg(s SupervisorCfg) {
m.Environment = s.Environment
m.Channel = s.Channel
m.Site = s.Site
}
func (m *MessagePrototype) CreateMessage(uuid string) *habitat.HealthCheckEvent {
return &habitat.HealthCheckEvent{
ServiceMetadata: &habitat.ServiceMetadata{
PackageIdent: m.PkgFQID(),
ServiceGroup: fmt.Sprintf("%s.default", m.PkgName),
UpdateConfig: &habitat.UpdateConfig{
Strategy: habitat.UpdateStrategy_AtOnce,
Channel: "stable",
},
},
EventMetadata: &habitat.EventMetadata{
SupervisorId: uuid,
OccurredAt: ptypes.TimestampNow(),
Application: m.Application,
Environment: m.Environment,
Fqdn: fmt.Sprintf("%s.example", uuid),
Site: "test",
},
Result: healthCheck99PercentOk(uuid, m.PkgName),
Execution: &duration.Duration{},
Stdout: &wrappers.StringValue{Value: ""},
Stderr: &wrappers.StringValue{Value: ""},
ExitStatus: &wrappers.Int32Value{Value: int32(0)},
}
}
// healthCheck99PercentOk makes a random-seeming healthcheck result, which on
// average should return 99% ok results, 0.5% warning and 0.5% critical. It
// uses the time, truncated to 5 minute increments, and UUID as inputs so that
// the result will change over time for a particular service but will be stable
// for 5 minutes at a time. Very frequent changes are not a common scenario and
// also make the UI a little funky since we currently don't refresh the service
// groups list in the background.
func healthCheck99PercentOk(uuid, svcName string) habitat.HealthCheckResult {
t := time.Now().Truncate(5 * time.Minute)
s := fmt.Sprintf("%s-%s-%s", uuid, svcName, t.String())
c := crc32.ChecksumIEEE([]byte(s))
n := c % 1000
switch {
case n < 989:
return habitat.HealthCheckResult_Ok
case n < 994:
return habitat.HealthCheckResult_Warning
default:
return habitat.HealthCheckResult_Critical
}
}
func (m *MessagePrototype) PkgFQID() string {
return fmt.Sprintf("%s/%s/%s/%s", m.Origin, m.PkgName, versionNumber, m.Release)
}
func (m *MessagePrototype) PrettyStr() string {
var b strings.Builder
b.WriteString(fmt.Sprintf(" - Package: %s/%s/%s\n", m.Origin, m.PkgName, m.Release))
b.WriteString(fmt.Sprintf(" - Application: %s\n", m.Application))
b.WriteString(fmt.Sprintf(" - Environment: %s\n", m.Environment))
b.WriteString(fmt.Sprintf(" - Channel: %s\n", m.Channel))
b.WriteString(fmt.Sprintf(" - Site: %s\n", m.Site))
return b.String()
}