forked from twpayne/nagios-plugin-bacula
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcheck_bacula_client
executable file
·249 lines (210 loc) · 7.32 KB
/
check_bacula_client
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
#!/usr/bin/env python3
#
# check_bacula_client Nagios plugin to check Bacula client backups
# Copyright (C) 2010 Tom Payne
# Copyright (C) 2024 Julien Riou
# Copyright (C) 2024 Stefan Meinecke
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime, timedelta
from optparse import OptionParser, OptionValueError, Option
import re
import sys
import time
from typing import Optional, Tuple, List
import pexpect
OK, WARNING, CRITICAL, UNKNOWN = range(0, 4)
STATUS_MESSAGES = "OK WARNING CRITICAL UNKNOWN".split()
MULTIPLIERS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
DIVISORS = ((60, "minutes"), (60, "hours"), (24, "days"), (7, "weeks"))
JOB_INFO_RE = re.compile(r"""^\s*(?P<job_id>\d+)\s+(?P<level>\S+)\s+(?P<files>\S+)\s+(?P<size>\d+\.\d+\s+[KMGTP]|\d+)\s+(?P<status>\S+)\s+(?P<finished>\S+\s+\S+)\s+(?P<name>\w+)""", re.I)
def parse_period(
option: Option,
opt_str: str,
value: str,
parser: OptionParser
) -> None:
"""
Parse a period option that is a floating point number followed by a
unit of time (s, m, h, d, w). The result is a timedelta object.
Args:
option: Option object
opt_str: str, the option string
value: str, the value of the option
parser: OptionParser object
Returns:
None
"""
m = re.match(
r"(\d+(?:\.\d+)?)(%s)\Z" % "|".join(MULTIPLIERS.keys()), value
)
if not m:
raise OptionValueError("invalid period - %s" % value)
# Set the attribute with the parsed value
setattr(
parser.values,
option.dest,
timedelta(seconds=float(m.group(1)) * MULTIPLIERS[m.group(2)]),
)
def get_job_info(
bconsole_bin: str,
bareos: bool,
client_id: str,
backup_job_name: Optional[str],
warn_thres: Optional[timedelta],
crit_thres: Optional[timedelta]
) -> Tuple[int, str]:
"""Get information about a job from the bconsole
Args:
bconsole_bin: the path to the bconsole binary
bareos: whether or not the bconsole is bareos
client_id: the name of the client
backup_job_name: the name of the backup job
warn_thres: the timedelta for warning
crit_thres: the timedelta for critical
Returns:
tuple: exit_status (int) and message (str)
"""
# Set default status
exit_status, message = OK, None
# Connect to the bconsole
child = pexpect.spawn(bconsole_bin, ["-n"] if not bareos else [])
try:
child.expect(r"\*$")
child.sendline("status client=%s" % client_id)
# Error list to check for if the client does not exist or job has failed
patterns = child.compile_pattern_list([
r"Terminated Jobs:",
r"Error: Client resource .* does not exist.",
r"Failed to connect to Client",
pexpect.TIMEOUT,
])
if child.expect_list(patterns):
raise RuntimeError("Timeout, Failed to connect or unknown client: %s" % client_id)
child.expect(r"\*$")
jobs = {}
for line in child.before.splitlines():
m = JOB_INFO_RE.match(line.decode("utf-8"))
if not m:
continue
job = m.groupdict()
job['id'] = int(job['job_id'])
job['files'] = int(re.sub(r",", "", job['files']))
job['size'] = re.sub(r"\s+", "", job['size'])
job['finished'] = datetime(*(time.strptime(job['finished'], "%d-%b-%y %H:%M")[0:6]))
jobs[job['name']] = job
if not jobs:
raise RuntimeError("no terminated jobs")
messages = []
for job_name, job in jobs.items():
if backup_job_name and backup_job_name != job_name:
continue
age = datetime.now() - job['finished']
if job['status'] == 'OK':
if crit_thres and age > crit_thres:
exit_status = CRITICAL
elif warn_thres and age > warn_thres:
exit_status = WARNING
else:
exit_status = CRITICAL
# Format age in human readable format
age, units = 24.0 * 60 * 60 * age.days + age.seconds, "seconds"
for d, u in DIVISORS:
if age < d:
break
else:
age /= d
units = u
messages.append("%s, %s, %d files, %sB, %s (%.1f %s ago)" % (
job['name'],
job['status'],
job['files'],
job['size'],
job['finished'],
age,
units
))
if not messages:
raise RuntimeError("no successful jobs")
message = "\n".join(messages)
except RuntimeError:
exit_status, message = (CRITICAL, str(sys.exc_info()[1]))
child.sendeof()
child.expect_list(child.compile_pattern_list([pexpect.EOF, pexpect.TIMEOUT]))
return exit_status, message
def main(argv: List[str]) -> int:
"""
Main entry point
Args:
argv: list of command line arguments
Returns:
int: exit code
"""
parser = OptionParser()
parser.add_option(
"-H", metavar="FD_NAME", dest="client_id", help="client file director name"
)
parser.add_option(
"-B", metavar="BACKUP_NAME", dest="job_name", help="backup job name"
)
parser.add_option(
"-w",
metavar="PERIOD",
type=str,
dest="warning",
action="callback",
callback=parse_period,
help="generate warning if last successful backup older than PERIOD",
)
parser.add_option(
"-c",
metavar="PERIOD",
type=str,
dest="critical",
action="callback",
callback=parse_period,
help="generate critical if last successful backup older than PERIOD",
)
parser.add_option(
"--bareos",
action="store_true",
dest="bareos",
help="use bareos client (remove the unknown argument -n from bconsole)",
default=False,
)
parser.add_option(
"-b",
metavar="PATH",
dest="bconsole_bin",
help="path to bconsole",
default="/usr/sbin/bconsole",
)
options, args = parser.parse_args(argv[1:])
# If client_id is not provided, show help
if not options.client_id:
print("Missing -H option")
parser.print_help()
return(CRITICAL)
exit_status, message = get_job_info(
options.bconsole_bin,
options.bareos,
options.client_id,
options.job_name,
options.warning,
options.critical,
)
print(f"{STATUS_MESSAGES[exit_status]}: {message}")
return exit_status
if __name__ == "__main__":
sys.exit(main(sys.argv))