diff --git a/lib/utils.py b/lib/utils.py index a1fd259e0b065e8c0e4cb98fbf3c1448513e7f49..ffb8b70f20531225ae9010259ac1a45d02642e73 100644 --- a/lib/utils.py +++ b/lib/utils.py @@ -3188,6 +3188,31 @@ def FormatTime(val): return time.strftime("%F %T", time.localtime(val)) +def FormatSeconds(secs): + """Formats seconds for easier reading. + + @type secs: number + @param secs: Number of seconds + @rtype: string + @return: Formatted seconds (e.g. "2d 9h 19m 49s") + + """ + parts = [] + + secs = round(secs, 0) + + if secs > 0: + # Negative values would be a bit tricky + for unit, one in [("d", 24 * 60 * 60), ("h", 60 * 60), ("m", 60)]: + (complete, secs) = divmod(secs, one) + if complete or parts: + parts.append("%d%s" % (complete, unit)) + + parts.append("%ds" % secs) + + return " ".join(parts) + + def ReadWatcherPauseFile(filename, now=None, remove_after=3600): """Reads the watcher pause file. diff --git a/test/ganeti.utils_unittest.py b/test/ganeti.utils_unittest.py index 2c964d57c5ecec95949c08457deec77bf42265bb..68ef826727b036ca0718b1e7d05a729ef4ff31a0 100755 --- a/test/ganeti.utils_unittest.py +++ b/test/ganeti.utils_unittest.py @@ -2364,5 +2364,27 @@ class TestEnsureDirs(unittest.TestCase): os.rmdir(self.dir) os.umask(self.old_umask) + +class TestFormatSeconds(unittest.TestCase): + def test(self): + self.assertEqual(utils.FormatSeconds(1), "1s") + self.assertEqual(utils.FormatSeconds(3600), "1h 0m 0s") + self.assertEqual(utils.FormatSeconds(3599), "59m 59s") + self.assertEqual(utils.FormatSeconds(7200), "2h 0m 0s") + self.assertEqual(utils.FormatSeconds(7201), "2h 0m 1s") + self.assertEqual(utils.FormatSeconds(7281), "2h 1m 21s") + self.assertEqual(utils.FormatSeconds(29119), "8h 5m 19s") + self.assertEqual(utils.FormatSeconds(19431228), "224d 21h 33m 48s") + self.assertEqual(utils.FormatSeconds(-1), "-1s") + self.assertEqual(utils.FormatSeconds(-282), "-282s") + self.assertEqual(utils.FormatSeconds(-29119), "-29119s") + + def testFloat(self): + self.assertEqual(utils.FormatSeconds(1.3), "1s") + self.assertEqual(utils.FormatSeconds(1.9), "2s") + self.assertEqual(utils.FormatSeconds(3912.12311), "1h 5m 12s") + self.assertEqual(utils.FormatSeconds(3912.8), "1h 5m 13s") + + if __name__ == '__main__': testutils.GanetiTestProgram()