forked from roland-gsell/check_proxmox_backups
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_proxmox_backup.py
580 lines (511 loc) · 19.5 KB
/
check_proxmox_backup.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
#!/usr/bin/env python3
"""
Tool for checking all VM-Backups for Proxmox at once.
It reads the current backup schedule and storage config
to check the relevant backup logs.
Author: Roland Gsell
E-Mail: [email protected]
2017 by Siedl Networks
enhanced by: IT-Native <[email protected]>
"""
from pyproxmox import prox_auth, pyproxmox
import urllib3
from datetime import datetime, date, timedelta
import fnmatch
import os
from optparse import OptionParser
import configparser
import string
import sys
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class Nagios:
ok = (0, 'OK')
warning = (1, 'WARNING')
critical = (2, 'CRITICAL')
unknown = (3, 'UNKNOWN')
nagios = Nagios()
def nagiosExit(exit_code, msg=None):
"""Exit script with a str() message and an integer 'nagios_code', which is a sys.exit level."""
if msg:
print(exit_code[0], exit_code[1] + " - " + str(msg))
sys.exit(exit_code[0])
parser = OptionParser()
parser.add_option("-u",
"--user",
dest="user",
default='',
help="User to connect to PVE")
parser.add_option("-p",
"--password",
dest="password",
default='',
help="Password for the API-User")
parser.add_option("-s",
"--host",
dest="host",
default='',
help="PVE-Server")
parser.add_option("-P",
"--path",
dest="path",
default='',
help="Path to VM Backup")
parser.add_option("-f",
"--file",
dest="apifile",
default='',
help="Path to API Configuration File")
parser.add_option("-d",
"--debug",
dest="debug",
default=False,
action="store_true",
help="Turn on debug mode")
(options, args) = parser.parse_args()
def printdebug(string):
if options.debug:
print(string)
def parse_days(days: str) -> list:
# https://pve.proxmox.com/pve-docs/pve-admin-guide.html#chapter_calendar_events
#check if contains weekday
days_of_week = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
if days == '*':
days = ','.join(days_of_week)
if any(ext in days for ext in days_of_week):
days = days.split(',')
if len(days) == 1:
days = days[0].split('..')
start = days_of_week.index(days[0])
end = days_of_week.index(days[1])
if end < start:
days = days_of_week[start : ] + days_of_week[ : end+1 ]
else:
days = days_of_week[start : end +1]
return(days)
else:
printdebug("Not a valid day input!")
def parse_time(time: str) -> tuple[int,int]:
# https://pve.proxmox.com/pve-docs/pve-admin-guide.html#chapter_calendar_events
time = time.split('..')
if len(time) == 2:
print("range", time)
else:
time = time[0].split(',')
if len(time) == 2:
print("list", time)
else:
time = time[0].split(':')
hours = int(time[0])
minutes = int(time[1])
if 0 <= hours < 24 and 0 <= minutes < 60:
return (hours, minutes)
#.split('/')
def getweekday(weekdaynumber):
weekday = ''
if weekdaynumber == 0:
weekday = 'mon'
elif weekdaynumber == 1:
weekday = 'tue'
elif weekdaynumber == 2:
weekday = 'wed'
elif weekdaynumber == 3:
weekday = 'thu'
elif weekdaynumber == 4:
weekday = 'fri'
elif weekdaynumber == 5:
weekday = 'sat'
elif weekdaynumber == 6:
weekday = 'sun'
return weekday
errorcodes = ['nobak', 'failed', 'running', '2old']
okcodes = ['ok']
def readlogfile(path, vmid, date, oneday2old=False):
found = False
backupok = False
code = ''
printdebug('Checking this pattern: ' + path + '/' + 'vzdump-*' + str(vmid) + '-' + date + '*.log')
for filename in os.listdir(path):
if fnmatch.fnmatch(filename, 'vzdump-*' + str(vmid) + '-' + date + '*.log'):
printdebug('Checking Filename: ' + filename)
try:
with open(path + '/' + filename, 'r') as f:
found = True
if oneday2old:
printdebug("WARNING - Found backup, but older than expected: " + str(vmid))
printdebug('Found and could open: ' + filename)
try:
lastline = f.readlines()[-1]
printdebug(lastline)
if 'INFO: Finished Backup' in lastline:
printdebug("OK")
backupok = True
code = 'ok'
elif 'ERROR: ' in lastline:
if not backupok:
code = 'failed'
printdebug("Backup failed")
elif 'INFO: status:' in lastline:
if not backupok:
code = 'running'
printdebug("Backup currently running")
else:
if not backupok:
code = 'nobak'
printdebug("Error: " + str(vmid))
except Exception:
printdebug("Cant read file")
except Exception:
printdebug("Cant open file")
return code, found
today = date.today()
datetimetoday = datetime.today()
# These values won't be altered later on
weekdaynumber_today = today.weekday()
weekday_today = getweekday(weekdaynumber_today)
printdebug("Today : " + weekday_today)
host = ''
user = ''
password = ''
if options.apifile != '':
config = configparser.ConfigParser()
config.optionxform = str
config.read(options.apifile)
try:
host = config.get('global', 'host')
user = config.get('global', 'user')
password = config.get('global', 'password')
except Exception:
message = 'Problem with api conf file'
nagiosExit(nagios.unknown, str(message))
else:
if options.user == '':
message = 'No username given, use -u'
nagiosExit(nagios.unknown, str(message))
else:
user = options.user
if options.password == '':
message = 'No Password given, use -p'
nagiosExit(nagios.unknown, str(message))
else:
password = options.password
if options.host == '':
message = 'No host given, use -s'
nagiosExit(nagios.unknown, str(message))
else:
host = options.host
auth = prox_auth(host, user, password)
prox = pyproxmox(auth)
# status = prox.getClusterStatus()
# print status
# config = prox.getClusterConfig()
# print config
# nextid = prox.getClusterVmNextId()
# print nextid
schedule = prox.getClusterBackupSchedule()
printdebug("Schedule(s):")
printdebug(str(schedule))
resources = prox.getClusterResources()
backup_all = False
vmid_status = {}
for i in schedule['data']:
if i['enabled'] == 1:
try:
if i['all'] == 1:
backup_all = True
for j in resources['data']:
try:
vmid_status[int(j['vmid'])] = 'nochk'
except Exception:
pass
except Exception:
for vmid in i['vmid'].split(","):
vmid_status[int(vmid)] = 'nochk'
for i in schedule['data']:
if i['enabled'] == 1:
try:
if i['all'] == 1:
try:
for exclude in i['exclude'].split(","):
vmid_status.pop(int(exclude), 0)
except Exception:
pass
except Exception:
pass
# Debug: Add a non-existent VM
# vmid_status[200] = 'nochk'
# printdebug("VMID status before: " + str(vmid_status))
# Iterate over all schedules
for i in schedule['data']:
weekdaynumber = today.weekday()
weekday = getweekday(weekdaynumber)
printdebug("------------")
printdebug("Storage : " + i['storage'])
#check if dow or schedule is there
if hasattr(i, 'dow') and hasattr(i, 'starttime'):
printdebug('Weekdays : ' + i['dow'])
starttimetoday = datetime(datetimetoday.year,
datetimetoday.month,
datetimetoday.day,
int(i['starttime'][:2]),
int(i['starttime'][3:]))
now = datetime(datetimetoday.year,
datetimetoday.month,
datetimetoday.day,
datetimetoday.hour,
datetimetoday.minute)
printdebug("Start time : " + str(i['starttime']))
printdebug("Now : " + str(now))
if now < starttimetoday:
printdebug("Start time not reached today - going back one day")
if weekdaynumber == 0:
weekdaynumber = 6
else:
weekdaynumber -= 1
weekday = getweekday(weekdaynumber)
date_to_check = date.today() - timedelta(days=1)
else:
printdebug("Start time reached today")
date_to_check = date.today()
try:
printdebug("VM-IDs : " + i['vmid'])
except Exception:
pass
days = i['dow'].split(",")
nrdays = []
for day in days:
if day == 'mon':
backup_weekdaynumber = 0
elif day == 'tue':
backup_weekdaynumber = 1
elif day == 'wed':
backup_weekdaynumber = 2
elif day == 'thu':
backup_weekdaynumber = 3
elif day == 'fri':
backup_weekdaynumber = 4
elif day == 'sat':
backup_weekdaynumber = 5
elif day == 'sun':
backup_weekdaynumber = 6
nrdays.append(backup_weekdaynumber)
vmids = []
# Debug: Add a non-existent VM
# vmids.append(200)
printdebug("Days of backup : " + str(nrdays))
if weekday in i['dow']:
printdebug("Weekday found: " + weekday)
printdebug("Date to check: " + str(date_to_check))
else:
printdebug("Today no backup should be done.")
days_to_go_back = 0
for _ in range(7):
# going back up to 7 times to find the first matching day to do the backup
days_to_go_back += 1
weekdaynumber -= 1
if weekdaynumber < 0:
weekdaynumber = 6
weekday = getweekday(weekdaynumber) #TODO better solution?
if weekday in i['dow']:
printdebug("Weekday found: " + weekday)
date_to_check = date.today() - timedelta(days=days_to_go_back)
printdebug("Days to go back: " + str(days_to_go_back))
printdebug("Date to check: " + str(date_to_check))
break
else:
printdebug('PVE version >=7 backup definition')
sched = i['schedule']
sched = sched.split(' ')
if len(sched) == 2:
days = sched[0]
days = parse_days(days)
time = sched[1]
time = parse_time(time)
else:
sched = sched[0]
days = parse_days(sched)
if days is None:
days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
time = parse_time(sched)
starttimetoday = datetime(datetimetoday.year,
datetimetoday.month,
datetimetoday.day,
int(time[0]),
int(time[1]))
now = datetime(datetimetoday.year,
datetimetoday.month,
datetimetoday.day,
datetimetoday.hour,
datetimetoday.minute)
printdebug("Start time : " + str(starttimetoday))
printdebug("Now : " + str(now))
if now < starttimetoday:
printdebug("Start time not reached today - going back one day")
if weekdaynumber == 0:
weekdaynumber = 6
else:
weekdaynumber -= 1
weekday = getweekday(weekdaynumber)
date_to_check = date.today() - timedelta(days=1)
else:
printdebug("Start time reached today")
date_to_check = date.today()
try:
printdebug("VM-IDs : " + i['vmid'])
except Exception:
pass
nrdays = []
for day in days:
if day == 'mon':
backup_weekdaynumber = 0
elif day == 'tue':
backup_weekdaynumber = 1
elif day == 'wed':
backup_weekdaynumber = 2
elif day == 'thu':
backup_weekdaynumber = 3
elif day == 'fri':
backup_weekdaynumber = 4
elif day == 'sat':
backup_weekdaynumber = 5
elif day == 'sun':
backup_weekdaynumber = 6
nrdays.append(backup_weekdaynumber)
vmids = []
#Debug: Add a non-existent VM
#vmids.append(200)
printdebug("Days of backup : " + str(nrdays))
if weekday in days:
printdebug("Weekday found: " + weekday)
printdebug("Date to check: " + str(date_to_check))
else:
printdebug("Today no backup should be done.")
days_to_go_back = 0
for _ in range(7):
# going back up to 7 times to find the first matching day to do the backup
days_to_go_back += 1
weekdaynumber -= 1
if weekdaynumber < 0:
weekdaynumber = 6
weekday = getweekday(weekdaynumber) #TODO better solution?
if weekday in days:
printdebug("Weekday found: " + weekday)
date_to_check = date.today() - timedelta(days=days_to_go_back)
printdebug("Days to go back: " + str(days_to_go_back))
printdebug("Date to check: " + str(date_to_check))
break
storage = prox.getStorageConfig(i['storage'])
printdebug("Storage-Config: " + str(storage))
if options.path == '':
path = storage['data']['path'] + '/dump'
else:
path = options.path
for (vmid, status) in vmid_status.items():
if not backup_all:
# get the VM ids of the specific schedule:
vmids_schedule = []
for sched in i['vmid'].split(','):
vmids_schedule.append(int(sched))
# and check only those
if vmid not in vmids_schedule:
continue
printdebug(" ")
printdebug("Checking VM-ID: " + str(vmid))
printdebug("Checking Path : " + str(path))
date_underscore = (str(date_to_check)).replace( '-', '_')
printdebug('Date with underscores: ' + date_underscore)
if vmid_status[int(vmid)] != 'ok':
vmid_status[int(vmid)], found = readlogfile(path, vmid, date_underscore)
else:
printdebug("log file already checked in another schedule and is ok: " + str(vmid))
found = True
if not found:
# No luck?
# Lets see if we find a backup, which is older and return a warning instead
for j in range(1, 8):
date_to_check_again = date_to_check - timedelta(days=j)
date_underscore_again = (str(date_to_check_again)).replace('-', '_')
if vmid_status[int(vmid)] != 'ok':
vmid_status[int(vmid)], found = readlogfile(path, vmid, date_underscore_again, True)
if vmid_status[int(vmid)] == 'ok':
vmid_status[int(vmid)] = '2old'
break
else:
found = False
if not found or vmid_status[int(vmid)] not in okcodes:
# didn't find anything or found a broken one
# So let's find any backup which is newer and worked
date_to_check_again = date_to_check + timedelta(days=1)
while date_to_check_again <= date.today():
# print(type(date_to_check_again))
printdebug('Checking the next day: ' + str(date_to_check_again))
date_underscore_again = str(date_to_check_again).replace('-', '_')
if vmid_status[int(vmid)] != 'ok':
code_from_last_day = vmid_status[int(vmid)]
vmid_status[int(vmid)], found = readlogfile(path, vmid, date_underscore_again)
# Didnt find a working backup on the next day, so keep the old status
if vmid_status[int(vmid)] != 'ok':
vmid_status[int(vmid)] = code_from_last_day
date_to_check_again = date_to_check_again + timedelta(days=1)
# I tried my best, but no logfile here :(
if not found:
if vmid_status[int(vmid)] != 'ok' and vmid_status[int(vmid)] not in errorcodes:
vmid_status[int(vmid)] = 'nolog'
printdebug("Error - no log file found: " + str(vmid))
printdebug("Storage-Path: " + path)
printdebug("------------")
# print " "
# print vmid_status
OK_STATUS = True
UNKNOWN_STATUS = False
WARNING_STATUS = False
CRITICAL_STATUS = False
nagios_response = {'ok': '', 'failed': '', 'nobak': '', 'nolog': '', 'running': '', 'nochk': '', '2old': ''}
for vmid, status in vmid_status.items():
printdebug(str(vmid) + status)
vmid = str(vmid)
if status == 'ok':
nagios_response['ok'] += vmid + ','
elif status == 'failed':
OK_STATUS = False
CRITICAL_STATUS = True
nagios_response['failed'] += vmid + ','
elif status == 'nobak':
OK_STATUS = False
CRITICAL_STATUS = True
nagios_response['nobak'] += vmid + ','
elif status == 'nolog':
OK_STATUS = False
CRITICAL_STATUS = True
nagios_response['nolog'] += vmid + ','
elif status == 'running':
OK_STATUS = False
WARNING_STATUS = True
nagios_response['running'] += vmid + ','
elif status == '2old':
OK_STATUS = False
WARNING_STATUS = True
nagios_response['2old'] += vmid + ','
elif status == 'nochk':
OK_STATUS = False
CRITICAL_STATUS = True
nagios_response['nochk'] += vmid + ','
else:
OK_STATUS = False
UNKNOWN_STATUS = True
# clean up unused key-value-pairs
new_nagios_response = {}
for key, value in nagios_response.items():
if value != '':
new_nagios_response[key] = value
if UNKNOWN_STATUS:
message = 'Cannot read backup status - %s' % (new_nagios_response)
nagiosExit(nagios.unknown, str(message))
elif CRITICAL_STATUS:
message = 'At least one backup did not work - %s' % (new_nagios_response)
nagiosExit(nagios.critical, str(message))
elif WARNING_STATUS:
message = 'At least one backup is not finished yet or older than expected - %s' % (new_nagios_response)
nagiosExit(nagios.warning, str(message))
else:
message = '%s' % (new_nagios_response)
nagiosExit(nagios.ok, str(message))