-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcheck_bareos.py
executable file
·768 lines (591 loc) · 28.9 KB
/
check_bareos.py
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
#!/usr/bin/python3
# Author : Philipp Posovszky, DLR
# E-Mail: [email protected]
# Date : 22/04/2015
#
# Modifications : Thomas Widhalm, NETWAYS GmbH
# E-Mail: [email protected]
#
# Modifications : Markus Opolka, NETWAYS GmbH
#
# This program is free software; you can redistribute it or modify
# it under the terms of the GNU General Public License version 3.0
import argparse
import sys
import re
import os
import psycopg2
import psycopg2.extras
# Constants
__version__ = '2.0.0'
OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3
JOBSTATES = {
'A': 'Job canceled by user',
'B': 'Job blocked',
'C': 'Job created but not yet running',
'D': 'Verify differences',
'E': 'Job terminated in error',
'F': 'Job waiting on File daemon',
'I': 'Incomplete Job',
'L': 'Committing data (last despool)',
'M': 'Job waiting for Mount',
'R': 'Job running',
'S': 'Job waiting on the Storage daemon',
'T': 'Job terminated normally',
'W': 'Job terminated normally with warnings',
'a': 'SD despooling attributes',
'c': 'Waiting for Client resource',
'd': 'Waiting for maximum jobs',
'e': 'Non-fatal error',
'f': 'Fatal error',
'i': 'Doing batch insert file records',
'j': 'Waiting for job resource',
'l': 'Doing data despooling',
'm': 'Waiting for new media',
'p': 'Waiting for higher priority jobs to finish',
'q': 'Queued waiting for device',
's': 'Waiting for storage resource',
't': 'Waiting for start time'
}
def read_password_from_file(fp):
"""
Tries to read a password from the given file
This allows to extract the password from the Bareos configuration
or from any other file that contains 'Password = secretpassword'
"""
l = []
password = None
# Extract the password from the given file
with open(fp, encoding='utf-8') as pwfile:
for line in pwfile:
line = line.strip()
if 'Password' in line:
l = line.split()
# Validate that we got a password
try:
password = l[2]
except IndexError:
pass
if not password:
raise ValueError('No password found in', fp)
return password
def check_threshold(value, warning, critical):
# checks a value against warning and critical thresholds
if critical is not None:
if not critical.check(value):
return CRITICAL
if warning is not None:
if not warning.check(value):
return WARNING
return OK
class Threshold:
def __init__(self, threshold):
self._threshold = str(threshold)
self._min = 0
self._max = 0
self._inclusive = False
self._parse(str(threshold))
def _parse(self, threshold):
match = re.search(r'^(@?)((~|\d*):)?(\d*)$', threshold)
if not match:
raise ValueError('Error parsing Threshold: {0}'.format(threshold))
if match.group(1) == '@':
self._inclusive = True
if match.group(3) == '~':
self._min = float('-inf')
elif match.group(3):
self._min = float(match.group(3))
else:
self._min = float(0)
if match.group(4):
self._max = float(match.group(4))
else:
self._max = float('inf')
if self._max < self._min:
raise ValueError('max must be superior to min')
def check(self, value):
# check if a value is correct according to threshold
if self._inclusive:
return False if self._min <= value <= self._max else True # pylint: disable=simplifiable-if-expression
return False if value > self._max or value < self._min else True # pylint: disable=simplifiable-if-expression
def __repr__(self) -> str:
return '{0}({1})'.format(self.__class__.__name__, self._threshold)
def __str__(self) -> str:
return self._threshold
def createBackupKindString(full, inc, diff):
if full is False and inc is False and diff is False:
return "'F','D','I'"
kind = []
if full:
kind.append("'F'")
if inc:
kind.append("'I'")
if diff:
kind.append("'D'")
return ",".join(kind)
def createFactor(unit):
options = {'EB': 2 ** 60,
'PB': 2 ** 50,
'TB': 2 ** 40,
'GB': 2 ** 30,
'MB': 10 ** 20}
return options[unit]
def checkFailedBackups(cursor, time, warning, critical):
checkState = {}
if time is None:
time = 7
query = """
SELECT Job.Name,Level,starttime, JobStatus
FROM Job
WHERE JobStatus in ('E','f') AND starttime > (now()::date-""" + str(time) + """ * '1 day'::INTERVAL);
"""
cursor.execute(query)
results = cursor.fetchall()
result = len(results)
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Backups failed/canceled in the last " + str(time) + " days"
checkState["performanceData"] = "bareos.backup.failed=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkBackupSize(cursor, time, kind, factor):
query = """
SELECT ROUND(SUM(JobBytes/""" + str(float(factor)) + """),3)
FROM Job
Where Level in (""" + kind + """);
"""
if time is not None:
query = """
SELECT ROUND(SUM(JobBytes/""" + str(float(factor)) + """),3)
FROM Job
Where Level in (""" + kind + """) and starttime > (now()-""" + str(time) + """ * '1 day'::INTERVAL) ;
"""
cursor.execute(query)
results = cursor.fetchone()
return results[0]
def checkTotalBackupSize(cursor, time, kind, unit, warning, critical):
checkState = {}
result = checkBackupSize(cursor, time, kind, createFactor(unit))
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " " + unit + " Kind:" + kind
if time:
checkState["returnMessage"] += " Days: " + str(time)
checkState["performanceData"] = "bareos.backup.size=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkOversizedBackups(cursor, time, size, kind, unit, warning, critical):
checkState = {}
if time is None:
time = 7
factor = createFactor(unit)
query = """
SELECT Job.Name,Level,starttime, JobBytes/""" + str(float(factor)) + """
FROM Job
WHERE Level in (""" + kind + """) AND starttime > (now()::date-""" + str(time) + """ * '1 day'::INTERVAL) AND JobBytes/""" + str(float(factor)) + """>""" + str(size) + """;
"""
cursor.execute(query)
results = cursor.fetchall()
result = len(results)
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " " + kind + " Backups larger than " + str(size) + " " + unit + " in the last " + str(time) + " days"
checkState["performanceData"] = "bareos.backup.oversized=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkEmptyBackups(cursor, time, kind, warning, critical):
checkState = {}
if time is None:
time = 7
query = """
SELECT Job.Name,Level,starttime
FROM Job
WHERE Level in (""" + str(kind) + """) AND JobBytes=0 AND starttime > (now()::date-""" + str(time) + """ * '1 day'::INTERVAL) AND JobStatus in ('T');
"""
cursor.execute(query)
results = cursor.fetchall()
result = len(results)
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL] - " + str(result) + " successful " + str(kind) + " backups are empty"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING] - " + str(result) + " successful " + str(kind) + " backups are empty!"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK] - All " + str(kind) + " Backups are fine"
checkState["performanceData"] = "bareos.backup.empty=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkJobs(cursor, state, kind, time, warning, critical):
checkState = {}
if time is None:
time = 7
query = """
SELECT count(Job.Name)
FROM Job
WHERE Job.JobStatus like '""" + str(state) + """' AND (starttime > (now()::date-""" + str(time) + """ * '1 day'::INTERVAL) OR starttime IS NULL) AND Job.Level in (""" + kind + """);
"""
cursor.execute(query)
results = cursor.fetchone()
result = float(results[0])
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Jobs are in the state: " + JOBSTATES.get(state, state)
checkState["performanceData"] = "'bareos." + JOBSTATES.get(state, state) + "'=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkSingleJob(cursor, name, state, kind, time, warning, critical):
checkState = {}
# Return on empty name
if not name:
checkState["returnCode"] = UNKNOWN
checkState["returnMessage"] = "[UNKNOWN] - Job Name missing"
return checkState
if time is None:
time = 7
query = """
SELECT Job.Name,Job.JobStatus, Job.Starttime
FROM Job
WHERE Job.Name like '%"""+name+"""%' AND Job.JobStatus like '"""+state+"""' AND (starttime > (now()::date-"""+str(time)+""" * '1 day'::INTERVAL) OR starttime IS NULL) AND Job.Level in ("""+kind+""");
"""
cursor.execute(query)
results = cursor.fetchall()
result = len(results)
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Jobs are in the state: " + JOBSTATES.get(state, state)
checkState["performanceData"] = "'bareos." + JOBSTATES.get(state, state) + "'=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkRunTimeJobs(cursor, state, time, warning, critical):
checkState = {}
if time is None:
time = 7
query = """
SELECT Count(Job.Name)
FROM Job
WHERE starttime < (now()::date-""" + str(time) + """ * '1 day'::INTERVAL) AND Job.JobStatus like '""" + state + """';
"""
cursor.execute(query)
results = cursor.fetchone()
result = float(results[0])
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Jobs in state '" + JOBSTATES.get(state, state) + "' are running longer than " + str(time) + " days"
checkState["performanceData"] = "bareos.job.count=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkTapesInStorage(cursor, warning, critical):
checkState = {}
query = """
SELECT count(MediaId)
FROM Media,Pool,Storage
WHERE Media.PoolId=Pool.PoolId
AND Slot>0 AND InChanger=1
AND Media.StorageId=Storage.StorageId;
"""
cursor.execute(query)
results = cursor.fetchone()
result = float(results[0])
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Tapes are in the Storage"
checkState["performanceData"] = "bareos.tape.instorage=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkExpiredTapes(cursor, warning, critical):
checkState = {}
query = """
SELECT Count(MediaId)
FROM Media
WHERE lastwritten+(media.volretention * '1 second'::INTERVAL)<now() AND volstatus not like 'Error';
"""
cursor.execute(query)
results = cursor.fetchone()
result = float(results[0])
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Tapes are expired"
checkState["performanceData"] = "bareos.tape.expired=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkWillExpiredTapes(cursor, time, warning, critical):
checkState = {}
query = """
SELECT Count(MediaId)
FROM Media
WHERE lastwritten+(media.volretention * '1 second'::INTERVAL)<now()+(""" + str(time) + """ * '1 day'::INTERVAL) AND lastwritten+(media.volretention * '1 second'::INTERVAL)>now() AND volstatus not like 'Error';;
"""
cursor.execute(query)
results = cursor.fetchone()
result = float(results[0])
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Tapes will expire in " + str(time) + " days"
checkState["performanceData"] = "bareos.tape.willexpire=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkReplaceTapes(cursor, mounts, warning, critical):
checkState = {}
query = """
SELECT COUNT(VolumeName)
FROM Media
WHERE (VolErrors>0) OR (VolStatus='Error') OR (VolMounts>""" + str(mounts) + """) OR (VolStatus='Disabled');
"""
cursor.execute(query)
results = cursor.fetchone()
result = float(results[0])
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Tapes might need replacement"
checkState["performanceData"] = "bareos.tape.replace=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def checkEmptyTapes(cursor, warning, critical):
checkState = {}
query = """
SELECT Count(MediaId)
FROM Media,Pool,Storage
WHERE Media.PoolId=Pool.PoolId
AND Slot>0 AND InChanger=1
AND Media.StorageId=Storage.StorageId
AND (VolStatus like 'Purged' OR VolStatus like 'Recycle' OR lastwritten+(media.volretention * '1 second'::INTERVAL)<now() AND VolStatus not like 'Error');
"""
cursor.execute(query)
results = cursor.fetchone()
result = float(results[0])
if check_threshold(result, warning=warning, critical=critical) == CRITICAL:
checkState["returnCode"] = CRITICAL
checkState["returnMessage"] = "[CRITICAL]"
elif check_threshold(result, warning=warning, critical=critical) == WARNING:
checkState["returnCode"] = WARNING
checkState["returnMessage"] = "[WARNING]"
else:
checkState["returnCode"] = OK
checkState["returnMessage"] = "[OK]"
checkState["returnMessage"] += " - " + str(result) + " Tapes are empty"
checkState["performanceData"] = "bareos.tape.empty=" + str(result) + ";" + str(warning) + ";" + str(critical) + ";;"
return checkState
def connectDB(username, pw, hostname, databasename, port):
try:
connString = "host='" + hostname + "' port=" + str(port) + " dbname='" + databasename + "' user='" + username + "' password='" + pw + "'"
conn = psycopg2.connect(connString)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
return cursor
except psycopg2.DatabaseError as e:
checkState = {}
checkState["returnCode"] = UNKNOWN
checkState["returnMessage"] = "[UNKNOWN] - " + str(e)[:-1]
checkState["performanceData"] = ";;;;"
printNagiosOutput(checkState)
def printNagiosOutput(checkResult):
if checkResult is not None:
print((checkResult["returnMessage"] + "|" + checkResult.get("performanceData", ";;;;")))
sys.exit(checkResult["returnCode"])
print("[UNKNOWN] - Error in Script")
sys.exit(3)
def commandline(args):
"""
Parse commandline arguments.
"""
def environ_or_required(key):
return ({'default': os.environ.get(key)} if os.environ.get(key) else {})
parser = argparse.ArgumentParser(description='Check Plugin for Bareos Backup Status')
group = parser.add_argument_group()
group.add_argument('-U', '--user', dest='user', action='store', required=True, help='user name for the database connections')
password_group = group.add_mutually_exclusive_group()
password_group.add_argument('-p', '--password', dest='password', action='store',
**environ_or_required('CHECK_BAREOS_DATABASE_PASSWORD'),
help='password for the database connections (CHECK_BAREOS_DATABASE_PASSWORD)')
password_group.add_argument('--password-file', dest='password_file', action='store',
default='/etc/bareos/bareos-dir.conf',
help='path to a password file. Can be the bareos-dir.conf')
group.add_argument('-H', '--Host', dest='host', action='store', help='database host', default="127.0.0.1")
group.add_argument('-P', '--port', dest='port', action='store', help='database port', default=5432, type=int)
group.add_argument('-d', '--database', dest='database', default='bareos', help='database name')
group.add_argument('-v', '--version', action='version', version=f'%(prog)s {__version__}')
subParser = parser.add_subparsers()
jobParser = subParser.add_parser('job', help='Subchecks for Bareos Jobs')
jobGroup = jobParser.add_mutually_exclusive_group(required=True)
jobParser.set_defaults(func=checkJob)
jobGroup.add_argument('-js', '--checkJobs', dest='checkJobs', action='store_true', help='Check how many jobs are in a specific state [default=queued]')
jobGroup.add_argument('-j', '--checkJob', dest='checkJob', action='store_true', help='Check the state of a specific job [default=queued]')
jobGroup.add_argument('-rt', '--runTimeJobs', dest='runTimeJobs', action='store_true', help='Check if a backup runs longer then n day')
jobParser.add_argument('-n', '--name', dest='name', action='store', help='Name of the job')
jobParser.add_argument('-t', '--time', dest='time', action='store', help='Time in days (default=7 days)')
jobParser.add_argument('-u', '--unit', dest='unit', choices=['GB', 'TB', 'PB'], default='TB', help='display unit')
jobParser.add_argument('-w', '--warning', dest='warning', action='store', help='Warning threshold', default=5)
jobParser.add_argument('-c', '--critical', dest='critical', action='store', help='Critical threshold', default=10)
jobParser.add_argument('-st', '--state', dest='state', choices=JOBSTATES.keys(), default='C', help='Bareos Job State [default=C]')
jobParser.add_argument('-f', '--full', dest='full', action='store_true', help='Backup kind full')
jobParser.add_argument('-i', '--inc', dest='inc', action='store_true', help='Backup kind inc')
jobParser.add_argument('-d', '--diff', dest='diff', action='store_true', help='Backup kind diff')
tapeParser = subParser.add_parser('tape', help='Subcheck for Bareos States')
tapeGroup = tapeParser.add_mutually_exclusive_group(required=True)
tapeParser.set_defaults(func=checkTape)
tapeGroup.add_argument('-e', '--emptyTapes', dest='emptyTapes', action='store_true', help='Count empty tapes in the storage (Status Purged/Expired)')
tapeGroup.add_argument('-ts', '--tapesInStorage', dest='tapesInStorage', action='store_true', help='Count how much tapes are in the storage')
tapeGroup.add_argument('-ex', '--expiredTapes', dest='expiredTapes', action='store_true', help='Count how much tapes are expired')
tapeGroup.add_argument('-wex', '--willExpire', dest='willExpire', action='store_true', help='Count how much tapes are will expire in n day')
tapeGroup.add_argument('-r', '--replaceTapes', dest='replaceTapes', action='store_true', help='Count how much tapes should by replaced')
tapeParser.add_argument('-w', '--warning', dest='warning', action='store', help='Warning threshold', default=5)
tapeParser.add_argument('-c', '--critical', dest='critical', action='store', help='Critical threshold', default=10)
tapeParser.add_argument('-m', '--mounts', dest='mounts', action='store', help='Amout of allowed mounts for a tape [used for replace tapes]', default=200)
tapeParser.add_argument('-t', '--time', dest='time', action='store', help='Time in days (default=7 days)', default=7)
statusParser = subParser.add_parser('status', help='Subcheck for various Bareos information')
statusGroup = statusParser.add_mutually_exclusive_group(required=True)
statusParser.set_defaults(func=checkStatus)
statusGroup.add_argument('-b', '--totalBackupsSize', dest='totalBackupsSize', action='store_true', help='the size of all backups in the database [use time and kind for mor restrictions]')
statusGroup.add_argument('-e', '--emptyBackups', dest='emptyBackups', action='store_true', help='Check if a successful backup have 0 bytes [only wise for full backups]')
statusGroup.add_argument('-o', '--oversizedBackup', dest='oversizedBackups', action='store_true', help='Check if a backup have more than n TB')
statusGroup.add_argument('-fb', '--failedBackups', dest='failedBackups', action='store_true', help='Check if a backup failed in the last n day')
statusParser.add_argument('-f', '--full', dest='full', action='store_true', help='Backup kind full')
statusParser.add_argument('-i', '--inc', dest='inc', action='store_true', help='Backup kind inc')
statusParser.add_argument('-d', '--diff', dest='diff', action='store_true', help='Backup kind diff')
statusParser.add_argument('-t', '--time', dest='time', action='store', help='Time in days')
statusParser.add_argument('-w', '--warning', dest='warning', action='store', help='Warning threshold [default=5]', default="5")
statusParser.add_argument('-c', '--critical', dest='critical', action='store', help='Critical threshold [default=10]', default="10")
statusParser.add_argument('-s', '--size', dest='size', action='store', help='Border value for oversized backups [default=2]', default=2)
statusParser.add_argument('-u', '--unit', dest='unit', choices=['MB', 'GB', 'TB', 'PB', 'EB'], default='TB', help='display unit [default=TB]')
parsed = parser.parse_args(args)
if not hasattr(parsed, 'func'):
print("[UNKNOWN] - Error: Object to check is missing")
parser.print_help()
sys.exit(3)
return parsed
def checkConnection(cursor):
if cursor is None:
checkResult = {}
checkResult["returnCode"] = UNKNOWN
checkResult["returnMessage"] = "[UNKNOWN] - No DB connection"
printNagiosOutput(checkResult)
return True
def checkTape(args):
cursor = connectDB(args.user, args.password, args.host, args.database, args.port)
checkConnection(cursor)
warning = Threshold(args.warning)
critical = Threshold(args.critical)
checkResult = {}
if args.emptyTapes:
checkResult = checkEmptyTapes(cursor, warning, critical)
if args.replaceTapes:
checkResult = checkReplaceTapes(cursor, args.mounts, warning, critical)
elif args.tapesInStorage:
checkResult = checkTapesInStorage(cursor, warning, critical)
elif args.expiredTapes:
checkResult = checkExpiredTapes(cursor, warning, critical)
elif args.willExpire:
checkResult = checkWillExpiredTapes(cursor, args.time, warning, critical)
printNagiosOutput(checkResult)
cursor.close()
def checkJob(args):
cursor = connectDB(args.user, args.password, args.host, args.database, args.port)
checkConnection(cursor)
warning = Threshold(args.warning)
critical = Threshold(args.critical)
checkResult = {}
if args.checkJob:
kind = createBackupKindString(args.full, args.inc, args.diff)
checkResult = checkSingleJob(cursor, args.name, args.state, kind, args.time, warning, critical)
elif args.checkJobs:
kind = createBackupKindString(args.full, args.inc, args.diff)
checkResult = checkJobs(cursor, args.state, kind, args.time, warning, critical)
elif args.runTimeJobs:
checkResult = checkRunTimeJobs(cursor, args.state, args.time, warning, critical)
printNagiosOutput(checkResult)
cursor.close()
def checkStatus(args):
cursor = connectDB(args.user, args.password, args.host, args.database, args.port)
checkConnection(cursor)
warning = Threshold(args.warning)
critical = Threshold(args.critical)
checkResult = {}
if args.emptyBackups:
kind = createBackupKindString(args.full, args.inc, args.diff)
checkResult = checkEmptyBackups(cursor, args.time, kind, warning, critical)
elif args.totalBackupsSize:
kind = createBackupKindString(args.full, args.inc, args.diff)
checkResult = checkTotalBackupSize(cursor, args.time, kind, args.unit, warning, critical)
elif args.oversizedBackups:
kind = createBackupKindString(args.full, args.inc, args.diff)
checkResult = checkOversizedBackups(cursor, args.time, args.size, kind, args.unit, warning, critical)
elif args.failedBackups:
kind = createBackupKindString(args.full, args.inc, args.diff)
checkResult = checkFailedBackups(cursor, args.time, warning, critical)
printNagiosOutput(checkResult)
cursor.close()
if __name__ == '__main__': # pragma: no cover
try:
ARGS = commandline(sys.argv[1:])
if ARGS.password_file and not ARGS.password:
ARGS.password = read_password_from_file(ARGS.password_file)
ARGS.func(ARGS)
except SystemExit:
# Re-throw the exception
raise sys.exc_info()[1].with_traceback(sys.exc_info()[2]) # pylint: disable=raise-missing-from
except: # pylint: disable=bare-except
print("[UNKNOWN] - Error: %s" % (str(sys.exc_info()[1])))
sys.exit(3)