This repository has been archived by the owner on Apr 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathcheck_docker.go
297 lines (236 loc) · 8.72 KB
/
check_docker.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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
dockerlib "github.com/fsouza/go-dockerclient"
"github.com/newrelic/go_nagios"
"github.com/shenwei356/util/bytesize"
"strings"
"sync"
)
func NewCheckDocker(endpoint string) (*CheckDocker, error) {
var err error
cd := &CheckDocker{}
cd.WarnMetaSpace = 100 // defaults
cd.CritMetaSpace = 100
cd.WarnDataSpace = 100
cd.CritDataSpace = 100
if endpoint != "" {
err = cd.setupClient(endpoint)
}
return cd, err
}
type CheckDocker struct {
WarnMetaSpace float64
CritMetaSpace float64
WarnDataSpace float64
CritDataSpace float64
ImageId string
ContainerName string
TLSCertPath string
TLSKeyPath string
TLSCAPath string
dockerclient *dockerlib.Client
dockerInfoData *dockerlib.Env
dockerContainersData []dockerlib.APIContainers
}
func (cd *CheckDocker) setupClient(endpoint string) error {
var err error
if cd.TLSCertPath != "" && cd.TLSKeyPath != "" && cd.TLSCAPath != "" {
cd.dockerclient, err = dockerlib.NewTLSClient(endpoint, cd.TLSCertPath, cd.TLSKeyPath, cd.TLSCAPath)
} else {
cd.dockerclient, err = dockerlib.NewClient(endpoint)
}
return err
}
func (cd *CheckDocker) GetData() error {
errChan := make(chan error)
var err error
var wg sync.WaitGroup
wg.Add(2)
go func(cd *CheckDocker, errChan chan error) {
defer wg.Done()
cd.dockerInfoData, err = cd.dockerclient.Info()
if err != nil {
errChan <- err
}
}(cd, errChan)
go func(cd *CheckDocker, errChan chan error) {
defer wg.Done()
cd.dockerContainersData, err = cd.dockerclient.ListContainers(dockerlib.ListContainersOptions{})
if err != nil {
errChan <- err
}
}(cd, errChan)
go func() {
wg.Wait()
close(errChan)
}()
err = <-errChan
return err
}
func (cd *CheckDocker) getByteSizeDriverStatus(key string) (bytesize.ByteSize, error) {
var statusInArray [][]string
err := json.Unmarshal([]byte(cd.dockerInfoData.Get("DriverStatus")), &statusInArray)
if err != nil {
return -1, errors.New("Unable to extract DriverStatus info.")
}
for _, status := range statusInArray {
if status[0] == key {
return bytesize.Parse([]byte(status[1]))
}
}
return -1, errors.New(fmt.Sprintf("DriverStatus does not contain \"%v\"", key))
}
func (cd *CheckDocker) GetDataSpaceUsed() (bytesize.ByteSize, error) {
return cd.getByteSizeDriverStatus("Data Space Used")
}
func (cd *CheckDocker) GetDataSpaceTotal() (bytesize.ByteSize, error) {
return cd.getByteSizeDriverStatus("Data Space Total")
}
func (cd *CheckDocker) GetMetaSpaceUsed() (bytesize.ByteSize, error) {
return cd.getByteSizeDriverStatus("Metadata Space Used")
}
func (cd *CheckDocker) GetMetaSpaceTotal() (bytesize.ByteSize, error) {
return cd.getByteSizeDriverStatus("Metadata Space Total")
}
func (cd *CheckDocker) IsContainerRunning(imageId string) (dockerlib.APIContainers, bool) {
for _, container := range cd.dockerContainersData {
if strings.HasPrefix(container.Image, imageId) && strings.HasPrefix(container.Status, "Up") {
return container, true
}
}
return dockerlib.APIContainers{}, false
}
func (cd *CheckDocker) IsNamedContainerRunning(containerName string) (dockerlib.APIContainers, bool) {
for _, container := range cd.dockerContainersData {
for _, name := range container.Names {
// Container names start with a slash for some reason, maybe a bug?
// Remove the leading / only if it's found so this doesn't break in
// the future.
if strings.HasPrefix(name, "/") {
name = name[1:]
}
if name == containerName {
if strings.HasPrefix(container.Status, "Up") {
return container, true
} else {
return dockerlib.APIContainers{}, false
}
}
}
}
return dockerlib.APIContainers{}, false
}
func (cd *CheckDocker) IsContainerAGhost(imageId string) (dockerlib.APIContainers, bool) {
for _, container := range cd.dockerContainersData {
if strings.HasPrefix(container.Image, imageId) && strings.Contains(container.Status, "Ghost") {
return container, true
}
}
return dockerlib.APIContainers{}, false
}
func (cd *CheckDocker) CheckMetaSpace(warnThreshold, criticalThreshold float64) *nagios.NagiosStatus {
usedByteSize, err := cd.GetMetaSpaceUsed()
if err != nil {
return &nagios.NagiosStatus{err.Error(), nagios.NAGIOS_CRITICAL}
}
totalByteSize, err := cd.GetMetaSpaceTotal()
if err != nil {
return &nagios.NagiosStatus{err.Error(), nagios.NAGIOS_CRITICAL}
}
percentUsed := float64(usedByteSize/totalByteSize) * 100
status := &nagios.NagiosStatus{fmt.Sprintf("Metadata Space Usage: %f", percentUsed) + "%", nagios.NAGIOS_OK}
if percentUsed >= warnThreshold {
status.Value = nagios.NAGIOS_WARNING
}
if percentUsed >= criticalThreshold {
status.Value = nagios.NAGIOS_CRITICAL
}
return status
}
func (cd *CheckDocker) CheckDataSpace(warnThreshold, criticalThreshold float64) *nagios.NagiosStatus {
usedByteSize, err := cd.GetDataSpaceUsed()
if err != nil {
return &nagios.NagiosStatus{err.Error(), nagios.NAGIOS_CRITICAL}
}
totalByteSize, err := cd.GetDataSpaceTotal()
if err != nil {
return &nagios.NagiosStatus{err.Error(), nagios.NAGIOS_CRITICAL}
}
percentUsed := float64(usedByteSize/totalByteSize) * 100
status := &nagios.NagiosStatus{fmt.Sprintf("Data Space Usage: %f", percentUsed) + "%", nagios.NAGIOS_OK}
if percentUsed >= warnThreshold {
status.Value = nagios.NAGIOS_WARNING
}
if percentUsed >= criticalThreshold {
status.Value = nagios.NAGIOS_CRITICAL
}
return status
}
func (cd *CheckDocker) CheckImageContainerIsInGoodShape(imageId string) *nagios.NagiosStatus {
containerRunning, isRunning := cd.IsContainerRunning(imageId)
containerGhost, isGhost := cd.IsContainerAGhost(imageId)
if !isRunning {
return &nagios.NagiosStatus{fmt.Sprintf("Container of image: %v is not running.", imageId), nagios.NAGIOS_CRITICAL}
}
if isGhost {
return &nagios.NagiosStatus{fmt.Sprintf("Container(ID: %v) of image: %v is in ghost state.", containerGhost.ID, imageId), nagios.NAGIOS_CRITICAL}
}
return &nagios.NagiosStatus{fmt.Sprintf("Container(ID: %v) of image: %v is in top shape.", containerRunning.ID, imageId), nagios.NAGIOS_OK}
}
func (cd *CheckDocker) CheckNamedContainerIsInGoodShape(containerName string) *nagios.NagiosStatus {
container, isRunning := cd.IsNamedContainerRunning(containerName)
_, isGhost := cd.IsContainerAGhost(container.ID)
if !isRunning {
return &nagios.NagiosStatus{fmt.Sprintf("Container named: %v is not running.", containerName), nagios.NAGIOS_CRITICAL}
}
if isGhost {
return &nagios.NagiosStatus{fmt.Sprintf("Container(ID: %v) named: %v is in ghost state.", container.ID, containerName), nagios.NAGIOS_CRITICAL}
}
return &nagios.NagiosStatus{fmt.Sprintf("Container(ID: %v) named: %v is in top shape.", container.ID, containerName), nagios.NAGIOS_OK}
}
func main() {
cd, err := NewCheckDocker("")
if err != nil {
nagios.Critical(err)
}
var dockerEndpoint string
flag.StringVar(&dockerEndpoint, "base-url", "http://localhost:2375", "The Base URL for the Docker server")
flag.Float64Var(&cd.WarnMetaSpace, "warn-meta-space", 100, "Warning threshold for Metadata Space")
flag.Float64Var(&cd.CritMetaSpace, "crit-meta-space", 100, "Critical threshold for Metadata Space")
flag.Float64Var(&cd.WarnDataSpace, "warn-data-space", 100, "Warning threshold for Data Space")
flag.Float64Var(&cd.CritDataSpace, "crit-data-space", 100, "Critical threshold for Data Space")
flag.StringVar(&cd.ImageId, "image-id", "", "An image ID that must be running on the Docker server")
flag.StringVar(&cd.ContainerName, "container-name", "", "The name of a container that must be running on the Docker server")
flag.StringVar(&cd.TLSCertPath, "tls-cert", "", "Path to TLS cert file.")
flag.StringVar(&cd.TLSKeyPath, "tls-key", "", "Path to TLS key file.")
flag.StringVar(&cd.TLSCAPath, "tls-ca", "", "Path to TLS CA file.")
flag.Parse()
err = cd.setupClient(dockerEndpoint)
if err != nil {
nagios.Critical(err)
}
err = cd.GetData()
if err != nil {
nagios.Critical(err)
}
baseStatus := &nagios.NagiosStatus{fmt.Sprintf("Total Containers: %v", len(cd.dockerContainersData)), nagios.NAGIOS_OK}
statuses := make([]*nagios.NagiosStatus, 0)
driver := cd.dockerInfoData.Get("Driver")
// Unfortunately, Metadata Space and Data Space information is only available on devicemapper
if driver == "devicemapper" {
statuses = append(statuses, cd.CheckMetaSpace(cd.WarnMetaSpace, cd.CritMetaSpace))
statuses = append(statuses, cd.CheckDataSpace(cd.WarnDataSpace, cd.CritDataSpace))
}
if cd.ImageId != "" {
statuses = append(statuses, cd.CheckImageContainerIsInGoodShape(cd.ImageId))
}
if cd.ContainerName != "" {
statuses = append(statuses, cd.CheckNamedContainerIsInGoodShape(cd.ContainerName))
}
baseStatus.Aggregate(statuses)
nagios.ExitWithStatus(baseStatus)
}