定期删除 ZFS Snapshot

好风 发表于 2018-09-17T03:57:51.522053Z
引用地址:https://plus.ooclab.com/note/article/1417

ZFS Snapshot 非常方便,开销小。不过,对于备份数据来讲,创建 snapshot 的频率越高(比如1小时一次), 占用存储空间越大,因此定期删除非常重要。

本文提供一个简单的方案: 1. ZFS 创建 snapshot 时,添加时间戳 2. 通过一个 python 脚本判断时间戳,筛选需要删除的 snapshot 名称 3. 调用 zfs 命令删除快照

#!/usr/bin/env python

'''
Usage:

    # save this script to /stor/clean_snapshot.py
    zfs list -t snapshot | python /stor/clean_snapshot.py | xargs -i zfs destroy {}

Debug:

    stor/xxx-git@20180910210229  7.54M      -  5.36G  -
'''

import datetime
import sys
import fileinput

def takeSecond(elem):
    return elem[1]

def main():
    now = datetime.datetime.now()
    keep_one = {}
    for line in fileinput.input():
        L = line.strip().split()
        if len(L) != 5:
            continue
        snapname = L[0]
        L = snapname.split('/')
        if len(L) != 2:
            continue
        L = L[1].split('@')
        if len(L) != 2:
            continue
        project = L[0]
        snapdate = datetime.datetime.strptime(L[1], "%Y%m%d%H%M%S")
        diff = now.date() - snapdate.date()

        if diff.days <= 3:
            continue

        if diff.days > 60:
            print snapname

        if diff.days > 3:
            k = ":".join([str(diff.days), project])
            if k in keep_one:
                keep_one[k].append((snapname, snapdate))
            else:
                keep_one[k] = [(snapname, snapdate)]

    for k in keep_one:
        keep_one[k].sort(key=takeSecond)
        for sn, _ in keep_one[k][1:]:
            print sn



if __name__ == '__main__':
    main()