-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheck_lxd.py
More file actions
executable file
·168 lines (137 loc) · 6.79 KB
/
Copy pathcheck_lxd.py
File metadata and controls
executable file
·168 lines (137 loc) · 6.79 KB
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
#!/usr/bin/env python3
from subprocess import check_output, CalledProcessError
from yaml import load
import argparse
# data
state = {
"unknown": 3,
"critical": 2,
"warning": 1,
"ok": 0
}
# Logic
def parser_args():
"""Parse args using argparse and subparsers. return parse_args()"""
parser = argparse.ArgumentParser(
description="""nagios plugin for check LXD containers""")
subparsers = parser.add_subparsers(dest='command')
parser_state = subparsers.add_parser('state',
help='''Check the state of the container and generate
CRITICAL state if not running''')
parser_run = subparsers.add_parser('run',
help='''Run a custom command into container.
example: check_lxd run -c "/bin/bash /home/foo/foo.sh"''')
parser_run.add_argument("cmd", nargs=1, type=str,
help='''the command to run in container, remember close it in quotes.
example: check_lxd run -c "/bin/bash /home/foo/foo.sh"''')
parser_procs = subparsers.add_parser('procs',
help='''Check processes of the container
and generates WARNING or CRITICAL states if
the number is outside of the required threshold ranges.
ex: check_lxd procs -w 12-14 -c 12-20''')
parser_procs.add_argument("-w", "--warning", nargs=1, required=True,
help='''range of processes for state WARNING
min-max''', type=str)
parser_mem = subparsers.add_parser('mem',
help='''Check the amount of memory used by the container
and generates WARNING or CRITICAL states if
the number is higher of the threshold defined in MB.
ex: check_lxd mem -w 1024 -c 2048''')
parser_mem.add_argument("-c", "--critical", nargs=1, required=True,
help='''amount of memory in MB for state CRITICAL''', type=int)
parser_mem.add_argument("-w", "--warning", nargs=1, required=True,
help='''amount of memory in MB for state WARNING''', type=int)
parser.add_argument("container_name",
help='''container name to check, mandatory''',
type=str, nargs=1)
return parser.parse_args()
def return_state(state, msg=""):
"""Used by check functions to deliver a nagios a info line and status code."""
print(msg)
exit(state)
def get_containers_data():
"""return dict of contaners info from lxc command"""
try:
result = check_output(["lxc", "list", "--format", "yaml"])
except Exception as error:
return_state(state['critical'], "ERROR: can't run the lxc command")
return load(result)
def find_container(container_name):
"""search a container name and return his data or deliver a unknown state"""
containers_data = get_containers_data()
for item in containers_data:
if item['container']['name'] == container_name:
return item
return_state(state['unknown'],
"ERROR: the container %s don't exist" % container_name)
def check_container_state(container_data):
"""Deliver critical if container not running, else OK"""
if container_data['container']['status'].lower() != "running":
return_state(
state['critical'],
"CRITICAL: the container %s don't running" % container_data['container']['name'])
else:
return_state(
state['ok'], "OK: the container %s is running" % container_data['container']['name'])
def check_container_mem(container_data, critical, warning):
"""deliver status code based on the mem thresholds"""
used_mem = int(container_data['state']['memory']['usage'] / 1048576)
if used_mem > critical[0]:
return_state(
['critical'],
"CRITICAL, the container consumes %dM of RAM, over %dM" % (used_mem, critical[0]))
if used_mem > warning[0]:
return_state(
state['warning'],
"WARNING, the container consumes %dM of RAM, over %dM" % (used_mem, warning[0]))
return_state(
state['ok'], "OK, the container consumes %dM of RAM, under thresholds" % used_mem)
def check_container_procs(container_data, critical, warning):
"""check syntax of thresholds "int-int" and deliver status code based on
the procs thresholds"""
try:
critical = critical[0].split("-")
warning = warning[0].split("-")
assert (len(critical) == 2 and len(warning) == 2)
for item in range(2):
critical[item] = int(critical[item])
warning[item] = int(warning[item])
except Exception as error:
print("ERROR: wrong arguments", error)
exit(state['unknown'])
used_procs = container_data['state']['processes']
if used_procs < critical[0] or used_procs > critical[1]:
return_state(
state['critical'], "CRITICAL, the container has %d procs, is out of range: %d - %ds" % (used_procs, critical[0], critical[1]))
if used_procs < warning[0] or used_procs > warning[1]:
return_state(
state['warning'], "WARNING, the container has %d procs, is out of range: %d - %d" % (used_procs, warning[0], warning[1]))
else:
return_state(
state['ok'], "OK, the container has %d procs, under thresholds" % used_procs)
def run_in_container(container_name, cmd):
"""run command in container using lxc command, and deliver the status
code and last message"""
try:
res = check_output("lxc exec " + container_name + " -- " + cmd, shell=True)
return_state(state["ok"], str(res.decode()))
except CalledProcessError as ret:
if ret.returncode == 1:
return_state(state["warning"], str(ret.output.decode()))
elif ret.returncode == 2:
return_state(state["critical"], str(ret.output.decode()))
else:
return_state(state["unknown"], "Code status: %d, msg: %s" % (ret.returncode, str(ret.output.decode())))
# Main
args = parser_args()
container_name = args.container_name[0]
# this get container data or return unknown if container dont't exist
container_data = find_container(container_name)
if args.command == 'state':
check_container_state(container_data)
if args.command == 'mem':
check_container_mem(container_data, args.critical, args.warning)
if args.command == 'procs':
check_container_procs(container_data, args.critical, args.warning)
if args.command == 'run':
run_in_container(container_name, args.cmd[0])