2
# Copyright (C) 2005, 2006, 2007, 2012 James Troup <james.troup@canonical.com>
11
################################################################################
13
class CriticalError(Exception):
14
"""This indicates a critical error."""
18
class WarnError(Exception):
19
"""This indicates a warning condition."""
23
class UnknownError(Exception):
24
"""This indicates a unknown error was encountered."""
28
def try_check(function, *args, **kwargs):
29
"""Perform a check with error/warn/unknown handling."""
31
function(*args, **kwargs)
32
except UnknownError, msg:
35
except CriticalError, msg:
38
except WarnError, msg:
42
print "%s raised unknown exception '%s'" % (function, sys.exc_info()[0])
44
traceback.print_exc(file=sys.stdout)
49
################################################################################
51
def check_file_freshness(filename, newer_than=600):
52
"""Check a file exists, is readable and is newer than <n> seconds (where <n> defaults to 600)."""
53
# First check the file exists and is readable
54
if not os.path.exists(filename):
55
raise CriticalError("%s: does not exist." % (filename))
56
if os.access(filename, os.R_OK) == 0:
57
raise CriticalError("%s: is not readable." % (filename))
59
# Then ensure the file is up-to-date enough
60
mtime = os.stat(filename)[stat.ST_MTIME]
61
last_modified = time.time() - mtime
62
if last_modified > newer_than:
63
raise CriticalError("%s: was last modified on %s and is too old (> %s seconds)."
64
% (filename, time.ctime(mtime), newer_than))
66
raise CriticalError("%s: was last modified on %s which is in the future."
67
% (filename, time.ctime(mtime)))
69
################################################################################