3198: Support mkdir() and rmdir() to create collections on projects. Support
[arvados.git] / services / fuse / arvados_fuse / __init__.py
index e5d812824cbfb97d53f88f7f2cf7ee5682e85edc..2b51b58c07952ece44557ae4a1f1fd6fe35f1f3f 100644 (file)
@@ -67,60 +67,73 @@ class DirectoryHandle(Handle):
 
 
 class InodeCache(object):
-    def __init__(self, cap):
+    def __init__(self, cap, min_entries=4):
         self._entries = collections.OrderedDict()
-        self._counter = itertools.count(1)
+        self._by_uuid = {}
+        self._counter = itertools.count(0)
         self.cap = cap
         self._total = 0
+        self.min_entries = min_entries
+
+    def total(self):
+        return self._total
 
     def _remove(self, obj, clear):
         if clear and not obj.clear():
-            _logger.debug("Could not clear %s in_use %s", obj, obj.in_use())
+            _logger.debug("InodeCache could not clear %i in_use %s", obj.inode, obj.in_use())
             return False
-        self._total -= obj._cache_size
-        del self._entries[obj._cache_priority]
-        _logger.debug("Cleared %s total now %i", obj, self._total)
+        self._total -= obj.cache_size
+        del self._entries[obj.cache_priority]
+        if obj.cache_uuid:
+            del self._by_uuid[obj.cache_uuid]
+            obj.cache_uuid = None
+        if clear:
+            _logger.debug("InodeCache cleared %i total now %i", obj.inode, self._total)
         return True
 
     def cap_cache(self):
-        _logger.debug("total is %i cap is %i", self._total, self.cap)
+        #_logger.debug("InodeCache total is %i cap is %i", self._total, self.cap)
         if self._total > self.cap:
-            need_gc = False
             for key in list(self._entries.keys()):
-                if self._total < self.cap or len(self._entries) < 4:
+                if self._total < self.cap or len(self._entries) < self.min_entries:
                     break
                 self._remove(self._entries[key], True)
 
-
     def manage(self, obj):
         if obj.persisted():
-            obj._cache_priority = next(self._counter)
-            obj._cache_size = obj.objsize()
-            self._entries[obj._cache_priority] = obj
+            obj.cache_priority = next(self._counter)
+            obj.cache_size = obj.objsize()
+            self._entries[obj.cache_priority] = obj
+            obj.cache_uuid = obj.uuid()
+            if obj.cache_uuid:
+                self._by_uuid[obj.cache_uuid] = obj
             self._total += obj.objsize()
-            _logger.debug("Managing %s total now %i", obj, self._total)
+            _logger.debug("InodeCache touched %i (size %i) total now %i", obj.inode, obj.objsize(), self._total)
             self.cap_cache()
+        else:
+            obj.cache_priority = None
 
     def touch(self, obj):
         if obj.persisted():
-            if obj._cache_priority in self._entries:
+            if obj.cache_priority in self._entries:
                 self._remove(obj, False)
             self.manage(obj)
-            _logger.debug("Touched %s (%i) total now %i", obj, obj.objsize(), self._total)
 
     def unmanage(self, obj):
-        if obj.persisted() and obj._cache_priority in self._entries:
+        if obj.persisted() and obj.cache_priority in self._entries:
             self._remove(obj, True)
 
+    def find(self, uuid):
+        return self._by_uuid.get(uuid)
 
 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=256*1024*1024):
+    def __init__(self, inode_cache):
         self._entries = {}
         self._counter = itertools.count(llfuse.ROOT_INODE)
-        self._obj_cache = InodeCache(cap=inode_cache)
+        self.inode_cache = inode_cache
 
     def __getitem__(self, item):
         return self._entries[item]
@@ -139,26 +152,26 @@ class Inodes(object):
 
     def touch(self, entry):
         entry._atime = time.time()
