Backend trash and container/object purge.
[pithos] / pithos / backends / simple.py
index 00aad0e..220bca2 100644 (file)
@@ -58,11 +58,17 @@ class SimpleBackend(BaseBackend):
         self.hash_algorithm = 'sha1'
         self.block_size = 128 * 1024 # 128KB
         
+        self.default_policy = {'quota': 0, 'versioning': 'auto'}
+        
         basepath = os.path.split(db)[0]
         if basepath and not os.path.exists(basepath):
             os.makedirs(basepath)
         
         self.con = sqlite3.connect(db, check_same_thread=False)
+        
+        sql = '''pragma foreign_keys = on'''
+        self.con.execute(sql)
+        
         sql = '''create table if not exists versions (
                     version_id integer primary key,
                     name text,
@@ -72,30 +78,40 @@ class SimpleBackend(BaseBackend):
                     hide integer default 0)'''
         self.con.execute(sql)
         sql = '''create table if not exists metadata (
-                    version_id integer, key text, value text, primary key (version_id, key))'''
+                    version_id integer,
+                    key text,
+                    value text,
+                    primary key (version_id, key)
+                    foreign key (version_id) references versions(version_id)
+                    on delete cascade)'''
+        self.con.execute(sql)
+        sql = '''create table if not exists hashmaps (
+                    version_id integer,
+                    pos integer,
+                    block_id text,
+                    primary key (version_id, pos)
+                    foreign key (version_id) references versions(version_id)
+                    on delete cascade)'''
         self.con.execute(sql)
         sql = '''create table if not exists blocks (
                     block_id text, data blob, primary key (block_id))'''
         self.con.execute(sql)
-        sql = '''create table if not exists hashmaps (
-                    version_id integer, pos integer, block_id text, primary key (version_id, pos))'''
+        
+        sql = '''create table if not exists policy (
+                    name text, key text, value text, primary key (name, key))'''
+        self.con.execute(sql)
+        
+        sql = '''create table if not exists groups (
+                    account text, name text, users text, primary key (account, name))'''
         self.con.execute(sql)
         sql = '''create table if not exists permissions (
                     name text, read text, write text, primary key (name))'''
         self.con.execute(sql)
+        sql = '''create table if not exists public (
+                    name text, primary key (name))'''
+        self.con.execute(sql)
         self.con.commit()
     
-    def delete_account(self, user, account):
-        """Delete the account with the given name."""
-        
-        logger.debug("delete_account: %s", account)
-        if user != account:
-            raise NotAllowedError
-        count, bytes, tstamp = self._get_pathstats(account)
-        if count > 0:
-            raise IndexError('Account is not empty')
-        self._del_path(account) # Point of no return.
-    
     def get_account_meta(self, user, account, until=None):
         """Return a dictionary with the account metadata."""
         
@@ -140,40 +156,72 @@ class SimpleBackend(BaseBackend):
             raise NotAllowedError
         self._put_metadata(user, account, meta, replace)
     
-    def list_containers(self, user, account, marker=None, limit=10000, until=None):
-        """Return a list of containers existing under an account."""
+    def get_account_groups(self, user, account):
+        """Return a dictionary with the user groups defined for this account."""
         
-        logger.debug("list_containers: %s %s %s %s", account, marker, limit, until)
+        logger.debug("get_account_groups: %s", account)
         if user != account:
             raise NotAllowedError
-        return self._list_objects(account, '', '/', marker, limit, False, [], until)
+        return self._get_groups(account)
     
-    def put_container(self, user, account, container):
-        """Create a new container with the given name."""
+    def update_account_groups(self, user, account, groups, replace=False):
+        """Update the groups associated with the account."""
         
-        logger.debug("put_container: %s %s", account, container)
+        logger.debug("update_account_groups: %s %s %s", account, groups, replace)
+        if user != account:
+            raise NotAllowedError
+        for k, v in groups.iteritems():
+            if True in [False or ',' in x for x in v]:
+                raise ValueError('Bad characters in groups')
+        if replace:
+            sql = 'delete from groups where account = ?'
+            self.con.execute(sql, (account,))
+        for k, v in groups.iteritems():
+            if len(v) == 0:
+                if not replace:
+                    sql = 'delete from groups where account = ? and name = ?'
+                    self.con.execute(sql, (account, k))
+            else:
+                sql = 'insert or replace into groups (account, name, users) values (?, ?, ?)'
+                self.con.execute(sql, (account, k, ','.join(v)))
+        self.con.commit()
+    
+    def put_account(self, user, account):
+        """Create a new account with the given name."""
+        
+        logger.debug("put_account: %s", account)
         if user != account:
             raise NotAllowedError
         try:
-            path, version_id, mtime = self._get_containerinfo(account, container)
+            version_id, mtime = self._get_accountinfo(account)
         except NameError:
-            path = os.path.join(account, container)
-            version_id = self._put_version(path, user)
+            pass
         else:
-            raise NameError('Container already exists')
+            raise NameError('Account already exists')
+        version_id = self._put_version(account, user)
+        self.con.commit()
     
-    def delete_container(self, user, account, container):
-        """Delete the container with the given name."""
+    def delete_account(self, user, account):
+        """Delete the account with the given name."""
         
-        logger.debug("delete_container: %s %s", account, container)
+        logger.debug("delete_account: %s", account)
         if user != account:
             raise NotAllowedError
-        path, version_id, mtime = self._get_containerinfo(account, container)
-        count, bytes, tstamp = self._get_pathstats(path)
-        if count > 0:
-            raise IndexError('Container is not empty')
-        self._del_path(path) # Point of no return.
-        self._copy_version(user, account, account, True, True) # New account version.
+        if self._get_pathcount(account) > 0:
+            raise IndexError('Account is not empty')
+        sql = 'delete from versions where name = ?'
+        self.con.execute(sql, (path,))
+        sql = 'delete from groups where name = ?'
+        self.con.execute(sql, (account,))
+        self.con.commit()
+    
+    def list_containers(self, user, account, marker=None, limit=10000, until=None):
+        """Return a list of containers existing under an account."""
+        
+        logger.debug("list_containers: %s %s %s %s", account, marker, limit, until)
+        if user != account:
+            raise NotAllowedError
+        return self._list_objects(account, '', '/', marker, limit, False, [], until)
     
     def get_container_meta(self, user, account, container, until=None):
         """Return a dictionary with the container metadata."""
@@ -207,6 +255,84 @@ class SimpleBackend(BaseBackend):
         path, version_id, mtime = self._get_containerinfo(account, container)
         self._put_metadata(user, path, meta, replace)
     
+    def get_container_policy(self, user, account, container):
+        """Return a dictionary with the container policy."""
+        
+        logger.debug("get_container_policy: %s %s", account, container)
+        if user != account:
+            raise NotAllowedError
+        path = self._get_containerinfo(account, container)[0]
+        return self._get_policy(path)
+    
+    def update_container_policy(self, user, account, container, policy, replace=False):
+        """Update the policy associated with the account."""
+        
+        logger.debug("update_container_policy: %s %s %s %s", account, container, policy, replace)
+        if user != account:
+            raise NotAllowedError
+        path = self._get_containerinfo(account, container)[0]
+        self._check_policy(policy)
+        if replace:
+            for k, v in self.default_policy.iteritems():
+                if k not in policy:
+                    policy[k] = v
+        for k, v in policy.iteritems():
+            sql = 'insert or replace into policy (name, key, value) values (?, ?, ?)'
+            self.con.execute(sql, (path, k, v))
+        self.con.commit()
+    
+    def put_container(self, user, account, container, policy=None):
+        """Create a new container with the given name."""
+        
+        logger.debug("put_container: %s %s %s", account, container, policy)
+        if user != account:
+            raise NotAllowedError
+        try:
+            path, version_id, mtime = self._get_containerinfo(account, container)
+        except NameError:
+            pass
+        else:
+            raise NameError('Container already exists')
+        if policy:
+            self._check_policy(policy)
+        path = os.path.join(account, container)
+        version_id = self._put_version(path, user)
+        for k, v in self.default_policy.iteritems():
+            if k not in policy:
+                policy[k] = v
+        for k, v in policy.iteritems():
+            sql = 'insert or replace into policy (name, key, value) values (?, ?, ?)'
+            self.con.execute(sql, (path, k, v))
+        self.con.commit()
+    
+    def delete_container(self, user, account, container, until=None):
+        """Delete the container with the given name."""
+        
+        logger.debug("delete_container: %s %s %s", account, container, until)
+        if user != account:
+            raise NotAllowedError
+        path, version_id, mtime = self._get_containerinfo(account, container)
+        
+        if until is not None:
+            sql = '''select version_id from versions where name like ? and tstamp <= datetime(%s, 'unixepoch')'''
+            c = self.con.execute(sql, (path + '/%', until))
+            versions = [x[0] for x in c.fetchall()]
+            for v in versions:
+                sql = 'delete from hashmaps where version_id = ?'
+                self.con.execute(sql, (v,))
+                sql = 'delete from versions where version_id = ?'
+                self.con.execute(sql, (v,))
+            self.con.commit()
+            return
+        
+        if self._get_pathcount(path) > 0:
+            raise IndexError('Container is not empty')
+        sql = 'delete from versions where name = ?'
+        self.con.execute(sql, (path,))
+        sql = 'delete from policy where name = ?'
+        self.con.execute(sql, (path,))
+        self._copy_version(user, account, account, True, True) # New account version (for timestamp update).
+    
     def list_objects(self, user, account, container, prefix='', delimiter=None, marker=None, limit=10000, virtual=True, keys=[], until=None):
         """Return a list of objects existing under a container."""
         
@@ -273,6 +399,24 @@ class SimpleBackend(BaseBackend):
         r, w = self._check_permissions(path, permissions)
         self._put_permissions(path, r, w)
     
+    def get_object_public(self, user, account, container, name):
+        """Return the public URL of the object if applicable."""
+        
+        logger.debug("get_object_public: %s %s %s", account, container, name)
+        self._can_read(user, account, container, name)
+        path = self._get_objectinfo(account, container, name)[0]
+        if self._get_public(path):
+            return '/public/' + path
+        return None
+    
+    def update_object_public(self, user, account, container, name, public):
+        """Update the public status of the object."""
+        
+        logger.debug("update_object_public: %s %s %s %s", account, container, name, public)
+        self._can_write(user, account, container, name)
+        path = self._get_objectinfo(account, container, name)[0]
+        self._put_public(path, public)
+    
     def get_object_hashmap(self, user, account, container, name, version=None):
         """Return the object's size and a list with partial hashes."""
         
@@ -353,18 +497,57 @@ class SimpleBackend(BaseBackend):
         self.copy_object(user, account, src_container, src_name, dest_container, dest_name, dest_meta, replace_meta, permissions, None)
         self.delete_object(user, account, src_container, src_name)
     
-    def delete_object(self, user, account, container, name):
+    def delete_object(self, user, account, container, name, until=None):
         """Delete an object."""
         
-        logger.debug("delete_object: %s %s %s", account, container, name)
+        logger.debug("delete_object: %s %s %s %s", account, container, name, until)
         if user != account:
             raise NotAllowedError
-        path = self._get_objectinfo(account, container, name)[0]
-        self._put_version(path, user, 0, 1)
-        sql = 'delete from permissions where name = ?'
-        self.con.execute(sql, (path,))
+        if until is None:
+            path = self._get_objectinfo(account, container, name)[0]
+            sql = 'select version_id from versions where name = ?'
+            c = self.con.execute(sql, (path,))
+        else:
+            path = os.path.join(account, container, name)
+            sql = '''select version_id from versions where name = ? and tstamp <= datetime(%s, 'unixepoch')'''
+            c = self.con.execute(sql, (path, until))
+        versions = [x[0] for x in c.fetchall()]
+        for v in versions:
+            sql = 'delete from hashmaps where version_id = ?'
+            self.con.execute(sql, (v,))
+            sql = 'delete from versions where version_id = ?'
+            self.con.execute(sql, (v,))
+        
+        # If no more versions exist, delete permissions/public.
+        sql = 'select version_id from versions where name = ?'
+        row = self.con.execute(sql, (path,)).fetchone()
+        if row is None:
+            self._del_sharing(path)
         self.con.commit()
     
+    def update_object_trash(self, user, account, container, name, trash=True):
+        """Trash/untrash an object."""
+        
+        logger.debug("trash_object: %s %s %s", account, container, name)
+        if user != account:
+            raise NotAllowedError
+        if trash:
+            path, version_id, muser, mtime, size = self._get_objectinfo(account, container, name)
+            self._del_sharing(path)
+        else:
+            path = os.path.join(account, container, name)
+            sql = '''select version_id, hide from versions where name = ?
+                        order by version_id desc limit 1'''
+            c = self.con.execute(sql, (path,))
+            row = c.fetchone()
+            if not row or not int(row[1]):
+                raise NameError('Object not in trash')
+            version_id = row[0]
+        hide = 1 if trash else 0
+        sql = 'update versions set hide = ? where version_id = ?'
+        self.con.execute(sql, (hide, version_id,))
+        seld.con.commit()
+    
     def list_versions(self, user, account, container, name):
         """Return a list of all (version, version_timestamp) tuples for an object."""
         
@@ -372,7 +555,7 @@ class SimpleBackend(BaseBackend):
         self._can_read(user, account, container, name)
         # This will even show deleted versions.
         path = os.path.join(account, container, name)
-        sql = '''select distinct version_id, strftime('%s', tstamp) from versions where name = ? and hide = 0'''
+        sql = '''select distinct version_id, strftime('%s', tstamp) from versions where name = ?'''
         c = self.con.execute(sql, (path,))
         return [(int(x[0]), int(x[1])) for x in c.fetchall()]
     
@@ -423,7 +606,7 @@ class SimpleBackend(BaseBackend):
         return sql % ('%s', until)
     
     def _get_pathstats(self, path, until=None):
-        """Return count and sum of size of everything under path and latest timestamp."""
+        """Return count, sum of size and latest timestamp of everything under path (latest versions/no trash)."""
         
         sql = 'select count(version_id), total(size), max(tstamp) from (%s) where name like ?'
         sql = sql % self._sql_until(until)
@@ -432,6 +615,14 @@ class SimpleBackend(BaseBackend):
         tstamp = row[2] if row[2] is not None else 0
         return int(row[0]), int(row[1]), int(tstamp)
     
+    def _get_pathcount(self, path):
+        """Return count of everything under path (including versions/trash)."""
+        
+        sql = 'select count(version_id) from versions where name like ?'
+        c = self.con.execute(sql, (path + '/%',))
+        row = c.fetchone()
+        return int(row[0])
+    
     def _get_version(self, path, version=None):
         if version is None:
             sql = '''select version_id, user, strftime('%s', tstamp), size, hide from versions where name = ?
