142 lines
5.0 KiB
Python
Executable File
142 lines
5.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""spacereport - full disk-space report: mounts, top directories, top files, growth.
|
|
Usage: spacereport [PATH] [--top N] [--selftest]"""
|
|
import argparse, csv, os, sys
|
|
from collections import defaultdict
|
|
|
|
def human(n):
|
|
for u in ("B", "K", "M", "G", "T"):
|
|
if abs(n) < 1024 or u == "T":
|
|
return f"{n:.1f}{u}" if u != "B" else f"{int(n)}B"
|
|
n /= 1024.0
|
|
return f"{n:.1f}T"
|
|
|
|
def scan(path, depth=2):
|
|
"""Return (dir_sizes, top_files). dir_sizes maps dir->bytes (recursive, depth-limited)."""
|
|
dir_sizes = defaultdict(int)
|
|
top_files = []
|
|
for root, dirs, files in os.walk(path):
|
|
rel = os.path.relpath(root, path)
|
|
d = 0 if rel == "." else rel.count(os.sep) + 1
|
|
if d > depth:
|
|
dirs[:] = []
|
|
continue
|
|
for name in files:
|
|
p = os.path.join(root, name)
|
|
try:
|
|
st = os.lstat(p)
|
|
except OSError:
|
|
continue
|
|
if not os.path.isfile(p):
|
|
continue
|
|
sz = st.st_size
|
|
top_files.append((sz, p))
|
|
# credit every ancestor up to the scanned root
|
|
cur = root
|
|
while True:
|
|
dir_sizes[cur] += sz
|
|
if cur == path:
|
|
break
|
|
cur = os.path.dirname(cur)
|
|
top_files.sort(reverse=True)
|
|
return dir_sizes, top_files
|
|
|
|
def growth_lines(db="~/.cache/fileutils/diskfill.csv"):
|
|
path = os.path.expanduser(db)
|
|
if not os.path.exists(path):
|
|
return ["no diskfill snapshots found - run 'diskfill snapshot' twice, days apart."]
|
|
rows = []
|
|
try:
|
|
with open(path, newline="") as f:
|
|
for row in csv.reader(f):
|
|
if len(row) == 4:
|
|
rows.append((float(row[0]), row[1], int(row[2]), int(row[3])))
|
|
except (OSError, ValueError):
|
|
return ["diskfill snapshot file unreadable."]
|
|
by = defaultdict(list)
|
|
for r in rows:
|
|
by[r[1]].append(r)
|
|
out = []
|
|
for mp in sorted(by):
|
|
rs = sorted(by[mp])
|
|
if len(rs) < 2:
|
|
out.append(f"{mp}: 1 snapshot, no trend yet")
|
|
continue
|
|
dt = (rs[-1][0] - rs[0][0]) / 86400
|
|
du = rs[-1][2] - rs[0][2]
|
|
rate = du / dt if dt > 0 else 0
|
|
left = rs[-1][3] - rs[-1][2]
|
|
days = left / rate if rate > 0 else float("inf")
|
|
out.append(f"{mp}: {human(rate)}/day, {human(left)} free, "
|
|
f"{'fills in %.0f days' % days if rate > 0 else 'not growing'}")
|
|
return out
|
|
|
|
def report(path, top=10):
|
|
lines = []
|
|
lines.append(f"=== mounts ===")
|
|
for mp, fs in _mounts():
|
|
try:
|
|
st = os.statvfs(mp)
|
|
except OSError:
|
|
continue
|
|
total = st.f_blocks * st.f_frsize
|
|
if total == 0:
|
|
continue
|
|
free = st.f_bfree * st.f_frsize
|
|
pct = 100.0 * (total - free) / total
|
|
flag = " <-- FULL" if pct >= 90 else ""
|
|
lines.append(f"{mp:<24} {fs:<10} {human(total):>9} total {human(free):>9} free {pct:5.1f}%{flag}")
|
|
dir_sizes, top_files = scan(path)
|
|
lines.append(f"\n=== top directories under {path} ===")
|
|
for d, sz in sorted(dir_sizes.items(), key=lambda kv: -kv[1])[:top]:
|
|
lines.append(f"{human(sz):>10} {d}")
|
|
lines.append(f"\n=== top files under {path} ===")
|
|
for sz, p in top_files[:top]:
|
|
lines.append(f"{human(sz):>10} {p}")
|
|
lines.append("\n=== growth (from diskfill snapshots) ===")
|
|
lines.extend(growth_lines())
|
|
return "\n".join(lines)
|
|
|
|
def _mounts():
|
|
try:
|
|
with open("/proc/mounts") as f:
|
|
for line in f:
|
|
p = line.split()
|
|
if len(p) >= 3:
|
|
yield p[1], p[2]
|
|
except OSError:
|
|
return
|
|
|
|
def selftest():
|
|
import tempfile
|
|
tmp = tempfile.mkdtemp(prefix="spacereport-test-")
|
|
os.makedirs(os.path.join(tmp, "sub"))
|
|
with open(os.path.join(tmp, "sub", "big.bin"), "wb") as f:
|
|
f.write(b"x" * 5000)
|
|
with open(os.path.join(tmp, "small.txt"), "w") as f:
|
|
f.write("hi")
|
|
out = report(tmp, top=5)
|
|
ok = True
|
|
for needle in ("mounts", "top directories", "top files", "growth", "big.bin", "sub"):
|
|
if needle not in out:
|
|
print(f"FAIL: report missing {needle!r}"); ok = False
|
|
import shutil; shutil.rmtree(tmp, ignore_errors=True)
|
|
if ok:
|
|
print("selftest: PASS (all four report sections present on temp tree)")
|
|
return 0 if ok else 1
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(prog="spacereport",
|
|
description="Full disk-space report: mounts, top directories, top files, growth.")
|
|
ap.add_argument("path", nargs="?", default=".", help="tree to scan (default: .)")
|
|
ap.add_argument("--top", type=int, default=10, help="entries per list (default 10)")
|
|
ap.add_argument("--selftest", action="store_true", help="run built-in checks on a temp tree")
|
|
a = ap.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
print(report(a.path, a.top))
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|