rename get-deleteable-volumes -> volumes-delete-old
[mirror/dsa-puppet.git] / modules / bacula / files / volumes-delete-old
1 #!/usr/bin/python3
2
3 # queries a bacula database for volumes to delete and deletes them using bconsole
4
5 # Copyright 2010, 2011, 2013, 2017 Peter Palfrader
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining
8 # a copy of this software and associated documentation files (the
9 # "Software"), to deal in the Software without restriction, including
10 # without limitation the rights to use, copy, modify, merge, publish,
11 # distribute, sublicense, and/or sell copies of the Software, and to
12 # permit persons to whom the Software is furnished to do so, subject to
13 # the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be
16 # included in all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
26 import argparse
27 import psycopg2
28 import psycopg2.extras
29 import re
30 import sys
31 import subprocess
32
33 parser = argparse.ArgumentParser()
34 parser.add_argument("-d", "--db-connect-string", metavar="connect-string", dest="db",
35   help="Database connect string")
36 parser.add_argument("-D", "--db-connect-string-file", metavar="FILE", dest="dbfile",
37   default='/etc/dsa/bacula-reader-database',
38   help="File to read database connect string from (/etc/dsa/bacula-reader-database)")
39 parser.add_argument("-v", "--verbose", dest="verbose",
40   default=False, action="store_true",
41   help="Be more verbose.")
42 parser.add_argument("-n", "--nodo", dest="nodo",
43   default=False, action="store_true",
44   help="Print to cat rather than bconsole.")
45 args = parser.parse_args()
46
47 if args.db is not None:
48     pass
49 elif args.dbfile is not None:
50     args.db = open(args.dbfile).read().rstrip()
51 else:
52     print >>sys.stderr, "Need one of -d or -D."
53     sys.exit(1)
54
55
56 conn = psycopg2.connect(args.db)
57 cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
58
59 # Error volumes
60 cursor.execute("""
61   SELECT volumename
62   FROM media
63   WHERE
64     volstatus='Error' AND
65     firstwritten < current_date - interval '2 weeks' AND
66     labeldate < current_date - interval '2 weeks' AND
67     (lastwritten IS NULL OR lastwritten < current_date - interval '6 weeks')
68 """, {})
69 for r in cursor.fetchall():
70   print("delete volume=%s yes"%(r['volumename'],))
71
72 # Append volumes - we should not have any of these
73 cursor.execute("""
74   SELECT volumename
75   FROM media
76   WHERE
77     volstatus='Append' AND
78     firstwritten IS NULL AND
79     labeldate IS NULL AND
80     lastwritten IS NULL AND
81     voljobs = 0 AND
82     volfiles = 0 AND
83     volblocks = 0 AND
84     volbytes = 0 AND
85     volwrites = 0
86 """, {})
87 for r in cursor.fetchall():
88   print("delete volume=%s yes"%(r['volumename'],))
89
90 cursor.execute("""
91   SELECT volumename
92   FROM media
93   WHERE
94     volstatus='Purged' AND
95     firstwritten < current_date - interval '18 weeks' AND
96     labeldate < current_date - interval '18 weeks' AND
97     lastwritten < current_date - interval '16 weeks' AND
98     volfiles = 0 AND
99     volbytes < 1000 AND
100     recycle=1
101 """, {})
102
103 cmd = []
104 for r in cursor.fetchall():
105   c = "delete volume=%s yes"%(r['volumename'],)
106   cmd.append(c)
107
108 if args.nodo:
109   print("\n".join(cmd))
110   sys.exit(0)
111
112 if args.verbose:
113     for c in cmd:
114       print("Will run: %s"%(c,))
115
116 p = subprocess.Popen(['bconsole'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
117 (out, err) = p.communicate("\n".join(cmd).encode())
118 if p.returncode != 0:
119     raise Exception("bconsole failed.  stdout:\n%s\nstderr:%s\n"%(out, err))
120
121 if args.verbose:
122     print("stdout:\n%s"%(out,))
123
124 if err != "":
125   print("bconsole said on stderr:\n%s\n"%(err,), file=sys.stderr)
126   sys.exit(1)