1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
17 _logger = logging.getLogger('arvados.keep')
19 cacheblock_suffix = ".keepcacheblock"
21 class DiskCacheSlot(object):
22 __slots__ = ("locator", "ready", "content", "cachedir", "filehandle", "linger")
24 def __init__(self, locator, cachedir):
25 self.locator = locator
26 self.ready = threading.Event()
28 self.cachedir = cachedir
29 self.filehandle = None
45 # Can't mmap a 0 length file
50 if self.content is not None:
51 # Has been set already
55 blockdir = os.path.join(self.cachedir, self.locator[0:3])
56 os.makedirs(blockdir, mode=0o700, exist_ok=True)
58 final = os.path.join(blockdir, self.locator) + cacheblock_suffix
60 self.filehandle = tempfile.NamedTemporaryFile(dir=blockdir, delete=False, prefix="tmp", suffix=cacheblock_suffix)
61 tmpfile = self.filehandle.name
62 os.chmod(tmpfile, stat.S_IRUSR | stat.S_IWUSR)
64 # aquire a shared lock, this tells other processes that
65 # we're using this block and to please not delete it.
66 fcntl.flock(self.filehandle, fcntl.LOCK_SH)
68 self.filehandle.write(value)
69 self.filehandle.flush()
70 os.rename(tmpfile, final)
73 self.content = mmap.mmap(self.filehandle.fileno(), 0, access=mmap.ACCESS_READ)
74 # only set the event when mmap is successful
77 if tmpfile is not None:
78 # If the tempfile hasn't been renamed on disk yet, try to delete it.
85 if self.content is None:
86 if self.linger is not None:
87 # If it is still lingering (object is still accessible
88 # through the weak reference) it is still taking up
90 content = self.linger()
91 if content is not None:
95 return len(self.content)
98 if self.content is not None and len(self.content) > 0:
99 # The mmap region might be in use when we decided to evict
100 # it. This can happen if the cache is too small.
102 # If we call close() now, it'll throw an error if
103 # something tries to access it.
105 # However, we don't need to explicitly call mmap.close()
107 # I confirmed in mmapmodule.c that that both close
108 # and deallocate do the same thing:
110 # a) close the file descriptor
111 # b) unmap the memory range
113 # So we can forget it in the cache and delete the file on
114 # disk, and it will tear it down after any other
115 # lingering Python references to the mapped memory are
118 blockdir = os.path.join(self.cachedir, self.locator[0:3])
119 final = os.path.join(blockdir, self.locator) + cacheblock_suffix
121 fcntl.flock(self.filehandle, fcntl.LOCK_UN)
123 # try to get an exclusive lock, this ensures other
124 # processes are not using the block. It is
125 # nonblocking and will throw an exception if we
126 # can't get it, which is fine because that means
127 # we just won't try to delete it.
129 # I should note here, the file locking is not
130 # strictly necessary, we could just remove it and
131 # the kernel would ensure that the underlying
132 # inode remains available as long as other
133 # processes still have the file open. However, if
134 # you have multiple processes sharing the cache
135 # and deleting each other's files, you'll end up
136 # with a bunch of ghost files that don't show up
137 # in the file system but are still taking up
138 # space, which isn't particularly user friendly.
139 # The locking strategy ensures that cache blocks
140 # in use remain visible.
142 fcntl.flock(self.filehandle, fcntl.LOCK_EX | fcntl.LOCK_NB)
149 self.filehandle = None
150 self.linger = weakref.ref(self.content)
155 # Test if an evicted object is lingering
156 return self.content is None and (self.linger is None or self.linger() is None)
159 def get_from_disk(locator, cachedir):
160 blockdir = os.path.join(cachedir, locator[0:3])
161 final = os.path.join(blockdir, locator) + cacheblock_suffix
164 filehandle = open(final, "rb")
166 # aquire a shared lock, this tells other processes that
167 # we're using this block and to please not delete it.
168 fcntl.flock(filehandle, fcntl.LOCK_SH)
170 content = mmap.mmap(filehandle.fileno(), 0, access=mmap.ACCESS_READ)
171 dc = DiskCacheSlot(locator, cachedir)
172 dc.filehandle = filehandle
176 except FileNotFoundError:
178 except Exception as e:
179 traceback.print_exc()
184 def cache_usage(cachedir):
186 for root, dirs, files in os.walk(cachedir):
188 if not name.endswith(cacheblock_suffix):
191 blockpath = os.path.join(root, name)
192 res = os.stat(blockpath)
198 def init_cache(cachedir, maxslots):
200 # First check the disk cache works at all by creating a 1 byte cache entry
202 checkexists = DiskCacheSlot.get_from_disk('0cc175b9c0f1b6a831c399e269772661', cachedir)
203 ds = DiskCacheSlot('0cc175b9c0f1b6a831c399e269772661', cachedir)
205 if checkexists is None:
206 # Don't keep the test entry around unless it existed beforehand.
209 # map in all the files in the cache directory, up to max slots.
210 # after max slots, try to delete the excess blocks.
212 # this gives the calling process ownership of all the blocks
215 for root, dirs, files in os.walk(cachedir):
217 if not name.endswith(cacheblock_suffix):
220 blockpath = os.path.join(root, name)
221 res = os.stat(blockpath)
223 if len(name) == (32+len(cacheblock_suffix)) and not name.startswith("tmp"):
224 blocks.append((name[0:32], res.st_atime))
225 elif name.startswith("tmp") and ((time.time() - res.st_mtime) > 60):
226 # found a temporary file more than 1 minute old,
233 # sort by access time (atime), going from most recently
234 # accessed (highest timestamp) to least recently accessed
235 # (lowest timestamp).
236 blocks.sort(key=lambda x: x[1], reverse=True)
238 # Map in all the files we found, up to maxslots, if we exceed
239 # maxslots, start throwing things out.
242 got = DiskCacheSlot.get_from_disk(b[0], cachedir)
245 if len(cachelist) < maxslots:
246 cachelist.append(got)
248 # we found more blocks than maxslots, try to
249 # throw it out of the cache.