Skip to content

Commit 74e3b38

Browse files
authored
Prevent cache errors from crashing the client (#317)
1 parent 5fe6132 commit 74e3b38

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

openshift/dynamic/client.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -101,14 +101,25 @@ class DynamicClient(object):
101101
def __init__(self, client, cache_file=None):
102102
self.client = client
103103
self.configuration = client.configuration
104-
default_cache_id = self.configuration.host
105-
if PY3:
106-
default_cache_id = default_cache_id.encode('utf-8')
107-
default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id).hexdigest())
104+
default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(self.__get_default_cache_id()).hexdigest())
105+
108106
self.__resources = ResourceContainer({}, client=self)
109107
self.__cache_file = cache_file or os.path.join(tempfile.gettempdir(), default_cachefile_name)
110108
self.__init_cache()
111109

110+
def __get_default_cache_id(self):
111+
user = ""
112+
for func in [os.getlogin, os.getuid]:
113+
try:
114+
user = str(func())
115+
except OSError:
116+
pass
117+
118+
cache_id = "{0}-{1}".format(self.client.configuration.host, user)
119+
if PY3:
120+
return cache_id.encode('utf-8')
121+
return cache_id
122+
112123
def __init_cache(self, refresh=False):
113124
if refresh or not os.path.exists(self.__cache_file):
114125
self.__cache = {'library_version': __version__}
@@ -129,8 +140,12 @@ def __init_cache(self, refresh=False):
129140
self.__write_cache()
130141

131142
def __write_cache(self):
132-
with open(self.__cache_file, 'w') as f:
133-
json.dump(self.__cache, f, cls=CacheEncoder)
143+
try:
144+
with open(self.__cache_file, 'w') as f:
145+
json.dump(self._cache, f, cls=CacheEncoder)
146+
except Exception:
147+
# Failing to write the cache shouldn't crash the library
148+
pass
134149

135150
def invalidate_cache(self):
136151
self.__init_cache(refresh=True)

0 commit comments

Comments
 (0)