3198: Add enable_write flag to FUSE and --enable-write and --read-only to
[arvados.git] / services / fuse / arvados_fuse / __init__.py
index 46c5a1b06bd88fdd22ddbe779bd195e2006cfc0f..a2b91a67187a27122bece6c8c381fcce823cdc19 100644 (file)
@@ -72,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
@@ -145,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:
@@ -183,10 +183,11 @@ class Inodes(object):
     """Manage the set of inodes.  This is the mapping from a numeric id
     to a concrete File or Directory object"""
 
-    def __init__(self, inode_cache):
+    def __init__(self, inode_cache, encoding="utf-8"):
         self._entries = {}
         self._counter = itertools.count(llfuse.ROOT_INODE)
         self.inode_cache = inode_cache
+        self.encoding = encoding
 
     def __getitem__(self, item):
         return self._entries[item]
@@ -220,6 +221,7 @@ 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:
@@ -257,15 +259,15 @@ class Operations(llfuse.Operations):
 
     """
 
-    def __init__(self, uid, gid, encoding="utf-8", inode_cache=None, num_retries=4):
+    def __init__(self, uid, gid, encoding="utf-8", inode_cache=None, num_retries=4, enable_write=False):
         super(Operations, self).__init__()
 
         if not inode_cache:
             inode_cache = InodeCache(cap=256*1024*1024)
-        self.inodes = Inodes(inode_cache)
+        self.inodes = Inodes(inode_cache, encoding=encoding)
         self.uid = uid
         self.gid = gid
-        self.encoding = encoding
+        self.enable_write = enable_write
 
         # dict of inode to filehandle
         self._filehandles = {}
@@ -284,18 +286,25 @@ 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)
 
+    @catch_exceptions
     def on_event(self, ev):
         if 'event_type' in ev:
             with llfuse.lock:
@@ -303,11 +312,13 @@ class Operations(llfuse.Operations):
                 if item is not None:
                     item.invalidate()
                     if ev["object_kind"] == "arvados#collection":
-                        item.update(to_pdh=ev.get("properties", {}).get("new_attributes", {}).get("portable_data_hash"))
+                        new_attr = ev.get("properties") and ev["properties"].get("new_attributes") and ev["properties"]["new_attributes"]
+                        record_version = (new_attr["modified_at"], new_attr["portable_data_hash"]) if new_attr else None
+                        item.update(to_record_version=record_version)
                     else:
                         item.update()
 
-                oldowner = ev.get("properties", {}).get("old_attributes", {}).get("owner_uuid")
+                oldowner = ev.get("properties") and ev["properties"].get("old_attributes") and ev["properties"]["old_attributes"].get("owner_uuid")
                 olditemparent = self.inodes.inode_cache.find(oldowner)
                 if olditemparent is not None:
                     olditemparent.invalidate()
@@ -328,8 +339,8 @@ class Operations(llfuse.Operations):
         entry = llfuse.EntryAttributes()
         entry.st_ino = inode
         entry.generation = 0
-        entry.entry_timeout = 300
-        entry.attr_timeout = 300
+        entry.entry_timeout = 60
+        entry.attr_timeout = 60
 
         entry.st_mode = stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
         if isinstance(e, Directory):
@@ -339,7 +350,7 @@ class Operations(llfuse.Operations):
             if isinstance(e, FuseArvadosFile):
                 entry.st_mode |= stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
 
-        if e.writable():
+        if self.enable_write and e.writable():
             entry.st_mode |= stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH
 
         entry.st_nlink = 1
@@ -350,7 +361,7 @@ class Operations(llfuse.Operations):
         entry.st_size = e.size()
 
         entry.st_blksize = 512
-        entry.st_blocks = (e.size()/512)+1
+        entry.st_blocks = (entry.st_size/512)+1
         entry.st_atime = int(e.atime())
         entry.st_mtime = int(e.mtime())
         entry.st_ctime = int(e.mtime())
@@ -372,7 +383,7 @@ class Operations(llfuse.Operations):
 
     @catch_exceptions
     def lookup(self, parent_inode, name):
-        name = unicode(name, self.encoding)
+        name = unicode(name, self.inodes.encoding)
         inode = None
 
         if name == '.':
@@ -506,10 +517,7 @@ class Operations(llfuse.Operations):
         e = off
         while e < len(handle.entries):
             if handle.entries[e][1].inode in self.inodes:
-                try:
-                    yield (handle.entries[e][0].encode(self.encoding), self.getattr(handle.entries[e][1].inode), e+1)
-                except UnicodeEncodeError:
-                    pass
+                yield (handle.entries[e][0].encode(self.inodes.encoding), self.getattr(handle.entries[e][1].inode), e+1)
             e += 1
 
     @catch_exceptions
@@ -529,6 +537,9 @@ class Operations(llfuse.Operations):
         return st
 
     def _check_writable(self, inode_parent):
+        if not self.enable_write:
+            raise llfuse.FUSEError(errno.EROFS)
+
         if inode_parent in self.inodes:
             p = self.inodes[inode_parent]
         else: