Browse code

Initial version

Lorenz Hüdepohl authored on23/04/2015 15:22:26
Showing1 changed files
1 1
new file mode 100755
... ...
@@ -0,0 +1,43 @@
1
+#!/usr/bin/python
2
+
3
+import sys
4
+import datetime
5
+from subprocess import Popen, PIPE, check_call
6
+
7
+tagname, = sys.argv[1:]
8
+
9
+zfs_props = Popen(["/usr/sbin/zfs", "get", "-t", "filesystem", "autosnapshot:{0}".format(tagname), "-H"],
10
+        stdout=PIPE)
11
+
12
+for line in zfs_props.stdout:
13
+    fs, prop, number, source = line.split("\t")
14
+    if number != "-":
15
+        # Create new snapshot
16
+        check_call(["/usr/sbin/zfs", "snapshot", "{0}@autosnapshot-{1}-{2}".format(fs, tagname,
17
+            datetime.datetime.now().strftime("%Y-%m-%d-%H:%M"))])
18
+
19
+        # Delete oldest snapshots
20
+        if number == "forever":
21
+            continue
22
+        else:
23
+            number = int(number)
24
+
25
+        if number <= 0:
26
+            raise Exception("Invalid number for property 'autosnapshot:{0}' on filesystem {1}: {2}".format(tagname, fs, number))
27
+
28
+        snapshots = []
29
+
30
+        zfs_snapshots = Popen(["/usr/sbin/zfs", "list", "-t", "snapshot", "-d", "1", fs, "-H"], stdout=PIPE)
31
+
32
+        for line_snapshots in zfs_snapshots.stdout:
33
+            snapname, rest = line_snapshots.split("\t", 1)
34
+            if snapname.startswith("{0}@autosnapshot-{1}-".format(fs, tagname)):
35
+                snapshots.append(snapname)
36
+
37
+        to_delete = snapshots[:-number]
38
+
39
+        for d in to_delete:
40
+            # Delete this old snapshot
41
+            if not snapname.startswith("{0}@autosnapshot-{1}-".format(fs, tagname)):
42
+                raise Exception("Invalid snapshot name '{0}', does not start with '{1}@autosnapshot-{2}-'".format(snapname, fs, tagname))
43
+            check_call(["/usr/sbin/zfs", "destroy", d])