git » pyweave » commit f10d895

Implement user locking

author Alberto Bertogli
2009-09-29 17:43:44 UTC
committer Alberto Bertogli
2009-09-29 17:43:44 UTC
parent 3251978125d0c3bf2c0fd8ce922dd5a8d7444c9d

Implement user locking

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>

pyweave.cgi +17 -1

diff --git a/pyweave.cgi b/pyweave.cgi
index 937a38f..e7df225 100755
--- a/pyweave.cgi
+++ b/pyweave.cgi
@@ -26,6 +26,7 @@ import sys
 import os
 import time
 import cgi
+import fcntl
 
 try:
 	import cPickle as pickle
@@ -177,7 +178,6 @@ class Storage (object):
 					d[len(COL_PREFIX):]))
 		return cs
 
-# TODO: per-collection locking
 class Collection (object):
 	def __init__(self, basepath, id):
 		self.basepath = basepath + '/' + col_path(id)
@@ -359,6 +359,18 @@ def read_stdin():
 	debug('STDIN: ' + repr(s))
 	return s
 
+def user_lock(user):
+	"""Locks the given user, returns a lock token to pass to
+	user_unlock()."""
+	fd = open(data_path + '/' + user + '/lock', 'w')
+	fcntl.lockf(fd, fcntl.LOCK_EX)
+	return fd
+
+def user_unlock(token):
+	"""Unlocks the given user. The token must be the one returned by
+	user_lock()."""
+	fcntl.lockf(token, fcntl.LOCK_UN)
+
 def handle_cgi():
 	user = os.environ.get('REMOTE_USER', None)
 	method = os.environ['REQUEST_METHOD']
@@ -372,6 +384,8 @@ def handle_cgi():
 		error(401, "User/path mismatch: %s - %s" % (user, path_user))
 		return
 
+	lock_token = user_lock(user)
+
 	storage = Storage(data_path + '/' + user)
 
 	# TODO: put these into different functions and clean them up
@@ -493,6 +507,8 @@ def handle_cgi():
 			output(time.time())
 
 
+	user_unlock(lock_token)
+
 def handle_cmd():
 	print "This is a CGI application."
 	print "It only runs inside a web server."