Initial commit.
authorRichard W.M. Jones <rjones@redhat.com>
Thu, 6 Jul 2017 10:36:48 +0000 (11:36 +0100)
committerRichard W.M. Jones <rjones@redhat.com>
Thu, 6 Jul 2017 18:54:26 +0000 (19:54 +0100)
12 files changed:
.gitignore [new file with mode: 0644]
COPYING [new file with mode: 0644]
README [new file with mode: 0644]
check-release.sh [new file with mode: 0755]
check-syntax.sh [new file with mode: 0755]
config.py [new file with mode: 0644]
create-queues.py [new file with mode: 0755]
drain-queues.py [new file with mode: 0755]
inject-mbox.py [new file with mode: 0755]
perform-tests.py [new file with mode: 0755]
send-reports.py [new file with mode: 0755]
threader.py [new file with mode: 0755]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..6300279
--- /dev/null
@@ -0,0 +1,3 @@
+*~
+*.pyc
+*.pyo
diff --git a/COPYING b/COPYING
new file mode 100644 (file)
index 0000000..d159169
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/README b/README
new file mode 100644 (file)
index 0000000..93bff66
--- /dev/null
+++ b/README
@@ -0,0 +1,106 @@
+patchq is an email patch processing service which can monitor mailing
+list(s) for single patches or a series of patches, run tests on them
+("does it compile", "does it pass the test suite"), and then sends a
+follow up email with the results.
+
+It requires:
+
+ - Python 2
+   (because we need to run on RHEL 6 which doesn't have python3-pika)
+
+ - python-pika (https://pypi.python.org/pypi/pika)
+
+ - A RabbitMQ server running somewhere on your network.
+   You have to open port 5672 on the server, and provide the
+   hostname of the server in ‘config.py’.
+
+ - Procmail or similar to feed email into the system.
+
+To understand how patchq works, please read these blog posts:
+
+ - XXX
+
+Installation:
+
+ - There is no Makefile and nothing to build or install.  You can run
+   everything from the local directory.
+
+ - Edit ‘config.py’ to configure a few things.
+
+ - Write some tests!  For every test listed in the ‘config.tests’
+   list, you will need to write a corresponding ‘test-name.sh’.  Don't
+   forget to make it executable.  See also: ‘perform-tests.py’.
+
+ - Run ‘./create-queues.py’ to set up the RabbitMQ exchanges, queues
+   and other objects.  All RabbitMQ objects are prefixed by
+   ‘patchq_...’, so to reverse this script you just have to delete
+   everything in RabbitMQ with that prefix.
+
+ - If you want, you can manually test that everything works:
+
+     * Run ‘rabbitmqctl list_queues‘ => All queues should have 0 messages.
+
+     * Save some patch series into an mbox and inject them:
+           ./inject-mbox.py mbox
+
+     * ‘rabbitmqctl list_queues’ should show the number of injected
+       emails in the ‘patchq_input’ queue.
+
+     * Run ‘./threader.py’ which should combine single emails into
+       threads and move all the patches to ‘patchq_test_*’.  If you
+       check again with ‘rabbitmqctl list_queues’ you should see one
+       message per patch series in every test queue.
+
+     * Run ‘./perform-tests.py’ which should start testing.
+
+     * Modify ‘config.py’ so that ‘reply_override’ is set to your own
+       email address and run ‘./send-reports.py’.  This should send
+       out report emails to you containing the results of the tests.
+       Once you are happy that report emails are correct, you can set
+       ‘reply_override’ to ‘None’ for production use.
+
+     * Run ‘./drain-queues.py’ to drop any messages remaining in all
+       the queues, if you need to.
+
+     * Note because of the wonders of message brokers, you can run
+       email, threader and testing on different hosts or a single
+       host.
+
+ - Set up cron jobs:
+
+     * Set up a cron job to run ‘./threader.py’ periodically.  At
+       least once every hour for light usage, and more often for
+       mailing lists with heavy traffic.
+
+     * Set up a cron job to run ‘./perform-tests.py’ on your test
+       system(s).  You can run different tests on different machines
+       if you want.  Read the script to see how it works.
+
+     * Set up a cron job to run ‘./send-reports.py’ periodically.
+
+ - Set up procmail (or equivalent) to pick up emails sent to the
+   mailing list and inject them into patchq.  See ‘procmail-example’
+   for some ideas.
+
+This code is released under the GNU General Public License v2 or any
+later version.  See ‘COPYING’ for details.
+
+Development:
+
+ - Written by Richard W.M. Jones
+
+ - Send patches to the virt-tools mailing list:
+   https://www.redhat.com/mailman/listinfo/virt-tools-list
+
+To do:
+
+ - Handle multiple mailing lists and projects.
+
+ - Allow dependencies between tests (ie. test if the code compiles
+   first before running other tests).
+
+Similar projects:
+
+ - The 0-day test service is a very comprehensive set of tests
+   which are run on kernel trees and patches posted to LKML
+   https://01.org/lkp/documentation/0-day-test-service
diff --git a/check-release.sh b/check-release.sh
new file mode 100755 (executable)
index 0000000..d46d99a
--- /dev/null
@@ -0,0 +1,3 @@
+#!/bin/bash -
+
+echo check-release called: $@
diff --git a/check-syntax.sh b/check-syntax.sh
new file mode 100755 (executable)
index 0000000..65f5a5f
--- /dev/null
@@ -0,0 +1,4 @@
+#!/bin/bash -
+
+echo check-syntax called: $@
+exit 1
diff --git a/config.py b/config.py
new file mode 100644 (file)
index 0000000..10dcc97
--- /dev/null
+++ b/config.py
@@ -0,0 +1,28 @@
+# patchq configuration.
+
+# Address of the RabbitMQ server.  Port 5672 must be open on the
+# server's firewall.
+mq_server = "mq.home.annexia.org"
+
+# These are the test jobs that we run in parallel on each patch series.
+tests = [
+    "check-syntax",   # runs make check-syntax
+    "check-release"   # compiles and runs all of the release tests
+]
+
+# How long to wait (in seconds) for all emails in a thread to appear.
+assembly_time = 86400
+
+# If not None [for testing], then replies are only sent to this email
+# address.
+#
+# If this is None [for production], then we do a "group reply".
+#reply_override = None
+reply_override = ("Richard Jones", "rjones@redhat.com")
+
+# The address where report emails come from.
+# Set this to your own (name, email).
+from_address = ("Richard Jones", "rjones@redhat.com")
+
+# The SMTP server to send through.
+smtp_server = "smtp.corp.redhat.com"
diff --git a/create-queues.py b/create-queues.py
new file mode 100755 (executable)
index 0000000..29fc194
--- /dev/null
@@ -0,0 +1,63 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# Create all the exchanges, queues and other objects in RabbitMQ.
+#
+# You must configure the hostname of the RabbitMQ server in
+# ‘config.py’ first.
+#
+# You only have to run this once, but you must run it before running
+# any other part of patchq.
+#
+# All RabbitMQ objects created are prefixed by ‘patchq_...’.  To
+# reverse the effects of this script, delete those objects (using
+# rabbitmqadmin or similar).
+
+import pika
+import config
+
+connection = pika.BlockingConnection(pika.ConnectionParameters(
+    host = config.mq_server))
+channel = connection.channel()
+
+# Create the input exchange and queue which take raw emails in any
+# order and queues them so they can be later threaded and ordered (by
+# ‘threader.py’).
+channel.exchange_declare(exchange = 'patchq_input',
+                         exchange_type = 'fanout',
+                         durable = True)
+q = channel.queue_declare(queue = 'patchq_input',
+                          durable = True)
+channel.queue_bind(exchange = 'patchq_input',
+                   queue = q.method.queue)
+
+# Create the exchange and queue(s) which take fully threaded and
+# ordered patch series and passes them to the tests.
+channel.exchange_declare (exchange = 'patchq_thread',
+                          exchange_type = 'fanout',
+                          durable = True)
+for t in config.tests:
+    qname = "patchq_test_%s" % t
+    q = channel.queue_declare(queue = qname,
+                              durable = True)
+    channel.queue_bind(exchange = 'patchq_thread',
+                       queue = q.method.queue)
+
+# Create the email results queue.
+channel.exchange_declare(exchange = 'patchq_reports',
+                         exchange_type = 'fanout',
+                         durable = True)
+q = channel.queue_declare(queue = 'patchq_reports',
+                          durable = True)
+channel.queue_bind(exchange = 'patchq_reports',
+                   queue = q.method.queue)
+
+print "All done."
+print
+print "You might want to look at the queues and exchanges by running"
+print "‘rabbitmqctl list_queues’ and ‘rabbitmqctl list_exchanges’."
+print
+print "If you want to see the queue contents in more detail, then use"
+print "rabbitmqadmin, see:"
+print "  https://www.rabbitmq.com/management-cli.html"
+print "  https://stackoverflow.com/questions/10709533/is-it-possible-to-view-rabbitmq-message-contents-directly-from-the-command-line"
diff --git a/drain-queues.py b/drain-queues.py
new file mode 100755 (executable)
index 0000000..4f27daa
--- /dev/null
@@ -0,0 +1,29 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# This program drains all the queues, throwing away all the messages.
+# Note that messages which are being processed are not and cannot be
+# drained.
+
+import pika
+import config
+
+connection = pika.BlockingConnection(pika.ConnectionParameters(
+    host = config.mq_server))
+channel = connection.channel()
+
+while True:
+    method, _, _ = channel.basic_get(queue = 'patchq_input', no_ack = True)
+    if not method: break
+
+for t in config.tests:
+    qname = "patchq_test_%s" % t
+    while True:
+        method, _, _ = channel.basic_get(queue = qname, no_ack = True)
+        if not method: break
+
+while True:
+    method, _, _ = channel.basic_get(queue = 'patchq_reports', no_ack = True)
+    if not method: break
+
+print "All queues drained."
diff --git a/inject-mbox.py b/inject-mbox.py
new file mode 100755 (executable)
index 0000000..7a5539c
--- /dev/null
@@ -0,0 +1,49 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# Inject one or more mbox of email, or a single email into the system.
+#
+# ./inject-mbox.py mbox [mbox ...]
+# ./inject-mbox.py < single_email
+#
+# Note that if you inject the same message or message threads twice,
+# then they are processed twice.  patchq does not deduplicate.
+#
+# This script will inject anything that looks similar enough to an
+# email, even non-patches, cover letters, etc.  The ‘threader.py’
+# script filters out non-patches.
+
+import email
+import mailbox
+import pika
+import sys
+import config
+
+connection = pika.BlockingConnection(pika.ConnectionParameters(
+    host = config.mq_server))
+channel = connection.channel()
+
+processed = 0
+
+def inject(m):
+    global processed
+
+    print("Injecting %s" % m['Subject'])
+
+    channel.basic_publish(exchange = 'patchq_input',
+                          routing_key = '',
+                          body = m.as_string())
+    processed = processed+1
+
+# Read from mboxes passed on the command line, or read a single
+# email from stdin.
+if len(sys.argv) > 1:
+    for arg in sys.argv[1:]:
+        mbox = mailbox.mbox(arg)
+        for m in mbox:
+            inject(m)
+else:
+    m = email.message_from_file(sys.stdin)
+    inject(m)
+
+print ("Processed %d email(s)." % processed)
diff --git a/perform-tests.py b/perform-tests.py
new file mode 100755 (executable)
index 0000000..e46e1cc
--- /dev/null
@@ -0,0 +1,112 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# This task takes patch series messages off one of the ‘patchq_test_*’
+# queues and tests the patch series.
+#
+# If you run it without arguments, it will pick up patches from each
+# test queue in turn and test them (but not in parallel).  You can
+# also list one or more tests on the command line, in which case only
+# that test or tests are considered.
+#
+# This script does not perform tests in parallel, but doesn't care if
+# other instances of the script are running (even across machines).
+# Because of the message broker each patch series is only tested once.
+
+import email
+import json
+import mailbox
+import os
+import pika
+import shutil
+import subprocess
+import sys
+import tempfile
+
+import config
+
+connection = pika.BlockingConnection(pika.ConnectionParameters(
+    host = config.mq_server))
+channel = connection.channel()
+
+def ack(method):
+    channel.basic_ack(delivery_tag = method.delivery_tag)
+
+# Which tests to run?
+if len(sys.argv) <= 1:
+    tests = config.tests
+else:
+    tests = []
+    for arg in sys.argv[1:]:
+        if arg not in config.tests:
+            sys.exit("%s is not listed in config.tests" % arg)
+        tests.append(arg)
+
+pwd = os.getcwd()
+
+for t in tests:
+    qname = "patchq_test_%s" % t
+    while True:
+        method, _, body = channel.basic_get(queue = qname, no_ack = False)
+        if not method: break
+
+        # Parse the ordered list of messages forming the patch series.
+        msgs = json.loads(body)
+        msgs = [email.message_from_string(m) for m in msgs]
+
+        # This should never happen, but the rest of the code
+        # below assumes number of msgs > 0, so ...
+        if len(msgs) == 0:
+            ack(method)
+            continue
+
+        print ("%s: Running test:" % t)
+
+        # Save them to a temporary directory.
+        dir = tempfile.mkdtemp()
+        os.chdir(dir)
+
+        # Save the patches to files.
+        i = 0
+        args = []
+        args.append("%s/%s.sh" % (pwd, t))
+        last_msg = None
+        for m in msgs:
+            i = i+1
+            filename = ("%05d" % i)
+            args.append(filename)
+            print ("%05d %s" % (i, m['Subject']))
+            with open(filename, "w") as file:
+                file.write(m.as_string())
+            last_msg = m
+
+        # Run the test.
+        with open("output", "w") as out:
+            r = subprocess.call(args, stdout=out, stderr=out)
+
+        if r == 77:
+            print ("%s: Test skipped" % t)
+        else:
+            # Do a "group reply" to the last email.
+            tos = last_msg.get_all('to', [])
+            ccs = last_msg.get_all('cc', [])
+            from_ = last_msg['From']
+            to = email.utils.getaddresses(tos + ccs + [from_])
+            ref = last_msg['Message-Id']
+            if r == 0:
+                status = "success"
+            else:
+                status = "FAILED"
+            subject = "%s %s (was: Re: %s)" % (t, status, last_msg['Subject'])
+            with open("output", "r") as file:
+                content = file.read()
+
+            body = json.dumps((to, subject, ref, content))
+            channel.basic_publish(exchange = 'patchq_reports',
+                                  routing_key = '',
+                                  body = body)
+
+        # Ack the input message since we have processed it.
+        ack(method)
+
+        shutil.rmtree(dir, ignore_errors = True)
diff --git a/send-reports.py b/send-reports.py
new file mode 100755 (executable)
index 0000000..b526683
--- /dev/null
@@ -0,0 +1,57 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# This script sends out the report emails.
+#
+# Important: When testing, edit ‘config.py’ and set ‘reply_override’
+# to your own email address.  For production use, set it to ‘None’.
+
+import email
+from email.mime.text import MIMEText
+import json
+import pika
+import smtplib
+
+import config
+
+connection = pika.BlockingConnection(pika.ConnectionParameters(
+    host = config.mq_server))
+channel = connection.channel()
+
+smtp = smtplib.SMTP(config.smtp_server)
+emails = 0
+
+def ack(method):
+    channel.basic_ack(delivery_tag = method.delivery_tag)
+
+while True:
+    method, _, body = channel.basic_get(queue = 'patchq_reports',
+                                        no_ack = False)
+    if not method: break
+
+    to, subject, ref, content = json.loads(body)
+
+    if config.reply_override is not None:
+        to = [config.reply_override]
+
+    # Construct an email of type text/plain with the body of the
+    # message.
+    msg = MIMEText(content)
+    msg['Subject'] = subject
+    msg['From'] = email.utils.formataddr(config.from_address)
+    msg['To'] = ",".join([email.utils.formataddr(t) for t in to])
+    msg['In-Reply-To'] = ref
+    msg['References'] = ref
+
+    # Send the email.
+    smtp.sendmail(config.from_address[1],
+                  [email.utils.formataddr(t) for t in to],
+                  msg.as_string())
+    emails = emails+1
+
+    # We've sent the reply, so ack the message.
+    ack(method)
+
+smtp.quit()
+
+print ("Sent %d emails." % emails)
diff --git a/threader.py b/threader.py
new file mode 100755 (executable)
index 0000000..22416e6
--- /dev/null
@@ -0,0 +1,203 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# This task takes messages off ‘patchq_input’ queue in any order and
+# tries to assemble properly ordered threads containing a complete,
+# self-contained series of patches).  If it succeeds, it puts the
+# single thread objects into the ‘patchq_thread’ exchange from where
+# they get distributed to queues ready for testing.
+#
+# Incomplete patch sets are dealt with in two ways:
+#
+# (1) If the emails are not too old, then they stay in ‘patchq_input’
+# until a later run of this script.
+#
+# (2) If they are too old, they are dropped.  We assume in this case
+# that a patch series was sent and either some emails were dropped or
+# not all the emails were sent.
+#
+# Emails which are not patches or parts of a patch set are filtered
+# out and dropped by this script.  Note it is possible for a single
+# email to contain a self-contained patch, in which case it is dealt
+# with as a special case of a thread as above.
+
+import calendar
+import email
+import email.utils
+import hashlib
+import json
+import mailbox
+import pika
+import re
+import sys
+import time
+
+import config
+
+connection = pika.BlockingConnection(pika.ConnectionParameters(
+    host = config.mq_server))
+channel = connection.channel()
+
+re_diff = re.compile('^diff ', flags = re.MULTILINE)
+
+# This is where we try to construct threads of messages.
+threads = dict()
+
+def ack(method):
+    channel.basic_ack(delivery_tag = method.delivery_tag)
+
+# Process a single part patch.  We can add it immediately to the
+# outgoing queue and acknowledge it.
+def single_patch(m, method):
+    # The receiver expects a list of messages, so we have to encode a
+    # message list here, not the single message.
+    body = json.dumps([m.as_string()])
+    channel.basic_publish(exchange = 'patchq_thread',
+                          routing_key = '',
+                          body = body)
+    ack(method)
+
+# Process a single email which we know is part of a patch series.  We
+# add it to the threads hash based on the parent ID, and we'll deal
+# with it at the end.
+def thread_patch(m, method, parent_id, part, n):
+    if parent_id in threads:
+        msg_dict = threads[parent_id]
+    else:
+        msg_dict = dict()
+    msg_dict[part] = [m, method, part, n]
+    threads[parent_id] = msg_dict
+
+# Process an email which looks like a patch.
+# m = the email
+# title = the '...' in '[PATCH...]'
+# part, n = patch part number out of n
+def process_patch(m, method, title, part, n):
+    # If it's a single patch (0/0 or 1/1) then handle that.
+    if n == 0 or n == 1:
+        single_patch(m, method)
+        return
+
+    # Hopefully the patch series was posted using ‘git send-email
+    # --thread’, in which case all messages should contain an
+    # In-Reply-To header and we can thread them easily.
+    parent_id = m['In-Reply-To']
+    if parent_id:
+        # Ignore the 'title' field.
+        thread_patch(m, method, parent_id, part, n)
+        return
+
+    # Otherwise we have to do some horrible heuristics.  Make up a
+    # pseudo parent message ID composed of the From and To fields,
+    # title and number of patches in the series, and hope for the
+    # best.
+    h = hashlib.md5()
+    h.update(m['From'])
+    h.update(m['To'])
+    h.update(title)
+    h.update(string(n))
+    parent_id = h.hexdigest()
+    thread_patch(m, method, parent_id, part, n)
+
+# Process a single email.  This deals with filtering non-patches.
+def process(m, method):
+    subj = m['Subject']
+    print ("Processing %s" % subj)
+
+    # Filter out and drop non-patches.
+    m1 = re.search('\[PATCH(.*)\]', subj)
+    if not m1:
+        print "... dropped: doesn't have [PATCH] in the subject line"
+        # Drop the non-patch by acknowledging it.
+        ack(method)
+        return
+
+    # Is it part of a series?
+    m2 = re.search('(\d+)/(\d+)$', m1.group(1))
+    part = 0
+    n = 0
+    if m2:
+        part = int(m2.group(1))
+        n = int(m2.group(2))
+        # Is it a cover letter?  That is part 0, drop it.
+        if part == 0:
+            print "... dropped: cover letter"
+            ack(method)
+            return
+
+    # The message must be singlepart and must contain "^diff" somewhere.
+    if m.is_multipart():
+        print "... dropped: multipart message"
+        ack(method)
+        return
+
+    if not re.search(re_diff, m.get_payload(decode = True)):
+        print "... dropped: does not contain a 'diff' line"
+        ack(method)
+        return
+
+    # It looks sufficiently like a patch to continue.
+    process_patch(m, method, m1.group(1), part, n)
+
+# Read all messages from ‘patchq_input’ but DO NOT ACKNOWLEDGE THEM (yet).
+while True:
+    method, _, body = channel.basic_get(queue = 'patchq_input', no_ack = False)
+    if not method: break
+    m = email.message_from_string(body) # the email
+    process(m, method)
+
+# Once we've processed all the incoming messages, look at the threads
+# dictionary to see if we've got any completed threads and send those.
+for parent_id in threads.keys():
+    msg_dict = threads[parent_id]
+
+    # If we didn't get part 1/n, it must be incomplete.
+    if 1 not in msg_dict:
+        continue
+    n = msg_dict[1][3]
+
+    # Check if we got all parts.
+    incomplete = False
+    msgs = []
+    for i in range(1, n+1):
+        if i in msg_dict:
+            msgs.append(msg_dict[i][0].as_string())
+        else:
+            incomplete = True
+    if incomplete:
+        continue
+
+    # It looks like we got a full set, so we can send it.
+    body = json.dumps(msgs)
+    channel.basic_publish(exchange = 'patchq_thread',
+                          routing_key = '',
+                          body = body)
+
+    # Acknowledge each message so they are dropped from the
+    # incoming queue.
+    for i in range(1, n+1):
+        ack(msg_dict[i][1])
+
+    del threads[parent_id]
+
+# Check for incomplete threads.  If they consist only of old messages
+# then we drop them, otherwise we leave them for the next run.
+for parent_id in threads.keys():
+    msg_dict = threads[parent_id]
+
+    old = True
+    for msg in msg_dict.itervalues():
+        t = None
+        date_tuple = email.utils.parsedate_tz(msg[0]['Date'])
+        if date_tuple:
+            t = email.utils.mktime_tz(date_tuple)
+        now = calendar.timegm(time.gmtime())
+        #print ("t = %d, now = %d, now-t = %d" % (t, now, now-t))
+        if t and now - t < config.assembly_time:
+            old = False
+
+    # If they're too old, drop.
+    if old:
+        for msg in msg_dict.itervalues():
+            print "... dropped: incomplete thread too old"
+            ack(msg[1])