3198: Fix tests for change in ~conflict~ format. Tweak comments.
[arvados.git] / services / fuse / arvados_fuse / __init__.py
index 9df9429e2587d13d723ecdd84e7497bbaadf7ca2..abe9821ec3504ff6fabbc02f4deda35869013027 100644 (file)
@@ -1,6 +1,49 @@
-#
-# FUSE driver for Arvados Keep
-#
+"""FUSE driver for Arvados Keep
+
+Architecture:
+
+There is one `Operations` object per mount point.  It is the entry point for all
+read and write requests from the llfuse module.
+
+The operations object owns an `Inodes` object.  The inodes object stores the
+mapping from numeric inode (used throughout the file system API to uniquely
+identify files) to the Python objects that implement files and directories.
+
+The `Inodes` object owns an `InodeCache` object.  The inode cache records the
+memory footprint of file system objects and when they are last used.  When the
+cache limit is exceeded, the least recently used objects are cleared.
+
+File system objects inherit from `fresh.FreshBase` which manages the object lifecycle.
+
+File objects inherit from `fusefile.File`.  Key methods are `readfrom` and `writeto`
+which implement actual reads and writes.
+
+Directory objects inherit from `fusedir.Directory`.  The directory object wraps
+a Python dict which stores the mapping from filenames to directory entries.
+Directory contents can be accessed through the Python operators such as `[]`
+and `in`.  These methods automatically check if the directory is fresh (up to
+date) or stale (needs update) and will call `update` if necessary before
+returing a result.
+
+The general FUSE operation flow is as follows:
+
+- The request handler is called with either an inode or file handle that is the
+  subject of the operation.
+
+- Look up the inode using the Inodes table or the file handle in the
+  filehandles table to get the file system object.
+
+- For methods that alter files or directories, check that the operation is
+  valid and permitted using _check_writable().
+
+- Call the relevant method on the file system object.
+
+- Return the result.
+
+The FUSE driver supports the Arvados event bus.  When an event is received for
+an object that is live in the inode cache, that object is immediately updated.
+
+"""
 
 import os
 import sys
@@ -29,10 +72,11 @@ from fusefile import StringFile, FuseArvadosFile
 
 _logger = logging.getLogger('arvados.arvados_fuse')
 
-log_handler = logging.StreamHandler()
-llogger = logging.getLogger('llfuse')
-llogger.addHandler(log_handler)
-llogger.setLevel(logging.DEBUG)
+# Uncomment this to enable llfuse debug logging.
+# log_handler = logging.StreamHandler()
+# llogger = logging.getLogger('llfuse')
+# llogger.addHandler(log_handler)
+# llogger.setLevel(logging.DEBUG)
 
 class Handle(object):
     """Connects a numeric file handle to a File or Directory object that has
@@ -66,6 +110,17 @@ class DirectoryHandle(Handle):
 
 
 class InodeCache(object):
+    """Records the memory footprint of objects and when they are last used.
+
+    When the cache limit is exceeded, the least recently used objects are
+    cleared.  Clearing the object means discarding its contents to release
+    memory.  The next time the object is accessed, it must be re-fetched from
+    the server.  Note that the inode cache limit is a soft limit; the cache
+    limit may be exceeded if necessary to load very large objects, it may also
+    be exceeded if open file handles prevent objects from being cleared.
+
+    """
+
     def __init__(self, cap, min_entries=4):
         self._entries = collections.OrderedDict()
         self._by_uuid = {}
@@ -91,7 +146,6 @@ class InodeCache(object):
         return True
 
     def cap_cache(self):
-        #_logger.debug("InodeCache total is %i cap is %i", self._total, self.cap)
         if self._total > self.cap:
             for key in list(self._entries.keys()):
                 if self._total < self.cap or len(self._entries) < self.min_entries:
@@ -166,13 +220,17 @@ class Inodes(object):
             _logger.debug("Deleting inode %i", entry.inode)
             self.inode_cache.unmanage(entry)
             llfuse.invalidate_inode(entry.inode)
+            entry.finalize()
             del self._entries[entry.inode]
             entry.inode = None
         else:
             entry.dead = True
             _logger.debug("del_entry on inode %i with refcount %i", entry.inode, entry.ref_count)
 
+
 def catch_exceptions(orig_func):
+    """Catch uncaught exceptions and log them consistently."""
+
     @functools.wraps(orig_func)
     def catch_exceptions_wrapper(self, *args, **kwargs):
         try:
@@ -227,15 +285,21 @@ class Operations(llfuse.Operations):
         # initializing to continue
         self.initlock.set()
 
+    @catch_exceptions
     def destroy(self):
         if self.events:
             self.events.close()
+            self.events = None
+
+        for k,v in self.inodes.items():
+            v.finalize()
+        self.inodes = None
 
     def access(self, inode, mode, ctx):
         return True
 
     def listen_for_events(self, api_client):
-        self.event = arvados.events.subscribe(api_client,
+        self.events = arvados.events.subscribe(api_client,
                                  [["event_type", "in", ["create", "update", "delete"]]],
                                  self.on_event)
 
@@ -245,7 +309,16 @@ class Operations(llfuse.Operations):
                 item = self.inodes.inode_cache.find(ev["object_uuid"])
                 if item is not None:
                     item.invalidate()
-                    item.update()
+                    if ev["object_kind"] == "arvados#collection":
+                        item.update(to_pdh=ev.get("properties", {}).get("new_attributes", {}).get("portable_data_hash"))
+                    else:
+                        item.update()
+
+                oldowner = ev.get("properties", {}).get("old_attributes", {}).get("owner_uuid")
+                olditemparent = self.inodes.inode_cache.find(oldowner)
+                if olditemparent is not None:
+                    olditemparent.invalidate()
+                    olditemparent.update()
 
                 itemparent = self.inodes.inode_cache.find(ev["object_owner_uuid"])
                 if itemparent is not None:
@@ -366,10 +439,9 @@ class Operations(llfuse.Operations):
         self.inodes.touch(handle.obj)
 
         try:
-            with llfuse.lock_released:
-                return handle.obj.readfrom(off, size, self.num_retries)
+            return handle.obj.readfrom(off, size, self.num_retries)
         except arvados.errors.NotFoundError as e:
-            _logger.warning("Block not found: " + str(e))
+            _logger.error("Block not found: " + str(e))
             raise llfuse.FUSEError(errno.EIO)
 
     @catch_exceptions
@@ -385,8 +457,7 @@ class Operations(llfuse.Operations):
 
         self.inodes.touch(handle.obj)
 
-        with llfuse.lock_released:
-            return handle.obj.writeto(off, buf, self.num_retries)
+        return handle.obj.writeto(off, buf, self.num_retries)
 
     @catch_exceptions
     def release(self, fh):
@@ -451,7 +522,7 @@ class Operations(llfuse.Operations):
     @catch_exceptions
     def statfs(self):
         st = llfuse.StatvfsData()
-        st.f_bsize = 64 * 1024
+        st.f_bsize = 128 * 1024
         st.f_blocks = 0
         st.f_files = 0