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 <>
Reviewed-by: default avatarIustin Pop <>
parent 2f1fe558
...@@ -38,17 +38,22 @@ from ganeti.utils import filelock ...@@ -38,17 +38,22 @@ from ganeti.utils import filelock
_RANDOM_UUID_FILE = "/proc/sys/kernel/random/uuid" _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. """Reads a file.
@type size: int @type size: int
@param size: Read at most size bytes (if negative, entire file) @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 @rtype: str
@return: the (possibly partial) content of the file @return: the (possibly partial) content of the file
""" """
f = open(file_name, "r") f = open(file_name, "r")
try: try:
if preread:
return return
finally: finally:
f.close() f.close()
...@@ -55,6 +55,12 @@ class TestReadFile(testutils.GanetiTestCase): ...@@ -55,6 +55,12 @@ class TestReadFile(testutils.GanetiTestCase):
h.update(data) h.update(data)
self.assertEqual(h.hexdigest(), "893772354e4e690b9efd073eed433ce7") 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): def testError(self):
self.assertRaises(EnvironmentError, utils.ReadFile, self.assertRaises(EnvironmentError, utils.ReadFile,
"/dev/null/does-not-exist") "/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