-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathnode.go
95 lines (78 loc) · 1.6 KB
/
node.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
package slb
import (
"bytes"
"fmt"
"math"
)
type node struct {
host string
index int
pending int
}
func newNode(host string, index int) *node {
return &node{
host: host,
pending: 0,
index: index,
}
}
type nodes []*node
func newNodes(hosts []string) nodes {
pool := make(nodes, len(hosts))
for i, url := range hosts {
pool[i] = newNode(url, i)
}
return pool
}
func (n nodes) Len() int {
return len(n)
}
func (n nodes) Less(i, j int) bool {
return n[i].pending < n[j].pending
}
func (n nodes) Swap(i, j int) {
n[i], n[j] = n[j], n[i]
n[i].index = i
n[j].index = j
}
func (n *nodes) Push(x interface{}) {
node := x.(*node)
node.index = n.Len()
*n = append(*n, node)
}
func (n *nodes) Pop() interface{} {
nodes := *n
last := n.Len() - 1
node := nodes[last]
*n = nodes[:last]
return node
}
func (n nodes) String() string {
var output bytes.Buffer
output.WriteString("\nHost with pending tasks: \n")
for _, node := range n {
str := fmt.Sprintf("%+v\n", *node)
output.WriteString(str)
}
output.WriteString("\n")
mean := n.mean()
stdDev := n.standardDeviation()
stats := fmt.Sprintf("Avg Load: %.2f | Std Dev: %.2f\n", mean, stdDev)
output.WriteString(stats)
return output.String()
}
func (n nodes) mean() (mean float64) {
length := float64(len(n))
for _, server := range n {
mean += float64(server.pending)
}
return mean / length
}
func (n nodes) standardDeviation() (stdDev float64) {
length := float64(len(n))
mean := n.mean()
for _, server := range n {
stdDev += math.Pow((float64(server.pending) - mean), 2)
}
return math.Sqrt((1 / length) * stdDev)
}