Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 import logging | |
| 6 import os | |
| 7 import pickle | |
| 8 import threading | |
| 9 import zlib | |
| 10 | |
| 11 from lib.cache_decorator import Cacher | |
| 12 | |
| 13 | |
| 14 class LocalCacher(Cacher): | |
| 15 """Cacher that uses local files to cache data.""" | |
| 16 lock = threading.Lock() | |
| 17 | |
| 18 def __init__(self, cache_dir): | |
| 19 self.cache_dir = cache_dir | |
| 20 if not os.path.exists(cache_dir): # pragma: no cover. | |
|
wrengr
2016/11/11 18:26:26
Again, this sort of code has an inherent race cond
Sharu Jiang
2016/11/12 01:01:50
How about using locks? Or there would be a lot exc
wrengr
2016/11/14 21:48:45
The problem is in (the interaction with) the files
| |
| 21 os.makedirs(cache_dir) | |
| 22 | |
| 23 def Get(self, key): | |
| 24 with LocalCacher.lock: | |
| 25 path = os.path.join(self.cache_dir, key) | |
| 26 if not os.path.exists(path): | |
| 27 return None | |
|
wrengr
2016/11/11 18:26:26
You probably want this case to also do the logging
Sharu Jiang
2016/11/12 01:01:50
Done.
Sharu Jiang
2016/11/12 02:00:48
I added back this, for local cacher won't cache fo
| |
| 28 | |
| 29 try: | |
| 30 with open(path) as f: | |
| 31 return pickle.loads(zlib.decompress(f.read())) | |
| 32 except Exception as e: # pragma: no cover. | |
| 33 logging.exception('Failed loading cache: %s', e) | |
| 34 return None | |
| 35 | |
| 36 def Set(self, key, data, expire_time=0): # pylint: disable=W | |
| 37 with LocalCacher.lock: | |
| 38 try: | |
| 39 with open(os.path.join(self.cache_dir, key), 'wb') as f: | |
| 40 f.write(zlib.compress(pickle.dumps(data))) | |
| 41 except Exception as e: # pragma: no cover. | |
| 42 logging.exception('Failed setting cache for key %s: %s', key, e) | |
| OLD | NEW |