Files
windows-fenjian/core/evidence/retention.py
T

189 lines
5.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""抓拍留档的定期清理。
现场每天几百到上千张抓拍,全是 1280px 的 JPEG,一张约 150KB。攒一年就是
几十 GB —— C 盘那点空间早就撑不住,而且出问题时翻旧图也没意义。
这里只做两件事:
① 按天数和总量淘汰旧图(老的最先走);
② 保住最近的一批(keep_min),哪怕天数超了 —— 万一现场刚出完错账,
当班的图一定要还在。
不删「最近 10 分钟内」的文件:可能正被台账页/拒绝队列引用,也可能正在
上传,删了会看到一堆死链。
"""
import os
import json
import time
import datetime
STATE_PATH = os.path.join('data', 'cleanup_state.json')
EXTS = ('.jpg', '.jpeg', '.png')
RECENT_GUARD_S = 600.0 # 10 分钟内新写的文件不碰
def _files(d):
out = []
try:
names = os.listdir(d)
except OSError:
return out
for fn in names:
if not fn.lower().endswith(EXTS):
continue
p = os.path.join(d, fn)
try:
st = os.stat(p)
except OSError:
continue
if not os.path.isfile(p):
continue
out.append((p, st.st_size, st.st_mtime))
return out
def usage(d):
"""(张数, 字节数)。目录不存在时返回 (0, 0)。"""
fs = _files(d)
return len(fs), sum(s for _p, s, _m in fs)
def cleanup(d, keep_days=30, keep_min=200, max_mb=0, now=None, dry_run=False):
"""清一次。返回统计 dict(dry_run 时只统计不删)。
淘汰顺序:先按天数(超过 keep_days 的删),再按总量(超过 max_mb 的
从最旧的开始删)。两道闸都受 keep_min 与「10 分钟内」保护。
"""
now = time.time() if now is None else now
fs = _files(d)
fs.sort(key=lambda x: x[2]) # 旧 → 新
total = sum(s for _p, s, _m in fs)
stat = {'dir': d, 'files': len(fs), 'bytes': total,
'removed': 0, 'freed': 0, 'kept': len(fs), 'bytes_after': total}
if not fs:
return stat
try:
keep_min = max(0, int(keep_min))
except (TypeError, ValueError):
keep_min = 0
try:
keep_days = float(keep_days)
except (TypeError, ValueError):
keep_days = 0
try:
max_bytes = float(max_mb) * 1024 * 1024
except (TypeError, ValueError):
max_bytes = 0
cutoff = now - keep_days * 86400 if keep_days > 0 else None
# keep_min 是「最新 N 张」的下标边界:只有排在它之前的才允许删
frozen_from = max(0, len(fs) - keep_min)
drop = []
for i, (p, s, m) in enumerate(fs):
if i >= frozen_from:
break
if now - m < RECENT_GUARD_S:
continue # 刚写入的,跳过
if cutoff is not None and m < cutoff:
drop.append((p, s))
dropped = sum(s for _p, s in drop)
remain = total - dropped
if max_bytes > 0 and remain > max_bytes:
for i, (p, s, m) in enumerate(fs):
if remain <= max_bytes:
break
if i >= frozen_from or now - m < RECENT_GUARD_S:
continue
if any(p == q for q, _s in drop):
continue
drop.append((p, s))
remain -= s
if not dry_run:
for p, s in drop:
try:
os.remove(p)
stat['removed'] += 1
stat['freed'] += s
except OSError:
remain += s
else:
stat['removed'] = len(drop)
stat['freed'] = sum(s for _p, s in drop)
stat['kept'] = stat['files'] - stat['removed']
stat['bytes_after'] = max(0, total - stat['freed'])
return stat
def read_state(path=STATE_PATH):
try:
with open(path, encoding='utf-8') as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def write_state(state, path=STATE_PATH):
try:
os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
tmp = path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(state, f, ensure_ascii=False, indent=1)
os.replace(tmp, path)
except OSError:
pass
def due(interval_h=6.0, now=None, path=STATE_PATH):
"""距上次清理是否够久了。首次运行(没记录)算 due。"""
now = time.time() if now is None else now
try:
interval_h = float(interval_h)
except (TypeError, ValueError):
interval_h = 6.0
if interval_h <= 0:
return False
last = read_state(path).get('last_at') or 0
try:
last = float(last)
except (TypeError, ValueError):
last = 0
if last <= 0:
return True # 从没清过(新机器/换目录)就该清
return now - last >= interval_h * 3600
def stamp(result, now=None, path=STATE_PATH):
"""记下这次清理的结果,下次 due() 才有依据。"""
now = time.time() if now is None else now
st = read_state(path)
st.update({
'last_at': now,
'last_text': datetime.datetime.fromtimestamp(now)
.strftime('%Y-%m-%d %H:%M:%S'),
'dir': result.get('dir'),
'removed': result.get('removed', 0),
'freed': result.get('freed', 0),
'kept': result.get('kept', 0),
'bytes_after': result.get('bytes_after', 0),
})
write_state(st, path)
return st
def human(n):
"""字节数 → 「1.5 MB」这种看得懂的形式。"""
n = float(n or 0)
units = ('B', 'KB', 'MB', 'GB')
i = 0
while n >= 1024 and i < len(units) - 1:
n /= 1024.0
i += 1
return ('%d %s' % (n, units[i])) if i == 0 else ('%.1f %s' % (n, units[i]))