1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
12 class DiskCacheSlot(object):
13 __slots__ = ("locator", "ready", "content", "cachedir")
15 def __init__(self, locator, cachedir):
16 self.locator = locator
17 self.ready = threading.Event()
19 self.cachedir = cachedir
32 # Can't mmap a 0 length file
36 if self.content is not None:
37 # Has been set already
40 blockdir = os.path.join(self.cachedir, self.locator[0:3])
41 os.makedirs(blockdir, mode=0o700, exist_ok=True)
43 final = os.path.join(blockdir, self.locator)
45 f = tempfile.NamedTemporaryFile(dir=blockdir, delete=False)
47 os.chmod(tmpfile, stat.S_IRUSR | stat.S_IWUSR)
51 os.rename(tmpfile, final)
53 self.content = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
54 except Exception as e:
60 if self.content is None:
63 return len(self.content)
66 if self.content is not None and len(self.content) > 0:
67 # The mmap region might be in use when we decided to evict
68 # it. This can happen if the cache is too small.
70 # If we call close() now, it'll throw an error if
71 # something tries to access it.
73 # However, we don't need to explicitly call mmap.close()
75 # I confirmed in mmapmodule.c that that both close
76 # and deallocate do the same thing:
78 # a) close the file descriptor
79 # b) unmap the memory range
81 # So we can forget it in the cache and delete the file on
82 # disk, and it will tear it down after any other
83 # lingering Python references to the mapped memory are
86 blockdir = os.path.join(self.cachedir, self.locator[0:3])
87 final = os.path.join(blockdir, self.locator)
94 def get_from_disk(locator, cachedir):
95 blockdir = os.path.join(cachedir, locator[0:3])
96 final = os.path.join(blockdir, locator)
99 filehandle = open(final, "rb")
101 content = mmap.mmap(filehandle.fileno(), 0, access=mmap.ACCESS_READ)
102 dc = DiskCacheSlot(locator, cachedir)
106 except FileNotFoundError:
108 except Exception as e:
109 traceback.print_exc()
114 def init_cache(cachedir, maxslots):
115 # map in all the files in the cache directory, up to max slots.
116 # after max slots, try to delete the excess blocks.
118 # this gives the calling process ownership of all the blocks
121 for root, dirs, files in os.walk(cachedir):
123 blockpath = os.path.join(root, name)
124 res = os.stat(blockpath)
125 blocks.append((name, res.st_atime))
127 # sort by access time (atime), going from most recently
128 # accessed (highest timestamp) to least recently accessed
129 # (lowest timestamp).
130 blocks.sort(key=lambda x: x[1], reverse=True)
132 # Map in all the files we found, up to maxslots, if we exceed
133 # maxslots, start throwing things out.
136 got = DiskCacheSlot.get_from_disk(b[0], cachedir)
139 if len(cachelist) < maxslots:
140 cachelist.append(got)
142 # we found more blocks than maxslots, try to
143 # throw it out of the cache.