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
302
303
304
305
306
307
|
import socket
import yaml
import subprocess
from charmhelpers.core.services import helpers
from charmhelpers.core import hookenv
class Monitors(dict):
""" Represent the list of checks that a remote Nagios can query converting
local check to ones that can be queried remotely
"""
def __init__(self, version='0.3'):
self['monitors'] = {
'remote': {
'nrpe': {}
}
}
self['version'] = version
def add_monitors(self, mdict, monitor_label='default'):
if not mdict or not mdict.get('monitors'):
return
for checktype in mdict['monitors'].get('remote', []):
check_details = mdict['monitors']['remote'][checktype]
if self['monitors']['remote'].get(checktype):
self['monitors']['remote'][checktype].update(check_details)
else:
self['monitors']['remote'][checktype] = check_details
for checktype in mdict['monitors'].get('local', []):
check_details = self.convert_local_checks(
mdict['monitors']['local'],
monitor_label,
)
self['monitors']['remote']['nrpe'].update(check_details)
def add_nrpe_check(self, check_name, command):
self['monitors']['remote']['nrpe'][check_name] = command
def convert_local_checks(self, monitors, monitor_src):
""" Convert check from local checks to remote nrpe checks
monitors -- monitor dict
monitor_src -- Monitor source principle, subordinate or user
"""
mons = {}
for checktype in monitors.keys():
for checkname in monitors[checktype]:
check_def = NRPECheckCtxt(
checktype,
monitors[checktype][checkname],
monitor_src,
)
mons[check_def['cmd_name']] = \
{'command': check_def['cmd_name']}
return mons
class MonitorsRelation(helpers.RelationContext):
name = 'monitors'
interface = 'monitors'
def __init__(self, *args, **kwargs):
self.principle_relation = PrincipleRelation()
super(MonitorsRelation, self).__init__(*args, **kwargs)
def is_ready(self):
return self.principle_relation.is_ready()
def get_subordinate_monitors(self):
""" Return default monitors defined by this charm """
monitors = Monitors()
for check in SubordinateCheckDefinitions()['checks']:
monitors.add_nrpe_check(check['cmd_name'], check['cmd_name'])
return monitors
def get_user_defined_monitors(self):
""" Return monitors defined by monitors config option """
monitors = Monitors()
monitors.add_monitors(yaml.safe_load(hookenv.config('monitors')),
'user')
return monitors
def get_principle_monitors(self):
""" Return monitors passed by relation with principle """
return self.principle_relation.get_monitors()
def get_monitor_dicts(self):
""" Return all monitor dicts """
monitor_dicts = {
'principle': self.get_principle_monitors(),
'subordinate': self.get_subordinate_monitors(),
'user': self.get_user_defined_monitors(),
}
return monitor_dicts
def get_monitors(self):
""" Return monitor dict of all monitors merged together and local
monitors converted to remote nrpe checks
"""
all_monitors = Monitors()
monitors = [
self.get_principle_monitors(),
self.get_subordinate_monitors(),
self.get_user_defined_monitors(),
]
for mon in monitors:
all_monitors.add_monitors(mon)
return all_monitors
def get_data(self):
super(MonitorsRelation, self).get_data()
if not hookenv.relation_ids(self.name):
return
addresses = [info['private-address'] for info in self['monitors']]
self['monitor_allowed_hosts'] = ','.join(addresses)
def provide_data(self):
relation_info = {
'target-id': self.principle_relation.nagios_hostname(),
'monitors': self.get_monitors(),
}
return relation_info
class PrincipleRelation(helpers.RelationContext):
def __init__(self, *args, **kwargs):
if hookenv.relations_of_type('nrpe-external-master'):
self.name = 'nrpe-external-master'
self.interface = 'nrpe-external-master'
elif hookenv.relations_of_type('general-info'):
self.name = 'general-info'
self.interface = 'juju-info'
elif hookenv.relations_of_type('local-monitors'):
self.name = 'local-monitors'
self.interface = 'local-monitors'
super(PrincipleRelation, self).__init__(*args, **kwargs)
def is_ready(self):
if self.name not in self:
return False
return '__unit__' in self[self.name][0]
def principle_unit(self):
for rel in self[self.name]:
if 'primary' in rel and rel['primary'] == 'True':
return rel
# This is not necessarily the primary relation...
return rel[0]
def nagios_hostname(self):
""" Return the string that nagios will use to identify this host """
host_context = hookenv.config('nagios_host_context')
hostname_type = hookenv.config('nagios_hostname_type')
if hostname_type == 'host' or not self.is_ready():
return socket.gethostname()
else:
principle_unit = self.principle_unit()
principle_unitname = principle_unit['__unit__']
nagios_hostname = "{}-{}".format(host_context, principle_unitname)
nagios_hostname = nagios_hostname.replace('/', '-')
return nagios_hostname
def get_monitors(self):
""" Return monitors passed by services on the self.interface relation
"""
if not self.is_ready():
return
monitors = Monitors()
for rel in self[self.name]:
if rel.get('monitors'):
monitors.add_monitors(yaml.load(rel['monitors']), 'principle')
return monitors
def provide_data(self):
# Provide this data to principals because get_nagios_hostname expects
# them in charmhelpers/contrib/charmsupport/nrpe when writing principal
# service__* files
return {'nagios_hostname': self.nagios_hostname(),
'nagios_host_context': hookenv.config('nagios_host_context')}
class NagiosInfo(dict):
def __init__(self):
self.principle_relation = PrincipleRelation()
self['external_nagios_master'] = '127.0.0.1'
if hookenv.config()['nagios_master'] != 'None':
self['external_nagios_master'] = \
"{},{}".format(self['external_nagios_master'],
hookenv.config()['nagios_master'])
self['nagios_hostname'] = self.principle_relation.nagios_hostname()
ip_key = hookenv.config('nagios_address_type') + '-address'
self['nagios_ipaddress'] = hookenv.unit_get(ip_key)
class RsyncEnabled(helpers.RelationContext):
def __init__(self):
self['export_nagios_definitions'] = \
hookenv.config()['export_nagios_definitions']
def is_ready(self):
return self['export_nagios_definitions']
class NRPECheckCtxt(dict):
""" Convert a local monitor definition into dict needed for writting the
nrpe check definition
"""
def __init__(self, checktype, check_opts, monitor_src):
plugin_path = '/usr/lib/nagios/plugins'
if checktype == 'procrunning':
self['cmd_exec'] = plugin_path + '/check_procs'
self['description'] = \
'Check process {executable} is running'.format(**check_opts)
self['cmd_name'] = 'check_proc_' + check_opts['executable']
self['cmd_params'] = '-w {min} -c {max} -C {executable}'.format(
**check_opts
)
elif checktype == 'processcount':
self['cmd_exec'] = plugin_path + '/check_procs'
self['description'] = 'Check process count'
self['cmd_name'] = 'check_proc_principle'
if 'min' in check_opts:
self['cmd_params'] = '-w {min} -c {max}'.format(**check_opts)
else:
self['cmd_params'] = '-c {max}'.format(**check_opts)
elif checktype == 'disk':
self['cmd_exec'] = plugin_path + '/check_disk'
self['description'] = 'Check disk usage ' + \
check_opts['path'].replace('/', '_'),
self['cmd_name'] = 'check_disk_principle'
self['cmd_params'] = '-w 20 -c 10 -p ' + check_opts['path']
self['description'] += ' ({})'.format(monitor_src)
self['cmd_name'] += '_' + monitor_src
class SubordinateCheckDefinitions(dict):
""" Return dict of checks the charm configures """
def __init__(self):
if hookenv.config('procs') == "auto":
procs = self.proc_count()
proc_thresholds = "-w {} -c {}".format(25 * procs + 100,
50 * procs + 100)
else:
proc_thresholds = hookenv.config('procs')
pkg_plugin_dir = '/usr/lib/nagios/plugins/'
local_plugin_dir = '/usr/local/lib/nagios/plugins/'
checks = [
{
'description': 'Root disk',
'cmd_name': 'check_disk_root',
'cmd_exec': pkg_plugin_dir + 'check_disk',
'cmd_params': hookenv.config('disk_root') + " -p / ",
},
{
'description': 'Number of Zombie processes',
'cmd_name': 'check_zombie_procs',
'cmd_exec': pkg_plugin_dir + 'check_procs',
'cmd_params': hookenv.config('zombies'),
},
{
'description': 'Number of processes',
'cmd_name': 'check_total_procs',
'cmd_exec': pkg_plugin_dir + 'check_procs',
'cmd_params': proc_thresholds,
},
{
'description': 'System Load',
'cmd_name': 'check_load',
'cmd_exec': pkg_plugin_dir + 'check_load',
'cmd_params': hookenv.config('load'),
},
{
'description': 'Number of Users',
'cmd_name': 'check_users',
'cmd_exec': pkg_plugin_dir + 'check_users',
'cmd_params': hookenv.config('users'),
},
{
'description': 'Swap',
'cmd_name': 'check_swap',
'cmd_exec': pkg_plugin_dir + 'check_swap',
'cmd_params': hookenv.config('swap'),
},
{
'description': 'Memory',
'cmd_name': 'check_mem',
'cmd_exec': local_plugin_dir + 'check_mem.pl',
'cmd_params': hookenv.config('mem'),
},
]
self['checks'] = []
sub_postfix = str(hookenv.config("sub_postfix"))
for check in checks:
check['description'] += " (sub)"
check['cmd_name'] += sub_postfix
self['checks'].append(check)
def proc_count(self):
""" Return number number of processing units """
return int(subprocess.check_output('nproc'))
|