#!/usr/bin/env python3 from datetime import datetime, timedelta from re import match from subprocess import check_output from sys import exit output = check_output(['zfs', 'get', 'creation', '-Hpr', '-t', 'snapshot']) now = int(datetime.now().timestamp()) warn_age = now - (60 * 60 * 24 * 60) crit_age = now - (60 * 60 * 24 * 90) warn_snapshots = set() crit_snapshots = set() return_code = 0 for line in output.decode('utf-8').split("\n"): if line.strip() == '': continue items = line.split("\t") # If the snapshot name contains 'zfs-auto-snap', it's probably # really an automated snapshot and will be cleaned up eventually. # This check only cares about manually created snapshots, though. if 'zfs-auto-snap' in items[0]: continue # These are docker-internal snapshots and should not be touched by # us. if match(r'^tank/docker/[a-z0-9]+(-init)?@[0-9]+', items[0]): continue # line should be ' creation -', separated by # tabstops. if len(items) < 3: print('UNKNOWN - error while parsing ' + line) exit(3) creation_date = int(items[2]) if creation_date < crit_age: crit_snapshots.add(items[0]) elif creation_date < warn_age: warn_snapshots.add(items[0]) # We have to do additional loops in here to have CRITICAL items on top. for snap in sorted(crit_snapshots): print('CRITICAL - {} is older than 90 days'.format(snap)) for snap in sorted(warn_snapshots): print('WARN - {} is older than 60 days'.format(snap)) if len(crit_snapshots) > 0: return_code = 2 elif len(warn_snapshots) > 0: return_code = 1 else: print('OK - no snapshots are older than 60 days') exit(return_code)