]> git.decadent.org.uk Git - dak.git/blob - dak/clean_queues.py
Reject isn't a queue
[dak.git] / dak / clean_queues.py
1 #!/usr/bin/env python
2
3 """ Clean incoming of old unused files """
4 # Copyright (C) 2000, 2001, 2002, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # <aj> Bdale, a ham-er, and the leader,
23 # <aj> Willy, a GCC maintainer,
24 # <aj> Lamont-work, 'cause he's the top uploader....
25 # <aj>         Penguin Puff' save the day!
26 # <aj> Porting code, trying to build the world,
27 # <aj> Here they come just in time...
28 # <aj>         The Penguin Puff' Guys!
29 # <aj> [repeat]
30 # <aj> Penguin Puff'!
31 # <aj> willy: btw, if you don't maintain gcc you need to start, since
32 #      the lyrics fit really well that way
33
34 ################################################################################
35
36 import os, os.path, stat, sys, time
37 import apt_pkg
38 from daklib import utils
39 from daklib import daklog
40 from daklib.config import Config
41
42 ################################################################################
43
44 Options = None
45 Logger = None
46 del_dir = None
47 delete_date = None
48
49 ################################################################################
50
51 def usage (exit_code=0):
52     print """Usage: dak clean-queues [OPTIONS]
53 Clean out incoming directories.
54
55   -d, --days=DAYS            remove anything older than DAYS old
56   -i, --incoming=INCOMING    the incoming directory to clean
57   -n, --no-action            don't do anything
58   -v, --verbose              explain what is being done
59   -h, --help                 show this help and exit"""
60
61     sys.exit(exit_code)
62
63 ################################################################################
64
65 def init (cnf):
66     global delete_date, del_dir
67
68     delete_date = int(time.time())-(int(Options["Days"])*84600)
69     date = time.strftime("%Y-%m-%d")
70     del_dir = os.path.join(cnf["Dir::Morgue"], cnf["Clean-Queues::MorgueSubDir"], date)
71
72     # Ensure a directory exists to remove files to
73     if not Options["No-Action"]:
74         if not os.path.exists(del_dir):
75             os.makedirs(del_dir, 02775)
76         if not os.path.isdir(del_dir):
77             utils.fubar("%s must be a directory." % (del_dir))
78
79     # Move to the directory to clean
80     incoming = Options["Incoming"]
81     if incoming == "":
82         incoming = cnf["Dir::Queue::Unchecked"]
83     os.chdir(incoming)
84
85 # Remove a file to the morgue
86 def remove (from_dir, f):
87     fname = os.path.basename(f)
88     if os.access(f, os.R_OK):
89         Logger.log(["move file to morgue", from_dir, fname, del_dir])
90         if Options["Verbose"]:
91             print "Removing '%s' (to '%s')."  % (fname, del_dir)
92         if Options["No-Action"]:
93             return
94
95         dest_filename = os.path.join(del_dir, fname)
96         # If the destination file exists; try to find another filename to use
97         if os.path.exists(dest_filename):
98             dest_filename = utils.find_next_free(dest_filename, 10)
99             Logger.log(["change destination file name", os.path.basename(dest_filename)])
100         utils.move(f, dest_filename, 0660)
101     else:
102         Logger.log(["skipping file because of permission problem", fname])
103         utils.warn("skipping '%s', permission denied." % fname)
104
105 # Removes any old files.
106 # [Used for Incoming/REJECT]
107 #
108 def flush_old ():
109     Logger.log(["check Incoming/REJECT for old files", os.getcwd()])
110     for f in os.listdir('.'):
111         if os.path.isfile(f):
112             if os.stat(f)[stat.ST_MTIME] < delete_date:
113                 remove('Incoming/REJECT', f)
114             else:
115                 if Options["Verbose"]:
116                     print "Skipping, too new, '%s'." % (os.path.basename(f))
117
118 # Removes any files which are old orphans (not associated with a valid .changes file).
119 # [Used for Incoming]
120 #
121 def flush_orphans ():
122     all_files = {}
123     changes_files = []
124
125     Logger.log(["check Incoming for old orphaned files", os.getcwd()])
126     # Build up the list of all files in the directory
127     for i in os.listdir('.'):
128         if os.path.isfile(i):
129             all_files[i] = 1
130             if i.endswith(".changes"):
131                 changes_files.append(i)
132
133     # Proces all .changes and .dsc files.
134     for changes_filename in changes_files:
135         try:
136             changes = utils.parse_changes(changes_filename)
137             files = utils.build_file_list(changes)
138         except:
139             utils.warn("error processing '%s'; skipping it. [Got %s]" % (changes_filename, sys.exc_type))
140             continue
141
142         dsc_files = {}
143         for f in files.keys():
144             if f.endswith(".dsc"):
145                 try:
146                     dsc = utils.parse_changes(f, dsc_file=1)
147                     dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
148                 except:
149                     utils.warn("error processing '%s'; skipping it. [Got %s]" % (f, sys.exc_type))
150                     continue
151
152         # Ensure all the files we've seen aren't deleted
153         keys = []
154         for i in (files.keys(), dsc_files.keys(), [changes_filename]):
155             keys.extend(i)
156         for key in keys:
157             if all_files.has_key(key):
158                 if Options["Verbose"]:
159                     print "Skipping, has parents, '%s'." % (key)
160                 del all_files[key]
161
162     # Anthing left at this stage is not referenced by a .changes (or
163     # a .dsc) and should be deleted if old enough.
164     for f in all_files.keys():
165         if os.stat(f)[stat.ST_MTIME] < delete_date:
166             remove('Incoming', f)
167         else:
168             if Options["Verbose"]:
169                 print "Skipping, too new, '%s'." % (os.path.basename(f))
170
171 ################################################################################
172
173 def main ():
174     global Options, Logger
175
176     cnf = Config()
177
178     for i in ["Help", "Incoming", "No-Action", "Verbose" ]:
179         if not cnf.has_key("Clean-Queues::Options::%s" % (i)):
180             cnf["Clean-Queues::Options::%s" % (i)] = ""
181     if not cnf.has_key("Clean-Queues::Options::Days"):
182         cnf["Clean-Queues::Options::Days"] = "14"
183
184     Arguments = [('h',"help","Clean-Queues::Options::Help"),
185                  ('d',"days","Clean-Queues::Options::Days", "IntLevel"),
186                  ('i',"incoming","Clean-Queues::Options::Incoming", "HasArg"),
187                  ('n',"no-action","Clean-Queues::Options::No-Action"),
188                  ('v',"verbose","Clean-Queues::Options::Verbose")]
189
190     apt_pkg.ParseCommandLine(cnf.Cnf,Arguments,sys.argv)
191     Options = cnf.SubTree("Clean-Queues::Options")
192
193     if Options["Help"]:
194         usage()
195
196     Logger = daklog.Logger('clean-queues', Options['No-Action'])
197
198     init(cnf)
199
200     if Options["Verbose"]:
201         print "Processing incoming..."
202     flush_orphans()
203
204     reject = cnf["Dir::Reject"]
205     if os.path.exists(reject) and os.path.isdir(reject):
206         if Options["Verbose"]:
207             print "Processing reject directory..."
208         os.chdir(reject)
209         flush_old()
210
211     Logger.close()
212
213 #######################################################################################
214
215 if __name__ == '__main__':
216     main()