Debian Codegraph @

percona-nagios-plugins/nagios/bin/pmp-check-aws-rds.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/env python
2 """Nagios plugin for Amazon RDS monitoring.
3
4 This program is part of $PROJECT_NAME$
5 License: GPL License (see COPYING)
6
7 Author Roman Vynar
8 Copyright 2014-2015 Percona LLC and/or its affiliates
9 """
10
11 import datetime
12 import optparse
13 import pprint
14 import sys
15
16 import boto
17 import boto.rds
18 import boto.ec2.cloudwatch
19
20 # Nagios status codes
21 OK = 0
22 WARNING = 1
23 CRITICAL = 2
24 UNKNOWN = 3
25
26
27 class RDS(object):
28
29 """RDS connection class"""
30
31 def __init__(self, region, profile=None, identifier=None):
32 """Get RDS instance details"""
33 self.region = region
34 self.profile = profile
35 self.identifier = identifier
36
37 if self.region == 'all':
38 self.regions_list = [reg.name for reg in boto.rds.regions()]
39 else:
40 self.regions_list = [self.region]
41
42 self.info = None
43 if self.identifier:
44 for reg in self.regions_list:
45 try:
46 rds = boto.rds.connect_to_region(reg, profile_name=self.profile)
47 self.info = rds.get_all_dbinstances(self.identifier)
48 except (boto.provider.ProfileNotFoundError, boto.exception.BotoServerError) as msg:
49 debug(msg)
50 else:
51 # Exit on the first region and identifier match
52 self.region = reg
53 break
54
55 def get_info(self):
56 """Get RDS instance info"""
57 if self.info:
58 return self.info[0]
59 else:
60 return None
61
62 def get_list(self):
63 """Get list of available instances by region(s)"""
64 result = dict()
65 for reg in self.regions_list:
66 try:
67 rds = boto.rds.connect_to_region(reg, profile_name=self.profile)
68 result[reg] = rds.get_all_dbinstances()
69 except (boto.provider.ProfileNotFoundError, boto.exception.BotoServerError) as msg:
70 debug(msg)
71
72 return result
73
74 def get_metric(self, metric, start_time, end_time, step):
75 """Get RDS metric from CloudWatch"""
76 cw_conn = boto.ec2.cloudwatch.connect_to_region(self.region, profile_name=self.profile)
77 result = cw_conn.get_metric_statistics(
78 step,
79 start_time,
80 end_time,
81 metric,
82 'AWS/RDS',
83 'Average',
84 dimensions={'DBInstanceIdentifier': [self.identifier]}
85 )
86 if result:
87 if len(result) > 1:
88 # Get the last point
89 result = sorted(result, key=lambda k: k['Timestamp'])
90 result.reverse()
91
92 result = float('%.2f' % result[0]['Average'])
93
94 return result
95
96
97 def debug(val):
98 """Debugging output"""
99 global options
100 if options.debug:
•101 print 'DEBUG: %s' % val
102
103
104 def main():
105 """Main function"""
106 global options
107
108 short_status = {
109 OK: 'OK',
110 WARNING: 'WARN',
111 CRITICAL: 'CRIT',
112 UNKNOWN: 'UNK'
113 }
114
115 # DB instance classes as listed on
116 # http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html
117 db_classes = {
118 'db.t1.micro': 0.615,
119 'db.m1.small': 1.7,
120 'db.m1.medium': 3.75,
121 'db.m1.large': 7.5,
122 'db.m1.xlarge': 15,
123 'db.m4.large': 8,
124 'db.m4.xlarge': 16,
125 'db.m4.2xlarge': 32,
126 'db.m4.4xlarge': 64,
127 'db.m4.10xlarge': 160,
128 'db.r3.large': 15,
129 'db.r3.xlarge': 30.5,
130 'db.r3.2xlarge': 61,
131 'db.r3.4xlarge': 122,
132 'db.r3.8xlarge': 244,
133 'db.t2.micro': 1,
134 'db.t2.small': 2,
135 'db.t2.medium': 4,
136 'db.t2.large': 8,
137 'db.m3.medium': 3.75,
138 'db.m3.large': 7.5,
139 'db.m3.xlarge': 15,
140 'db.m3.2xlarge': 30,
141 'db.m2.xlarge': 17.1,
142 'db.m2.2xlarge': 34.2,
143 'db.m2.4xlarge': 68.4,
144 'db.cr1.8xlarge': 244,
145 }
146
147 # RDS metrics http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/rds-metricscollected.html
148 metrics = {
149 'status': 'RDS availability',
150 'load': 'CPUUtilization',
151 'memory': 'FreeableMemory',
152 'storage': 'FreeStorageSpace'
153 }
154
155 units = ('percent', 'GB')
156
157 # Parse options
158 parser = optparse.OptionParser()
159 parser.add_option('-l', '--list', help='list of all DB instances',
160 action='store_true', default=False, dest='db_list')
161 parser.add_option('-n', '--profile', default=None,
162 help='AWS profile from ~/.boto or /etc/boto.cfg. Default: None, fallbacks to "[Credentials]".')
163 parser.add_option('-r', '--region', default='us-east-1',
164 help='AWS region. Default: us-east-1. If set to "all", we try to detect the instance region '
165 'across all of them, note this will be slower than if you specify the region explicitly.')
166 parser.add_option('-i', '--ident', help='DB instance identifier')
167 parser.add_option('-p', '--print', help='print status and other details for a given DB instance',
168 action='store_true', default=False, dest='printinfo')
•169 parser.add_option('-m', '--metric', help='metric to check: [%s]' % ', '.join(metrics.keys()))
170 parser.add_option('-w', '--warn', help='warning threshold')
171 parser.add_option('-c', '--crit', help='critical threshold')
172 parser.add_option('-u', '--unit', help='unit of thresholds for "storage" and "memory" metrics: [%s].'
173 'Default: percent' % ', '.join(units), default='percent')
174 parser.add_option('-t', '--time', help='time period in minutes to query. Default: 5',
175 type='int', default=5)
176 parser.add_option('-a', '--avg', help='time average in minutes to request. Default: 1',
177 type='int', default=1)
178 parser.add_option('-f', '--forceunknown', help='force alerts on unknown status. This prevents issues related to '
179 'AWS Cloudwatch throttling limits Default: False',
180 action='store_true', default=False)
181 parser.add_option('-d', '--debug', help='enable debug output',
182 action='store_true', default=False)
183 options, _ = parser.parse_args()
184
185 if options.debug:
186 boto.set_stream_logger('boto')
187
188 rds = RDS(region=options.region, profile=options.profile, identifier=options.ident)
189
190 # Check args
191 if len(sys.argv) == 1:
192 parser.print_help()
193 sys.exit()
194 elif options.db_list:
195 info = rds.get_list()
•196 print 'List of all DB instances in %s region(s):' % (options.region,)
197 pprint.pprint(info)
198 sys.exit()
199 elif not options.ident:
200 parser.print_help()
201 parser.error('DB identifier is not set.')
202 elif options.printinfo:
203 info = rds.get_info()
204 if info:
205 pprint.pprint(vars(info))
206 else:
•207 print 'No DB instance "%s" found on your AWS account and %s region(s).' % (options.ident, options.region)
208
209 sys.exit()
•210 elif not options.metric or options.metric not in metrics.keys():
211 parser.print_help()
212 parser.error('Metric is not set or not valid.')
213 elif not options.warn and options.metric != 'status':
214 parser.print_help()
215 parser.error('Warning threshold is not set.')
216 elif not options.crit and options.metric != 'status':
217 parser.print_help()
218 parser.error('Critical threshold is not set.')
219 elif options.avg <= 0 and options.metric != 'status':
220 parser.print_help()
221 parser.error('Average must be greater than zero.')
222 elif options.time <= 0 and options.metric != 'status':
223 parser.print_help()
224 parser.error('Time must be greater than zero.')
225
226 now = datetime.datetime.utcnow()
227 status = None
228 note = ''
229 perf_data = None
230
231 # RDS Status
232 if options.metric == 'status':
233 info = rds.get_info()
234 if not info:
235 status = UNKNOWN
236 note = 'Unable to get RDS instance'
237 else:
238 status = OK
239 try:
240 version = info.EngineVersion
241 except:
242 version = info.engine_version
243
244 note = '%s %s. Status: %s' % (info.engine, version, info.status)
245
246 # RDS Load Average
247 elif options.metric == 'load':
248 # Check thresholds
249 try:
250 warns = [float(x) for x in options.warn.split(',')]
251 crits = [float(x) for x in options.crit.split(',')]
252 fail = len(warns) + len(crits)
253 except:
254 fail = 0
255
256 if fail != 6:
257 parser.error('Warning and critical thresholds should be 3 comma separated numbers, e.g. 20,15,10')
258
259 loads = []
260 fail = False
261 j = 0
262 perf_data = []
263 for i in [1, 5, 15]:
264 if i == 1:
265 # Some stats are delaying to update on CloudWatch.
266 # Let's pick a few points for 1-min load avg and get the last point.
267 points = 5
268 else:
269 points = i
270
271 load = rds.get_metric(metrics[options.metric], now - datetime.timedelta(seconds=points * 60), now, i * 60)
272 if not load:
273 status = UNKNOWN
274 note = 'Unable to get RDS statistics'
275 perf_data = None
276 break
277
278 loads.append(str(load))
279 perf_data.append('load%s=%s;%s;%s;0;100' % (i, load, warns[j], crits[j]))
280
281 # Compare thresholds
282 if not fail:
283 if warns[j] > crits[j]:
284 parser.error('Parameter inconsistency: warning threshold is greater than critical.')
285 elif load >= crits[j]:
286 status = CRITICAL
287 fail = True
288 elif load >= warns[j]:
289 status = WARNING
290
291 j = j + 1
292
293 if status != UNKNOWN:
294 if status is None:
295 status = OK
296
297 note = 'Load average: %s%%' % '%, '.join(loads)
298 perf_data = ' '.join(perf_data)
299
300 # RDS Free Storage
301 # RDS Free Memory
302 elif options.metric in ['storage', 'memory']:
303 # Check thresholds
304 try:
305 warn = float(options.warn)
306 crit = float(options.crit)
307 except:
308 parser.error('Warning and critical thresholds should be integers.')
309
310 if crit > warn:
311 parser.error('Parameter inconsistency: critical threshold is greater than warning.')
312
313 if options.unit not in units:
314 parser.print_help()
315 parser.error('Unit is not valid.')
316
317 info = rds.get_info()
318 free = rds.get_metric(metrics[options.metric], now - datetime.timedelta(seconds=options.time * 60),
319 now, options.avg * 60)
320 if not info or not free:
321 status = UNKNOWN
322 note = 'Unable to get RDS details and statistics'
323 else:
324 if options.metric == 'storage':
325 storage = float(info.allocated_storage)
326 elif options.metric == 'memory':
327 try:
328 storage = db_classes[info.instance_class]
329 except:
•330 print 'Unknown DB instance class "%s"' % info.instance_class
331 sys.exit(CRITICAL)
332
333 free = '%.2f' % (free / 1024 ** 3)
334 free_pct = '%.2f' % (float(free) / storage * 100)
335 if options.unit == 'percent':
336 val = float(free_pct)
337 val_max = 100
338 elif options.unit == 'GB':
339 val = float(free)
340 val_max = storage
341
342 # Compare thresholds
343 if val <= crit:
344 status = CRITICAL
345 elif val <= warn:
346 status = WARNING
347
348 if status is None:
349 status = OK
350
351 note = 'Free %s: %s GB (%.0f%%) of %s GB' % (options.metric, free, float(free_pct), storage)
352 perf_data = 'free_%s=%s;%s;%s;0;%s' % (options.metric, val, warn, crit, val_max)
353
354 # Final output
355 if status != UNKNOWN and perf_data:
•356 print '%s %s | %s' % (short_status[status], note, perf_data)
357 elif status == UNKNOWN and not options.forceunknown:
•358 print '%s %s | null' % ('OK', note)
359 sys.exit(0)
360 else:
•361 print '%s %s' % (short_status[status], note)
362
363 sys.exit(status)
364
365
366 if __name__ == '__main__':
367 main()
368
369 # ############################################################################
370 # Documentation
371 # ############################################################################
372 """
373 =pod
374
375 =head1 NAME
376
377 pmp-check-aws-rds.py - Check Amazon RDS metrics.
378
379 =head1 SYNOPSIS
380
381 Usage: pmp-check-aws-rds.py [options]
382
383 Options:
384 -h, --help show this help message and exit
385 -l, --list list of all DB instances
386 -n PROFILE, --profile-name=PROFILE
387 AWS profile from ~/.boto or /etc/boto.cfg. Default:
388 None, fallbacks to "[Credentials]".
389 -r REGION, --region=REGION
390 AWS region. Default: us-east-1. If set to "all", we
391 try to detect the instance region across all of them,
392 note this will be slower than you specify the region.
393 -i IDENT, --ident=IDENT
394 DB instance identifier
395 -p, --print print status and other details for a given DB instance
396 -m METRIC, --metric=METRIC
397 metric to check: [status, load, storage, memory]
398 -w WARN, --warn=WARN warning threshold
399 -c CRIT, --crit=CRIT critical threshold
400 -u UNIT, --unit=UNIT unit of thresholds for "storage" and "memory" metrics:
401 [percent, GB]. Default: percent
402 -t TIME, --time=TIME time period in minutes to query. Default: 5
403 -a AVG, --avg=AVG time average in minutes to request. Default: 1
404 -f, --forceunknown force alerts on unknown status. This prevents issues
405 related to AWS Cloudwatch throttling limits Default:
406 False
407 -d, --debug enable debug output
408
409 =head1 REQUIREMENTS
410
411 This plugin is written on Python and utilizes the module C<boto> (Python interface
412 to Amazon Web Services) to get various RDS metrics from CloudWatch and compare
413 them against the thresholds.
414
415 * Install the package: C<yum install python-boto> or C<apt-get install python-boto>
416 * Create a config /etc/boto.cfg or ~nagios/.boto with your AWS API credentials.
417 See http://code.google.com/p/boto/wiki/BotoConfig
418
419 This plugin that is supposed to be run by Nagios, i.e. under ``nagios`` user,
420 should have permissions to read the config /etc/boto.cfg or ~nagios/.boto.
421
422 Example:
423
424 [root@centos6 ~]# cat /etc/boto.cfg
425 [Credentials]
426 aws_access_key_id = THISISATESTKEY
427 aws_secret_access_key = thisisatestawssecretaccesskey
428
429 If you do not use this config with other tools such as our Cacti script,
430 you can secure this file the following way:
431
432 [root@centos6 ~]# chown nagios /etc/boto.cfg
433 [root@centos6 ~]# chmod 600 /etc/boto.cfg
434
435 =head1 DESCRIPTION
436
437 The plugin provides 4 checks and some options to list and print RDS details:
438
439 * RDS Status
440 * RDS Load Average
441 * RDS Free Storage
442 * RDS Free Memory
443
444 To get the list of all RDS instances under AWS account:
445
446 # ./pmp-check-aws-rds.py -l
447
448 To get the detailed status of RDS instance identified as C<blackbox>:
449
450 # ./pmp-check-aws-rds.py -i blackbox -p
451
452 Nagios check for the overall status. Useful if you want to set the rest
453 of the checks dependent from this one:
454
455 # ./pmp-check-aws-rds.py -i blackbox -m status
456 OK mysql 5.1.63. Status: available
457
458 Nagios check for CPU utilization, specify thresholds as percentage of
459 1-min., 5-min., 15-min. average accordingly:
460
461 # ./pmp-check-aws-rds.py -i blackbox -m load -w 90,85,80 -c 98,95,90
462 OK Load average: 18.36%, 18.51%, 15.95% | load1=18.36;90.0;98.0;0;100 load5=18.51;85.0;95.0;0;100 load15=15.95;80.0;90.0;0;100
463
464 Nagios check for the free memory, specify thresholds as percentage:
465
466 # ./pmp-check-aws-rds.py -i blackbox -m memory -w 5 -c 2
467 OK Free memory: 5.90 GB (9%) of 68 GB | free_memory=8.68;5.0;2.0;0;100
468 # ./pmp-check-aws-rds.py -i blackbox -m memory -u GB -w 4 -c 2
469 OK Free memory: 5.90 GB (9%) of 68 GB | free_memory=5.9;4.0;2.0;0;68
470
471 Nagios check for the free storage space, specify thresholds as percentage or GB:
472
473 # ./pmp-check-aws-rds.py -i blackbox -m storage -w 10 -c 5
474 OK Free storage: 162.55 GB (33%) of 500.0 GB | free_storage=32.51;10.0;5.0;0;100
475 # ./pmp-check-aws-rds.py -i blackbox -m storage -u GB -w 10 -c 5
476 OK Free storage: 162.55 GB (33%) of 500.0 GB | free_storage=162.55;10.0;5.0;0;500.0
477
478 By default, the region is set to ``us-east-1``. You can re-define it globally in boto config or
479 specify with -r option. The following command will list all instances across all regions under your AWS account:
480
481 # ./pmp-check-aws-rds.py -r all -l
482
483 The following command will show the status for the first instance identified as ``blackbox`` in all regions:
484
485 # ./pmp-check-aws-rds.py -r all -i blackbox -p
486
487 Remember, scanning regions are slower operation than specifying it explicitly.
488
489 =head1 CONFIGURATION
490
491 Here is the excerpt of potential Nagios config:
492
493 define host{
494 use mysql-host
495 host_name blackbox
496 alias blackbox
497 address blackbox.abcdefgh.us-east-1.rds.amazonaws.com
498 }
499
500 define servicedependency{
501 host_name blackbox
502 service_description RDS Status
503 dependent_service_description RDS Load Average, RDS Free Storage, RDS Free Memory
504 execution_failure_criteria w,c,u,p
505 notification_failure_criteria w,c,u,p
506 }
507
508 define service{
509 use active-service
510 host_name blackbox
511 service_description RDS Status
512 check_command check_rds!status!0!0
513 }
514
515 define service{
516 use active-service
517 host_name blackbox
518 service_description RDS Load Average
519 check_command check_rds!load!90,85,80!98,95,90
520 }
521
522 define service{
523 use active-service
524 host_name blackbox
525 service_description RDS Free Storage
526 check_command check_rds!storage!10!5
527 }
528
529 define service{
530 use active-service
531 host_name blackbox
532 service_description RDS Free Memory
533 check_command check_rds!memory!5!2
534 }
535
536 define command{
537 command_name check_rds
538 command_line $USER1$/pmp-check-aws-rds.py -i $HOSTALIAS$ -m $ARG1$ -w $ARG2$ -c $ARG3$
539 }
540
541 =head1 COPYRIGHT, LICENSE, AND WARRANTY
542
543 This program is copyright 2014 Percona LLC and/or its affiliates.
544 Feedback and improvements are welcome.
545
546 THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
547 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
548 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
549
550 This program is free software; you can redistribute it and/or modify it under
551 the terms of the GNU General Public License as published by the Free Software
552 Foundation, version 2. You should have received a copy of the GNU General
553 Public License along with this program; if not, write to the Free Software
554 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
555
556 =head1 VERSION
557
558 $PROJECT_NAME$ pmp-check-aws-rds.py $VERSION$
559
560 =cut
561
562 """