From 9975d57d5ec1b45f069aebef8b37e868000a349f Mon Sep 17 00:00:00 2001 From: Jarrod Johnson Date: Fri, 25 Sep 2015 16:59:42 -0400 Subject: [PATCH] Implement Locking in Windows log code Under windows, we can't use flock. However we can get locking using msvcrt using different, but related semantics. Imitate whole file locking by just locking first byte. We have to make sure we seek() to the same place when locking and unlocking, as Windows requires the offset to be same for both operations. --- confluent_server/confluent/log.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/confluent_server/confluent/log.py b/confluent_server/confluent/log.py index 5b85ee54..951ed2de 100644 --- a/confluent_server/confluent/log.py +++ b/confluent_server/confluent/log.py @@ -71,11 +71,18 @@ import traceback try: from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_SH except ImportError: - flock = lambda file, flag: True - LOCK_EX = None - LOCK_UN = None - LOCK_SH = None - + if os.name == 'nt': + import msvcrt + LOCK_SH = msvcrt.LK_LOCK # no shared, degrade to exclusive + LOCK_EX = msvcrt.LK_LOCK + LOCK_UN = msvcrt.LK_UNLCK + def flock(file, flag): + oldoffset = file.tell() + file.seek(0) + msvcrt.locking(file.fileno(), flag, 1) + file.seek(oldoffset) + else: + raise # on conserving filehandles: # upon write, if file not open, open it for append @@ -152,8 +159,10 @@ class Logger(object): def writedata(self): if self.textfile is None: self.textfile = open(self.textpath, mode='ab') + self.textfile.seek(0, 2) if self.binfile is None: self.binfile = open(self.binpath, mode='ab') + self.binfile.seek(0, 2) while self.logentries: entry = self.logentries.popleft() ltype = entry[0]