We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
UnboudLocalError: local variable 'f' referenced before assignment
Version: 1.9 but also devel as the file handling code does not changed.
Server/Client OS: Ubuntu

This is not a duplicate of #2618. When defining a caching path for the jsonfile caching plugin that is not writable by Ansible. Ansible fails with the following message:

```
fatal: [my-host] => Traceback (most recent call last):
  File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 586, in _executor
    exec_rc = self._executor_internal(host, new_stdin)
  File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 668, in _executor_internal
    inject = self.get_inject_vars(host)
  File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 611, in get_inject_vars
    combined_cache = self.get_combined_cache()
  File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 606, in get_combined_cache
    combined_cache = self.setup_cache.copy()
  File "/home/david/.pip/ansible/lib/ansible/cache/__init__.py", line 54, in copy
    return dict([(k, v) for (k, v) in self.iteritems()])
  File "/usr/lib/python2.7/_abcoll.py", line 406, in iteritems
    yield (key, self[key])
  File "/home/david/.pip/ansible/lib/ansible/cache/__init__.py", line 35, in __getitem__
    return self._plugin.get(key)
  File "/home/david/.pip/ansible/lib/ansible/cache/jsonfile.py", line 69, in get
    f.close()
UnboundLocalError: local variable 'f' referenced before assignment
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `lib/ansible/plugins/cache/base.py`
Content:
```
1 # (c) 2014, Brian Coca, Josh Drake, et al
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
17 
18 from __future__ import (absolute_import, division, print_function)
19 __metaclass__ = type
20 
21 import os
22 import time
23 import errno
24 from abc import ABCMeta, abstractmethod
25 
26 from ansible import constants as C
27 from ansible.compat.six import with_metaclass
28 from ansible.errors import AnsibleError
29 from ansible.module_utils._text import to_bytes
30 
31 try:
32     from __main__ import display
33 except ImportError:
34     from ansible.utils.display import Display
35     display = Display()
36 
37 class BaseCacheModule(with_metaclass(ABCMeta, object)):
38 
39     # Backwards compat only.  Just import the global display instead
40     _display = display
41 
42     @abstractmethod
43     def get(self, key):
44         pass
45 
46     @abstractmethod
47     def set(self, key, value):
48         pass
49 
50     @abstractmethod
51     def keys(self):
52         pass
53 
54     @abstractmethod
55     def contains(self, key):
56         pass
57 
58     @abstractmethod
59     def delete(self, key):
60         pass
61 
62     @abstractmethod
63     def flush(self):
64         pass
65 
66     @abstractmethod
67     def copy(self):
68         pass
69 
70 
71 class BaseFileCacheModule(BaseCacheModule):
72     """
73     A caching module backed by file based storage.
74     """
75     def __init__(self, *args, **kwargs):
76 
77         self.plugin_name = self.__module__.split('.')[-1]
78         self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)
79         self._cache = {}
80         self._cache_dir = None
81 
82         if C.CACHE_PLUGIN_CONNECTION:
83             # expects a dir path
84             self._cache_dir = os.path.expanduser(os.path.expandvars(C.CACHE_PLUGIN_CONNECTION))
85 
86         if not self._cache_dir:
87             raise AnsibleError("error, '%s' cache plugin requires the 'fact_caching_connection' config option"
88                     " to be set (to a writeable directory path)" % self.plugin_name)
89 
90         if not os.path.exists(self._cache_dir):
91             try:
92                 os.makedirs(self._cache_dir)
93             except (OSError,IOError) as e:
94                 display.warning("error in '%s' cache plugin while trying to create cache dir %s : %s" % (self.plugin_name, self._cache_dir, to_bytes(e)))
95                 return None
96 
97     def get(self, key):
98         """ This checks the in memory cache first as the fact was not expired at 'gather time'
99         and it would be problematic if the key did expire after some long running tasks and
100         user gets 'undefined' error in the same play """
101 
102         if key in self._cache:
103             return self._cache.get(key)
104 
105         if self.has_expired(key) or key == "":
106             raise KeyError
107 
108         cachefile = "%s/%s" % (self._cache_dir, key)
109         try:
110             try:
111                 value = self._load(cachefile)
112                 self._cache[key] = value
113                 return value
114             except ValueError as e:
115                 display.warning("error in '%s' cache plugin while trying to read %s : %s."
116                         " Most likely a corrupt file, so erasing and failing." % (self.plugin_name, cachefile, to_bytes(e)))
117                 self.delete(key)
118                 raise AnsibleError("The cache file %s was corrupt, or did not otherwise contain valid data."
119                         " It has been removed, so you can re-run your command now." % cachefile)
120         except (OSError,IOError) as e:
121             display.warning("error in '%s' cache plugin while trying to read %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
122             raise KeyError
123         except Exception as e:
124             raise AnsibleError("Error while decoding the cache file %s: %s" % (cachefile, to_bytes(e)))
125 
126     def set(self, key, value):
127 
128         self._cache[key] = value
129 
130         cachefile = "%s/%s" % (self._cache_dir, key)
131         try:
132             self._dump(value, cachefile)
133         except (OSError,IOError) as e:
134             display.warning("error in '%s' cache plugin while trying to write to %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
135 
136     def has_expired(self, key):
137 
138         if self._timeout == 0:
139             return False
140 
141         cachefile = "%s/%s" % (self._cache_dir, key)
142         try:
143             st = os.stat(cachefile)
144         except (OSError,IOError) as e:
145             if e.errno == errno.ENOENT:
146                 return False
147             else:
148                 display.warning("error in '%s' cache plugin while trying to stat %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
149                 pass
150 
151         if time.time() - st.st_mtime <= self._timeout:
152             return False
153 
154         if key in self._cache:
155             del self._cache[key]
156         return True
157 
158     def keys(self):
159         keys = []
160         for k in os.listdir(self._cache_dir):
161             if not (k.startswith('.') or self.has_expired(k)):
162                 keys.append(k)
163         return keys
164 
165     def contains(self, key):
166         cachefile = "%s/%s" % (self._cache_dir, key)
167 
168         if key in self._cache:
169             return True
170 
171         if self.has_expired(key):
172             return False
173         try:
174             os.stat(cachefile)
175             return True
176         except (OSError,IOError) as e:
177             if e.errno == errno.ENOENT:
178                 return False
179             else:
180                 display.warning("error in '%s' cache plugin while trying to stat %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
181                 pass
182 
183     def delete(self, key):
184         try:
185             del self._cache[key]
186         except KeyError:
187             pass
188         try:
189             os.remove("%s/%s" % (self._cache_dir, key))
190         except (OSError, IOError):
191             pass #TODO: only pass on non existing?
192 
193     def flush(self):
194         self._cache = {}
195         for key in self.keys():
196             self.delete(key)
197 
198     def copy(self):
199         ret = dict()
200         for key in self.keys():
201             ret[key] = self.get(key)
202         return ret
203 
204     @abstractmethod
205     def _load(self, filepath):
206         """
207         Read data from a filepath and return it as a value
208 
209         :arg filepath: The filepath to read from.
210         :returns: The value stored in the filepath
211 
212         This method reads from the file on disk and takes care of any parsing
213         and transformation of the data before returning it.  The value
214         returned should be what Ansible would expect if it were uncached data.
215 
216         .. note:: Filehandles have advantages but calling code doesn't know
217             whether this file is text or binary, should be decoded, or accessed via
218             a library function.  Therefore the API uses a filepath and opens
219             the file inside of the method.
220         """
221         pass
222 
223     @abstractmethod
224     def _dump(self, value, filepath):
225         """
226         Write data to a filepath
227 
228         :arg value: The value to store
229         :arg filepath: The filepath to store it at
230         """
231         pass
232
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/lib/ansible/plugins/cache/base.py b/lib/ansible/plugins/cache/base.py
--- a/lib/ansible/plugins/cache/base.py
+++ b/lib/ansible/plugins/cache/base.py
@@ -91,8 +91,11 @@
             try:
                 os.makedirs(self._cache_dir)
             except (OSError,IOError) as e:
-                display.warning("error in '%s' cache plugin while trying to create cache dir %s : %s" % (self.plugin_name, self._cache_dir, to_bytes(e)))
-                return None
+                raise AnsibleError("error in '%s' cache plugin while trying to create cache dir %s : %s" % (self.plugin_name, self._cache_dir, to_bytes(e)))
+        else:
+            for x in (os.R_OK, os.W_OK, os.X_OK):
+                if not os.access(self._cache_dir, x):
+                    raise AnsibleError("error in '%s' cache, configured path (%s) does not have necessary permissions (rwx), disabling plugin" % (self.plugin_name, self._cache_dir))
 
     def get(self, key):
         """ This checks the in memory cache first as the fact was not expired at 'gather time'
@@ -146,7 +149,7 @@
                 return False
             else:
                 display.warning("error in '%s' cache plugin while trying to stat %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
-                pass
+                return False
 
         if time.time() - st.st_mtime <= self._timeout:
             return False

{"golden_diff": "diff --git a/lib/ansible/plugins/cache/base.py b/lib/ansible/plugins/cache/base.py\n--- a/lib/ansible/plugins/cache/base.py\n+++ b/lib/ansible/plugins/cache/base.py\n@@ -91,8 +91,11 @@\n             try:\n                 os.makedirs(self._cache_dir)\n             except (OSError,IOError) as e:\n-                display.warning(\"error in '%s' cache plugin while trying to create cache dir %s : %s\" % (self.plugin_name, self._cache_dir, to_bytes(e)))\n-                return None\n+                raise AnsibleError(\"error in '%s' cache plugin while trying to create cache dir %s : %s\" % (self.plugin_name, self._cache_dir, to_bytes(e)))\n+        else:\n+            for x in (os.R_OK, os.W_OK, os.X_OK):\n+                if not os.access(self._cache_dir, x):\n+                    raise AnsibleError(\"error in '%s' cache, configured path (%s) does not have necessary permissions (rwx), disabling plugin\" % (self.plugin_name, self._cache_dir))\n \n     def get(self, key):\n         \"\"\" This checks the in memory cache first as the fact was not expired at 'gather time'\n@@ -146,7 +149,7 @@\n                 return False\n             else:\n                 display.warning(\"error in '%s' cache plugin while trying to stat %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n-                pass\n+                return False\n \n         if time.time() - st.st_mtime <= self._timeout:\n             return False\n", "issue": "UnboudLocalError: local variable 'f' referenced before assignment\nVersion: 1.9 but also devel as the file handling code does not changed.\nServer/Client OS: Ubuntu\n\nThis is not a duplicate of #2618. When defining a caching path for the jsonfile caching plugin that is not writable by Ansible. Ansible fails with the following message:\n\n```\nfatal: [my-host] => Traceback (most recent call last):\n  File \"/home/david/.pip/ansible/lib/ansible/runner/__init__.py\", line 586, in _executor\n    exec_rc = self._executor_internal(host, new_stdin)\n  File \"/home/david/.pip/ansible/lib/ansible/runner/__init__.py\", line 668, in _executor_internal\n    inject = self.get_inject_vars(host)\n  File \"/home/david/.pip/ansible/lib/ansible/runner/__init__.py\", line 611, in get_inject_vars\n    combined_cache = self.get_combined_cache()\n  File \"/home/david/.pip/ansible/lib/ansible/runner/__init__.py\", line 606, in get_combined_cache\n    combined_cache = self.setup_cache.copy()\n  File \"/home/david/.pip/ansible/lib/ansible/cache/__init__.py\", line 54, in copy\n    return dict([(k, v) for (k, v) in self.iteritems()])\n  File \"/usr/lib/python2.7/_abcoll.py\", line 406, in iteritems\n    yield (key, self[key])\n  File \"/home/david/.pip/ansible/lib/ansible/cache/__init__.py\", line 35, in __getitem__\n    return self._plugin.get(key)\n  File \"/home/david/.pip/ansible/lib/ansible/cache/jsonfile.py\", line 69, in get\n    f.close()\nUnboundLocalError: local variable 'f' referenced before assignment\n```\n\n", "before_files": [{"content": "# (c) 2014, Brian Coca, Josh Drake, et al\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport os\nimport time\nimport errno\nfrom abc import ABCMeta, abstractmethod\n\nfrom ansible import constants as C\nfrom ansible.compat.six import with_metaclass\nfrom ansible.errors import AnsibleError\nfrom ansible.module_utils._text import to_bytes\n\ntry:\n    from __main__ import display\nexcept ImportError:\n    from ansible.utils.display import Display\n    display = Display()\n\nclass BaseCacheModule(with_metaclass(ABCMeta, object)):\n\n    # Backwards compat only.  Just import the global display instead\n    _display = display\n\n    @abstractmethod\n    def get(self, key):\n        pass\n\n    @abstractmethod\n    def set(self, key, value):\n        pass\n\n    @abstractmethod\n    def keys(self):\n        pass\n\n    @abstractmethod\n    def contains(self, key):\n        pass\n\n    @abstractmethod\n    def delete(self, key):\n        pass\n\n    @abstractmethod\n    def flush(self):\n        pass\n\n    @abstractmethod\n    def copy(self):\n        pass\n\n\nclass BaseFileCacheModule(BaseCacheModule):\n    \"\"\"\n    A caching module backed by file based storage.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n\n        self.plugin_name = self.__module__.split('.')[-1]\n        self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)\n        self._cache = {}\n        self._cache_dir = None\n\n        if C.CACHE_PLUGIN_CONNECTION:\n            # expects a dir path\n            self._cache_dir = os.path.expanduser(os.path.expandvars(C.CACHE_PLUGIN_CONNECTION))\n\n        if not self._cache_dir:\n            raise AnsibleError(\"error, '%s' cache plugin requires the 'fact_caching_connection' config option\"\n                    \" to be set (to a writeable directory path)\" % self.plugin_name)\n\n        if not os.path.exists(self._cache_dir):\n            try:\n                os.makedirs(self._cache_dir)\n            except (OSError,IOError) as e:\n                display.warning(\"error in '%s' cache plugin while trying to create cache dir %s : %s\" % (self.plugin_name, self._cache_dir, to_bytes(e)))\n                return None\n\n    def get(self, key):\n        \"\"\" This checks the in memory cache first as the fact was not expired at 'gather time'\n        and it would be problematic if the key did expire after some long running tasks and\n        user gets 'undefined' error in the same play \"\"\"\n\n        if key in self._cache:\n            return self._cache.get(key)\n\n        if self.has_expired(key) or key == \"\":\n            raise KeyError\n\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n        try:\n            try:\n                value = self._load(cachefile)\n                self._cache[key] = value\n                return value\n            except ValueError as e:\n                display.warning(\"error in '%s' cache plugin while trying to read %s : %s.\"\n                        \" Most likely a corrupt file, so erasing and failing.\" % (self.plugin_name, cachefile, to_bytes(e)))\n                self.delete(key)\n                raise AnsibleError(\"The cache file %s was corrupt, or did not otherwise contain valid data.\"\n                        \" It has been removed, so you can re-run your command now.\" % cachefile)\n        except (OSError,IOError) as e:\n            display.warning(\"error in '%s' cache plugin while trying to read %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n            raise KeyError\n        except Exception as e:\n            raise AnsibleError(\"Error while decoding the cache file %s: %s\" % (cachefile, to_bytes(e)))\n\n    def set(self, key, value):\n\n        self._cache[key] = value\n\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n        try:\n            self._dump(value, cachefile)\n        except (OSError,IOError) as e:\n            display.warning(\"error in '%s' cache plugin while trying to write to %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n\n    def has_expired(self, key):\n\n        if self._timeout == 0:\n            return False\n\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n        try:\n            st = os.stat(cachefile)\n        except (OSError,IOError) as e:\n            if e.errno == errno.ENOENT:\n                return False\n            else:\n                display.warning(\"error in '%s' cache plugin while trying to stat %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n                pass\n\n        if time.time() - st.st_mtime <= self._timeout:\n            return False\n\n        if key in self._cache:\n            del self._cache[key]\n        return True\n\n    def keys(self):\n        keys = []\n        for k in os.listdir(self._cache_dir):\n            if not (k.startswith('.') or self.has_expired(k)):\n                keys.append(k)\n        return keys\n\n    def contains(self, key):\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n\n        if key in self._cache:\n            return True\n\n        if self.has_expired(key):\n            return False\n        try:\n            os.stat(cachefile)\n            return True\n        except (OSError,IOError) as e:\n            if e.errno == errno.ENOENT:\n                return False\n            else:\n                display.warning(\"error in '%s' cache plugin while trying to stat %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n                pass\n\n    def delete(self, key):\n        try:\n            del self._cache[key]\n        except KeyError:\n            pass\n        try:\n            os.remove(\"%s/%s\" % (self._cache_dir, key))\n        except (OSError, IOError):\n            pass #TODO: only pass on non existing?\n\n    def flush(self):\n        self._cache = {}\n        for key in self.keys():\n            self.delete(key)\n\n    def copy(self):\n        ret = dict()\n        for key in self.keys():\n            ret[key] = self.get(key)\n        return ret\n\n    @abstractmethod\n    def _load(self, filepath):\n        \"\"\"\n        Read data from a filepath and return it as a value\n\n        :arg filepath: The filepath to read from.\n        :returns: The value stored in the filepath\n\n        This method reads from the file on disk and takes care of any parsing\n        and transformation of the data before returning it.  The value\n        returned should be what Ansible would expect if it were uncached data.\n\n        .. note:: Filehandles have advantages but calling code doesn't know\n            whether this file is text or binary, should be decoded, or accessed via\n            a library function.  Therefore the API uses a filepath and opens\n            the file inside of the method.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def _dump(self, value, filepath):\n        \"\"\"\n        Write data to a filepath\n\n        :arg value: The value to store\n        :arg filepath: The filepath to store it at\n        \"\"\"\n        pass\n", "path": "lib/ansible/plugins/cache/base.py"}], "after_files": [{"content": "# (c) 2014, Brian Coca, Josh Drake, et al\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport os\nimport time\nimport errno\nfrom abc import ABCMeta, abstractmethod\n\nfrom ansible import constants as C\nfrom ansible.compat.six import with_metaclass\nfrom ansible.errors import AnsibleError\nfrom ansible.module_utils._text import to_bytes\n\ntry:\n    from __main__ import display\nexcept ImportError:\n    from ansible.utils.display import Display\n    display = Display()\n\nclass BaseCacheModule(with_metaclass(ABCMeta, object)):\n\n    # Backwards compat only.  Just import the global display instead\n    _display = display\n\n    @abstractmethod\n    def get(self, key):\n        pass\n\n    @abstractmethod\n    def set(self, key, value):\n        pass\n\n    @abstractmethod\n    def keys(self):\n        pass\n\n    @abstractmethod\n    def contains(self, key):\n        pass\n\n    @abstractmethod\n    def delete(self, key):\n        pass\n\n    @abstractmethod\n    def flush(self):\n        pass\n\n    @abstractmethod\n    def copy(self):\n        pass\n\n\nclass BaseFileCacheModule(BaseCacheModule):\n    \"\"\"\n    A caching module backed by file based storage.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n\n        self.plugin_name = self.__module__.split('.')[-1]\n        self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)\n        self._cache = {}\n        self._cache_dir = None\n\n        if C.CACHE_PLUGIN_CONNECTION:\n            # expects a dir path\n            self._cache_dir = os.path.expanduser(os.path.expandvars(C.CACHE_PLUGIN_CONNECTION))\n\n        if not self._cache_dir:\n            raise AnsibleError(\"error, '%s' cache plugin requires the 'fact_caching_connection' config option\"\n                    \" to be set (to a writeable directory path)\" % self.plugin_name)\n\n        if not os.path.exists(self._cache_dir):\n            try:\n                os.makedirs(self._cache_dir)\n            except (OSError,IOError) as e:\n                raise AnsibleError(\"error in '%s' cache plugin while trying to create cache dir %s : %s\" % (self.plugin_name, self._cache_dir, to_bytes(e)))\n        else:\n            for x in (os.R_OK, os.W_OK, os.X_OK):\n                if not os.access(self._cache_dir, x):\n                    raise AnsibleError(\"error in '%s' cache, configured path (%s) does not have necessary permissions (rwx), disabling plugin\" % (self.plugin_name, self._cache_dir))\n\n    def get(self, key):\n        \"\"\" This checks the in memory cache first as the fact was not expired at 'gather time'\n        and it would be problematic if the key did expire after some long running tasks and\n        user gets 'undefined' error in the same play \"\"\"\n\n        if key in self._cache:\n            return self._cache.get(key)\n\n        if self.has_expired(key) or key == \"\":\n            raise KeyError\n\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n        try:\n            try:\n                value = self._load(cachefile)\n                self._cache[key] = value\n                return value\n            except ValueError as e:\n                display.warning(\"error in '%s' cache plugin while trying to read %s : %s.\"\n                        \" Most likely a corrupt file, so erasing and failing.\" % (self.plugin_name, cachefile, to_bytes(e)))\n                self.delete(key)\n                raise AnsibleError(\"The cache file %s was corrupt, or did not otherwise contain valid data.\"\n                        \" It has been removed, so you can re-run your command now.\" % cachefile)\n        except (OSError,IOError) as e:\n            display.warning(\"error in '%s' cache plugin while trying to read %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n            raise KeyError\n        except Exception as e:\n            raise AnsibleError(\"Error while decoding the cache file %s: %s\" % (cachefile, to_bytes(e)))\n\n    def set(self, key, value):\n\n        self._cache[key] = value\n\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n        try:\n            self._dump(value, cachefile)\n        except (OSError,IOError) as e:\n            display.warning(\"error in '%s' cache plugin while trying to write to %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n\n    def has_expired(self, key):\n\n        if self._timeout == 0:\n            return False\n\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n        try:\n            st = os.stat(cachefile)\n        except (OSError,IOError) as e:\n            if e.errno == errno.ENOENT:\n                return False\n            else:\n                display.warning(\"error in '%s' cache plugin while trying to stat %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n                return False\n\n        if time.time() - st.st_mtime <= self._timeout:\n            return False\n\n        if key in self._cache:\n            del self._cache[key]\n        return True\n\n    def keys(self):\n        keys = []\n        for k in os.listdir(self._cache_dir):\n            if not (k.startswith('.') or self.has_expired(k)):\n                keys.append(k)\n        return keys\n\n    def contains(self, key):\n        cachefile = \"%s/%s\" % (self._cache_dir, key)\n\n        if key in self._cache:\n            return True\n\n        if self.has_expired(key):\n            return False\n        try:\n            os.stat(cachefile)\n            return True\n        except (OSError,IOError) as e:\n            if e.errno == errno.ENOENT:\n                return False\n            else:\n                display.warning(\"error in '%s' cache plugin while trying to stat %s : %s\" % (self.plugin_name, cachefile, to_bytes(e)))\n                pass\n\n    def delete(self, key):\n        try:\n            del self._cache[key]\n        except KeyError:\n            pass\n        try:\n            os.remove(\"%s/%s\" % (self._cache_dir, key))\n        except (OSError, IOError):\n            pass #TODO: only pass on non existing?\n\n    def flush(self):\n        self._cache = {}\n        for key in self.keys():\n            self.delete(key)\n\n    def copy(self):\n        ret = dict()\n        for key in self.keys():\n            ret[key] = self.get(key)\n        return ret\n\n    @abstractmethod\n    def _load(self, filepath):\n        \"\"\"\n        Read data from a filepath and return it as a value\n\n        :arg filepath: The filepath to read from.\n        :returns: The value stored in the filepath\n\n        This method reads from the file on disk and takes care of any parsing\n        and transformation of the data before returning it.  The value\n        returned should be what Ansible would expect if it were uncached data.\n\n        .. note:: Filehandles have advantages but calling code doesn't know\n            whether this file is text or binary, should be decoded, or accessed via\n            a library function.  Therefore the API uses a filepath and opens\n            the file inside of the method.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def _dump(self, value, filepath):\n        \"\"\"\n        Write data to a filepath\n\n        :arg value: The value to store\n        :arg filepath: The filepath to store it at\n        \"\"\"\n        pass\n", "path": "lib/ansible/plugins/cache/base.py"}]}