#!/usr/bin/env python1###############################################################################2#3# CoCalc: Collaborative Calculation in the Cloud4#5# Copyright (C) 2016, Sagemath Inc.6#7# This program is free software: you can redistribute it and/or modify8# it under the terms of the GNU General Public License as published by9# the Free Software Foundation, either version 3 of the License, or10# (at your option) any later version.11#12# This program is distributed in the hope that it will be useful,13# but WITHOUT ANY WARRANTY; without even the implied warranty of14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15# GNU General Public License for more details.16#17# You should have received a copy of the GNU General Public License18# along with this program. If not, see <http://www.gnu.org/licenses/>.19#20###############################################################################21222324# Delete all snapshots of a given ZFS filesystem but **NOT** of descendant filesystems25# Or -- if filesystem='90d', delete all snapshots of all filesystems whose name ends in "--90d".2627import sys, time28from subprocess import Popen, PIPE293031def cmd(v):32t = time.time()33print ' '.join(v),34sys.stdout.flush()35out = Popen(v,stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)36x = out.stdout.read()37y = out.stderr.read()38e = out.wait()39if e:40raise RuntimeError(y)41print " (%.2f seconds)"%(time.time()-t)42return x4344def delete_snapshots(filesystem):4546if filesystem == '90d':47print "deleting all snapshots of any filesystem in any pool that contain '--90d\\t'"48x = cmd(['zfs', 'list', '-H', '-r', '-t', 'snapshot'])4950# take only those ending in --90d51lines = [t for t in x.splitlines() if '--90d\t'in t]5253else:54print "deleting snapshots of filesystem %s"%filesystem55x = cmd(['zfs', 'list', '-H', '-r', '-t', 'snapshot', filesystem])5657# get rid of descendant filesystems in list.58lines = [t for t in x.splitlines() if filesystem+"@" in t]5960total = len(lines)61print "%s snapshots to delete"%total6263i = 064for a in lines:65if a:66snapshot = a.split()[0]67print snapshot68cmd(['zfs', 'destroy', snapshot])69i += 170print "%s/%s"%(i,total)7172for filesystem in sys.argv[1:]:73delete_snapshots(filesystem)74757677