From 3f6a47a8e67ffcccc631b3508bf9013289342011 Mon Sep 17 00:00:00 2001 From: Michael Hanselmann <hansmi@google.com> Date: Tue, 28 Jul 2009 19:29:47 +0200 Subject: [PATCH] utils: Add functions to calc directory size and free space on filesystem These will be used by the new storage unit framework. Signed-off-by: Michael Hanselmann <hansmi@google.com> Reviewed-by: Iustin Pop <iustin@google.com> Reviewed-by: Guido Trotter <ultrotter@google.com> --- lib/utils.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/lib/utils.py b/lib/utils.py index 37bb12804..0af26132a 100644 --- a/lib/utils.py +++ b/lib/utils.py @@ -1847,6 +1847,51 @@ def CommaJoin(names): return ", ".join(["'%s'" % val for val in names]) +def BytesToMebibyte(value): + """Converts bytes to mebibytes. + + @type value: int + @param value: Value in bytes + @rtype: int + @return: Value in mebibytes + + """ + return int(round(value / (1024.0 * 1024.0), 0)) + + +def CalculateDirectorySize(path): + """Calculates the size of a directory recursively. + + @type path: string + @param path: Path to directory + @rtype: int + @return: Size in mebibytes + + """ + size = 0 + + for (curpath, _, files) in os.walk(path): + for file in files: + st = os.lstat(os.path.join(curpath, file)) + size += st.st_size + + return BytesToMebibyte(size) + + +def GetFreeFilesystemSpace(path): + """Returns the free space on a filesystem. + + @type path: string + @param path: Path on filesystem to be examined + @rtype: int + @return: Free space in mebibytes + + """ + st = os.statvfs(path) + + return BytesToMebibyte(st.f_bavail * st.f_frsize) + + def LockedMethod(fn): """Synchronized object access decorator. -- GitLab