From 1091b4f3bed9b0ad8c23e5db6d4a5cee15fc786c Mon Sep 17 00:00:00 2001 From: Flaper Fesp Date: Mon, 29 Apr 2013 16:58:23 +0200 Subject: Reduce duplicated code related to policies This patch adds some logic that is currently duplicated throughout Openstack. As part of this de-duplication, the patch also modifies current implementation. Major Changes: * check, set_rules, reset, init are now part of the Enforcer class * check was renamed into enforce * init was renamed into load_rules * It is now possible to load multiple files and have per instance rules instead of global rules. * There's a global instance of the Enforcer class that can be used as main enforcer. from openstack.common import policy ENFORCER = policy.ENFORCER ENFORCER.enforce(rule, target, creds) Minor Changes: * Added do_raise to the enforce method * Enforcer instance is now passed to the Check call. NOTE: If / once this patch gets in, I'll update other projects and port them to the latest version. Change-Id: Ife909bdf3277ef33c2fb1eae16ae261fa6374c63 --- openstack/common/fileutils.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'openstack/common/fileutils.py') diff --git a/openstack/common/fileutils.py b/openstack/common/fileutils.py index b988ad0..bb2ef61 100644 --- a/openstack/common/fileutils.py +++ b/openstack/common/fileutils.py @@ -19,6 +19,13 @@ import errno import os +from openstack.common.gettextutils import _ +from openstack.common import log as logging + +LOG = logging.getLogger(__name__) + +_FILE_CACHE = {} + def ensure_tree(path): """Create a directory (and any ancestor directories required) @@ -33,3 +40,28 @@ def ensure_tree(path): raise else: raise + + +def read_cached_file(filename, force_reload=False): + """Read from a file if it has been modified. + + :param force_reload: Whether to reload the file. + :returns: A tuple with a boolean specifying if the data is fresh + or not. + """ + global _FILE_CACHE + + if force_reload and filename in _FILE_CACHE: + del _FILE_CACHE[filename] + + reloaded = False + mtime = os.path.getmtime(filename) + cache_info = _FILE_CACHE.setdefault(filename, {}) + + if not cache_info or mtime > cache_info.get('mtime', 0): + LOG.debug(_("Reloading cached file %s") % filename) + with open(filename) as fap: + cache_info['data'] = fap.read() + cache_info['mtime'] = mtime + reloaded = True + return (reloaded, cache_info['data']) -- cgit