diff options
Diffstat (limited to 'nova/utils.py')
-rw-r--r-- | nova/utils.py | 26 |
1 files changed, 16 insertions, 10 deletions
diff --git a/nova/utils.py b/nova/utils.py index 991e68b3b..f34db4aba 100644 --- a/nova/utils.py +++ b/nova/utils.py @@ -1176,18 +1176,24 @@ def sanitize_hostname(hostname): return hostname -def read_cached_file(filename, cache_info): - """Return the contents of a file. If the file hasn't changed since the - last invocation, a cached version will be returned. +def read_cached_file(filename, cache_info, reload_func=None): + """Read from a file if it has been modified. + + :param cache_info: dictionary to hold opaque cache. + :param reload_func: optional function to be called with data when + file is reloaded due to a modification. + + :returns: data from file + """ mtime = os.path.getmtime(filename) - if cache_info and mtime == cache_info.get('mtime', None): - return cache_info['data'] - - data = open(filename).read() - cache_info['data'] = data - cache_info['mtime'] = mtime - return data + if not cache_info or mtime != cache_info.get('mtime'): + with open(filename) as fap: + cache_info['data'] = fap.read() + cache_info['mtime'] = mtime + if reload_func: + reload_func(cache_info['data']) + return cache_info['data'] @contextlib.contextmanager |