forked from moby/swarmkit
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
benchmark.go
107 lines (95 loc) · 2.25 KB
/
benchmark.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
package main
import (
"fmt"
"os"
"strconv"
"time"
"github.com/docker/swarmkit/api"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// Config holds the benchmarking configuration.
type Config struct {
Count uint64
Manager string
IP string
Port int
Unit time.Duration
}
// Benchmark represents a benchmark session.
type Benchmark struct {
cfg *Config
collector *Collector
}
// NewBenchmark creates a new benchmark session with the given configuration.
func NewBenchmark(cfg *Config) *Benchmark {
return &Benchmark{
cfg: cfg,
collector: NewCollector(),
}
}
// Run starts the benchmark session and waits for it to be completed.
func (b *Benchmark) Run() error {
fmt.Printf("Listening for incoming connections at %s:%d\n", b.cfg.IP, b.cfg.Port)
if err := b.collector.Listen(b.cfg.Port); err != nil {
return err
}
j, err := b.launch()
if err != nil {
return err
}
fmt.Printf("Service %s launched (%d instances)\n", j.ID, b.cfg.Count)
// Periodically print stats.
doneCh := make(chan struct{})
go func() {
for {
select {
case <-time.After(5 * time.Second):
fmt.Printf("\n%s: Progression report\n", time.Now())
b.collector.Stats(os.Stdout, time.Second)
case <-doneCh:
return
}
}
}()
fmt.Println("Collecting metrics...")
b.collector.Collect(b.cfg.Count)
doneCh <- struct{}{}
fmt.Printf("\n%s: Benchmark completed\n", time.Now())
b.collector.Stats(os.Stdout, time.Second)
return nil
}
func (b *Benchmark) spec() *api.ServiceSpec {
return &api.ServiceSpec{
Annotations: api.Annotations{
Name: "benchmark",
},
Task: api.TaskSpec{
Runtime: &api.TaskSpec_Container{
Container: &api.ContainerSpec{
Image: "alpine:latest",
Command: []string{"nc", b.cfg.IP, strconv.Itoa(b.cfg.Port)},
},
},
},
Mode: &api.ServiceSpec_Replicated{
Replicated: &api.ReplicatedService{
Replicas: b.cfg.Count,
},
},
}
}
func (b *Benchmark) launch() (*api.Service, error) {
conn, err := grpc.Dial(b.cfg.Manager, grpc.WithInsecure())
if err != nil {
return nil, err
}
client := api.NewControlClient(conn)
r, err := client.CreateService(context.Background(), &api.CreateServiceRequest{
Spec: b.spec(),
})
if err != nil {
return nil, err
}
return r.Service, nil
}