~cprov/charms/trusty/adt-cloud-worker/py2-production

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/contrib/charmsupport/nrpe.py

  • Committer: Paul Larson
  • Date: 2015-03-04 14:54:10 UTC
  • Revision ID: paul.larson@canonical.com-20150304145410-t8lexkpisk2kz308
start working on adt-cloud-worker

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2014-2015 Canonical Limited.
 
2
#
 
3
# This file is part of charm-helpers.
 
4
#
 
5
# charm-helpers is free software: you can redistribute it and/or modify
 
6
# it under the terms of the GNU Lesser General Public License version 3 as
 
7
# published by the Free Software Foundation.
 
8
#
 
9
# charm-helpers is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU Lesser General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU Lesser General Public License
 
15
# along with charm-helpers.  If not, see <http://www.gnu.org/licenses/>.
 
16
 
 
17
"""Compatibility with the nrpe-external-master charm"""
 
18
# Copyright 2012 Canonical Ltd.
 
19
#
 
20
# Authors:
 
21
#  Matthew Wedgwood <matthew.wedgwood@canonical.com>
 
22
 
 
23
import subprocess
 
24
import pwd
 
25
import grp
 
26
import os
 
27
import re
 
28
import shlex
 
29
import yaml
 
30
 
 
31
from charmhelpers.core.hookenv import (
 
32
    config,
 
33
    local_unit,
 
34
    log,
 
35
    relation_ids,
 
36
    relation_set,
 
37
    relations_of_type,
 
38
)
 
39
 
 
40
from charmhelpers.core.host import service
 
41
 
 
42
# This module adds compatibility with the nrpe-external-master and plain nrpe
 
43
# subordinate charms. To use it in your charm:
 
44
#
 
45
# 1. Update metadata.yaml
 
46
#
 
47
#   provides:
 
48
#     (...)
 
49
#     nrpe-external-master:
 
50
#       interface: nrpe-external-master
 
51
#       scope: container
 
52
#
 
53
#   and/or
 
54
#
 
55
#   provides:
 
56
#     (...)
 
57
#     local-monitors:
 
58
#       interface: local-monitors
 
59
#       scope: container
 
60
 
 
61
#
 
62
# 2. Add the following to config.yaml
 
63
#
 
64
#    nagios_context:
 
65
#      default: "juju"
 
66
#      type: string
 
67
#      description: |
 
68
#        Used by the nrpe subordinate charms.
 
69
#        A string that will be prepended to instance name to set the host name
 
70
#        in nagios. So for instance the hostname would be something like:
 
71
#            juju-myservice-0
 
72
#        If you're running multiple environments with the same services in them
 
73
#        this allows you to differentiate between them.
 
74
#    nagios_servicegroups:
 
75
#      default: ""
 
76
#      type: string
 
77
#      description: |
 
78
#        A comma-separated list of nagios servicegroups.
 
79
#        If left empty, the nagios_context will be used as the servicegroup
 
80
#
 
81
# 3. Add custom checks (Nagios plugins) to files/nrpe-external-master
 
82
#
 
83
# 4. Update your hooks.py with something like this:
 
84
#
 
85
#    from charmsupport.nrpe import NRPE
 
86
#    (...)
 
87
#    def update_nrpe_config():
 
88
#        nrpe_compat = NRPE()
 
89
#        nrpe_compat.add_check(
 
90
#            shortname = "myservice",
 
91
#            description = "Check MyService",
 
92
#            check_cmd = "check_http -w 2 -c 10 http://localhost"
 
93
#            )
 
94
#        nrpe_compat.add_check(
 
95
#            "myservice_other",
 
96
#            "Check for widget failures",
 
97
#            check_cmd = "/srv/myapp/scripts/widget_check"
 
98
#            )
 
99
#        nrpe_compat.write()
 
100
#
 
101
#    def config_changed():
 
102
#        (...)
 
103
#        update_nrpe_config()
 
104
#
 
105
#    def nrpe_external_master_relation_changed():
 
106
#        update_nrpe_config()
 
107
#
 
108
#    def local_monitors_relation_changed():
 
109
#        update_nrpe_config()
 
110
#
 
111
# 5. ln -s hooks.py nrpe-external-master-relation-changed
 
112
#    ln -s hooks.py local-monitors-relation-changed
 
113
 
 
114
 
 
115
class CheckException(Exception):
 
116
    pass
 
117
 
 
118
 
 
119
class Check(object):
 
120
    shortname_re = '[A-Za-z0-9-_]+$'
 
