~launchpad-pqm/launchpad/devel

10637.3.1 by Guilherme Salgado
Use the default python version instead of a hard-coded version
1
#!/usr/bin/python -S
8687.15.22 by Karl Fogel
Add the copyright header block to the remaining .py files.
2
#
3
# Copyright 2009 Canonical Ltd.  This software is licensed under the
4
# GNU Affero General Public License version 3 (see the file LICENSE).
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
5
4417.4.23 by Tom Haddon
Another round of comments from Andrew Bennets and RF merge
6
"""Nagios plugin for script monitoring.
7
10303.1.1 by Gary Poster
use newest version of zc.buildout
8
This script is needed as separate from script-monitor.py because Nagios
4417.4.24 by Tom Haddon
Improved docstring for script-monitor-nagios script
9
only understands one line of returned text, and interprets specific
4417.4.23 by Tom Haddon
Another round of comments from Andrew Bennets and RF merge
10
return codes as plugin statuses. These are:
4417.4.24 by Tom Haddon
Improved docstring for script-monitor-nagios script
11
12
    0: OK
13
    1: WARNING
14
    2: CRITICAL
15
    3: UNKNOWN
16
10303.1.1 by Gary Poster
use newest version of zc.buildout
17
As such, it was felt more appropriate to separate out the scripts,
4417.4.24 by Tom Haddon
Improved docstring for script-monitor-nagios script
18
even though there is some code duplication.
4417.4.23 by Tom Haddon
Another round of comments from Andrew Bennets and RF merge
19
"""
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
20
21
__metaclass__ = type
22
__all__ = ['check_script']
23
24
import _pythonpath
25
26
from datetime import datetime, timedelta
27
from optparse import OptionParser
28
from time import strftime
29
import sys
30
31
from canonical.database.sqlbase import connect
32
from canonical.launchpad.scripts import db_options, logger_options, logger
33
from canonical.launchpad.scripts.scriptmonitor import check_script
34
35
36
def main():
10303.1.1 by Gary Poster
use newest version of zc.buildout
37
    # XXX: Tom Haddon 2007-07-12
38
    # There's a lot of untested stuff here: parsing options -
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
39
    # this should be moved into a testable location.
4417.4.22 by Tom Haddon
Clean up code after comments from Andrew Bennets
40
    # Also duplicated code in scripts/script-monitor.py
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
41
    parser = OptionParser(
42
            '%prog [options] (minutes) (host:scriptname) [host:scriptname]'
43
            )
44
    db_options(parser)
45
    logger_options(parser)
46
47
    (options, args) = parser.parse_args()
48
49
    if len(args) < 2:
50
        print "Must specify time in minutes and " \
51
            "at least one host and script"
52
        return 3
53
54
    # First argument is the number of minutes into the past
55
    # we want to look for the scripts on the specified hosts
56
    try:
57
        minutes_ago, args = int(args[0]), args[1:]
58
        start_date = datetime.now() - timedelta(minutes=minutes_ago)
59
60
        completed_from = strftime("%Y-%m-%d %H:%M:%S", start_date.timetuple())
61
        completed_to = strftime("%Y-%m-%d %H:%M:%S", datetime.now().timetuple())
62
63
        hosts_scripts = []
64
        for arg in args:
65
            try:
66
                hostname, scriptname = arg.split(':')
67
            except TypeError:
4417.4.21 by Tom Haddon
Fixed string conversion and error_found now boolean
68
                print "%r is not in the format 'host:scriptname'" % arg
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
69
                return 3
70
            hosts_scripts.append((hostname, scriptname))
71
    except ValueError:
72
        print "Must specify time in minutes and " \
73
            "at least one host and script"
74
        return 3
75
76
    log = logger(options)
77
78
    try:
79
        log.debug("Connecting to database")
80
        con = connect(options.dbuser)
81
        error_found = False
82
        msg = []
83
        for hostname, scriptname in hosts_scripts:
10303.1.1 by Gary Poster
use newest version of zc.buildout
84
            failure_msg = check_script(con, log, hostname,
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
85
                scriptname, completed_from, completed_to)
86
            if failure_msg is not None:
87
                msg.append("%s:%s" % (hostname, scriptname))
4417.4.21 by Tom Haddon
Fixed string conversion and error_found now boolean
88
                error_found = True
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
89
        if error_found:
90
            # Construct our return message
91
            print "Scripts failed to run: %s" % ', '.join(msg)
92
            return 2
93
        else:
94
            # Construct our return message
95
            print "All scripts ran as expected"
96
            return 0
4417.4.23 by Tom Haddon
Another round of comments from Andrew Bennets and RF merge
97
    except Exception, e:
98
        # Squeeze the exception type and stringification of the exception value
99
        # on to one line.
100
        print "Unhandled exception: %s %r" % (e.__class__.__name__, str(e))
4417.4.18 by Tom Haddon
Merged RF and added Nagios script monitoring check
101
        return 3
102
103
if __name__ == '__main__':
104
    sys.exit(main())