From 2635bb04740bc5b90a5f955ba29c7569b9d55b45 Mon Sep 17 00:00:00 2001
From: Michael Hanselmann <hansmi@google.com>
Date: Thu, 5 Jan 2012 21:22:45 +0100
Subject: [PATCH] Move helper class from watcher to utils.io
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

β€œFileStatHelper” can be used together with β€œReadFile” to a file's status
while it's opened. This avoids certain race conditions.

Signed-off-by: Michael Hanselmann <hansmi@google.com>
Reviewed-by: Iustin Pop <iustin@google.com>
---
 lib/utils/io.py         | 19 +++++++++++++++++++
 lib/watcher/__init__.py | 19 +------------------
 2 files changed, 20 insertions(+), 18 deletions(-)

diff --git a/lib/utils/io.py b/lib/utils/io.py
index 8c785f7d7..ed55f92d6 100644
--- a/lib/utils/io.py
+++ b/lib/utils/io.py
@@ -72,6 +72,25 @@ def ErrnoOrStr(err):
   return detail
 
 
+class FileStatHelper:
+  """Helper to store file handle's C{fstat}.
+
+  Useful in combination with L{ReadFile}'s C{preread} parameter.
+
+  """
+  def __init__(self):
+    """Initializes this class.
+
+    """
+    self.st = None
+
+  def __call__(self, fh):
+    """Calls C{fstat} on file handle.
+
+    """
+    self.st = os.fstat(fh.fileno())
+
+
 def ReadFile(file_name, size=-1, preread=None):
   """Reads a file.
 
diff --git a/lib/watcher/__init__.py b/lib/watcher/__init__.py
index 915dea031..0325cce15 100644
--- a/lib/watcher/__init__.py
+++ b/lib/watcher/__init__.py
@@ -410,23 +410,6 @@ def _UpdateInstanceStatus(filename, instances):
                                   for inst in instances])
 
 
-class _StatCb:
-  """Helper to store file handle's C{fstat}.
-
-  """
-  def __init__(self):
-    """Initializes this class.
-
-    """
-    self.st = None
-
-  def __call__(self, fh):
-    """Calls C{fstat} on file handle.
-
-    """
-    self.st = os.fstat(fh.fileno())
-
-
 def _ReadInstanceStatus(filename):
   """Reads an instance status file.
 
@@ -440,7 +423,7 @@ def _ReadInstanceStatus(filename):
   """
   logging.debug("Reading per-group instance status from '%s'", filename)
 
-  statcb = _StatCb()
+  statcb = utils.FileStatHelper()
   try:
     content = utils.ReadFile(filename, preread=statcb)
   except EnvironmentError, err:
-- 
GitLab