121
    service_template = ("""
 
122
#---------------------------------------------------
 
123
# This file is Juju managed
 
124
#---------------------------------------------------
 
125
define service {{
 
126
    use                             active-service
 
127
    host_name                       {nagios_hostname}
 
128
    service_description             {nagios_hostname}[{shortname}] """
 
129
                        """{description}
 
130
    check_command                   check_nrpe!{command}
 
131
    servicegroups                   {nagios_servicegroup}
 
132
}}
 
133
""")
 
134
 
 
135
    def __init__(self, shortname, description, check_cmd):
 
136
        super(Check, self).__init__()
 
137
        # XXX: could be better to calculate this from the service name
 
138
        if not re.match(self.shortname_re, shortname):
 
139
            raise CheckException("shortname must match {}".format(
 
140
                Check.shortname_re))
 
141
        self.shortname = shortname
 
142
        self.command = "check_{}".format(shortname)
 
143
        # Note: a set of invalid characters is defined by the
 
144
        # Nagios server config
 
145
        # The default is: illegal_object_name_chars=`~!$%^&*"|'<>?,()=
 
146
        self.description = description
 
147
        self.check_cmd = self._locate_cmd(check_cmd)
 
148
 
 
149
    def _locate_cmd(self, check_cmd):
 
150
        search_path = (
 
151
            '/usr/lib/nagios/plugins',
 
152
            '/usr/local/lib/nagios/plugins',
 
153
        )
 
154
        parts = shlex.split(check_cmd)
 
155
        for path in search_path:
 
156
            if os.path.exists(os.path.join(path, parts[0])):
 
157
                command = os.path.join(path, parts[0])
 
158
                if len(parts) > 1:
 
159
                    command += " " + " ".join(parts[1:])
 
160
                return command
 
161
        log('Check command not found: {}'.format(parts[0]))
 
162
        return ''
 
163
 
 
164
    def write(self, nagios_context, hostname, nagios_servicegroups=None):
 
165
        nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format(
 
166
            self.command)
 
167
        with open(nrpe_check_file, 'w') as nrpe_check_config:
 
168
            nrpe_check_config.write("# check {}\n".format(self.shortname))
 
169
            nrpe_check_config.write("command[{}]={}\n".format(
 
170
                self.command, self.check_cmd))
 
171
 
 
172
        if not os.path.exists(NRPE.nagios_exportdir):
 
173
            log('Not writing service config as {} is not accessible'.format(
 
174
                NRPE.nagios_exportdir))
 
175
        else:
 
176
            self.write_service_config(nagios_context, hostname,
 
177
                                      nagios_servicegroups)
 
178
 
 
179
    def write_service_config(self, nagios_context, hostname,
 
180
                             nagios_servicegroups=None):
 
181
        for f in os.listdir(NRPE.nagios_exportdir):
 
182
            if re.search('.*{}.cfg'.format(self.command), f):
 
183
                os.remove(os.path.join(NRPE.nagios_exportdir, f))
 
184
 
 
185
        if not nagios_servicegroups:
 
186
            nagios_servicegroups = nagios_context
 
187
 
 
188
        templ_vars = {
 
189
            'nagios_hostname': hostname,
 
190
            'nagios_servicegroup': nagios_servicegroups,
 
191
            'description': self.description,
 
192
            'shortname': self.shortname,
 
193
            'command': self.command,
 
194
        }
 
195
        nrpe_service_text = Check.service_template.format(**templ_vars)
 
196
        nrpe_service_file = '{}/service__{}_{}.cfg'.format(
 
197
            NRPE.nagios_exportdir, hostname, self.command)
 
198
        with open(nrpe_service_file, 'w') as nrpe_service_config:
 
199
            nrpe_service_config.write(str(nrpe_service_text))
 
200
 
 
201
    def run(self):
 
202
        subprocess.call(self.check_cmd)
 
203
 
 
204
 
 
205
class NRPE(object):
 
206
    nagios_logdir = '/var/log/nagios'
 
207
    nagios_exportdir = '/var/lib/nagios/export'
 
208
    nrpe_confdir = '/etc/nagios/nrpe.d'
 
209
 
 
210
    def __init__(self, hostname=None):
 
211
        super(NRPE, self).__init__()
 
212
        self.config = config()
 
213
        self.nagios_context = self.config['nagios_context']
 
214
        if 'nagios_servicegroups' in self.config:
 
215
            self.nagios_servicegroups = self.config['nagios_servicegroups']
 
216
        else:
 
217
            self.nagios_servicegroups = 'juju'
 
218
        self.unit_name = local_unit().replace('/', '-')
 
219
        if hostname:
 
220
            self.hostname = hostname
 
221
        else:
 
