-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
271 lines (234 loc) · 6.13 KB
/
main.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
/// docker-stats-dump by andrzej lichnerowicz, unlicensed (~public domain)
/// program uses API v1.33 https://docs.docker.com/engine/api/v1.33/
package main
import (
"bufio"
"context"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"text/template"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/go-units"
flag "github.com/spf13/pflag"
)
func getDockerContainerStats(context context.Context, client *client.Client, stat chan<- Stats, container types.Container) error {
response, err := client.ContainerStats(context, container.ID, true)
if err != nil {
return err
}
reader := bufio.NewReader(response.Body)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
return fmt.Errorf("Stream finished")
}
var dockerStats types.Stats
json.Unmarshal(line, &dockerStats)
stat <- Stats{container: container, stats: dockerStats, os: response.OSType}
}
}
// Stats .
type Stats struct {
container types.Container
stats types.Stats
os string
}
type CalculatedStats struct {
OS string
ID string
Name string
Image string
CpuPercentage float64
Memory float64
MemoryLimit float64
MemoryPercentage float64
}
func (cs *CalculatedStats) Strings(isHumanReadable bool) []string {
var t []string
t = append(t, cs.OS)
t = append(t, cs.ID[:10])
t = append(t, strings.TrimLeft(cs.Name, "/"))
t = append(t, cs.Image)
if isHumanReadable {
t = append(t, fmt.Sprintf("%.2f%%", cs.CpuPercentage))
t = append(t, units.BytesSize(cs.Memory))
t = append(t, units.BytesSize(cs.MemoryLimit))
t = append(t, fmt.Sprintf("%.2f%%", cs.MemoryPercentage))
} else {
t = append(t, fmt.Sprintf("%.2f", cs.CpuPercentage))
t = append(t, fmt.Sprintf("%.2f", cs.Memory))
t = append(t, fmt.Sprintf("%.2f", cs.MemoryLimit))
t = append(t, fmt.Sprintf("%.2f", cs.MemoryPercentage))
}
return t
}
func Header() []string {
return []string{"os", "id", "name", "image", "cpup", "musage", "mlimit", "memp"}
}
type Options struct {
IsHumanReadable bool
Format string
CompiledTemplate *template.Template
}
func (o *Options) Init() {
flag.BoolVarP(&o.IsHumanReadable, "human-readable", "h", false, "output size numbers in IEC format")
flag.StringVarP(&o.Format, "format", "f", "table", "format for results: table (default), csv, json")
}
func (o *Options) Parse() {
flag.Parse()
switch o.Format {
case "table":
case "csv":
case "json":
default:
var err error
o.CompiledTemplate, err = template.New("format").Parse(o.Format)
if err != nil {
flag.PrintDefaults()
fmt.Println("Invalid Go template: ", err)
os.Exit(0)
}
}
}
type Writer interface {
Write(record CalculatedStats, isHumanReadable bool) error
WriteS(record []string) error
Flush()
}
type TableWriter struct {
w io.Writer
}
func NewTableWriter(w io.Writer) *TableWriter {
return &TableWriter{w}
}
func (w *TableWriter) Write(record CalculatedStats, isHumanReadable bool) error {
return w.WriteS(record.Strings(isHumanReadable))
}
func (w *TableWriter) WriteS(record []string) error {
_, err := w.w.Write([]byte(fmt.Sprintln(strings.Join(record, "\t"))))
return err
}
func (w *TableWriter) Flush() {}
type JsonWriter struct {
w *json.Encoder
}
func NewJsonWriter(w *json.Encoder) *JsonWriter {
return &JsonWriter{w}
}
func (w *JsonWriter) Write(record CalculatedStats, isHumanReadable bool) error {
return w.w.Encode(record)
}
func (w *JsonWriter) WriteS(record []string) error {
return nil
}
func (w *JsonWriter) Flush() {}
type CsvWriter struct {
w *csv.Writer
}
func NewCsvWriter(w *csv.Writer) *CsvWriter {
return &CsvWriter{w}
}
func (w *CsvWriter) Write(record CalculatedStats, isHumanReadable bool) error {
return w.WriteS(record.Strings(isHumanReadable))
}
func (w *CsvWriter) WriteS(record []string) error {
return w.w.Write(record)
}
func (w *CsvWriter) Flush() {
w.w.Flush()
}
func main() {
var options Options
options.Init()
options.Parse()
quit := make(chan error)
done := make(chan string)
stat := make(chan Stats)
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
quit <- fmt.Errorf("SIGTERM Received")
}()
cli, err := client.NewEnvClient()
if err != nil {
panic(err)
}
dockerContainerList, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
panic(err)
}
dockerMonitors := len(dockerContainerList)
for i := 0; i < len(dockerContainerList); i++ {
go func(index int) {
err := getDockerContainerStats(context.Background(), cli, stat, dockerContainerList[index])
if err != nil {
done <- dockerContainerList[index].ID
}
}(i)
}
var writer Writer
var template bool = false
switch options.Format {
case "csv":
writer = NewCsvWriter(csv.NewWriter(os.Stdout))
case "json":
writer = NewJsonWriter(json.NewEncoder(os.Stdout))
case "table":
writer = NewTableWriter(os.Stdout)
default:
template = true
}
if template {
} else {
writer.WriteS(Header())
writer.Flush()
}
for {
select {
case s := <-stat:
// TODO: Add shortened ID to the structure, so CSV output can be done as fixed template
// TODO: Trim Image in structure to use Go templates directly
// TODO: Move human readable inside structure as method
cs := CalculatedStats{
OS: s.os,
ID: s.container.ID,
Name: s.container.Names[0],
Image: s.container.Image,
CpuPercentage: CalculateCPUPercentage(s.os, s.stats),
Memory: CalculateMemoryUsage(s.os, s.stats),
MemoryLimit: CalculateMemoryLimit(s.os, s.stats),
MemoryPercentage: CalculateMemoryPercentage(s.os, s.stats),
}
var err error
if template {
err = options.CompiledTemplate.Execute(os.Stdout, cs)
os.Stdout.WriteString("\n")
} else {
err = writer.Write(cs, options.IsHumanReadable)
}
if err != nil {
panic(err)
}
if template == false {
writer.Flush()
}
case <-done:
dockerMonitors--
if dockerMonitors == 0 {
go func() {
quit <- fmt.Errorf("No monitors left")
}()
}
case <-quit:
os.Exit(0)
}
}
}