1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
13 class DiskCacheSlot(object):
14 __slots__ = ("locator", "ready", "content", "cachedir")
16 def __init__(self, locator, cachedir):
17 self.locator = locator
18 self.ready = threading.Event()
20 self.cachedir = cachedir
33 # Can't mmap a 0 length file
37 if self.content is not None:
38 # Has been set already
41 blockdir = os.path.join(self.cachedir, self.locator[0:3])
42 os.makedirs(blockdir, mode=0o700, exist_ok=True)
44 final = os.path.join(blockdir, self.locator)
46 f = tempfile.NamedTemporaryFile(dir=blockdir, delete=False)
48 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 # Get it, check it, return it
96 blockdir = os.path.join(cachedir, locator[0:3])
97 final = os.path.join(blockdir, locator)
100 filehandle = open(final, "rb")
101 content = mmap.mmap(filehandle.fileno(), 0, access=mmap.ACCESS_READ)
102 disk_md5 = hashlib.md5(content).hexdigest()
103 if disk_md5 == locator:
104 dc = DiskCacheSlot(locator, cachedir)
108 except FileNotFoundError:
110 except Exception as e:
111 traceback.print_exc()