@@ -450,9 +641,9 @@ class SimpleBackend(BaseBackend):
                 raise IndexError('Version does not exist')
         return str(row[0]), str(row[1]), int(row[2]), int(row[3])
     
-    def _put_version(self, path, user, size=0, hide=0):
-        sql = 'insert into versions (name, user, size, hide) values (?, ?, ?, ?)'
-        id = self.con.execute(sql, (path, user, size, hide)).lastrowid
+    def _put_version(self, path, user, size=0):
+        sql = 'insert into versions (name, user, size) values (?, ?, ?)'
+        id = self.con.execute(sql, (path, user, size)).lastrowid
         self.con.commit()
         return str(id)
     
@@ -534,11 +725,51 @@ class SimpleBackend(BaseBackend):
                 self.con.execute(sql, (dest_version_id, k, v))
         self.con.commit()
     
+    def _get_groups(self, account):
+        sql = 'select name, users from groups where account = ?'
+        c = self.con.execute(sql, (account,))
+        return dict([(x[0], x[1].split(',')) for x in c.fetchall()])
+    
+    def _check_policy(self, policy):
+        for k in policy.keys():
+            if policy[k] == '':
+                policy[k] = self.default_policy.get(k)
+        for k, v in policy.iteritems():
+            if k == 'quota':
+                q = int(v) # May raise ValueError.
+                if q < 0:
+                    raise ValueError
+            elif k == 'versioning':
+                if v not in ['auto', 'manual', 'none']:
+                    raise ValueError
+            else:
+                raise ValueError
+    
+    def _get_policy(self, path):
+        sql = 'select key, value from policy where name = ?'
+        c = self.con.execute(sql, (path,))
+        return dict(c.fetchall())
+    
     def _is_allowed(self, user, account, container, name, op='read'):
         if user == account:
             return True
         path = os.path.join(account, container, name)
