1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
14 class DiskCacheSlot(object):
15 __slots__ = ("locator", "ready", "content", "cachedir")
17 def __init__(self, locator, cachedir):
18 self.locator = locator
19 self.ready = threading.Event()
21 self.cachedir = cachedir
34 # Can't mmap a 0 length file
38 if self.content is not None:
39 # Has been set already
42 blockdir = os.path.join(self.cachedir, self.locator[0:3])
43 os.makedirs(blockdir, mode=0o700, exist_ok=True)
45 final = os.path.join(blockdir, self.locator)
47 f = tempfile.NamedTemporaryFile(dir=blockdir, delete=False)
49 os.chmod(tmpfile, stat.S_IRUSR | stat.S_IWUSR)
51 # aquire a shared lock, this tells other processes that
52 # we're using this block and to please not delete it.
53 fcntl.flock(f, fcntl.LOCK_SH)
57 os.rename(tmpfile, final)
59 self.content = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
60 except Exception as e:
66 if self.content is None:
69 return len(self.content)
72 if self.content is not None and len(self.content) > 0:
73 # The mmap region might be in use when we decided to evict
74 # it. This can happen if the cache is too small.
76 # If we call close() now, it'll throw an error if
77 # something tries to access it.
79 # However, we don't need to explicitly call mmap.close()
81 # I confirmed in mmapmodule.c that that both close
82 # and deallocate do the same thing:
84 # a) close the file descriptor
85 # b) unmap the memory range
87 # So we can forget it in the cache and delete the file on
88 # disk, and it will tear it down after any other
89 # lingering Python references to the mapped memory are
92 blockdir = os.path.join(self.cachedir, self.locator[0:3])
93 final = os.path.join(blockdir, self.locator)
95 # If we can't upgrade our shared lock to an exclusive
96 # lock, it'll throw an error, that's fine and
97 # desirable, it means another process has a lock and
98 # we shouldn't delete the block.
99 fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
105 def get_from_disk(locator, cachedir):
106 # Get it, check it, return it
107 blockdir = os.path.join(cachedir, locator[0:3])
108 final = os.path.join(blockdir, locator)
111 filehandle = open(final, "rb")
113 # aquire a shared lock, this tells other processes that
114 # we're using this block and to please not delete it.
115 fcntl.flock(f, fcntl.LOCK_SH)
117 content = mmap.mmap(filehandle.fileno(), 0, access=mmap.ACCESS_READ)
118 disk_md5 = hashlib.md5(content).hexdigest()
119 if disk_md5 == locator:
120 dc = DiskCacheSlot(locator, cachedir)
124 except FileNotFoundError:
126 except Exception as e:
127 traceback.print_exc()
132 def cleanup_cachedir(cachedir, maxsize):
135 for root, dirs, files in os.walk(cachedir):
137 blockpath = os.path.join(root, name)
138 res = os.stat(blockpath)
139 blocks.append((blockpath, res.st_size, res.st_atime))
140 totalsize += res.st_size
142 if totalsize <= maxsize:
145 # sort by atime, so the blocks accessed the longest time in
146 # the past get deleted first.
147 blocks.sort(key=lambda x: x[2])
149 # go through the list and try deleting blocks until we're
150 # below the target size and/or we run out of blocks
152 while i < len(blocks) and totalsize > maxsize:
154 with open(blocks[i][0], "rb") as f:
155 # If we can't get an exclusive lock, it'll
156 # throw an error, that's fine and desirable,
157 # it means another process has a lock and we
158 # shouldn't delete the block.
159 fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
161 totalsize -= blocks[i][1]