Merge lp:~roadmr/checkbox/1185508-memory-compare-units into lp:checkbox

Proposed by Daniel Manrique
Status: Merged
Approved by: Zygmunt Krynicki
Approved revision: 3245
Merged at revision: 3258
Proposed branch: lp:~roadmr/checkbox/1185508-memory-compare-units
Merge into: lp:checkbox
Diff against target: 85 lines (+40/-8)
1 file modified
providers/plainbox-provider-checkbox/bin/memory_compare (+40/-8)
To merge this branch: bzr merge lp:~roadmr/checkbox/1185508-memory-compare-units
Reviewer Review Type Date Requested Status
Zygmunt Krynicki (community) Approve
Review via email: mp+233282@code.launchpad.net

Commit message

providers:checkbox: Improved memory size presentation in memory_compare.

Description of the change

providers:checkbox: Improved memory size presentation in memory_compare.

Sizes will always look like:

X.XX$UNIT

where UNIT can be bytes or QiB (where Q in turn is the appropriate metric prefix).

For instance:

456.00 bytes (the decimal number is redundant; if this is too ugly let me know and I can fix it, though it would balloon the dead-simple method to about twice its size :D)

7.56GiB

1023.99TiB (e.g. if I add 0.01 TiB here, it would become 1.00 PiB; also, if the quantity is already an integer I can remove the decimals, at the expense of more time and code).

To post a comment you must log in.
Revision history for this message
Zygmunt Krynicki (zyga) wrote :

(venv)zyga@silverblade:/ramdisk/1185508-memory-compare-units/providers/plainbox-provider-checkbox$ ./bin/memory_compare
Results:
 /proc/meminfo reports: 15.37GiB
 lshw reports: 15.37GiB
Traceback (most recent call last):
  File "./bin/memory_compare", line 92, in bytes_to_human
    exponent = log(my_bytes, 1024)
ValueError: math domain error

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./bin/memory_compare", line 140, in <module>
    sys.exit(main())
  File "./bin/memory_compare", line 125, in main
    "%d%% variance allowed." % (bytes_to_human(difference), percentage, threshold))
  File "./bin/memory_compare", line 94, in bytes_to_human
    raise ValueError("cannot compute base-1024 logarithm of {!r}: {}".format(my_bytes, exc))
ValueError: cannot compute base-1024 logarithm of 0: math domain error

Hmm?

review: Needs Fixing
Revision history for this message
Zygmunt Krynicki (zyga) wrote :

That was with the following delta:

(venv)zyga@silverblade:/ramdisk/1185508-memory-compare-units/providers/plainbox-provider-checkbox$ bzr diff
=== modified file 'providers/plainbox-provider-checkbox/bin/memory_compare'
--- providers/plainbox-provider-checkbox/bin/memory_compare 2014-09-03 22:04:18 +0000
+++ providers/plainbox-provider-checkbox/bin/memory_compare 2014-09-03 22:35:14 +0000
@@ -88,7 +88,10 @@
     suffixes = ["bytes", "KiB", "MiB", "GiB", "TiB",
                 "PiB", "EiB", "ZiB", "YiB"]
     # my_bytes' base-1024 logarithm.
- exponent = log(my_bytes, 1024)
+ try:
+ exponent = log(my_bytes, 1024)
+ except ValueError as exc:
+ raise ValueError("cannot compute base-1024 logarithm of {!r}: {}".format(my_bytes, exc))
     suffix = suffixes[int(exponent)]
     scalar = my_bytes / (1024**int(exponent))

@@ -96,10 +99,6 @@

 def main():
- if os.geteuid() != 0:
- print("This script must be run as root.", file=sys.stderr)
- return 1
-
     installed_memory = get_installed_memory_size()
     visible_memory = get_visible_memory_size()
     threshold = get_threshold(installed_memory)

Revision history for this message
Daniel Manrique (roadmr) wrote :

Wow :) Passing '0' to the function is possible (as you saw) and easy to handle, but mathematically the logarithm will also barf if I pass a negative value; how to handle this is less clear, and though it *should* not happen, it could happen if for some reason reported memory is less than visible memory. Perhaps we should catch that possibility earlier; or strip the sign before doing the calculation and then reattaching it before outputting the string.

I'll think of a good way to handle that case, will resubmit soon.

3245. By Daniel Manrique

