2 # vim:set et ts=4 sw=4:
4 """ Handles NEW and BYHAND packages
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2001, 2002, 2003, 2004, 2005, 2006 James Troup <james@nocrew.org>
8 @copyright: 2009 Joerg Jaspert <joerg@debian.org>
9 @copyright: 2009 Frank Lichtenheld <djpig@debian.org>
10 @license: GNU General Public License version 2 or later
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 ################################################################################
28 # 23:12|<aj> I will not hush!
30 # 23:12|<aj> Where there is injustice in the world, I shall be there!
31 # 23:13|<aj> I shall not be silenced!
32 # 23:13|<aj> The world shall know!
33 # 23:13|<aj> The world *must* know!
34 # 23:13|<elmo> oh dear, he's gone back to powerpuff girls... ;-)
35 # 23:13|<aj> yay powerpuff girls!!
36 # 23:13|<aj> buttercup's my favourite, who's yours?
37 # 23:14|<aj> you're backing away from the keyboard right now aren't you?
38 # 23:14|<aj> *AREN'T YOU*?!
39 # 23:15|<aj> I will not be treated like this.
40 # 23:15|<aj> I shall have my revenge.
41 # 23:15|<aj> I SHALL!!!
43 ################################################################################
54 import apt_pkg, apt_inst
55 import examine_package
57 from sqlalchemy import or_
59 from daklib.dbconn import *
60 from daklib.queue import *
61 from daklib import daklog
62 from daklib import utils
63 from daklib.regexes import re_no_epoch, re_default_answer, re_isanum, re_package
64 from daklib.dak_exceptions import CantOpenError, AlreadyLockedError, CantGetLockError
65 from daklib.summarystats import SummaryStats
66 from daklib.config import Config
67 from daklib.policy import UploadCopy, PolicyQueueUploadHandler
76 ################################################################################
77 ################################################################################
78 ################################################################################
80 class Section_Completer:
81 def __init__ (self, session):
84 for s, in session.query(Section.section):
85 self.sections.append(s)
87 def complete(self, text, state):
91 for word in self.sections:
93 self.matches.append(word)
95 return self.matches[state]
99 ############################################################
101 class Priority_Completer:
102 def __init__ (self, session):
105 for p, in session.query(Priority.priority):
106 self.priorities.append(p)
108 def complete(self, text, state):
112 for word in self.priorities:
114 self.matches.append(word)
116 return self.matches[state]
120 ################################################################################
122 def takenover_binaries(upload, missing, session):
124 binaries = set([x.package for x in upload.binaries])
126 if m['type'] != 'dsc':
127 binaries.remove(m['package'])
129 suite = upload.target_suite.overridesuite or \
130 upload.target_suite.suite_name
131 suites = [s[0] for s in session.query(Suite.suite_name).filter \
132 (or_(Suite.suite_name == suite,
133 Suite.overridesuite == suite)).all()]
134 rows = session.query(DBSource.source, DBBinary.package).distinct(). \
135 filter(DBBinary.package.in_(binaries)). \
136 join(DBBinary.source). \
137 filter(DBSource.source != upload.source.source). \
138 join(DBBinary.suites). \
139 filter(Suite.suite_name.in_(suites)). \
140 order_by(DBSource.source, DBBinary.package).all()
143 ################################################################################
145 def print_new (upload, missing, indexed, session, file=sys.stdout):
146 check_valid(missing, session)
150 if m['type'] != 'deb':
151 package = '{0}:{1}'.format(m['type'], m['package'])
153 package = m['package']
154 section = m['section']
155 priority = m['priority']
157 line = "(%s): %-20s %-20s %-20s" % (index, package, priority, section)
159 line = "%-20s %-20s %-20s" % (package, priority, section)
164 takenover = takenover_binaries(upload, missing, session)
166 print '\n\nBINARIES TAKEN OVER\n'
168 print '%s: %s' % (t[0], t[1])
169 notes = get_new_comments(upload.policy_queue, upload.changes.source)
171 print "\nAuthor: %s\nVersion: %s\nTimestamp: %s\n\n%s" \
172 % (note.author, note.version, note.notedate, note.comment)
174 return len(notes) > 0
176 ################################################################################
178 def index_range (index):
182 return "1-%s" % (index)
184 ################################################################################
185 ################################################################################
187 def edit_new (overrides, upload, session):
188 # Write the current data to a temporary file
189 (fd, temp_filename) = utils.temp_filename()
190 temp_file = os.fdopen(fd, 'w')
191 print_new (upload, overrides, indexed=0, session=session, file=temp_file)
193 # Spawn an editor on that file
194 editor = os.environ.get("EDITOR","vi")
195 result = os.system("%s %s" % (editor, temp_filename))
197 utils.fubar ("%s invocation failed for %s." % (editor, temp_filename), result)
198 # Read the edited data back in
199 temp_file = utils.open_file(temp_filename)
200 lines = temp_file.readlines()
202 os.unlink(temp_filename)
204 overrides_map = dict([ ((o['type'], o['package']), o) for o in overrides ])
209 if line == "" or line[0] == '#':
212 # Pad the list if necessary
213 s[len(s):3] = [None] * (3-len(s))
214 (pkg, priority, section) = s[:3]
215 if pkg.find(':') != -1:
216 type, pkg = pkg.split(':', 1)
219 if (type, pkg) not in overrides_map:
220 utils.warn("Ignoring unknown package '%s'" % (pkg))
222 if section.find('/') != -1:
223 component = section.split('/', 1)[0]
226 new_overrides.append(dict(
235 ################################################################################
237 def edit_index (new, upload, index):
238 package = new[index]['package']
239 priority = new[index]["priority"]
240 section = new[index]["section"]
241 ftype = new[index]["type"]
244 print "\t".join([package, priority, section])
248 prompt = "[B]oth, Priority, Section, Done ? "
250 prompt = "[S]ection, Done ? "
251 edit_priority = edit_section = 0
253 while prompt.find(answer) == -1:
254 answer = utils.our_raw_input(prompt)
255 m = re_default_answer.match(prompt)
258 answer = answer[:1].upper()
265 edit_priority = edit_section = 1
271 readline.set_completer(Priorities.complete)
273 while not got_priority:
274 new_priority = utils.our_raw_input("New priority: ").strip()
275 if new_priority not in Priorities.priorities:
276 print "E: '%s' is not a valid priority, try again." % (new_priority)
279 priority = new_priority
283 readline.set_completer(Sections.complete)
285 while not got_section:
286 new_section = utils.our_raw_input("New section: ").strip()
287 if new_section not in Sections.sections:
288 print "E: '%s' is not a valid section, try again." % (new_section)
291 section = new_section
293 # Reset the readline completer
294 readline.set_completer(None)
296 new[index]["priority"] = priority
297 new[index]["section"] = section
298 if section.find('/') != -1:
299 component = section.split('/', 1)[0]
302 new[index]['component'] = component
306 ################################################################################
308 def edit_overrides (new, upload, session):
312 print_new (upload, new, indexed=1, session=session)
313 prompt = "edit override <n>, Editor, Done ? "
316 while not got_answer:
317 answer = utils.our_raw_input(prompt)
318 if not answer.isdigit():
319 answer = answer[:1].upper()
320 if answer == "E" or answer == "D":
322 elif re_isanum.match (answer):
324 if answer < 1 or answer > len(new):
325 print "{0} is not a valid index. Please retry.".format(answer)
330 new = edit_new(new, upload, session)
334 edit_index (new, upload, answer - 1)
339 ################################################################################
341 def check_pkg (upload, upload_copy, session):
343 save_stdout = sys.stdout
344 changes = os.path.join(upload_copy.directory, upload.changes.changesname)
345 suite_name = upload.target_suite.suite_name
346 handler = PolicyQueueUploadHandler(upload, session)
347 missing = [(m['type'], m["package"]) for m in handler.missing_overrides(hints=missing)]
349 sys.stdout = os.popen("less -R -", 'w', 0)
350 print examine_package.display_changes(suite_name, changes)
352 source = upload.source
353 if source is not None:
354 source_file = os.path.join(upload_copy.directory, os.path.basename(source.poolfile.filename))
355 print examine_package.check_dsc(suite_name, source_file)
357 for binary in upload.binaries:
358 binary_file = os.path.join(upload_copy.directory, os.path.basename(binary.poolfile.filename))
359 examined = examine_package.check_deb(suite_name, binary_file)
360 # We always need to call check_deb to display package relations for every binary,
361 # but we print its output only if new overrides are being added.
362 if ("deb", binary.package) in missing:
365 print examine_package.output_package_relations()
367 if e.errno == errno.EPIPE:
368 utils.warn("[examine_package] Caught EPIPE; skipping.")
371 except KeyboardInterrupt:
372 utils.warn("[examine_package] Caught C-c; skipping.")
374 sys.stdout = save_stdout
376 ################################################################################
378 ## FIXME: horribly Debian specific
380 def do_bxa_notification(new, upload, session):
383 new = set([ o['package'] for o in new if o['type'] == 'deb' ])
387 key = session.query(MetadataKey).filter_by(key='Description').one()
389 for binary in upload.binaries:
390 if binary.package not in new:
392 description = session.query(BinaryMetadata).filter_by(binary=binary, key=key).one().value
394 summary += "Package: {0}\n".format(binary.package)
395 summary += "Description: {0}\n".format(description)
398 '__DISTRO__': cnf['Dinstall::MyDistribution'],
399 '__BCC__': 'X-DAK: dak process-new',
400 '__BINARY_DESCRIPTIONS__': summary,
403 bxa_mail = utils.TemplateSubst(subst,os.path.join(cnf["Dir::Templates"], "process-new.bxa_notification"))
404 utils.send_mail(bxa_mail)
406 ################################################################################
408 def add_overrides (new_overrides, suite, session):
409 if suite.overridesuite is not None:
410 suite = session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
412 for override in new_overrides:
413 package = override['package']
414 priority = session.query(Priority).filter_by(priority=override['priority']).first()
415 section = session.query(Section).filter_by(section=override['section']).first()
416 component = get_mapped_component(override['component'], session)
417 overridetype = session.query(OverrideType).filter_by(overridetype=override['type']).one()
420 raise Exception('Invalid priority {0} for package {1}'.format(priority, package))
422 raise Exception('Invalid section {0} for package {1}'.format(section, package))
423 if component is None:
424 raise Exception('Invalid component {0} for package {1}'.format(component, package))
426 o = Override(package=package, suite=suite, component=component, priority=priority, section=section, overridetype=overridetype)
431 ################################################################################
433 def run_user_inspect_command(upload, upload_copy):
434 command = os.environ.get('DAK_INSPECT_UPLOAD')
438 directory = upload_copy.directory
440 dsc = os.path.basename(upload.source.poolfile.filename)
443 changes = upload.changes.changesname
445 shell_command = command.format(
451 subprocess.check_call(shell_command, shell=True)
453 ################################################################################
455 def get_reject_reason(reason=''):
456 """get reason for rejection
459 @return: string giving the reason for the rejection or C{None} if the
460 rejection should be cancelled
463 if Options['Automatic']:
467 reason = utils.call_editor(reason)
468 print "Reject message:"
469 print utils.prefix_multi_line_string(reason, " ", include_blank_lines=1)
470 prompt = "[R]eject, Edit, Abandon, Quit ?"
472 while prompt.find(answer) == -1:
473 answer = utils.our_raw_input(prompt)
474 m = re_default_answer.search(prompt)
477 answer = answer[:1].upper()
486 ################################################################################
488 def do_new(upload, upload_copy, handler, session):
491 run_user_inspect_command(upload, upload_copy)
493 # The main NEW processing loop
497 queuedir = upload.policy_queue.path
498 byhand = upload.byhand
500 missing = handler.missing_overrides(hints=missing)
501 broken = not check_valid(missing, session)
503 changesname = os.path.basename(upload.changes.changesname)
507 print "-" * len(changesname)
509 print " Target: {0}".format(upload.target_suite.suite_name)
510 print " Changed-By: {0}".format(upload.changes.changedby)
513 #if len(byhand) == 0 and len(missing) == 0:
520 if Options["No-Action"] or Options["Automatic"]:
523 note = print_new(upload, missing, indexed=0, session=session)
526 has_unprocessed_byhand = False
528 path = os.path.join(queuedir, f.filename)
529 if not f.processed and os.path.exists(path):
530 print "W: {0} still present; please process byhand components and try again".format(f.filename)
531 has_unprocessed_byhand = True
533 if not has_unprocessed_byhand and not broken and not note:
534 if len(missing) == 0:
538 prompt = "Add overrides, "
540 print "W: [!] marked entries must be fixed before package can be processed."
542 print "W: note must be removed before package can be processed."
543 prompt += "RemOve all notes, Remove note, "
545 prompt += "Edit overrides, Check, Manual reject, Note edit, Prod, [S]kip, Quit ?"
547 while prompt.find(answer) == -1:
548 answer = utils.our_raw_input(prompt)
549 m = re_default_answer.search(prompt)
552 answer = answer[:1].upper()
554 if answer in ( 'A', 'E', 'M', 'O', 'R' ) and Options["Trainee"]:
555 utils.warn("Trainees can't do that")
558 if answer == 'A' and not Options["Trainee"]:
559 add_overrides(missing, upload.target_suite, session)
560 if Config().find_b("Dinstall::BXANotify"):
561 do_bxa_notification(missing, upload, session)
564 Logger.log(["NEW ACCEPT", upload.changes.changesname])
566 check_pkg(upload, upload_copy, session)
567 elif answer == 'E' and not Options["Trainee"]:
568 missing = edit_overrides (missing, upload, session)
569 elif answer == 'M' and not Options["Trainee"]:
570 reason = Options.get('Manual-Reject', '') + "\n"
571 reason = reason + "\n\n=====\n\n".join([n.comment for n in get_new_comments(upload.policy_queue, upload.changes.source, session=session)])
572 reason = get_reject_reason(reason)
573 if reason is not None:
574 Logger.log(["NEW REJECT", upload.changes.changesname])
575 handler.reject(reason)
578 if edit_note(get_new_comments(upload.policy_queue, upload.changes.source, session=session),
579 upload, session, bool(Options["Trainee"])) == 0:
582 elif answer == 'P' and not Options["Trainee"]:
583 if prod_maintainer(get_new_comments(upload.policy_queue, upload.changes.source, session=session),
587 Logger.log(["NEW PROD", upload.changes.changesname])
588 elif answer == 'R' and not Options["Trainee"]:
589 confirm = utils.our_raw_input("Really clear note (y/N)? ").lower()
591 for c in get_new_comments(upload.policy_queue, upload.changes.source, upload.changes.version, session=session):
594 elif answer == 'O' and not Options["Trainee"]:
595 confirm = utils.our_raw_input("Really clear all notes (y/N)? ").lower()
597 for c in get_new_comments(upload.policy_queue, upload.changes.source, session=session):
607 if handler.get_action():
608 print "PENDING %s\n" % handler.get_action()
610 ################################################################################
611 ################################################################################
612 ################################################################################
614 def usage (exit_code=0):
615 print """Usage: dak process-new [OPTION]... [CHANGES]...
616 -a, --automatic automatic run
617 -b, --no-binaries do not sort binary-NEW packages first
618 -c, --comments show NEW comments
619 -h, --help show this help and exit.
620 -m, --manual-reject=MSG manual reject with `msg'
621 -n, --no-action don't do anything
622 -q, --queue=QUEUE operate on a different queue
623 -t, --trainee FTP Trainee mode
624 -V, --version display the version number and exit
626 ENVIRONMENT VARIABLES
628 DAK_INSPECT_UPLOAD: shell command to run to inspect a package
629 The command is automatically run in a shell when an upload
630 is checked. The following substitutions are available:
632 {directory}: directory the upload is contained in
633 {dsc}: name of the included dsc or the empty string
634 {changes}: name of the changes file
636 Note that Python's 'format' method is used to format the command.
638 Example: run mc in a tmux session to inspect the upload
640 export DAK_INSPECT_UPLOAD='tmux new-session -d -s process-new 2>/dev/null; tmux new-window -n "{changes}" -t process-new:0 -k "cd {directory}; mc"'
644 tmux attach -t process-new
646 in a separate terminal session.
650 ################################################################################
652 @contextlib.contextmanager
653 def lock_package(package):
655 Lock C{package} so that noone else jumps in processing it.
657 @type package: string
658 @param package: source package name to lock
663 path = os.path.join(cnf.get("Process-New::LockDir", cnf['Dir::Lock']), package)
666 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDONLY)
668 if e.errno == errno.EEXIST or e.errno == errno.EACCES:
669 user = pwd.getpwuid(os.stat(path)[stat.ST_UID])[4].split(',')[0].replace('.', '')
670 raise AlreadyLockedError(user)
677 def do_pkg(upload, session):
678 # Try to get an included dsc
682 group = cnf.get('Dinstall::UnprivGroup') or None
684 #bcc = "X-DAK: dak process-new"
685 #if cnf.has_key("Dinstall::Bcc"):
686 # u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
688 # u.Subst["__BCC__"] = bcc
691 with lock_package(upload.changes.source):
692 with UploadCopy(upload, group=group) as upload_copy:
693 handler = PolicyQueueUploadHandler(upload, session)
694 if handler.get_action() is not None:
695 print "PENDING %s\n" % handler.get_action()
698 do_new(upload, upload_copy, handler, session)
699 except AlreadyLockedError as e:
700 print "Seems to be locked by %s already, skipping..." % (e)
702 def show_new_comments(uploads, session):
703 sources = [ upload.changes.source for upload in uploads ]
704 if len(sources) == 0:
707 query = """SELECT package, version, comment, author
709 WHERE package IN :sources
710 ORDER BY package, version"""
712 r = session.execute(query, params=dict(sources=tuple(sources)))
715 print "%s_%s\n%s\n(%s)\n\n\n" % (i[0], i[1], i[2], i[3])
719 ################################################################################
721 def sort_uploads(new_queue, uploads, session, nobinaries=False):
724 suitesrc = [s.source for s in session.query(DBSource.source). \
725 filter(DBSource.suites.any(Suite.suite_name.in_(['unstable', 'experimental'])))]
726 comments = [p.package for p in session.query(NewComment.package). \
727 filter_by(trainee=False, policy_queue=new_queue).distinct()]
728 for upload in uploads:
729 source = upload.changes.source
730 if not source in sources:
732 sources[source].append({'upload': upload,
733 'date': upload.changes.created,
735 'binary': True if source in suitesrc else False,
736 'comments': True if source in comments else False})
738 if len(sources[src]) > 1:
739 changes = sources[src]
740 firstseen = sorted(changes, key=lambda k: (k['date']))[0]['date']
741 changes.sort(key=lambda item:item['date'])
742 for i in range (0, len(changes)):
743 changes[i]['date'] = firstseen
744 changes[i]['stack'] = i + 1
745 sorteduploads += sources[src]
747 sorteduploads = [u["upload"] for u in sorted(sorteduploads,
748 key=lambda k: (k["comments"], k["binary"],
749 k["date"], -k["stack"]))]
751 sorteduploads = [u["upload"] for u in sorted(sorteduploads,
752 key=lambda k: (k["comments"], -k["binary"],
753 k["date"], -k["stack"]))]
756 ################################################################################
759 accept_count = SummaryStats().accept_count
760 accept_bytes = SummaryStats().accept_bytes
766 sys.stderr.write("Accepted %d package %s, %s.\n" % (accept_count, sets, utils.size_type(int(accept_bytes))))
767 Logger.log(["total",accept_count,accept_bytes])
769 if not Options["No-Action"] and not Options["Trainee"]:
772 ################################################################################
775 global Options, Logger, Sections, Priorities
778 session = DBConn().session()
780 Arguments = [('a',"automatic","Process-New::Options::Automatic"),
781 ('b',"no-binaries","Process-New::Options::No-Binaries"),
782 ('c',"comments","Process-New::Options::Comments"),
783 ('h',"help","Process-New::Options::Help"),
784 ('m',"manual-reject","Process-New::Options::Manual-Reject", "HasArg"),
785 ('t',"trainee","Process-New::Options::Trainee"),
786 ('q','queue','Process-New::Options::Queue', 'HasArg'),
787 ('n',"no-action","Process-New::Options::No-Action")]
789 changes_files = apt_pkg.parse_commandline(cnf.Cnf,Arguments,sys.argv)
791 for i in ["automatic", "no-binaries", "comments", "help", "manual-reject", "no-action", "version", "trainee"]:
792 if not cnf.has_key("Process-New::Options::%s" % (i)):
793 cnf["Process-New::Options::%s" % (i)] = ""
795 queue_name = cnf.get('Process-New::Options::Queue', 'new')
796 new_queue = session.query(PolicyQueue).filter_by(queue_name=queue_name).one()
797 if len(changes_files) == 0:
798 uploads = new_queue.uploads
800 uploads = session.query(PolicyQueueUpload).filter_by(policy_queue=new_queue) \
801 .join(DBChange).filter(DBChange.changesname.in_(changes_files)).all()
803 Options = cnf.subtree("Process-New::Options")
808 if not Options["No-Action"]:
810 Logger = daklog.Logger("process-new")
811 except CantOpenError as e:
812 Options["Trainee"] = "True"
814 Sections = Section_Completer(session)
815 Priorities = Priority_Completer(session)
816 readline.parse_and_bind("tab: complete")
819 sys.stderr.write("Sorting changes...\n")
820 uploads = sort_uploads(new_queue, uploads, session, Options["No-Binaries"])
822 if Options["Comments"]:
823 show_new_comments(uploads, session)
825 for upload in uploads:
826 do_pkg (upload, session)
830 ################################################################################
832 if __name__ == '__main__':