+        if op == 'read' and self._get_public(path):
+            return True
         perm_path, perms = self._get_permissions(path)
+        
+        # Expand groups.
+        for x in ('read', 'write'):
+            g_perms = []
+            for y in perms.get(x, []):
+                groups = self._get_groups(account)
+                if y in groups: #it's a group
+                    for g_name in groups[y]:
+                        g_perms.append(g_name)
+                else: #it's a user
+                    g_perms.append(y)
+            perms[x] = g_perms
+        
         if op == 'read' and user in perms.get('read', []):
             return True
         if user in perms.get('write', []):
@@ -558,9 +789,11 @@ class SimpleBackend(BaseBackend):
         sql = '''select name from permissions
                     where name != ? and (name like ? or ? like name || ?)'''
         c = self.con.execute(sql, (path, path + '%', path, '%'))
-        rows = c.fetchall()
-        if rows:
-            raise AttributeError('Permissions already set')
+        row = c.fetchone()
+        if row:
+            ae = AttributeError()
+            ae.data = row[0]
+            raise ae
         
         # Format given permissions.
         if len(permissions) == 0:
@@ -598,6 +831,29 @@ class SimpleBackend(BaseBackend):
             self.con.execute(sql, (path, r, w))
         self.con.commit()
     
+    def _get_public(self, path):
+        sql = 'select name from public where name = ?'
+        c = self.con.execute(sql, (path,))
+        row = c.fetchone()
+        if not row:
+            return False
+        return True
+    
+    def _put_public(self, path, public):
+        if not public:
+            sql = 'delete from public where name = ?'
+        else:
+            sql = 'insert or replace into public (name) values (?)'
+        self.con.execute(sql, (path,))
+        self.con.commit()
+    
+    def _del_sharing(self, path):
+        sql = 'delete from permissions where name = ?'
+        self.con.execute(sql, (path,))
+        sql = 'delete from public where name = ?'
+        self.con.execute(sql, (path,))
+        self.con.commit()
+    
     def _list_objects(self, path, prefix='', delimiter=None, marker=None, limit=10000, virtual=True, keys=[], until=None):
         cont_prefix = path + '/'
         if keys and len(keys) > 0:
@@ -641,16 +897,3 @@ class SimpleBackend(BaseBackend):
         if not limit or limit > 10000:
             limit = 10000
         return objects[start:start + limit]
-    
-    def _del_path(self, path):
-        sql = '''delete from hashmaps where version_id in
-                    (select version_id from versions where name = ?)'''
-        self.con.execute(sql, (path,))
-        sql = '''delete from metadata where version_id in
-                    (select version_id from versions where name = ?)'''
-        self.con.execute(sql, (path,))
-        sql = '''delete from versions where name = ?'''
-        self.con.execute(sql, (path,))
-        sql = '''delete from permissions where name like ?'''
-        self.con.execute(sql, (path + '%',)) # Redundant.
-        self.con.commit()