providers:checkbox: Improved memory size presentation in memory_compare

Revision history for this message
Daniel Manrique (roadmr) wrote :

Fixed, it should now handle both 0-byte and negative sizes correctly (in addition it won't crash if you give something larger than 1024 Yottabytes, which is unlikely, but at least it will now output something sensible).

Revision history for this message
Zygmunt Krynicki (zyga) wrote :

Thanks :-)

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'providers/plainbox-provider-checkbox/bin/memory_compare'
2--- providers/plainbox-provider-checkbox/bin/memory_compare 2014-08-11 21:21:14 +0000
3+++ providers/plainbox-provider-checkbox/bin/memory_compare 2014-09-04 14:27:47 +0000
4@@ -24,6 +24,7 @@
5
6 import os
7 import sys
8+from math import log, copysign
9 from subprocess import check_output, PIPE
10
11 from checkbox_support.parsers.lshwjson import LshwJsonParser
12@@ -81,6 +82,32 @@
13 return 10
14
15
16+def bytes_to_human(my_bytes):
17+ """ Convert my_bytes to a scaled representation with a
18+ suffix
19+ """
20+ if my_bytes == 0:
21+ return "0 bytes"
22+
23+ suffixes = ["bytes", "KiB", "MiB", "GiB", "TiB",
24+ "PiB", "EiB", "ZiB", "YiB"]
25+
26+ try:
27+ sign = copysign(1, my_bytes)
28+ except OverflowError as excp:
29+ return "(Number too large: {})".format(excp)
30+ my_bytes = abs(my_bytes)
31+ # my_bytes' base-1024 logarithm.
32+ exponent = log(my_bytes, 1024)
33+ try:
34+ suffix = suffixes[int(exponent)]
35+ except IndexError:
36+ return "(Number too large)"
37+ scalar = my_bytes / (1024**int(exponent))
38+
39+ return "{:.2f} {}".format(sign * scalar, suffix)
40+
41+
42 def main():
43 if os.geteuid() != 0:
44 print("This script must be run as root.", file=sys.stderr)
45@@ -95,9 +122,11 @@
46 percentage = difference / installed_memory * 100
47 except ZeroDivisionError:
48 print("Results:")
49- print("\t/proc/meminfo reports:\t%s kB" % (visible_memory / 1024),
50+ print("\t/proc/meminfo reports:\t{}".format(
51+ bytes_to_human(visible_memory)),
52 file=sys.stderr)
53- print("\tlshw reports:\t%s kB" % (installed_memory / 1024),
54+ print("\tlshw reports:\t{}".format(
55+ bytes_to_human(installed_memory)),
56 file=sys.stderr)
57 print("\nFAIL: Either lshw or /proc/meminfo returned a memory size "
58 "of 0 kB", file=sys.stderr)
59@@ -105,17 +134,20 @@
60
61 if percentage <= threshold:
62 print("Results:")
63- print("\t/proc/meminfo reports:\t%s kB" % (visible_memory / 1024))
64- print("\tlshw reports:\t%s kB" % (installed_memory / 1024))
65- print("\nPASS: Meminfo reports %d bytes less than lshw, a "
66+ print("\t/proc/meminfo reports:\t{}".format(
67+ bytes_to_human(visible_memory)))
68+ print("\tlshw reports:\t{}".format(bytes_to_human(installed_memory)))
69+ print("\nPASS: Meminfo reports %s less than lshw, a "
70 "difference of %.2f%%. This is less than the "
71- "%d%% variance allowed." % (difference, percentage, threshold))
72+ "%d%% variance allowed." % (bytes_to_human(difference),
73+ percentage, threshold))
74 return 0
75 else:
76 print("Results:", file=sys.stderr)
77- print("\t/proc/meminfo reports:\t%s kB" % (visible_memory / 1024),
78+ print("\t/proc/meminfo reports:\t{}".format(
79+ bytes_to_human(visible_memory)),
80 file=sys.stderr)
81- print("\tlshw reports:\t%s kB" % (installed_memory / 1024),
82+ print("\tlshw reports:\t{}".format(bytes_to_human(installed_memory)),
83 file=sys.stderr)
84 print("\nFAIL: Meminfo reports %d bytes less than lshw, "
85 "a difference of %.2f%%. Only a variance of %d%% in "

Subscribers

People subscribed via source and target branches