forked from sandia-minimega/minimega
/
event.go
67 lines (56 loc) · 1.5 KB
/
event.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
// Copyright (2015) Sandia Corporation.
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
package main
import (
"math/rand"
log "minilog"
"time"
)
type EventTicker struct {
mean time.Duration
stddev time.Duration
min time.Duration
max time.Duration
count uint64
}
func NewEventTicker(mean, stddev, min, max time.Duration) *EventTicker {
return &EventTicker{
mean: mean,
stddev: stddev,
min: min,
max: max,
}
}
func Milliseconds(t time.Duration) float64 {
msec := t.Nanoseconds() / int64(time.Millisecond)
nsec := t.Nanoseconds() % int64(time.Millisecond)
return float64(msec) + float64(nsec)*(1e-9*1000)
}
func (e *EventTicker) Tick() {
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
t := time.Duration(int64(r.NormFloat64()*Milliseconds(e.stddev)+Milliseconds(e.mean)) * int64(time.Millisecond))
// truncate to min and max
if t < e.min {
t = e.min
} else if t > e.max {
t = e.max
}
log.Debug("tick time %v", t)
time.Sleep(time.Duration(t))
}
// randomHost returns a host and the original specified text from the user
// command line. Therefore, if the user specified 10.0.0.0/24, randomHost may
// return (10.0.0.200, 10.0.0.0/24).
func randomHost() (host string, original string) {
if len(hosts) == 0 || hosts == nil {
return "", ""
}
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
v := r.Intn(len(hosts))
host = keys[v]
original = hosts[host]
return
}