Skip to content

Commit ca398fd

Browse files
committed
Approximate the amount of space freed during backup rotation
The current output is somewhat hard to read because it displays the size in bytes. Before: ``` Sep 17 03:00:02 xsnippet python3[2230826]: Used space: 30 files, 133721164 bytes Sep 17 03:00:02 xsnippet python3[2230826]: Freed space: 1 files, 4455144 bytes ``` After: ``` Sep 17 03:00:02 xsnippet python3[2230826]: Used space: 30 files, 127.5 MiB Sep 17 03:00:02 xsnippet python3[2230826]: Freed space: 1 files, 4.2 MiB ```
1 parent e14681a commit ca398fd

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

roles/postgres/files/rotate.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,26 @@ def cleanup(to_keep: list[Backup], to_remove: list[Backup], *, dry_run: bool = T
9797
for backup in to_remove:
9898
backup.path.unlink()
9999

100-
print(f"Used space: {len(to_keep)} files, {used_space} bytes")
101-
print(f"Freed space: {len(to_remove)} files, {freed_space} bytes")
100+
print(f"Used space: {len(to_keep)} files, {approximate_size(used_space)}")
101+
print(f"Freed space: {len(to_remove)} files, {approximate_size(freed_space)}")
102+
103+
104+
def approximate_size(size: int) -> str:
105+
"""Convert size in bytes to a human-readable form."""
106+
107+
units = {
108+
2**10: "KiB",
109+
2**20: "MiB",
110+
2**30: "GiB",
111+
2**40: "TiB",
112+
2**50: "PiB",
113+
}
114+
115+
for multiplier, name in reversed(units.items()):
116+
if size >= multiplier:
117+
return "{:.1f} {}".format(size / multiplier, name)
118+
119+
return "{} B".format(size)
102120

103121

104122
def main():

roles/postgres/files/test_rotate.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
import pytest
55

6+
import rotate
7+
68

79
EXPECTED_FILES = [
810
"2024-06-27.tar.gz",
@@ -123,3 +125,26 @@ def test_keep_pattern_does_not_match_anything(backups):
123125
]
124126
)
125127
assert sorted(item.name for item in backups.glob("*")) == EXPECTED_FILES
128+
129+
130+
@pytest.mark.parametrize(
131+
"size,expected",
132+
[
133+
(0, "0 B"),
134+
(1, "1 B"),
135+
(1023, "1023 B"),
136+
(1024, "1.0 KiB"),
137+
(1025, "1.0 KiB"),
138+
(1024 * 1024, "1.0 MiB"),
139+
(5 * 1024 * 1024, "5.0 MiB"),
140+
(1024 * 1024 * 1024, "1.0 GiB"),
141+
(10 * 1024 * 1024 * 1024, "10.0 GiB"),
142+
(1024 * 1024 * 1024 * 1024, "1.0 TiB"),
143+
(13.5 * 1024 * 1024 * 1024 * 1024, "13.5 TiB"),
144+
(1024 * 1024 * 1024 * 1024 * 1024, "1.0 PiB"),
145+
(145.7 * 1024 * 1024 * 1024 * 1024 * 1024, "145.7 PiB"),
146+
(1024 * 1024 * 1024 * 1024 * 1024 * 1024, "1024.0 PiB"),
147+
],
148+
)
149+
def test_approximate_size(size, expected):
150+
assert rotate.approximate_size(size) == expected

0 commit comments

Comments
 (0)