-        self._obj_cache.touch(entry)
-
-    def cap_cache(self):
-        self._obj_cache.cap_cache()
+        self.inode_cache.touch(entry)
 
     def add_entry(self, entry):
         entry.inode = next(self._counter)
+        if entry.inode == llfuse.ROOT_INODE:
+            entry.inc_ref()
         self._entries[entry.inode] = entry
-        self._obj_cache.manage(entry)
+        self.inode_cache.manage(entry)
         return entry
 
     def del_entry(self, entry):
         if entry.ref_count == 0:
-            _logger.warn("Deleting inode %i", entry.inode)
-            self._obj_cache.unmanage(entry)
+            _logger.debug("Deleting inode %i", entry.inode)
+            self.inode_cache.unmanage(entry)
             llfuse.invalidate_inode(entry.inode)
             del self._entries[entry.inode]
+            entry.inode = None
         else:
-            _logger.warn("Inode %i has refcount %i", entry.inode, entry.ref_count)
             entry.dead = True
+            _logger.debug("del_entry on inode %i with refcount %i", entry.inode, entry.ref_count)
 
 def catch_exceptions(orig_func):
     @functools.wraps(orig_func)
@@ -188,9 +201,11 @@ class Operations(llfuse.Operations):
 
     """
 
-    def __init__(self, uid, gid, encoding="utf-8", inode_cache=1000, num_retries=7):
+    def __init__(self, uid, gid, encoding="utf-8", inode_cache=None, num_retries=4):
         super(Operations, self).__init__()
 
+        if not inode_cache:
+            inode_cache = InodeCache(cap=256*1024*1024)
         self.inodes = Inodes(inode_cache)
         self.uid = uid
         self.gid = gid
@@ -198,7 +213,7 @@ class Operations(llfuse.Operations):
 
         # dict of inode to filehandle
         self._filehandles = {}
-        self._filehandles_counter = 1
+        self._filehandles_counter = itertools.count(0)
 
         # Other threads that need to wait until the fuse driver
         # is fully initialized should wait() on this event object.
@@ -206,14 +221,38 @@ class Operations(llfuse.Operations):
 
         self.num_retries = num_retries
 
+        self.events = None
+
     def init(self):
         # Allow threads that are waiting for the driver to be finished
         # initializing to continue
         self.initlock.set()
 
+    def destroy(self):
+        if self.events:
+            self.events.close()
+
     def access(self, inode, mode, ctx):
         return True
 
+    def listen_for_events(self, api_client):
+        self.event = arvados.events.subscribe(api_client,
+                                 [["event_type", "in", ["create", "update", "delete"]]],
+                                 self.on_event)
+
+    def on_event(self, ev):
+        if 'event_type' in ev:
+            with llfuse.lock:
+                item = self.inodes.inode_cache.find(ev["object_uuid"])
+                if item:
+                    item.invalidate()
+                    item.update()
+
+                itemparent = self.inodes.inode_cache.find(ev["object_owner_uuid"])
+                if itemparent:
+                    itemparent.invalidate()
+                    itemparent.update()
+
     @catch_exceptions
     def getattr(self, inode):
         if inode not in self.inodes:
@@ -281,8 +320,8 @@ class Operations(llfuse.Operations):
     @catch_exceptions
     def forget(self, inodes):
         for inode, nlookup in inodes:
-            _logger.debug("arv-mount forget: %i %i", inode, nlookup)
             ent = self.inodes[inode]
+            _logger.debug("arv-mount forget: inode %i nlookup %i ref_count %i", inode, nlookup, ent.ref_count)
             if ent.dec_ref(nlookup) == 0 and ent.dead:
                 self.inodes.del_entry(ent)
 
@@ -299,8 +338,7 @@ class Operations(llfuse.Operations):
         if ((flags & os.O_WRONLY) or (flags & os.O_RDWR)) and not p.writable():
             raise llfuse.FUSEError(errno.EPERM)
 
-        fh = self._filehandles_counter
-        self._filehandles_counter += 1
+        fh = next(self._filehandles_counter)
         self._filehandles[fh] = FileHandle(fh, p)
         self.inodes.touch(p)
         return fh
@@ -349,7 +387,7 @@ class Operations(llfuse.Operations):
                 _logger.exception("Flush error")
             self._filehandles[fh].release()
             del self._filehandles[fh]
-        self.inodes.cap_cache()
+        self.inodes.inode_cache.cap_cache()
 
     def releasedir(self, fh):
         self.release(fh)
@@ -366,8 +404,7 @@ class Operations(llfuse.Operations):
         if not isinstance(p, Directory):
             raise llfuse.FUSEError(errno.ENOTDIR)
 
-        fh = self._filehandles_counter
-        self._filehandles_counter += 1
+        fh = next(self._filehandles_counter)
         if p.parent_inode in self.inodes:
             parent = self.inodes[p.parent_inode]
         else:
@@ -427,22 +464,16 @@ class Operations(llfuse.Operations):
         if not p.writable():
             raise llfuse.FUSEError(errno.EPERM)
 
-        if not isinstance(p, CollectionDirectoryBase):
-            raise llfuse.FUSEError(errno.EPERM)
-
         return p
 
     @catch_exceptions
     def create(self, inode_parent, name, mode, flags, ctx):
         p = self._check_writable(inode_parent)
-
-        with llfuse.lock_released:
-            p.collection.open(name, "w")
+        p.create(name)
 
         # The file entry should have been implicitly created by callback.
         f = p[name]
-        fh = self._filehandles_counter
-        self._filehandles_counter += 1
+        fh = next(self._filehandles_counter)
         self._filehandles[fh] = FileHandle(fh, f)
         self.inodes.touch(p)
 
@@ -451,10 +482,10 @@ class Operations(llfuse.Operations):
 
     @catch_exceptions
     def mkdir(self, inode_parent, name, mode, ctx):
-        p = self._check_writable(inode_parent)
+        _logger.debug("arv-mount mkdir: %i '%s' %o", inode_parent, name, mode)
 
-        with llfuse.lock_released:
-            p.collection.mkdirs(name)
+        p = self._check_writable(inode_parent)
+        p.mkdir(name)
 
         # The dir entry should have been implicitly created by callback.
         d = p[name]
@@ -464,22 +495,22 @@ class Operations(llfuse.Operations):
 
     @catch_exceptions
     def unlink(self, inode_parent, name):
+        _logger.debug("arv-mount unlink: %i '%s'", inode_parent, name)
         p = self._check_writable(inode_parent)
+        p.unlink(name)
 
-        with llfuse.lock_released:
-            p.collection.remove(name)
-
+    @catch_exceptions
     def rmdir(self, inode_parent, name):
-        self.unlink(inode_parent, name)
-
-    # @catch_exceptions
-    # def rename(self, inode_parent_old, name_old, inode_parent_new, name_new):
-    #     src = self._check_writable(inode_parent_old)
-    #     dest = self._check_writable(inode_parent_new)
-    #
-    #     with llfuse.lock_released:
-    #         dest.collection.copy(name_old, name_new, source_collection=src.collection, overwrite=True)
-    #         src.collection.remove(name_old)
+        _logger.debug("arv-mount rmdir: %i '%s'", inode_parent, name)
+        p = self._check_writable(inode_parent)
+        p.rmdir(name)
+
+    @catch_exceptions
+    def rename(self, inode_parent_old, name_old, inode_parent_new, name_new):
+        _logger.debug("arv-mount rename: %i '%s' %i '%s'", inode_parent_old, name_old, inode_parent_new, name_new)
+        src = self._check_writable(inode_parent_old)
+        dest = self._check_writable(inode_parent_new)
+        dest.rename(name_old, name_new, src)
 
     @catch_exceptions
     def flush(self, fh):