-
Notifications
You must be signed in to change notification settings - Fork 2
/
io.go
301 lines (247 loc) · 7.6 KB
/
io.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
package docker
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"math"
"os"
"path/filepath"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"go.dedis.ch/simnet/metrics"
"go.dedis.ch/simnet/sim"
"golang.org/x/xerrors"
)
type dockerio struct {
cli client.APIClient
stats metrics.Stats
statsLock sync.Mutex
}
func newDockerIO(cli client.APIClient) *dockerio {
return &dockerio{
cli: cli,
stats: metrics.NewStats(),
}
}
// Tag saves the tag using the current timestamp as the key. It allows the
// drawing of plots with points in time tagged.
func (dio *dockerio) Tag(name string) {
dio.statsLock.Lock()
key := time.Now().UnixNano()
dio.stats.Tags[key] = name
dio.statsLock.Unlock()
}
// Read reads a file in the container at the given path. It returns a reader
// that will eventually deliver the content of the file. The caller is
// responsible for closing the stream.
func (dio *dockerio) Read(container, path string) (io.ReadCloser, error) {
ctx := context.Background()
reader, _, err := dio.cli.CopyFromContainer(ctx, container, path)
if err != nil {
return nil, xerrors.Errorf("couldn't open stream: %v", err)
}
tr := tar.NewReader(reader)
if _, err = tr.Next(); err != nil {
return nil, xerrors.Errorf("couldn't untar: %v", err)
}
return ioutil.NopCloser(tr), nil
}
// Write writes a file in the container at the given path using the content. It
// will read until it reaches EOF and it will return an error if something bad
// has happened.
func (dio *dockerio) Write(container, path string, content io.Reader) error {
ctx := context.Background()
reader, writer := io.Pipe()
tw := tar.NewWriter(writer)
// The size needs to be known beforehands so the content is read first.
buffer := new(bytes.Buffer)
_, err := io.Copy(buffer, content)
if err != nil {
return xerrors.Errorf("failed copying data into buffer: %v", err)
}
go func() {
tw.WriteHeader(&tar.Header{
Size: int64(buffer.Len()),
})
io.Copy(tw, buffer)
writer.Close()
}()
err = dio.cli.CopyToContainer(ctx, container, path, reader, types.CopyToContainerOptions{})
if err != nil {
return xerrors.Errorf("failed copying buffer into container: %v", err)
}
return nil
}
// Exec executes a command in the container.
func (dio *dockerio) Exec(container string, cmd []string, options sim.ExecOptions) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
resp, err := dio.cli.ContainerExecCreate(ctx, container, types.ExecConfig{
AttachStdin: options.Stdin != nil,
AttachStdout: options.Stdout != nil,
AttachStderr: options.Stderr != nil,
Cmd: cmd,
})
if err != nil {
return xerrors.Errorf("couldn't create exec: %v", err)
}
msgCh, errCh := dio.cli.Events(ctx, types.EventsOptions{})
conn, err := dio.cli.ContainerExecAttach(ctx, resp.ID, types.ExecConfig{})
if err != nil {
return xerrors.Errorf("couldn't attach exec: %v", err)
}
defer conn.Close()
// We want a chance to catch errors happening when writing to the standard
// input so this channel is used to synchronized the result.
done := make(chan error, 1)
if options.Stdin != nil {
go func() {
defer close(done)
_, err := io.Copy(conn.Conn, options.Stdin)
if err != nil {
done <- err
}
conn.CloseWrite()
}()
} else {
// But ignore if the caller does not need stdin.
close(done)
}
if options.Stdout == nil {
options.Stdout = ioutil.Discard
}
if options.Stderr == nil {
options.Stderr = ioutil.Discard
}
// Docker provides a function to correctly split stdout and stderr from
// the incoming reader. The Go routine will close when the hijacked
// connection is.
go stdcopy.StdCopy(options.Stdout, options.Stderr, conn.Reader)
err = dio.cli.ContainerExecStart(ctx, resp.ID, types.ExecStartCheck{})
if err != nil {
return xerrors.Errorf("couldn't start exec: %v", err)
}
// Check if something bad happened when writing to stdin.
err, ok := <-done
if err != nil && ok {
return xerrors.Errorf("couldn't write to stdin: %v", err)
}
// Everything's good so far so let's wait for the command to be completly done
// to check the return status.
for {
select {
case msg := <-msgCh:
if msg.Status == "exec_die" && msg.Actor.Attributes["execID"] == resp.ID {
code := msg.Actor.Attributes["exitCode"]
if code != "0" {
return xerrors.Errorf("exited with %s", code)
}
return nil
}
case err := <-errCh:
return xerrors.Errorf("received error event: %w", err)
}
}
}
func (dio *dockerio) Disconnect(src string, targets ...string) error {
// TODO: implement
return nil
}
func (dio *dockerio) Reconnect(node string) error {
return nil
}
func (dio *dockerio) FetchStats(from, end time.Time, filename string) error {
dio.statsLock.Lock()
defer dio.statsLock.Unlock()
dir, _ := filepath.Split(filename)
err := os.MkdirAll(dir, 0755)
if err != nil {
return xerrors.Errorf("couldn't create directory: %v", err)
}
file, err := os.Create(filename)
if err != nil {
return xerrors.Errorf("couldn't create file: %v", err)
}
// TODO: time range
enc := json.NewEncoder(file)
err = enc.Encode(&dio.stats)
if err != nil {
return xerrors.Errorf("couldn't encode the stats: %v", err)
}
return nil
}
func (dio *dockerio) monitorContainers(ctx context.Context, containers []types.Container) (func(), error) {
dio.statsLock.Lock()
dio.stats.Timestamp = time.Now().Unix()
dio.statsLock.Unlock()
closers := make([]func(), 0, len(containers))
globalCloser := func() {
for _, closer := range closers {
closer()
}
}
for _, container := range containers {
closer, err := dio.monitorContainer(ctx, container)
if err != nil {
globalCloser()
return nil, xerrors.Errorf("couldn't listen stats: %v", err)
}
closers = append(closers, closer)
}
return globalCloser, nil
}
func (dio *dockerio) monitorContainer(ctx context.Context, container types.Container) (func(), error) {
resp, err := dio.cli.ContainerStats(ctx, container.ID, true)
if err != nil {
return nil, xerrors.Errorf("couldn't get stats: %v", err)
}
dec := json.NewDecoder(resp.Body)
ns := &metrics.NodeStats{}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for {
data := &types.StatsJSON{}
err := dec.Decode(data)
if err != nil {
wg.Done()
return
}
ns.Timestamps = append(ns.Timestamps, time.Now().Unix())
ns.RxBytes = append(ns.RxBytes, data.Networks["eth0"].RxBytes)
ns.TxBytes = append(ns.TxBytes, data.Networks["eth0"].TxBytes)
prev := data.PreCPUStats.CPUUsage.TotalUsage
prevSys := data.PreCPUStats.SystemUsage
ns.CPU = append(ns.CPU, uint64(calculateCPUPercent(prev, prevSys, data)))
ns.Memory = append(ns.Memory, data.MemoryStats.Usage)
dio.statsLock.Lock()
dio.stats.Nodes[containerName(container)] = *ns
dio.statsLock.Unlock()
}
}()
closer := func() {
resp.Body.Close()
wg.Wait()
}
return closer, nil
}
// https://github.com/moby/moby/blob/eb131c5383db8cac633919f82abad86c99bffbe5/cli/command/container/stats_helpers.go#L175-L188
func calculateCPUPercent(previousCPU, previousSystem uint64, v *types.StatsJSON) int {
var (
cpuPercent = 0.0
// calculate the change for the cpu usage of the container in between readings
cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
// calculate the change for the entire system between readings
systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
)
if systemDelta > 0.0 && cpuDelta > 0.0 {
cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
}
return int(math.Ceil(cpuPercent * 100))
}