222
            self.hostname = "{}-{}".format(self.nagios_context, self.unit_name)
 
223
        self.checks = []
 
224
 
 
225
    def add_check(self, *args, **kwargs):
 
226
        self.checks.append(Check(*args, **kwargs))
 
227
 
 
228
    def write(self):
 
229
        try:
 
230
            nagios_uid = pwd.getpwnam('nagios').pw_uid
 
231
            nagios_gid = grp.getgrnam('nagios').gr_gid
 
232
        except:
 
233
            log("Nagios user not set up, nrpe checks not updated")
 
234
            return
 
235
 
 
236
        if not os.path.exists(NRPE.nagios_logdir):
 
237
            os.mkdir(NRPE.nagios_logdir)
 
238
            os.chown(NRPE.nagios_logdir, nagios_uid, nagios_gid)
 
239
 
 
240
        nrpe_monitors = {}
 
241
        monitors = {"monitors": {"remote": {"nrpe": nrpe_monitors}}}
 
242
        for nrpecheck in self.checks:
 
243
            nrpecheck.write(self.nagios_context, self.hostname,
 
244
                            self.nagios_servicegroups)
 
245
            nrpe_monitors[nrpecheck.shortname] = {
 
246
                "command": nrpecheck.command,
 
247
            }
 
248
 
 
249
        service('restart', 'nagios-nrpe-server')
 
250
 
 
251
        for rid in relation_ids("local-monitors"):
 
252
            relation_set(relation_id=rid, monitors=yaml.dump(monitors))
 
253
 
 
254
 
 
255
def get_nagios_hostcontext(relation_name='nrpe-external-master'):
 
256
    """
 
257
    Query relation with nrpe subordinate, return the nagios_host_context
 
258
 
 
259
    :param str relation_name: Name of relation nrpe sub joined to
 
260
    """
 
261
    for rel in relations_of_type(relation_name):
 
262
        if 'nagios_hostname' in rel:
 
263
            return rel['nagios_host_context']
 
264
 
 
265
 
 
266
def get_nagios_hostname(relation_name='nrpe-external-master'):
 
267
    """
 
268
    Query relation with nrpe subordinate, return the nagios_hostname
 
269
 
 
270
    :param str relation_name: Name of relation nrpe sub joined to
 
271
    """
 
272
    for rel in relations_of_type(relation_name):
 
273
        if 'nagios_hostname' in rel:
 
274
            return rel['nagios_hostname']
 
275
 
 
276
 
 
277
def get_nagios_unit_name(relation_name='nrpe-external-master'):
 
278
    """
 
279
    Return the nagios unit name prepended with host_context if needed
 
280
 
 
281
    :param str relation_name: Name of relation nrpe sub joined to
 
282
    """
 
283
    host_context = get_nagios_hostcontext(relation_name)
 
284
    if host_context:
 
285
        unit = "%s:%s" % (host_context, local_unit())
 
286
    else:
 
287
        unit = local_unit()
 
288
    return unit
 
289
 
 
290
 
 
291
def add_init_service_checks(nrpe, services, unit_name):
 
292
    """
 
293
    Add checks for each service in list
 
294
 
 
295
    :param NRPE nrpe: NRPE object to add check to
 
296
    :param list services: List of services to check
 
297
    :param str unit_name: Unit name to use in check description
 
298
    """
 
299
    for svc in services:
 
300
        upstart_init = '/etc/init/%s.conf' % svc
 
301
        sysv_init = '/etc/init.d/%s' % svc
 
302
        if os.path.exists(upstart_init):
 
303
            nrpe.add_check(
 
304
                shortname=svc,
 
305
                description='process check {%s}' % unit_name,
 
306
                check_cmd='check_upstart_job %s' % svc
 
307
            )
 
308
        elif os.path.exists(sysv_init):
 
309
            cronpath = '/etc/cron.d/nagios-service-check-%s' % svc
 
310
            cron_file = ('*/5 * * * * root '
 
311
                         '/usr/local/lib/nagios/plugins/check_exit_status.pl '
 
312
                         '-s /etc/init.d/%s status > '
 
313
                         '/var/lib/nagios/service-check-%s.txt\n' % (svc,
 
314
                                                                     svc)
 
315
                         )
 
316
            f = open(cronpath, 'w')
 
317
            f.write(cron_file)
 
318
            f.close()
 
319
            nrpe.add_check(
 
320
                shortname=svc,
 
321
                description='process check {%s}' % unit_name,
 
322
                check_cmd='check_status_file.py -f '
 
323
                          '/var/lib/nagios/service-check-%s.txt' % svc,
 
324
            )