20259: Add documentation for banner and tooltip features
[arvados.git] / sdk / python / arvados / diskcache.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import threading
6 import mmap
7 import os
8 import traceback
9 import stat
10 import tempfile
11 import fcntl
12 import time
13 import errno
14 import logging
15 import weakref
16
17 _logger = logging.getLogger('arvados.keep')
18
19 cacheblock_suffix = ".keepcacheblock"
20
21 class DiskCacheSlot(object):
22     __slots__ = ("locator", "ready", "content", "cachedir", "filehandle", "linger")
23
24     def __init__(self, locator, cachedir):
25         self.locator = locator
26         self.ready = threading.Event()
27         self.content = None
28         self.cachedir = cachedir
29         self.filehandle = None
30         self.linger = None
31
32     def get(self):
33         self.ready.wait()
34         return self.content
35
36     def set(self, value):
37         tmpfile = None
38         try:
39             if value is None:
40                 self.content = None
41                 self.ready.set()
42                 return
43
44             if len(value) == 0:
45                 # Can't mmap a 0 length file
46                 self.content = b''
47                 self.ready.set()
48                 return
49
50             if self.content is not None:
51                 # Has been set already
52                 self.ready.set()
53                 return
54
55             blockdir = os.path.join(self.cachedir, self.locator[0:3])
56             os.makedirs(blockdir, mode=0o700, exist_ok=True)
57
58             final = os.path.join(blockdir, self.locator) + cacheblock_suffix
59
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)
63
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)
67
68             self.filehandle.write(value)
69             self.filehandle.flush()
70             os.rename(tmpfile, final)
71             tmpfile = None
72
73             self.content = mmap.mmap(self.filehandle.fileno(), 0, access=mmap.ACCESS_READ)
74             # only set the event when mmap is successful
75             self.ready.set()
76         finally:
77             if tmpfile is not None:
78                 # If the tempfile hasn't been renamed on disk yet, try to delete it.
79                 try:
80                     os.remove(tmpfile)
81                 except:
82                     pass
83
84     def size(self):
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
89                 # space.
90                 content = self.linger()
91                 if content is not None:
92                     return len(content)
93             return 0
94         else:
95             return len(self.content)
96
97     def evict(self):
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.
101             #
102             # If we call close() now, it'll throw an error if
103             # something tries to access it.
104             #
105             # However, we don't need to explicitly call mmap.close()
106             #
107             # I confirmed in mmapmodule.c that that both close
108             # and deallocate do the same thing:
109             #
110             # a) close the file descriptor
111             # b) unmap the memory range
112             #
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
116             # gone.
117
118             blockdir = os.path.join(self.cachedir, self.locator[0:3])
119             final = os.path.join(blockdir, self.locator) + cacheblock_suffix
120             try:
121                 fcntl.flock(self.filehandle, fcntl.LOCK_UN)
122
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.
128                 #
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.
141                 #
142                 fcntl.flock(self.filehandle, fcntl.LOCK_EX | fcntl.LOCK_NB)
143
144                 os.remove(final)
145                 return True
146             except OSError:
147                 pass
148             finally:
149                 self.filehandle = None
150                 self.linger = weakref.ref(self.content)
151                 self.content = None
152         return False
153
154     def gone(self):
155         # Test if an evicted object is lingering
156         return self.content is None and (self.linger is None or self.linger() is None)
157
158     @staticmethod
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
162
163         try:
164             filehandle = open(final, "rb")
165
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)
169
170             content = mmap.mmap(filehandle.fileno(), 0, access=mmap.ACCESS_READ)
171             dc = DiskCacheSlot(locator, cachedir)
172             dc.filehandle = filehandle
173             dc.content = content
174             dc.ready.set()
175             return dc
176         except FileNotFoundError:
177             pass
178         except Exception as e:
179             traceback.print_exc()
180
181         return None
182
183     @staticmethod
184     def cache_usage(cachedir):
185         usage = 0
186         for root, dirs, files in os.walk(cachedir):
187             for name in files:
188                 if not name.endswith(cacheblock_suffix):
189                     continue
190
191                 blockpath = os.path.join(root, name)
192                 res = os.stat(blockpath)
193                 usage += res.st_size
194         return usage
195
196
197     @staticmethod
198     def init_cache(cachedir, maxslots):
199         #
200         # First check the disk cache works at all by creating a 1 byte cache entry
201         #
202         checkexists = DiskCacheSlot.get_from_disk('0cc175b9c0f1b6a831c399e269772661', cachedir)
203         ds = DiskCacheSlot('0cc175b9c0f1b6a831c399e269772661', cachedir)
204         ds.set(b'a')
205         if checkexists is None:
206             # Don't keep the test entry around unless it existed beforehand.
207             ds.evict()
208
209         # map in all the files in the cache directory, up to max slots.
210         # after max slots, try to delete the excess blocks.
211         #
212         # this gives the calling process ownership of all the blocks
213
214         blocks = []
215         for root, dirs, files in os.walk(cachedir):
216             for name in files:
217                 if not name.endswith(cacheblock_suffix):
218                     continue
219
220                 blockpath = os.path.join(root, name)
221                 res = os.stat(blockpath)
222
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,
227                     # try to delete it.
228                     try:
229                         os.remove(blockpath)
230                     except:
231                         pass
232
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)
237
238         # Map in all the files we found, up to maxslots, if we exceed
239         # maxslots, start throwing things out.
240         cachelist = []
241         for b in blocks:
242             got = DiskCacheSlot.get_from_disk(b[0], cachedir)
243             if got is None:
244                 continue
245             if len(cachelist) < maxslots:
246                 cachelist.append(got)
247             else:
248                 # we found more blocks than maxslots, try to
249                 # throw it out of the cache.
250                 got.evict()
251
252         return cachelist