Commit 0e5084ee authored by Michael Hanselmann's avatar Michael Hanselmann
Browse files

utils.ReadFile: Add pre-read callback



This will be used by the watcher to store the file's fstat(2). It must
be done from the filehandle.
Signed-off-by: default avatarMichael Hanselmann <hansmi@google.com>
Reviewed-by: default avatarIustin Pop <iustin@google.com>
parent 2f1fe558
......@@ -38,17 +38,22 @@ from ganeti.utils import filelock
_RANDOM_UUID_FILE = "/proc/sys/kernel/random/uuid"
def ReadFile(file_name, size=-1):
def ReadFile(file_name, size=-1, preread=None):
"""Reads a file.
@type size: int
@param size: Read at most size bytes (if negative, entire file)
@type preread: callable receiving file handle as single parameter
@param preread: Function called before file is read
@rtype: str
@return: the (possibly partial) content of the file
"""
f = open(file_name, "r")
try:
if preread:
preread(f)
return f.read(size)
finally:
f.close()
......
......@@ -55,6 +55,12 @@ class TestReadFile(testutils.GanetiTestCase):
h.update(data)
self.assertEqual(h.hexdigest(), "893772354e4e690b9efd073eed433ce7")
def testCallback(self):
def _Cb(fh):
self.assertEqual(fh.tell(), 0)
data = utils.ReadFile(self._TestDataFilename("cert1.pem"), preread=_Cb)
self.assertEqual(len(data), 814)
def testError(self):
self.assertRaises(EnvironmentError, utils.ReadFile,
"/dev/null/does-not-exist")
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment